flashtrace 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/flashtrace.mjs +401 -119
  2. package/package.json +1 -1
@@ -7,7 +7,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
7
7
 
8
8
  // src/cli.mjs
9
9
  import { promises as fs2, readFileSync } from "node:fs";
10
- import path4 from "node:path";
10
+ import path5 from "node:path";
11
11
  import process3 from "node:process";
12
12
 
13
13
  // src/errors.mjs
@@ -163,7 +163,7 @@ var CODE_EXT = new Set(Object.keys(BY_EXT));
163
163
  var grammarFor = (ext) => BY_EXT[ext] ?? null;
164
164
 
165
165
  // src/files.mjs
166
- var MD_EXT = /* @__PURE__ */ new Set([".md", ".markdown"]);
166
+ var SPEC_EXT = /* @__PURE__ */ new Set([".md", ".markdown"]);
167
167
  var GIT_LOCATIONS = process.platform === "win32" ? [
168
168
  String.raw`C:\Program Files\Git\cmd\git.exe`,
169
169
  String.raw`C:\Program Files (x86)\Git\cmd\git.exe`
@@ -222,7 +222,7 @@ async function collectFiles(dirs) {
222
222
  }
223
223
  return [...files].filter((file) => {
224
224
  const ext = path.extname(file).toLowerCase();
225
- return MD_EXT.has(ext) || CODE_EXT.has(ext);
225
+ return SPEC_EXT.has(ext) || CODE_EXT.has(ext);
226
226
  }).sort(compareStrings);
227
227
  }
228
228
 
@@ -239,16 +239,17 @@ var REF_RE = new RegExp(`^${REF_SRC}$`);
239
239
  var COVER_REF_RE = new RegExp(`^([A-Za-z]+)(?::(${PATH_SRC}))?(?:#(${REV_SRC}))?$`);
240
240
  var FORWARD_SRC = String.raw`\[\s*${ID_SRC}\s*-->\s*${ID_SRC}\s*\]`;
241
241
  var makeId = (type, group, name, rev) => `${type}:${group ? group + "/" : ""}${name}#${rev}`;
