@skillstech/thunderlang 1.3.0 → 1.4.1

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/src/read.mjs CHANGED
@@ -135,6 +135,27 @@ function matchClose(src, open) {
135
135
  // The language being read. Only Rust has lifetimes ('static, 'a), which look like an opening quote.
136
136
  let READING_RUST = false;
137
137
 
138
+ /** For C# and Java: a flag per character, 1 inside text ("…", $"…", @"…", '…', """…""") or a comment. */
139
+ function textRanges(src) {
140
+ const flags = new Uint8Array(src.length + 1);
141
+ for (let i = 0; i < src.length; i++) {
142
+ const c = src[i];
143
+ if (c === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); const end = e < 0 ? src.length : e; flags.fill(1, i, end); i = end; continue; }
144
+ if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); const end = e < 0 ? src.length : e + 2; flags.fill(1, i, end); i = end - 1; continue; }
145
+ if (c === '"' || c === '\'') {
146
+ let end;
147
+ if (c === '"' && src[i - 1] === '@' || (c === '"' && src[i - 1] === '$' && src[i - 2] === '@')) {
148
+ // A verbatim string: "" is a quote inside it.
149
+ end = i + 1;
150
+ while (end < src.length && !(src[end] === '"' && src[end + 1] !== '"')) end += src[end] === '"' ? 2 : 1;
151
+ } else end = skipString(src, i);
152
+ flags.fill(1, i, Math.min(src.length, end + 1));
153
+ i = end;
154
+ }
155
+ }
156
+ return flags;
157
+ }
158
+
138
159
  function skipString(src, i) {
139
160
  const q = src[i];
140
161
  // A multi-line string (triple quotes in Swift, Kotlin, Java, C#) runs to its closing triple quote.
@@ -338,6 +359,9 @@ function findFunctions(src, language) {
338
359
  patterns.javascript = patterns.typescript;
339
360
  patterns.csharp = [/(?:(?:public|private|protected|internal|static|virtual|override|async|sealed|abstract|readonly)\s+)*[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g];
340
361
  const seen = new Set();
362
+ // C# and Java: words inside text (`$"known bug (fails as expected) {name}"`) are never a method, and neither is a
363
+ // lambda passed as an argument (`Check("…", async () => { … })`).
364
+ const inText = (language === 'csharp' || language === 'java') ? textRanges(src) : null;
341
365
  for (const re of patterns[language] || []) {
342
366
  let m;
343
367
  re.lastIndex = 0;
@@ -345,6 +369,7 @@ function findFunctions(src, language) {
345
369
  const name = m[1];
346
370
  const open = src.indexOf('(', m.index + m[0].length - 1);
347
371
  if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
372
+ if (inText && (inText[m.index + m[0].lastIndexOf(name, m[0].length - 1)] || (language === 'csharp' && name === 'async'))) continue;
348
373
  const close = matchClose(src, open);
349
374
  if (close < 0) continue;
350
375
  // After the parameter list: an optional return type / throws clause, then a body. A signature's head is short,
@@ -419,6 +444,9 @@ function findFunctions(src, language) {
419
444
  ? [/\bRoute::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]\s*,\s*(?:static\s+)?function\s*\(/g]
420
445
  : language === 'go'
421
446
  ? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g]
447
+ : language === 'csharp'
448
+ // ASP.NET minimal APIs: app.MapPost("/orders", async (OrderRequest request, OrderService orders) => { … })
449
+ ? [/\b\w+\.Map(Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"\s*,\s*(?:async\s*)?\(/g]
422
450
  : (language === 'typescript' || language === 'javascript')
423
451
  // (The handler may be wrapped: `fastify.get('/x', handle(async (request) => …))`, `asyncHandler(…)`.)
424
452
  ? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:[A-Za-z_$][\w$.]*(?:<[^<>()]*>)?\(\s*)*(?:async\s*)?(?:function\s*\w*\s*)?\(/g]
@@ -435,7 +463,7 @@ function findFunctions(src, language) {
435
463
  // An arrow whose body is one expression: `async (request) => practiceView(…)`. It gives back that value;
436
464
  // the expression runs to the first ")" or "," that closes the call around it.
437
465
  const arrow = /^\s*(?::\s*[^=()]+)?=>\s*/.exec(src.slice(close + 1));
438
- if (!(language === 'typescript' || language === 'javascript') || !arrow || src[close + 1 + arrow[0].length] === '{') continue;
466
+ if (!(language === 'typescript' || language === 'javascript' || language === 'csharp') || !arrow || src[close + 1 + arrow[0].length] === '{') continue;
439
467
  const from = close + 1 + arrow[0].length;
440
468
  let depth = 0, end = from, q = null;
441
469
  for (; end < src.length; end++) {
@@ -1179,6 +1207,14 @@ function annotateRoutes(fns, src) {
1179
1207
  const above = fn.decorators
1180
1208
  ? [...fn.decorators].reverse()
1181
1209
  : lines.slice(Math.max(0, fn.line - 6), Math.max(0, fn.line - 1)).reverse().map((x) => x.trim());
1210
+ // Python's standard library server: a handler's do_POST answers POST, and the one path it checks
1211
+ // (`if self.path != "/charges": …`) is its route. Two or more paths checked: no single route, so none is named.
1212
+ const std = /^do_(GET|POST|PUT|PATCH|DELETE|HEAD)$/.exec(fn.name ?? '');
1213
+ const stdBody = typeof fn.body === 'string' ? fn.body : Array.isArray(fn.pyBody) ? fn.pyBody.map((x) => x.text).join('\n') : null;
1214
+ if (std && stdBody) {
1215
+ const paths = new Set([...stdBody.matchAll(/\bself\.path\s*(?:==|!=)\s*['"](\/[^'"]*)['"]/g)].map((x) => x[1]));
1216
+ if (paths.size === 1) { fn.route = { method: std[1], path: [...paths][0] }; continue; }
1217
+ }
1182
1218
  for (const l of above) {
1183
1219
  let m;
1184
1220
  if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
@@ -0,0 +1,40 @@
1
+ import type { ThunderModel, Thing, Member } from './model.d.mts';
2
+
3
+ export const READING_LAYOUT_SCHEMA: 'thunder-reading-layout-v1';
4
+ export const READING_LABELS: Readonly<{
5
+ thing: string; knows: string; can: string; starts: (label: string) => string; startsWithKnows: (label: string) => string;
6
+ record: string; choices: string; recordSymbol: string; choicesSymbol: string; things: string; data: string;
7
+ give: string; getBack: string; stops: string; givesNothing: string; getsNothing: string; partOf: (label: string) => string; io: string;
8
+ }>;
9
+ export type ThunderSymbolId = 'app' | 'area' | 'file' | 'thing' | 'data' | 'record' | 'choices' | 'action' | 'rule' | 'steps' | 'setup' | 'stop' | 'not-read' | 'resource' | 'permission';
10
+ export interface KnowsLine { name: string; label: string; detail: string | null; secret?: true; line: number | null }
11
+ export interface ThingCardLayout {
12
+ kind: 'thing'; id: string; label: string; doc: string | null; heading: string; symbol: 'thing';
13
+ knows: { heading: string; items: KnowsLine[] };
14
+ can: { heading: string; items: { id: string; label: string; symbol: ThunderSymbolId }[] };
15
+ /** id: the setup member to open, or null when a new one starts with what it knows. */
16
+ starts: { id: string | null; text: string };
17
+ }
18
+ export interface DataCardLayout {
19
+ kind: 'record' | 'choices'; id: string; label: string; doc: string | null; heading: string;
20
+ symbol: 'record' | 'choices'; symbolLabel: string; choices: string[]; knows: KnowsLine[];
21
+ }
22
+ export interface IOBoxesLayout {
23
+ kind: 'io'; id: string; label: string; doc: string | null; symbol: ThunderSymbolId;
24
+ give: { heading: string; items: { label: string; kind: string | null }[]; empty: string };
25
+ getBack: { heading: string; text: string | null; empty: string };
26
+ stops: { heading: string; items: { text: string; line: number | null }[] };
27
+ /** The Thing it belongs to, to link back to its card. */
28
+ partOf: { id: string; text: string } | null;
29
+ }
30
+ export interface ReadingLayout {
31
+ schema: 'thunder-reading-layout-v1';
32
+ focus: { kind: 'app' | 'file' | 'thing' | 'member' | 'unknown'; id: string | null };
33
+ sections: Array<{ id: 'things'; heading: string; cards: ThingCardLayout[] } | { id: 'data'; heading: string; cards: DataCardLayout[] } | { id: 'io'; heading: string; cards: IOBoxesLayout[] }>;
34
+ }
35
+ export function memberSymbolId(member: { kind: string }): ThunderSymbolId;
36
+ export function thingCard(model: ThunderModel, thing: Thing): ThingCardLayout;
37
+ export function dataCard(thing: Thing): DataCardLayout;
38
+ export function ioBoxes(model: ThunderModel, member: Member): IOBoxesLayout;
39
+ /** The Big Picture, zoomed by focus: none or a file (Things, then records, then choices), a Thing (its card, then its file's Data), or an action/rule (its IO boxes). */
40
+ export function readingLayout(model: ThunderModel, options?: { focus?: string | null }): ReadingLayout;
@@ -0,0 +1,112 @@
1
+ // What a Thunder reading shows, and in what order, as plain data: the words on every card, which list comes first,
2
+ // and what each entry opens. Every app that draws a reading (OpenThunder, thunderlang.dev, the Skills Tech Talk
3
+ // course) draws from this, so the three say the same thing in the same order; the drawing kit
4
+ // (@skillstech/thunderlang/react) only turns it into elements. Pure, deterministic, browser-safe, no React.
5
+
6
+ export const READING_LAYOUT_SCHEMA = 'thunder-reading-layout-v1';
7
+
8
+ /** Every fixed word a reading shows. Change a label here and every app changes with it. */
9
+ export const READING_LABELS = Object.freeze({
10
+ thing: 'A Thing',
11
+ knows: 'It knows',
12
+ can: 'It can',
13
+ starts: (label) => `How a new ${label} starts`,
14
+ startsWithKnows: (label) => `A new ${label} starts with what it knows above`,
15
+ record: 'Data: a record',
16
+ choices: 'Data: choices',
17
+ recordSymbol: 'Record',
18
+ choicesSymbol: 'Choices',
19
+ things: 'Things',
20
+ data: 'Data',
21
+ give: 'You give it',
22
+ getBack: 'You get back',
23
+ stops: 'It can stop with',
24
+ givesNothing: 'Nothing',
25
+ getsNothing: 'Nothing it hands back',
26
+ partOf: (label) => `Part of ${label}`,
27
+ io: 'What goes in and out',
28
+ });
29
+
30
+ /** The symbol (thunder-visual-v1) for a member, as every view draws it. */
31
+ export const memberSymbolId = (m) => (m.kind === 'action' || m.kind === 'pipeline' ? 'action' : m.kind === 'rule' ? 'rule' : m.kind === 'setup' ? 'setup' : m.kind === 'not-read' ? 'not-read' : 'steps');
32
+
33
+ /** One "It knows" line: the name, and its kind and starting value in words when the code says them. */
34
+ const knowsLine = (k) => {
35
+ const detail = [k.kind, k.start].filter(Boolean).join(', ');
36
+ return { name: k.name, label: k.label, detail: detail || null, ...(k.secret ? { secret: true } : {}), line: k.line ?? null };
37
+ };
38
+
39
+ /** A Thing card: what it knows, what it can do (each a door to open), and how a new one starts. */
40
+ export function thingCard(model, thing) {
41
+ const members = new Map(model.members.map((m) => [m.id, m]));
42
+ const can = thing.can.map((id) => members.get(id)).filter(Boolean);
43
+ const setup = can.find((m) => m.kind === 'setup') ?? null;
44
+ return {
45
+ kind: 'thing', id: thing.id, label: thing.label, doc: thing.doc ?? null,
46
+ heading: READING_LABELS.thing, symbol: 'thing',
47
+ knows: { heading: READING_LABELS.knows, items: thing.knows.map(knowsLine) },
48
+ can: { heading: READING_LABELS.can, items: can.filter((m) => m !== setup).map((m) => ({ id: m.id, label: `${m.label}${m.yesNo ? '?' : ''}`, symbol: memberSymbolId(m) })) },
49
+ starts: setup ? { id: setup.id, text: READING_LABELS.starts(thing.label) } : { id: null, text: READING_LABELS.startsWithKnows(thing.label) },
50
+ };
51
+ }
52
+
53
+ /** A Data card: a record (facts, like an ID card) or choices (one allowed value). */
54
+ export function dataCard(thing) {
55
+ const record = thing.kind === 'record';
56
+ return {
57
+ kind: record ? 'record' : 'choices', id: thing.id, label: thing.label, doc: thing.doc ?? null,
58
+ heading: record ? READING_LABELS.record : READING_LABELS.choices,
59
+ symbol: record ? 'record' : 'choices', symbolLabel: record ? READING_LABELS.recordSymbol : READING_LABELS.choicesSymbol,
60
+ choices: [...thing.choices],
61
+ knows: thing.knows.map(knowsLine),
62
+ };
63
+ }
64
+
65
+ /**
66
+ * What goes in and out of one action or rule: "You give it" (each input, with its kind when the code says it), "You
67
+ * get back", "It can stop with" (every Stop in its flow, with its line), and "Part of <Thing>" back to its card.
68
+ */
69
+ export function ioBoxes(model, member) {
70
+ const owner = member.owner ? model.things.find((t) => t.id === member.owner) : null;
71
+ const kinds = member.inputKinds ?? {};
72
+ const stops = (member.flow?.nodes ?? []).filter((n) => n.kind === 'stop').map((n) => ({ text: n.text.replace(/^Stop:\s*/, ''), line: n.line ?? null }));
73
+ return {
74
+ kind: 'io', id: member.id, label: `${member.label}${member.yesNo ? '?' : ''}`, doc: member.doc ?? null, symbol: memberSymbolId(member),
75
+ give: { heading: READING_LABELS.give, items: member.youGive.map((label) => ({ label, kind: kinds[label] ?? null })), empty: READING_LABELS.givesNothing },
76
+ getBack: { heading: READING_LABELS.getBack, text: member.youGetBack ?? null, empty: READING_LABELS.getsNothing },
77
+ stops: { heading: READING_LABELS.stops, items: stops },
78
+ partOf: owner ? { id: owner.id, text: READING_LABELS.partOf(owner.label) } : null,
79
+ };
80
+ }
81
+
82
+ const sectionsFor = (model, things) => {
83
+ const cards = things.filter((t) => t.kind === 'thing').map((t) => thingCard(model, t));
84
+ const data = [...things.filter((t) => t.kind === 'record'), ...things.filter((t) => t.kind === 'choices')].map(dataCard);
85
+ return [
86
+ ...(cards.length ? [{ id: 'things', heading: READING_LABELS.things, cards }] : []),
87
+ ...(data.length ? [{ id: 'data', heading: READING_LABELS.data, cards: data }] : []),
88
+ ];
89
+ };
90
+
91
+ /**
92
+ * The Big Picture, which zooms with what is in focus (the tabs stay Big Picture / Flow / Details / Text / Original):
93
+ * no focus: every Thing, then every record, then every set of choices
94
+ * a file's path: the same, for that file
95
+ * a Thing's id: its card, then the Data in its file
96
+ * an action or rule: its "You give it / You get back / It can stop with" boxes, with "Part of <Thing>"
97
+ * Resources are infrastructure and have their own view. `focus.kind` says which one it was ('unknown' when the id is
98
+ * not in the model: nothing is drawn rather than something else).
99
+ */
100
+ export function readingLayout(model, { focus = null } = {}) {
101
+ const base = { schema: READING_LAYOUT_SCHEMA };
102
+ if (focus == null) return { ...base, focus: { kind: 'app', id: null }, sections: sectionsFor(model, model.things) };
103
+ const member = model.members.find((m) => m.id === focus);
104
+ if (member) return { ...base, focus: { kind: 'member', id: focus }, sections: [{ id: 'io', heading: READING_LABELS.io, cards: [ioBoxes(model, member)] }] };
105
+ const thing = model.things.find((t) => t.id === focus);
106
+ if (thing) {
107
+ const rest = model.things.filter((t) => t !== thing && t.file === thing.file && t.kind !== 'thing');
108
+ return { ...base, focus: { kind: 'thing', id: focus }, sections: sectionsFor(model, [thing, ...rest]) };
109
+ }
110
+ if (model.files.some((f) => f.path === focus)) return { ...base, focus: { kind: 'file', id: focus }, sections: sectionsFor(model, model.things.filter((t) => t.file === focus)) };
111
+ return { ...base, focus: { kind: 'unknown', id: focus }, sections: [] };
112
+ }
package/src/review.mjs CHANGED
@@ -376,14 +376,15 @@ function valueChanges(o, n) {
376
376
  return ` (values ${onlyA.length ? `${onlyA.slice(0, 4).join(', ')} removed` : ''}${onlyA.length && onlyB.length ? ', ' : ''}${onlyB.length ? `${onlyB.slice(0, 4).join(', ')} added` : ''})`;
377
377
  }
378
378
 
379
- function compareMember(o, n, items) {
379
+ function compareMember(o, n, items, { extracted = false } = {}) {
380
380
  const subject = subjectOf(n);
381
381
  const sameCode = sameTokens(o.tokens, n.tokens);
382
382
  const sameThunder = o.sig === n.sig;
383
383
  const renamedOrMoved = [];
384
384
  if (o.m.file !== n.m.file) renamedOrMoved.push(`moved from ${o.m.file} to ${n.m.file}`);
385
385
  // A route handler is named after its address: a new address is said once, as the address.
386
- if (nameKey(o.m.name) !== nameKey(n.m.name) && (o.m.route ?? '') === (n.m.route ?? '')) renamedOrMoved.push(`renamed from ${o.m.label} to ${n.m.label}`);
386
+ // (Steps moved into a new function are not a rename: the old function is still there and runs the new one.)
387
+ if (!extracted && nameKey(o.m.name) !== nameKey(n.m.name) && (o.m.route ?? '') === (n.m.route ?? '')) renamedOrMoved.push(`renamed from ${o.m.label} to ${n.m.label}`);
387
388
  const moveKind = o.m.file !== n.m.file && nameKey(o.m.name) === nameKey(n.m.name) ? 'moved' : 'renamed';
388
389
  const formOnly = (why) => items.push(item(renamedOrMoved.length ? moveKind : 'form', 'form', subject, whereOf(n),
389
390
  `${renamedOrMoved.length ? `${cap(renamedOrMoved.join(' and '))}. ` : ''}Only the form changed: ${why}`));
@@ -520,6 +521,18 @@ function enclosingName(lines, line) {
520
521
  * pass only the files that changed (and, for a moved file, both paths) or whole trees. Returns
521
522
  * { schema, summary, items, notRead, unchanged } with items ordered by importance (risk, then meaning, then form).
522
523
  */
524
+ /** Whether most of `a`'s code tokens (by count) are also in `b`: three out of four or more, ignoring punctuation. */
525
+ function mostlyIn(a, b) {
526
+ const words = (ts) => ts.map((t) => t.t).filter((t) => /\w/.test(t));
527
+ const have = new Map();
528
+ for (const t of words(b)) have.set(t, (have.get(t) || 0) + 1);
529
+ const want = words(a);
530
+ if (want.length < 12) return false;
531
+ let hit = 0;
532
+ for (const t of want) { const c = have.get(t) || 0; if (c) { hit++; have.set(t, c - 1); } }
533
+ return hit / want.length >= 0.75;
534
+ }
535
+
523
536
  export function thunderReview(oldFiles, newFiles) {
524
537
  detailsCache = new WeakMap();
525
538
  const A = side(oldFiles || []), B = side(newFiles || []);
@@ -551,8 +564,23 @@ export function thunderReview(oldFiles, newFiles) {
551
564
  || (o.m.rule && e.m.rule && !o.m.rule.partial && !e.m.rule.partial && comparePlainRules(o.m.rule, e.m.rule).same)));
552
565
  if (n) { used.add(n); pairs.push([o, n]); o.paired = true; }
553
566
  }
567
+ // 5. Steps moved into a new function: the function now runs a new one in the same file, and most of its old code
568
+ // is there. Its old steps are compared with the new function (what really changed in them), and the function
569
+ // itself is said to run it, instead of "no longer gives back …" for every step that only moved.
570
+ const movedInto = new Map();
571
+ for (const [o, n] of pairs) {
572
+ const named = new Set(n.tokens.map((t) => t.t));
573
+ const target = leftB().find((b) => b.m.file === n.m.file && b.m.kind !== 'not-read' && named.has(b.m.name) && b.m.name !== n.m.name && mostlyIn(o.tokens, b.tokens));
574
+ if (target) { used.add(target); movedInto.set(o, target); }
575
+ }
554
576
  let unchanged = 0;
555
- for (const [o, n] of pairs) if (compareMember(o, n, items) === 'unchanged') unchanged++;
577
+ for (const [o, n] of pairs) {
578
+ const into = movedInto.get(o);
579
+ if (!into) { if (compareMember(o, n, items) === 'unchanged') unchanged++; continue; }
580
+ const now = n.text.slice(1).map((l) => l.trim()).filter(Boolean);
581
+ items.push(item('moved-into', 'meaning', subjectOf(n), whereOf(n), `Its steps moved to ${subjectOf(into)}, a new function it now runs; what changed in them is listed under ${subjectOf(into)}.`, { before: null, after: now }));
582
+ compareMember(o, into, items, { extracted: true });
583
+ }
556
584
  for (const o of leftA()) items.push(item('removed', 'meaning', subjectOf(o), whereOf(o), `Removed ${KIND_WORD[o.m.kind] ?? 'function'}: ${subjectOf(o)}.`, { before: o.text, after: null }));
557
585
  for (const n of leftB()) items.push(item('added', n.m.kind === 'not-read' ? 'risk' : 'meaning', subjectOf(n), whereOf(n),
558
586
  n.m.kind === 'not-read' ? "New function that Thunder cannot read yet: check the code itself." : `New ${KIND_WORD[n.m.kind] ?? 'function'}: ${subjectOf(n)}${summaryOf(n)}.`, { before: null, after: n.text }));
package/src/say-less.mjs CHANGED
@@ -385,6 +385,15 @@ function newThing(v, says) {
385
385
  if (!m) return false;
386
386
  let c = coreOf(v);
387
387
  if (c?.kind === 'unary' && c.op === '&') c = coreOf(c.value);
388
+ // "a new random ID" for the calls that make one (crypto.randomUUID(), uuid.uuid4(), Guid.NewGuid(), …), and for
389
+ // its text form (`.ToString()`, `.hex`).
390
+ if (m[1] === 'random ID') {
391
+ let x = c;
392
+ if (x?.kind === 'call' && x.callee?.kind === 'member' && /^(?:ToString|toString)$/.test(x.callee.property)) x = x.callee.object;
393
+ if (x?.kind === 'member' && x.property === 'hex') x = x.object;
394
+ const name = x?.kind === 'call' ? (x.callee?.kind === 'member' ? x.callee.property : x.callee?.name) : null;
395
+ return /^(?:randomUUID|uuid4|NewGuid|uuidv4|v4|new_v4)$/.test(name ?? '') && !(x.args?.length);
396
+ }
388
397
  const type = c?.kind === 'object' ? c.type : c?.kind === 'call' ? (c.callee.kind === 'name' ? c.callee.name : c.callee.kind === 'member' ? (/^(?:new|New)$/.test(c.callee.property) ? (c.callee.object.name ?? c.callee.object.property) : c.callee.property) : null) : null;
389
398
  return !!type && sameWords(String(type).replace(/<.*$/, '').split(/::|\./).pop(), m[1]);
390
399
  }
@@ -476,6 +485,8 @@ function namesKept(tree, said) {
476
485
  if (name && /^(?:any|some|all|every|none|find|first|filter|where|select|detect|find_index|findIndex|includes|include\?|contains|Contains|any\?|all\?|none\?|exists|Any|All|Exists|in_array|has|hasOwnProperty|has_key|key\?|containsKey|ContainsKey|startswith|endswith|startsWith|endsWith|StartsWith|EndsWith|start_with\?|end_with\?)$/.test(name) && / (?:any|every|all|no|first|matches|match|in|has|contains|starts|ends|one of) /.test(sw)) return ok(own) && n.args.every((a) => a.kind === 'lambda' || ok(a));
477
486
  if (name && /^(?:len|length|size|count|nrow|NROW|Count|sizeof|strlen|wcslen|mb_strlen|nchar|str_length|lengths|Length)$/.test(name) && howMany) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
478
487
  if (name && /^(?:isinstance|is_a\??|kind_of\??|instance_of\??|inherits|is)$/.test(name) && isA) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
488
+ // (C#'s String.IsNullOrEmpty(x) is a question about x: the type it is asked on is not a value.)
489
+ if (name && /^IsNullOr(?:Empty|WhiteSpace)$/.test(name) && c?.kind === 'member' && /^[Ss]tring$/.test(c.object?.name ?? '') && setWords) return ok(n.args);
479
490
  if (name && /^(?:is\.null|is_null|isNull|is\.na|isset|empty|is_none|isNone|isNil|is_nil|nil\?|null\?|blank\?|present\?|empty\?|isEmpty|IsNullOrEmpty|IsNullOrWhiteSpace|isBlank|isNotEmpty|isNotBlank|any\?|none\?)$/.test(name) && setWords) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
480
491
  return (name == null || has(name)) && (c?.kind !== 'member' || ok(c.object) || /^[A-Z]/.test(c.object?.name ?? '')) && ok(n.args);
481
492
  }
@@ -500,7 +511,9 @@ const KEYWORD_CALLEE = /^(?:use|unsafe|using|foreach|for|type|return|pub|public|
500
511
 
501
512
  const coreOf = (e) => {
502
513
  let c = e;
503
- while (c && ((c.kind === 'unary' && (c.op === 'await' || c.op === '?' || c.op === '!!')) || (c.kind === 'cast' && c.form === 'nonnull'))) c = c.value;
514
+ // (.NET: a get-or-add of a Lazy, `byKey.GetOrAdd(k, _ => new Lazy<T>(…)).Value`, gives the entry's value: the call is the core.)
515
+ while (c && ((c.kind === 'unary' && (c.op === 'await' || c.op === '?' || c.op === '!!')) || (c.kind === 'cast' && c.form === 'nonnull')
516
+ || (c.kind === 'member' && c.property === 'Value' && c.object?.kind === 'call' && c.object.callee?.property === 'GetOrAdd'))) c = c.kind === 'member' ? c.object : c.value;
504
517
  return c;
505
518
  };
506
519
  /** The names of the calls along a value's receiver chain: a.b().c() -> [b, c]. */
@@ -824,7 +837,8 @@ function conditionCore(test, says, code, lang) {
824
837
  const said = claimText(says);
825
838
  const tn = treeNegations(test), wn = saidNegations(says);
826
839
  if (tn !== wn) return M('L378');
827
- let logic = 0; for (const n of nodesOf(test)) if (n.kind === 'logic') logic += n.operands.length - 1;
840
+ // (String.IsNullOrEmpty(x) asks "null, or empty": the "or" is in its name; see accountsFor.)
841
+ let logic = 0; for (const n of nodesOf(test)) if (n.kind === 'logic') logic += n.operands.length - 1; else if (n.kind === 'call' && /^IsNullOr(?:Empty|WhiteSpace)$/.test(n.callee?.property ?? '')) logic++;
828
842
  const wl = (said.match(/\band\b|\bor\b/g) || []).length;
829
843
  if (logic !== wl) return M('L381');
830
844
  if (!orderingKept(test, says)) return M('L382');
package/src/steps.mjs CHANGED
@@ -315,6 +315,10 @@ function sayCodeConditionInner(cond) {
315
315
  if (call[2] === 'is_null') return `${what} is ${call[1] ? 'not ' : ''}null`;
316
316
  return call[2] === 'isset' ? `${what} is ${call[1] ? 'not ' : ''}set` : `${what} is ${neg ? 'not ' : ''}empty`;
317
317
  }
318
+ // C#: String.IsNullOrEmpty(x) -> "x is empty or missing"; IsNullOrWhiteSpace -> "x is blank or missing".
319
+ if ((call = c.match(/^(!|not\s+)?[Ss]tring\.IsNullOr(Empty|WhiteSpace)\(\s*([\w$.]+)\s*\)$/))) {
320
+ return `${possessiveWords(call[3])} is ${call[1] ? 'not ' : ''}${call[2] === 'Empty' ? 'empty' : 'blank'}${call[1] ? ' and is set' : ' or missing'}`;
321
+ }
318
322
  // isObject(x) -> "x is object"; !isRequest(options.request) -> "the options's request is not request".
319
323
  if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call[2])) {
320
324
  return `${possessiveWords(call[3])} is ${call[1] ? 'not ' : ''}${words(call[2])}`;
@@ -1538,6 +1542,12 @@ export function statementExpr(raw) {
1538
1542
  }
1539
1543
  const codeExpr = (text) => ({ kind: 'code', text: String(text ?? '').replace(/\s+/g, ' ').trim() });
1540
1544
 
1545
+ /**
1546
+ * A first line that opens an object as a call's argument, `fetch(url, {` / `post({`: the statement goes on to the
1547
+ * line that closes the call, so it is read whole. (A callback, `items.forEach((x) => {`, is a block: not this.)
1548
+ */
1549
+ const callWithObject = (first) => /[(,]\s*\{\s*$/.test(first) && !/=>\s*\{\s*$/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, ''));
1550
+
1541
1551
  function classifyWords(raw, { inner = 0 } = {}) {
1542
1552
  const text = String(raw).trim();
1543
1553
  // A condition written over several lines (`if (\n a &&\n b\n) {`) is read whole.
@@ -1559,11 +1569,13 @@ function classifyWords(raw, { inner = 0 } = {}) {
1559
1569
  const rest = c > 0 ? text.slice(c + 1).trim() : '';
1560
1570
  if (rest && !rest.startsWith('{') && !text.slice(c + 1).split('\n')[0].trim()) first = `${text.slice(0, c + 1).replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')')} ${rest.replace(/\s+/g, ' ')}`.trim();
1561
1571
  }
1572
+ // C#: `return Task.FromResult(x);` gives back x (as a finished task): read as `return x;`.
1573
+ if (LANG === 'csharp') first = first.replace(/^return\s+(?:Task|ValueTask)\.FromResult\((.*)\)\s*;?$/, 'return $1;');
1562
1574
  // `return (` with JSX on the next line: what is drawn on screen.
1563
1575
  if (/^return\s*\(\s*$/.test(first) && /^\s*</.test(text.split('\n')[1] || '')) first = `return (${text.split('\n')[1].trim()}`;
1564
1576
  // A statement written over several lines (`return a\n && b`, `x =\n cond ? y : z`, `return (\n <div>…`) is read
1565
1577
  // whole, so a value is never cut to its first line.
1566
- else if (text.includes('\n') && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first)) && !/=>\s*\{?\s*$/.test(first) && text.length < 2000 && balancedText(text) && (!/\{\s*$/.test(text.split('\n')[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first))) {
1578
+ else if (text.includes('\n') && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first) || callWithObject(first)) && !/=>\s*\{?\s*$/.test(first) && text.length < 2000 && balancedText(text) && (!/\{\s*$/.test(text.split('\n')[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first) || callWithObject(first))) {
1567
1579
  const lines = text.split('\n');
1568
1580
  const joined = lines.map((l) => l.trim()).join(' ');
1569
1581
  if (!bracketsClosed(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || '')) first = joined;
@@ -66,8 +66,18 @@ function cDocAbove(src, idx) {
66
66
 
67
67
  /** The body of a brace block with nested blocks removed: the type's own declarations, not its methods' bodies. */
68
68
  function ownLevel(body) {
69
- let depth = 0, own = '';
70
- for (const c of body) { if (c === '{') depth++; if (depth === 0) own += c; if (c === '}') depth--; }
69
+ let depth = 0, own = '', start = 0;
70
+ for (let i = 0; i < body.length; i++) {
71
+ const c = body[i];
72
+ if (c === '{') { if (depth === 0) start = i; depth++; }
73
+ if (depth === 0) own += c;
74
+ if (c === '}') {
75
+ depth--;
76
+ // A value's initializer (`= new() { ["a"] = 1 }`, `= new List<int> { 1, 2 }`, `= { 1, 2 }`) is kept as a
77
+ // mark, so a filled-in value never reads as empty; a method's body is dropped.
78
+ if (depth === 0 && /(?:=|\bnew\b[\w.<>,[\] ?]*(?:\([^()]*\))?)\s*$/.test(own) && body.slice(start + 1, i).trim()) own = `${own.replace(/\s+$/, '')} {…}`;
79
+ }
80
+ }
71
81
  return own;
72
82
  }
73
83
 
@@ -95,7 +105,12 @@ function goDoc(src, at, name) {
95
105
  const MODIFIERS = /^(?:(?:public|private|protected|internal|static|final|readonly|const|volatile|transient|override|open|abstract|sealed|lateinit|required|unsafe|mut|pub(?:\([^)]*\))?|var|val|let)\s+)*/;
96
106
 
97
107
  export function makeThingReaders({ words, kindWords, startValue }) {
98
- const know = (name, type, start, params, line = null) => ({ name, label: words(name.replace(/^[_$]+|_$/g, '')), kind: type ? kindWords(type) : null, start: start != null && start !== '' ? startValue(start, params) : null, line });
108
+ // (C#'s `new()` names no type: it is empty only when the declared type is a list or lookup table.)
109
+ const know = (name, type, start, params, line = null) => {
110
+ const kind = type ? kindWords(type) : null;
111
+ const said = start != null && start !== '' ? (/^new\(\)$/.test(String(start).trim()) && !/^(a list|a lookup table|a set)/.test(kind ?? '') ? 'worked out when it starts' : startValue(start, params)) : null;
112
+ return { name, label: words(name.replace(/^[_$]+|_$/g, '')), kind, start: said, line };
113
+ };
99
114
 
100
115
  /** Java, C#, Kotlin, PHP: brace-bodied classes. */
101
116
  function curlyThings(src, file, language) {
@@ -164,6 +179,8 @@ export function makeThingReaders({ words, kindWords, startValue }) {
164
179
  thing.knows.push(know(f[2], f[1], f[3], params));
165
180
  }
166
181
  }
182
+ // A property that shows a field (`_orders` and `Orders`) is the same thing known twice: keep it once.
183
+ thing.knows = thing.knows.filter((k, i, all) => all.findIndex((x) => x.label === k.label) === i);
167
184
  // Starting values set in the constructor: this.x = …; / $this->x = …; / x = … (Kotlin init blocks).
168
185
  const ctorRe = language === 'php' ? /function\s+__construct\s*\(([^)]*)\)\s*\{/ : language === 'kotlin' ? /\binit\s*\{/ : new RegExp(`(?:public|private|protected|internal)?\\s*${name}\\s*\\(([^)]*)\\)\\s*(?::\\s*(?:this|base)\\([^)]*\\)\\s*)?\\{`);
169
186
  const ctor = body.match(ctorRe);
@@ -0,0 +1,143 @@
1
+ // thunder write across folders: one rule change written into every service that implements it (write-across.mjs).
2
+ // thunder write <folder…> --decision <name> --rule <n> --when "<condition>" [--write] [--run "part: cmd" …]
3
+ // [--passport passport.json] [--purpose "…"] [--json]
4
+ // Without --write it shows the plan and changes nothing. With --write it changes every implementation or none, then
5
+ // runs the --run commands and, with --passport, records the change and the runs as a Software Passport.
6
+ import { readFileSync, writeFileSync, statSync } from 'node:fs';
7
+ import { basename, dirname, join, resolve } from 'node:path';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { collectReadableFiles } from './read-repo-fs.mjs';
10
+ import { writeRuleAcross, writeAcrossEvidence } from './write-across.mjs';
11
+ import { buildPassport } from './passport-fs.mjs';
12
+ import { renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
13
+ import { paint, useColor } from './term.mjs';
14
+
15
+ const USAGE = `usage: thunder write <folder…> --decision <name> --rule <n> --when "<condition>" [--write]
16
+ [--run "part: cmd" …] [--passport passport.json] [--purpose "…"] [--json]
17
+ Finds every implementation of the rule across the folders (each one part, in any language Thunder reads) and
18
+ changes its number, comparison, or text value in each of them. Without --write: the plan only. With --write: every
19
+ implementation changes, or none does. Test files are never edited; those that mention the old value are listed.
20
+ Exit codes: 0 done (or planned), 1 refused or a --run command failed, 2 usage.`;
21
+
22
+ /** Is this `thunder write` call about several folders (rather than one file)? */
23
+ export function isWriteAcross(argv) {
24
+ const paths = [];
25
+ for (let i = 0; i < argv.length; i++) {
26
+ if (argv[i].startsWith('--')) { if (!['--write', '--json', '-w'].includes(argv[i])) i++; continue; }
27
+ paths.push(argv[i]);
28
+ }
29
+ if (argv.includes('--edit')) return false;
30
+ return paths.length > 1 || paths.some((p) => { try { return statSync(p).isDirectory(); } catch { return false; } });
31
+ }
32
+
33
+ export async function writeAcrossMain(argv) {
34
+ const a = { _: [], decision: null, rule: null, when: null, write: false, run: [], passport: null, mdOut: null, purpose: null, json: false };
35
+ for (let i = 0; i < argv.length; i++) {
36
+ const x = argv[i];
37
+ const need = () => { const v = argv[++i]; if (v == null) throw new Error(`${x} needs a value.`); return v; };
38
+ try {
39
+ if (x === '--decision') a.decision = need();
40
+ else if (x === '--rule') a.rule = need();
41
+ else if (x === '--when') a.when = need();
42
+ else if (x === '--write' || x === '-w') a.write = true;
43
+ else if (x === '--run') a.run.push(need());
44
+ else if (x === '--passport') a.passport = need();
45
+ else if (x === '--md-out') a.mdOut = need();
46
+ else if (x === '--purpose') a.purpose = need();
47
+ else if (x === '--json') a.json = true;
48
+ else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
49
+ else if (x === '--answer') { console.error('thunder write: across folders, only a rule\'s condition can change (--when). Each service may answer in its own way (a label on the page, an amount in billing), so one new answer would not fit them all.'); return 2; }
50
+ else if (x.startsWith('--')) { console.error(`thunder write: there is no option ${x} for a change across folders.\n${USAGE}`); return 2; }
51
+ else a._.push(x);
52
+ } catch (e) { console.error(`thunder write: ${e.message}\n${USAGE}`); return 2; }
53
+ }
54
+ if (!a.decision || !a.rule || a.when == null) { console.error(`thunder write: say which rule and its new condition.\n${USAGE}`); return 2; }
55
+ if (a.run.length && !a.write) { console.error('thunder write: --run runs your tests on the changed code, so it needs --write.'); return 2; }
56
+ if (a.passport && !a.write) { console.error('thunder write: --passport records a written change, so it needs --write.'); return 2; }
57
+
58
+ const parts = [];
59
+ for (const p of a._) {
60
+ let dir = false;
61
+ try { dir = statSync(p).isDirectory(); } catch { console.error(`thunder write: there is no folder called ${p} here.`); return 2; }
62
+ if (!dir) { console.error(`thunder write: ${p} is a file. Across services, name the folders (each one part); for one file use thunder write <file> --decision …`); return 2; }
63
+ parts.push({ name: basename(resolve(p)), dir: p });
64
+ }
65
+ if (new Set(parts.map((p) => p.name)).size !== parts.length) { console.error('thunder write: two folders have the same name; give folders with different names.'); return 2; }
66
+ const files = parts.flatMap((p) => collectReadableFiles(p.dir).map((f) => ({ part: p.name, path: f.path, source: f.source })));
67
+ const r = writeRuleAcross(files, { decision: a.decision, rule: a.rule, when: a.when });
68
+ const dirOf = (k) => { const [part, ...rest] = k.split('/'); return join(parts.find((p) => p.name === part).dir, rest.join('/')); };
69
+
70
+ // Write every file, or none (a failed write puts back the ones already written).
71
+ let written = false;
72
+ if (r.ok && a.write) {
73
+ const done = [];
74
+ try {
75
+ for (const [k, src] of Object.entries(r.files)) { const path = dirOf(k); const old = readFileSync(path, 'utf8'); writeFileSync(path, src); done.push([path, old]); }
76
+ for (const [k, src] of Object.entries(r.files)) if (readFileSync(dirOf(k), 'utf8') !== src) throw new Error(`${k} does not hold what was written`);
77
+ written = true;
78
+ } catch (e) {
79
+ for (const [path, old] of done) writeFileSync(path, old);
80
+ console.error(`thunder write: could not write every file (${e.message}); the ones already written were put back.`);
81
+ return 1;
82
+ }
83
+ }
84
+
85
+ // Proof: the tests, and the passport (which runs them itself, so they run once).
86
+ let runs = [], passport = null;
87
+ if (written && a.passport) {
88
+ passport = buildPassport({ parts: parts.map((p) => p.dir), base: 'HEAD', run: a.run, purpose: a.purpose ? { text: a.purpose, source: 'given with --purpose' } : null, evidence: [writeAcrossEvidence(r)], relativeTo: dirname(resolve(a.passport)) });
89
+ writeFileSync(a.passport, `${JSON.stringify(passport, null, 2)}\n`);
90
+ if (a.mdOut) writeFileSync(a.mdOut, renderPassportMarkdown(passport));
91
+ runs = passport.evidence.filter((e) => e.kind === 'test-run').map((e) => ({ command: e.basis.command, exitCode: e.basis.exitCode, part: e.claim.match(/ in ([^ ]+) exited/)?.[1] ?? null, tail: e.basis.outputTail }));
92
+ } else if (written) {
93
+ for (const spec of a.run) {
94
+ const m = String(spec).match(/^([A-Za-z0-9_.-]+):\s+(.+)$/);
95
+ const part = m && parts.find((p) => p.name === m[1]);
96
+ const command = part ? m[2] : spec;
97
+ const x = spawnSync(`(${command}) 2>&1`, { shell: true, cwd: part ? part.dir : process.cwd(), encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
98
+ runs.push({ command, part: part?.name ?? null, exitCode: x.status ?? 1, tail: String(x.stdout ?? '').trimEnd().split('\n').slice(-12).join('\n') });
99
+ }
100
+ }
101
+ const failed = runs.filter((x) => x.exitCode !== 0);
102
+
103
+ if (a.json) {
104
+ const { files: _f, ...rest } = r;
105
+ console.log(JSON.stringify({ ...rest, written, runs, ...(a.passport ? { passport: a.passport } : {}) }, null, 2));
106
+ return !r.ok || failed.length ? 1 : 0;
107
+ }
108
+ const say = (s = '') => console.log(paint(s, useColor()));
109
+ if (!r.ok) {
110
+ console.error(paint('✗ Not changed. No file was touched.', useColor(process.stderr)));
111
+ for (const p of r.problems) console.error(` ${p}`);
112
+ if (r.notIncluded?.length) { console.error('\nAlso similar, never changed by Thunder:'); for (const n of r.notIncluded) console.error(` ${n.part}/${n.file}:${n.line} ${n.why}`); }
113
+ return 1;
114
+ }
115
+ say(`One rule, ${r.plan.length} implementation${r.plan.length === 1 ? '' : 's'}: ${r.rule.before} → ${r.rule.after}`);
116
+ say('');
117
+ for (const p of r.plan) {
118
+ say(`${p.part}/${p.file} (${p.language}, ${p.decision}, rule ${p.rule})`);
119
+ say(` why it is the same rule: ${p.why}`);
120
+ say(` was: ${p.before}`);
121
+ say(` now: ${p.after}`);
122
+ for (const c of p.change) say(` line ${c.line}, column ${c.column}: ${c.before} -> ${c.after}`);
123
+ }
124
+ say('\nChecked by reading each file again: the rule reads as intended, and every other rule and function in each file reads exactly as before.');
125
+ if (r.notIncluded.length) {
126
+ say('\nNot included (similar, but Thunder cannot tell it is the same rule; check by hand):');
127
+ for (const n of r.notIncluded) say(` ${n.part}/${n.file}:${n.line} ${n.why}`);
128
+ }
129
+ if (r.tests.length) {
130
+ say('\nTests that mention the old value (Thunder never edits tests; they may pin the old rule):');
131
+ for (const t of r.tests) say(` ${t.part}/${t.file}:${t.line} ${t.text}`);
132
+ }
133
+ if (!written) { say('\nPlan only; nothing was saved. Add --write to change every implementation (all or none).'); return 0; }
134
+ say(`\nSaved ${Object.keys(r.files).length} file${Object.keys(r.files).length === 1 ? '' : 's'}: ${Object.keys(r.files).join(', ')}.`);
135
+ if (runs.length) {
136
+ say('\nTests on the changed code:');
137
+ for (const x of runs) say(` ${x.exitCode === 0 ? '✓ passed' : `✗ failed (exit ${x.exitCode})`} ${x.part ? `${x.part}: ` : ''}${x.command}`);
138
+ for (const x of failed) { say(`\n ${x.part ? `${x.part}: ` : ''}${x.command} said:`); for (const l of String(x.tail).split('\n')) say(` ${l}`); }
139
+ if (failed.length) say('\nThe change is saved, and these tests fail on it. A test that pins the old rule fails until it is updated; any other failure needs a look.');
140
+ }
141
+ if (passport) { say(`\nPassport: ${a.passport}`); say(renderPassportSummary(passport)); }
142
+ return failed.length ? 1 : 0;
143
+ }