-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown-docs.test.ts
More file actions
782 lines (657 loc) · 24.2 KB
/
Copy pathmarkdown-docs.test.ts
File metadata and controls
782 lines (657 loc) · 24.2 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
/**
* Unit tests for markdown docs generator
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { PipelineContext } from '../../../src/core/types.js';
import type { ArchletteIR } from '../../../src/core/types-ir.js';
// Mock node modules
vi.mock('node:fs');
vi.mock('node:path');
vi.mock('node:module', () => ({
createRequire: vi.fn(() => vi.fn(() => mockNunjucks)),
}));
// Mock path resolver
vi.mock('../../../src/core/path-resolver.js', () => ({
getCliDir: vi.fn(() => '/test/cli/dir'),
resolveArchlettePath: vi.fn((path: string) => `/resolved/${path}`),
}));
// Mock nunjucks
const mockNunjucks = {
configure: vi.fn(() => mockEnv),
};
const mockEnv = {
addFilter: vi.fn((_name: string, _fn: (...args: any[]) => any) => {}),
render: vi.fn((template: string, _data?: any) => `# Generated ${template} content`),
};
describe('markdown-docs generator', () => {
let markdownDocs: any;
let mockContext: PipelineContext;
let mockFs: any;
let mockPath: any;
beforeEach(async () => {
// Reset all mocks
vi.clearAllMocks();
// Import and setup mocked modules
mockFs = await import('node:fs');
mockPath = await import('node:path');
// Setup default mock implementations
mockFs.mkdirSync = vi.fn();
mockFs.writeFileSync = vi.fn();
mockFs.copyFileSync = vi.fn();
mockFs.existsSync = vi.fn(() => true);
mockFs.readdirSync = vi.fn(() => []);
mockPath.join = vi.fn((...args: string[]) => args.join('/'));
mockPath.dirname = vi.fn((p: string) => p.split('/').slice(0, -1).join('/'));
mockPath.basename = vi.fn((p: string, ext?: string) => {
const base = p.split('/').pop() || '';
return ext ? base.replace(ext, '') : base;
});
mockPath.relative = vi.fn((from: string, to: string) => {
// Simple mock: just return the 'to' path
return to.replace(from + '/', '');
});
// Mock fileURLToPath
vi.mock('node:url', () => ({
fileURLToPath: vi.fn((url: string) => url.replace('file://', '')),
}));
// Create mock IR
const mockIR: ArchletteIR = {
version: '1.0.0',
system: {
name: 'Test System',
description: 'Test system description',
},
actors: [
{
id: 'user',
name: 'User',
type: 'Person',
description: 'End user',
},
],
containers: [
{
id: 'api',
name: 'API Service',
type: 'Service',
layer: 'Application',
},
],
components: [
{
id: 'api__auth',
containerId: 'api',
name: 'Authentication',
type: 'module',
description: 'Authentication component',
},
{
id: 'api__user',
containerId: 'api',
name: 'UserManagement',
type: 'module',
description: 'User management component',
},
],
code: [
{
id: 'api__auth__handler',
componentId: 'api__auth',
name: 'AuthHandler',
type: 'class',
filePath: '/src/auth/handler.ts',
},
],
deployments: [],
deploymentRelationships: [],
containerRelationships: [],
componentRelationships: [],
codeRelationships: [],
};
// Create mock context
mockContext = {
config: {
project: {
name: 'test-project',
props: {},
},
paths: {
ir_out: 'test-ir.json',
dsl_out: 'test-dsl.txt',
render_out: 'test-render',
docs_out: 'test-docs',
},
defaults: {
includes: [],
excludes: [],
props: {},
},
extractors: [],
validators: [],
generators: [],
renderers: [],
docs: [],
},
state: {
aggregatedIR: mockIR,
rendererOutputs: [
{
renderer: 'structurizr',
format: 'png',
files: [
'structurizr-SystemContext.png',
'structurizr-Containers.png',
'structurizr-Components.png',
'structurizr-Classes_api__auth.png',
],
timestamp: Date.now(),
},
],
docOutputs: [],
},
log: {
info: vi.fn(),
debug: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
} as any;
// Import the module under test after mocks are set up
markdownDocs = (await import('../../../src/docs/builtin/markdown-docs.js')).default;
});
afterEach(() => {
vi.resetModules();
});
describe('markdownDocs', () => {
it('generates README.md system overview page', async () => {
await markdownDocs(mockContext);
// Verify README.md was written
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('README.md'),
expect.stringContaining('Generated system.md.njk content'),
'utf8',
);
});
it('generates individual component pages', async () => {
await markdownDocs(mockContext);
// Verify component pages were written
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining(`${sanitizeFileName('api__auth.md')}`),
expect.stringContaining('Generated component.md.njk content'),
'utf8',
);
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('api__user.md'),
expect.stringContaining('Generated component.md.njk content'),
'utf8',
);
});
it('creates output directory if it does not exist', async () => {
await markdownDocs(mockContext);
expect(mockFs.mkdirSync).toHaveBeenCalledWith(expect.any(String), {
recursive: true,
});
});
it('configures nunjucks with template directory', async () => {
await markdownDocs(mockContext);
expect(mockNunjucks.configure).toHaveBeenCalledWith(
expect.stringContaining('templates'),
expect.objectContaining({
autoescape: false,
trimBlocks: true,
lstripBlocks: true,
}),
);
});
it('adds custom nunjucks filters', async () => {
await markdownDocs(mockContext);
// Verify all custom filters were added
expect(mockEnv.addFilter).toHaveBeenCalledWith('kebabCase', expect.any(Function));
expect(mockEnv.addFilter).toHaveBeenCalledWith(
'forwardSlashes',
expect.any(Function),
);
expect(mockEnv.addFilter).toHaveBeenCalledWith('date', expect.any(Function));
expect(mockEnv.addFilter).toHaveBeenCalledWith(
'selectattr',
expect.any(Function),
);
expect(mockEnv.addFilter).toHaveBeenCalledWith('map', expect.any(Function));
expect(mockEnv.addFilter).toHaveBeenCalledWith('first', expect.any(Function));
});
it('renders system page with IR data and diagrams', async () => {
await markdownDocs(mockContext);
expect(mockEnv.render).toHaveBeenCalledWith(
'system.md.njk',
expect.objectContaining({
system: mockContext.state.aggregatedIR?.system,
actors: mockContext.state.aggregatedIR?.actors,
containers: mockContext.state.aggregatedIR?.containers,
components: mockContext.state.aggregatedIR?.components,
systemDiagrams: expect.any(Array),
containerDiagrams: expect.any(Array),
componentDiagrams: expect.any(Array),
}),
);
});
it('renders component pages with component-specific data', async () => {
await markdownDocs(mockContext);
// Check first component
expect(mockEnv.render).toHaveBeenCalledWith(
'component.md.njk',
expect.objectContaining({
component: mockContext.state.aggregatedIR?.components[0],
system: mockContext.state.aggregatedIR?.system,
codeItems: expect.any(Array),
}),
);
// Check second component
expect(mockEnv.render).toHaveBeenCalledWith(
'component.md.njk',
expect.objectContaining({
component: mockContext.state.aggregatedIR?.components[1],
}),
);
});
it('filters code items by component ID', async () => {
await markdownDocs(mockContext);
// Find the render call for comp-auth
const authRenderCall = vi
.mocked(mockEnv.render)
.mock.calls.find((call) => call[1]?.component?.id === 'api__auth');
if (!authRenderCall || !authRenderCall[1]) {
throw new Error('Mock render call for api__auth not found');
} else {
expect(authRenderCall).toBeDefined();
expect(authRenderCall![1].codeItems).toHaveLength(1);
expect(authRenderCall![1].codeItems[0].id).toBe('api__auth__handler');
}
});
it('updates pipeline state with generated files', async () => {
await markdownDocs(mockContext);
expect(mockContext.state.docOutputs).toHaveLength(1);
expect(mockContext.state.docOutputs![0]).toMatchObject({
generator: 'markdown-docs',
format: 'markdown',
files: expect.arrayContaining(['README.md', 'api__auth.md', 'api__user.md']),
timestamp: expect.any(Number),
});
});
it('initializes docOutputs array if undefined', async () => {
mockContext.state.docOutputs = undefined;
await markdownDocs(mockContext);
expect(mockContext.state.docOutputs).toBeDefined();
expect(Array.isArray(mockContext.state.docOutputs)).toBe(true);
});
it('prefers validatedIR over aggregatedIR', async () => {
const validatedIR = {
...mockContext.state.aggregatedIR!,
system: { name: 'Validated System' },
};
mockContext.state.validatedIR = validatedIR;
await markdownDocs(mockContext);
// Verify validatedIR was used
expect(mockEnv.render).toHaveBeenCalledWith(
'system.md.njk',
expect.objectContaining({
system: validatedIR.system,
}),
);
});
it('throws error when no IR data found', async () => {
mockContext.state.aggregatedIR = undefined;
mockContext.state.validatedIR = undefined;
await expect(markdownDocs(mockContext)).rejects.toThrow(
'No IR data found. Run extract and validate stages first.',
);
expect(mockContext.log.error).toHaveBeenCalledWith(
'No IR data found in pipeline state',
);
});
it('logs progress information', async () => {
await markdownDocs(mockContext);
expect(mockContext.log.info).toHaveBeenCalledWith(
'Markdown Docs: generating documentation...',
);
expect(mockContext.log.info).toHaveBeenCalledWith(
'Generating system overview page...',
);
expect(mockContext.log.info).toHaveBeenCalledWith(
expect.stringContaining('Generating 2 component page(s)'),
);
expect(mockContext.log.info).toHaveBeenCalledWith('Generated README.md');
expect(mockContext.log.info).toHaveBeenCalledWith(
expect.stringContaining('Generated 2 component page(s)'),
);
expect(mockContext.log.info).toHaveBeenCalledWith('Markdown Docs: completed');
});
it('logs debug information about IR and renderers', async () => {
await markdownDocs(mockContext);
expect(mockContext.log.debug).toHaveBeenCalledWith(
'Loaded IR: 2 components, 1 actors',
);
expect(mockContext.log.debug).toHaveBeenCalledWith('Found 1 renderer output(s)');
});
it('handles empty renderer outputs gracefully', async () => {
mockContext.state.rendererOutputs = [];
await markdownDocs(mockContext);
// Should still generate docs, just without diagrams
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('README.md'),
expect.any(String),
'utf8',
);
});
it('handles undefined renderer outputs gracefully', async () => {
mockContext.state.rendererOutputs = undefined;
await markdownDocs(mockContext);
// Should still generate docs, just without diagrams
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('README.md'),
expect.any(String),
'utf8',
);
});
it('looks for diagrams in render_out directory', async () => {
await markdownDocs(mockContext);
// Verify existsSync was called with paths in the render_out directory
const existsSyncCalls = vi.mocked(mockFs.existsSync).mock.calls;
const diagramCalls = existsSyncCalls.filter((call: any[]) =>
call[0].includes('test-render'),
);
expect(diagramCalls.length).toBeGreaterThan(0);
});
});
describe('custom nunjucks filters', () => {
it('kebabCase filter converts strings to kebab-case', async () => {
await markdownDocs(mockContext);
const kebabCaseFilter = vi
.mocked(mockEnv.addFilter)
.mock.calls.find((call) => call[0] === 'kebabCase')![1] as (
str: string,
) => string;
expect(kebabCaseFilter('Hello World')).toBe('hello-world');
expect(kebabCaseFilter('Test Component 123')).toBe('test-component-123');
expect(kebabCaseFilter('Special@Chars#Here')).toBe('specialcharshere');
});
it('forwardSlashes filter converts backslashes to forward slashes', async () => {
await markdownDocs(mockContext);
const forwardSlashesFilter = vi
.mocked(mockEnv.addFilter)
.mock.calls.find((call) => call[0] === 'forwardSlashes')![1] as (
str: string,
) => string;
expect(forwardSlashesFilter('C:\\Users\\test\\file.txt')).toBe(
'C:/Users/test/file.txt',
);
expect(forwardSlashesFilter('path/to/file')).toBe('path/to/file');
});
it('date filter formats dates correctly', async () => {
await markdownDocs(mockContext);
const dateFilter = vi
.mocked(mockEnv.addFilter)
.mock.calls.find((call) => call[0] === 'date')![1] as (
date: Date,
format: string,
) => string;
const testDate = new Date('2023-05-15T14:30:45');
expect(dateFilter(testDate, 'YYYY-MM-DD')).toBe('2023-05-15');
expect(dateFilter(testDate, 'YYYY-MM-DD HH:mm:ss')).toBe('2023-05-15 14:30:45');
});
it('selectattr filter filters array by attribute value', async () => {
await markdownDocs(mockContext);
const selectattrFilter = vi
.mocked(mockEnv.addFilter)
.mock.calls.find((call) => call[0] === 'selectattr')![1] as (
items: any[],
attr: string,
operator: string,
value: any,
) => any[];
const items = [
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' },
{ name: 'Charlie', role: 'admin' },
];
const result = selectattrFilter(items, 'role', 'equalto', 'admin');
expect(result).toHaveLength(2);
expect(result[0].name).toBe('Alice');
expect(result[1].name).toBe('Charlie');
});
it('map filter extracts attribute values from array', async () => {
await markdownDocs(mockContext);
const mapFilter = vi
.mocked(mockEnv.addFilter)
.mock.calls.find((call) => call[0] === 'map')![1] as (
items: any[],
keyword: string,
attr: string,
) => any[];
const items = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
];
const result = mapFilter(items, 'attribute', 'name');
expect(result).toEqual(['Alice', 'Bob']);
});
it('first filter returns first element of array', async () => {
await markdownDocs(mockContext);
const firstFilter = vi
.mocked(mockEnv.addFilter)
.mock.calls.find((call) => call[0] === 'first')![1] as (
items: any[] | null,
) => any;
expect(firstFilter([1, 2, 3])).toBe(1);
expect(firstFilter(['a', 'b', 'c'])).toBe('a');
expect(firstFilter([])).toBeUndefined();
expect(firstFilter(null)).toBeUndefined();
});
});
describe('diagram finding logic', () => {
it('finds system context diagrams', async () => {
await markdownDocs(mockContext);
// Verify existsSync was called for system diagrams
const existsCalls = vi.mocked(mockFs.existsSync).mock.calls;
const systemDiagramCheck = existsCalls.some((call: any[]) =>
String(call[0]).includes('SystemContext'),
);
expect(systemDiagramCheck).toBe(true);
});
it('finds container diagrams', async () => {
await markdownDocs(mockContext);
const existsCalls = vi.mocked(mockFs.existsSync).mock.calls;
const containerDiagramCheck = existsCalls.some((call: any[]) =>
String(call[0]).includes('Containers'),
);
expect(containerDiagramCheck).toBe(true);
});
it('finds component diagrams', async () => {
await markdownDocs(mockContext);
const existsCalls = vi.mocked(mockFs.existsSync).mock.calls;
const componentDiagramCheck = existsCalls.some((call: any[]) =>
String(call[0]).includes('Components'),
);
expect(componentDiagramCheck).toBe(true);
});
it('finds class diagrams for components', async () => {
await markdownDocs(mockContext);
const existsCalls = vi.mocked(mockFs.existsSync).mock.calls;
const classDiagramCheck = existsCalls.some((call: any[]) =>
String(call[0]).includes('Classes'),
);
expect(classDiagramCheck).toBe(true);
});
it('skips non-existent diagrams', async () => {
mockFs.existsSync = vi.fn((path: string) => {
// Only SystemContext exists
return String(path).includes('SystemContext');
});
await markdownDocs(mockContext);
// Should still generate docs successfully
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('README.md'),
expect.any(String),
'utf8',
);
});
it('filters out non-image renderer outputs', async () => {
mockContext.state.rendererOutputs = [
{
renderer: 'structurizr',
format: 'dsl',
files: ['structurizr.dsl'],
timestamp: Date.now(),
},
{
renderer: 'plantuml',
format: 'png',
files: ['diagram.png'],
timestamp: Date.now(),
},
];
await markdownDocs(mockContext);
// Only PNG/SVG files should be checked, not DSL
const existsCalls = vi.mocked(mockFs.existsSync).mock.calls;
const dslCheck = existsCalls.some((call: any[]) =>
String(call[0]).includes('structurizr.dsl'),
);
expect(dslCheck).toBe(false);
});
it('supports SVG diagram files', async () => {
mockContext.state.rendererOutputs = [
{
renderer: 'mermaid',
format: 'svg',
files: ['structurizr-SystemContext.svg', 'structurizr-Containers.svg'],
timestamp: Date.now(),
},
];
await markdownDocs(mockContext);
// SVG files should be checked
const existsCalls = vi.mocked(mockFs.existsSync).mock.calls;
const svgChecks = existsCalls.filter((call: any[]) =>
String(call[0]).includes('.svg'),
);
expect(svgChecks.length).toBeGreaterThan(0);
});
});
describe('brand image copying', () => {
it('copies brand images (PNG and SVG) to <docs_out>/../images/ when source dir exists', async () => {
mockFs.readdirSync = vi.fn(() => [
'archlette-stainedglassA-light.png',
'archlette-stainedglassA-dark.png',
'archlette-stainedglassA-light.svg',
'archlette-stainedglassA-dark.svg',
]);
await markdownDocs(mockContext);
// images dir should be created one level above docs_out
expect(mockFs.mkdirSync).toHaveBeenCalledWith(expect.stringContaining('images'), {
recursive: true,
});
// all four files (2 PNG + 2 SVG) should be copied
expect(mockFs.copyFileSync).toHaveBeenCalledTimes(4);
expect(mockFs.copyFileSync).toHaveBeenCalledWith(
expect.stringContaining('archlette-stainedglassA-light.png'),
expect.stringContaining('archlette-stainedglassA-light.png'),
);
expect(mockFs.copyFileSync).toHaveBeenCalledWith(
expect.stringContaining('archlette-stainedglassA-dark.png'),
expect.stringContaining('archlette-stainedglassA-dark.png'),
);
expect(mockFs.copyFileSync).toHaveBeenCalledWith(
expect.stringContaining('archlette-stainedglassA-light.svg'),
expect.stringContaining('archlette-stainedglassA-light.svg'),
);
expect(mockFs.copyFileSync).toHaveBeenCalledWith(
expect.stringContaining('archlette-stainedglassA-dark.svg'),
expect.stringContaining('archlette-stainedglassA-dark.svg'),
);
});
it('copies images to a path one level above docs_out', async () => {
mockFs.readdirSync = vi.fn(() => ['archlette-stainedglassA-light.png']);
await markdownDocs(mockContext);
// destination should be <docsDir>/../images/<file>
const copyCall = vi.mocked(mockFs.copyFileSync).mock.calls[0];
expect(copyCall).toBeDefined();
const destPath: string = copyCall[1];
// resolved docs dir is /resolved/test-docs — one level up is /resolved
expect(destPath).toContain('/resolved');
expect(destPath).toContain('images');
expect(destPath).toContain('archlette-stainedglassA-light.png');
});
it('skips image copy when source images dir does not exist', async () => {
mockFs.existsSync = vi.fn((p: string) => !String(p).includes('images'));
await markdownDocs(mockContext);
expect(mockFs.copyFileSync).not.toHaveBeenCalled();
});
it('generated README references images with correct relative path', async () => {
await markdownDocs(mockContext);
const readmeContent: string = vi
.mocked(mockFs.writeFileSync)
.mock.calls.find((call) => String(call[0]).includes('README.md'))![1] as string;
// template output contains the ../images/ reference
expect(readmeContent).toContain('Generated system.md.njk content');
});
});
describe('edge cases', () => {
it('handles components without container', async () => {
mockContext.state.aggregatedIR!.components[0].containerId = 'non-existent';
await markdownDocs(mockContext);
// Should still generate component page
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining(`${sanitizeFileName('api__auth.md')}`),
expect.any(String),
'utf8',
);
});
it('handles components with no code items', async () => {
mockContext.state.aggregatedIR!.code = [];
await markdownDocs(mockContext);
// Verify empty code items array was passed
const componentRenderCall = vi
.mocked(mockEnv.render)
.mock.calls.find((call) => call[0] === 'component.md.njk');
expect(componentRenderCall).toBeDefined();
expect(componentRenderCall![1].codeItems).toEqual([]);
});
it('handles zero components', async () => {
mockContext.state.aggregatedIR!.components = [];
await markdownDocs(mockContext);
// Should generate README + container page (but no component pages)
expect(mockFs.writeFileSync).toHaveBeenCalledTimes(2);
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('README.md'),
expect.any(String),
'utf8',
);
});
it('handles component IDs with special characters', async () => {
mockContext.state.aggregatedIR!.components = [
{
id: 'comp-auth-v2',
containerId: 'api',
name: 'Auth V2',
type: 'module',
},
];
await markdownDocs(mockContext);
const name = sanitizeFileName(mockContext.state.aggregatedIR!.components[0].id);
expect(mockFs.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining(name),
expect.any(String),
'utf8',
);
});
});
});
function sanitizeFileName(name: string): string {
// Remove or replace characters not allowed in Windows or Linux filenames
// Windows: \ / : * ? " < > |
// Linux: /
return name
.replace(/[\\/:*?"<>|]/g, '-') // Replace invalid characters with hyphen
.replace(/^\.+/, '') // Remove leading dots
.replace(/\s+/g, '-') // Replace spaces with hyphen
.replace(/-+/g, '-') // Collapse multiple hyphens
.replace(/^-+|-+$/g, ''); // Trim leading/trailing hyphens
}