@mgks/docmd 0.2.6 → 0.2.8

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.
@@ -1,19 +1,27 @@
1
1
  // Source file from the docmd project — https://github.com/mgks/docmd
2
2
 
3
3
  const fs = require('fs-extra');
4
- const MarkdownIt = require('markdown-it');
5
- const matter = require('gray-matter');
6
- const hljs = require('highlight.js');
7
- const attrs = require('markdown-it-attrs');
8
4
  const path = require('path');
9
- const markdown_it_footnote = require('markdown-it-footnote');
10
- const markdown_it_task_lists = require('markdown-it-task-lists');
11
- const markdown_it_abbr = require('markdown-it-abbr');
12
- const markdown_it_deflist = require('markdown-it-deflist');
5
+ const matter = require('gray-matter');
6
+ const { createMarkdownItInstance } = require('./markdown/setup');
7
+
8
+ function decodeHtmlEntities(html) {
9
+ return html.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, ' ');
10
+ }
11
+
12
+ function extractHeadingsFromHtml(htmlContent) {
13
+ const headings = [];
14
+ const headingRegex = /<h([1-6])[^>]*?id="([^"]*)"[^>]*?>([\s\S]*?)<\/h\1>/g;
15
+ let match;
16
+ while ((match = headingRegex.exec(htmlContent)) !== null) {
17
+ const level = parseInt(match[1], 10);
18
+ const id = match[2];
19
+ const text = decodeHtmlEntities(match[3].replace(/<\/?[^>]+(>|$)/g, ''));
20
+ headings.push({ id, level, text });
21
+ }
22
+ return headings;
23
+ }
13
24
 
