@niscorp/strata 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/DESIGN.md +4 -0
  3. package/README.md +47 -8
  4. package/dist/check/index.cjs +6 -6
  5. package/dist/check/index.js +1 -1
  6. package/dist/{chunk-SH6BBA2X.js → chunk-2G3DFR6P.js} +13 -11
  7. package/dist/chunk-2G3DFR6P.js.map +1 -0
  8. package/dist/{chunk-FSEUYRLN.cjs → chunk-FMXFHYU2.cjs} +15 -6
  9. package/dist/chunk-FMXFHYU2.cjs.map +1 -0
  10. package/dist/{chunk-SYU7NKZR.cjs → chunk-HTW4IEBC.cjs} +13 -11
  11. package/dist/chunk-HTW4IEBC.cjs.map +1 -0
  12. package/dist/{chunk-564JCO6Q.cjs → chunk-I2CR5CBI.cjs} +17 -13
  13. package/dist/chunk-I2CR5CBI.cjs.map +1 -0
  14. package/dist/{chunk-FNMGVPSA.js → chunk-LJAB5G5Y.js} +13 -4
  15. package/dist/chunk-LJAB5G5Y.js.map +1 -0
  16. package/dist/{chunk-DGS4XJQQ.js → chunk-QDZYRBRP.js} +14 -11
  17. package/dist/chunk-QDZYRBRP.js.map +1 -0
  18. package/dist/{chunk-KYNER7UU.cjs → chunk-SJNHLIKR.cjs} +4 -3
  19. package/dist/chunk-SJNHLIKR.cjs.map +1 -0
  20. package/dist/{chunk-PAMQMFBK.js → chunk-YCQ6LS7X.js} +4 -3
  21. package/dist/chunk-YCQ6LS7X.js.map +1 -0
  22. package/dist/index.cjs +19 -19
  23. package/dist/index.js +2 -2
  24. package/dist/node/index.cjs +178 -89
  25. package/dist/node/index.cjs.map +1 -1
  26. package/dist/node/index.js +180 -91
  27. package/dist/node/index.js.map +1 -1
  28. package/dist/postgres/index.cjs +26 -11
  29. package/dist/postgres/index.cjs.map +1 -1
  30. package/dist/postgres/index.d.cts +1 -0
  31. package/dist/postgres/index.d.ts +1 -0
  32. package/dist/postgres/index.js +20 -5
  33. package/dist/postgres/index.js.map +1 -1
  34. package/dist/upgrade/index.cjs +6 -6
  35. package/dist/upgrade/index.js +2 -2
  36. package/package.json +1 -1
  37. package/dist/chunk-564JCO6Q.cjs.map +0 -1
  38. package/dist/chunk-DGS4XJQQ.js.map +0 -1
  39. package/dist/chunk-FNMGVPSA.js.map +0 -1
  40. package/dist/chunk-FSEUYRLN.cjs.map +0 -1
  41. package/dist/chunk-KYNER7UU.cjs.map +0 -1
  42. package/dist/chunk-PAMQMFBK.js.map +0 -1
  43. package/dist/chunk-SH6BBA2X.js.map +0 -1
  44. package/dist/chunk-SYU7NKZR.cjs.map +0 -1
@@ -1,33 +1,67 @@
1
1
  'use strict';
2
2
 
3
- var chunkFSEUYRLN_cjs = require('../chunk-FSEUYRLN.cjs');
4
- require('../chunk-KYNER7UU.cjs');
5
- var chunk564JCO6Q_cjs = require('../chunk-564JCO6Q.cjs');
6
- require('../chunk-SYU7NKZR.cjs');
3
+ var chunkFMXFHYU2_cjs = require('../chunk-FMXFHYU2.cjs');
4
+ require('../chunk-SJNHLIKR.cjs');
5
+ var chunkI2CR5CBI_cjs = require('../chunk-I2CR5CBI.cjs');
6
+ require('../chunk-HTW4IEBC.cjs');
7
7
  var chunk7PBIGCLL_cjs = require('../chunk-7PBIGCLL.cjs');
8
8
  var fs = require('fs');
9
9
  var path = require('path');
10
10
 
11
11
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12
+ var isPlan = (raw) => isRecord(raw) && isRecord(raw["to"]) && isRecord(raw["from"]) && Array.isArray(raw["documents"]) && Array.isArray(raw["untouched"]);
13
+ var sameStamp = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([id, n]) => b[id] === n);
14
+ var isMigrationCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 || typeof value === "string" && /^\d+$/.test(value);
12
15
  var stampText = (s) => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(", ") || "(nothing)";
13
16
  var filesUnder = (dir) => fs.existsSync(dir) ? fs.readdirSync(dir).flatMap((name) => {
14
17
  const path$1 = path.join(dir, name);
15
18
  if (name === "node_modules" || name.startsWith(".")) return [];
16
19
  return fs.statSync(path$1).isDirectory() ? filesUnder(path$1) : /\.(ts|tsx|js|mjs)$/.test(name) ? [path$1] : [];
17
20
  }) : [];
