@niscorp/strata 0.1.3 → 0.1.5

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +2 -2
  3. package/dist/check/index.cjs +23 -228
  4. package/dist/check/index.cjs.map +1 -1
  5. package/dist/check/index.js +2 -2
  6. package/dist/{chunk-274M232S.js → chunk-4BLHBVSC.js} +3 -3
  7. package/dist/{chunk-274M232S.js.map → chunk-4BLHBVSC.js.map} +1 -1
  8. package/dist/{chunk-U5CPF4LQ.js → chunk-5KTXEN43.js} +3 -3
  9. package/dist/{chunk-U5CPF4LQ.js.map → chunk-5KTXEN43.js.map} +1 -1
  10. package/dist/{chunk-EGFF63GA.js → chunk-AKKWEXO2.js} +2 -2
  11. package/dist/{chunk-EGFF63GA.js.map → chunk-AKKWEXO2.js.map} +1 -1
  12. package/dist/chunk-ATHZ7HT5.cjs +18 -0
  13. package/dist/chunk-ATHZ7HT5.cjs.map +1 -0
  14. package/dist/chunk-CL5DF2IQ.cjs +192 -0
  15. package/dist/chunk-CL5DF2IQ.cjs.map +1 -0
  16. package/dist/chunk-IHYBGLNW.cjs +161 -0
  17. package/dist/chunk-IHYBGLNW.cjs.map +1 -0
  18. package/dist/chunk-KNBS3AJZ.cjs +223 -0
  19. package/dist/chunk-KNBS3AJZ.cjs.map +1 -0
  20. package/dist/{chunk-TWAEZHTB.js → chunk-OLDORFOQ.js} +4 -4
  21. package/dist/{chunk-TWAEZHTB.js.map → chunk-OLDORFOQ.js.map} +1 -1
  22. package/dist/{chunk-2FIZEJXW.js → chunk-WU3OJHVZ.js} +4 -4
  23. package/dist/{chunk-2FIZEJXW.js.map → chunk-WU3OJHVZ.js.map} +1 -1
  24. package/dist/chunk-YXFEJJMC.cjs +136 -0
  25. package/dist/chunk-YXFEJJMC.cjs.map +1 -0
  26. package/dist/index.cjs +75 -330
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +3 -3
  31. package/dist/node/index.cjs +14 -493
  32. package/dist/node/index.cjs.map +1 -1
  33. package/dist/node/index.js +5 -5
  34. package/dist/{plan-BEIlXVUt.d.cts → plan-CxuteSH1.d.cts} +2 -2
  35. package/dist/{plan-BAewc8DG.d.ts → plan-mFmdh0qT.d.ts} +2 -2
  36. package/dist/postgres/index.cjs +30 -198
  37. package/dist/postgres/index.cjs.map +1 -1
  38. package/dist/postgres/index.d.cts +7 -2
  39. package/dist/postgres/index.d.ts +7 -2
  40. package/dist/postgres/index.js +17 -3
  41. package/dist/postgres/index.js.map +1 -1
  42. package/dist/upgrade/index.cjs +19 -240
  43. package/dist/upgrade/index.cjs.map +1 -1
  44. package/dist/upgrade/index.js +3 -3
  45. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,61 @@
1
1
  # @niscorp/strata
2
2
 
3
+ ## 0.1.5
4
+
5
+ ### Patch Changes
6
+
7
+ - f834f3f: `evaluate` checks a config object once and only evaluates it after that; `prismTransform` is gone. **Breaking.**
8
+
9
+ BREAKING — approved by moccadroid, 2026-10-09: replace `prismTransform` with `evaluate` (`transform: evaluate`), and pass limits as `{ limits: … }`.
10
+
11
+ Prism had three ways to run a config, and the one a host was told to hand to its seam (`prismTransform`) was the one that reported worst, while the hosts on a hot path each wrapped `evaluate`, which checked the config on every call. There are two now, with one job each.
12
+
13
+ **`evaluate(config, source, options?)`** — for a config a program holds.
14
+ - The first time it is handed a config object it checks it and keeps its tree; the second time it prepares the tree as `compile` would; from then on a call only evaluates. Four fields picked and renamed, the same config object again: 3.5 µs before, 0.4 µs now. A nested choice on two fields: 18 µs before, 0.7 µs now. A config that is a new object on every call costs what it did.
15
+ - It is kept **by the object**: a config changed in place after its first call is not read again. Hand over a new object.
16
+ - Both arguments are `unknown`, so it is what a host's transform seam takes: `createTide({ transform: evaluate })`, `createUpgrader(grammars, { transform: evaluate })`.
17
+ - The third argument is `{ limits?, check? }`. Limits were the third argument themselves: `evaluate(config, source, { maxSteps: 100 })` is now `evaluate(config, source, { limits: { maxSteps: 100 } })`.
18
+ - `check: 'always'` is for writing a config, for tests and for tools: nothing is kept, the config is checked on every call, and the source must be plain JSON (a source holding `undefined`, a function, a `Date` or a non-finite number is refused with `E_TYPE`).
19
+ - An invalid config is a `PrismError` (`E_SCHEMA`) naming the part that is wrong, however deep the config. `prismTransform` threw zod's own error, and a `RangeError` for a config nested far past the limit.
20
+
21
+ `evaluateSafe` takes the same arguments.
22
+
23
+ **`compile` and `execute`** — for a config that is stored. Unchanged.
24
+
25
+ **`prismTransform` is removed**, from `@niscorp/prism` and from `@niscorp/prism/migrations`. What it added over `evaluate` was a check that the source is plain JSON; that check is now `check: 'always'`, and a seam's source is taken as it is.
26
+
27
+ **moss, nova, vex, loom, nisc, create-nisc and the cli move with it.** Each has Prism as a peer or a dependency, or has one of those that do, and a Prism at 0.3 is outside the range their last versions accept: an app takes them together. Nothing in vex, loom or the cli changed beyond that range.
28
+
29
+ moss's shell and nova's `$prism` binding called `evaluate` on every use and so paid the check each time: an endpoint's request and response under moss, and a `$prism` value on each draw and for each row of a list, are 8 to 45 times faster for the configs measured. tide's and strata's documentation name `evaluate` where they named `prismTransform`.
30
+
31
+ **What to change**
32
+ - `import { prismTransform } from '@niscorp/prism'` or `'@niscorp/prism/migrations'` → `import { evaluate } from '@niscorp/prism'`, and `transform: prismTransform` → `transform: evaluate`. Every app made by `create-nisc` has this in `src/dev/strata.ts`; the app's typecheck and `npm run strata` both stop on that line until it is changed.
33
+ - A third argument of limits becomes `{ limits: … }`.
34
+ - A wrapper that parsed the config before calling `evaluate` (`evaluate(ConfigSchema.parse(config), …)`) makes a new object on every call and so is checked on every call: hand `evaluate` the config itself.
35
+ - Code that changes a config object in place and evaluates it again must hand over a new object, or pass `{ check: 'always' }`.
36
+ - A host that relied on `prismTransform` refusing a source that is not plain JSON checks it itself, or passes `{ check: 'always' }`.
37
+
38
+ ## 0.1.4
39
+
40
+ ### Patch Changes
41
+
42
+ - 7f8d202: Under `require`, the entry points of nova, prism and strata share one copy of their code, as they always have under `import`.
43
+
44
+ The CommonJS build was not split, so every entry point carried its own copy of each class and of each React context. The ESM build is byte for byte what it was. Under `require`:
45
+ - an error from `@niscorp/strata/postgres`, `/check`, `/upgrade` or `/node` is an `instanceof` the `StrataError` that `@niscorp/strata` exports; one from `prismTransform` of `@niscorp/prism/migrations` is an `instanceof PrismError`; one from `<Nova.Layout>` is an `instanceof NovaError` and of its own class. None of them was.
46
+ - `upgradeStore` names the row it refused — `integration_actions (integration_id="…", action_id="…"): …`, with the upgrader's error as its `cause` — and so does a moss boot that meets a stored row it cannot read. Both gave the upgrader's sentence alone.
47
+ - a kit registered from `@niscorp/nova/adapters/react/components` renders under `<Nova.Shell>`. It threw `useShell must be used inside <NovaShellProvider>`.
48
+
49
+ **What to change:** nothing in an ESM app. A CommonJS app that had built on any of the above — a branch that ran because `instanceof` failed, a match on the whole text of an `upgradeStore` refusal — now sees what an ESM app sees. An app that loads both builds of one package in one process still has two copies of it.
50
+
51
+ - 2b5fd83: `migrate` takes a `guard` and a `dryRun`.
52
+
53
+ A host could run a table migration and could not ask anything of the result before it landed, or see what a run would do without doing it.
54
+
55
+ `guard(tx)` is asked inside the run's transaction, after the last pending step — when nothing was pending too. Every sentence it returns refuses the run with `DOES_NOT_FIT`, and nothing was applied. `dryRun` does all of it, guard included, then rolls it back: the report says what would be applied, and it takes the locks a real run takes.
56
+
57
+ **What to change:** nothing. A run given neither behaves exactly as before. `StrataErrorCode` gains one member, `DOES_NOT_FIT`.
58
+
3
59
  ## 0.1.3
4
60
 
5
61
  ### Patch Changes
package/README.md CHANGED
@@ -78,7 +78,7 @@ own tables, the sessions table, the vex cache — in one ledgered run at boot.
78
78
 
79
79
  | | |
80
80
  |---|---|
81
- | `migrate(pool, sequences, { mode, table, schema })` | The run. `mode: 'apply'` (default) or `'verify'`. Returns `{ applied, plan }`. |
81
+ | `migrate(pool, sequences, { mode, guard, dryRun, table, schema })` | The run. `mode: 'apply'` (default) or `'verify'`. Returns `{ applied, plan }`. `guard(tx)` is asked inside the run, after the last pending step — when nothing was pending too: every sentence it returns refuses the run (`DOES_NOT_FIT`), and nothing was applied. `dryRun` does all of it, guard included, then rolls it back — the report says what would be applied, and it takes the locks a real run takes. |
82
82
  | `status(pool, sequences, options)` | The plan, read-only — creates nothing, not even the ledger. |
83
83
  | `readLedger(pool, options)` | The ledger's rows; empty for a database never migrated. |
84
84
  | `ledgerDdl(options)` | The ledger table's DDL — the one statement strata runs outside a ledger. |
@@ -181,7 +181,7 @@ works out EXACTLY what each must become, and holds the edit to it.
181
181
  ```ts
182
182
  // the app's src/dev/strata.ts — it lists its artifacts; strata does the rest
183
183
  import { runSourceUpgrade } from '@niscorp/strata/node';
184
- process.exit(await runSourceUpgrade({ root, grammars, transform: prismTransform, schemas, documents }, process.argv.slice(2)));
184
+ process.exit(await runSourceUpgrade({ root, grammars, transform: evaluate, schemas, documents }, process.argv.slice(2)));
185
185
  ```
186
186
 
187
187
  ```bash
@@ -1,234 +1,29 @@
1
1
  'use strict';
2
2
 
3
- // src/errors.ts
4
- var StrataError = class extends Error {
5
- code;
6
- details;
7
- constructor(code, message, details = [], options) {
8
- super(details.length > 0 ? `${message}
9
- ${details.map((d) => ` ${d}`).join("\n")}` : message, options);
10
- this.name = "StrataError";
11
- this.code = code;
12
- this.details = details;
13
- }
14
- };
3
+ var chunkKNBS3AJZ_cjs = require('../chunk-KNBS3AJZ.cjs');
4
+ require('../chunk-ATHZ7HT5.cjs');
15
5
 
16
- // src/check/index.ts
17
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18
- var byKey = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
19
- var sortKeys = (value) => {
20
- if (Array.isArray(value)) return value.map(sortKeys);
21
- if (!isRecord(value)) return value;
22
- return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));
23
- };
24
- var NAMED = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
25
- var DATA = /* @__PURE__ */ new Set(["const", "enum", "default", "examples"]);
26
- var normalize = (value) => {
27
- if (Array.isArray(value)) return value.map(normalize);
28
- if (!isRecord(value)) return value;
29
- return Object.fromEntries(
30
- Object.entries(value).filter(([key]) => key !== "description" && key !== "$schema").sort(byKey).map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)])
31
- );
32
- };
33
- var namedSchemas = (map, each) => Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));
34
- var snapshotOf = (sequence, schemas) => {
35
- const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);
36
- const given = Object.keys(schemas);
37
- const missing = declared.filter((k) => !given.includes(k));
38
- const extra = given.filter((k) => !declared.includes(k));
39
- if (missing.length > 0 || extra.length > 0) {
40
- throw new StrataError("UNKNOWN_KIND", `The schemas for ${sequence.id} do not match its kinds.`, [
41
- ...missing.map((k) => `no schema for ${k}`),
42
- ...extra.map((k) => `${k} is not a kind of ${sequence.id}`)
43
- ]);
44
- }
45
- const kinds = {};
46
- for (const kind of [...declared].sort()) {
47
- const schema = schemas[kind];
48
- if (schema !== void 0) kinds[kind] = sortKeys(schema["~standard"].jsonSchema.input({ target: "draft-2020-12" }));
49
- }
50
- return { sequence: sequence.id, version: sequence.migrations.length, kinds };
51
- };
52
- var snapshotText = (snapshot) => `${JSON.stringify(sortKeys(snapshot), null, 2)}
53
- `;
54
- var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
55
- if (out.length >= limit) return;
56
- if (JSON.stringify(a) === JSON.stringify(b)) return;
57
- if (isRecord(a) && isRecord(b)) {
58
- for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
59
- const at = path === "" ? key : `${path}.${key}`;
60
- const before = a[key];
61
- const after = b[key];
62
- if (!(key in a)) out.push(`+ ${at}`);
63
- else if (!(key in b)) out.push(`- ${at}`);
64
- else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);
65
- else diffLines(before, after, at, out, limit, canon, sets);
66
- if (out.length >= limit) return;
67
- }
68
- return;
69
- }
70
- if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {
71
- a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));
72
- return;
73
- }
74
- if (Array.isArray(a) && Array.isArray(b)) {
75
- const text = (v) => JSON.stringify(canon(v));
76
- const label = (v) => isRecord(v) && isRecord(v["properties"]) ? Object.keys(v["properties"]).join(",") : (text(v) ?? "").slice(0, 50);
77
- const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));
78
- const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));
79
- const byLabel = new Map(onlyB.map((y) => [label(y), y]));
80
- for (const x of onlyA) {
81
- const partner = byLabel.get(label(x));
82
- if (partner !== void 0) {
83
- diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);
84
- byLabel.delete(label(x));
85
- } else {
86
- out.push(`- ${path}[${label(x)}]`);
87
- }
88
- if (out.length >= limit) return;
89
- }
90
- for (const [name] of byLabel) {
91
- out.push(`+ ${path}[${name}]`);
92
- if (out.length >= limit) return;
93
- }
94
- return;
95
- }
96
- out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
97
- };
98
- var diffPositions = (a, b, path, out, limit, canon) => {
99
- for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
100
- if (out.length >= limit) return;
101
- if (i >= a.length) out.push(`+ ${path}[${i}]`);
102
- else if (i >= b.length) out.push(`- ${path}[${i}]`);
103
- else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);
104
- }
105
- };
106
- var REF_PREFIX = /^#\/(\$defs|definitions)\//;
107
- var respell = (value) => {
108
- let node = value;
109
- const anyOf = node["anyOf"];
110
- if (!("type" in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m["type"] === "string")) {
111
- const { anyOf: _union, ...rest } = node;
112
- node = { ...rest, type: anyOf.map((m) => isRecord(m) ? m["type"] : void 0) };
113
- }
114
- const type = node["type"];
115
- if (Array.isArray(type)) {
116
- const types = [...new Set(type.map(String))].sort();
117
- node = { ...node, type: types.length === 1 ? types[0] : types };
118
- }
119
- const allOf = node["allOf"];
120
- const only = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : void 0;
121
- if (!("$ref" in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only["$ref"] === "string") {
122
- const { allOf: _wrapper, ...rest } = node;
123
- node = { ...rest, $ref: only["$ref"] };
124
- }
125
- return node;
126
- };
127
- var schemaChildren = (node) => Object.entries(node).flatMap(
128
- ([key, child]) => key === "$ref" || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child]
129
- );
130
- var canonical = (recorded) => {
131
- const schema = normalize(recorded);
132
- if (!isRecord(schema)) return schema;
133
- const defs = {
134
- ...isRecord(schema["definitions"]) ? schema["definitions"] : {},
135
- ...isRecord(schema["$defs"]) ? schema["$defs"] : {}
136
- };
137
- const { $defs: _defs, definitions: _definitions, ...body } = schema;
138
- const target = (ref) => ref === "#" ? { key: "#", node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, "")] };
139
- const recursive = /* @__PURE__ */ new Set();
140
- const findCycles = (value, stack) => {
141
- if (Array.isArray(value)) {
142
- for (const item of value) findCycles(item, stack);
143
- return;
144
- }
145
- if (!isRecord(value)) return;
146
- const node = respell(value);
147
- for (const child of schemaChildren(node)) findCycles(child, stack);
148
- const ref = node["$ref"];
149
- if (typeof ref !== "string") return;
150
- const { key, node: next } = target(ref);
151
- if (stack.includes(key)) recursive.add(key);
152
- else findCycles(next, [...stack, key]);
153
- };
154
- findCycles(body, ["#"]);
155
- const names = /* @__PURE__ */ new Map();
156
- const named = {};
157
- const nameOf = (key, node) => {
158
- const known = names.get(key);
159
- if (known !== void 0) return known;
160
- const name = `d${names.size}`;
161
- names.set(key, name);
162
- named[name] = emit(node);
163
- return name;
164
- };
165
- const emit = (value) => {
166
- if (Array.isArray(value)) return value.map(emit);
167
- if (!isRecord(value)) return value;
168
- const node = respell(value);
169
- const rest = Object.fromEntries(
170
- Object.entries(node).filter(([key2]) => key2 !== "$ref").sort(byKey).map(([key2, child]) => [key2, NAMED.has(key2) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key2) ? child : emit(child)])
171
- );
172
- const ref = node["$ref"];
173
- if (typeof ref !== "string") return rest;
174
- const { key, node: next } = target(ref);
175
- const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);
176
- return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;
177
- };
178
- const root = recursive.has("#") ? { $ref: `#/$defs/${nameOf("#", body)}` } : emit(body);
179
- return Object.keys(named).length === 0 ? root : sortKeys({ ...isRecord(root) ? root : { allOf: [root] }, $defs: named });
180
- };
181
- var compareSnapshot = (recorded, current) => {
182
- if (recorded === void 0) return { status: "missing" };
183
- const changes = [];
184
- for (const kind of [.../* @__PURE__ */ new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {
185
- const lines = [];
186
- if (!(kind in recorded.kinds)) lines.push("+ (a new kind)");
187
- else if (!(kind in current.kinds)) lines.push("- (the kind is gone)");
188
- else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), "", lines, 12);
189
- if (lines.length > 0) changes.push({ kind, lines });
190
- }
191
- return changes.length === 0 ? { status: "same" } : { status: "changed", changes };
192
- };
193
- var issueText = (issue) => {
194
- const path = (issue.path ?? []).map((p) => typeof p === "object" ? String(p.key) : String(p)).join(".");
195
- return `${path === "" ? "" : `${path}: `}${issue.message}`;
196
- };
197
- var diffJson = (a, b, limit = 20) => {
198
- const out = [];
199
- diffLines(a, b, "", out, limit, sortKeys, false);
200
- return out;
201
- };
202
- var checkCorpus = async (upgrader, schemas, documents) => {
203
- const failures = [];
204
- let passed = 0;
205
- for (const doc of documents) {
206
- const schema = schemas[doc.kind];
207
- if (schema === void 0) {
208
- failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });
209
- continue;
210
- }
211
- let upgraded;
212
- try {
213
- upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;
214
- } catch (error) {
215
- failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split("\n")[0] ?? error.message : String(error) });
216
- continue;
217
- }
218
- const result = await schema["~standard"].validate(upgraded);
219
- if (result.issues !== void 0) {
220
- failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join("; ") });
221
- } else {
222
- passed += 1;
223
- }
224
- }
225
- return { passed, failures };
226
- };
227
6
 