14
- /**
15
- * Formats an absolute path to be relative to the current working directory for cleaner logging.
16
- */
17
25
  function formatPathForDisplay(absolutePath) {
18
26
  const CWD = process.cwd();
19
27
  const relativePath = path.relative(CWD, absolutePath);
@@ -23,775 +31,47 @@ function formatPathForDisplay(absolutePath) {
23
31
  return relativePath;
24
32
  }
25
33
 
26
- function createMarkdownItInstance(config) {
27
- const mdOptions = {
28
- html: true,
29
- linkify: true,
30
- typographer: true,
31
- breaks: true,
32
- };
33
-
34
- // Conditionally enable highlighting
35
- if (config.theme?.codeHighlight !== false) {
36
- mdOptions.highlight = function (str, lang) {
37
- // Handle mermaid diagrams
38
- if (lang === 'mermaid') {
39
- return `<pre class="mermaid">${new MarkdownIt().utils.escapeHtml(str)}</pre>`;
40
- }
41
-
42
- if (lang && hljs.getLanguage(lang)) {
43
- try {
44
- return `<pre class="hljs"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`;
45
- } catch (e) { console.error(`Highlighting error for lang ${lang}:`, e); }
46
- }
47
- return `<pre class="hljs"><code>${new MarkdownIt().utils.escapeHtml(str)}</code></pre>`;
48
- };
49
- } else {
50
- // Even if highlighting is disabled, we need to handle mermaid
51
- mdOptions.highlight = function (str, lang) {
52
- if (lang === 'mermaid') {
53
- return `<pre class="mermaid">${new MarkdownIt().utils.escapeHtml(str)}</pre>`;
54
- }
55
- return `<pre><code>${new MarkdownIt().utils.escapeHtml(str)}</code></pre>`;
56
- };
57
- }
58
-
59
- const md = new MarkdownIt(mdOptions);
60
-
61
- // --- Attach all plugins and rules to this instance ---
62
- md.use(attrs, { leftDelimiter: '{', rightDelimiter: '}' });
63
- md.use(markdown_it_footnote);
64
- md.use(markdown_it_task_lists);
65
- md.use(markdown_it_abbr);
66
- md.use(markdown_it_deflist);
67
- md.use(headingIdPlugin);
68
-
69
- // Register renderers for all containers
70
- Object.keys(containers).forEach(containerName => {
71
- const container = containers[containerName];
72
- md.renderer.rules[`container_${containerName}_open`] = container.render;
73
- md.renderer.rules[`container_${containerName}_close`] = container.render;
74
- });
75
-
76
- // Register the enhanced rules
77
- md.block.ruler.before('fence', 'steps_container', stepsContainerRule, {
78
- alt: ['paragraph', 'reference', 'blockquote', 'list']
79
- });
80
- md.block.ruler.before('fence', 'enhanced_tabs', enhancedTabsRule, {
81
- alt: ['paragraph', 'reference', 'blockquote', 'list']
82
- });
83
- md.block.ruler.before('paragraph', 'advanced_container', advancedContainerRule, {
84
- alt: ['paragraph', 'reference', 'blockquote', 'list']
85
- });
86
-
87
- // Register all custom renderers
88
- md.renderer.rules.ordered_list_open = customOrderedListOpenRenderer;
89
- md.renderer.rules.list_item_open = customListItemOpenRenderer;
90
- md.renderer.rules.image = customImageRenderer;
91
-
92
- // Register tabs renderers
93
- md.renderer.rules.tabs_open = tabsOpenRenderer;
94
- md.renderer.rules.tabs_nav_open = tabsNavOpenRenderer;
95
- md.renderer.rules.tabs_nav_close = tabsNavCloseRenderer;
96
- md.renderer.rules.tabs_nav_item = tabsNavItemRenderer;
97
- md.renderer.rules.tabs_content_open = tabsContentOpenRenderer;
98
- md.renderer.rules.tabs_content_close = tabsContentCloseRenderer;
99
- md.renderer.rules.tab_pane_open = tabPaneOpenRenderer;
100
- md.renderer.rules.tab_pane_close = tabPaneCloseRenderer;
101
- md.renderer.rules.tabs_close = tabsCloseRenderer;
102
-
103
- // Register heading ID plugin
104
- md.use(headingIdPlugin);
105
-
106
- // Register standalone closing rule
107
- md.block.ruler.before('paragraph', 'standalone_closing', standaloneClosingRule, {
108
- alt: ['paragraph', 'reference', 'blockquote', 'list']
109
- });
110
-
111
- return md;
112
- }
113
-
114
- // ===================================================================
115
- // --- ADVANCED NESTED CONTAINER SYSTEM ---
116
- // ===================================================================
117
-
118
- // Container definitions
119
- // To add a new container type:
120
- // 1. Add it to this containers object
121
- // 2. Define the render function for opening (nesting === 1) and closing (nesting === -1)
122
- // 3. The system will automatically register it and support nesting
123
- const containers = {
124
- card: {
125
- name: 'card',
126
- render: (tokens, idx) => {
127
- if (tokens[idx].nesting === 1) {
128
- const title = tokens[idx].info ? tokens[idx].info.trim() : '';
129
- return `<div class="docmd-container card">${title ? `<div class="card-title">${title}</div>` : ''}<div class="card-content">`;
130
- }
131
- return '</div></div>';
132
- }
133
- },
134
- callout: {
135
- name: 'callout',
136
- render: (tokens, idx) => {
137
- if (tokens[idx].nesting === 1) {
138
- const [type, ...titleParts] = tokens[idx].info.split(' ');
139
- const title = titleParts.join(' ');
140
- return `<div class="docmd-container callout callout-${type}">${title ? `<div class="callout-title">${title}</div>` : ''}<div class="callout-content">`;
141
- }
142
- return '</div></div>';
143
- }
144
- },
145
- button: {
146
- name: 'button',
147
- selfClosing: true, // Mark as self-closing
148
- render: (tokens, idx) => {
149
- if (tokens[idx].nesting === 1) {
150
- const parts = tokens[idx].info.split(' ');
151
- const text = parts[0];
152
- const url = parts[1];
153
- const color = parts[2];
154
- const colorStyle = color && color.startsWith('color:') ? ` style="background-color: ${color.split(':')[1]}"` : '';
155
-
156
- // Check if URL starts with 'external:' for new tab behavior
157
- let finalUrl = url;
158
- let targetAttr = '';
159
- if (url && url.startsWith('external:')) {
160
- finalUrl = url.substring(9); // Remove 'external:' prefix
161
- targetAttr = ' target="_blank" rel="noopener noreferrer"';
162
- }
163
-
164
- return `<a href="${finalUrl}" class="docmd-button"${colorStyle}${targetAttr}>${text.replace(/_/g, ' ')}</a>`;
165
- }
166
- return '';
167
- }
168
- },
169
- steps: {
170
- name: 'steps',
171
- render: (tokens, idx) => {
172
- if (tokens[idx].nesting === 1) {
173
- // Add a unique class for steps containers to enable CSS-based numbering reset
174
- // The steps-numbering class will style only direct ol > li children as numbered steps
175
- return '<div class="docmd-container steps steps-reset steps-numbering">';
176
- }
177
- return '</div>';
178
- }
179
- }
180
- // Future containers can be added here:
181
- // timeline: {
182
- // name: 'timeline',
183
- // render: (tokens, idx) => {
184
- // if (tokens[idx].nesting === 1) {
185
- // return '<div class="docmd-container timeline">';
186
- // }
187
- // return '</div>';
188
- // }
189
- // },
190
- // changelog: {
191
- // name: 'changelog',
192
- // render: (tokens, idx) => {
193
- // if (tokens[idx].nesting === 1) {
194
- // return '<div class="docmd-container changelog">';
195
- // }
196
- // return '</div>';
197
- // }
198
- // }
199
- };
200
-
201
- // Advanced container rule with proper nesting support
202
- function advancedContainerRule(state, startLine, endLine, silent) {
203
- const start = state.bMarks[startLine] + state.tShift[startLine];
204
- const max = state.eMarks[startLine];
205
- const lineContent = state.src.slice(start, max).trim();
206
-
207
- // Check if this is a container opening
208
- const containerMatch = lineContent.match(/^:::\s*(\w+)(?:\s+(.+))?$/);
209
- if (!containerMatch) return false;
210
-
211
- const [, containerName, params] = containerMatch;
212
- const container = containers[containerName];
213
-
214
- if (!container) return false;
215
-
216
- if (silent) return true;
217
-
218
- // Handle self-closing containers (like buttons)
219
- if (container.selfClosing) {
220
- const openToken = state.push(`container_${containerName}_open`, 'div', 1);
221
- openToken.info = params || '';
222
- const closeToken = state.push(`container_${containerName}_close`, 'div', -1);
223
- state.line = startLine + 1;
224
- return true;
225
- }
226
-
227
- // Find the closing tag with proper nesting handling
228
- let nextLine = startLine;
229
- let found = false;
230
- let depth = 1;
231
-
232
- while (nextLine < endLine) {
233
- nextLine++;
234
- const nextStart = state.bMarks[nextLine] + state.tShift[nextLine];
235
- const nextMax = state.eMarks[nextLine];
236
- const nextContent = state.src.slice(nextStart, nextMax).trim();
237
-
238
- // Check for opening tags (any container)
239
- if (nextContent.startsWith(':::')) {
240
- const containerMatch = nextContent.match(/^:::\s*(\w+)/);
241
- if (containerMatch && containerMatch[1] !== containerName) {
242
- // Only increment depth for non-self-closing containers
243
- const innerContainer = containers[containerMatch[1]];
244
- if (innerContainer && innerContainer.render && !innerContainer.selfClosing) {
245
- depth++;
246
- }
247
- continue;
248
- }
249
- }
250
-
251
- // Check for closing tags
252
- if (nextContent === ':::') {
253
- depth--;
254
- if (depth === 0) {
255
- found = true;
256
- break;
257
- }
258
- }
259
- }
260
-
261
- if (!found) return false;
262
-
263
- // Create tokens
264
- const openToken = state.push(`container_${containerName}_open`, 'div', 1);
265
- openToken.info = params || '';
266
-
267
- // Process content recursively
268
- const oldParentType = state.parentType;
269
- const oldLineMax = state.lineMax;
270
-
271
- state.parentType = 'container';
272
- state.lineMax = nextLine;
273
-
274
- // Process the content inside the container
275
- state.md.block.tokenize(state, startLine + 1, nextLine);
276
-
277
- const closeToken = state.push(`container_${containerName}_close`, 'div', -1);
278
-
279
- state.parentType = oldParentType;
280
- state.lineMax = oldLineMax;
281
- state.line = nextLine + 1;
282
-
283
- return true;
284
- }
285
-
286
- // --- Simple Steps Container Rule ---
287
- function stepsContainerRule(state, startLine, endLine, silent) {
288
- const start = state.bMarks[startLine] + state.tShift[startLine];
289
- const max = state.eMarks[startLine];
290
- const lineContent = state.src.slice(start, max).trim();
291
- if (lineContent !== '::: steps') return false;
292
- if (silent) return true;
293
-
294
- // Find the closing ':::' for the steps container
295
- let nextLine = startLine;
296
- let found = false;
297
- let depth = 1;
34
+ async function processMarkdownFile(filePath, md, config) {
35
+ const rawContent = await fs.readFile(filePath, 'utf8');
36
+ let frontmatter, markdownContent;
298
37
 
299
- while (nextLine < endLine) {
300
- nextLine++;
301
- const nextStart = state.bMarks[nextLine] + state.tShift[nextLine];
302
- const nextMax = state.eMarks[nextLine];
303
- const nextContent = state.src.slice(nextStart, nextMax).trim();
304
-
305
- // Skip tab markers as they don't affect container depth
306
- if (nextContent.startsWith('== tab')) {
307
- continue;
308
- }
309
-
310
- // Check for opening tags (any container)
311
- if (nextContent.startsWith(':::')) {
312
- const containerMatch = nextContent.match(/^:::\s*(\w+)/);
313
- if (containerMatch) {
314
- const containerName = containerMatch[1];
315
- // Only count non-self-closing containers for depth
316
- const innerContainer = containers[containerName];
317
- if (innerContainer && !innerContainer.selfClosing) {
318
- depth++;
319
- }
320
- continue;
321
- }
322
- }
323
-
324
- // Check for closing tags
325
- if (nextContent === ':::') {
326
- depth--;
327
- if (depth === 0) {
328
- found = true;
329
- break;
330
- }
38
+ try {
39
+ ({ data: frontmatter, content: markdownContent } = matter(rawContent));
40
+ } catch (e) {
41
+ console.error(`❌ Error parsing frontmatter in ${formatPathForDisplay(filePath)}:`);
42
+ console.error(` ${e.message}`);
43
+ return null;
331
44
  }
332
- }
333
-
334
- if (!found) return false;
335
-
336
- // Create tokens for steps container
337
- const openToken = state.push('container_steps_open', 'div', 1);
338
- openToken.info = '';
339
-
340
- // Process content normally but disable automatic list processing
341
- const oldParentType = state.parentType;
342
- const oldLineMax = state.lineMax;
343
45
 
344
- state.parentType = 'container';
345
- state.lineMax = nextLine;
346
-
347
- // Process the content inside the container
348
- state.md.block.tokenize(state, startLine + 1, nextLine);
349
-
350
- const closeToken = state.push('container_steps_close', 'div', -1);
351
-
352
- state.parentType = oldParentType;
353
- state.lineMax = oldLineMax;
354
- state.line = nextLine + 1;
355
-
356
- return true;
357
- }
358
-
359
- // --- Enhanced tabs rule with nested content support ---
360
- function enhancedTabsRule(state, startLine, endLine, silent) {
361
- const start = state.bMarks[startLine] + state.tShift[startLine];
362
- const max = state.eMarks[startLine];
363
- const lineContent = state.src.slice(start, max).trim();
364
-
365
- if (lineContent !== '::: tabs') return false;
366
- if (silent) return true;
367
-
368
- // Find the closing tag with proper nesting handling
369
- let nextLine = startLine;
370
- let found = false;
371
- let depth = 1;
372
- while (nextLine < endLine) {
373
- nextLine++;
374
- const nextStart = state.bMarks[nextLine] + state.tShift[nextLine];
375
- const nextMax = state.eMarks[nextLine];
376
- const nextContent = state.src.slice(nextStart, nextMax).trim();
377
-
378
- // Check for opening tags (any container)
379
- if (nextContent.startsWith(':::')) {
380
- const containerMatch = nextContent.match(/^:::\s*(\w+)/);
381
- if (containerMatch && containerMatch[1] !== 'tabs') {
382
- // Don't increment depth for steps - they have their own depth counting
383
- if (containerMatch[1] === 'steps') {
384
- continue;
385
- }
386
- // Only increment depth for non-self-closing containers
387
- const innerContainer = containers[containerMatch[1]];
388
- if (innerContainer && !innerContainer.selfClosing) {
389
- depth++;
390
- }
391
- continue;
392
- }
393
- }
394
-
395
- // Check for closing tags
396
- if (nextContent === ':::') {
397
- depth--;
398
- if (depth === 0) {
399
- found = true;
400
- break;
401
- }
46
+ if (!frontmatter.title && config.autoTitleFromH1 !== false) {
47
+ const h1Match = markdownContent.match(/^#\s+(.*)/m);
48
+ if (h1Match) frontmatter.title = h1Match[1].trim();
402
49
  }
403
- }
404
- if (!found) return false;
405
-
406
- // Get the raw content by manually extracting lines
407
- let content = '';
408
- for (let i = startLine + 1; i < nextLine; i++) {
409
- const lineStart = state.bMarks[i] + state.tShift[i];
410
- const lineEnd = state.eMarks[i];
411
- content += state.src.slice(lineStart, lineEnd) + '\n';
412
- }
413
-
414
- // Parse tabs manually
415
- const lines = content.split('\n');
416
- const tabs = [];
417
- let currentTab = null;
418
- let currentContent = [];
419
50
 
420
- for (let i = 0; i < lines.length; i++) {
421
- const line = lines[i].trim();
422
- const tabMatch = line.match(/^==\s*tab\s+(?:"([^"]+)"|(\S+))$/);
423
-
424
- if (tabMatch) {
425
- // Save previous tab if exists
426
- if (currentTab) {
427
- currentTab.content = currentContent.join('\n').trim();
428
- tabs.push(currentTab);
429
- }
430
- // Start new tab
431
- const title = tabMatch[1] || tabMatch[2];
432
- currentTab = { title: title, content: '' };
433
- currentContent = [];
434
- } else if (currentTab) {
435
- // Add line to current tab content (only if not empty and not a tab marker)
436
- if (lines[i].trim() && !lines[i].trim().startsWith('==')) {
437
- currentContent.push(lines[i]);
438
- }
51
+ let htmlContent, headings;
52
+ if (frontmatter.noStyle === true) {
53
+ htmlContent = markdownContent;
54
+ headings = [];
55
+ } else {
56
+ htmlContent = md.render(markdownContent);
57
+ headings = extractHeadingsFromHtml(htmlContent);
439
58
  }
440
- }
441
59
 
442
- // Save the last tab
443
- if (currentTab) {
444
- currentTab.content = currentContent.join('\n').trim();
445
- tabs.push(currentTab);
446
- }
447
-
448
- // Create tabs structure
449
- const openToken = state.push('tabs_open', 'div', 1);
450
- openToken.attrs = [['class', 'docmd-tabs']];
451
-
452
- // Create navigation
453
- const navToken = state.push('tabs_nav_open', 'div', 1);
454
- navToken.attrs = [['class', 'docmd-tabs-nav']];
455
- tabs.forEach((tab, index) => {
456
- const navItemToken = state.push('tabs_nav_item', 'div', 0);
457
- navItemToken.attrs = [['class', `docmd-tabs-nav-item ${index === 0 ? 'active' : ''}`]];
458
- navItemToken.content = tab.title;
459
- });
460
- state.push('tabs_nav_close', 'div', -1);
461
-
462
- // Create content
463
- const contentToken = state.push('tabs_content_open', 'div', 1);
464
- contentToken.attrs = [['class', 'docmd-tabs-content']];
465
- tabs.forEach((tab, index) => {
466
- const paneToken = state.push('tab_pane_open', 'div', 1);
467
- paneToken.attrs = [['class', `docmd-tab-pane ${index === 0 ? 'active' : ''}`]];
468
-
469
- // Process tab content with the main markdown-it instance
470
- if (tab.content.trim()) {
471
- const tabContent = tab.content.trim();
472
-
473
- // Create a separate markdown-it instance for tab content to avoid double processing
474
- const tabMd = new MarkdownIt({
475
- html: true,
476
- linkify: true,
477
- typographer: true,
478
- breaks: true,
479
- highlight: function (str, lang) {
480
- // Handle mermaid diagrams in tabs
481
- if (lang === 'mermaid') {
482
- return '<pre class="mermaid">' + MarkdownIt.utils.escapeHtml(str) + '</pre>';
483
- }
484
-
485
- if (lang && hljs.getLanguage(lang)) {
486
- try {
487
- return '<pre class="hljs"><code>' +
488
- hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
489
- '</code></pre>';
490
- } catch (e) { console.error(`Error highlighting language ${lang}:`, e); }
491
- }
492
- return '<pre class="hljs"><code>' + MarkdownIt.utils.escapeHtml(str) + '</code></pre>';
493
- }
494
- });
495
-
496
- // Register the same plugins for the tab markdown instance
497
- tabMd.use(attrs, { leftDelimiter: '{', rightDelimiter: '}' });
498
- tabMd.use(markdown_it_footnote);
499
- tabMd.use(markdown_it_task_lists);
500
- tabMd.use(markdown_it_abbr);
501
- tabMd.use(markdown_it_deflist);
502
-
503
- // Register container renderers for the tab markdown instance
504
- Object.keys(containers).forEach(containerName => {
505
- const container = containers[containerName];
506
- tabMd.renderer.rules[`container_${containerName}_open`] = container.render;
507
- tabMd.renderer.rules[`container_${containerName}_close`] = container.render;
508
- });
509
-
510
- // Register the enhanced rules for the tab markdown instance
511
- tabMd.block.ruler.before('fence', 'enhanced_tabs', enhancedTabsRule, {
512
- alt: ['paragraph', 'reference', 'blockquote', 'list']
513
- });
514
- tabMd.block.ruler.before('paragraph', 'steps_container', stepsContainerRule, {
515
- alt: ['paragraph', 'reference', 'blockquote', 'list']
516
- });
517
- tabMd.block.ruler.before('paragraph', 'advanced_container', advancedContainerRule, {
518
- alt: ['paragraph', 'reference', 'blockquote', 'list']
519
- });
520
-
521
- // Register custom renderers for the tab markdown instance
522
- tabMd.renderer.rules.ordered_list_open = customOrderedListOpenRenderer;
523
- tabMd.renderer.rules.list_item_open = customListItemOpenRenderer;
524
- tabMd.renderer.rules.image = customImageRenderer;
525
-
526
- // Register tabs renderers for the tab markdown instance
527
- tabMd.renderer.rules.tabs_open = tabsOpenRenderer;
528
- tabMd.renderer.rules.tabs_nav_open = tabsNavOpenRenderer;
529
- tabMd.renderer.rules.tabs_nav_close = tabsNavCloseRenderer;
530
- tabMd.renderer.rules.tabs_nav_item = tabsNavItemRenderer;
531
- tabMd.renderer.rules.tabs_content_open = tabsContentOpenRenderer;
532
- tabMd.renderer.rules.tabs_content_close = tabsContentCloseRenderer;
533
- tabMd.renderer.rules.tab_pane_open = tabPaneOpenRenderer;
534
- tabMd.renderer.rules.tab_pane_close = tabPaneCloseRenderer;
535
- tabMd.renderer.rules.tabs_close = tabsCloseRenderer;
536
-
537
- // Register heading ID plugin for the tab markdown instance
538
- tabMd.use(headingIdPlugin);
539
-
540
- // Register standalone closing rule for the tab markdown instance
541
- tabMd.block.ruler.before('paragraph', 'standalone_closing', standaloneClosingRule, {
542
- alt: ['paragraph', 'reference', 'blockquote', 'list']
543
- });
544
-
545
- // Render the tab content
546
- const renderedContent = tabMd.render(tabContent);
547
- const htmlToken = state.push('html_block', '', 0);
548
- htmlToken.content = renderedContent;
549
- }
550
-
551
- state.push('tab_pane_close', 'div', -1);
552
- });
553
- state.push('tabs_content_close', 'div', -1);
554
- state.push('tabs_close', 'div', -1);
555
- state.line = nextLine + 1;
556
- return true;
60
+ return { frontmatter, htmlContent, headings };
557
61
  }
558
-
559
- // Add a rule to handle standalone closing tags
560
- const standaloneClosingRule = (state, startLine, endLine, silent) => {
561
- const start = state.bMarks[startLine] + state.tShift[startLine];
562
- const max = state.eMarks[startLine];
563
- const lineContent = state.src.slice(start, max).trim();
564
-
565
- if (lineContent === ':::') {
566
- if (silent) return true;
567
- // Skip this line by not creating any tokens
568
- state.line = startLine + 1;
569
- return true;
570
- }
571
-
572
- return false;
573
- };
574
-
575
- // Custom renderer for ordered lists in steps containers
576
- const customOrderedListOpenRenderer = function(tokens, idx, options, env, self) {
577
- const token = tokens[idx];
578
- // Check if we're inside a steps container by looking at the context
579
- let isInSteps = false;
580
-
581
- // Look back through tokens to see if we're in a steps container
582
- for (let i = idx - 1; i >= 0; i--) {
583
- if (tokens[i].type === 'container_steps_open') {
584
- isInSteps = true;
585
- break;
586
- }
587
- if (tokens[i].type === 'container_steps_close') {
588
- break;
589
- }
590
- }
591
62
 
592
- if (isInSteps) {
593
- const start = token.attrGet('start');
594
- return start ?
595
- `<ol class="steps-list" start="${start}">` :
596
- '<ol class="steps-list">';
597
- }
598
-
599
- // Default behavior for non-steps ordered lists
600
- const start = token.attrGet('start');
601
- return start ? `<ol start="${start}">` : '<ol>';
602
- };
603
-
604
- // Custom renderer for list items in steps containers
605
- const customListItemOpenRenderer = function(tokens, idx, options, env, self) {
606
- const token = tokens[idx];
607
- // Check if we're inside a steps container and this is a direct child
608
- let isInStepsList = false;
609
-
610
- // Look back through tokens to see if we're in a steps list
611
- for (let i = idx - 1; i >= 0; i--) {
612
- if (tokens[i].type === 'ordered_list_open' &&
613
- tokens[i].markup &&
614
- tokens[i].level < token.level) {
615
- // Check if this ordered list has steps-list class (meaning it's in steps container)
616
- let j = i - 1;
617
- while (j >= 0) {
618
- if (tokens[j].type === 'container_steps_open') {
619
- isInStepsList = true;
620
- break;
621
- }
622
- if (tokens[j].type === 'container_steps_close') {
623
- break;
624
- }
625
- j--;
626
- }
627
- break;
628
- }
629
- }
630
-
631
- if (isInStepsList) {
632
- return '<li class="step-item">';
633
- }
634
-
635
- // Default behavior for non-step list items
636
- return '<li>';
637
- };
638
-
639
- // Enhanced tabs renderers
640
- const tabsOpenRenderer = (tokens, idx) => {
641
- const token = tokens[idx];
642
- return `<div class="${token.attrs.map(attr => attr[1]).join(' ')}">`;
643
- };
644
-
645
- const tabsNavOpenRenderer = () => '<div class="docmd-tabs-nav">';
646
- const tabsNavCloseRenderer = () => '</div>';
647
-
648
- const tabsNavItemRenderer = (tokens, idx) => {
649
- const token = tokens[idx];
650
- return `<div class="${token.attrs[0][1]}">${token.content}</div>`;
651
- };
652
-
653
- const tabsContentOpenRenderer = () => '<div class="docmd-tabs-content">';
654
- const tabsContentCloseRenderer = () => '</div>';
655
-
656
- const tabPaneOpenRenderer = (tokens, idx) => {
657
- const token = tokens[idx];
658
- return `<div class="${token.attrs[0][1]}">`;
659
- };
660
-
661
- const tabPaneCloseRenderer = () => '</div>';
662
-
663
- const tabsCloseRenderer = () => '</div>';
664
-
665
- // Override the default image renderer to properly handle attributes like {.class}.
666
- const customImageRenderer = function(tokens, idx, options, env, self) {
667
- const defaultImageRenderer = function(tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); };
668
- const renderedImage = defaultImageRenderer(tokens, idx, options, env, self);
669
- const nextToken = tokens[idx + 1];
670
- if (nextToken && nextToken.type === 'attrs_block') {
671
- const attrs = nextToken.attrs || [];
672
- const attrsStr = attrs.map(([name, value]) => `${name}="${value}"`).join(' ');
673
- return renderedImage.replace('<img ', `<img ${attrsStr} `);
674
- }
675
- return renderedImage;
676
- };
677
-
678
- // Add IDs to headings for anchor links, used by the Table of Contents.
679
- const headingIdPlugin = (md) => {
680
- const originalHeadingOpen = md.renderer.rules.heading_open || function(tokens, idx, options, env, self) {
681
- return self.renderToken(tokens, idx, options);
682
- };
683
-
684
- md.renderer.rules.heading_open = function(tokens, idx, options, env, self) {
685
- const token = tokens[idx];
686
- const contentToken = tokens[idx + 1];
687
-
688
- if (contentToken && contentToken.type === 'inline' && contentToken.content) {
689
- const headingText = contentToken.content;
690
- const id = headingText
691
- .toLowerCase()
692
- .replace(/\s+/g, '-') // Replace spaces with -
693
- .replace(/[^\w-]+/g, '') // Remove all non-word chars
694
- .replace(/--+/g, '-') // Replace multiple - with single -
695
- .replace(/^-+/, '') // Trim - from start of text
696
- .replace(/-+$/, ''); // Trim - from end of text
697
-
698
- if (id) {
699
- token.attrSet('id', id);
700
- }
701
- }
702
-
703
- return originalHeadingOpen(tokens, idx, options, env, self);
704
- };
705
- };
706
-
707
- // ===================================================================
708
- // --- SAFE CONTAINER WRAPPER (FOR SIMPLE CONTAINERS) ---
709
- // The safeContainer function has been replaced by the advanced nested container system
710
- // which provides better nesting support and more robust parsing.
711
-
712
- // ===================================================================
713
- // --- ADVANCED NESTED CONTAINER SYSTEM IMPLEMENTATION ---
714
- // ===================================================================
715
-
716
- // The advanced nested container system is now implemented above
717
- // All containers (card, callout, button, steps, tabs) are handled by the new system
718
- // which supports seamless nesting of any container within any other container.
719
-
720
-
721
- // --- UTILITY AND PROCESSING FUNCTIONS ---
722
-
723
- function decodeHtmlEntities(html) {
724
- return html.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, ' ');
725
- }
726
-
727
- function extractHeadingsFromHtml(htmlContent) {
728
- const headings = [];
729
- const headingRegex = /<h([1-6])[^>]*?id="([^"]*)"[^>]*?>([\s\S]*?)<\/h\1>/g;
730
- let match;
731
- while ((match = headingRegex.exec(htmlContent)) !== null) {
732
- const level = parseInt(match[1], 10);
733
- const id = match[2];
734
- const text = decodeHtmlEntities(match[3].replace(/<\/?[^>]+(>|$)/g, ''));
735
- headings.push({ id, level, text });
736
- }
737
- return headings;
738
- }
739
-
740
- async function processMarkdownFile(filePath, md, config) {
741
- const rawContent = await fs.readFile(filePath, 'utf8');
742
- let frontmatter, markdownContent;
743
-
744
- try {
745
- ({ data: frontmatter, content: markdownContent } = matter(rawContent));
746
- } catch (e) {
747
- console.error(`❌ Error parsing frontmatter in ${formatPathForDisplay(filePath)}:`);
748
- console.error(` ${e.message}`);
749
- console.error(' This page will be skipped. Please fix the YAML syntax.');
750
- return null;
751
- }
752
-
753
- if (!frontmatter.title) {
754
- if (config.autoTitleFromH1 !== false) {
755
- const h1Match = markdownContent.match(/^#\s+(.*)/m);
756
- if (h1Match && h1Match[1]) {
757
- frontmatter.title = h1Match[1].trim();
758
- }
759
- }
760
- if (!frontmatter.title) {
761
- console.warn(`⚠️ Warning: Markdown file ${formatPathForDisplay(filePath)} has no title in frontmatter and no H1 fallback. The page header will be hidden.`);
762
- }
763
- }
764
-
765
- let htmlContent, headings;
766
- if (frontmatter.noStyle === true) {
767
- // For noStyle pages, NO markdown processing at all
768
- // Pass the raw content directly as-is
769
- htmlContent = markdownContent;
770
- headings = [];
771
- } else {
772
- htmlContent = md.render(markdownContent);
773
- headings = extractHeadingsFromHtml(htmlContent);
774
- }
775
-
776
- return {
777
- frontmatter,
778
- htmlContent,
779
- headings,
780
- };
781
- }
782
-
783
63
  async function findMarkdownFiles(dir) {
784
- let files = [];
785
- const items = await fs.readdir(dir, { withFileTypes: true });
786
- for (const item of items) {
787
- const fullPath = path.join(dir, item.name);
788
- if (item.isDirectory()) {
789
- files = files.concat(await findMarkdownFiles(fullPath));
790
- } else if (item.isFile() && (item.name.endsWith('.md') || item.name.endsWith('.markdown'))) {
791
- files.push(fullPath);
64
+ let files = [];
65
+ const items = await fs.readdir(dir, { withFileTypes: true });
66
+ for (const item of items) {
67
+ const fullPath = path.join(dir, item.name);
68
+ if (item.isDirectory()) {
69
+ files = files.concat(await findMarkdownFiles(fullPath));
70
+ } else if (item.isFile() && (item.name.endsWith('.md') || item.name.endsWith('.markdown'))) {
71
+ files.push(fullPath);
72
+ }
792
73
  }
793
- }
794
- return files;
74
+ return files;
795
75
  }
796
76
 
797
77
  module.exports = {