18
- var runSourceUpgrade = async (options, argv) => {
19
- const log = options.log ?? ((line) => console.log(line));
20
- const command = argv.find((a) => !a.startsWith("-")) ?? "status";
21
+ var workspaceOf = async (options) => {
21
22
  const lockPath = path.join(options.root, options.lock ?? "strata.lock.json");
22
23
  const work = path.join(options.root, options.workDir ?? path.join(".strata", "upgrade"));
23
24
  const rel = (path$1) => path.relative(options.root, path$1).split(path.sep).join("/");
24
- const upgrader = await chunkFSEUYRLN_cjs.createUpgrader(options.grammars, { transform: options.transform });
25
- const descriptions = new Map(options.grammars.flatMap((g) => g.migrations.map((m, i) => [`${g.id}/${i + 1}`, m.description])));
26
- const readLock = () => {
27
- if (!fs.existsSync(lockPath)) return void 0;
28
- const raw = JSON.parse(fs.readFileSync(lockPath, "utf8"));
29
- if (!isRecord(raw) || !isRecord(raw["grammar"])) throw new chunk7PBIGCLL_cjs.StrataError("INVALID_SEQUENCE", `${rel(lockPath)} is not a lock: expected { "grammar": { \u2026 } }.`);
30
- return Object.fromEntries(Object.entries(raw["grammar"]).map(([k, v]) => [k, Number(v)]));
25
+ const planPath = path.join(work, "plan.json");
26
+ const reportPath = path.join(work, "REPORT.md");
27
+ const expectedPathsOf = (docs) => {
28
+ const taken = /* @__PURE__ */ new Map();
29
+ return new Map(
30
+ docs.map((doc) => {
31
+ const name = path.join(work, "expected", doc.kind.replace(/[^a-z0-9.-]/gi, "_"), doc.id.replace(/[^A-Za-z0-9._-]/g, "_"));
32
+ const count = (taken.get(name) ?? 0) + 1;
33
+ taken.set(name, count);
34
+ return [`${doc.kind}:${doc.id}`, `${name}${count === 1 ? "" : `~${count}`}.json`];
35
+ })
36
+ );
37
+ };
38
+ const readJson = (path) => {
39
+ try {
40
+ return JSON.parse(fs.readFileSync(path, "utf8"));
41
+ } catch {
42
+ return void 0;
43
+ }
44
+ };
45
+ const reportIsOurs = () => options.workDir === void 0 || !fs.existsSync(reportPath) || fs.readFileSync(reportPath, "utf8").replace(/^\uFEFF/, "").startsWith("# strata upgrade");
46
+ const planIsOurs = () => options.workDir === void 0 || !fs.existsSync(planPath) || isPlan(readJson(planPath));
47
+ const notStrata = () => !reportIsOurs() ? reportPath : !planIsOurs() ? planPath : void 0;
48
+ const removeIfEmpty = (dir) => {
49
+ if (fs.existsSync(dir) && fs.statSync(dir).isDirectory() && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
50
+ };
51
+ const removeWork = () => {
52
+ const ownPlan = planIsOurs();
53
+ const raw = ownPlan && fs.existsSync(planPath) ? readJson(planPath) : void 0;
54
+ const planned = isRecord(raw) && Array.isArray(raw["documents"]) ? raw["documents"].flatMap((d) => isRecord(d) && typeof d["kind"] === "string" && typeof d["id"] === "string" ? [{ kind: d["kind"], id: d["id"] }] : []) : [];
55
+ const expected = path.join(work, "expected");
56
+ const written = [...expectedPathsOf(planned).values()].filter((path$1) => {
57
+ const inside = path.relative(expected, path$1);
58
+ return inside !== "" && !inside.startsWith("..") && !path.isAbsolute(inside);
59
+ });
60
+ for (const path of written) fs.rmSync(path, { force: true });
61
+ for (const path$1 of written) removeIfEmpty(path.join(path$1, ".."));
62
+ removeIfEmpty(expected);
63
+ if (ownPlan) fs.rmSync(planPath, { force: true });
64
+ if (reportIsOurs()) fs.rmSync(reportPath, { force: true });
31
65
  };
32
66
  const writeLock = (stamp) => fs.writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => a < b ? -1 : 1)) }, null, 2)}
