@skillstech/thunderlang 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +190 -0
- package/dist/core.cjs +6718 -1232
- package/dist/index.cjs +17490 -12204
- package/dist/learn.cjs +5866 -497
- package/package.json +6 -2
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +54 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +59 -0
- package/src/core.mjs +14 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +34 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/libraries.mjs +32 -4
- package/src/model.mjs +72 -9
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +64 -5
- package/src/replay-cli.mjs +123 -0
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +168 -13
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +443 -20
- package/src/term.mjs +43 -0
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +168 -0
package/src/index.d.ts
CHANGED
|
@@ -763,3 +763,6 @@ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPAR
|
|
|
763
763
|
export type { ChangedCase, ChangedCases, WriteChange, RulePart } from './write.mjs';
|
|
764
764
|
export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from './write-steps.mjs';
|
|
765
765
|
export type { ThunderEdit, ThunderWriteResult, WriteProof } from './write-steps.mjs';
|
|
766
|
+
export { buildPassport, checkPassportOnDisk, accessEvidence } from './passport-fs.mjs';
|
|
767
|
+
export { PASSPORT_SCHEMA, assemblePassport, checkPassport, renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
|
|
768
|
+
export type { Passport, PassportEvidence, PassportCheck } from './passport.mjs';
|
package/src/index.mjs
CHANGED
|
@@ -207,3 +207,6 @@ export { promoteDecision, PROMOTE_SCHEMA } from "./promote.mjs";
|
|
|
207
207
|
// Thunder write: change a recovered rule and write exactly those characters back, verified by re-reading.
|
|
208
208
|
export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from "./write.mjs";
|
|
209
209
|
export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from "./write-steps.mjs";
|
|
210
|
+
// The Thunder Software Passport (docs/passport.md): build one from folders (git, runs) and check it on disk.
|
|
211
|
+
export { buildPassport, checkPassportOnDisk, accessEvidence } from './passport-fs.mjs';
|
|
212
|
+
export { PASSPORT_SCHEMA, assemblePassport, checkPassport, renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
|
package/src/libraries.mjs
CHANGED
|
@@ -75,6 +75,13 @@ const URL_WORDS = (u) => {
|
|
|
75
75
|
return /^[A-Za-z_][\w.]*$/.test(t) ? `the ${words(t.split('.').pop()).replace(/\burl\b/, 'URL')}` : 'an address worked out by the code';
|
|
76
76
|
};
|
|
77
77
|
|
|
78
|
+
/** A file path in words: a quoted path as written, a name as "at <name>" ("Reads the file at config path"). */
|
|
79
|
+
const FILE_WORDS = (u) => {
|
|
80
|
+
const t = String(u || '').trim();
|
|
81
|
+
if (/^["'`]/.test(t)) return t.slice(1, -1).replace(/\$\{[^}]*\}/g, '…');
|
|
82
|
+
return /^[A-Za-z_][\w.]*$/.test(t) ? `at ${t.includes('.') ? `the ${words(t.split('.').pop())}` : words(t)}` : 'at a path worked out by the code';
|
|
83
|
+
};
|
|
84
|
+
|
|
78
85
|
// Spring Data / Rails-style derived query names: findByEmailAndActive -> "whose email is … and active is …".
|
|
79
86
|
function derivedWhose(name, args) {
|
|
80
87
|
const m = name.match(/^(?:find|get|read|query|search|stream|count|exists|delete|remove)(?:All|First|Top\d*|One)?By(\w+)$/);
|
|
@@ -90,11 +97,24 @@ const CATALOG = [
|
|
|
90
97
|
{ re: /^fetch\s*\(/, say: (m, c) => { const a = splitTop(inside(c, c.indexOf('(')) ?? ''); const method = (a[1]?.match(/method\s*:\s*["'`](\w+)/i) || [])[1]?.toUpperCase() ?? 'GET'; return { says: `Sends a ${method} request to ${URL_WORDS(a[0])}`, does: 'ask' }; } },
|
|
91
98
|
{ re: /^(?:axios|http|httpClient|client|api|ky|got|superagent|request)\s*\.\s*(get|post|put|patch|delete|head)\s*\(/i, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
92
99
|
{ re: /^(?:requests|httpx|session|self\.session|aiohttp\.ClientSession\(\))\s*\.\s*(get|post|put|patch|delete)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
93
|
-
{ re: /^(?:_?
|
|
100
|
+
{ re: /^(?:this\.)?(?:_?[Hh]ttp(?:Client)?|_?client|\w*HttpClient|_?\w+Client)\s*\.\s*(Get|Post|Put|Patch|Delete)(?:AsJson|FromJson|String)?Async\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
94
101
|
{ re: /^(?:restTemplate|webClient)\s*\.\s*(get|post|put|delete|patch)(?:ForObject|ForEntity)?\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
95
102
|
{ re: /^http\s*\.\s*(Get|Post|Head)\s*\(/, say: (m, c) => ({ says: `Sends a ${m[1].toUpperCase()} request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
96
103
|
{ re: /^reqwest\s*::\s*get\s*\(/, say: (m, c) => ({ says: `Sends a GET request to ${URL_WORDS(splitTop(inside(c, c.indexOf('(')) ?? '')[0])}`, does: 'ask' }) },
|
|
97
104
|
|
|
105
|
+
// ── A new random ID: crypto.randomUUID(), uuid.uuid4(), Guid.NewGuid(), uuidv4(), UUID.randomUUID() ──
|
|
106
|
+
{ re: /^(?:(?:globalThis\.|window\.)?crypto\.randomUUID|uuid\.uuid4|Guid\.NewGuid|uuidv4|uuid\.v4|UUID\.randomUUID|Uuid::new_v4)\s*\(\s*\)(?:\.(?:ToString|toString|hex)\(\)|\.hex)?$/, say: () => ({ says: 'a new random ID', does: 'calculate', value: true }) },
|
|
107
|
+
|
|
108
|
+
// ── .NET: a shared lookup table that makes an entry only once (ConcurrentDictionary.GetOrAdd) ──
|
|
109
|
+
// `byKey.GetOrAdd(key, _ => new Lazy<Task<T>>(() => Place(request))).Value`: later calls with the same key get the
|
|
110
|
+
// entry made the first time. The function that makes it is named when the code names one.
|
|
111
|
+
{ re: /^(?:this\.)?(_?[A-Za-z]\w*)\s*\.\s*GetOrAdd\s*\(/, say: (m, c) => {
|
|
112
|
+
const args = splitTop(inside(c, c.indexOf('(', m.index + m[0].length - 1)) ?? '');
|
|
113
|
+
if (args.length !== 2) return null;
|
|
114
|
+
const made = [...args[1].matchAll(/\b([A-Za-z_]\w*)\s*\(/g)].map((x) => x[1]).filter((x) => !/^(?:new|Lazy|Task|ValueTask)$/.test(x)).pop();
|
|
115
|
+
return { says: `the entry for ${valueWords(args[0])} in ${words(m[1])}, made${made ? ` by ${words(made)}` : ''} if it is missing (a later call with the same ${valueWords(args[0]).replace(/^the [\w ]+'s /, '')} gets that same entry)`, does: 'find', value: true };
|
|
116
|
+
} },
|
|
117
|
+
|
|
98
118
|
// ── Prisma ──
|
|
99
119
|
{ re: /^(?:this\.)?prisma\s*\.\s*(\w+)\s*\.\s*(findUnique|findUniqueOrThrow|findFirst|findFirstOrThrow|findMany|create|createMany|update|updateMany|upsert|delete|deleteMany|count|aggregate)\s*\(/, say: (m, c) => {
|
|
100
120
|
const thing = words(m[1]), args = inside(c, c.indexOf('(', m.index + m[0].length - 1)) ?? '', whose = whereOf(args);
|
|
@@ -169,15 +189,23 @@ const CATALOG = [
|
|
|
169
189
|
|
|
170
190
|
// ── JSON, files, time ──
|
|
171
191
|
{ re: /^JSON\s*\.\s*parse\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[1])} as JSON`, does: 'calculate' }) },
|
|
192
|
+
// An object written right there names its fields: JSON.stringify({ items: cart, coupon }) -> "Turns items (cart) and coupon into JSON text".
|
|
193
|
+
{ re: /^JSON\s*\.\s*stringify\s*\(\s*\{/, say: (m, c) => {
|
|
194
|
+
const obj = inside(c, c.indexOf('{'));
|
|
195
|
+
const fields = obj == null ? null : splitTop(obj).filter((x) => x.trim()).map((x) => x.trim().match(/^([A-Za-z_$][\w$]*)(?:\s*:\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?))?$/));
|
|
196
|
+
if (!fields?.length || fields.some((f) => !f)) return null;
|
|
197
|
+
const said = fields.map((f) => (f[2] && f[2] !== f[1] ? `${words(f[1])} (${valueWords(f[2])})` : words(f[1])));
|
|
198
|
+
return { says: `Turns ${said.length === 1 ? said[0] : `${said.slice(0, -1).join(', ')} and ${said.at(-1)}`} into JSON text`, does: 'calculate' };
|
|
199
|
+
} },
|
|
172
200
|
{ re: /^JSON\s*\.\s*stringify\s*\(\s*([^,]+)/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON text`, does: 'calculate' }) },
|
|
173
201
|
{ re: /^json\s*\.\s*(loads|load)\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Reads ${valueWords(m[2])} as JSON`, does: 'calculate' }) },
|
|
174
202
|
{ re: /^json\s*\.\s*(dumps|dump)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Turns ${valueWords(m[2])} into JSON text`, does: 'calculate' }) },
|
|
175
203
|
{ re: /^json\s*\.\s*Marshal\s*\(\s*(.+)\)$/, say: (m) => ({ says: `Turns ${valueWords(m[1])} into JSON`, does: 'calculate' }) },
|
|
176
204
|
{ re: /^json\s*\.\s*Unmarshal\s*\(\s*[^,]+,\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads the JSON into ${words(m[1])}`, does: 'calculate' }) },
|
|
177
205
|
{ re: /^json\s*\.\s*NewDecoder\s*\(\s*r\.Body\s*\)\s*\.\s*Decode\s*\(\s*&?(\w+)\s*\)$/, say: (m) => ({ says: `Reads what it was sent into ${words(m[1])}`, does: 'calculate' }) },
|
|
178
|
-
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(readFile|readFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Reads the file ${
|
|
179
|
-
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(writeFile|writeFileSync|appendFile|appendFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `${/append/.test(m[1]) ? 'Adds to' : 'Writes'} the file ${
|
|
180
|
-
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(unlink|unlinkSync|rm|rmSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Removes the file ${
|
|
206
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(readFile|readFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Reads the file ${FILE_WORDS(m[2])}`, does: 'find' }) },
|
|
207
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(writeFile|writeFileSync|appendFile|appendFileSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `${/append/.test(m[1]) ? 'Adds to' : 'Writes'} the file ${FILE_WORDS(m[2])}`, does: 'save' }) },
|
|
208
|
+
{ re: /^(?:fs|fsp|fs\.promises)\s*\.\s*(unlink|unlinkSync|rm|rmSync)\s*\(\s*([^,)]+)/, say: (m) => ({ says: `Removes the file ${FILE_WORDS(m[2])}`, does: 'save' }) },
|
|
181
209
|
{ re: /^(?:Date\.now|datetime\.now|datetime\.utcnow|time\.Now|DateTime\.Now|DateTime\.UtcNow|Instant\.now|LocalDateTime\.now|Time\.now)\s*\(?\s*\)?$/, say: () => ({ says: 'the current time', does: 'calculate', value: true }) },
|
|
182
210
|
];
|
|
183
211
|
|
package/src/model.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// choices), and members (actions, rules, steps, setup) with their flow as a graph, links between them, source lines,
|
|
3
3
|
// and everything Thunder could not read. Thunder pictures and Thunder Text are projections of this model; nothing in
|
|
4
4
|
// them may say more than the model does. Browser-safe: takes [{ path, source }].
|
|
5
|
+
import { readScreens, screenText } from './screens.mjs';
|
|
5
6
|
import { readCode, INFRA_LANGUAGES } from './read.mjs';
|
|
6
7
|
import { readableLanguage, readingOf } from './read-repo.mjs';
|
|
7
8
|
import { plainFromReading, explainPlain } from './plain-contract.mjs';
|
|
@@ -13,6 +14,7 @@ import { psThings } from './powershell.mjs';
|
|
|
13
14
|
import { splitLogic, closeOf, isCodeWords, balancedText } from './faithful.mjs';
|
|
14
15
|
import { detailParts } from './meaning.mjs';
|
|
15
16
|
import { linkSystem, callsSummary } from './system.mjs';
|
|
17
|
+
import { accessFlow, ownershipWords } from './flow/access.mjs';
|
|
16
18
|
|
|
17
19
|
export const MODEL_SCHEMA = 'thunder-model-v1';
|
|
18
20
|
/**
|
|
@@ -40,6 +42,8 @@ function startValue(expr, params = {}) {
|
|
|
40
42
|
if (/^(True|true)$/.test(e)) return 'yes at first';
|
|
41
43
|
if (/^(False|false)$/.test(e)) return 'no at first';
|
|
42
44
|
if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
|
|
45
|
+
// A typed number (C# 0.08m, Java 10L, 2.5f): the number, without its type letter.
|
|
46
|
+
if (/^-?\d+(\.\d+)?(?:[mMfFdDlL]|[uU][lL]?|[lL][uU])$/.test(e)) return `${e.replace(/[a-zA-Z]+$/, '')} at first`;
|
|
43
47
|
if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes(e)}" at first`;
|
|
44
48
|
const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/) || e.match(/^(?:[A-Z]\w*)?\.([a-z]\w*)$/); // Swift: .onShelf
|
|
45
49
|
if (en) return `${words(en[1])} at first`;
|
|
@@ -59,10 +63,17 @@ function kindWords(type) {
|
|
|
59
63
|
const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^(?:Array|List|ArrayList|LinkedList|Vec|VecDeque|IList|IEnumerable|ICollection|IReadOnlyList|Collection|Set|HashSet|MutableList|MutableSet|Sequence|Iterable)<(.+)>$|^(.+)\[\]$|^\[\](.+)$/);
|
|
60
64
|
if (list) { const inner = (list[1] || list[2] || list[3] || list[4]).trim(); return `a list of ${kindWords(inner)?.replace(/^an? /, '') ?? inner}s`.replace(/wordss$/, 'words').replace(/ys$/, 'ies').replace(/(yes or no)s$/, '$1 answers'); }
|
|
61
65
|
const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$|^(?:Option|Optional|Nullable)<(.+)>$|^(.+)\?$|^\*(\w+)$/);
|
|
62
|
-
if (opt) { const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7]; return `${kindWords(inner) ??
|
|
66
|
+
if (opt) { const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7]; return `${kindWords(inner) ?? withArticle(inner)}, or nothing`; }
|
|
63
67
|
const map = t.match(/^(?:Map|HashMap|Dictionary|IDictionary|MutableMap|BTreeMap|dict|Dict|Record)[<\[]/) || /^map\[/.test(t);
|
|
64
68
|
if (map) return 'a lookup table';
|
|
65
|
-
return /^[A-Z]/.test(t) ?
|
|
69
|
+
return /^[A-Z]/.test(t) ? withArticle(t) : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** "a" or "an" by the sound of the word: an AgentCheckResult, an Order, a User, an Unknown, a Euro. */
|
|
73
|
+
export function withArticle(w) {
|
|
74
|
+
const t = String(w);
|
|
75
|
+
const an = /^(?:[AEIOaeio]|U(?:n|m|nd|tt|pp)|u(?:n|m)|[FHLMNRSX][A-Z0-9]|[fhlmnrsx](?=[A-Z0-9]))/.test(t) && !/^(?:Eu|eu|Uni|uni|Use|use|Usu|One|one|Ur)/.test(t);
|
|
76
|
+
return `${an ? 'an' : 'a'} ${t}`;
|
|
66
77
|
}
|
|
67
78
|
|
|
68
79
|
/** C: a function belongs to a struct it takes first (`library_late_fee(const Library *lib, …)`) or is named after. */
|
|
@@ -808,6 +819,35 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
808
819
|
const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts, explainedSteps, totalSteps };
|
|
809
820
|
// The whole system: calls that go to another file, HTTP requests to this repo's routes, events to listeners.
|
|
810
821
|
try { linkSystem(model, files); } catch (e) { model.notLinked = [{ file: fileInfo[0]?.path ?? null, line: 1, why: `Calls across files could not be linked: ${e.message}` }]; }
|
|
822
|
+
// Screens: React and Angular components read as what a person sees and does (src/screens.mjs). Listed only when
|
|
823
|
+
// there are some; the function or class behind each one points to it.
|
|
824
|
+
try {
|
|
825
|
+
const screens = readScreens(files, { members });
|
|
826
|
+
if (screens.length) {
|
|
827
|
+
model.screens = screens;
|
|
828
|
+
for (const sc of screens) {
|
|
829
|
+
const m = members.find((x) => x.file === sc.file && x.name === sc.name);
|
|
830
|
+
if (m) { m.screen = sc.id; sc.member = m.id; }
|
|
831
|
+
const t = things.find((x) => x.file === sc.file && x.name === sc.name);
|
|
832
|
+
if (t) { t.screen = sc.id; sc.thing = t.id; }
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
} catch (e) { unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Screens could not be read: ${e.message}` }); }
|
|
836
|
+
// Ownership on web routes (src/flow/access.mjs): does a record chosen by the request get limited to the caller?
|
|
837
|
+
// Only for TypeScript/JavaScript routes; each route's member says its verdict in words.
|
|
838
|
+
const routeMembers = members.filter((m) => m.route && /^(typescript|javascript)$/i.test(m.language ?? ''));
|
|
839
|
+
if (routeMembers.length) {
|
|
840
|
+
try {
|
|
841
|
+
const access = accessFlow(files.filter((f) => /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(f.path)));
|
|
842
|
+
for (const r of access.routes) {
|
|
843
|
+
if (!r.verdict) continue;
|
|
844
|
+
const m = routeMembers.find((x) => x.file === r.file && x.route === `${r.method} ${r.path}`)
|
|
845
|
+
?? routeMembers.find((x) => x.file === r.file && Math.abs((x.lines?.[0] ?? 0) - r.line) <= 2);
|
|
846
|
+
if (m) m.ownership = { verdict: r.verdict, says: ownershipWords(r), why: r.why, paths: r.paths };
|
|
847
|
+
}
|
|
848
|
+
model.access = { schema: access.schema, summary: access.summary };
|
|
849
|
+
} catch (e) { unknowns.push({ file: fileInfo[0]?.path ?? null, line: 1, why: `Ownership on routes could not be checked: ${e.message}` }); }
|
|
850
|
+
}
|
|
811
851
|
return model;
|
|
812
852
|
}
|
|
813
853
|
|
|
@@ -853,6 +893,8 @@ function flowLines(flow, depth = 1, note = null, full = false) {
|
|
|
853
893
|
* cannot disagree. Pass the model and an id.
|
|
854
894
|
*/
|
|
855
895
|
export function modelText(model, id, { note = null, full = false } = {}) {
|
|
896
|
+
const sc = (model.screens ?? []).find((x) => x.id === id);
|
|
897
|
+
if (sc) return screenText(sc);
|
|
856
898
|
const t = model.things.find((x) => x.id === id);
|
|
857
899
|
if (t) {
|
|
858
900
|
const lines = [t.kind === 'resource' ? `Resource ${t.label} (${t.resourceType})` : `${t.kind === 'thing' ? 'Thing' : t.kind === 'record' ? 'Record' : 'Choices'} ${t.label}`];
|
|
@@ -869,6 +911,7 @@ export function modelText(model, id, { note = null, full = false } = {}) {
|
|
|
869
911
|
const lines = [`${m.label}${owner && m.kind !== 'setup' ? ` (${owner.label})` : ''}${m.kind === 'rule' ? ': a rule' : ''}`];
|
|
870
912
|
if (m.when) lines.push(` ${m.when}`);
|
|
871
913
|
else if (m.route) lines.push(` When someone calls ${m.route}`);
|
|
914
|
+
if (m.ownership) lines.push(` ${m.ownership.says}`);
|
|
872
915
|
if (m.doc) lines.push(` Author's note: ${m.doc}`);
|
|
873
916
|
if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(', ')}`);
|
|
874
917
|
if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
|
|
@@ -878,7 +921,7 @@ export function modelText(model, id, { note = null, full = false } = {}) {
|
|
|
878
921
|
|
|
879
922
|
// ── The five reading levels: what each one shows, decided here so every product shows the same thing ─────────
|
|
880
923
|
|
|
881
|
-
const SYMBOL_OF = { action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices', pipeline: 'action', 'image-build': 'steps', resource: 'resource' };
|
|
924
|
+
const SYMBOL_OF = { screen: 'screen', action: 'action', rule: 'rule', steps: 'steps', setup: 'setup', 'not-read': 'not-read', thing: 'thing', record: 'record', choices: 'choices', pipeline: 'action', 'image-build': 'steps', resource: 'resource' };
|
|
882
925
|
|
|
883
926
|
const SETTING_WORDS = { parameter: 'given when it starts or is built', variable: 'a variable kept outside the file', secret: 'a secret (only its name is shown)', literal: 'written in the file', computed: 'worked out when it runs' };
|
|
884
927
|
const APPLIED_WORDS = { parameter: 'given when it is applied', computed: 'worked out when it is applied' };
|
|
@@ -1036,6 +1079,17 @@ function detailsFacts(model, member) {
|
|
|
1036
1079
|
return { inputs, changes, stops, givesBack, reliesOn, ...(answers ? { answers } : {}), ...(limits ? { limits } : {}), openQuestions };
|
|
1037
1080
|
}
|
|
1038
1081
|
|
|
1082
|
+
/** One reading level of a screen (a React or Angular component): the same five levels as any member. */
|
|
1083
|
+
function screenLevel(lv, sc, model) {
|
|
1084
|
+
const base = { level: lv.id, name: lv.name, question: lv.question };
|
|
1085
|
+
const about = { scope: 'screen', id: sc.id, title: sc.label, symbol: 'screen', file: sc.file, lines: sc.lines, framework: sc.framework, ...(sc.selector ? { selector: sc.selector } : {}) };
|
|
1086
|
+
if (lv.id === 'big-picture') return { ...base, ...about, inputs: sc.inputs, state: sc.state, outputs: sc.outputs, ...(sc.services ? { services: sc.services } : {}), uses: sc.uses, usedBy: sc.usedBy ?? [], events: sc.events.length, notRead: sc.notRead.length };
|
|
1087
|
+
if (lv.id === 'flow') return { ...base, ...about, shows: sc.shows, ...(sc.early ? { early: sc.early } : {}) };
|
|
1088
|
+
if (lv.id === 'details') return { ...base, ...about, inputs: sc.inputs, state: sc.state, events: sc.events, effects: sc.effects, outputs: sc.outputs, notRead: sc.notRead, source: 'Read from code by the Thunder compiler, with no AI.' };
|
|
1089
|
+
if (lv.id === 'text') return { ...base, ...about, text: screenText(sc) };
|
|
1090
|
+
return { ...base, ...about, language: model.files.find((f) => f.path === sc.file)?.language ?? null, ...(sc.template ? { template: sc.template } : {}) };
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1039
1093
|
/**
|
|
1040
1094
|
* What one reading level shows: `level` is a LEVELS id (big-picture, flow, details, text, original); `focus` is a
|
|
1041
1095
|
* Thing or member id, or nothing for the whole model. Flow and Details need an action or rule; without one they
|
|
@@ -1044,6 +1098,8 @@ function detailsFacts(model, member) {
|
|
|
1044
1098
|
export function readLevel(model, level, focus, { full = false } = {}) {
|
|
1045
1099
|
const lv = LEVELS.find((l) => l.id === level);
|
|
1046
1100
|
if (!lv) throw new Error(`Unknown reading level "${level}". Use one of: ${LEVELS.map((l) => l.id).join(', ')}.`);
|
|
1101
|
+
const screen = focus ? (model.screens ?? []).find((x) => x.id === focus) : undefined;
|
|
1102
|
+
if (screen) return screenLevel(lv, screen, model);
|
|
1047
1103
|
const member = focus ? model.members.find((m) => m.id === focus) : undefined;
|
|
1048
1104
|
const thing = focus && !member ? model.things.find((t) => t.id === focus) : undefined;
|
|
1049
1105
|
if (focus && !member && !thing) throw new Error(`Nothing in this model has the id "${focus}".`);
|
|
@@ -1062,30 +1118,35 @@ export function readLevel(model, level, focus, { full = false } = {}) {
|
|
|
1062
1118
|
|
|
1063
1119
|
if (!member && (lv.id === 'flow' || lv.id === 'details')) {
|
|
1064
1120
|
const inScope = model.members.filter((m) => m.kind !== 'setup' && (!thing || m.owner === thing.id));
|
|
1065
|
-
|
|
1121
|
+
const screens = thing ? [] : (model.screens ?? []).map((x) => ({ id: x.id, label: x.label, symbol: 'screen' }));
|
|
1122
|
+
return { ...base, ...about, needsFocus: true, says: `${lv.name} shows one ${screens.length ? 'screen, action, or rule' : 'action or rule'}. Choose one.`, choose: [...screens, ...inScope.filter((m) => !m.screen).map(short)] };
|
|
1066
1123
|
}
|
|
1067
1124
|
if (lv.id === 'big-picture') {
|
|
1068
1125
|
if (member) {
|
|
1069
1126
|
return { ...base, ...about, ...(member.route ? { route: member.route } : {}), ...(member.doc ? { doc: member.doc } : {}),
|
|
1070
1127
|
...(owner ? { owner: { id: owner.id, label: owner.label } } : {}), youGive: member.youGive, ...(member.youGetBack ? { youGetBack: member.youGetBack } : {}), uses, usedBy };
|
|
1071
1128
|
}
|
|
1072
|
-
|
|
1129
|
+
// (A screen's function or class is listed once, as the screen.)
|
|
1130
|
+
const inScope = (m) => m.kind !== 'setup' && (thing ? m.owner === thing.id : !m.screen);
|
|
1073
1131
|
const resourceCard = (t) => ({ id: t.id, label: t.label, symbol: 'resource', resourceType: t.resourceType, address: t.address, file: t.file,
|
|
1074
1132
|
knows: t.knows.map((k) => ({ label: k.label, value: k.kind, ...(k.computed ? { computed: true } : {}), ...(k.secret ? { secret: true } : {}), line: k.line })),
|
|
1075
1133
|
links: (model.links || []).filter((l) => l.from === t.id || l.to === t.id).map((l) => ({ from: l.from, to: l.to, kind: l.kind, ...(l.line ? { line: l.line } : {}) })) });
|
|
1076
1134
|
const resource = thing?.kind === 'resource' ? thing : null;
|
|
1077
1135
|
const thingCard = (t) => ({ id: t.id, label: t.label, ...(t.doc ? { doc: t.doc } : {}), knows: t.knows.map((k) => ({ label: k.label, ...(k.start ? { start: k.start } : {}) })), can: model.members.filter((m) => m.owner === t.id && m.kind !== 'setup' && !m.callback).map(short) });
|
|
1078
1136
|
return { ...base, ...about,
|
|
1079
|
-
|
|
1080
|
-
|
|
1137
|
+
// (A file's own description describes that file: the whole app takes one only when it is one file.)
|
|
1138
|
+
...((() => { const p = thing ? (thing.doc ?? model.files.find((f) => f.path === thing.file)?.purpose) : model.files.length === 1 ? model.files[0]?.purpose : null; return p ? { purpose: p } : {}; })()),
|
|
1139
|
+
things: (resource ? [] : thing ? [thing] : model.things.filter((t) => t.kind === 'thing' && !t.screen)).map(thingCard),
|
|
1081
1140
|
resources: (resource ? [resource] : thing ? [] : model.things.filter((t) => t.kind === 'resource')).map(resourceCard),
|
|
1082
1141
|
...(thing ? {} : { permissions: model.permissions ?? [], settings: model.settings ?? [], facts: model.facts ?? [] }),
|
|
1083
1142
|
data: thing ? [] : model.things.filter((t) => t.kind !== 'thing' && t.kind !== 'resource').map((t) => ({ id: t.id, label: t.label, symbol: SYMBOL_OF[t.kind], ...(t.choices.length ? { choices: t.choices } : {}), knows: t.knows.map((k) => k.label) })),
|
|
1084
1143
|
actions: model.members.filter((m) => inScope(m) && m.kind === 'action').map(short),
|
|
1085
1144
|
rules: model.members.filter((m) => inScope(m) && m.kind === 'rule').map(short),
|
|
1086
1145
|
// (A callback is reached from the step that passes it, not listed on its own.)
|
|
1087
|
-
loose: thing ? [] : model.members.filter((m) => !m.owner && !m.callback && m.kind !== 'setup' && m.kind !== 'action' && m.kind !== 'rule').map(short),
|
|
1146
|
+
loose: thing ? [] : model.members.filter((m) => !m.owner && !m.callback && !m.screen && m.kind !== 'setup' && m.kind !== 'action' && m.kind !== 'rule').map(short),
|
|
1088
1147
|
unknowns: thing ? [] : model.unknowns,
|
|
1148
|
+
// The app's screens (React and Angular components), and the screens and components each one shows.
|
|
1149
|
+
...(!thing && model.screens?.length ? { screens: [...model.screens].sort((x, y) => ['page', 'top', 'part'].indexOf(x.role) - ['page', 'top', 'part'].indexOf(y.role)).map((x) => ({ id: x.id, label: x.label, framework: x.framework, file: x.file, ...(x.selector ? { selector: x.selector } : {}), ...(x.role ? { role: x.role } : {}), uses: x.uses.map((u) => u.label) })) } : {}),
|
|
1089
1150
|
// The app's map: which areas (folders) call which, and send requests or events to which.
|
|
1090
1151
|
...(thing ? {} : { calls: callsSummary(model), notLinked: model.notLinked ?? [] }) };
|
|
1091
1152
|
}
|
|
@@ -1097,13 +1158,15 @@ export function readLevel(model, level, focus, { full = false } = {}) {
|
|
|
1097
1158
|
// Calls and requests worth linking that could not be, with the reason (never guessed).
|
|
1098
1159
|
notLinked: (model.notLinked ?? []).filter((x) => x.from === member.id),
|
|
1099
1160
|
notExplained: steps.filter((s) => s.notExplained).length, uses, usedBy, tryable: !!member.rule, ...(member.rule ? { rule: member.rule } : {}),
|
|
1161
|
+
...(member.ownership ? { ownership: member.ownership } : {}),
|
|
1100
1162
|
source: 'Read from code by the Thunder compiler, with no AI.' };
|
|
1101
1163
|
}
|
|
1102
1164
|
if (lv.id === 'text') {
|
|
1103
1165
|
const extra = [];
|
|
1104
1166
|
if (!focus && model.permissions?.length) extra.push(`Permissions\n${model.permissions.map((p) => ` ${p.says ?? `${p.who} can ${p.can} ${p.on}`}${p.wide && !/\(wide\)/.test(p.says ?? '') ? ' (wide)' : ''} (line ${p.line})`).join('\n')}\n`);
|
|
1105
1167
|
if (!focus && model.settings?.length) extra.push(`Settings\n${model.settings.map((x) => ` Setting ${x.name}: ${settingWords(x, model)} (line ${x.line})`).join('\n')}\n`);
|
|
1106
|
-
|
|
1168
|
+
// The whole app: its screens first (as screens, not as the classes behind them), then everything else.
|
|
1169
|
+
const text = focus ? modelText(model, focus, { full }) : [...(model.screens ?? []).map((sc) => screenText(sc)), ...model.things.filter((t) => !t.screen).map((t) => modelText(model, t.id)), ...model.members.filter((m) => !m.owner && m.kind !== 'setup' && !m.screen).map((m) => modelText(model, m.id, { full })), ...extra].join('\n');
|
|
1107
1170
|
return { ...base, ...about, text };
|
|
1108
1171
|
}
|
|
1109
1172
|
return { ...base, ...about, language: (member ?? thing) ? (member?.language ?? model.files.find((f) => f.path === thing.file)?.language ?? null) : (model.files[0]?.language ?? null) };
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// thunder passport: the command line for the Thunder Software Passport (passport.mjs, passport-fs.mjs, docs/passport.md).
|
|
2
|
+
// thunder passport <folder…> [--base REV] [--head REV] [--run "cmd" | --run "part: cmd" …] [--purpose "…" | --purpose-file f]
|
|
3
|
+
// [--evidence f.json …] [--json | --md] [--out file] [--md-out file.md]
|
|
4
|
+
// thunder passport check <passport.json> [--part name=folder …] [--json]
|
|
5
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { dirname, resolve } from 'node:path';
|
|
7
|
+
import { buildPassport, checkPassportOnDisk } from './passport-fs.mjs';
|
|
8
|
+
import { renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
|
|
9
|
+
import { paint, useColor } from './term.mjs';
|
|
10
|
+
|
|
11
|
+
const USAGE = `usage: thunder passport <folder…> [--base REV] [--run "cmd" | --run "part: cmd" …] [--purpose "…" | --purpose-file f]
|
|
12
|
+
[--evidence result.json …] [--no-access] [--json | --md] [--out passport.json] [--md-out passport.md]
|
|
13
|
+
thunder passport check <passport.json> [--part name=folder …] [--json]
|
|
14
|
+
A passport records what is known about a feature or a change: its behavior, what it depends on and changes, the
|
|
15
|
+
evidence for each claim (with what it does not cover), and what is not verified. When this build has the ownership
|
|
16
|
+
check (thunder read --access), its verdicts join as evidence (--no-access leaves them out). Only git and the commands you pass
|
|
17
|
+
with --run are executed. Exit codes: 0 built, 1 a --run command failed (still recorded), 2 usage.`;
|
|
18
|
+
|
|
19
|
+
const say = (s) => console.log(paint(s, useColor()));
|
|
20
|
+
|
|
21
|
+
/** The ownership check (src/flow/access.mjs), when this build has it; null otherwise. */
|
|
22
|
+
async function loadAccess() {
|
|
23
|
+
try { const m = await import('./flow/access.mjs'); return typeof m.accessFlow === 'function' ? m.accessFlow : null; } catch { return null; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function passportMain(argv) {
|
|
27
|
+
if (argv[0] === 'check') return checkMain(argv.slice(1));
|
|
28
|
+
const a = { _: [], base: null, head: null, run: [], purpose: null, purposeFile: null, evidence: [], json: false, md: false, out: null, mdOut: null, access: true };
|
|
29
|
+
for (let i = 0; i < argv.length; i++) {
|
|
30
|
+
const x = argv[i];
|
|
31
|
+
const need = () => { const v = argv[++i]; if (v == null) throw new Error(`${x} needs a value.`); return v; };
|
|
32
|
+
try {
|
|
33
|
+
if (x === '--base') a.base = need();
|
|
34
|
+
else if (x === '--head') a.head = need();
|
|
35
|
+
else if (x === '--run') a.run.push(need());
|
|
36
|
+
else if (x === '--purpose') a.purpose = need();
|
|
37
|
+
else if (x === '--purpose-file') a.purposeFile = need();
|
|
38
|
+
else if (x === '--evidence') a.evidence.push(need());
|
|
39
|
+
else if (x === '--json') a.json = true;
|
|
40
|
+
else if (x === '--no-access') a.access = false;
|
|
41
|
+
else if (x === '--md') a.md = true;
|
|
42
|
+
else if (x === '--out') a.out = need();
|
|
43
|
+
else if (x === '--md-out') a.mdOut = need();
|
|
44
|
+
else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
|
|
45
|
+
else if (x.startsWith('--')) { console.error(`thunder passport: there is no option ${x}.\n${USAGE}`); return 2; }
|
|
46
|
+
else a._.push(x);
|
|
47
|
+
} catch (e) { console.error(`thunder passport: ${e.message}\n${USAGE}`); return 2; }
|
|
48
|
+
}
|
|
49
|
+
if (!a._.length) { console.error(`thunder passport: name the folders it describes (each one part, as for thunder trace).\n${USAGE}`); return 2; }
|
|
50
|
+
if (a.json && a.md) { console.error('thunder passport: choose --json or --md, not both.'); return 2; }
|
|
51
|
+
let purpose = null;
|
|
52
|
+
if (a.purposeFile) {
|
|
53
|
+
try { purpose = { text: readFileSync(a.purposeFile, 'utf8').trim().slice(0, 4000), source: a.purposeFile }; } catch { console.error(`thunder passport: couldn't read ${a.purposeFile}.`); return 2; }
|
|
54
|
+
} else if (a.purpose) purpose = { text: a.purpose, source: 'given with --purpose' };
|
|
55
|
+
const evidence = [];
|
|
56
|
+
for (const f of a.evidence) {
|
|
57
|
+
try { evidence.push(JSON.parse(readFileSync(f, 'utf8'))); } catch { console.error(`thunder passport: ${f} is not a JSON file Thunder can read.`); return 2; }
|
|
58
|
+
}
|
|
59
|
+
const relativeTo = a.out ? dirname(resolve(a.out)) : process.cwd();
|
|
60
|
+
let p;
|
|
61
|
+
const access = a.access ? await loadAccess() : null;
|
|
62
|
+
try { p = buildPassport({ parts: a._, base: a.base, head: a.head, run: a.run, purpose, evidence, access, relativeTo }); }
|
|
63
|
+
catch (e) { console.error(`thunder passport: ${e.message}`); return 2; }
|
|
64
|
+
if (a.mdOut) writeFileSync(a.mdOut, renderPassportMarkdown(p));
|
|
65
|
+
const failed = p.evidence.some((e) => e.kind === 'test-run' && e.status === 'failed');
|
|
66
|
+
const text = a.md ? renderPassportMarkdown(p) : `${JSON.stringify(p, null, 2)}\n`;
|
|
67
|
+
if (a.out) {
|
|
68
|
+
writeFileSync(a.out, a.md ? text : `${JSON.stringify(p, null, 2)}\n`);
|
|
69
|
+
if (!a.json) { say(renderPassportSummary(p)); say(`\nWrote ${a.out}. Check it later with: thunder passport check ${a.out}`); }
|
|
70
|
+
} else if (a.json) process.stdout.write(text);
|
|
71
|
+
else if (a.md) process.stdout.write(text);
|
|
72
|
+
else say(renderPassportSummary(p));
|
|
73
|
+
return failed ? 1 : 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function checkMain(argv) {
|
|
77
|
+
const a = { _: [], json: false, dirs: {} };
|
|
78
|
+
for (let i = 0; i < argv.length; i++) {
|
|
79
|
+
const x = argv[i];
|
|
80
|
+
if (x === '--json') a.json = true;
|
|
81
|
+
else if (x === '--part') { const m = String(argv[++i] ?? '').match(/^([^=]+)=(.+)$/); if (!m) { console.error('thunder passport check: --part needs name=folder.'); return 2; } a.dirs[m[1]] = m[2]; }
|
|
82
|
+
else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
|
|
83
|
+
else if (x.startsWith('--')) { console.error(`thunder passport check: there is no option ${x}.\n${USAGE}`); return 2; }
|
|
84
|
+
else a._.push(x);
|
|
85
|
+
}
|
|
86
|
+
if (a._.length !== 1) { console.error(`thunder passport check: name one passport file.\n${USAGE}`); return 2; }
|
|
87
|
+
let p;
|
|
88
|
+
try { p = JSON.parse(readFileSync(a._[0], 'utf8')); } catch { console.error(`thunder passport check: couldn't read ${a._[0]} as a passport.`); return 2; }
|
|
89
|
+
let r;
|
|
90
|
+
try { r = checkPassportOnDisk(p, { baseDir: dirname(resolve(a._[0])), dirs: a.dirs }); } catch (e) { console.error(`thunder passport check: ${e.message}`); return 2; }
|
|
91
|
+
if (a.json) { console.log(JSON.stringify(r, null, 2)); return 0; }
|
|
92
|
+
const L = [`Thunder passport check: ${r.current} current, ${r.stale} stale (nothing was re-run)`, ''];
|
|
93
|
+
for (const x of r.items) {
|
|
94
|
+
L.push(` ${x.freshness === 'current' ? '✓ current' : x.freshness === 'stale' ? '! stale' : '○ unknown'}: ${x.claim}`);
|
|
95
|
+
for (const c of x.changed) L.push(` ${c.part}/${c.file} ${c.now === 'missing' ? 'is gone' : 'changed since the passport was built'}`);
|
|
96
|
+
}
|
|
97
|
+
if (r.changedFiles.length) L.push('', `Files that changed since the passport was built: ${r.changedFiles.map((c) => `${c.part}/${c.file}${c.now === 'missing' ? ' (gone)' : ''}`).join(', ')}`);
|
|
98
|
+
if (r.stale) L.push('', 'Stale claims are not evidence about the code as it is now. Build a new passport to re-run them.');
|
|
99
|
+
say(L.join('\n'));
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Passport, PassportCheck, PassportEvidence } from './passport.mjs';
|
|
2
|
+
export function buildPassport(options: {
|
|
3
|
+
parts: string[]; base?: string | null; head?: string | null; run?: string[];
|
|
4
|
+
purpose?: { text: string; source?: string } | null; evidence?: unknown[];
|
|
5
|
+
/** The ownership check (accessFlow from src/flow/access.mjs), run per part when given. */
|
|
6
|
+
access?: ((files: Array<{ path: string; source: string }>) => unknown) | null; relativeTo?: string; builtAt?: string; timeoutMs?: number;
|
|
7
|
+
}): Passport;
|
|
8
|
+
export function checkPassportOnDisk(passport: Passport, options?: { baseDir?: string; dirs?: Record<string, string> }): PassportCheck;
|
|
9
|
+
export function accessEvidence(report: unknown, partOf?: (file: string) => string | null): Array<Omit<PassportEvidence, 'id'>>;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Thunder Software Passport, the Node side: read the parts (folders or repositories), what changed since a base
|
|
2
|
+
// commit, run the test commands you name, and hand everything to assemblePassport (passport.mjs, pure).
|
|
3
|
+
// Only git and the commands you pass with `run` are executed; nothing else is run, fetched, or sent anywhere.
|
|
4
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
5
|
+
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
|
6
|
+
import { basename, join, resolve, relative } from 'node:path';
|
|
7
|
+
import { collectReadableFiles } from './read-repo-fs.mjs';
|
|
8
|
+
import { assemblePassport, checkPassport } from './passport.mjs';
|
|
9
|
+
import { COMPILER_VERSION } from './emit.mjs';
|
|
10
|
+
|
|
11
|
+
const git = (dir, args) => {
|
|
12
|
+
try { return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024 }); } catch { return null; }
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const SKIP = new Set(['node_modules', '.git', 'bin', 'obj', 'dist', 'build', '__pycache__', '.venv', 'venv', 'target', '.next']);
|
|
16
|
+
|
|
17
|
+
/** Packages a part declares: package.json dependencies, requirements.txt, and .csproj PackageReference. */
|
|
18
|
+
function packagesIn(root) {
|
|
19
|
+
const out = [];
|
|
20
|
+
const walk = (dir, depth) => {
|
|
21
|
+
if (depth > 4) return;
|
|
22
|
+
let names = [];
|
|
23
|
+
try { names = readdirSync(dir).sort(); } catch { return; }
|
|
24
|
+
for (const n of names) {
|
|
25
|
+
if (SKIP.has(n)) continue;
|
|
26
|
+
const full = join(dir, n);
|
|
27
|
+
let st;
|
|
28
|
+
try { st = statSync(full); } catch { continue; }
|
|
29
|
+
if (st.isDirectory()) { walk(full, depth + 1); continue; }
|
|
30
|
+
const rel = relative(root, full).split('\\').join('/');
|
|
31
|
+
try {
|
|
32
|
+
if (n === 'package.json') {
|
|
33
|
+
const j = JSON.parse(readFileSync(full, 'utf8'));
|
|
34
|
+
for (const k of ['dependencies', 'devDependencies']) for (const [name, version] of Object.entries(j[k] ?? {})) out.push({ name, version: String(version), from: rel, ...(k === 'devDependencies' ? { dev: true } : {}) });
|
|
35
|
+
} else if (n === 'requirements.txt') {
|
|
36
|
+
for (const line of readFileSync(full, 'utf8').split('\n')) {
|
|
37
|
+
const m = line.replace(/#.*/, '').trim().match(/^([A-Za-z0-9_.-]+)\s*(.*)$/);
|
|
38
|
+
if (m) out.push({ name: m[1], ...(m[2] ? { version: m[2] } : {}), from: rel });
|
|
39
|
+
}
|
|
40
|
+
} else if (/\.csproj$/.test(n)) {
|
|
41
|
+
for (const m of readFileSync(full, 'utf8').matchAll(/<PackageReference\s+Include="([^"]+)"(?:\s+Version="([^"]+)")?/g)) out.push({ name: m[1], ...(m[2] ? { version: m[2] } : {}), from: rel });
|
|
42
|
+
}
|
|
43
|
+
} catch { /* a manifest Thunder cannot parse is not a package list */ }
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
walk(root, 0);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** What changed in one part since `base` (committed and not), with each changed file's base version. */
|
|
51
|
+
function changesSince(root, base) {
|
|
52
|
+
const prefix = git(root, ['rev-parse', '--show-prefix'])?.trim() ?? '';
|
|
53
|
+
const diff = git(root, ['diff', '--unified=0', '--no-color', '--no-renames', base, '--', '.']) ?? '';
|
|
54
|
+
const byFile = new Map();
|
|
55
|
+
let cur = null;
|
|
56
|
+
for (const line of diff.split('\n')) {
|
|
57
|
+
let m;
|
|
58
|
+
if ((m = line.match(/^diff --git a\/(.+) b\/(.+)$/))) { cur = { file: m[2], ranges: [], status: 'changed' }; byFile.set(cur.file, cur); }
|
|
59
|
+
else if (cur && line.startsWith('new file mode')) cur.status = 'added';
|
|
60
|
+
else if (cur && line.startsWith('deleted file mode')) cur.status = 'removed';
|
|
61
|
+
else if (cur && (m = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/))) {
|
|
62
|
+
const start = Number(m[1]), n = m[2] === undefined ? 1 : Number(m[2]);
|
|
63
|
+
cur.ranges.push(n === 0 ? [Math.max(1, start), Math.max(1, start)] : [start, start + n - 1]);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
for (const f of (git(root, ['ls-files', '--others', '--exclude-standard', '--', '.']) ?? '').split('\n').filter(Boolean)) {
|
|
67
|
+
const file = prefix + f;
|
|
68
|
+
if (!byFile.has(file)) byFile.set(file, { file, ranges: [], status: 'added' });
|
|
69
|
+
}
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const c of byFile.values()) {
|
|
72
|
+
if (!c.file.startsWith(prefix)) continue;
|
|
73
|
+
const old = c.status === 'added' ? null : git(root, ['show', `${base}:${c.file}`]);
|
|
74
|
+
out.push({ file: c.file.slice(prefix.length), status: c.status, ranges: c.ranges, old: old == null || old.includes('\0') ? null : old });
|
|
75
|
+
}
|
|
76
|
+
return out.sort((a, b) => a.file.localeCompare(b.file));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Evidence items from a thunder-access-v1 report (the ownership check, src/flow/access.mjs, when present). One item
|
|
81
|
+
* per route that has a verdict. `partOf(file)` names the part a file is in when the report does not say.
|
|
82
|
+
*/
|
|
83
|
+
export function accessEvidence(report, partOf = () => null) {
|
|
84
|
+
const words = { guarded: 'checks that the record belongs to the caller on every path', unguarded: 'has a path with no ownership check (every step was followed)', 'cannot tell': 'cannot be told: Thunder could not follow every step', 'cannot-tell': 'cannot be told: Thunder could not follow every step' };
|
|
85
|
+
return (report?.routes ?? []).filter((r) => r.verdict).map((r) => {
|
|
86
|
+
const part = r.part ?? partOf(r.file);
|
|
87
|
+
const files = [...new Set([r.file, ...(r.paths ?? []).flatMap((x) => (x.steps ?? []).map((st) => st.file))].filter(Boolean))];
|
|
88
|
+
return {
|
|
89
|
+
kind: 'access-flow', status: 'read',
|
|
90
|
+
claim: `${r.method && r.path ? `${r.method} ${r.path}` : r.route ?? 'A route'}${part ? ` in ${part}` : ''} ${words[r.verdict] ?? `has the verdict "${r.verdict}"`}.`,
|
|
91
|
+
basis: { schema: report.schema ?? 'thunder-access-v1', verdict: r.verdict, at: r.file ? `${part ? `${part}:` : ''}${r.file}${r.line ? `:${r.line}` : ''}` : null, why: r.why ?? null },
|
|
92
|
+
scope: 'Read from code by the ownership check; nothing was run. Only the frameworks and data libraries it supports, and only these files.',
|
|
93
|
+
inputs: part ? files.map((file) => ({ part, file })) : [],
|
|
94
|
+
};
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Build a passport from folders on disk.
|
|
100
|
+
* parts: folder paths (each one part, named by its folder, as Thunder Trace takes them)
|
|
101
|
+
* base: a commit to compare with (a change); none for a snapshot
|
|
102
|
+
* head: must be the checked-out commit when given (the passport reads the files on disk)
|
|
103
|
+
* run: commands to run and record; "billing: python3 -m unittest" runs in the part named billing
|
|
104
|
+
* purpose: { text, source } (from --purpose or --purpose-file); never invented
|
|
105
|
+
* evidence: extra evidence (parsed JSON: a thunder-access-v1 result, or a list of evidence items)
|
|
106
|
+
* relativeTo: where part paths are recorded from (the passport's folder, so `check` finds them later)
|
|
107
|
+
*/
|
|
108
|
+
export function buildPassport({ parts, base = null, head = null, run = [], purpose = null, evidence = [], access = null, relativeTo = process.cwd(), builtAt, timeoutMs = 20 * 60 * 1000 } = {}) {
|
|
109
|
+
if (!parts?.length) throw new Error('name at least one folder to describe.');
|
|
110
|
+
const names = new Set();
|
|
111
|
+
const read = parts.map((dir) => {
|
|
112
|
+
const root = resolve(dir);
|
|
113
|
+
let ok = false;
|
|
114
|
+
try { ok = statSync(root).isDirectory(); } catch { /* missing */ }
|
|
115
|
+
if (!ok) throw new Error(`${dir} is not a folder.`);
|
|
116
|
+
const name = basename(root);
|
|
117
|
+
if (names.has(name)) throw new Error(`two parts are called "${name}"; give folders with different names.`);
|
|
118
|
+
names.add(name);
|
|
119
|
+
const top = git(root, ['rev-parse', '--show-toplevel'])?.trim() ?? null;
|
|
120
|
+
const sha = top ? git(root, ['rev-parse', 'HEAD'])?.trim() || null : null;
|
|
121
|
+
const dirty = top ? !!git(root, ['status', '--porcelain', '--', '.'])?.trim() : false;
|
|
122
|
+
if (head && top) {
|
|
123
|
+
const want = git(root, ['rev-parse', '--verify', `${head}^{commit}`])?.trim();
|
|
124
|
+
if (!want) throw new Error(`${head} is not a commit in ${dir}.`);
|
|
125
|
+
if (want !== sha) throw new Error(`the passport reads the files on disk, and ${dir} is not at ${head}. Check out ${head} first.`);
|
|
126
|
+
}
|
|
127
|
+
let changes;
|
|
128
|
+
if (base) {
|
|
129
|
+
if (!top) throw new Error(`${dir} is not in a git repository, so there is no ${base} to compare with.`);
|
|
130
|
+
if (!git(root, ['rev-parse', '--verify', `${base}^{commit}`])?.trim()) throw new Error(`${base} is not a commit in ${dir}.`);
|
|
131
|
+
changes = changesSince(root, base);
|
|
132
|
+
}
|
|
133
|
+
const files = collectReadableFiles(root).map((f) => ({ path: f.path, source: f.source }));
|
|
134
|
+
return { name, root, path: relative(relativeTo, root).split('\\').join('/') || '.', sha, dirty, files, packages: packagesIn(root), ...(changes ? { changes } : {}) };
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
const runs = run.map((spec) => {
|
|
138
|
+
const m = String(spec).match(/^([A-Za-z0-9_.-]+):\s+(.+)$/);
|
|
139
|
+
const part = m && read.find((p) => p.name === m[1]) ? m[1] : null;
|
|
140
|
+
const command = part ? m[2] : String(spec);
|
|
141
|
+
const cwd = part ? read.find((p) => p.name === part).root : process.cwd();
|
|
142
|
+
const r = spawnSync(`(${command}) 2>&1`, { shell: true, cwd, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 });
|
|
143
|
+
const exitCode = r.status ?? (r.error || r.signal ? 1 : 0);
|
|
144
|
+
const output = `${r.stdout ?? ''}${r.error ? `\n(${r.error.message})` : ''}${r.signal ? `\n(stopped by ${r.signal})` : ''}`;
|
|
145
|
+
return { command, part, cwd: relative(relativeTo, cwd).split('\\').join('/') || '.', exitCode, output };
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
const extra = [];
|
|
149
|
+
// A file path names its part when exactly one part has it.
|
|
150
|
+
const partOf = (file) => { const hits = read.filter((p) => p.files.some((f) => f.path === file)); return hits.length === 1 ? hits[0].name : null; };
|
|
151
|
+
// The ownership check, when given (the CLI passes accessFlow when src/flow/access.mjs is there): run per part.
|
|
152
|
+
if (typeof access === 'function') {
|
|
153
|
+
for (const p of read) {
|
|
154
|
+
try { extra.push(...accessEvidence(access(p.files), () => p.name)); } catch { /* a part the check cannot read adds no evidence */ }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
for (const e of evidence) {
|
|
158
|
+
if (e?.schema === 'thunder-access-v1') extra.push(...accessEvidence(e, partOf));
|
|
159
|
+
else if (Array.isArray(e)) extra.push(...e.filter((x) => x && x.kind && x.claim && x.basis && x.scope).map((x) => ({ status: 'read', ...x })));
|
|
160
|
+
}
|
|
161
|
+
const change = base ? { base: git(read[0].root, ['rev-parse', base])?.trim() ?? base, head: head ? read[0].sha : read[0].sha ? `${read[0].sha}${read.some((p) => p.dirty) ? ' (with uncommitted changes)' : ''}` : null } : null;
|
|
162
|
+
return assemblePassport({ parts: read, change, runs, purpose, extra, builtAt, thunder: COMPILER_VERSION });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Check a passport against the files on disk: each evidence item current or stale. Part folders are found from
|
|
167
|
+
* the paths the passport recorded, relative to `baseDir` (the passport's folder), unless `dirs` names them.
|
|
168
|
+
*/
|
|
169
|
+
export function checkPassportOnDisk(passport, { baseDir = process.cwd(), dirs = {} } = {}) {
|
|
170
|
+
const where = new Map(passport.subject.parts.map((p) => [p.name, dirs[p.name] ? resolve(dirs[p.name]) : resolve(baseDir, p.path)]));
|
|
171
|
+
return checkPassport(passport, {
|
|
172
|
+
read: (part, file) => {
|
|
173
|
+
const root = where.get(part);
|
|
174
|
+
if (!root) return null;
|
|
175
|
+
const full = join(root, file);
|
|
176
|
+
try { return existsSync(full) ? readFileSync(full, 'utf8') : null; } catch { return null; }
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|