242
- var makeForward = (m, base, file, line) => ({
242
+ var makeForward = (m, base, file, line, character) => ({
243
243
  from: makeId(m[base], m[base + 1], m[base + 2], m[base + 3]),
244
244
  to: makeId(m[base + 4], m[base + 5], m[base + 6], m[base + 7]),
245
245
  file,
246
- line
246
+ line,
247
+ character
247
248
  });
248
249
  var keyOf = (id) => id.slice(0, id.lastIndexOf("#"));
249
250
  var revOf = (id) => id.slice(id.lastIndexOf("#") + 1);
250
251
  var pathOf = (id) => id.slice(id.indexOf(":") + 1, id.lastIndexOf("#"));
251
- var resolveRef = (type, path5, rev, ownerId) => `${type}:${path5 ?? pathOf(ownerId)}#${rev ?? revOf(ownerId)}`;
252
+ var resolveRef = (type, path6, rev, ownerId) => `${type}:${path6 ?? pathOf(ownerId)}#${rev ?? revOf(ownerId)}`;
252
253
  function compareRev(a, b) {
253
254
  const partsA = a.split(".");
254
255
  const partsB = b.split(".");
@@ -282,15 +283,17 @@ function parseCoverEntry(raw, ownerId) {
282
283
  const m = cleaned.match(COVER_REF_RE);
283
284
  return m ? resolveRef(m[1], m[2], m[3], ownerId) : null;
284
285
  }
285
- function newItem(id, origin, file, line) {
286
+ function newItem(id, origin, file, line, character) {
286
287
  return {
287
288
  id,
288
289
  key: keyOf(id),
289
290
  revision: revOf(id),
290
291
  origin,
291
- // 'markdown' | 'code'
292
+ // 'spec' | 'code'
292
293
  file,
293
294
  line,
295
+ character,
296
+ // 1-based column of the first character of the defining construct
294
297
  title: null,
295
298
  description: [],
296
299
  needs: [],
@@ -311,9 +314,10 @@ var KEYWORD_RE = /^(Needs|Covers|Tags):\s*((?:\S.*)?)$/;
311
314
  var BULLET_RE = /^\s*[-*+]\s+(\S(?:.*\S)?)\s*$/;
312
315
  var DELIMITER_CELL_RE = /^:?-+:?$/;
313
316
  var FORWARD_LINE_RE = new RegExp(String.raw`^\s*(\`?)${FORWARD_SRC}\1\s*$`);
317
+ var firstNonBlankColumn = (line) => line.search(/\S/) + 1;
314
318
  function takeForward(line, file, lineIndex, forwards) {
315
319
  const forward = line.match(FORWARD_LINE_RE);
316
- if (forward) forwards.push(makeForward(forward, 2, file, lineIndex + 1));
320
+ if (forward) forwards.push(makeForward(forward, 2, file, lineIndex + 1, firstNonBlankColumn(line)));
317
321
  return !!forward;
318
322
  }
319
323
  function isParagraphLine(line) {
@@ -362,13 +366,24 @@ function titleAbove(lines, inTable, definitionIndex) {
362
366
  }
363
367
  function keywordEntries(lines, j, inline) {
364
368
  if (inline.trim() !== "") {
365
- return { entries: inline.split(",").map((s) => s.trim()).filter(Boolean), j };
369
+ const inlineStart = lines[j].length - inline.length;
370
+ const entries2 = [];
371
+ let pos = 0;
372
+ for (const part of inline.split(",")) {
373
+ const value = part.trim();
374
+ if (value) {
375
+ const leading = part.length - part.trimStart().length;
376
+ entries2.push({ value, line: j + 1, character: inlineStart + pos + leading + 1 });
377
+ }
378
+ pos += part.length + 1;
379
+ }
380
+ return { entries: entries2, j };
366
381
  }
367
382
  const entries = [];
368
383
  while (j + 1 < lines.length) {
369
384
  const bullet = lines[j + 1].match(BULLET_RE);
370
385
  if (!bullet) break;
371
- entries.push(bullet[1].trim());
386
+ entries.push({ value: bullet[1].trim(), line: j + 2, character: lines[j + 1].indexOf(bullet[1]) + 1 });
372
387
  j++;
373
388
  }
374
389
  return { entries, j };
@@ -380,6 +395,26 @@ function rowCells(line) {
380
395
  if (row.endsWith("|")) row = row.slice(0, -1);
381
396
  return row.split("|").map((cell) => cell.trim());
382
397
  }
398
+ function rowCellColumns(line) {
399
+ if (rowCells(line) === null) return [firstNonBlankColumn(line)];
400
+ let base = line.length - line.trimStart().length;
401
+ const trimmed = line.trim();
402
+ let body = trimmed;
403
+ if (body.startsWith("|")) {
404
+ body = body.slice(1);
405
+ base += 1;
406
+ }
407
+ if (body.endsWith("|")) body = body.slice(0, -1);
408
+ const columns = [];
409
+ let pos = 0;
410
+ for (const part of body.split("|")) {
411
+ const value = part.trim();
412
+ const leading = value ? part.length - part.trimStart().length : 0;
413
+ columns.push(base + pos + leading + 1);
414
+ pos += part.length + 1;
415
+ }
416
+ return columns;
417
+ }
383
418
  function tableStartsAt(lines, j) {
384
419
  const header = rowCells(lines[j]);
385
420
  if (!header) return false;
@@ -407,12 +442,14 @@ function scanTables(lines, file, problems) {
407
442
  for (let k = start; k <= end; k++) {
408
443
  inTable[k] = true;
409
444
  if (k === start + 1) continue;
445
+ const columns = rowCellColumns(lines[k]);
410
446
  rowCellsInTable(lines[k]).forEach((cell, col) => {
411
447
  const definition = keywordColumns.has(col) ? null : cell.match(DEFINITION_RE);
412
448
  if (definition)
413
449
  problems.push({
414
450
  file,
415
451
  line: k + 1,
452
+ character: columns[col],
416
453
  message: `item ${makeId(definition[1], definition[2], definition[3], definition[4])} defined inside a table; a table cell is not an item definition`
417
454
  });
418
455
  });
@@ -432,28 +469,37 @@ function takeKeywordTable(lines, inTable, j, item, file, problems) {
432
469
  while (j + 1 < lines.length && inTable[j + 1]) {
433
470
  j++;
434
471
  const cells = rowCellsInTable(lines[j]);
472
+ const cellColumns = rowCellColumns(lines[j]);
435
473
  for (const [col, keyword] of columns) {
436
474
  if (cells[col])
437
- applyKeyword(item, keyword, [cells[col]], file, j + 1, problems, `the ${keyword} column of ${item.id}`);
475
+ applyKeyword(
476
+ item,
477
+ keyword,
478
+ [{ value: cells[col], line: j + 1, character: cellColumns[col] }],
479
+ file,
480
+ problems,
481
+ `the ${keyword} column of ${item.id}`
482
+ );
438
483
  }
439
484
  }
440
485
  return j;
441
486
  }
442
- function applyKeyword(item, keyword, entries, file, keywordLine, problems, source) {
487
+ function applyKeyword(item, keyword, entries, file, problems, source) {
443
488
  if (keyword === "Tags") {
444
- item.tags.push(...entries);
489
+ for (const entry of entries) item.tags.push(entry.value);
445
490
  return;
446
491
  }
447
492
  const target = keyword === "Needs" ? "needs" : "covers";
448
493
  const parse = keyword === "Needs" ? parseNeedEntry : parseCoverEntry;
449
494
  for (const entry of entries) {
450
- const id = parse(entry, item.id);
495
+ const id = parse(entry.value, item.id);
451
496
  if (id) item[target].push(id);
452
497
  else
453
498
  problems.push({
454
499
  file,
455
- line: keywordLine,
456
- message: `invalid ID "${entry}" in ${source}`
500
+ line: entry.line,
501
+ character: entry.character,
502
+ message: `invalid ID "${entry.value}" in ${source}`
457
503
  });
458
504
  }
459
505
  }
@@ -477,7 +523,6 @@ function parseItemBody(lines, boundary, start, item, file, problems, forwards) {
477
523
  keywordMatch[1],
478
524
  collected.entries,
479
525
  file,
480
- j + 1,
481
526
  problems,
482
527
  `${keywordMatch[1]}: list of ${item.id}`
483
528
  );
@@ -512,6 +557,7 @@ function parseMarkdown(file, text, problems, forwards = []) {
512
557
  problems.push({
513
558
  file,
514
559
  line: i + 1,
560
+ character: firstNonBlankColumn(lines[i]),
515
561
  message: `item ${makeId(definition[1], definition[2], definition[3], definition[4])} defined inside a setext heading; a heading is not an item definition`
516
562
  });
517
563
  i++;
@@ -521,7 +567,7 @@ function parseMarkdown(file, text, problems, forwards = []) {
521
567
  i++;
522
568
  continue;
523
569
  }
524
- const item = newItem(makeId(definition[1], definition[2], definition[3], definition[4]), "markdown", file, i + 1);
570
+ const item = newItem(makeId(definition[1], definition[2], definition[3], definition[4]), "spec", file, i + 1, firstNonBlankColumn(lines[i]));
525
571
  item.title = titleAbove(lines, inTable, i);
526
572
  i = parseItemBody(lines, boundary, i + 1, item, file, problems, forwards);
527
573
  items.push(item);
@@ -611,9 +657,9 @@ function readBlockRest(line, pos, block, limit = line.length) {
611
657
  }
612
658
  block.depth--;
613
659
  i = closeIdx + close.length;
614
- if (block.depth === 0) return { text: line.slice(pos, closeIdx) + " ", pos: i, closed: true };
660
+ if (block.depth === 0) return { end: closeIdx, pos: i, closed: true };
615
661
  }
616
- return { text: line.slice(pos, limit) + " ", pos: limit, closed: false };
662
+ return { end: limit, pos: limit, closed: false };
617
663
  }
618
664
  function regionExitAt(line, pos, region) {
619
665
  const m = matchAt(region.exit, line, pos);
@@ -623,31 +669,34 @@ function consumeBlock(line, pos, state, exit) {
623
669
  const rest = readBlockRest(line, pos, state.block, exit ? exit.idx : line.length);
624
670
  if (rest.closed) {
625
671
  state.block = null;
626
- return { text: rest.text, pos: rest.pos };
672
+ return { end: rest.end, pos: rest.pos };
627
673
  }
628
674
  if (exit) {
629
675
  state.block = null;
630
676
  state.region = null;
631
- return { text: rest.text, pos: exit.idx + exit.len };
677
+ return { end: rest.end, pos: exit.idx + exit.len };
632
678
  }
633
- return { text: rest.text, pos: rest.pos };
679
+ return { end: rest.end, pos: rest.pos };
634
680
  }
635
681
  function consumeLine(line, pos, state, exit) {
636
682
  if (exit) {
637
683
  state.region = null;
638
- return { text: line.slice(pos, exit.idx) + " ", pos: exit.idx + exit.len, done: false };
684
+ return { end: exit.idx, pos: exit.idx + exit.len, done: false };
639
685
  }
640
- return { text: line.slice(pos) + " ", pos: line.length, done: true };
686
+ return { end: line.length, pos: line.length, done: true };
641
687
  }
642
688
  function commentText(line, state, grammar) {
643
689
  const spans = urlSpans(line);
644
- let comment = "";
690
+ const buffer = new Array(line.length).fill(" ");
691
+ const keep = (from, to) => {
692
+ for (let k = from; k < to; k++) buffer[k] = line[k];
693
+ };
645
694
  let pos = 0;
646
695
  while (pos < line.length) {
647
696
  const exit = state.region ? regionExitAt(line, pos, state.region) : null;
648
697
  if (state.block) {
649
698
  const consumed = consumeBlock(line, pos, state, exit);
650
- comment += consumed.text;
699
+ keep(pos, consumed.end);
651
700
  pos = consumed.pos;
652
701
  continue;
653
702
  }
@@ -656,7 +705,7 @@ function commentText(line, state, grammar) {
656
705
  pos = event.idx + event.len;
657
706
  if (event.kind === "line") {
658
707
  const consumed = consumeLine(line, pos, state, exit);
659
- comment += consumed.text;
708
+ keep(pos, consumed.end);
660
709
  pos = consumed.pos;
661
710
  if (consumed.done) break;
662
711
  } else if (event.kind === "block") {
@@ -667,9 +716,9 @@ function commentText(line, state, grammar) {
667
716
  state.region = null;
668
717
  }
669
718
  }
670
- return comment;
719
+ return buffer.join("");
671
720
  }
672
- function attachNeed(m, file, line, state, problems) {
721
+ function attachNeed(m, file, line, character, state, problems) {
673
722
  const source = m[1] ? makeId(m[1], m[2], m[3], m[4]) : null;
674
723
  const anchor = source ? state.byId.get(source) : state.lastItem;
675
724
  if (!anchor) {
@@ -677,6 +726,7 @@ function attachNeed(m, file, line, state, problems) {
677
726
  problems.push({
678
727
  file,
679
728
  line,
729
+ character,
680
730
  message: source ? `need tag [${source} >> ${written}] has no preceding item tag [${source}] in this file` : `need tag [>>${written}] has no preceding item tag in this file`
681
731
  });
682
732
  return;
@@ -685,13 +735,14 @@ function attachNeed(m, file, line, state, problems) {
685
735
  }
686
736
  function collectTags(comment, file, line, state, items, problems) {
687
737
  for (const m of comment.matchAll(TAG_RE)) {
738
+ const character = m.index + 1;
688
739
  if (m[8]) {
689
- const item = newItem(makeId(m[8], m[9], m[10], m[11]), "code", file, line);
740
+ const item = newItem(makeId(m[8], m[9], m[10], m[11]), "code", file, line, character);
690
741
  state.lastItem = item;
691
742
  state.byId.set(item.id, item);
692
743
  items.push(item);
693
744
  } else {
694
- attachNeed(m, file, line, state, problems);
745
+ attachNeed(m, file, line, character, state, problems);
695
746
  }
696
747
  }
697
748
  }
@@ -704,35 +755,81 @@ function parseCode(file, text, problems, forwards = []) {
704
755
  for (let i = 0; i < lines.length; i++) {
705
756
  const comment = commentText(lines[i], state, grammar);
706
757
  for (const m of comment.matchAll(FORWARD_RE)) {
707
- forwards.push(makeForward(m, 1, file, i + 1));
758
+ forwards.push(makeForward(m, 1, file, i + 1, m.index + 1));
708
759
  }
709
760
  collectTags(comment, file, i + 1, state, items, problems);
710
761
  }
711
762
  return items;
712
763
  }
713
764
 
765
+ // src/defects.mjs
766
+ var DEFECT_KINDS = Object.freeze([
767
+ "uncovered-need",
768
+ "uncovered-forward",
769
+ "orphaned-cover",
770
+ "unwanted-cover",
771
+ "unwanted-item",
772
+ "duplicate-id",
773
+ "duplicate-forwarding"
774
+ ]);
775
+ var uncoveredNeed = (need) => ({
776
+ kind: "uncovered-need",
777
+ ref: need,
778
+ message: `uncovered: needs ${need}, which does not exist`
779
+ });
780
+ var uncoveredForward = (target) => ({
781
+ kind: "uncovered-forward",
782
+ ref: target,
783
+ message: `uncovered: forwards to ${target}, which does not exist`
784
+ });
785
+ var orphanedCover = (coverId) => ({
786
+ kind: "orphaned-cover",
787
+ ref: coverId,
788
+ message: `orphaned: covers ${coverId}, which does not exist`
789
+ });
790
+ var unwantedCover = (coverId, itemId) => ({
791
+ kind: "unwanted-cover",
792
+ ref: coverId,
793
+ message: `unwanted: covers ${coverId}, but ${coverId} does not need ${itemId}`
794
+ });
795
+ var unwantedItem = (itemId) => ({
796
+ kind: "unwanted-item",
797
+ ref: itemId,
798
+ message: `unwanted: no item needs ${itemId}`
799
+ });
800
+ var duplicateId = (id, count) => ({
801
+ kind: "duplicate-id",
802
+ ref: id,
803
+ message: `duplicate: ID ${id} is defined ${count} times`
804
+ });
805
+ var duplicateForwarding = (from, count) => ({
806
+ kind: "duplicate-forwarding",
807
+ ref: from,
808
+ message: `duplicate: forwarding for ${from} is declared ${count} times`
809
+ });
810
+
714
811
  // src/analyze.mjs
715
- function checkItemReferences(item, byId, matchesOf, isNeeded, revHint, forwardTargets) {
812
+ function checkItemReferences(item, byId, matchesOf, isNeeded, withRevisions, forwardTargets) {
716
813
  const forwardTarget = forwardTargets.get(item.id);
717
814
  if (forwardTarget !== void 0) {
718
815
  if (!byId.has(forwardTarget))
719
- item.defects.push(`uncovered: forwards to ${forwardTarget}, which does not exist${revHint(forwardTarget)}`);
816
+ item.defects.push(withRevisions(uncoveredForward(forwardTarget)));
720
817
  } else {
721
818
  for (const need of item.needs) {
722
819
  if (matchesOf(need).length === 0)
723
- item.defects.push(`uncovered: needs ${need}, which does not exist${revHint(need)}`);
820
+ item.defects.push(withRevisions(uncoveredNeed(need)));
724
821
  }
725
822
  }
726
823
  for (const coverId of item.covers) {
727
824
  const targets = byId.get(coverId);
728
825
  if (!targets) {
729
- item.defects.push(`orphaned: covers ${coverId}, which does not exist${revHint(coverId)}`);
826
+ item.defects.push(withRevisions(orphanedCover(coverId)));
730
827
  } else if (!targets.some((target) => target.needs.some((need) => idMatches(need, item.id)))) {
731
- item.defects.push(`unwanted: covers ${coverId}, but ${coverId} does not need ${item.id}`);
828
+ item.defects.push(unwantedCover(coverId, item.id));
732
829
  }
733
830
  }
734
831
  if (item.origin === "code" && !isNeeded(item.id)) {
735
- item.defects.push(`unwanted: no item needs ${item.id}`);
832
+ item.defects.push(unwantedItem(item.id));
736
833
  }
737
834
  }
738
835
  function dropCyclicForwards(forwardTargets, declarationBySource, problems) {
@@ -740,23 +837,30 @@ function dropCyclicForwards(forwardTargets, declarationBySource, problems) {
740
837
  for (const start of forwardTargets.keys()) {
741
838
  if (done.has(start)) continue;
742
839
  const seen = /* @__PURE__ */ new Map();
743
- const path5 = [];
840
+ const path6 = [];
744
841
  let current = start;
745
842
  while (forwardTargets.has(current) && !done.has(current) && !seen.has(current)) {
746
- seen.set(current, path5.length);
747
- path5.push(current);
843
+ seen.set(current, path6.length);
844
+ path6.push(current);
748
845
  current = forwardTargets.get(current);
749
846
  }
750
847
  if (seen.has(current)) {
751
- const cycle = path5.slice(seen.get(current));
848
+ const cycle = path6.slice(seen.get(current));
752
849
  const chain = [...cycle, current].join(" --> ");
753
850
  for (const id of cycle) {
754
851
  const declaration = declarationBySource.get(id);
755
- problems.push({ file: declaration.file, line: declaration.line, message: `cyclic forwarding: ${chain}` });
852
+ declaration.effective = false;
853
+ declaration.voidedBy = "cycle";
854
+ problems.push({
855
+ file: declaration.file,
856
+ line: declaration.line,
857
+ character: declaration.character,
858
+ message: `cyclic forwarding: ${chain}`
859
+ });
756
860
  forwardTargets.delete(id);
757
861
  }
758
862
  }
759
- for (const id of path5) done.add(id);
863
+ for (const id of path6) done.add(id);
760
864
  }
761
865
  }
762
866
  function buildForwardMap(forwards, byId, neededIds, revHint, problems) {
@@ -769,17 +873,25 @@ function buildForwardMap(forwards, byId, neededIds, revHint, problems) {
769
873
  for (const [from, group] of forwardsBySource) {
770
874
  const sources = byId.get(from);
771
875
  if (!sources) {
772
- for (const forward of group)
876
+ for (const forward of group) {
877
+ forward.effective = false;
878
+ forward.voidedBy = "missing-source";
773
879
  problems.push({
774
880
  file: forward.file,
775
881
  line: forward.line,
882
+ character: forward.character,
776
883
  message: `forwarding from ${from}, which does not exist${revHint(from)}`
777
884
  });
885
+ }
778
886
  continue;
779
887
  }
780
888
  if (group.length > 1)
781
- for (const item of sources)
782
- item.defects.push(`duplicate: forwarding for ${from} is declared ${group.length} times`);
889
+ for (const item of sources) item.defects.push(duplicateForwarding(from, group.length));
890
+ group[0].effective = true;
891
+ for (let i = 1; i < group.length; i++) {
892
+ group[i].effective = false;
893
+ group[i].voidedBy = "duplicate";
894
+ }
783
895
  forwardTargets.set(from, group[0].to);
784
896
  declarationBySource.set(from, group[0]);
785
897
  }
@@ -816,13 +928,43 @@ function groupIdsByKey(byId) {
816
928
  (idsByKey.get(keyOf(id)) ?? idsByKey.set(keyOf(id), []).get(keyOf(id))).push(id);
817
929
  return idsByKey;
818
930
  }
931
+ function buildWantedBy(items, byId, matchesOf) {
932
+ const wantedBy = /* @__PURE__ */ new Map();
933
+ for (const item of items)
934
+ for (const need of item.needs)
935
+ for (const id of matchesOf(need))
936
+ for (const provider of byId.get(id))
937
+ (wantedBy.get(provider) ?? wantedBy.set(provider, /* @__PURE__ */ new Set()).get(provider)).add(item);
938
+ return wantedBy;
939
+ }
819
940
  function buildResolver(items) {
820
941
  const byId = /* @__PURE__ */ new Map();
821
942
  for (const item of items) (byId.get(item.id) ?? byId.set(item.id, []).get(item.id)).push(item);
822
943
  const idsByKey = groupIdsByKey(byId);
823
944
  const matchesOf = (ref) => (idsByKey.get(keyOf(ref)) ?? []).filter((id) => idMatches(ref, id));
824
- return { byId, matchesOf };
945
+ return { byId, matchesOf, wantedBy: buildWantedBy(items, byId, matchesOf) };
946
+ }
947
+ function statusOf(item) {
948
+ if (item.defects.length > 0) return "defective";
949
+ return item.deepCovered ? "deep-covered" : "shallow-covered";
950
+ }
951
+ function summarize(items, problems) {
952
+ const specItems = items.filter((item) => item.origin === "spec").length;
953
+ const defectiveItems = items.filter((item) => item.defects.length > 0).length;
954
+ const shallowCoveredItems = items.filter(
955
+ (item) => item.defects.length === 0 && !item.deepCovered
956
+ ).length;
957
+ return {
958
+ items: items.length,
959
+ specItems,
960
+ codeItems: items.length - specItems,
961
+ okItems: items.length - defectiveItems,
962
+ defectiveItems,
963
+ shallowCoveredItems,
964
+ problems: problems.length
965
+ };
825
966
  }
967
+ var isClean = (summary) => summary.defectiveItems === 0 && summary.problems === 0;
826
968
  function splitNeeds(items) {
827
969
  const exact = /* @__PURE__ */ new Set();
828
970
  const wildcard = [];
@@ -841,17 +983,30 @@ function analyze(items, forwards = [], problems = []) {
841
983
  const { exact: exactNeeds, wildcard: wildcardNeeds } = splitNeeds(items);
842
984
  const isNeeded = (id) => exactNeeds.has(id) || wildcardNeeds.some((wildcard) => idMatches(wildcard, id));
843
985
  for (const [id, group] of byId) {
844
- if (group.length > 1)
845
- for (const item of group) item.defects.push(`duplicate: ID ${id} is defined ${group.length} times`);
986
+ if (group.length > 1) for (const item of group) item.defects.push(duplicateId(id, group.length));
846
987
  }
847
- const revHint = (id) => {
988
+ const existingRevisionsOf = (id) => {
848
989
  const revs = revsByKey.get(keyOf(id));
849
- return revs ? ` (revision mismatch: existing revision(s) of ${keyOf(id)}: ${[...revs].sort(compareRev).join(", ")})` : "";
990
+ return revs ? [...revs].sort(compareRev) : null;
991
+ };
992
+ const revHint = (id) => {
993
+ const revs = existingRevisionsOf(id);
994
+ return revs ? ` (revision mismatch: existing revision(s) of ${keyOf(id)}: ${revs.join(", ")})` : "";
995
+ };
996
+ const withRevisions = (defect) => {
997
+ const existingRevisions = existingRevisionsOf(defect.ref);
998
+ if (!existingRevisions) return defect;
999
+ return {
1000
+ kind: defect.kind,
1001
+ ref: defect.ref,
1002
+ existingRevisions,
1003
+ message: `${defect.message} (revision mismatch: existing revision(s) of ${keyOf(defect.ref)}: ${existingRevisions.join(", ")})`
1004
+ };
850
1005
  };
851
1006
  const forwardTargets = buildForwardMap(forwards, byId, exactNeeds, revHint, problems);
852
1007
  for (const item of items) {
853
1008
  item.forwardsTo = forwardTargets.get(item.id) ?? null;
854
- checkItemReferences(item, byId, matchesOf, isNeeded, revHint, forwardTargets);
1009
+ checkItemReferences(item, byId, matchesOf, isNeeded, withRevisions, forwardTargets);
855
1010
  }
856
1011
  markDeepCoverage(items, byId, matchesOf, forwardTargets);
857
1012
  }
@@ -871,19 +1026,15 @@ function makeStyler() {
871
1026
  bold: wrap("1")
872
1027
  };
873
1028
  }
874
- function statusOf(item, style) {
875
- if (item.defects.length > 0) return { mark: style.red("\u2718"), tag: style.red("[defective]") };
876
- if (!item.deepCovered) return { mark: style.yellow("~"), tag: style.yellow("[shallow-covered]") };
877
- return { mark: style.green("\u2714"), tag: style.green("[deep-covered]") };
878
- }
879
- function buildWantedBy(items, byId, matchesOf) {
880
- const wantedBy = /* @__PURE__ */ new Map();
881
- for (const item of items)
882
- for (const need of item.needs)
883
- for (const id of matchesOf(need))
884
- for (const provider of byId.get(id))
885
- (wantedBy.get(provider) ?? wantedBy.set(provider, /* @__PURE__ */ new Set()).get(provider)).add(item);
886
- return wantedBy;
1029
+ var STATUS_STYLES = {
1030
+ defective: ["\u2718", "red"],
1031
+ "shallow-covered": ["~", "yellow"],
1032
+ "deep-covered": ["\u2714", "green"]
1033
+ };
1034
+ function styledStatus(item, style) {
1035
+ const status = statusOf(item);
1036
+ const [mark, color] = STATUS_STYLES[status];
1037
+ return { mark: style[color](mark), tag: style[color](`[${status}]`) };
887
1038
  }
888
1039
  function byFileLine(a, b) {
889
1040
  if (a.file !== b.file) return a.file < b.file ? -1 : 1;
@@ -892,7 +1043,7 @@ function byFileLine(a, b) {
892
1043
  function forwardEdge(item, byId, style, dimLocation) {
893
1044
  const target = byId.get(item.forwardsTo)?.[0];
894
1045
  if (!target) return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${style.red("\u2718 missing")}`;
895
- return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${statusOf(target, style).mark} ${dimLocation(target.file, target.line)}`;
1046
+ return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${styledStatus(target, style).mark} ${dimLocation(target.file, target.line)}`;
896
1047
  }
897
1048
  function needEdges(item, byId, matchesOf, style, dimLocation) {
898
1049
  const lines = [];
@@ -907,7 +1058,7 @@ function needEdges(item, byId, matchesOf, style, dimLocation) {
907
1058
  const covering = byId.get(id)[0];
908
1059
  const arrow = style.dim(`(\u2192 ${id})`);
909
1060
  const ref = wildcard ? `${need} ${arrow}` : need;
910
- lines.push(` ${style.dim("needs")} ${ref} ${statusOf(covering, style).mark} ${dimLocation(covering.file, covering.line)}`);
1061
+ lines.push(` ${style.dim("needs")} ${ref} ${styledStatus(covering, style).mark} ${dimLocation(covering.file, covering.line)}`);
911
1062
  }
912
1063
  }
913
1064
  return lines;
@@ -924,27 +1075,26 @@ function coverEdges(item, byId, style, dimLocation) {
924
1075
  function edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation) {
925
1076
  const lines = [];
926
1077
  if (item.forwardsTo !== null) lines.push(forwardEdge(item, byId, style, dimLocation));
927
- else if (item.origin === "markdown") lines.push(...needEdges(item, byId, matchesOf, style, dimLocation));
1078
+ else if (item.origin === "spec") lines.push(...needEdges(item, byId, matchesOf, style, dimLocation));
928
1079
  lines.push(...coverEdges(item, byId, style, dimLocation));
929
1080
  for (const wanting of wantedBy.get(item) ?? [])
930
1081
  lines.push(` ${style.dim("wanted by")} ${wanting.id} ${dimLocation(wanting.file, wanting.line)}`);
931
1082
  return lines;
932
1083
  }
933
1084
  function renderVerbose(items, out, style, dimLocation) {
934
- const { byId, matchesOf } = buildResolver(items);
935
- const wantedBy = buildWantedBy(items, byId, matchesOf);
1085
+ const { byId, matchesOf, wantedBy } = buildResolver(items);
936
1086
  const sorted = [...items].sort(byFileLine);
937
1087
  let prevFile = null;
938
1088
  for (const item of sorted) {
939
1089
  if (prevFile !== null && item.file !== prevFile) out.push("");
940
1090
  prevFile = item.file;
941
- const { mark, tag } = statusOf(item, style);
1091
+ const { mark, tag } = styledStatus(item, style);
942
1092
  const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
943
1093
  out.push(
944
1094
  `${mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)} ${tag}`,
945
1095
  ...edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation)
946
1096
  );
947
- for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect}`);
1097
+ for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect.message}`);
948
1098
  }
949
1099
  if (sorted.length) out.push("");
950
1100
  }
@@ -952,25 +1102,22 @@ function renderDefective(defective, out, style, dimLocation) {
952
1102
  for (const item of defective) {
953
1103
  const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
954
1104
  out.push(
955
- `${statusOf(item, style).mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)}`
1105
+ `${styledStatus(item, style).mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)}`
956
1106
  );
957
- for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect}`);
1107
+ for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect.message}`);
958
1108
  out.push("");
959
1109
  }
960
1110
  }
961
- function renderSummary(items, defective, problems, out, style) {
962
- const okCount = items.length - defective.length;
963
- const shallowCount = items.filter((item) => item.defects.length === 0 && !item.deepCovered).length;
964
- const markdownCount = items.filter((item) => item.origin === "markdown").length;
965
- const originBreakdown = style.dim(`(${markdownCount} from markdown, ${items.length - markdownCount} from code)`);
1111
+ function renderSummary(summary, out, style) {
1112
+ const originBreakdown = style.dim(`(${summary.specItems} from specs, ${summary.codeItems} from code)`);
966
1113
  out.push(
967
1114
  style.bold("Summary"),
968
- ` items ${items.length} ${originBreakdown}`,
969
- ` ok ${style.green(String(okCount))}`,
970
- ` defective ${defective.length ? style.red(String(defective.length)) : "0"}`
1115
+ ` items ${summary.items} ${originBreakdown}`,
1116
+ ` ok ${style.green(String(summary.okItems))}`,
1117
+ ` defective ${summary.defectiveItems ? style.red(String(summary.defectiveItems)) : "0"}`
971
1118
  );
972
- if (shallowCount) out.push(" " + style.dim(`of the ok items, ${shallowCount} are only shallow-covered (an item further down the tracing chain is defective)`));
973
- if (problems.length) out.push(` problems ${style.yellow(String(problems.length))}`);
1119
+ if (summary.shallowCoveredItems) out.push(" " + style.dim(`of the ok items, ${summary.shallowCoveredItems} are only shallow-covered (an item further down the tracing chain is defective)`));
1120
+ if (summary.problems) out.push(` problems ${style.yellow(String(summary.problems))}`);
974
1121
  out.push("");
975
1122
  }
976
1123
  function report(items, problems, cwd, opts = {}) {
@@ -978,21 +1125,105 @@ function report(items, problems, cwd, opts = {}) {
978
1125
  const style = makeStyler();
979
1126
  const relativePath = (file) => path3.relative(cwd, file) || file;
980
1127
  const dimLocation = (file, line) => style.dim(`${relativePath(file)}:${line}`);
981
- const defective = items.filter((item) => item.defects.length > 0);
1128
+ const summary = summarize(items, problems);
982
1129
  const out = [];
983
1130
  if (verbose) renderVerbose(items, out, style, dimLocation);
984
- else renderDefective(defective, out, style, dimLocation);
1131
+ else renderDefective(items.filter((item) => item.defects.length > 0), out, style, dimLocation);
985
1132
  for (const problem of problems) {
986
1133
  out.push(`${style.yellow("\u26A0")} ${problem.message} ${dimLocation(problem.file, problem.line)}`);
987
1134
  }
988
1135
  if (problems.length) out.push("");
989
- renderSummary(items, defective, problems, out, style);
990
- const clean = defective.length === 0 && problems.length === 0;
1136
+ renderSummary(summary, out, style);
1137
+ const clean = isClean(summary);
991
1138
  out.push(clean ? style.green(style.bold("ok")) : style.red(style.bold("not ok")));
992
1139
  console.log(out.join("\n"));
993
1140
  return clean;
994
1141
  }
995
1142
 
1143
+ // src/report-json.mjs
1144
+ import path4 from "node:path";
1145
+ var SCHEMA_VERSION = 0;
1146
+ function coverStatusOf(item) {
1147
+ const status = /* @__PURE__ */ new Map();
1148
+ for (const defect of item.defects) {
1149
+ if (defect.kind === "orphaned-cover") status.set(defect.ref, "orphaned");
1150
+ else if (defect.kind === "unwanted-cover") status.set(defect.ref, "unwanted");
1151
+ }
1152
+ return (ref) => status.get(ref) ?? "valid";
1153
+ }
1154
+ function buildForwardedFrom(items, byId) {
1155
+ const forwardedFrom = /* @__PURE__ */ new Map();
1156
+ for (const item of items) {
1157
+ if (item.forwardsTo === null) continue;
1158
+ for (const target of byId.get(item.forwardsTo) ?? [])
1159
+ (forwardedFrom.get(target) ?? forwardedFrom.set(target, []).get(target)).push(item);
1160
+ }
1161
+ return forwardedFrom;
1162
+ }
1163
+ function defectDocument(defect) {
1164
+ const out = { kind: defect.kind, ref: defect.ref };
1165
+ if (defect.existingRevisions) out.existingRevisions = defect.existingRevisions;
1166
+ out.message = defect.message;
1167
+ return out;
1168
+ }
1169
+ function buildReportDocument(items, forwards, problems, cwd, opts = {}) {
1170
+ const { version } = opts;
1171
+ if (typeof version !== "string")
1172
+ throw new TypeError(`opts.version is required: it becomes the document's "flashtrace" field`);
1173
+ const relative = (file) => (path4.relative(cwd, file) || file).replaceAll("\\", "/");
1174
+ const location = (x) => ({ file: relative(x.file), line: x.line, character: x.character });
1175
+ const byLocation = (a, b) => {
1176
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
1177
+ if (a.line !== b.line) return a.line - b.line;
1178
+ return a.character - b.character;
1179
+ };
1180
+ const { byId, matchesOf, wantedBy } = buildResolver(items);
1181
+ const forwardedFrom = buildForwardedFrom(items, byId);
1182
+ const resolvedTo = (ref) => matchesOf(ref).sort((a, b) => compareRev(revOf(a), revOf(b)));
1183
+ const itemRefs = (related) => [...related].map((other) => ({ id: other.id, ...location(other) })).sort(byLocation);
1184
+ const itemDocument = (item) => {
1185
+ const coverStatus = coverStatusOf(item);
1186
+ return {
1187
+ id: item.id,
1188
+ title: item.title,
1189
+ origin: item.origin,
1190
+ tags: item.tags,
1191
+ ...location(item),
1192
+ status: statusOf(item),
1193
+ defective: item.defects.length > 0,
1194
+ deepCovered: item.deepCovered,
1195
+ needs: item.needs.map((ref) => ({ ref, resolvedTo: resolvedTo(ref) })),
1196
+ covers: item.covers.map((ref) => ({ ref, status: coverStatus(ref) })),
1197
+ forwardsTo: item.forwardsTo,
1198
+ forwardedFrom: itemRefs(forwardedFrom.get(item) ?? []),
1199
+ defects: item.defects.map(defectDocument),
1200
+ wantedBy: itemRefs(wantedBy.get(item) ?? [])
1201
+ };
1202
+ };
1203
+ const forwardDocument = (forward) => {
1204
+ const document = { from: forward.from, to: forward.to, ...location(forward), effective: forward.effective };
1205
+ if (!forward.effective) document.voidedBy = forward.voidedBy;
1206
+ return document;
1207
+ };
1208
+ const itemDocuments = items.map(itemDocument).sort(byLocation);
1209
+ const problemDocuments = problems.map((problem) => ({ ...location(problem), message: problem.message })).sort(byLocation);
1210
+ const summary = summarize(items, problems);
1211
+ return {
1212
+ schemaVersion: SCHEMA_VERSION,
1213
+ flashtrace: version,
1214
+ ok: isClean(summary),
1215
+ items: itemDocuments,
1216
+ forwards: forwards.map(forwardDocument).sort(byLocation),
1217
+ problems: problemDocuments,
1218
+ summary
1219
+ };
1220
+ }
1221
+ function reportJson(items, forwards, problems, cwd, opts = {}) {
1222
+ const document = buildReportDocument(items, forwards, problems, cwd, opts);
1223
+ console.log(JSON.stringify(document, null, 2));
1224
+ return document.ok;
1225
+ }
1226
+
996
1227
  // src/cli.mjs
997
1228
  var HELP = `Usage: flashtrace [options] [directory-or-file ...]
998
1229
 
@@ -1001,10 +1232,13 @@ Traces requirement coverage between Markdown specifications and source code
1001
1232
  by git are excluded.
1002
1233
 
1003
1234
  Options:
1004
- -t, --tags <t1,t2,...> only import markdown items carrying one of these
1235
+ -t, --tags <t1,t2,...> only import spec items carrying one of these
1005
1236
  tags; add "_" to also include untagged items
1237
+ -f, --format <format> report format: "text" (default) or "json"; --json
1238
+ is shorthand for --format json. The format may be
1239
+ selected only once
1006
1240
  -v, --verbose list every item with its coverage status and trace
1007
- edges, not only the defective ones
1241
+ edges, not only the defective ones; text format only
1008
1242
  -V, --version print the version number
1009
1243
  -h, --help show this help
1010
1244
 
@@ -1017,36 +1251,81 @@ function packageVersion() {
1017
1251
  }
1018
1252
  function splitLongOption(token) {
1019
1253
  const eqIndex = token.startsWith("--") ? token.indexOf("=") : -1;
1020
- return eqIndex === -1 ? [token, null] : [token.slice(0, eqIndex), token.slice(eqIndex + 1)];
1254
+ return eqIndex === -1 ? [token, void 0] : [token.slice(0, eqIndex), token.slice(eqIndex + 1)];
1021
1255
  }
1022
1256
  function rejectValue(name, inline) {
1023
- if (inline !== null) throw new UsageError(`option ${name} does not take a value`);
1024
- }
1257
+ if (inline !== void 0) throw new UsageError(`option ${name} does not take a value`);
1258
+ }
1259
+ function selectFormat(opts, raw, format) {
1260
+ if (opts.formatSelectedBy !== null)
1261
+ throw new UsageError(`the report format is already selected by ${opts.formatSelectedBy}`);
1262
+ opts.format = format;
1263
+ opts.formatSelectedBy = raw;
1264
+ }
1265
+ function reportFormat(raw, value) {
1266
+ if (value !== "text" && value !== "json")
1267
+ throw new UsageError(`invalid value for ${raw}: "${value}" (expected "text" or "json")`);
1268
+ return value;
1269
+ }
1270
+ var LONG_ALIAS = {
1271
+ "-h": "--help",
1272
+ "-v": "--verbose",
1273
+ "-V": "--version",
1274
+ "-t": "--tags",
1275
+ "-f": "--format"
1276
+ };
1277
+ function printHelp() {
1278
+ console.log(HELP);
1279
+ process3.exit(0);
1280
+ }
1281
+ function printVersion() {
1282
+ console.log(packageVersion());
1283
+ process3.exit(0);
1284
+ }
1285
+ function enableVerbose(opts) {
1286
+ opts.verbose = true;
1287
+ }
1288
+ function selectJsonFormat(opts, raw) {
1289
+ selectFormat(opts, raw, "json");
1290
+ }
1291
+ var VALUELESS_OPTIONS = /* @__PURE__ */ new Map([
1292
+ ["--help", printHelp],
1293
+ ["--version", printVersion],
1294
+ ["--verbose", enableVerbose],
1295
+ ["--json", selectJsonFormat]
1296
+ ]);
1297
+ function setFormat(opts, raw, value) {
1298
+ selectFormat(opts, raw, reportFormat(raw, value));
1299
+ }
1300
+ function setTags(opts, raw, value) {
1301
+ opts.tags = value.split(",").map((tag) => tag.trim()).filter(Boolean);
1302
+ }
1303
+ var VALUED_OPTIONS = /* @__PURE__ */ new Map([
1304
+ ["--format", setFormat],
1305
+ ["--tags", setTags]
1306
+ ]);
1025
1307
  function parseArgs(argv) {
1026
- const opts = { dirs: [], tags: null, verbose: false };
1308
+ const opts = { dirs: [], tags: null, verbose: false, format: "text", formatSelectedBy: null };
1027
1309
  for (let i = 0; i < argv.length; i++) {
1028
- const [name, inline] = splitLongOption(argv[i]);
1029
- if (name === "-h" || name === "--help") {
1030
- rejectValue(name, inline);
1031
- console.log(HELP);
1032
- process3.exit(0);
1033
- } else if (name === "-v" || name === "--verbose") {
1034
- rejectValue(name, inline);
1035
- opts.verbose = true;
1036
- } else if (name === "-V" || name === "--version") {
1037
- rejectValue(name, inline);
1038
- console.log(packageVersion());
1039
- process3.exit(0);
1040
- } else if (name === "-t" || name === "--tags") {
1310
+ const [raw, inline] = splitLongOption(argv[i]);
1311
+ const name = LONG_ALIAS[raw] ?? raw;
1312
+ const applyValuelessOption = VALUELESS_OPTIONS.get(name);
1313
+ const applyValuedOption = VALUED_OPTIONS.get(name);
1314
+ if (applyValuelessOption) {
1315
+ rejectValue(raw, inline);
1316
+ applyValuelessOption(opts, raw);
1317
+ } else if (applyValuedOption) {
1041
1318
  const value = inline ?? argv[++i];
1042
- if (!value) throw new UsageError(`missing value for ${name}`);
1043
- opts.tags = value.split(",").map((s) => s.trim()).filter(Boolean);
1044
- } else if (name.startsWith("-")) {
1045
- throw new UsageError(`unknown option: ${name}`);
1319
+ if (!value) throw new UsageError(`missing value for ${raw}`);
1320
+ applyValuedOption(opts, raw, value);
1321
+ } else if (raw.startsWith("-")) {
1322
+ throw new UsageError(`unknown option: ${raw}`);
1046
1323
  } else {
1047
- opts.dirs.push(name);
1324
+ opts.dirs.push(raw);
1048
1325
  }
1049
1326
  }
1327
+ if (opts.format === "json" && opts.verbose)
1328
+ throw new UsageError("-v/--verbose applies to the text format only");
1050
1329
  if (opts.dirs.length === 0) opts.dirs.push(".");
1051
1330
  return opts;
1052
1331
  }
@@ -1058,9 +1337,9 @@ async function main() {
1058
1337
  let items = [];
1059
1338
  for (const file of files) {
1060
1339
  const text = await fs2.readFile(file, "utf8");
1061
- const ext = path4.extname(file).toLowerCase();
1340
+ const ext = path5.extname(file).toLowerCase();
1062
1341
  items.push(
1063
- ...MD_EXT.has(ext) ? parseMarkdown(file, text, problems, forwards) : parseCode(file, text, problems, forwards)
1342
+ ...SPEC_EXT.has(ext) ? parseMarkdown(file, text, problems, forwards) : parseCode(file, text, problems, forwards)
1064
1343
  );
1065
1344
  }
1066
1345
  if (opts.tags) {
@@ -1070,7 +1349,7 @@ async function main() {
1070
1349
  );
1071
1350
  }
1072
1351
  analyze(items, forwards, problems);
1073
- const clean = report(items, problems, process3.cwd(), { verbose: opts.verbose });
1352
+ const clean = opts.format === "json" ? reportJson(items, forwards, problems, process3.cwd(), { version: packageVersion() }) : report(items, problems, process3.cwd(), { verbose: opts.verbose });
1074
1353
  process3.exit(clean ? 0 : 1);
1075
1354
  }
1076
1355
  function runCli() {
@@ -1098,9 +1377,12 @@ function runAsCli() {
1098
1377
  }
1099
1378
  if (runAsCli()) runCli();
1100
1379
  export {
1380
+ DEFECT_KINDS,
1101
1381
  UsageError,
1102
1382
  analyze,
1383
+ buildReportDocument,
1103
1384
  collectFiles,
1104
1385
  parseCode,
1105
- parseMarkdown
1386
+ parseMarkdown,
1387
+ reportJson
1106
1388
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flashtrace",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Lightning-fast, reference-based requirement tracing that works anywhere.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {