-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvalidate-docs-examples.mts
More file actions
1196 lines (1024 loc) · 35.1 KB
/
Copy pathvalidate-docs-examples.mts
File metadata and controls
1196 lines (1024 loc) · 35.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node --import @swc-node/register/esm-register
/**
* Validates all PromptScript code examples in documentation.
*
* Usage:
* pnpm docs:validate # Validate all examples
* pnpm docs:validate --check # CI mode (exit 1 on errors)
* pnpm docs:validate --update-snapshots # Update output snapshots
* pnpm docs:validate --update-outputs # Update inline output blocks in docs
*
* Output blocks in documentation:
* Use <!-- output:TARGET for="META_ID" --> to mark expected output blocks.
* The validator will compare them against actual compiled output.
*
* Main output file:
* <!-- output:github for="my-example" -->
* ```markdown
* ## shortcuts
* - /review: Review code
* ```
* <!-- /output -->
*
* Additional files (e.g., .prompt.md):
* <!-- output:github for="my-example" file="prompts/test.prompt.md" -->
* ```markdown
* ---
* description: 'Test prompt'
* ---
* Write tests.
* ```
* <!-- /output -->
*/
import {
readFileSync,
writeFileSync,
readdirSync,
statSync,
mkdirSync,
existsSync,
rmSync,
} from 'fs';
import { join, relative } from 'path';
import { createHash } from 'crypto';
// Import PromptScript packages (using swc-node for direct TypeScript imports)
import { parse, type ParseResult } from '../packages/parser/src/index.js';
import { validate, type ValidationResult } from '../packages/validator/src/index.js';
import { compile, type CompileResult } from '../packages/browser-compiler/src/index.js';
// Types
interface CodeBlock {
content: string;
file: string;
line: number;
column: number;
metaId: string | null;
rawMatch: string;
}
interface ValidationError {
file: string;
line: number;
column: number;
code: string;
message: string;
context?: string;
suggestion?: string;
}
interface SnapshotDiff {
file: string;
metaId: string;
target: string;
expected: string;
actual: string;
}
interface OutputBlock {
target: string;
metaId: string;
outputFile: string | null; // null = main output file, string = specific file path
expectedOutput: string;
file: string;
line: number;
startIndex: number;
endIndex: number;
rawMatch: string;
}
interface OutputMismatch {
file: string;
line: number;
metaId: string;
target: string;
expected: string;
actual: string;
}
interface ValidationStats {
filesProcessed: number;
codeBlocksFound: number;
parseErrors: number;
validationErrors: number;
snapshotDiffs: number;
snapshotsUpdated: number;
snapshotsRemoved: number;
outputBlocksFound: number;
outputMismatches: number;
outputsUpdated: number;
}
// Constants
const DOCS_DIR = 'docs';
const SNAPSHOTS_DIR = 'docs/__snapshots__';
const TARGETS = ['claude', 'github', 'cursor'] as const;
const TARGET_EXTENSIONS: Record<string, string> = {
claude: '.md',
github: '.md',
cursor: '.mdc',
};
// Regex to match PRS code blocks (same as add-playground-links.mts)
const CODE_BLOCK_REGEX = /```(?:prs|promptscript)(?:[ \t]+[^\n]*)?\n([\s\S]*?)```/g;
// Regex to match output blocks: <!-- output:TARGET for="META_ID" [file="PATH"] --> ... <!-- /output -->
// The closing tag is optional. The file attribute is optional (defaults to main output file).
const OUTPUT_BLOCK_REGEX =
/<!-- output:(\w+) for="([^"]+)"(?: file="([^"]+)")? -->\s*```(?:markdown|md|yaml)?\n([\s\S]*?)```\s*(?:<!-- \/output -->)?/g;
// Colors for terminal output
const colors = {
red: (s: string) => `\x1b[31m${s}\x1b[0m`,
green: (s: string) => `\x1b[32m${s}\x1b[0m`,
yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,
blue: (s: string) => `\x1b[34m${s}\x1b[0m`,
gray: (s: string) => `\x1b[90m${s}\x1b[0m`,
bold: (s: string) => `\x1b[1m${s}\x1b[0m`,
};
// Extraction utilities
/**
* Remove common leading whitespace from all lines (dedent).
*/
function dedent(text: string): string {
const lines = text.split('\n');
let minIndent = Infinity;
for (const line of lines) {
if (line.trim().length === 0) continue;
const match = line.match(/^(\s*)/);
if (match) {
minIndent = Math.min(minIndent, match[1].length);
}
}
if (minIndent === Infinity || minIndent === 0) {
return text;
}
return lines.map((line) => line.slice(minIndent)).join('\n');
}
/**
* Extract @meta.id from code content.
*/
function extractMetaId(code: string): string | null {
// Match @meta { id: "value" ... } or @meta { id: "value", ... }
const match = code.match(/@meta\s*\{\s*id:\s*"([^"]+)"/);
return match ? match[1] : null;
}
/**
* Generate a short hash for code without meta.id.
*/
function hashCode(code: string): string {
return createHash('md5').update(code).digest('hex').slice(0, 8);
}
/**
* Recursively find all markdown files in a directory.
*/
function findMarkdownFiles(dir: string): string[] {
const files: string[] = [];
if (!existsSync(dir)) {
return files;
}
for (const entry of readdirSync(dir)) {
const fullPath = join(dir, entry);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
// Skip special directories
if (
!['node_modules', 'dist', '.git', 'coverage', 'api-reference', '__snapshots__'].includes(
entry
)
) {
files.push(...findMarkdownFiles(fullPath));
}
} else if (entry.endsWith('.md')) {
files.push(fullPath);
}
}
return files;
}
/**
* Check if a code block should be skipped for validation.
* Returns true for fragments, multi-file examples, and intentionally invalid examples.
*/
function shouldSkipBlock(content: string, markdownContext: string): boolean {
// Skip blocks that show multiple files (have multiple # FileName patterns)
const fileHeaderPattern = /^# [A-Za-z][\w.-]*\.prs$/gm;
const fileHeaders = content.match(fileHeaderPattern);
if (fileHeaders && fileHeaders.length > 1) {
return true;
}
// Skip blocks marked as invalid examples (❌ Invalid, # Invalid, etc.)
if (content.includes('# ❌') || content.includes('❌ Invalid') || content.includes('# Invalid')) {
return true;
}
// Skip blocks preceded by "**Wrong:**" in markdown context (intentionally invalid examples)
if (markdownContext.includes('**Wrong:**') || markdownContext.includes('Wrong:')) {
return true;
}
// Skip blocks preceded by "**❌ Invalid:**" or "**✅ Valid:**" markers
// These are typically showing intentionally broken or fixed examples
if (markdownContext.includes('**❌ Invalid:**') || markdownContext.includes('❌ Invalid:')) {
return true;
}
if (markdownContext.includes('**✅ Valid') || markdownContext.includes('✅ Valid')) {
return true;
}
// Skip blocks with placeholder syntax like { ... } - these are structural overviews
if (content.includes('{ ... }') || content.includes('{...}')) {
return true;
}
// Skip blocks that appear to be fragments (don't have @meta or meaningful structure)
const hasMetaBlock = content.includes('@meta');
const hasMainBlocks = /@(identity|standards|context|knowledge|guards)\s*\{/.test(content);
// If no @meta and no main blocks, it's likely a fragment showing partial syntax
if (!hasMetaBlock && !hasMainBlocks) {
return true;
}
// Skip blocks containing @extend (proposed syntax not yet supported by parser)
if (content.includes('@extend ')) {
return true;
}
// Skip blocks with unquoted file paths in arrays (e.g., ./references/foo.md)
if (/^\s+\.\/[\w/.-]+\.md\s*$/m.test(content)) {
return true;
}
// Skip blocks that are showing YAML-like config syntax (not .prs)
if (
content.match(/^tags:\s*\[/) ||
content.match(/^code:\s*\{/) ||
content.match(/^strictness:\s*range/)
) {
return true;
}
// Skip blocks that show registry namespaces as standalone examples
if (content.match(/^@inherit\s+@[\w/-]+@v[\d.]+$/m) && !hasMetaBlock) {
return true;
}
return false;
}
/**
* Extract all code blocks from a markdown file.
*/
function extractCodeBlocks(filePath: string): CodeBlock[] {
const content = readFileSync(filePath, 'utf-8');
const blocks: CodeBlock[] = [];
let match: RegExpExecArray | null;
CODE_BLOCK_REGEX.lastIndex = 0;
while ((match = CODE_BLOCK_REGEX.exec(content)) !== null) {
const codeContent = match[1];
const trimmedCode = dedent(codeContent).trim();
// Skip empty or very short examples
if (trimmedCode.length < 10) {
continue;
}
// Calculate line number
const beforeMatch = content.slice(0, match.index);
const line = (beforeMatch.match(/\n/g) || []).length + 1;
// Calculate column (position in line)
const lastNewline = beforeMatch.lastIndexOf('\n');
const column = match.index - lastNewline;
// Get surrounding markdown context (look for headers or special markers)
const contextStart = Math.max(0, match.index - 200);
const contextEnd = Math.min(content.length, match.index + match[0].length + 100);
const markdownContext = content.slice(contextStart, contextEnd);
// Skip blocks that shouldn't be validated
if (shouldSkipBlock(trimmedCode, markdownContext)) {
continue;
}
const metaId = extractMetaId(trimmedCode);
blocks.push({
content: trimmedCode,
file: filePath,
line,
column,
metaId,
rawMatch: match[0],
});
}
return blocks;
}
/**
* Extract all output blocks from a markdown file.
* These are marked with <!-- output:TARGET for="META_ID" [file="PATH"] --> comments.
*/
function extractOutputBlocks(filePath: string): OutputBlock[] {
const content = readFileSync(filePath, 'utf-8');
const blocks: OutputBlock[] = [];
let match: RegExpExecArray | null;
OUTPUT_BLOCK_REGEX.lastIndex = 0;
while ((match = OUTPUT_BLOCK_REGEX.exec(content)) !== null) {
const target = match[1];
const metaId = match[2];
const outputFile = match[3] || null; // Optional file attribute
const expectedOutput = match[4].trim();
// Calculate line number
const beforeMatch = content.slice(0, match.index);
const line = (beforeMatch.match(/\n/g) || []).length + 1;
blocks.push({
target,
metaId,
outputFile,
expectedOutput,
file: filePath,
line,
startIndex: match.index,
endIndex: match.index + match[0].length,
rawMatch: match[0],
});
}
return blocks;
}
// Validation utilities
/**
* Parse a code block and return errors.
*/
function parseCodeBlock(block: CodeBlock): ValidationError[] {
const errors: ValidationError[] = [];
try {
const result: ParseResult = parse(block.content);
if (!result.success || result.errors.length > 0) {
for (const error of result.errors) {
const errorLine = block.line + (error.line ?? 1) - 1;
const errorColumn = error.column ?? block.column;
// Extract context line
const lines = block.content.split('\n');
const contextLine = lines[error.line ? error.line - 1 : 0] ?? '';
// Generate suggestion for common errors
let suggestion: string | undefined;
if (error.message.includes('Unexpected token') && contextLine.includes(',')) {
suggestion = 'Remove comma. PromptScript uses space-separated key-value pairs in blocks.';
}
errors.push({
file: block.file,
line: errorLine,
column: errorColumn,
code: 'PS1000',
message: error.message,
context: contextLine,
suggestion,
});
}
}
} catch (err) {
errors.push({
file: block.file,
line: block.line,
column: block.column,
code: 'PS0000',
message: `Parse error: ${(err as Error).message}`,
});
}
return errors;
}
/**
* Validate parsed AST and return errors.
*/
function validateCodeBlock(block: CodeBlock): ValidationError[] {
const errors: ValidationError[] = [];
try {
const parseResult = parse(block.content);
if (!parseResult.success || !parseResult.ast) {
return []; // Parse errors already reported
}
const validationResult: ValidationResult = validate(parseResult.ast, {
// Disable some rules for doc examples
disableRules: ['required-meta-id', 'required-meta-syntax'],
});
for (const error of validationResult.errors) {
const errorLine = block.line + (error.location?.line ?? 1) - 1;
errors.push({
file: block.file,
line: errorLine,
column: error.location?.column ?? block.column,
code: error.ruleId,
message: error.message,
});
}
} catch (err) {
errors.push({
file: block.file,
line: block.line,
column: block.column,
code: 'PS0000',
message: `Validation error: ${(err as Error).message}`,
});
}
return errors;
}
// Snapshot utilities
/**
* Get the snapshot directory path for a code block.
* Uses meta.id + line number to ensure uniqueness even when the same ID appears multiple times.
*/
function getSnapshotDir(block: CodeBlock, rootDir: string): string {
const relFile = relative(rootDir, block.file);
const baseId = block.metaId ?? `_hash_${hashCode(block.content)}`;
// Include line number to distinguish blocks with same ID in same file
const identifier = `${baseId}_L${block.line}`;
return join(rootDir, SNAPSHOTS_DIR, relFile, identifier);
}
/**
* Compile a code block for all targets.
* Returns a map where keys are either:
* - "target" for main output file (e.g., "github" -> copilot-instructions.md)
* - "target:path" for additional files (e.g., "github:prompts/test.prompt.md")
*/
async function compileCodeBlock(block: CodeBlock): Promise<Map<string, string> | null> {
try {
const files = new Map<string, string>([['example.prs', block.content]]);
// Use 'full' version to generate all additional files (prompts, instructions, skills, agents)
const formattersWithConfig = TARGETS.map((name) => ({
name,
config: { version: 'full' },
}));
const result: CompileResult = await compile(files, 'example.prs', {
formatters: formattersWithConfig,
bundledRegistry: true,
});
if (!result.success) {
return null;
}
const outputs = new Map<string, string>();
// Track main output files per formatter
const mainFiles: Record<string, string> = {
claude: 'CLAUDE.md',
github: '.github/copilot-instructions.md',
cursor: '.cursor/rules/project.mdc',
};
for (const [path, output] of result.outputs) {
// Determine formatter from path
let formatter: string | null = null;
if (path.includes('CLAUDE') || path === 'CLAUDE.md' || path.startsWith('.claude/')) {
formatter = 'claude';
} else if (path.includes('.github') || path.includes('copilot')) {
formatter = 'github';
} else if (path.includes('.cursor')) {
formatter = 'cursor';
}
if (!formatter) continue;
// Check if this is the main output file
const isMainFile = path === mainFiles[formatter] || path.endsWith(mainFiles[formatter]);
if (isMainFile) {
// Main file: use just the formatter name as key
outputs.set(formatter, output.content);
} else {
// Additional file: use "formatter:relativePath" as key
// Extract relative path within the formatter's directory
let relativePath = path;
if (formatter === 'github' && path.startsWith('.github/')) {
relativePath = path.slice('.github/'.length);
} else if (formatter === 'cursor' && path.startsWith('.cursor/')) {
relativePath = path.slice('.cursor/'.length);
} else if (formatter === 'claude' && path.startsWith('.claude/')) {
relativePath = path.slice('.claude/'.length);
}
outputs.set(`${formatter}:${relativePath}`, output.content);
}
}
return outputs;
} catch {
return null;
}
}
/**
* Read existing snapshot for a target.
*/
function readSnapshot(snapshotDir: string, target: string): string | null {
const ext = TARGET_EXTENSIONS[target] ?? '.md';
const path = join(snapshotDir, `${target}${ext}`);
if (existsSync(path)) {
return readFileSync(path, 'utf-8');
}
return null;
}
/**
* Write snapshot for a target.
*/
function writeSnapshot(snapshotDir: string, target: string, content: string): void {
mkdirSync(snapshotDir, { recursive: true });
const ext = TARGET_EXTENSIONS[target] ?? '.md';
const path = join(snapshotDir, `${target}${ext}`);
writeFileSync(path, content);
}
/**
* Compare snapshots and return diffs.
*/
function compareSnapshots(
block: CodeBlock,
outputs: Map<string, string>,
rootDir: string
): SnapshotDiff[] {
const diffs: SnapshotDiff[] = [];
const snapshotDir = getSnapshotDir(block, rootDir);
for (const target of TARGETS) {
const actual = outputs.get(target);
if (!actual) continue;
const expected = readSnapshot(snapshotDir, target);
if (expected === null) {
// No snapshot exists
diffs.push({
file: block.file,
metaId: block.metaId ?? hashCode(block.content),
target,
expected: '(no snapshot)',
actual,
});
} else if (normalizeOutput(expected) !== normalizeOutput(actual)) {
diffs.push({
file: block.file,
metaId: block.metaId ?? hashCode(block.content),
target,
expected,
actual,
});
}
}
return diffs;
}
/**
* Normalize output for comparison (ignore timestamps, trailing whitespace, quote styles, etc.).
*/
function normalizeOutput(content: string): string {
return (
content
// Remove PromptScript timestamp markers
.replace(
/<!-- PromptScript \d{4}-\d{2}-\d{2}T[\d:.]+ - do not edit -->/g,
'<!-- PromptScript TIMESTAMP - do not edit -->'
)
// Normalize line endings
.replace(/\r\n/g, '\n')
// Normalize YAML quote styles (single to double quotes for consistent comparison)
// This handles Prettier reformatting '**/*.ts' to "**/*.ts"
.replace(/: '([^']+)'/g, ': "$1"')
.replace(/- '([^']+)'/g, '- "$1"')
// Normalize inline list format from Prettier (collapse to multiline for comparison)
// "- item1 - item2" becomes "- item1\n- item2" equivalent
.replace(/ - /g, '\n- ')
// Remove leading whitespace before list items (indentation normalization)
.replace(/^(\s*)- /gm, '- ')
// Remove trailing whitespace from each line
.split('\n')
.map((line) => line.trimEnd())
.join('\n')
// Remove trailing newlines
.trimEnd()
);
}
/**
* Update snapshots for a code block.
*/
function updateSnapshots(block: CodeBlock, outputs: Map<string, string>, rootDir: string): number {
const snapshotDir = getSnapshotDir(block, rootDir);
let updated = 0;
for (const target of TARGETS) {
const content = outputs.get(target);
if (content) {
writeSnapshot(snapshotDir, target, content);
updated++;
}
}
return updated;
}
/**
* Get all snapshot directories that currently exist.
*/
function getExistingSnapshotDirs(rootDir: string): Set<string> {
const snapshotsBase = join(rootDir, SNAPSHOTS_DIR);
const existing = new Set<string>();
if (!existsSync(snapshotsBase)) {
return existing;
}
// Recursively find all snapshot directories (those containing target files)
function walkDir(dir: string): void {
if (!existsSync(dir)) return;
for (const entry of readdirSync(dir)) {
const fullPath = join(dir, entry);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
// Check if this directory contains snapshot files (claude.md, github.md, cursor.mdc)
const hasSnapshots = TARGETS.some((target) => {
const ext = TARGET_EXTENSIONS[target] ?? '.md';
return existsSync(join(fullPath, `${target}${ext}`));
});
if (hasSnapshots) {
existing.add(fullPath);
} else {
// Continue walking subdirectories
walkDir(fullPath);
}
}
}
}
walkDir(snapshotsBase);
return existing;
}
/**
* Clean up stale snapshot directories that are no longer valid.
* A snapshot is stale if its directory doesn't match any current code block.
*/
function cleanStaleSnapshots(validSnapshotDirs: Set<string>, rootDir: string): number {
const existing = getExistingSnapshotDirs(rootDir);
let removed = 0;
for (const dir of existing) {
if (!validSnapshotDirs.has(dir)) {
// This snapshot directory is stale - remove it
rmSync(dir, { recursive: true, force: true });
removed++;
}
}
// Also clean up empty parent directories in __snapshots__
const snapshotsBase = join(rootDir, SNAPSHOTS_DIR);
cleanEmptyDirs(snapshotsBase);
return removed;
}
/**
* Recursively remove empty directories.
*/
function cleanEmptyDirs(dir: string): boolean {
if (!existsSync(dir)) return true;
const entries = readdirSync(dir);
let allEmpty = true;
for (const entry of entries) {
const fullPath = join(dir, entry);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
const isEmpty = cleanEmptyDirs(fullPath);
if (!isEmpty) {
allEmpty = false;
}
} else {
allEmpty = false;
}
}
// If directory is empty, remove it (but not the root __snapshots__ dir)
if (allEmpty && dir !== join(process.cwd(), SNAPSHOTS_DIR)) {
rmSync(dir, { recursive: true, force: true });
return true;
}
return allEmpty;
}
/**
* Validate output blocks against compiled outputs.
*/
function validateOutputBlocks(
outputBlocks: OutputBlock[],
compiledOutputs: Map<string, Map<string, string>>
): OutputMismatch[] {
const mismatches: OutputMismatch[] = [];
for (const block of outputBlocks) {
const outputs = compiledOutputs.get(block.metaId);
if (!outputs) {
// No compiled output for this metaId - the source example might not exist or failed to compile
mismatches.push({
file: block.file,
line: block.line,
metaId: block.metaId,
target: block.outputFile ? `${block.target}:${block.outputFile}` : block.target,
expected: block.expectedOutput,
actual: `(no compiled output - check if example with id="${block.metaId}" exists and compiles)`,
});
continue;
}
// Build the key to look up: either "target" or "target:path"
const outputKey = block.outputFile ? `${block.target}:${block.outputFile}` : block.target;
const actualOutput = outputs.get(outputKey);
if (!actualOutput) {
// If looking for a specific file, list available files for this target
const availableFiles = Array.from(outputs.keys())
.filter((k) => k === block.target || k.startsWith(`${block.target}:`))
.join(', ');
mismatches.push({
file: block.file,
line: block.line,
metaId: block.metaId,
target: outputKey,
expected: block.expectedOutput,
actual: `(no output for "${outputKey}". Available: ${availableFiles || 'none'})`,
});
continue;
}
// Compare normalized outputs
if (normalizeOutput(block.expectedOutput) !== normalizeOutput(actualOutput)) {
mismatches.push({
file: block.file,
line: block.line,
metaId: block.metaId,
target: outputKey,
expected: block.expectedOutput,
actual: actualOutput,
});
}
}
return mismatches;
}
/**
* Update output blocks in markdown files with actual compiled output.
*/
function updateOutputBlocks(
outputBlocks: OutputBlock[],
compiledOutputs: Map<string, Map<string, string>>
): number {
// Group blocks by file
const blocksByFile = new Map<string, OutputBlock[]>();
for (const block of outputBlocks) {
const existing = blocksByFile.get(block.file) ?? [];
existing.push(block);
blocksByFile.set(block.file, existing);
}
let updatedCount = 0;
for (const [filePath, blocks] of blocksByFile) {
let content = readFileSync(filePath, 'utf-8');
let offset = 0;
// Sort blocks by startIndex to process in order
const sortedBlocks = [...blocks].sort((a, b) => a.startIndex - b.startIndex);
for (const block of sortedBlocks) {
const outputs = compiledOutputs.get(block.metaId);
if (!outputs) continue;
// Build the key to look up: either "target" or "target:path"
const outputKey = block.outputFile ? `${block.target}:${block.outputFile}` : block.target;
const actualOutput = outputs.get(outputKey);
if (!actualOutput) continue;
// Build the new block content, preserving the file attribute if present
const fileAttr = block.outputFile ? ` file="${block.outputFile}"` : '';
const newBlock = `<!-- output:${block.target} for="${block.metaId}"${fileAttr} -->\n\`\`\`markdown\n${actualOutput.trim()}\n\`\`\`\n<!-- /output -->`;
// Replace in content (accounting for previous replacements via offset)
const adjustedStart = block.startIndex + offset;
const adjustedEnd = block.endIndex + offset;
content = content.slice(0, adjustedStart) + newBlock + content.slice(adjustedEnd);
// Update offset for next replacement
offset += newBlock.length - (block.endIndex - block.startIndex);
updatedCount++;
}
writeFileSync(filePath, content);
}
return updatedCount;
}
// Reporting utilities
/**
* Format an error with context.
*/
function formatError(error: ValidationError, rootDir: string): string {
const relPath = relative(rootDir, error.file);
const lines: string[] = [];
lines.push(`${colors.bold(relPath)}:${error.line}:${error.column}`);
lines.push(` ${colors.red('error')} ${colors.gray(error.code)}: ${error.message}`);
if (error.context) {
lines.push('');
lines.push(` ${colors.gray(error.context)}`);
// Add caret pointing to error position
if (error.column > 0) {
const padding = ' '.repeat(error.column - 1);
lines.push(` ${padding}${colors.red('^')}`);
}
}
if (error.suggestion) {
lines.push('');
lines.push(` ${colors.blue('Fix')}: ${error.suggestion}`);
}
return lines.join('\n');
}
/**
* Format a snapshot diff.
*/
function formatSnapshotDiff(diff: SnapshotDiff, rootDir: string): string {
const relPath = relative(rootDir, diff.file);
const lines: string[] = [];
lines.push(`${colors.bold(relPath)} (${diff.metaId}) - ${diff.target}`);
lines.push('');
if (diff.expected === '(no snapshot)') {
lines.push(` ${colors.yellow('Missing snapshot')} - run with --update-snapshots to create`);
} else {
// Show a simplified diff
const expectedLines = diff.expected.split('\n').slice(0, 5);
const actualLines = diff.actual.split('\n').slice(0, 5);
lines.push(` ${colors.red('Expected')} (first 5 lines):`);
for (const line of expectedLines) {
lines.push(` ${colors.gray(line)}`);
}
lines.push('');
lines.push(` ${colors.green('Actual')} (first 5 lines):`);
for (const line of actualLines) {
lines.push(` ${colors.gray(line)}`);
}
}
return lines.join('\n');
}
/**
* Format an output mismatch.
*/
function formatOutputMismatch(mismatch: OutputMismatch, rootDir: string): string {
const relPath = relative(rootDir, mismatch.file);
const lines: string[] = [];
lines.push(`${colors.bold(relPath)}:${mismatch.line} (${mismatch.metaId}) - ${mismatch.target}`);
lines.push(` ${colors.red('Output mismatch')}`);
lines.push('');
if (mismatch.actual.startsWith('(no ')) {
lines.push(` ${colors.yellow(mismatch.actual)}`);
} else {
// Show a simplified diff
const expectedLines = mismatch.expected.split('\n').slice(0, 5);
const actualLines = mismatch.actual.split('\n').slice(0, 5);
lines.push(` ${colors.red('Expected')} (from docs, first 5 lines):`);
for (const line of expectedLines) {
lines.push(` ${colors.gray(line)}`);
}
lines.push('');
lines.push(` ${colors.green('Actual')} (from compiler, first 5 lines):`);
for (const line of actualLines) {
lines.push(` ${colors.gray(line)}`);
}
}
lines.push('');
lines.push(` Run with ${colors.blue('--update-outputs')} to fix.`);
return lines.join('\n');
}
/**
* Print summary statistics.
*/
function printSummary(stats: ValidationStats): void {
console.log('\n' + colors.bold('Summary'));
console.log(` Files processed: ${stats.filesProcessed}`);
console.log(` Code blocks found: ${stats.codeBlocksFound}`);
if (stats.outputBlocksFound > 0) {
console.log(` Output blocks found: ${stats.outputBlocksFound}`);
}
if (stats.parseErrors > 0) {
console.log(` ${colors.red('Parse errors')}: ${stats.parseErrors}`);
}
if (stats.validationErrors > 0) {
console.log(` ${colors.yellow('Validation errors')}: ${stats.validationErrors}`);
}
if (stats.snapshotDiffs > 0) {
console.log(` ${colors.yellow('Snapshot differences')}: ${stats.snapshotDiffs}`);
}
if (stats.snapshotsUpdated > 0) {
console.log(` ${colors.green('Snapshots updated')}: ${stats.snapshotsUpdated}`);
}
if (stats.snapshotsRemoved > 0) {
console.log(` ${colors.green('Stale snapshots removed')}: ${stats.snapshotsRemoved}`);
}
if (stats.outputMismatches > 0) {
console.log(` ${colors.yellow('Output mismatches')}: ${stats.outputMismatches}`);
}
if (stats.outputsUpdated > 0) {
console.log(` ${colors.green('Outputs updated')}: ${stats.outputsUpdated}`);
}