@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.
- package/CHANGELOG.md +56 -0
- package/README.md +2 -2
- package/dist/check/index.cjs +23 -228
- package/dist/check/index.cjs.map +1 -1
- package/dist/check/index.js +2 -2
- package/dist/{chunk-274M232S.js → chunk-4BLHBVSC.js} +3 -3
- package/dist/{chunk-274M232S.js.map → chunk-4BLHBVSC.js.map} +1 -1
- package/dist/{chunk-U5CPF4LQ.js → chunk-5KTXEN43.js} +3 -3
- package/dist/{chunk-U5CPF4LQ.js.map → chunk-5KTXEN43.js.map} +1 -1
- package/dist/{chunk-EGFF63GA.js → chunk-AKKWEXO2.js} +2 -2
- package/dist/{chunk-EGFF63GA.js.map → chunk-AKKWEXO2.js.map} +1 -1
- package/dist/chunk-ATHZ7HT5.cjs +18 -0
- package/dist/chunk-ATHZ7HT5.cjs.map +1 -0
- package/dist/chunk-CL5DF2IQ.cjs +192 -0
- package/dist/chunk-CL5DF2IQ.cjs.map +1 -0
- package/dist/chunk-IHYBGLNW.cjs +161 -0
- package/dist/chunk-IHYBGLNW.cjs.map +1 -0
- package/dist/chunk-KNBS3AJZ.cjs +223 -0
- package/dist/chunk-KNBS3AJZ.cjs.map +1 -0
- package/dist/{chunk-TWAEZHTB.js → chunk-OLDORFOQ.js} +4 -4
- package/dist/{chunk-TWAEZHTB.js.map → chunk-OLDORFOQ.js.map} +1 -1
- package/dist/{chunk-2FIZEJXW.js → chunk-WU3OJHVZ.js} +4 -4
- package/dist/{chunk-2FIZEJXW.js.map → chunk-WU3OJHVZ.js.map} +1 -1
- package/dist/chunk-YXFEJJMC.cjs +136 -0
- package/dist/chunk-YXFEJJMC.cjs.map +1 -0
- package/dist/index.cjs +75 -330
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/node/index.cjs +14 -493
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.js +5 -5
- package/dist/{plan-BEIlXVUt.d.cts → plan-CxuteSH1.d.cts} +2 -2
- package/dist/{plan-BAewc8DG.d.ts → plan-mFmdh0qT.d.ts} +2 -2
- package/dist/postgres/index.cjs +30 -198
- package/dist/postgres/index.cjs.map +1 -1
- package/dist/postgres/index.d.cts +7 -2
- package/dist/postgres/index.d.ts +7 -2
- package/dist/postgres/index.js +17 -3
- package/dist/postgres/index.js.map +1 -1
- package/dist/upgrade/index.cjs +19 -240
- package/dist/upgrade/index.cjs.map +1 -1
- package/dist/upgrade/index.js +3 -3
- package/package.json +1 -1
package/dist/node/index.cjs
CHANGED
|
@@ -1,493 +1,14 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var chunkYXFEJJMC_cjs = require('../chunk-YXFEJJMC.cjs');
|
|
4
|
+
require('../chunk-CL5DF2IQ.cjs');
|
|
5
|
+
var chunkIHYBGLNW_cjs = require('../chunk-IHYBGLNW.cjs');
|
|
6
|
+
require('../chunk-KNBS3AJZ.cjs');
|
|
7
|
+
var chunkATHZ7HT5_cjs = require('../chunk-ATHZ7HT5.cjs');
|
|
3
8
|
var fs = require('fs');
|
|
4
9
|
var path = require('path');
|
|
5
|
-
var zod = require('zod');
|
|
6
10
|
|
|
7
|
-
// src/node/index.ts
|
|
8
|
-
var SEQUENCE_ID = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
|
|
9
|
-
var MIGRATION_REF = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+\/[1-9][0-9]*$/;
|
|
10
|
-
var KIND_NAME = /^[a-z][a-z0-9-]*$/;
|
|
11
|
-
var KIND_REF = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+\/[a-z][a-z0-9-]*$/;
|
|
12
|
-
var EMBED_PATH = /^([A-Za-z_$][\w$]*|\*)(\[\])?(\.([A-Za-z_$][\w$]*|\*)(\[\])?)*$/;
|
|
13
|
-
var SqlStepSchema = zod.z.object({
|
|
14
|
-
kind: zod.z.literal("sql"),
|
|
15
|
-
sql: zod.z.string().min(1).describe(
|
|
16
|
-
"ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string carrying several \u2014 split them into steps rather than joining them with semicolons."
|
|
17
|
-
)
|
|
18
|
-
}).strict().describe("A statement run against the database, inside the migration transaction.");
|
|
19
|
-
var DocumentStepSchema = zod.z.object({
|
|
20
|
-
kind: zod.z.literal("document"),
|
|
21
|
-
at: zod.z.string().regex(KIND_REF).describe('The kind of document this step rewrites, e.g. "nisc.nova/layout" \u2014 wherever one sits, at any depth.'),
|
|
22
|
-
transform: zod.z.unknown().describe(
|
|
23
|
-
"A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the grammar's embeddings and rewritten on their own, deepest first \u2014 a transform only ever sees one flat node."
|
|
24
|
-
)
|
|
25
|
-
}).strict().describe("A rewrite of stored JSON documents of one kind.");
|
|
26
|
-
var StepSchema = zod.z.discriminatedUnion("kind", [SqlStepSchema, DocumentStepSchema]);
|
|
27
|
-
var DocumentKindSchema = zod.z.object({
|
|
28
|
-
embeds: zod.z.record(zod.z.string().regex(EMBED_PATH), zod.z.string().regex(KIND_REF)).optional().describe("Where other documents sit inside this one: path \u2192 the kind found there (possibly this kind itself).")
|
|
29
|
-
}).strict();
|
|
30
|
-
var MigrationSchema = zod.z.object({
|
|
31
|
-
description: zod.z.string().min(1).describe("One sentence: what this migration does. It is the changelog line and the ledger's description."),
|
|
32
|
-
steps: zod.z.array(StepSchema).describe(
|
|
33
|
-
"Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: the version moves and nothing runs \u2014 how an addition to a strict grammar tells older readers to refuse."
|
|
34
|
-
),
|
|
35
|
-
dependsOn: zod.z.array(zod.z.string().regex(MIGRATION_REF)).optional().describe('Migrations of OTHER sequences that must be applied first, each as "<sequence>/<n>".')
|
|
36
|
-
}).strict();
|
|
37
|
-
var SequenceSchema = zod.z.object({
|
|
38
|
-
id: zod.z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. "nisc.vex.cache" or "midas.app".'),
|
|
39
|
-
documents: zod.z.record(zod.z.string().regex(KIND_NAME), DocumentKindSchema).optional().describe('The document kinds this sequence owns (a GRAMMAR sequence), each named "<id>/<kind>" elsewhere.'),
|
|
40
|
-
migrations: zod.z.array(MigrationSchema).describe("Append-only. A migration is numbered by its position (from 1); the sequence's version is its length.")
|
|
41
|
-
}).strict().superRefine((sequence, ctx) => {
|
|
42
|
-
const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));
|
|
43
|
-
if (kinds.has("sql") && (kinds.has("document") || sequence.documents !== void 0)) {
|
|
44
|
-
ctx.addIssue({
|
|
45
|
-
code: "custom",
|
|
46
|
-
message: "A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both."
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
// src/checksum.ts
|
|
52
|
-
var canonical = (value) => {
|
|
53
|
-
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
54
|
-
if (value !== null && typeof value === "object") {
|
|
55
|
-
const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
56
|
-
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
57
|
-
}
|
|
58
|
-
return JSON.stringify(value);
|
|
59
|
-
};
|
|
60
|
-
var effectOf = (sql) => sql.split("\n").filter((line) => !line.trimStart().startsWith("--")).map((line) => line.trimEnd()).join("\n").trim();
|
|
61
|
-
var checksumOf = async (migration) => {
|
|
62
|
-
const steps = migration.steps.map((step) => step.kind === "sql" ? { ...step, sql: effectOf(step.sql) } : step);
|
|
63
|
-
const bytes = new TextEncoder().encode(canonical(steps));
|
|
64
|
-
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
65
|
-
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
// src/errors.ts
|
|
69
|
-
var StrataError = class extends Error {
|
|
70
|
-
code;
|
|
71
|
-
details;
|
|
72
|
-
constructor(code, message, details = [], options) {
|
|
73
|
-
super(details.length > 0 ? `${message}
|
|
74
|
-
${details.map((d) => ` ${d}`).join("\n")}` : message, options);
|
|
75
|
-
this.name = "StrataError";
|
|
76
|
-
this.code = code;
|
|
77
|
-
this.details = details;
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
// src/plan.ts
|
|
82
|
-
var refOf = (sequence, n) => `${sequence}/${n}`;
|
|
83
|
-
var prepare = async (sequences) => {
|
|
84
|
-
const seen = /* @__PURE__ */ new Set();
|
|
85
|
-
const prepared = [];
|
|
86
|
-
for (const input of sequences) {
|
|
87
|
-
const parsed = SequenceSchema.safeParse(input);
|
|
88
|
-
if (!parsed.success) {
|
|
89
|
-
const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);
|
|
90
|
-
throw new StrataError("INVALID_SEQUENCE", `A sequence does not parse${typeof input.id === "string" ? ` ("${input.id}")` : ""}.`, issues);
|
|
91
|
-
}
|
|
92
|
-
const sequence = parsed.data;
|
|
93
|
-
if (seen.has(sequence.id)) {
|
|
94
|
-
throw new StrataError("INVALID_SEQUENCE", `Two sequences are both called "${sequence.id}" \u2014 a sequence id names one owner.`);
|
|
95
|
-
}
|
|
96
|
-
seen.add(sequence.id);
|
|
97
|
-
const migrations = [];
|
|
98
|
-
for (const [index, migration] of sequence.migrations.entries()) {
|
|
99
|
-
const n = index + 1;
|
|
100
|
-
migrations.push({
|
|
101
|
-
sequence: sequence.id,
|
|
102
|
-
n,
|
|
103
|
-
ref: refOf(sequence.id, n),
|
|
104
|
-
description: migration.description,
|
|
105
|
-
checksum: await checksumOf(migration),
|
|
106
|
-
steps: migration.steps,
|
|
107
|
-
dependsOn: migration.dependsOn ?? []
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
const grammar = sequence.documents !== void 0 || sequence.migrations.some((m) => m.steps.some((s) => s.kind === "document"));
|
|
111
|
-
prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });
|
|
112
|
-
}
|
|
113
|
-
return prepared;
|
|
114
|
-
};
|
|
115
|
-
var orderPending = (queues, alreadyDone) => {
|
|
116
|
-
const done = new Set(alreadyDone);
|
|
117
|
-
const waiting = queues.map((q) => [...q.waiting]);
|
|
118
|
-
const pending = [];
|
|
119
|
-
let moved = true;
|
|
120
|
-
while (moved) {
|
|
121
|
-
moved = false;
|
|
122
|
-
for (const queue of waiting) {
|
|
123
|
-
for (let head = queue[0]; head !== void 0; head = queue[0]) {
|
|
124
|
-
if (!head.dependsOn.every((d) => done.has(d))) break;
|
|
125
|
-
pending.push(head);
|
|
126
|
-
done.add(head.ref);
|
|
127
|
-
queue.shift();
|
|
128
|
-
moved = true;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
return { pending, stuck: waiting.flat() };
|
|
133
|
-
};
|
|
134
|
-
|
|
135
|
-
// src/documents.ts
|
|
136
11
|
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
137
|
-
var pathText = (path) => path.reduce((text, key) => typeof key === "number" ? `${text}[${key}]` : text === "" ? key : `${text}.${key}`, "");
|
|
138
|
-
var reach = (value, pattern) => {
|
|
139
|
-
let frontier = [{ path: [], value }];
|
|
140
|
-
for (const segment of pattern.split(".")) {
|
|
141
|
-
const array = segment.endsWith("[]");
|
|
142
|
-
const key = array ? segment.slice(0, -2) : segment;
|
|
143
|
-
const next = [];
|
|
144
|
-
for (const at of frontier) {
|
|
145
|
-
if (!isRecord(at.value)) continue;
|
|
146
|
-
const found = key === "*" ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v })) : key in at.value ? [{ path: [...at.path, key], value: at.value[key] }] : [];
|
|
147
|
-
for (const f of found) {
|
|
148
|
-
if (!array) next.push(f);
|
|
149
|
-
else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
frontier = next;
|
|
153
|
-
}
|
|
154
|
-
return frontier;
|
|
155
|
-
};
|
|
156
|
-
var getAt = (root, path) => path.reduce((at, key) => {
|
|
157
|
-
if (typeof key === "number") return Array.isArray(at) ? at[key] : void 0;
|
|
158
|
-
return isRecord(at) ? at[key] : void 0;
|
|
159
|
-
}, root);
|
|
160
|
-
var setAt = (root, path, value) => {
|
|
161
|
-
const [head, ...rest] = path;
|
|
162
|
-
if (head === void 0) return value;
|
|
163
|
-
if (typeof head === "number" && Array.isArray(root)) return root.map((item, i) => i === head ? setAt(item, rest, value) : item);
|
|
164
|
-
if (typeof head === "string" && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };
|
|
165
|
-
return root;
|
|
166
|
-
};
|
|
167
|
-
var createUpgrader = async (sequences, options) => {
|
|
168
|
-
const prepared = await prepare(sequences);
|
|
169
|
-
const tables = prepared.filter((s) => !s.grammar);
|
|
170
|
-
if (tables.length > 0) {
|
|
171
|
-
throw new StrataError(
|
|
172
|
-
"WRONG_OWNER",
|
|
173
|
-
"Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`). If one of them is a grammar, declare its `documents` \u2014 a sequence with no `documents` and no document step is read as owning tables.",
|
|
174
|
-
tables.map((s) => s.id)
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
const grammars = prepared;
|
|
178
|
-
const kinds = /* @__PURE__ */ new Map();
|
|
179
|
-
for (const sequence of grammars) {
|
|
180
|
-
for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);
|
|
181
|
-
}
|
|
182
|
-
const unknown = [
|
|
183
|
-
...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => step.kind === "document" && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : []))),
|
|
184
|
-
...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))
|
|
185
|
-
];
|
|
186
|
-
if (unknown.length > 0) throw new StrataError("UNKNOWN_KIND", "A document kind is named that no sequence declares.", unknown);
|
|
187
|
-
const stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));
|
|
188
|
-
const ownIds = new Set(grammars.map((s) => s.id));
|
|
189
|
-
const stampAfter = (given) => {
|
|
190
|
-
const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));
|
|
191
|
-
return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };
|
|
192
|
-
};
|
|
193
|
-
const locate = (document, kind) => {
|
|
194
|
-
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
195
|
-
const found = [];
|
|
196
|
-
const visit = (value, at, path) => {
|
|
197
|
-
if (!isRecord(value)) return;
|
|
198
|
-
found.push({ path, kind: at, value });
|
|
199
|
-
for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {
|
|
200
|
-
for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);
|
|
201
|
-
}
|
|
202
|
-
};
|
|
203
|
-
visit(document, kind, []);
|
|
204
|
-
return found;
|
|
205
|
-
};
|
|
206
|
-
const positionOf = (given, id) => given?.[id] ?? 0;
|
|
207
|
-
const behind = (given) => {
|
|
208
|
-
const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);
|
|
209
|
-
if (ahead.length > 0) {
|
|
210
|
-
throw new StrataError(
|
|
211
|
-
"TOO_NEW",
|
|
212
|
-
"This document was written by newer code than this \u2014 reading it would be guessing.",
|
|
213
|
-
ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`)
|
|
214
|
-
);
|
|
215
|
-
}
|
|
216
|
-
return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);
|
|
217
|
-
};
|
|
218
|
-
const upgrade = (document, { kind, stamp: given }) => {
|
|
219
|
-
if (!isRecord(document)) throw new StrataError("STEP_FAILED", `A ${kind} document must be a JSON object.`);
|
|
220
|
-
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
221
|
-
if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };
|
|
222
|
-
const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));
|
|
223
|
-
const { pending, stuck } = orderPending(
|
|
224
|
-
grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),
|
|
225
|
-
done
|
|
226
|
-
);
|
|
227
|
-
if (stuck.length > 0) throw new StrataError("CYCLE", "Document migrations wait on each other and can never run.", stuck.map((m) => m.ref));
|
|
228
|
-
let current = document;
|
|
229
|
-
const applied = [];
|
|
230
|
-
const runStep = (migration, at, transform) => {
|
|
231
|
-
const targets = locate(current, kind).filter((l) => l.kind === at).sort((a, b) => b.path.length - a.path.length);
|
|
232
|
-
for (const target of targets) {
|
|
233
|
-
const value = getAt(current, target.path);
|
|
234
|
-
let rewritten;
|
|
235
|
-
try {
|
|
236
|
-
rewritten = options.transform(transform, { document: value, path: pathText(target.path) });
|
|
237
|
-
} catch (cause) {
|
|
238
|
-
throw new StrataError(
|
|
239
|
-
"STEP_FAILED",
|
|
240
|
-
`${migration.ref} ("${migration.description}") failed on the ${at} at ${pathText(target.path) || "(root)"}.`,
|
|
241
|
-
[cause instanceof Error ? cause.message : String(cause)],
|
|
242
|
-
{ cause }
|
|
243
|
-
);
|
|
244
|
-
}
|
|
245
|
-
if (!isRecord(rewritten)) {
|
|
246
|
-
throw new StrataError("STEP_FAILED", `${migration.ref} turned the ${at} at ${pathText(target.path) || "(root)"} into something that is not a document.`, [
|
|
247
|
-
JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten)
|
|
248
|
-
]);
|
|
249
|
-
}
|
|
250
|
-
const next = setAt(current, target.path, rewritten);
|
|
251
|
-
if (isRecord(next)) current = next;
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
for (const migration of pending) {
|
|
255
|
-
for (const step of migration.steps) if (step.kind === "document") runStep(migration, step.at, step.transform);
|
|
256
|
-
applied.push(migration.ref);
|
|
257
|
-
}
|
|
258
|
-
return { document: current, stamp: stampAfter(given), applied };
|
|
259
|
-
};
|
|
260
|
-
return { stamp, upgrade, locate, behind };
|
|
261
|
-
};
|
|
262
|
-
|
|
263
|
-
// src/check/index.ts
|
|
264
|
-
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
265
|
-
var byKey = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
|
|
266
|
-
var sortKeys = (value) => {
|
|
267
|
-
if (Array.isArray(value)) return value.map(sortKeys);
|
|
268
|
-
if (!isRecord2(value)) return value;
|
|
269
|
-
return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));
|
|
270
|
-
};
|
|
271
|
-
var NAMED = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
|
|
272
|
-
var DATA = /* @__PURE__ */ new Set(["const", "enum", "default", "examples"]);
|
|
273
|
-
var normalize = (value) => {
|
|
274
|
-
if (Array.isArray(value)) return value.map(normalize);
|
|
275
|
-
if (!isRecord2(value)) return value;
|
|
276
|
-
return Object.fromEntries(
|
|
277
|
-
Object.entries(value).filter(([key]) => key !== "description" && key !== "$schema").sort(byKey).map(([key, v]) => [key, NAMED.has(key) && isRecord2(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)])
|
|
278
|
-
);
|
|
279
|
-
};
|
|
280
|
-
var namedSchemas = (map, each) => Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));
|
|
281
|
-
var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
|
|
282
|
-
if (out.length >= limit) return;
|
|
283
|
-
if (JSON.stringify(a) === JSON.stringify(b)) return;
|
|
284
|
-
if (isRecord2(a) && isRecord2(b)) {
|
|
285
|
-
for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
|
|
286
|
-
const at = path === "" ? key : `${path}.${key}`;
|
|
287
|
-
const before = a[key];
|
|
288
|
-
const after = b[key];
|
|
289
|
-
if (!(key in a)) out.push(`+ ${at}`);
|
|
290
|
-
else if (!(key in b)) out.push(`- ${at}`);
|
|
291
|
-
else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);
|
|
292
|
-
else diffLines(before, after, at, out, limit, canon, sets);
|
|
293
|
-
if (out.length >= limit) return;
|
|
294
|
-
}
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {
|
|
298
|
-
a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));
|
|
299
|
-
return;
|
|
300
|
-
}
|
|
301
|
-
if (Array.isArray(a) && Array.isArray(b)) {
|
|
302
|
-
const text = (v) => JSON.stringify(canon(v));
|
|
303
|
-
const label = (v) => isRecord2(v) && isRecord2(v["properties"]) ? Object.keys(v["properties"]).join(",") : (text(v) ?? "").slice(0, 50);
|
|
304
|
-
const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));
|
|
305
|
-
const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));
|
|
306
|
-
const byLabel = new Map(onlyB.map((y) => [label(y), y]));
|
|
307
|
-
for (const x of onlyA) {
|
|
308
|
-
const partner = byLabel.get(label(x));
|
|
309
|
-
if (partner !== void 0) {
|
|
310
|
-
diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);
|
|
311
|
-
byLabel.delete(label(x));
|
|
312
|
-
} else {
|
|
313
|
-
out.push(`- ${path}[${label(x)}]`);
|
|
314
|
-
}
|
|
315
|
-
if (out.length >= limit) return;
|
|
316
|
-
}
|
|
317
|
-
for (const [name] of byLabel) {
|
|
318
|
-
out.push(`+ ${path}[${name}]`);
|
|
319
|
-
if (out.length >= limit) return;
|
|
320
|
-
}
|
|
321
|
-
return;
|
|
322
|
-
}
|
|
323
|
-
out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
|
|
324
|
-
};
|
|
325
|
-
var diffPositions = (a, b, path, out, limit, canon) => {
|
|
326
|
-
for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
|
|
327
|
-
if (out.length >= limit) return;
|
|
328
|
-
if (i >= a.length) out.push(`+ ${path}[${i}]`);
|
|
329
|
-
else if (i >= b.length) out.push(`- ${path}[${i}]`);
|
|
330
|
-
else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);
|
|
331
|
-
}
|
|
332
|
-
};
|
|
333
|
-
var diffJson = (a, b, limit = 20) => {
|
|
334
|
-
const out = [];
|
|
335
|
-
diffLines(a, b, "", out, limit, sortKeys, false);
|
|
336
|
-
return out;
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
// src/upgrade/index.ts
|
|
340
|
-
var keyOf = (doc) => `${doc.kind}:${doc.id}`;
|
|
341
|
-
var sortKeys2 = (value) => {
|
|
342
|
-
if (Array.isArray(value)) return value.map(sortKeys2);
|
|
343
|
-
if (typeof value !== "object" || value === null) return value;
|
|
344
|
-
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, sortKeys2(v)]));
|
|
345
|
-
};
|
|
346
|
-
var sameJson = (a, b) => JSON.stringify(sortKeys2(a)) === JSON.stringify(sortKeys2(b));
|
|
347
|
-
var changedStrings = (before, after) => {
|
|
348
|
-
const found = /* @__PURE__ */ new Set();
|
|
349
|
-
const visit = (a, b) => {
|
|
350
|
-
if (JSON.stringify(a) === JSON.stringify(b)) return;
|
|
351
|
-
if (typeof a === "string") {
|
|
352
|
-
found.add(a);
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
if (Array.isArray(a)) {
|
|
356
|
-
a.forEach((item, i) => visit(item, Array.isArray(b) ? b[i] : void 0));
|
|
357
|
-
return;
|
|
358
|
-
}
|
|
359
|
-
if (typeof a === "object" && a !== null) {
|
|
360
|
-
for (const [k, v] of Object.entries(a)) visit(v, typeof b === "object" && b !== null && !Array.isArray(b) ? Reflect.get(b, k) : void 0);
|
|
361
|
-
}
|
|
362
|
-
};
|
|
363
|
-
visit(before, after);
|
|
364
|
-
return [...found].filter((s) => s.length >= 4);
|
|
365
|
-
};
|
|
366
|
-
var planSourceUpgrade = async (options) => {
|
|
367
|
-
const { upgrader, stamp, documents, schemas, describe } = options;
|
|
368
|
-
const seen = /* @__PURE__ */ new Set();
|
|
369
|
-
const planned = [];
|
|
370
|
-
const untouched = [];
|
|
371
|
-
const problems = [];
|
|
372
|
-
for (const doc of documents) {
|
|
373
|
-
const key = keyOf(doc);
|
|
374
|
-
if (seen.has(key)) throw new StrataError("INVALID_SEQUENCE", `Two artifacts are both ${key} \u2014 an artifact needs one identity to be planned.`);
|
|
375
|
-
seen.add(key);
|
|
376
|
-
const result = upgrader.upgrade(doc.document, { kind: doc.kind, stamp });
|
|
377
|
-
if (sameJson(result.document, doc.document)) {
|
|
378
|
-
untouched.push(key);
|
|
379
|
-
continue;
|
|
380
|
-
}
|
|
381
|
-
planned.push({
|
|
382
|
-
kind: doc.kind,
|
|
383
|
-
id: doc.id,
|
|
384
|
-
...doc.file === void 0 ? {} : { file: doc.file },
|
|
385
|
-
applied: result.applied,
|
|
386
|
-
changes: diffJson(doc.document, result.document),
|
|
387
|
-
expected: result.document
|
|
388
|
-
});
|
|
389
|
-
const schema = schemas?.[doc.kind];
|
|
390
|
-
if (schema !== void 0) {
|
|
391
|
-
const checked = await schema["~standard"].validate(result.document);
|
|
392
|
-
if (checked.issues !== void 0) {
|
|
393
|
-
problems.push(`${key}: the migrated artifact does not pass ${doc.kind}'s current schema \u2014 ${checked.issues.slice(0, 2).map((i) => i.message).join("; ")}`);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
const from = stamp;
|
|
398
|
-
const to = upgrader.stamp;
|
|
399
|
-
const migrations = Object.entries(to).flatMap(
|
|
400
|
-
([id, n]) => Array.from({ length: Math.max(0, n - (from[id] ?? 0)) }, (_, i) => `${id}/${(from[id] ?? 0) + i + 1}`)
|
|
401
|
-
);
|
|
402
|
-
return {
|
|
403
|
-
from,
|
|
404
|
-
to,
|
|
405
|
-
migrations: migrations.map((ref) => ({ ref, description: describe(ref) })),
|
|
406
|
-
documents: planned.sort((a, b) => keyOf(a) < keyOf(b) ? -1 : 1),
|
|
407
|
-
untouched: untouched.sort(),
|
|
408
|
-
problems
|
|
409
|
-
};
|
|
410
|
-
};
|
|
411
|
-
var verifySourceUpgrade = (options) => {
|
|
412
|
-
const { plan, upgrader, documents } = options;
|
|
413
|
-
const now = new Map(documents.map((d) => [keyOf(d), d]));
|
|
414
|
-
const lines = [];
|
|
415
|
-
for (const want of plan.documents) {
|
|
416
|
-
const key = keyOf(want);
|
|
417
|
-
const got = now.get(key);
|
|
418
|
-
if (got === void 0) {
|
|
419
|
-
lines.push({ ok: false, text: `${key} is gone \u2014 the plan expected it rewritten, not removed` });
|
|
420
|
-
} else if (sameJson(got.document, want.expected)) {
|
|
421
|
-
lines.push({ ok: true, text: `${key} matches its migrated JSON` });
|
|
422
|
-
} else {
|
|
423
|
-
lines.push({ ok: false, text: `${key} does not match its migrated JSON yet`, detail: diffJson(got.document, want.expected, 12) });
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
for (const key of plan.untouched) {
|
|
427
|
-
const got = now.get(key);
|
|
428
|
-
if (got === void 0) {
|
|
429
|
-
lines.push({ ok: false, text: `${key} is gone \u2014 no migration asked for that` });
|
|
430
|
-
continue;
|
|
431
|
-
}
|
|
432
|
-
const again = upgrader.upgrade(got.document, { kind: got.kind, stamp: plan.from });
|
|
433
|
-
if (!sameJson(again.document, got.document)) {
|
|
434
|
-
lines.push({ ok: false, text: `${key} was not in the plan, but the migrations would change it now`, detail: diffJson(got.document, again.document, 12) });
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
const known = /* @__PURE__ */ new Set([...plan.documents.map(keyOf), ...plan.untouched]);
|
|
438
|
-
for (const key of now.keys()) {
|
|
439
|
-
if (!known.has(key)) lines.push({ ok: false, text: `${key} is new since the plan \u2014 plan again so it is checked too` });
|
|
440
|
-
}
|
|
441
|
-
const ok = lines.every((l) => l.ok);
|
|
442
|
-
if (ok) lines.push({ ok: true, text: `${plan.untouched.length} artifact(s) no migration touches, still untouched` });
|
|
443
|
-
return { ok, lines };
|
|
444
|
-
};
|
|
445
|
-
var renderReport = (plan, expectedPathOf) => {
|
|
446
|
-
const stamp = (s) => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(", ");
|
|
447
|
-
const out = [
|
|
448
|
-
"# strata upgrade",
|
|
449
|
-
"",
|
|
450
|
-
`The source is written at **${stamp(plan.from)}**; the installed grammars are at **${stamp(plan.to)}**.`,
|
|
451
|
-
"",
|
|
452
|
-
"## Migrations",
|
|
453
|
-
"",
|
|
454
|
-
...plan.migrations.map((m) => `- \`${m.ref}\` \u2014 ${m.description}`),
|
|
455
|
-
""
|
|
456
|
-
];
|
|
457
|
-
if (plan.problems.length > 0) {
|
|
458
|
-
out.push("## Stop: a migration is wrong", "", "These artifacts would not pass their current schema after migrating \u2014 no edit can make `verify` pass. Fix the migration, then plan again.", "", ...plan.problems.map((p) => `- ${p}`), "");
|
|
459
|
-
}
|
|
460
|
-
if (plan.documents.length === 0) {
|
|
461
|
-
out.push("## Nothing to edit", "", `No artifact changes (${plan.untouched.length} checked). Run \`verify\` to move the lock.`, "");
|
|
462
|
-
} else {
|
|
463
|
-
out.push(
|
|
464
|
-
`## ${plan.documents.length} artifact(s) to edit`,
|
|
465
|
-
"",
|
|
466
|
-
"Edit each so that it serialises to EXACTLY its expected JSON (key order aside) \u2014 then run `verify`. Only what is listed changes; every other artifact must stay as it is.",
|
|
467
|
-
""
|
|
468
|
-
);
|
|
469
|
-
for (const doc of plan.documents) {
|
|
470
|
-
out.push(
|
|
471
|
-
`### \`${doc.id}\` (${doc.kind})`,
|
|
472
|
-
"",
|
|
473
|
-
doc.file === void 0 ? "" : `- **File:** \`${doc.file}\``,
|
|
474
|
-
doc.lookIn === void 0 || doc.lookIn.length === 0 ? "" : `- **Look in:** ${doc.lookIn.map((f) => `\`${f}\``).join(", ")} \u2014 where the changing values are written`,
|
|
475
|
-
`- **Migrations:** ${doc.applied.map((r) => `\`${r}\``).join(", ")}`,
|
|
476
|
-
`- **Expected JSON:** \`${expectedPathOf(doc)}\``,
|
|
477
|
-
"- **Changes:**",
|
|
478
|
-
"",
|
|
479
|
-
"```",
|
|
480
|
-
...doc.changes,
|
|
481
|
-
"```",
|
|
482
|
-
""
|
|
483
|
-
);
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
return out.filter((line, i, all) => !(line === "" && all[i - 1] === "")).join("\n");
|
|
487
|
-
};
|
|
488
|
-
|
|
489
|
-
// src/node/index.ts
|
|
490
|
-
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
491
12
|
var stampText = (s) => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(", ") || "(nothing)";
|
|
492
13
|
var filesUnder = (dir) => fs.existsSync(dir) ? fs.readdirSync(dir).flatMap((name) => {
|
|
493
14
|
const path$1 = path.join(dir, name);
|
|
@@ -500,12 +21,12 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
500
21
|
const lockPath = path.join(options.root, options.lock ?? "strata.lock.json");
|
|
501
22
|
const work = path.join(options.root, options.workDir ?? path.join(".strata", "upgrade"));
|
|
502
23
|
const rel = (path$1) => path.relative(options.root, path$1).split(path.sep).join("/");
|
|
503
|
-
const upgrader = await createUpgrader(options.grammars, { transform: options.transform });
|
|
24
|
+
const upgrader = await chunkYXFEJJMC_cjs.createUpgrader(options.grammars, { transform: options.transform });
|
|
504
25
|
const descriptions = new Map(options.grammars.flatMap((g) => g.migrations.map((m, i) => [`${g.id}/${i + 1}`, m.description])));
|
|
505
26
|
const readLock = () => {
|
|
506
27
|
if (!fs.existsSync(lockPath)) return void 0;
|
|
507
28
|
const raw = JSON.parse(fs.readFileSync(lockPath, "utf8"));
|
|
508
|
-
if (!
|
|
29
|
+
if (!isRecord(raw) || !isRecord(raw["grammar"])) throw new chunkATHZ7HT5_cjs.StrataError("INVALID_SEQUENCE", `${rel(lockPath)} is not a lock: expected { "grammar": { \u2026 } }.`);
|
|
509
30
|
return Object.fromEntries(Object.entries(raw["grammar"]).map(([k, v]) => [k, Number(v)]));
|
|
510
31
|
};
|
|
511
32
|
const writeLock = (stamp) => fs.writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => a < b ? -1 : 1)) }, null, 2)}
|
|
@@ -562,7 +83,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
562
83
|
return 0;
|
|
563
84
|
}
|
|
564
85
|
const documents = await loadDocuments();
|
|
565
|
-
const drafted = await planSourceUpgrade({
|
|
86
|
+
const drafted = await chunkIHYBGLNW_cjs.planSourceUpgrade({
|
|
566
87
|
upgrader,
|
|
567
88
|
stamp: lock,
|
|
568
89
|
documents,
|
|
@@ -570,11 +91,11 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
570
91
|
describe: (ref) => descriptions.get(ref) ?? "(no description)"
|
|
571
92
|
});
|
|
572
93
|
const text = sourceText();
|
|
573
|
-
const
|
|
94
|
+
const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));
|
|
574
95
|
const plan = {
|
|
575
96
|
...drafted,
|
|
576
97
|
documents: drafted.documents.map((doc) => {
|
|
577
|
-
const needles = changedStrings(
|
|
98
|
+
const needles = chunkIHYBGLNW_cjs.changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `"${s}"`]);
|
|
578
99
|
const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));
|
|
579
100
|
return { ...doc, lookIn };
|
|
580
101
|
})
|
|
@@ -590,7 +111,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
590
111
|
}
|
|
591
112
|
fs.writeFileSync(path.join(work, "plan.json"), `${JSON.stringify(plan, null, 2)}
|
|
592
113
|
`);
|
|
593
|
-
fs.writeFileSync(path.join(work, "REPORT.md"), `${renderReport(plan, (d) => rel(expectedPathOf(d)))}
|
|
114
|
+
fs.writeFileSync(path.join(work, "REPORT.md"), `${chunkIHYBGLNW_cjs.renderReport(plan, (d) => rel(expectedPathOf(d)))}
|
|
594
115
|
`);
|
|
595
116
|
log(`[plan] ${stampText(plan.from)} \u2192 ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);
|
|
596
117
|
for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);
|
|
@@ -607,7 +128,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
607
128
|
return 1;
|
|
608
129
|
}
|
|
609
130
|
const raw = JSON.parse(fs.readFileSync(planPath, "utf8"));
|
|
610
|
-
if (!
|
|
131
|
+
if (!isRecord(raw) || !isRecord(raw["to"]) || !isRecord(raw["from"]) || !Array.isArray(raw["documents"]) || !Array.isArray(raw["untouched"])) {
|
|
611
132
|
log(`[fail] ${rel(planPath)} is not a plan \u2014 run: strata upgrade`);
|
|
612
133
|
return 1;
|
|
613
134
|
}
|
|
@@ -616,7 +137,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
616
137
|
to: Object.fromEntries(Object.entries(raw["to"]).map(([k, v]) => [k, Number(v)])),
|
|
617
138
|
migrations: [],
|
|
618
139
|
documents: raw["documents"].flatMap(
|
|
619
|
-
(d) =>
|
|
140
|
+
(d) => isRecord(d) && typeof d["kind"] === "string" && typeof d["id"] === "string" ? [{ kind: d["kind"], id: d["id"], applied: [], changes: [], expected: d["expected"] }] : []
|
|
620
141
|
),
|
|
621
142
|
untouched: raw["untouched"].map(String),
|
|
622
143
|
problems: []
|
|
@@ -625,7 +146,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
625
146
|
log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} \u2014 plan again: strata upgrade`);
|
|
626
147
|
return 1;
|
|
627
148
|
}
|
|
628
|
-
const result = verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });
|
|
149
|
+
const result = chunkIHYBGLNW_cjs.verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });
|
|
629
150
|
for (const line of result.lines) {
|
|
630
151
|
log(`[${line.ok ? "pass" : "fail"}] ${line.text}`);
|
|
631
152
|
for (const d of line.detail ?? []) log(` ${d}`);
|