228
- exports.checkCorpus = checkCorpus;
229
- exports.compareSnapshot = compareSnapshot;
230
- exports.diffJson = diffJson;
231
- exports.snapshotOf = snapshotOf;
232
- exports.snapshotText = snapshotText;
7
+
8
+ Object.defineProperty(exports, "checkCorpus", {
9
+ enumerable: true,
10
+ get: function () { return chunkKNBS3AJZ_cjs.checkCorpus; }
11
+ });
12
+ Object.defineProperty(exports, "compareSnapshot", {
13
+ enumerable: true,
14
+ get: function () { return chunkKNBS3AJZ_cjs.compareSnapshot; }
15
+ });
16
+ Object.defineProperty(exports, "diffJson", {
17
+ enumerable: true,
18
+ get: function () { return chunkKNBS3AJZ_cjs.diffJson; }
19
+ });
20
+ Object.defineProperty(exports, "snapshotOf", {
21
+ enumerable: true,
22
+ get: function () { return chunkKNBS3AJZ_cjs.snapshotOf; }
23
+ });
24
+ Object.defineProperty(exports, "snapshotText", {
25
+ enumerable: true,
26
+ get: function () { return chunkKNBS3AJZ_cjs.snapshotText; }
27
+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AAA;AAC1D,IAAA,IAAI,MAAA,CAAO,WAAW,MAAA,EAAW;AAC/B,MAAA,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,GAAA,CAAI,IAAI,IAAA,EAAM,GAAA,CAAI,MAAM,MAAA,EAAQ,MAAA,CAAO,OAAO,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA,CAAE,GAAA,CAAI,SAAS,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,EAAG,CAAA;AAAA,IAC3G,CAAA,MAAO;AACL,MAAA,MAAA,IAAU,CAAA;AAAA,IACZ;AAAA,EACF;AACA,EAAA,OAAO,EAAE,QAAQ,QAAA,EAAS;AAC5B","file":"index.cjs","sourcesContent":["// Every refusal strata makes, by name. The message is a sentence for a person;\n// the code is for the program that has to decide what to do about it.\nexport type StrataErrorCode =\n // A sequence failed its schema, or two sequences share an id.\n | 'INVALID_SEQUENCE'\n // An applied migration's steps no longer match what the code says it ran.\n | 'EDITED'\n // The database has migrations of a sequence this code does not know yet —\n // it was migrated by newer code.\n | 'TOO_NEW'\n // A `dependsOn` names a migration nobody provides and the ledger lacks.\n | 'UNKNOWN_DEPENDENCY'\n // Pending migrations wait on each other.\n | 'CYCLE'\n // Verify mode found work to do.\n | 'PENDING'\n // A step threw; the whole run was rolled back.\n | 'STEP_FAILED'\n // The pool cannot hold one connection for a transaction.\n | 'NO_TRANSACTION'\n // A document kind nobody declares — as the root being upgraded, a step's\n // `at`, or an embedding's target.\n | 'UNKNOWN_KIND'\n // A grammar sequence handed to the ledger, or a table sequence to upgrade().\n | 'WRONG_OWNER';\n\nexport class StrataError extends Error {\n readonly code: StrataErrorCode;\n readonly details: readonly string[];\n\n constructor(code: StrataErrorCode, message: string, details: readonly string[] = [], options?: { cause?: unknown }) {\n super(details.length > 0 ? `${message}\\n${details.map((d) => ` ${d}`).join('\\n')}` : message, options);\n this.name = 'StrataError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/check — the gate a grammar change has to pass.\n//\n// Two questions, both mechanical:\n//\n// 1. SNAPSHOT — did a kind's schema change without the grammar gaining a\n// migration? Each kind's JSON Schema, taken through the schema's OWN\n// Standard JSON Schema hook, is recorded per grammar version. Same version,\n// different schema: something changed that older readers were never told.\n// Append a migration (an empty marker is enough for an addition — strict\n// readers still have to refuse the newer documents), then record the new\n// version.\n//\n// 2. CORPUS — does every real document ever captured, at the stamp it was\n// captured at, still upgrade to the current grammar and pass the current\n// strict schema? This is the judge: a snapshot only says something moved,\n// the corpus says whether old documents survive it. No JSON Schema diff\n// tool is trusted to decide compatibility.\n//\n// Pure: no files, no process. A host reads and writes snapshots where it keeps\n// them (nisc's own live in the repo's `strata/` directory).\n// ═══════════════════════════════════════════════════════════════\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\n// Any validator implementing Standard Schema + Standard JSON Schema (Zod ≥ 4.2,\n// Valibot, ArkType). Structural: strata depends on none of them.\nexport type GrammarSchema = {\n '~standard': {\n validate: (value: unknown) => StandardResult | Promise<StandardResult>;\n jsonSchema: { input: (options: { target: string }) => Record<string, unknown> };\n };\n};\n\nexport type Snapshot = { sequence: string; version: number; kinds: Readonly<Record<string, unknown>> };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Sorted keys, nothing else — for documents, where every key (a `description`\n// too) is content, and for a snapshot file, which keeps what the validator wrote.\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));\n};\n\n// Where a schema's keys are NAMES, not keywords — a field called `description`\n// or an op called `$ref` is grammar — and where its values are instance data\n// rather than schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// A schema without its prose: the `description` KEYWORD is documentation, and\n// rewording a `.describe()` must not demand a migration. `$schema` is the same\n// everywhere. Applied when comparing, never to what is recorded — so what the\n// gate ignores can change without touching a snapshot file.\nconst normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalize);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== 'description' && key !== '$schema')\n .sort(byKey)\n .map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)]),\n );\n};\n\n// A name → schema map, each schema through `each`, the names untouched.\nconst namedSchemas = (map: Record<string, unknown>, each: (schema: unknown) => unknown): Record<string, unknown> =>\n Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));\n\n// The grammar as it stands: every kind it declares, as JSON Schema — as the\n// validator wrote it, keys sorted. `schemas` must cover exactly the sequence's\n// kinds — a kind without a schema cannot be checked, and a schema without a\n// kind belongs to some other grammar.\nexport const snapshotOf = (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>): Snapshot => {\n const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);\n const given = Object.keys(schemas);\n const missing = declared.filter((k) => !given.includes(k));\n const extra = given.filter((k) => !declared.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new StrataError('UNKNOWN_KIND', `The schemas for ${sequence.id} do not match its kinds.`, [\n ...missing.map((k) => `no schema for ${k}`),\n ...extra.map((k) => `${k} is not a kind of ${sequence.id}`),\n ]);\n }\n const kinds: Record<string, unknown> = {};\n for (const kind of [...declared].sort()) {\n const schema = schemas[kind];\n if (schema !== undefined) kinds[kind] = sortKeys(schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }));\n }\n return { sequence: sequence.id, version: sequence.migrations.length, kinds };\n};\n\n// Stable text for a snapshot file: sorted keys, two-space indent, newline.\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\n// Schema arrays are compared as sets (`sets`) — all but a tuple's `prefixItems`,\n// see `diffPositions`; a document's arrays by position — `layout.children[1]` is\n// how a person finds the thing that changed.\nconst diffLines = (a: unknown, b: unknown, path: string, out: string[], limit: number, canon: (v: unknown) => unknown = normalize, sets = true): void => {\n if (out.length >= limit) return;\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (isRecord(a) && isRecord(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const at = path === '' ? key : `${path}.${key}`;\n const before = a[key];\n const after = b[key];\n if (!(key in a)) out.push(`+ ${at}`);\n else if (!(key in b)) out.push(`- ${at}`);\n else if (sets && key === 'prefixItems' && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);\n else diffLines(before, after, at, out, limit, canon, sets);\n if (out.length >= limit) return;\n }\n return;\n }\n if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {\n a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));\n return;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n // Schema arrays are SETS more often than sequences — a union's `anyOf`, a\n // `required` list, an `enum` — and one added branch shifts every index\n // after it. Match elements by what they describe (an object schema by its\n // property names — for Prism's union, the op), report the ones on one side\n // only, and diff the ones that changed in place.\n const text = (v: unknown): string => JSON.stringify(canon(v));\n const label = (v: unknown): string =>\n isRecord(v) && isRecord(v['properties']) ? Object.keys(v['properties']).join(',') : (text(v) ?? '').slice(0, 50);\n const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));\n const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));\n const byLabel = new Map(onlyB.map((y) => [label(y), y]));\n for (const x of onlyA) {\n const partner = byLabel.get(label(x));\n if (partner !== undefined) {\n diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);\n byLabel.delete(label(x));\n } else {\n out.push(`- ${path}[${label(x)}]`);\n }\n if (out.length >= limit) return;\n }\n for (const [name] of byLabel) {\n out.push(`+ ${path}[${name}]`);\n if (out.length >= limit) return;\n }\n return;\n }\n out.push(`~ ${path || '(root)'}: ${JSON.stringify(a)?.slice(0, 60)} → ${JSON.stringify(b)?.slice(0, 60)}`);\n};\n\n// A tuple's `prefixItems` is the one schema array that is a SEQUENCE: position\n// is the grammar, so [string, number] and [number, string] are different tuples\n// and a document valid for one is not for the other. Compared place by place;\n// what sits IN a place is a schema again, its own arrays sets as ever.\nconst diffPositions = (a: readonly unknown[], b: readonly unknown[], path: string, out: string[], limit: number, canon: (v: unknown) => unknown): void => {\n for (let i = 0; i < Math.max(a.length, b.length); i += 1) {\n if (out.length >= limit) return;\n if (i >= a.length) out.push(`+ ${path}[${i}]`);\n else if (i >= b.length) out.push(`- ${path}[${i}]`);\n else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);\n }\n};\n\n// ── canonical form ──────────────────────────────────────────────\n//\n// A snapshot records what the validator WROTE, and validators spell one schema\n// many ways: they name and inline definitions as they please (zod numbers them\n// in visit order, and 4.3 and 4.4 visit differently), write a described\n// reference as `allOf: [{ $ref }]` or as `$ref`, and a union of bare types as\n// `anyOf: [{ type }, …]` or `type: […]`. None of that is the grammar, so a\n// comparison reads both sides in one spelling: every definition inlined unless\n// it is recursive, the recursive ones renamed by first use, and every schema\n// identity above written one way. A snapshot FILE stays what the validator\n// wrote — only the comparison is canonical.\n\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\n// One spelling for the equivalences the node itself can show.\nconst respell = (value: Record<string, unknown>): Record<string, unknown> => {\n let node = value;\n const anyOf = node['anyOf'];\n if (!('type' in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m['type'] === 'string')) {\n const { anyOf: _union, ...rest } = node;\n node = { ...rest, type: anyOf.map((m) => (isRecord(m) ? m['type'] : undefined)) };\n }\n const type = node['type'];\n if (Array.isArray(type)) {\n const types = [...new Set(type.map(String))].sort();\n node = { ...node, type: types.length === 1 ? types[0] : types };\n }\n const allOf = node['allOf'];\n const only: unknown = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : undefined;\n if (!('$ref' in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only['$ref'] === 'string') {\n const { allOf: _wrapper, ...rest } = node;\n node = { ...rest, $ref: only['$ref'] };\n }\n return node;\n};\n\n// A schema node's own children — keyword values, and each schema of a name\n// map — but never the names, and never instance data.\nconst schemaChildren = (node: Record<string, unknown>): unknown[] =>\n Object.entries(node).flatMap(([key, child]) =>\n key === '$ref' || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child],\n );\n\nconst canonical = (recorded: unknown): unknown => {\n const schema = normalize(recorded);\n if (!isRecord(schema)) return schema;\n const defs: Record<string, unknown> = {\n ...(isRecord(schema['definitions']) ? schema['definitions'] : {}),\n ...(isRecord(schema['$defs']) ? schema['$defs'] : {}),\n };\n const { $defs: _defs, definitions: _definitions, ...body } = schema;\n const target = (ref: string): { key: string; node: unknown } =>\n ref === '#' ? { key: '#', node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, '')] };\n\n // Which targets are reached from inside their own expansion: those, and\n // only those, stay definitions.\n const recursive = new Set<string>();\n const findCycles = (value: unknown, stack: readonly string[]): void => {\n if (Array.isArray(value)) {\n for (const item of value) findCycles(item, stack);\n return;\n }\n if (!isRecord(value)) return;\n const node = respell(value);\n for (const child of schemaChildren(node)) findCycles(child, stack);\n const ref = node['$ref'];\n if (typeof ref !== 'string') return;\n const { key, node: next } = target(ref);\n if (stack.includes(key)) recursive.add(key);\n else findCycles(next, [...stack, key]);\n };\n findCycles(body, ['#']);\n\n const names = new Map<string, string>();\n const named: Record<string, unknown> = {};\n const nameOf = (key: string, node: unknown): string => {\n const known = names.get(key);\n if (known !== undefined) return known;\n const name = `d${names.size}`;\n names.set(key, name);\n named[name] = emit(node);\n return name;\n };\n const emit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(emit);\n if (!isRecord(value)) return value;\n const node = respell(value);\n const rest: Record<string, unknown> = Object.fromEntries(\n Object.entries(node)\n .filter(([key]) => key !== '$ref')\n .sort(byKey)\n .map(([key, child]) => [key, NAMED.has(key) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key) ? child : emit(child)]),\n );\n const ref = node['$ref'];\n if (typeof ref !== 'string') return rest;\n const { key, node: next } = target(ref);\n const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);\n return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;\n };\n\n const root = recursive.has('#') ? { $ref: `#/$defs/${nameOf('#', body)}` } : emit(body);\n return Object.keys(named).length === 0 ? root : sortKeys({ ...(isRecord(root) ? root : { allOf: [root] }), $defs: named });\n};\n\nexport type SnapshotComparison =\n | { status: 'same' }\n | { status: 'missing' }\n | { status: 'changed'; changes: readonly { kind: string; lines: readonly string[] }[] };\n\n// `recorded` is the snapshot kept for the grammar's CURRENT version (or\n// undefined if none was kept). Changed means: a migration is owed. Both sides\n// are read in canonical form, so a validator's respelling is not a change.\nexport const compareSnapshot = (recorded: Snapshot | undefined, current: Snapshot): SnapshotComparison => {\n if (recorded === undefined) return { status: 'missing' };\n const changes: { kind: string; lines: string[] }[] = [];\n for (const kind of [...new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {\n const lines: string[] = [];\n if (!(kind in recorded.kinds)) lines.push('+ (a new kind)');\n else if (!(kind in current.kinds)) lines.push('- (the kind is gone)');\n else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), '', lines, 12);\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\n\n// ── the corpus ──────────────────────────────────────────────────\n\nexport type CorpusDocument = { id: string; kind: string; stamp: Stamp; document: unknown };\nexport type CorpusFailure = { id: string; kind: string; reason: string };\nexport type CorpusReport = { passed: number; failures: readonly CorpusFailure[] };\n\nconst issueText = (issue: Issue): string => {\n const path = (issue.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return `${path === '' ? '' : `${path}: `}${issue.message}`;\n};\n\n// What differs between two JSON values, as short lines (`+ a.b`, `- c`,\n// `~ d: 1 → 2`) — for a report a person or an agent acts on.\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', out, limit, sortKeys, false);\n return out;\n};\n\n// Every document, upgraded from its stamp, must pass the current schema of its kind.\nexport const checkCorpus = async (\n upgrader: Upgrader,\n schemas: Readonly<Record<string, GrammarSchema>>,\n documents: readonly CorpusDocument[],\n): Promise<CorpusReport> => {\n const failures: CorpusFailure[] = [];\n let passed = 0;\n for (const doc of documents) {\n const schema = schemas[doc.kind];\n if (schema === undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });\n continue;\n }\n let upgraded: unknown;\n try {\n upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;\n } catch (error) {\n failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split('\\n')[0] ?? error.message : String(error) });\n continue;\n }\n const result = await schema['~standard'].validate(upgraded);\n if (result.issues !== undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join('; ') });\n } else {\n passed += 1;\n }\n }\n return { passed, failures };\n};\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
@@ -1,4 +1,4 @@
1
- export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-274M232S.js';
2
- import '../chunk-EGFF63GA.js';
1
+ export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-4BLHBVSC.js';
2
+ import '../chunk-AKKWEXO2.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { StrataError } from './chunk-EGFF63GA.js';
1
+ import { StrataError } from './chunk-AKKWEXO2.js';
2
2
 
3
3
  // src/check/index.ts
4
4
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -213,5 +213,5 @@ var checkCorpus = async (upgrader, schemas, documents) => {
213
213
  };
214
214
 
215
215
  export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText };
216
- //# sourceMappingURL=chunk-274M232S.js.map
217
- //# sourceMappingURL=chunk-274M232S.js.map
216
+ //# sourceMappingURL=chunk-4BLHBVSC.js.map
217
+ //# sourceMappingURL=chunk-4BLHBVSC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/check/index.ts"],"names":["key"],"mappings":";;;AAyCA,IAAM,QAAA,GAAW,CAAC,KAAA,KAChB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAErE,IAAM,KAAA,GAAQ,CAAC,CAAC,CAAC,CAAA,EAAsB,CAAC,CAAC,CAAA,KAAkC,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAIpG,IAAM,QAAA,GAAW,CAAC,KAAA,KAA4B;AAC5C,EAAA,IAAI,MAAM,OAAA,CAAQ,KAAK,GAAG,OAAO,KAAA,CAAM,IAAI,QAAQ,CAAA;AACnD,EAAA,IAAI,CAAC,QAAA,CAAS,KAAK,CAAA,EAAG,OAAO,KAAA;AAC7B,EAAA,OAAO,MAAA,CAAO,YAAY,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,CAAE,IAAA,CAA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W,MAAA,EAAW;AAC/B,MAAA,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,GAAA,CAAI,IAAI,IAAA,EAAM,GAAA,CAAI,MAAM,MAAA,EAAQ,MAAA,CAAO,OAAO,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA,CAAE,GAAA,CAAI,SAAS,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,EAAG,CAAA;AAAA,IAC3G,CAAA,MAAO;AACL,MAAA,MAAA,IAAU,CAAA;AAAA,IACZ;AAAA,EACF;AACA,EAAA,OAAO,EAAE,QAAQ,QAAA,EAAS;AAC5B","file":"chunk-274M232S.js","sourcesContent":["import type { Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/check — the gate a grammar change has to pass.\n//\n// Two questions, both mechanical:\n//\n// 1. SNAPSHOT — did a kind's schema change without the grammar gaining a\n// migration? Each kind's JSON Schema, taken through the schema's OWN\n// Standard JSON Schema hook, is recorded per grammar version. Same version,\n// different schema: something changed that older readers were never told.\n// Append a migration (an empty marker is enough for an addition — strict\n// readers still have to refuse the newer documents), then record the new\n// version.\n//\n// 2. CORPUS — does every real document ever captured, at the stamp it was\n// captured at, still upgrade to the current grammar and pass the current\n// strict schema? This is the judge: a snapshot only says something moved,\n// the corpus says whether old documents survive it. No JSON Schema diff\n// tool is trusted to decide compatibility.\n//\n// Pure: no files, no process. A host reads and writes snapshots where it keeps\n// them (nisc's own live in the repo's `strata/` directory).\n// ═══════════════════════════════════════════════════════════════\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\n// Any validator implementing Standard Schema + Standard JSON Schema (Zod ≥ 4.2,\n// Valibot, ArkType). Structural: strata depends on none of them.\nexport type GrammarSchema = {\n '~standard': {\n validate: (value: unknown) => StandardResult | Promise<StandardResult>;\n jsonSchema: { input: (options: { target: string }) => Record<string, unknown> };\n };\n};\n\nexport type Snapshot = { sequence: string; version: number; kinds: Readonly<Record<string, unknown>> };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Sorted keys, nothing else — for documents, where every key (a `description`\n// too) is content, and for a snapshot file, which keeps what the validator wrote.\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));\n};\n\n// Where a schema's keys are NAMES, not keywords — a field called `description`\n// or an op called `$ref` is grammar — and where its values are instance data\n// rather than schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// A schema without its prose: the `description` KEYWORD is documentation, and\n// rewording a `.describe()` must not demand a migration. `$schema` is the same\n// everywhere. Applied when comparing, never to what is recorded — so what the\n// gate ignores can change without touching a snapshot file.\nconst normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalize);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== 'description' && key !== '$schema')\n .sort(byKey)\n .map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)]),\n );\n};\n\n// A name → schema map, each schema through `each`, the names untouched.\nconst namedSchemas = (map: Record<string, unknown>, each: (schema: unknown) => unknown): Record<string, unknown> =>\n Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));\n\n// The grammar as it stands: every kind it declares, as JSON Schema — as the\n// validator wrote it, keys sorted. `schemas` must cover exactly the sequence's\n// kinds — a kind without a schema cannot be checked, and a schema without a\n// kind belongs to some other grammar.\nexport const snapshotOf = (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>): Snapshot => {\n const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);\n const given = Object.keys(schemas);\n const missing = declared.filter((k) => !given.includes(k));\n const extra = given.filter((k) => !declared.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new StrataError('UNKNOWN_KIND', `The schemas for ${sequence.id} do not match its kinds.`, [\n ...missing.map((k) => `no schema for ${k}`),\n ...extra.map((k) => `${k} is not a kind of ${sequence.id}`),\n ]);\n }\n const kinds: Record<string, unknown> = {};\n for (const kind of [...declared].sort()) {\n const schema = schemas[kind];\n if (schema !== undefined) kinds[kind] = sortKeys(schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }));\n }\n return { sequence: sequence.id, version: sequence.migrations.length, kinds };\n};\n\n// Stable text for a snapshot file: sorted keys, two-space indent, newline.\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\n// Schema arrays are compared as sets (`sets`) — all but a tuple's `prefixItems`,\n// see `diffPositions`; a document's arrays by position — `layout.children[1]` is\n// how a person finds the thing that changed.\nconst diffLines = (a: unknown, b: unknown, path: string, out: string[], limit: number, canon: (v: unknown) => unknown = normalize, sets = true): void => {\n if (out.length >= limit) return;\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (isRecord(a) && isRecord(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const at = path === '' ? key : `${path}.${key}`;\n const before = a[key];\n const after = b[key];\n if (!(key in a)) out.push(`+ ${at}`);\n else if (!(key in b)) out.push(`- ${at}`);\n else if (sets && key === 'prefixItems' && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);\n else diffLines(before, after, at, out, limit, canon, sets);\n if (out.length >= limit) return;\n }\n return;\n }\n if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {\n a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));\n return;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n // Schema arrays are SETS more often than sequences — a union's `anyOf`, a\n // `required` list, an `enum` — and one added branch shifts every index\n // after it. Match elements by what they describe (an object schema by its\n // property names — for Prism's union, the op), report the ones on one side\n // only, and diff the ones that changed in place.\n const text = (v: unknown): string => JSON.stringify(canon(v));\n const label = (v: unknown): string =>\n isRecord(v) && isRecord(v['properties']) ? Object.keys(v['properties']).join(',') : (text(v) ?? '').slice(0, 50);\n const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));\n const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));\n const byLabel = new Map(onlyB.map((y) => [label(y), y]));\n for (const x of onlyA) {\n const partner = byLabel.get(label(x));\n if (partner !== undefined) {\n diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);\n byLabel.delete(label(x));\n } else {\n out.push(`- ${path}[${label(x)}]`);\n }\n if (out.length >= limit) return;\n }\n for (const [name] of byLabel) {\n out.push(`+ ${path}[${name}]`);\n if (out.length >= limit) return;\n }\n return;\n }\n out.push(`~ ${path || '(root)'}: ${JSON.stringify(a)?.slice(0, 60)} → ${JSON.stringify(b)?.slice(0, 60)}`);\n};\n\n// A tuple's `prefixItems` is the one schema array that is a SEQUENCE: position\n// is the grammar, so [string, number] and [number, string] are different tuples\n// and a document valid for one is not for the other. Compared place by place;\n// what sits IN a place is a schema again, its own arrays sets as ever.\nconst diffPositions = (a: readonly unknown[], b: readonly unknown[], path: string, out: string[], limit: number, canon: (v: unknown) => unknown): void => {\n for (let i = 0; i < Math.max(a.length, b.length); i += 1) {\n if (out.length >= limit) return;\n if (i >= a.length) out.push(`+ ${path}[${i}]`);\n else if (i >= b.length) out.push(`- ${path}[${i}]`);\n else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);\n }\n};\n\n// ── canonical form ──────────────────────────────────────────────\n//\n// A snapshot records what the validator WROTE, and validators spell one schema\n// many ways: they name and inline definitions as they please (zod numbers them\n// in visit order, and 4.3 and 4.4 visit differently), write a described\n// reference as `allOf: [{ $ref }]` or as `$ref`, and a union of bare types as\n// `anyOf: [{ type }, …]` or `type: […]`. None of that is the grammar, so a\n// comparison reads both sides in one spelling: every definition inlined unless\n// it is recursive, the recursive ones renamed by first use, and every schema\n// identity above written one way. A snapshot FILE stays what the validator\n// wrote — only the comparison is canonical.\n\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\n// One spelling for the equivalences the node itself can show.\nconst respell = (value: Record<string, unknown>): Record<string, unknown> => {\n let node = value;\n const anyOf = node['anyOf'];\n if (!('type' in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m['type'] === 'string')) {\n const { anyOf: _union, ...rest } = node;\n node = { ...rest, type: anyOf.map((m) => (isRecord(m) ? m['type'] : undefined)) };\n }\n const type = node['type'];\n if (Array.isArray(type)) {\n const types = [...new Set(type.map(String))].sort();\n node = { ...node, type: types.length === 1 ? types[0] : types };\n }\n const allOf = node['allOf'];\n const only: unknown = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : undefined;\n if (!('$ref' in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only['$ref'] === 'string') {\n const { allOf: _wrapper, ...rest } = node;\n node = { ...rest, $ref: only['$ref'] };\n }\n return node;\n};\n\n// A schema node's own children — keyword values, and each schema of a name\n// map — but never the names, and never instance data.\nconst schemaChildren = (node: Record<string, unknown>): unknown[] =>\n Object.entries(node).flatMap(([key, child]) =>\n key === '$ref' || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child],\n );\n\nconst canonical = (recorded: unknown): unknown => {\n const schema = normalize(recorded);\n if (!isRecord(schema)) return schema;\n const defs: Record<string, unknown> = {\n ...(isRecord(schema['definitions']) ? schema['definitions'] : {}),\n ...(isRecord(schema['$defs']) ? schema['$defs'] : {}),\n };\n const { $defs: _defs, definitions: _definitions, ...body } = schema;\n const target = (ref: string): { key: string; node: unknown } =>\n ref === '#' ? { key: '#', node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, '')] };\n\n // Which targets are reached from inside their own expansion: those, and\n // only those, stay definitions.\n const recursive = new Set<string>();\n const findCycles = (value: unknown, stack: readonly string[]): void => {\n if (Array.isArray(value)) {\n for (const item of value) findCycles(item, stack);\n return;\n }\n if (!isRecord(value)) return;\n const node = respell(value);\n for (const child of schemaChildren(node)) findCycles(child, stack);\n const ref = node['$ref'];\n if (typeof ref !== 'string') return;\n const { key, node: next } = target(ref);\n if (stack.includes(key)) recursive.add(key);\n else findCycles(next, [...stack, key]);\n };\n findCycles(body, ['#']);\n\n const names = new Map<string, string>();\n const named: Record<string, unknown> = {};\n const nameOf = (key: string, node: unknown): string => {\n const known = names.get(key);\n if (known !== undefined) return known;\n const name = `d${names.size}`;\n names.set(key, name);\n named[name] = emit(node);\n return name;\n };\n const emit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(emit);\n if (!isRecord(value)) return value;\n const node = respell(value);\n const rest: Record<string, unknown> = Object.fromEntries(\n Object.entries(node)\n .filter(([key]) => key !== '$ref')\n .sort(byKey)\n .map(([key, child]) => [key, NAMED.has(key) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key) ? child : emit(child)]),\n );\n const ref = node['$ref'];\n if (typeof ref !== 'string') return rest;\n const { key, node: next } = target(ref);\n const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);\n return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;\n };\n\n const root = recursive.has('#') ? { $ref: `#/$defs/${nameOf('#', body)}` } : emit(body);\n return Object.keys(named).length === 0 ? root : sortKeys({ ...(isRecord(root) ? root : { allOf: [root] }), $defs: named });\n};\n\nexport type SnapshotComparison =\n | { status: 'same' }\n | { status: 'missing' }\n | { status: 'changed'; changes: readonly { kind: string; lines: readonly string[] }[] };\n\n// `recorded` is the snapshot kept for the grammar's CURRENT version (or\n// undefined if none was kept). Changed means: a migration is owed. Both sides\n// are read in canonical form, so a validator's respelling is not a change.\nexport const compareSnapshot = (recorded: Snapshot | undefined, current: Snapshot): SnapshotComparison => {\n if (recorded === undefined) return { status: 'missing' };\n const changes: { kind: string; lines: string[] }[] = [];\n for (const kind of [...new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {\n const lines: string[] = [];\n if (!(kind in recorded.kinds)) lines.push('+ (a new kind)');\n else if (!(kind in current.kinds)) lines.push('- (the kind is gone)');\n else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), '', lines, 12);\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\n\n// ── the corpus ──────────────────────────────────────────────────\n\nexport type CorpusDocument = { id: string; kind: string; stamp: Stamp; document: unknown };\nexport type CorpusFailure = { id: string; kind: string; reason: string };\nexport type CorpusReport = { passed: number; failures: readonly CorpusFailure[] };\n\nconst issueText = (issue: Issue): string => {\n const path = (issue.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return `${path === '' ? '' : `${path}: `}${issue.message}`;\n};\n\n// What differs between two JSON values, as short lines (`+ a.b`, `- c`,\n// `~ d: 1 → 2`) — for a report a person or an agent acts on.\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', out, limit, sortKeys, false);\n return out;\n};\n\n// Every document, upgraded from its stamp, must pass the current schema of its kind.\nexport const checkCorpus = async (\n upgrader: Upgrader,\n schemas: Readonly<Record<string, GrammarSchema>>,\n documents: readonly CorpusDocument[],\n): Promise<CorpusReport> => {\n const failures: CorpusFailure[] = [];\n let passed = 0;\n for (const doc of documents) {\n const schema = schemas[doc.kind];\n if (schema === undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });\n continue;\n }\n let upgraded: unknown;\n try {\n upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;\n } catch (error) {\n failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split('\\n')[0] ?? error.message : String(error) });\n continue;\n }\n const result = await schema['~standard'].validate(upgraded);\n if (result.issues !== undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join('; ') });\n } else {\n passed += 1;\n }\n }\n return { passed, failures };\n};\n"]}
1
+ {"version":3,"sources":["../src/check/index.ts"],"names":["key"],"mappings":";;;AAyCA,IAAM,QAAA,GAAW,CAAC,KAAA,KAChB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAErE,IAAM,KAAA,GAAQ,CAAC,CAAC,CAAC,CAAA,EAAsB,CAAC,CAAC,CAAA,KAAkC,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAIpG,IAAM,QAAA,GAAW,CAAC,KAAA,KAA4B;AAC5C,EAAA,IAAI,MAAM,OAAA,CAAQ,KAAK,GAAG,OAAO,KAAA,CAAM,IAAI,QAAQ,CAAA;AACnD,EAAA,IAAI,CAAC,QAAA,CAAS,KAAK,CAAA,EAAG,OAAO,KAAA;AAC7B,EAAA,OAAO,MAAA,CAAO,YAAY,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,CAAE,IAAA,CAAK,KAAK,CAAA,CAAE,GAAA,CAAI,CAAC,CAAC,CAAA,EAAG,CAAC,CAAA,KAAM,CAAC,GAAG,QAAA,CAAS,CAAC,CAAC,CAAC,CAAC,CAAA;AAC/F,CAAA;AAKA,IAAM,KAAA,uBAAY,GAAA,CAAI,CAAC,cAAc,mBAAA,EAAqB,OAAA,EAAS,aAAA,EAAe,kBAAkB,CAAC,CAAA;AACrG,IAAM,IAAA,uBAAW,GAAA,CAAI,CAAC,S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AAA,IAAU,CAAA;AAAA,IACZ;AAAA,EACF;AACA,EAAA,OAAO,EAAE,QAAQ,QAAA,EAAS;AAC5B","file":"chunk-4BLHBVSC.js","sourcesContent":["import type { Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/check — the gate a grammar change has to pass.\n//\n// Two questions, both mechanical:\n//\n// 1. SNAPSHOT — did a kind's schema change without the grammar gaining a\n// migration? Each kind's JSON Schema, taken through the schema's OWN\n// Standard JSON Schema hook, is recorded per grammar version. Same version,\n// different schema: something changed that older readers were never told.\n// Append a migration (an empty marker is enough for an addition — strict\n// readers still have to refuse the newer documents), then record the new\n// version.\n//\n// 2. CORPUS — does every real document ever captured, at the stamp it was\n// captured at, still upgrade to the current grammar and pass the current\n// strict schema? This is the judge: a snapshot only says something moved,\n// the corpus says whether old documents survive it. No JSON Schema diff\n// tool is trusted to decide compatibility.\n//\n// Pure: no files, no process. A host reads and writes snapshots where it keeps\n// them (nisc's own live in the repo's `strata/` directory).\n// ═══════════════════════════════════════════════════════════════\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\n// Any validator implementing Standard Schema + Standard JSON Schema (Zod ≥ 4.2,\n// Valibot, ArkType). Structural: strata depends on none of them.\nexport type GrammarSchema = {\n '~standard': {\n validate: (value: unknown) => StandardResult | Promise<StandardResult>;\n jsonSchema: { input: (options: { target: string }) => Record<string, unknown> };\n };\n};\n\nexport type Snapshot = { sequence: string; version: number; kinds: Readonly<Record<string, unknown>> };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Sorted keys, nothing else — for documents, where every key (a `description`\n// too) is content, and for a snapshot file, which keeps what the validator wrote.\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));\n};\n\n// Where a schema's keys are NAMES, not keywords — a field called `description`\n// or an op called `$ref` is grammar — and where its values are instance data\n// rather than schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// A schema without its prose: the `description` KEYWORD is documentation, and\n// rewording a `.describe()` must not demand a migration. `$schema` is the same\n// everywhere. Applied when comparing, never to what is recorded — so what the\n// gate ignores can change without touching a snapshot file.\nconst normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalize);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== 'description' && key !== '$schema')\n .sort(byKey)\n .map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)]),\n );\n};\n\n// A name → schema map, each schema through `each`, the names untouched.\nconst namedSchemas = (map: Record<string, unknown>, each: (schema: unknown) => unknown): Record<string, unknown> =>\n Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));\n\n// The grammar as it stands: every kind it declares, as JSON Schema — as the\n// validator wrote it, keys sorted. `schemas` must cover exactly the sequence's\n// kinds — a kind without a schema cannot be checked, and a schema without a\n// kind belongs to some other grammar.\nexport const snapshotOf = (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>): Snapshot => {\n const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);\n const given = Object.keys(schemas);\n const missing = declared.filter((k) => !given.includes(k));\n const extra = given.filter((k) => !declared.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new StrataError('UNKNOWN_KIND', `The schemas for ${sequence.id} do not match its kinds.`, [\n ...missing.map((k) => `no schema for ${k}`),\n ...extra.map((k) => `${k} is not a kind of ${sequence.id}`),\n ]);\n }\n const kinds: Record<string, unknown> = {};\n for (const kind of [...declared].sort()) {\n const schema = schemas[kind];\n if (schema !== undefined) kinds[kind] = sortKeys(schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }));\n }\n return { sequence: sequence.id, version: sequence.migrations.length, kinds };\n};\n\n// Stable text for a snapshot file: sorted keys, two-space indent, newline.\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\n// Schema arrays are compared as sets (`sets`) — all but a tuple's `prefixItems`,\n// see `diffPositions`; a document's arrays by position — `layout.children[1]` is\n// how a person finds the thing that changed.\nconst diffLines = (a: unknown, b: unknown, path: string, out: string[], limit: number, canon: (v: unknown) => unknown = normalize, sets = true): void => {\n if (out.length >= limit) return;\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (isRecord(a) && isRecord(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const at = path === '' ? key : `${path}.${key}`;\n const before = a[key];\n const after = b[key];\n if (!(key in a)) out.push(`+ ${at}`);\n else if (!(key in b)) out.push(`- ${at}`);\n else if (sets && key === 'prefixItems' && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);\n else diffLines(before, after, at, out, limit, canon, sets);\n if (out.length >= limit) return;\n }\n return;\n }\n if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {\n a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));\n return;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n // Schema arrays are SETS more often than sequences — a union's `anyOf`, a\n // `required` list, an `enum` — and one added branch shifts every index\n // after it. Match elements by what they describe (an object schema by its\n // property names — for Prism's union, the op), report the ones on one side\n // only, and diff the ones that changed in place.\n const text = (v: unknown): string => JSON.stringify(canon(v));\n const label = (v: unknown): string =>\n isRecord(v) && isRecord(v['properties']) ? Object.keys(v['properties']).join(',') : (text(v) ?? '').slice(0, 50);\n const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));\n const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));\n const byLabel = new Map(onlyB.map((y) => [label(y), y]));\n for (const x of onlyA) {\n const partner = byLabel.get(label(x));\n if (partner !== undefined) {\n diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);\n byLabel.delete(label(x));\n } else {\n out.push(`- ${path}[${label(x)}]`);\n }\n if (out.length >= limit) return;\n }\n for (const [name] of byLabel) {\n out.push(`+ ${path}[${name}]`);\n if (out.length >= limit) return;\n }\n return;\n }\n out.push(`~ ${path || '(root)'}: ${JSON.stringify(a)?.slice(0, 60)} → ${JSON.stringify(b)?.slice(0, 60)}`);\n};\n\n// A tuple's `prefixItems` is the one schema array that is a SEQUENCE: position\n// is the grammar, so [string, number] and [number, string] are different tuples\n// and a document valid for one is not for the other. Compared place by place;\n// what sits IN a place is a schema again, its own arrays sets as ever.\nconst diffPositions = (a: readonly unknown[], b: readonly unknown[], path: string, out: string[], limit: number, canon: (v: unknown) => unknown): void => {\n for (let i = 0; i < Math.max(a.length, b.length); i += 1) {\n if (out.length >= limit) return;\n if (i >= a.length) out.push(`+ ${path}[${i}]`);\n else if (i >= b.length) out.push(`- ${path}[${i}]`);\n else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);\n }\n};\n\n// ── canonical form ──────────────────────────────────────────────\n//\n// A snapshot records what the validator WROTE, and validators spell one schema\n// many ways: they name and inline definitions as they please (zod numbers them\n// in visit order, and 4.3 and 4.4 visit differently), write a described\n// reference as `allOf: [{ $ref }]` or as `$ref`, and a union of bare types as\n// `anyOf: [{ type }, …]` or `type: […]`. None of that is the grammar, so a\n// comparison reads both sides in one spelling: every definition inlined unless\n// it is recursive, the recursive ones renamed by first use, and every schema\n// identity above written one way. A snapshot FILE stays what the validator\n// wrote — only the comparison is canonical.\n\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\n// One spelling for the equivalences the node itself can show.\nconst respell = (value: Record<string, unknown>): Record<string, unknown> => {\n let node = value;\n const anyOf = node['anyOf'];\n if (!('type' in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m['type'] === 'string')) {\n const { anyOf: _union, ...rest } = node;\n node = { ...rest, type: anyOf.map((m) => (isRecord(m) ? m['type'] : undefined)) };\n }\n const type = node['type'];\n if (Array.isArray(type)) {\n const types = [...new Set(type.map(String))].sort();\n node = { ...node, type: types.length === 1 ? types[0] : types };\n }\n const allOf = node['allOf'];\n const only: unknown = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : undefined;\n if (!('$ref' in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only['$ref'] === 'string') {\n const { allOf: _wrapper, ...rest } = node;\n node = { ...rest, $ref: only['$ref'] };\n }\n return node;\n};\n\n// A schema node's own children — keyword values, and each schema of a name\n// map — but never the names, and never instance data.\nconst schemaChildren = (node: Record<string, unknown>): unknown[] =>\n Object.entries(node).flatMap(([key, child]) =>\n key === '$ref' || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child],\n );\n\nconst canonical = (recorded: unknown): unknown => {\n const schema = normalize(recorded);\n if (!isRecord(schema)) return schema;\n const defs: Record<string, unknown> = {\n ...(isRecord(schema['definitions']) ? schema['definitions'] : {}),\n ...(isRecord(schema['$defs']) ? schema['$defs'] : {}),\n };\n const { $defs: _defs, definitions: _definitions, ...body } = schema;\n const target = (ref: string): { key: string; node: unknown } =>\n ref === '#' ? { key: '#', node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, '')] };\n\n // Which targets are reached from inside their own expansion: those, and\n // only those, stay definitions.\n const recursive = new Set<string>();\n const findCycles = (value: unknown, stack: readonly string[]): void => {\n if (Array.isArray(value)) {\n for (const item of value) findCycles(item, stack);\n return;\n }\n if (!isRecord(value)) return;\n const node = respell(value);\n for (const child of schemaChildren(node)) findCycles(child, stack);\n const ref = node['$ref'];\n if (typeof ref !== 'string') return;\n const { key, node: next } = target(ref);\n if (stack.includes(key)) recursive.add(key);\n else findCycles(next, [...stack, key]);\n };\n findCycles(body, ['#']);\n\n const names = new Map<string, string>();\n const named: Record<string, unknown> = {};\n const nameOf = (key: string, node: unknown): string => {\n const known = names.get(key);\n if (known !== undefined) return known;\n const name = `d${names.size}`;\n names.set(key, name);\n named[name] = emit(node);\n return name;\n };\n const emit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(emit);\n if (!isRecord(value)) return value;\n const node = respell(value);\n const rest: Record<string, unknown> = Object.fromEntries(\n Object.entries(node)\n .filter(([key]) => key !== '$ref')\n .sort(byKey)\n .map(([key, child]) => [key, NAMED.has(key) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key) ? child : emit(child)]),\n );\n const ref = node['$ref'];\n if (typeof ref !== 'string') return rest;\n const { key, node: next } = target(ref);\n const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);\n return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;\n };\n\n const root = recursive.has('#') ? { $ref: `#/$defs/${nameOf('#', body)}` } : emit(body);\n return Object.keys(named).length === 0 ? root : sortKeys({ ...(isRecord(root) ? root : { allOf: [root] }), $defs: named });\n};\n\nexport type SnapshotComparison =\n | { status: 'same' }\n | { status: 'missing' }\n | { status: 'changed'; changes: readonly { kind: string; lines: readonly string[] }[] };\n\n// `recorded` is the snapshot kept for the grammar's CURRENT version (or\n// undefined if none was kept). Changed means: a migration is owed. Both sides\n// are read in canonical form, so a validator's respelling is not a change.\nexport const compareSnapshot = (recorded: Snapshot | undefined, current: Snapshot): SnapshotComparison => {\n if (recorded === undefined) return { status: 'missing' };\n const changes: { kind: string; lines: string[] }[] = [];\n for (const kind of [...new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {\n const lines: string[] = [];\n if (!(kind in recorded.kinds)) lines.push('+ (a new kind)');\n else if (!(kind in current.kinds)) lines.push('- (the kind is gone)');\n else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), '', lines, 12);\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\n\n// ── the corpus ──────────────────────────────────────────────────\n\nexport type CorpusDocument = { id: string; kind: string; stamp: Stamp; document: unknown };\nexport type CorpusFailure = { id: string; kind: string; reason: string };\nexport type CorpusReport = { passed: number; failures: readonly CorpusFailure[] };\n\nconst issueText = (issue: Issue): string => {\n const path = (issue.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return `${path === '' ? '' : `${path}: `}${issue.message}`;\n};\n\n// What differs between two JSON values, as short lines (`+ a.b`, `- c`,\n// `~ d: 1 → 2`) — for a report a person or an agent acts on.\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', out, limit, sortKeys, false);\n return out;\n};\n\n// Every document, upgraded from its stamp, must pass the current schema of its kind.\nexport const checkCorpus = async (\n upgrader: Upgrader,\n schemas: Readonly<Record<string, GrammarSchema>>,\n documents: readonly CorpusDocument[],\n): Promise<CorpusReport> => {\n const failures: CorpusFailure[] = [];\n let passed = 0;\n for (const doc of documents) {\n const schema = schemas[doc.kind];\n if (schema === undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });\n continue;\n }\n let upgraded: unknown;\n try {\n upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;\n } catch (error) {\n failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split('\\n')[0] ?? error.message : String(error) });\n continue;\n }\n const result = await schema['~standard'].validate(upgraded);\n if (result.issues !== undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join('; ') });\n } else {\n passed += 1;\n }\n }\n return { passed, failures };\n};\n"]}
@@ -1,4 +1,4 @@
1
- import { StrataError } from './chunk-EGFF63GA.js';
1
+ import { StrataError } from './chunk-AKKWEXO2.js';
2
2
  import { z } from 'zod';
3
3
 
4
4
  var SEQUENCE_ID = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
@@ -171,5 +171,5 @@ var refuseProblems = (plan) => {
171
171
  };
172
172
 
173
173
  export { DocumentKindSchema, DocumentStepSchema, EMBED_PATH, KIND_NAME, KIND_REF, MIGRATION_REF, MigrationSchema, SEQUENCE_ID, SequenceSchema, SqlStepSchema, StepSchema, checksumOf, orderPending, planMigrations, prepare, refuseProblems };
174
- //# sourceMappingURL=chunk-U5CPF4LQ.js.map
175
- //# sourceMappingURL=chunk-U5CPF4LQ.js.map
174
+ //# sourceMappingURL=chunk-5KTXEN43.js.map
175
+ //# sourceMappingURL=chunk-5KTXEN43.js.map