33
67
  `);
@@ -45,13 +79,140 @@ var runSourceUpgrade = async (options, argv) => {
45
79
  return { kind: d.kind, id: d.id, document, ...file === void 0 ? {} : { file } };
46
80
  });
47
81
  };
82
+ return {
83
+ options,
84
+ log: options.log ?? ((line) => console.log(line)),
85
+ upgrader: await chunkFMXFHYU2_cjs.createUpgrader(options.grammars, { transform: options.transform }),
86
+ lockPath,
87
+ work,
88
+ planPath,
89
+ reportPath,
90
+ rel,
91
+ expectedPathsOf,
92
+ notStrata,
93
+ removeIfEmpty,
94
+ removeWork,
95
+ writeLock,
96
+ sourceText,
97
+ loadDocuments
98
+ };
99
+ };
100
+ var upgradeSource = async (ws, lock) => {
101
+ const { options, log, upgrader, rel } = ws;
102
+ const descriptions = new Map(options.grammars.flatMap((g) => g.migrations.map((m, i) => [`${g.id}/${i + 1}`, m.description])));
103
+ const documents = await ws.loadDocuments();
104
+ const drafted = await chunkI2CR5CBI_cjs.planSourceUpgrade({
105
+ upgrader,
106
+ stamp: lock,
107
+ documents,
108
+ ...options.schemas === void 0 ? {} : { schemas: options.schemas },
109
+ describe: (ref) => descriptions.get(ref) ?? "(no description)"
110
+ });
111
+ const text = ws.sourceText();
112
+ const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));
113
+ const plan = {
114
+ ...drafted,
115
+ documents: drafted.documents.map((doc) => {
116
+ const needles = chunkI2CR5CBI_cjs.changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `"${s}"`]);
117
+ const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));
118
+ return { ...doc, lookIn };
119
+ })
120
+ };
121
+ const foreign = ws.notStrata();
122
+ if (foreign !== void 0) {
123
+ log(`[fail] ${rel(foreign)} is not one strata wrote \u2014 it is left as it is. Move it, or give strata a workDir of its own.`);
124
+ return 1;
125
+ }
126
+ ws.removeWork();
127
+ fs.mkdirSync(ws.work, { recursive: true });
128
+ const paths = ws.expectedPathsOf(plan.documents);
129
+ const pathOf = (doc) => paths.get(`${doc.kind}:${doc.id}`) ?? "";
130
+ for (const doc of plan.documents) {
131
+ const path$1 = pathOf(doc);
132
+ fs.mkdirSync(path.join(path$1, ".."), { recursive: true });
133
+ fs.writeFileSync(path$1, `${JSON.stringify(doc.expected, null, 2)}
134
+ `);
135
+ }
136
+ fs.writeFileSync(ws.planPath, `${JSON.stringify(plan, null, 2)}
137
+ `);
138
+ fs.writeFileSync(ws.reportPath, `${chunkI2CR5CBI_cjs.renderReport(plan, (d) => rel(pathOf(d)))}
139
+ `);
140
+ log(`[plan] ${stampText(plan.from)} \u2192 ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);
141
+ for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);
142
+ log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);
143
+ for (const d of plan.documents) log(` ${d.file ?? "(file not found)"} ${d.id}`);
144
+ log(` Report: ${rel(ws.reportPath)} \u2014 edit, then: strata verify`);
145
+ for (const p of plan.problems) log(`[fail] ${p}`);
146
+ return plan.problems.length > 0 ? 1 : 0;
147
+ };
148
+ var verifySource = async (ws, lock) => {
149
+ const { options, log, upgrader, rel, planPath } = ws;
150
+ if (!fs.existsSync(planPath)) {
151
+ log(`[fail] no plan at ${rel(planPath)} \u2014 run: strata upgrade`);
152
+ return 1;
153
+ }
154
+ const raw = JSON.parse(fs.readFileSync(planPath, "utf8"));
155
+ if (!isPlan(raw)) {
156
+ log(`[fail] ${rel(planPath)} is not a plan \u2014 run: strata upgrade`);
157
+ return 1;
158
+ }
159
+ const plan = {
160
+ from: Object.fromEntries(Object.entries(raw.from).map(([k, v]) => [k, Number(v)])),
161
+ to: Object.fromEntries(Object.entries(raw.to).map(([k, v]) => [k, Number(v)])),
162
+ migrations: [],
163
+ documents: raw.documents.flatMap(
164
+ (d) => isRecord(d) && typeof d["kind"] === "string" && typeof d["id"] === "string" ? [{ kind: d["kind"], id: d["id"], applied: [], changes: [], expected: d["expected"] }] : []
165
+ ),
166
+ untouched: raw.untouched.map(String),
167
+ problems: []
168
+ };
169
+ if (!sameStamp(plan.from, lock)) {
170
+ log(`[fail] the plan was made from ${stampText(plan.from)}, but ${rel(ws.lockPath)} records ${stampText(lock)} \u2014 plan again: strata upgrade`);
171
+ return 1;
172
+ }
173
+ if (!sameStamp(plan.to, upgrader.stamp)) {
174
+ log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} \u2014 plan again: strata upgrade`);
175
+ return 1;
176
+ }
177
+ const documents = await ws.loadDocuments();
178
+ const result = chunkI2CR5CBI_cjs.verifySourceUpgrade({ plan, upgrader, documents });
179
+ for (const line of result.lines) {
180
+ log(`[${line.ok ? "pass" : "fail"}] ${line.text}`);
181
+ for (const d of line.detail ?? []) log(` ${d}`);
182
+ }
183
+ const planned = new Set(plan.documents.map((d) => `${d.kind}:${d.id}`));
184
+ const misfits = [];
185
+ for (const doc of documents.filter((d) => planned.has(`${d.kind}:${d.id}`))) {
186
+ const misfit = await chunkI2CR5CBI_cjs.schemaMisfit(options.schemas, doc.kind, doc.document);
187
+ if (misfit !== void 0) misfits.push(`${doc.kind}:${doc.id} does not pass ${doc.kind}'s current schema \u2014 ${misfit}`);
188
+ }
189
+ for (const misfit of misfits) log(`[fail] ${misfit}`);
190
+ if (!result.ok || misfits.length > 0) return 1;
191
+ ws.writeLock(plan.to);
192
+ ws.removeWork();
193
+ ws.removeIfEmpty(ws.work);
194
+ if (options.workDir === void 0) ws.removeIfEmpty(path.join(options.root, ".strata"));
195
+ log(`[pass] the source is now written at ${stampText(plan.to)} \u2014 ${rel(ws.lockPath)} updated. Commit it with the edits.`);
196
+ return 0;
197
+ };
198
+ var runSourceUpgrade = async (options, argv) => {
199
+ const ws = await workspaceOf(options);
200
+ const { log, upgrader, lockPath, rel } = ws;
201
+ const command = argv.find((a) => !a.startsWith("-")) ?? "status";
202
+ const readLock = () => {
203
+ if (!fs.existsSync(lockPath)) return void 0;
204
+ const raw = JSON.parse(fs.readFileSync(lockPath, "utf8"));
205
+ if (!isRecord(raw) || !isRecord(raw["grammar"]) || !Object.values(raw["grammar"]).every(isMigrationCount))
206
+ throw new chunk7PBIGCLL_cjs.StrataError("INVALID_SEQUENCE", `${rel(lockPath)} is not a lock: expected { "grammar": { "<grammar id>": <how many of its migrations the source is written at> } }.`);
207
+ return Object.fromEntries(Object.entries(raw["grammar"]).map(([k, v]) => [k, Number(v)]));
208
+ };
48
209
  const lock = readLock();
49
210
  if (command === "init") {
50
211
  if (lock !== void 0) {
51
212
  log(`[fail] ${rel(lockPath)} already records ${stampText(lock)} \u2014 init only records a source that has never had a lock.`);
52
213
  return 1;
53
214
  }
54
- writeLock(upgrader.stamp);
215
+ ws.writeLock(upgrader.stamp);
55
216
  log(`[pass] recorded: the source is written at ${stampText(upgrader.stamp)} (${rel(lockPath)}). Only true if it is \u2014 commit it.`);
56
217
  return 0;
57
218
  }
@@ -82,81 +243,9 @@ var runSourceUpgrade = async (options, argv) => {
82
243
  log(`[pass] nothing to upgrade \u2014 the source is written at the installed grammars (${stampText(lock)})`);
83
244
  return 0;
84
245
  }
85
- const documents = await loadDocuments();
86
- const drafted = await chunk564JCO6Q_cjs.planSourceUpgrade({
87
- upgrader,
88
- stamp: lock,
89
- documents,
90
- ...options.schemas === void 0 ? {} : { schemas: options.schemas },
91
- describe: (ref) => descriptions.get(ref) ?? "(no description)"
92
- });
93
- const text = sourceText();
94
- const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));
95
- const plan = {
96
- ...drafted,
97
- documents: drafted.documents.map((doc) => {
98
- const needles = chunk564JCO6Q_cjs.changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `"${s}"`]);
99
- const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));
100
- return { ...doc, lookIn };
101
- })
102
- };
103
- fs.rmSync(work, { recursive: true, force: true });
104
- fs.mkdirSync(work, { recursive: true });
105
- const expectedPathOf = (doc) => path.join(work, "expected", doc.kind.replace(/[^a-z0-9.-]/gi, "_"), `${doc.id.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
106
- for (const doc of plan.documents) {
107
- const path$1 = expectedPathOf(doc);
108
- fs.mkdirSync(path.join(path$1, ".."), { recursive: true });
109
- fs.writeFileSync(path$1, `${JSON.stringify(doc.expected, null, 2)}
110
- `);
111
- }
112
- fs.writeFileSync(path.join(work, "plan.json"), `${JSON.stringify(plan, null, 2)}
113
- `);
114
- fs.writeFileSync(path.join(work, "REPORT.md"), `${chunk564JCO6Q_cjs.renderReport(plan, (d) => rel(expectedPathOf(d)))}
115
- `);
116
- log(`[plan] ${stampText(plan.from)} \u2192 ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);
117
- for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);
118
- log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);
119
- for (const d of plan.documents) log(` ${d.file ?? "(file not found)"} ${d.id}`);
120
- log(` Report: ${rel(path.join(work, "REPORT.md"))} \u2014 edit, then: strata verify`);
121
- for (const p of plan.problems) log(`[fail] ${p}`);
122
- return plan.problems.length > 0 ? 1 : 0;
123
- }
124
- if (command === "verify") {
125
- const planPath = path.join(work, "plan.json");
126
- if (!fs.existsSync(planPath)) {
127
- log(`[fail] no plan at ${rel(planPath)} \u2014 run: strata upgrade`);
128
- return 1;
129
- }
130
- const raw = JSON.parse(fs.readFileSync(planPath, "utf8"));
131
- if (!isRecord(raw) || !isRecord(raw["to"]) || !isRecord(raw["from"]) || !Array.isArray(raw["documents"]) || !Array.isArray(raw["untouched"])) {
132
- log(`[fail] ${rel(planPath)} is not a plan \u2014 run: strata upgrade`);
133
- return 1;
134
- }
135
- const plan = {
136
- from: Object.fromEntries(Object.entries(raw["from"]).map(([k, v]) => [k, Number(v)])),
137
- to: Object.fromEntries(Object.entries(raw["to"]).map(([k, v]) => [k, Number(v)])),
138
- migrations: [],
139
- documents: raw["documents"].flatMap(
140
- (d) => isRecord(d) && typeof d["kind"] === "string" && typeof d["id"] === "string" ? [{ kind: d["kind"], id: d["id"], applied: [], changes: [], expected: d["expected"] }] : []
141
- ),
142
- untouched: raw["untouched"].map(String),
143
- problems: []
144
- };
145
- if (JSON.stringify(plan.to) !== JSON.stringify(upgrader.stamp)) {
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`);
147
- return 1;
148
- }
149
- const result = chunk564JCO6Q_cjs.verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });
150
- for (const line of result.lines) {
151
- log(`[${line.ok ? "pass" : "fail"}] ${line.text}`);
152
- for (const d of line.detail ?? []) log(` ${d}`);
153
- }
154
- if (!result.ok) return 1;
155
- writeLock(plan.to);
156
- fs.rmSync(path.join(options.root, options.workDir ?? ".strata"), { recursive: true, force: true });
157
- log(`[pass] the source is now written at ${stampText(plan.to)} \u2014 ${rel(lockPath)} updated. Commit it with the edits.`);
158
- return 0;
246
+ return upgradeSource(ws, lock);
159
247
  }
248
+ if (command === "verify") return verifySource(ws, lock);
160
249
  log(`[fail] unknown command "${command}" \u2014 status [--check] | init | upgrade | verify`);
161
250
  return 1;
162
251
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/node/index.ts"],"names":["existsSync","readdirSync","path","join","statSync","relative","sep","createUpgrader","readFileSync","StrataError","writeFileSync","planSourceUpgrade","changedStrings","rmSync","mkdirSync","renderReport","verifySourceUpgrade"],"mappings":";;;;;;;;;;AAoBA,IAAM,QAAA,GAAW,CAAC,KAAA,KAAqD,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAE1I,IAAM,SAAA,GAAY,CAAC,CAAA,KAAqB,MAAA,CAAO,QAAQ,CAAC,CAAA,CAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA,KAAM,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,C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AI,CAAA,6BAAA,EAAgC,SAAA,CAAU,IAAA,CAAK,EAAE,CAAC,uCAAuC,SAAA,CAAU,QAAA,CAAS,KAAK,CAAC,CAAA,kCAAA,CAA+B,CAAA;AACrJ,MAAA,OAAO,CAAA;AAAA,IACT;AACA,IAAA,MAAM,MAAA,GAASQ,sCAAoB,EAAE,IAAA,EAAM,UAAU,SAAA,EAAW,MAAM,aAAA,EAAc,EAAG,CAAA;AACvF,IAAA,KAAA,MAAW,IAAA,IAAQ,OAAO,KAAA,EAAO;AAC/B,MAAA,GAAA,CAAI,CAAA,CAAA,EAAI,KAAK,EAAA,GAAK,MAAA,GAAS,MAAM,CAAA,EAAA,EAAK,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AACjD,MAAA,KAAA,MAAW,CAAA,IAAK,KAAK,MAAA,IAAU,IAAI,GAAA,CAAI,CAAA,SAAA,EAAY,CAAC,CAAA,CAAE,CAAA;AAAA,IACxD;AACA,IAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAO,CAAA;AACvB,IAAA,SAAA,CAAU,KAAK,EAAE,CAAA;AACjB,IAAAH,SAAA,CAAOV,SAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,OAAA,CAAQ,OAAA,IAAW,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,CAAA;AACzF,IAAA,GAAA,CAAI,CAAA,oCAAA,EAAuC,UAAU,IAAA,CAAK,EAAE,CAAC,CAAA,QAAA,EAAM,GAAA,CAAI,QAAQ,CAAC,CAAA,mCAAA,CAAqC,CAAA;AACrH,IAAA,OAAO,CAAA;AAAA,EACT;AAEA,EAAA,GAAA,CAAI,CAAA,wBAAA,EAA2B,OAAO,CAAA,mDAAA,CAAgD,CAAA;AACtF,EAAA,OAAO,CAAA;AACT","file":"index.cjs","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { createUpgrader, type Stamp, type Transform } from '../documents';\nimport type { Sequence } from '../schema';\nimport type { GrammarSchema } from '../check';\nimport { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade, type SourceDocument, type SourcePlan } from '../upgrade';\nimport { StrataError } from '../errors';\n\nexport type SourceUpgradeOptions = {\n root: string;\n grammars: readonly Sequence[];\n transform: Transform;\n documents: () => readonly SourceDocument[] | Promise<readonly SourceDocument[]>;\n schemas?: Readonly<Record<string, GrammarSchema>>;\n lock?: string;\n workDir?: string;\n sources?: string;\n log?: (line: string) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst stampText = (s: Stamp): string => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(', ') || '(nothing)';\n\nconst filesUnder = (dir: string): string[] =>\n existsSync(dir)\n ? readdirSync(dir).flatMap((name) => {\n const path = join(dir, name);\n if (name === 'node_modules' || name.startsWith('.')) return [];\n return statSync(path).isDirectory() ? filesUnder(path) : /\\.(ts|tsx|js|mjs)$/.test(name) ? [path] : [];\n })\n : [];\n\nexport const runSourceUpgrade = async (options: SourceUpgradeOptions, argv: readonly string[]): Promise<number> => {\n const log = options.log ?? ((line: string) => console.log(line));\n const command = argv.find((a) => !a.startsWith('-')) ?? 'status';\n const lockPath = join(options.root, options.lock ?? 'strata.lock.json');\n const work = join(options.root, options.workDir ?? join('.strata', 'upgrade'));\n // POSIX separators on every platform: these paths land in REPORT.md, plan.json and the log.\n const rel = (path: string): string => relative(options.root, path).split(sep).join('/');\n\n const upgrader = await createUpgrader(options.grammars, { transform: options.transform });\n const descriptions = new Map<string, string>(options.grammars.flatMap((g) => g.migrations.map((m, i): [string, string] => [`${g.id}/${i + 1}`, m.description])));\n\n const readLock = (): Stamp | undefined => {\n if (!existsSync(lockPath)) return undefined;\n const raw: unknown = JSON.parse(readFileSync(lockPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['grammar'])) throw new StrataError('INVALID_SEQUENCE', `${rel(lockPath)} is not a lock: expected { \"grammar\": { … } }.`);\n return Object.fromEntries(Object.entries(raw['grammar']).map(([k, v]) => [k, Number(v)]));\n };\n const writeLock = (stamp: Stamp): void =>\n writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => (a < b ? -1 : 1))) }, null, 2)}\\n`);\n\n const sourceText = (): Map<string, string> => new Map(filesUnder(join(options.root, options.sources ?? 'src')).map((f) => [f, readFileSync(f, 'utf8')]));\n\n const loadDocuments = async (): Promise<SourceDocument[]> => {\n const text = sourceText();\n const fileOf = (id: string): string | undefined => {\n const needles = [`id: '${id}'`, `id: \"${id}\"`, `\"id\": \"${id}\"`];\n for (const [path, body] of text) if (needles.some((n) => body.includes(n))) return rel(path);\n return undefined;\n };\n return (await options.documents()).map((d) => {\n // As it would be stored: no undefined, no functions.\n const document: unknown = JSON.parse(JSON.stringify(d.document));\n const file = d.file ?? fileOf(d.id);\n return { kind: d.kind, id: d.id, document, ...(file === undefined ? {} : { file }) };\n });\n };\n\n const lock = readLock();\n\n if (command === 'init') {\n if (lock !== undefined) {\n log(`[fail] ${rel(lockPath)} already records ${stampText(lock)} — init only records a source that has never had a lock.`);\n return 1;\n }\n writeLock(upgrader.stamp);\n log(`[pass] recorded: the source is written at ${stampText(upgrader.stamp)} (${rel(lockPath)}). Only true if it is — commit it.`);\n return 0;\n }\n\n if (lock === undefined) {\n log(`[fail] no ${rel(lockPath)} — nothing records which grammars this source is written in.`);\n log(` If it is written at the installed ones (${stampText(upgrader.stamp)}), run: strata init`);\n return 1;\n }\n\n let behind: boolean;\n try {\n behind = upgrader.behind(lock);\n } catch (error) {\n log(`[fail] ${error instanceof Error ? error.message.split('\\n').join('\\n ') : String(error)}`);\n log(' The lock is ahead of the installed grammars — install the newer packages, or the lock is wrong.');\n return 1;\n }\n\n if (command === 'status') {\n if (!behind) {\n log(`[pass] the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n log(`[${argv.includes('--check') ? 'fail' : 'info'}] the source is written at ${stampText(lock)}; the installed grammars are at ${stampText(upgrader.stamp)}.`);\n log(' Run: strata upgrade — then edit what REPORT.md lists — then: strata verify');\n return argv.includes('--check') ? 1 : 0;\n }\n\n if (command === 'upgrade') {\n if (!behind) {\n log(`[pass] nothing to upgrade — the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n const documents = await loadDocuments();\n const drafted = await planSourceUpgrade({\n upgrader,\n stamp: lock,\n documents,\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n describe: (ref) => descriptions.get(ref) ?? '(no description)',\n });\n const text = sourceText();\n const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));\n const plan: SourcePlan = {\n ...drafted,\n documents: drafted.documents.map((doc) => {\n const needles = changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `\"${s}\"`]);\n const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));\n return { ...doc, lookIn };\n }),\n };\n rmSync(work, { recursive: true, force: true });\n mkdirSync(work, { recursive: true });\n const expectedPathOf = (doc: { kind: string; id: string }): string => join(work, 'expected', doc.kind.replace(/[^a-z0-9.-]/gi, '_'), `${doc.id.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);\n for (const doc of plan.documents) {\n const path = expectedPathOf(doc);\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, `${JSON.stringify(doc.expected, null, 2)}\\n`);\n }\n writeFileSync(join(work, 'plan.json'), `${JSON.stringify(plan, null, 2)}\\n`);\n writeFileSync(join(work, 'REPORT.md'), `${renderReport(plan, (d) => rel(expectedPathOf(d)))}\\n`);\n log(`[plan] ${stampText(plan.from)} → ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);\n for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);\n log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);\n for (const d of plan.documents) log(` ${d.file ?? '(file not found)'} ${d.id}`);\n log(` Report: ${rel(join(work, 'REPORT.md'))} — edit, then: strata verify`);\n for (const p of plan.problems) log(`[fail] ${p}`);\n return plan.problems.length > 0 ? 1 : 0;\n }\n\n if (command === 'verify') {\n const planPath = join(work, 'plan.json');\n if (!existsSync(planPath)) {\n log(`[fail] no plan at ${rel(planPath)} — run: strata upgrade`);\n return 1;\n }\n const raw: unknown = JSON.parse(readFileSync(planPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['to']) || !isRecord(raw['from']) || !Array.isArray(raw['documents']) || !Array.isArray(raw['untouched'])) {\n log(`[fail] ${rel(planPath)} is not a plan — run: strata upgrade`);\n return 1;\n }\n const plan: SourcePlan = {\n from: Object.fromEntries(Object.entries(raw['from']).map(([k, v]) => [k, Number(v)])),\n to: Object.fromEntries(Object.entries(raw['to']).map(([k, v]) => [k, Number(v)])),\n migrations: [],\n documents: raw['documents'].flatMap((d: unknown) =>\n isRecord(d) && typeof d['kind'] === 'string' && typeof d['id'] === 'string' ? [{ kind: d['kind'], id: d['id'], applied: [], changes: [], expected: d['expected'] }] : [],\n ),\n untouched: raw['untouched'].map(String),\n problems: [],\n };\n if (JSON.stringify(plan.to) !== JSON.stringify(upgrader.stamp)) {\n log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} — plan again: strata upgrade`);\n return 1;\n }\n const result = verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });\n for (const line of result.lines) {\n log(`[${line.ok ? 'pass' : 'fail'}] ${line.text}`);\n for (const d of line.detail ?? []) log(` ${d}`);\n }\n if (!result.ok) return 1;\n writeLock(plan.to);\n rmSync(join(options.root, options.workDir ?? '.strata'), { recursive: true, force: true });\n log(`[pass] the source is now written at ${stampText(plan.to)} — ${rel(lockPath)} updated. Commit it with the edits.`);\n return 0;\n }\n\n log(`[fail] unknown command \"${command}\" — status [--check] | init | upgrade | verify`);\n return 1;\n};\n"]}
1
+ {"version":3,"sources":["../../src/node/index.ts"],"names":["existsSync","readdirSync","path","join","statSync","relative","sep","readFileSync","isAbsolute","rmSync","writeFileSync","createUpgrader","planSourceUpgrade","changedStrings","mkdirSync","renderReport","verifySourceUpgrade","schemaMisfit","StrataError"],"mappings":";;;;;;;;;;AAqBA,IAAM,QAAA,GAAW,CAAC,KAAA,KAAqD,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAE1I,IAAM,MAAA,GAAS,CAAC,GAAA,KACd,QAAA,CAAS,GAAG,CAAA,IAAK,QAAA,CAAS,GAAA,CAAI,IAAI,CAAC,CAAA,IAAK,QAAA,CAAS,GAAA,CAAI,MAAM,CAAC,CAAA,IAAK,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAC,CAAA,IAAK,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAC,CAAA;AAEpI,IAAM,SAAA,GAAY,CAAC,CAAA,EAAU,CAAA,KAAsB,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,CAAE,MAAA,KAAW,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,CAAE,MAAA,IAAU,MAAA,CAAO,OAAA,CAAQ,CAAC,CAAA,CAAE,KAAA,CAAM,CAAC,CAAC,EAAA,EAAI,CAAC,CAAA,KAAM,CAAA,CAAE,EAAE,CAAA,KAAM,CAAC,CAAA;AAGtJ,IAAM,mBAAmB,CAAC,KAAA,KAA6B,OAAO,KAAA,KAAU,YAAY,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IAAK,SAAS,CAAA,IAAO,OAAO,UAAU,QAAA,IAAY,OAAA,CAAQ,KAAK,KAAK,CAAA;AAE9K,IAAM,SAAA,GAAY,CAAC,CAAA,KAAqB,MAAA,CAAO,QAAQ,CAAC,CAAA,CAAE,IAAI,CAAC,CAAC,GAAG,CAA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AAA,CAAc,IAAI,IAAI,CAAA;AAAA,EAC/B;AAEA,EAAA,IAAI,OAAA,KAAY,QAAA,EAAU,OAAO,YAAA,CAAa,IAAI,IAAI,CAAA;AAEtD,EAAA,GAAA,CAAI,CAAA,wBAAA,EAA2B,OAAO,CAAA,mDAAA,CAAgD,CAAA;AACtF,EAAA,OAAO,CAAA;AACT","file":"index.cjs","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { isAbsolute, join, relative, sep } from 'node:path';\nimport { createUpgrader, type Stamp, type Transform, type Upgrader } from '../documents';\nimport type { Sequence } from '../schema';\nimport type { GrammarSchema } from '../check';\nimport { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade, type SourceDocument, type SourcePlan } from '../upgrade';\nimport { schemaMisfit } from '../upgrade/fits';\nimport { StrataError } from '../errors';\n\nexport type SourceUpgradeOptions = {\n root: string;\n grammars: readonly Sequence[];\n transform: Transform;\n documents: () => readonly SourceDocument[] | Promise<readonly SourceDocument[]>;\n schemas?: Readonly<Record<string, GrammarSchema>>;\n lock?: string;\n workDir?: string;\n sources?: string;\n log?: (line: string) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isPlan = (raw: unknown): raw is { from: Record<string, unknown>; to: Record<string, unknown>; documents: unknown[]; untouched: unknown[] } =>\n isRecord(raw) && isRecord(raw['to']) && isRecord(raw['from']) && Array.isArray(raw['documents']) && Array.isArray(raw['untouched']);\n\nconst sameStamp = (a: Stamp, b: Stamp): boolean => Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([id, n]) => b[id] === n);\n\n// Digits are taken as well as a number: `Number` read them correctly before this was checked.\nconst isMigrationCount = (value: unknown): boolean => (typeof value === 'number' && Number.isInteger(value) && value >= 0) || (typeof value === 'string' && /^\\d+$/.test(value));\n\nconst stampText = (s: Stamp): string => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(', ') || '(nothing)';\n\nconst filesUnder = (dir: string): string[] =>\n existsSync(dir)\n ? readdirSync(dir).flatMap((name) => {\n const path = join(dir, name);\n if (name === 'node_modules' || name.startsWith('.')) return [];\n return statSync(path).isDirectory() ? filesUnder(path) : /\\.(ts|tsx|js|mjs)$/.test(name) ? [path] : [];\n })\n : [];\n\ntype Workspace = {\n options: SourceUpgradeOptions;\n log: (line: string) => void;\n upgrader: Upgrader;\n lockPath: string;\n work: string;\n planPath: string;\n reportPath: string;\n rel: (path: string) => string;\n expectedPathsOf: (docs: readonly { kind: string; id: string }[]) => Map<string, string>;\n notStrata: () => string | undefined;\n removeIfEmpty: (dir: string) => void;\n removeWork: () => void;\n writeLock: (stamp: Stamp) => void;\n sourceText: () => Map<string, string>;\n loadDocuments: () => Promise<SourceDocument[]>;\n};\n\nconst workspaceOf = async (options: SourceUpgradeOptions): Promise<Workspace> => {\n const lockPath = join(options.root, options.lock ?? 'strata.lock.json');\n const work = join(options.root, options.workDir ?? join('.strata', 'upgrade'));\n // POSIX separators on every platform: these paths land in REPORT.md, plan.json and the log.\n const rel = (path: string): string => relative(options.root, path).split(sep).join('/');\n const planPath = join(work, 'plan.json');\n const reportPath = join(work, 'REPORT.md');\n // Ids that clean to one name get `~2`, `~3` after the first, in the plan's order: each has a file of its own.\n const expectedPathsOf = (docs: readonly { kind: string; id: string }[]): Map<string, string> => {\n const taken = new Map<string, number>();\n return new Map(\n docs.map((doc) => {\n const name = join(work, 'expected', doc.kind.replace(/[^a-z0-9.-]/gi, '_'), doc.id.replace(/[^A-Za-z0-9._-]/g, '_'));\n const count = (taken.get(name) ?? 0) + 1;\n taken.set(name, count);\n return [`${doc.kind}:${doc.id}`, `${name}${count === 1 ? '' : `~${count}`}.json`];\n }),\n );\n };\n\n const readJson = (path: string): unknown => {\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n return undefined;\n }\n };\n // In a work directory the host chose, a REPORT.md or plan.json is strata's only when it reads as one strata\n // wrote: the report under its heading, the plan in its shape. `.strata/upgrade` is strata's own.\n const reportIsOurs = (): boolean => options.workDir === undefined || !existsSync(reportPath) || readFileSync(reportPath, 'utf8').replace(/^\\uFEFF/, '').startsWith('# strata upgrade');\n const planIsOurs = (): boolean => options.workDir === undefined || !existsSync(planPath) || isPlan(readJson(planPath));\n const notStrata = (): string | undefined => (!reportIsOurs() ? reportPath : !planIsOurs() ? planPath : undefined);\n\n // The work directory can be any directory, the project's own included: only the files a plan wrote\n // are removed, and a directory only once it is empty. plan.json is read back from disk, so a path it\n // names is removed only when it lies inside expected/.\n const removeIfEmpty = (dir: string): void => {\n if (existsSync(dir) && statSync(dir).isDirectory() && readdirSync(dir).length === 0) rmdirSync(dir);\n };\n const removeWork = (): void => {\n const ownPlan = planIsOurs();\n const raw = ownPlan && existsSync(planPath) ? readJson(planPath) : undefined;\n const planned =\n isRecord(raw) && Array.isArray(raw['documents'])\n ? raw['documents'].flatMap((d: unknown) => (isRecord(d) && typeof d['kind'] === 'string' && typeof d['id'] === 'string' ? [{ kind: d['kind'], id: d['id'] }] : []))\n : [];\n const expected = join(work, 'expected');\n const written = [...expectedPathsOf(planned).values()].filter((path) => {\n const inside = relative(expected, path);\n return inside !== '' && !inside.startsWith('..') && !isAbsolute(inside);\n });\n for (const path of written) rmSync(path, { force: true });\n for (const path of written) removeIfEmpty(join(path, '..'));\n removeIfEmpty(expected);\n if (ownPlan) rmSync(planPath, { force: true });\n if (reportIsOurs()) rmSync(reportPath, { force: true });\n };\n\n const writeLock = (stamp: Stamp): void =>\n writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => (a < b ? -1 : 1))) }, null, 2)}\\n`);\n\n const sourceText = (): Map<string, string> => new Map(filesUnder(join(options.root, options.sources ?? 'src')).map((f) => [f, readFileSync(f, 'utf8')]));\n\n const loadDocuments = async (): Promise<SourceDocument[]> => {\n const text = sourceText();\n const fileOf = (id: string): string | undefined => {\n const needles = [`id: '${id}'`, `id: \"${id}\"`, `\"id\": \"${id}\"`];\n for (const [path, body] of text) if (needles.some((n) => body.includes(n))) return rel(path);\n return undefined;\n };\n return (await options.documents()).map((d) => {\n // As it would be stored: no undefined, no functions.\n const document: unknown = JSON.parse(JSON.stringify(d.document));\n const file = d.file ?? fileOf(d.id);\n return { kind: d.kind, id: d.id, document, ...(file === undefined ? {} : { file }) };\n });\n };\n\n return {\n options,\n log: options.log ?? ((line: string) => console.log(line)),\n upgrader: await createUpgrader(options.grammars, { transform: options.transform }),\n lockPath,\n work,\n planPath,\n reportPath,\n rel,\n expectedPathsOf,\n notStrata,\n removeIfEmpty,\n removeWork,\n writeLock,\n sourceText,\n loadDocuments,\n };\n};\n\nconst upgradeSource = async (ws: Workspace, lock: Stamp): Promise<number> => {\n const { options, log, upgrader, rel } = ws;\n const descriptions = new Map<string, string>(options.grammars.flatMap((g) => g.migrations.map((m, i): [string, string] => [`${g.id}/${i + 1}`, m.description])));\n const documents = await ws.loadDocuments();\n const drafted = await planSourceUpgrade({\n upgrader,\n stamp: lock,\n documents,\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n describe: (ref) => descriptions.get(ref) ?? '(no description)',\n });\n const text = ws.sourceText();\n const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));\n const plan: SourcePlan = {\n ...drafted,\n documents: drafted.documents.map((doc) => {\n const needles = changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `\"${s}\"`]);\n const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));\n return { ...doc, lookIn };\n }),\n };\n const foreign = ws.notStrata();\n if (foreign !== undefined) {\n log(`[fail] ${rel(foreign)} is not one strata wrote — it is left as it is. Move it, or give strata a workDir of its own.`);\n return 1;\n }\n ws.removeWork();\n mkdirSync(ws.work, { recursive: true });\n const paths = ws.expectedPathsOf(plan.documents);\n const pathOf = (doc: { kind: string; id: string }): string => paths.get(`${doc.kind}:${doc.id}`) ?? '';\n for (const doc of plan.documents) {\n const path = pathOf(doc);\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, `${JSON.stringify(doc.expected, null, 2)}\\n`);\n }\n writeFileSync(ws.planPath, `${JSON.stringify(plan, null, 2)}\\n`);\n writeFileSync(ws.reportPath, `${renderReport(plan, (d) => rel(pathOf(d)))}\\n`);\n log(`[plan] ${stampText(plan.from)} → ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);\n for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);\n log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);\n for (const d of plan.documents) log(` ${d.file ?? '(file not found)'} ${d.id}`);\n log(` Report: ${rel(ws.reportPath)} — edit, then: strata verify`);\n for (const p of plan.problems) log(`[fail] ${p}`);\n return plan.problems.length > 0 ? 1 : 0;\n};\n\nconst verifySource = async (ws: Workspace, lock: Stamp): Promise<number> => {\n const { options, log, upgrader, rel, planPath } = ws;\n if (!existsSync(planPath)) {\n log(`[fail] no plan at ${rel(planPath)} — run: strata upgrade`);\n return 1;\n }\n const raw: unknown = JSON.parse(readFileSync(planPath, 'utf8'));\n if (!isPlan(raw)) {\n log(`[fail] ${rel(planPath)} is not a plan — run: strata upgrade`);\n return 1;\n }\n const plan: SourcePlan = {\n from: Object.fromEntries(Object.entries(raw.from).map(([k, v]) => [k, Number(v)])),\n to: Object.fromEntries(Object.entries(raw.to).map(([k, v]) => [k, Number(v)])),\n migrations: [],\n documents: raw.documents.flatMap((d: unknown) =>\n isRecord(d) && typeof d['kind'] === 'string' && typeof d['id'] === 'string' ? [{ kind: d['kind'], id: d['id'], applied: [], changes: [], expected: d['expected'] }] : [],\n ),\n untouched: raw.untouched.map(String),\n problems: [],\n };\n // The lock is the source's stamp: what plan.json says the plan was made from is believed only where the two agree.\n if (!sameStamp(plan.from, lock)) {\n log(`[fail] the plan was made from ${stampText(plan.from)}, but ${rel(ws.lockPath)} records ${stampText(lock)} — plan again: strata upgrade`);\n return 1;\n }\n if (!sameStamp(plan.to, upgrader.stamp)) {\n log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} — plan again: strata upgrade`);\n return 1;\n }\n const documents = await ws.loadDocuments();\n const result = verifySourceUpgrade({ plan, upgrader, documents });\n for (const line of result.lines) {\n log(`[${line.ok ? 'pass' : 'fail'}] ${line.text}`);\n for (const d of line.detail ?? []) log(` ${d}`);\n }\n const planned = new Set(plan.documents.map((d) => `${d.kind}:${d.id}`));\n const misfits: string[] = [];\n for (const doc of documents.filter((d) => planned.has(`${d.kind}:${d.id}`))) {\n const misfit = await schemaMisfit(options.schemas, doc.kind, doc.document);\n if (misfit !== undefined) misfits.push(`${doc.kind}:${doc.id} does not pass ${doc.kind}'s current schema — ${misfit}`);\n }\n for (const misfit of misfits) log(`[fail] ${misfit}`);\n if (!result.ok || misfits.length > 0) return 1;\n ws.writeLock(plan.to);\n ws.removeWork();\n ws.removeIfEmpty(ws.work);\n if (options.workDir === undefined) ws.removeIfEmpty(join(options.root, '.strata'));\n log(`[pass] the source is now written at ${stampText(plan.to)} — ${rel(ws.lockPath)} updated. Commit it with the edits.`);\n return 0;\n};\n\nexport const runSourceUpgrade = async (options: SourceUpgradeOptions, argv: readonly string[]): Promise<number> => {\n const ws = await workspaceOf(options);\n const { log, upgrader, lockPath, rel } = ws;\n const command = argv.find((a) => !a.startsWith('-')) ?? 'status';\n\n const readLock = (): Stamp | undefined => {\n if (!existsSync(lockPath)) return undefined;\n const raw: unknown = JSON.parse(readFileSync(lockPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['grammar']) || !Object.values(raw['grammar']).every(isMigrationCount))\n throw new StrataError('INVALID_SEQUENCE', `${rel(lockPath)} is not a lock: expected { \"grammar\": { \"<grammar id>\": <how many of its migrations the source is written at> } }.`);\n return Object.fromEntries(Object.entries(raw['grammar']).map(([k, v]) => [k, Number(v)]));\n };\n\n const lock = readLock();\n\n if (command === 'init') {\n if (lock !== undefined) {\n log(`[fail] ${rel(lockPath)} already records ${stampText(lock)} — init only records a source that has never had a lock.`);\n return 1;\n }\n ws.writeLock(upgrader.stamp);\n log(`[pass] recorded: the source is written at ${stampText(upgrader.stamp)} (${rel(lockPath)}). Only true if it is — commit it.`);\n return 0;\n }\n\n if (lock === undefined) {\n log(`[fail] no ${rel(lockPath)} — nothing records which grammars this source is written in.`);\n log(` If it is written at the installed ones (${stampText(upgrader.stamp)}), run: strata init`);\n return 1;\n }\n\n let behind: boolean;\n try {\n behind = upgrader.behind(lock);\n } catch (error) {\n log(`[fail] ${error instanceof Error ? error.message.split('\\n').join('\\n ') : String(error)}`);\n log(' The lock is ahead of the installed grammars — install the newer packages, or the lock is wrong.');\n return 1;\n }\n\n if (command === 'status') {\n if (!behind) {\n log(`[pass] the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n log(`[${argv.includes('--check') ? 'fail' : 'info'}] the source is written at ${stampText(lock)}; the installed grammars are at ${stampText(upgrader.stamp)}.`);\n log(' Run: strata upgrade — then edit what REPORT.md lists — then: strata verify');\n return argv.includes('--check') ? 1 : 0;\n }\n\n if (command === 'upgrade') {\n if (!behind) {\n log(`[pass] nothing to upgrade — the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n return upgradeSource(ws, lock);\n }\n\n if (command === 'verify') return verifySource(ws, lock);\n\n log(`[fail] unknown command \"${command}\" — status [--check] | init | upgrade | verify`);\n return 1;\n};\n"]}