@farming-labs/svelte 0.2.72 → 0.2.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/content.d.ts CHANGED
@@ -35,6 +35,7 @@ export interface ContentPage {
35
35
  agent?: PageAgentFrontmatter;
36
36
  icon?: string;
37
37
  sourcePath?: string;
38
+ lastmod?: string;
38
39
  lastModified?: string;
39
40
  locale?: string;
40
41
  framework?: string;
@@ -44,9 +45,11 @@ export interface ContentPage {
44
45
  rawContent: string;
45
46
  agentContent?: string;
46
47
  agentRawContent?: string;
48
+ agentLastModified?: string;
47
49
  agentFallbackContent?: string;
48
50
  agentFallbackRawContent?: string;
49
51
  }
52
+ export declare function normalizeDocsFrontmatterLastmod(value: unknown): string | undefined;
50
53
  /**
51
54
  * Scan a content directory and return all docs pages.
52
55
  * Expects a flat or nested structure of `.md` files:
package/dist/content.js CHANGED
@@ -9,6 +9,13 @@ import fs from "node:fs";
9
9
  import path from "node:path";
10
10
  import matter from "gray-matter";
11
11
  import { normalizeDocsRelated, normalizePageAgentFrontmatter, resolveDocsAudienceMdxContent, resolvePageSidebarFolderIndexBehavior, } from "@farming-labs/docs";
12
+ export function normalizeDocsFrontmatterLastmod(value) {
13
+ if (typeof value === "string")
14
+ return value;
15
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
16
+ return value.toISOString();
17
+ return undefined;
18
+ }
12
19
  /**
13
20
  * Scan a content directory and return all docs pages.
14
21
  * Expects a flat or nested structure of `.md` files:
@@ -55,6 +62,7 @@ export function loadDocsContent(contentDir, entry = "docs") {
55
62
  agent: normalizePageAgentFrontmatter(data.agent),
56
63
  icon: data.icon,
57
64
  sourcePath: full.replace(/\\/g, "/"),
65
+ lastmod: normalizeDocsFrontmatterLastmod(data.lastmod),
58
66
  lastModified: stat.mtime.toISOString(),
59
67
  locale: typeof data.locale === "string" ? data.locale : undefined,
60
68
  framework: typeof data.framework === "string" ? data.framework : undefined,
@@ -87,6 +95,7 @@ function readAgentDoc(dir) {
87
95
  return {
88
96
  agentContent: stripMarkdown(agentRawContent),
89
97
  agentRawContent,
98
+ agentLastModified: fs.statSync(agentPath).mtime.toISOString(),
90
99
  };
91
100
  }
92
101
  /**
package/dist/markdown.js CHANGED
@@ -9,7 +9,8 @@
9
9
  * - Tables, lists, inline formatting, headings with anchor IDs
10
10
  */
11
11
  import { resolveDocsAudienceMdxContent } from "@farming-labs/docs";
12
- import { parsePromptStringArray, resolvePromptProviderChoices, sanitizePromptText, } from "@farming-labs/docs/server";
12
+ import { createDocsMarkdownBlockPlaceholderAllocator, extractDocsMarkdownReferenceDefinitions as extractMarkdownReferenceDefinitions, extractDocsRenderedHeadingElements as extractRenderedHeadingElements, prepareDocsMarkdownHeadings as prepareMarkdownHeadings, replaceDocsMarkdownFencedCodeBlocks as replaceMarkdownFencedCodeBlocks, renderDocsMarkdownBlockContent as renderMarkdownBlockContent, renderDocsMarkdownHeadings as renderMarkdownHeadings, renderDocsMarkdownInline as renderMarkdownInline, restoreDocsMarkdownHeadingOpeningTags as restoreMarkdownHeadingOpeningTags, stripPreparedDocsMarkdownHeadingTokens as stripPreparedMarkdownHeadingTokens, } from "@farming-labs/docs/markdown-rendering";
13
+ import { extractDocsMarkdownPromptBlocks, parsePromptStringArray, resolvePromptProviderChoices, sanitizePromptText, } from "@farming-labs/docs/server";
13
14
  import { createHighlighter } from "shiki";
14
15
  let highlighterPromise = null;
15
16
  function getHighlighter() {
@@ -36,15 +37,6 @@ function getHighlighter() {
36
37
  }
37
38
  return highlighterPromise;
38
39
  }
39
- function slugify(text) {
40
- return text
41
- .toLowerCase()
42
- .replace(/<[^>]+>/g, "")
43
- .replace(/[^\w\s-]/g, "")
44
- .replace(/\s+/g, "-")
45
- .replace(/-+/g, "-")
46
- .trim();
47
- }
48
40
  const hoverLinkDefaults = {
49
41
  linkLabel: "Open page",
50
42
  showIndicator: false,
@@ -61,6 +53,15 @@ const promptDefaults = {
61
53
  copiedIcon: "check",
62
54
  openIcon: "arrowUpRight",
63
55
  };
56
+ function slugifyCodeGroupTab(text) {
57
+ return text
58
+ .toLowerCase()
59
+ .replace(/<[^>]+>/g, "")
60
+ .replace(/[^\w\s-]/g, "")
61
+ .replace(/\s+/g, "-")
62
+ .replace(/-+/g, "-")
63
+ .trim();
64
+ }
64
65
  const promptActionIcons = {
65
66
  copy: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" /></svg>',
66
67
  check: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12" /></svg>',
@@ -335,22 +336,12 @@ function normalizeCalloutType(type) {
335
336
  const aliased = calloutTypeAliases[normalized] ?? normalized;
336
337
  return calloutIcons[aliased] ? aliased : "note";
337
338
  }
338
- function renderInlineCalloutContent(content) {
339
- return content
340
- .trim()
341
- .replace(/`([^`]+)`/g, "<code>$1</code>")
342
- .replace(/\*\*\*(.+?)\*\*\*/g, "<strong><em>$1</em></strong>")
343
- .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
344
- .replace(/\*(.+?)\*/g, "<em>$1</em>")
345
- .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
346
- .replace(/\n+/g, "<br />");
347
- }
348
- function renderCallout(type, content, title) {
339
+ function renderCallout(type, content, title, definitions) {
349
340
  const normalizedType = normalizeCalloutType(type);
350
341
  const icon = calloutIcons[normalizedType] || calloutIcons.note;
351
342
  const label = title?.trim() || calloutLabels[normalizedType] || "Note";
352
- const renderedContent = renderInlineCalloutContent(content);
353
- return `<div class="fd-callout fd-callout-${normalizedType}" role="note"><div class="fd-callout-indicator" role="none"></div><div class="fd-callout-icon">${icon}</div><div class="fd-callout-content"><p class="fd-callout-title">${escapeHtml(label)}</p><p>${renderedContent}</p></div></div>`;
343
+ const renderedContent = renderMarkdownBlockContent(content, definitions);
344
+ return `<div class="fd-callout fd-callout-${normalizedType}" role="note"><div class="fd-callout-indicator" role="none"></div><div class="fd-callout-icon">${icon}</div><div class="fd-callout-content"><p class="fd-callout-title">${escapeHtml(label)}</p>${renderedContent}</div></div>`;
354
345
  }
355
346
  function highlightCode(hl, code, lang) {
356
347
  if (lang === "sh" || lang === "shell")
@@ -426,7 +417,7 @@ function parseCodeGroupMeta(meta) {
426
417
  };
427
418
  }
428
419
  function createCodeGroupTabValue(label, used) {
429
- const slug = slugify(label) || `code-${used.size + 1}`;
420
+ const slug = slugifyCodeGroupTab(label) || `code-${used.size + 1}`;
430
421
  let value = slug;
431
422
  let suffix = 2;
432
423
  while (used.has(value)) {
@@ -491,7 +482,22 @@ export async function renderMarkdown(content, options = {}) {
491
482
  if (!content)
492
483
  return "";
493
484
  const hl = await getHighlighter();
494
- let result = resolveDocsAudienceMdxContent(content, "human");
485
+ // Prompt children are literal copyable text, not renderable Markdown. Protect
486
+ // them before audience projection, reference collection, and heading
487
+ // preparation so none of those document-level passes can consume or interpret
488
+ // Prompt-only syntax.
489
+ const extractedPrompts = extractDocsMarkdownPromptBlocks(content);
490
+ const promptBlocks = extractedPrompts.blocks;
491
+ let result = extractedPrompts.markdown;
492
+ result = resolveDocsAudienceMdxContent(result, "human");
493
+ const allocateBlockPlaceholder = createDocsMarkdownBlockPlaceholderAllocator(result);
494
+ const extractedReferences = extractMarkdownReferenceDefinitions(result);
495
+ const referenceDefinitions = extractedReferences.definitions;
496
+ const preparedHeadings = prepareMarkdownHeadings(result);
497
+ const preparedWithoutReferences = extractMarkdownReferenceDefinitions(preparedHeadings.markdown).markdown;
498
+ const renderedHeadings = renderMarkdownHeadings(preparedWithoutReferences, preparedHeadings.headings);
499
+ result = renderedHeadings.markdown;
500
+ const headingOpeningTags = renderedHeadings.openingTags;
495
501
  // ── Mintlify-style code groups: <CodeGroup> fenced code blocks </CodeGroup> ──
496
502
  const tabsBlocks = [];
497
503
  result = result.replace(/<CodeGroup(?:\s+([^>]*?))?>([\s\S]*?)<\/CodeGroup>/g, (_, attrSource, body) => {
@@ -499,23 +505,24 @@ export async function renderMarkdown(content, options = {}) {
499
505
  const dropdown = toBoolean(attrs.dropdown, false);
500
506
  const usedValues = new Set();
501
507
  const panels = [];
502
- const codeRegex = /```([^\n]*)\n([\s\S]*?)```/g;
503
- let codeMatch;
504
- while ((codeMatch = codeRegex.exec(body)) !== null) {
505
- const { lang, title } = parseCodeGroupMeta(codeMatch[1]);
508
+ replaceMarkdownFencedCodeBlocks(body, ({ code, info }) => {
509
+ const { lang, title } = parseCodeGroupMeta(info);
506
510
  const label = title || lang || `Code ${panels.length + 1}`;
507
511
  const value = createCodeGroupTabValue(label, usedValues);
508
- const dedented = dedentCode(codeMatch[2]);
512
+ const dedented = dedentCode(code);
509
513
  const { html, raw } = highlightCode(hl, dedented, lang);
510
514
  panels.push({
511
515
  label,
512
516
  value,
513
517
  html: wrapCodeWithCopy(html, raw, null, lang),
514
518
  });
515
- }
519
+ return "";
520
+ });
516
521
  if (panels.length === 0)
517
522
  return body;
518
- let tabsHtml = `<div class="fd-tabs fd-code-group" data-tabs data-code-group data-fd-code-group${dropdown ? ' data-dropdown="true"' : ""}>`;
523
+ const extractedHeadings = extractRenderedHeadingElements(body, referenceDefinitions, false, headingOpeningTags);
524
+ let tabsHtml = extractedHeadings.headingsHtml +
525
+ `<div class="fd-tabs fd-code-group" data-tabs data-code-group data-fd-code-group${dropdown ? ' data-dropdown="true"' : ""}>`;
519
526
  tabsHtml += `<div class="fd-tabs-list fd-code-group-list" role="tablist">`;
520
527
  for (let i = 0; i < panels.length; i++) {
521
528
  const state = i === 0 ? "active" : "inactive";
@@ -527,8 +534,8 @@ export async function renderMarkdown(content, options = {}) {
527
534
  tabsHtml += `<div class="fd-tab-panel fd-code-group-panel${i === 0 ? " fd-tab-panel-active" : ""}" data-tab-panel="${escapeHtml(panels[i].value)}" data-state="${state}" role="tabpanel">${panels[i].html}</div>`;
528
535
  }
529
536
  tabsHtml += `</div>`;
530
- const placeholder = `%%TABS_${tabsBlocks.length}%%`;
531
- tabsBlocks.push(tabsHtml);
537
+ const placeholder = allocateBlockPlaceholder("TABS");
538
+ tabsBlocks.push({ html: tabsHtml, token: placeholder });
532
539
  return placeholder;
533
540
  });
534
541
  // ── Tabs blocks: <Tabs items={[...]}> ... </Tabs> ──
@@ -539,16 +546,29 @@ export async function renderMarkdown(content, options = {}) {
539
546
  let tabMatch;
540
547
  while ((tabMatch = tabRegex.exec(body)) !== null) {
541
548
  const tabValue = tabMatch[1];
542
- const tabContent = tabMatch[2].trim();
543
- const codeMatch = tabContent.match(/```([^\n]*)\n([\s\S]*?)```/);
544
- if (codeMatch) {
545
- const { lang, title } = parseMeta(codeMatch[1]);
546
- const dedented = dedentCode(codeMatch[2]);
549
+ const extractedHeadings = extractRenderedHeadingElements(tabMatch[2].trim(), referenceDefinitions, false, headingOpeningTags);
550
+ let renderedCode;
551
+ replaceMarkdownFencedCodeBlocks(extractedHeadings.content, ({ code, info }) => {
552
+ if (renderedCode !== undefined)
553
+ return "";
554
+ const { lang, title } = parseMeta(info);
555
+ const dedented = dedentCode(code);
547
556
  const { html, raw } = highlightCode(hl, dedented, lang);
548
- panels.push({ value: tabValue, html: wrapCodeWithCopy(html, raw, title, lang) });
557
+ renderedCode = wrapCodeWithCopy(html, raw, title, lang);
558
+ return "";
559
+ });
560
+ if (renderedCode !== undefined) {
561
+ panels.push({
562
+ value: tabValue,
563
+ html: extractedHeadings.headingsHtml + renderedCode,
564
+ });
549
565
  }
550
566
  else {
551
- panels.push({ value: tabValue, html: `<p>${tabContent}</p>` });
567
+ panels.push({
568
+ value: tabValue,
569
+ html: extractedHeadings.headingsHtml +
570
+ renderMarkdownBlockContent(extractedHeadings.content, referenceDefinitions),
571
+ });
552
572
  }
553
573
  }
554
574
  let tabsHtml = `<div class="fd-tabs" data-tabs>`;
@@ -563,29 +583,28 @@ export async function renderMarkdown(content, options = {}) {
563
583
  tabsHtml += `<div class="fd-tab-panel${i === 0 ? " fd-tab-panel-active" : ""}" data-tab-panel="${escapeHtml(panels[i].value)}" data-state="${state}" role="tabpanel">${panels[i].html}</div>`;
564
584
  }
565
585
  tabsHtml += `</div>`;
566
- const placeholder = `%%TABS_${tabsBlocks.length}%%`;
567
- tabsBlocks.push(tabsHtml);
568
- return placeholder;
569
- });
570
- // ── Fenced code blocks ──
571
- const codeBlocks = [];
572
- result = result.replace(/```([^\n]*)\n([\s\S]*?)```/g, (_, meta, code) => {
573
- const { lang, title } = parseMeta(meta);
574
- const { html, raw } = highlightCode(hl, code, lang);
575
- const placeholder = `%%CODEBLOCK_${codeBlocks.length}%%`;
576
- codeBlocks.push(wrapCodeWithCopy(html, raw, title, lang));
586
+ const placeholder = allocateBlockPlaceholder("TABS");
587
+ tabsBlocks.push({ html: tabsHtml, token: placeholder });
577
588
  return placeholder;
578
589
  });
579
590
  const hoverLinkBlocks = [];
580
591
  result = result.replace(/<HoverLink\s+([^>]*?)>([\s\S]*?)<\/HoverLink>/g, (_, attrSource, children) => {
581
- const placeholder = `%%HOVERLINK_${hoverLinkBlocks.length}%%`;
582
- hoverLinkBlocks.push(renderHoverLink(attrSource, children, options.theme));
592
+ const placeholder = allocateBlockPlaceholder("HOVERLINK");
593
+ const extractedHeadings = extractRenderedHeadingElements(children, referenceDefinitions, false, headingOpeningTags);
594
+ hoverLinkBlocks.push({
595
+ html: extractedHeadings.headingsHtml +
596
+ renderHoverLink(attrSource, extractedHeadings.content, options.theme),
597
+ token: placeholder,
598
+ });
583
599
  return placeholder;
584
600
  });
585
- const promptBlocks = [];
586
- result = result.replace(/<Prompt(?:\s+([^>]*?))?>([\s\S]*?)<\/Prompt>/g, (_, attrSource, children) => {
587
- const placeholder = `%%PROMPT_${promptBlocks.length}%%`;
588
- promptBlocks.push(renderPrompt(attrSource ?? "", children, options));
601
+ // ── Fenced code blocks ──
602
+ const codeBlocks = [];
603
+ result = replaceMarkdownFencedCodeBlocks(result, ({ code, info }) => {
604
+ const { lang, title } = parseMeta(info);
605
+ const { html, raw } = highlightCode(hl, code, lang);
606
+ const placeholder = allocateBlockPlaceholder("CODEBLOCK");
607
+ codeBlocks.push({ html: wrapCodeWithCopy(html, raw, title, lang), token: placeholder });
589
608
  return placeholder;
590
609
  });
591
610
  const calloutBlocks = [];
@@ -593,53 +612,47 @@ export async function renderMarkdown(content, options = {}) {
593
612
  const attrs = parseJsxAttributes(attrSource ?? "");
594
613
  const type = toStringValue(attrs.type) ?? toStringValue(attrs.kind) ?? "note";
595
614
  const title = toStringValue(attrs.title);
596
- const placeholder = `%%CALLOUT_${calloutBlocks.length}%%`;
597
- calloutBlocks.push(renderCallout(type, children, title));
615
+ const placeholder = allocateBlockPlaceholder("CALLOUT");
616
+ calloutBlocks.push({
617
+ html: renderCallout(type, restoreMarkdownHeadingOpeningTags(children, headingOpeningTags), title, referenceDefinitions),
618
+ token: placeholder,
619
+ });
598
620
  return placeholder;
599
621
  });
600
- // Inline code
601
- result = result.replace(/`([^`]+)`/g, "<code>$1</code>");
602
- // Headings (h4 → h1 order to avoid prefix collisions)
603
- result = result.replace(/^#### (.+)$/gm, (_, text) => {
604
- return `<h4 id="${slugify(text)}">${text}</h4>`;
605
- });
606
- result = result.replace(/^### (.+)$/gm, (_, text) => {
607
- return `<h3 id="${slugify(text)}">${text}</h3>`;
608
- });
609
- result = result.replace(/^## (.+)$/gm, (_, text) => {
610
- return `<h2 id="${slugify(text)}">${text}</h2>`;
611
- });
612
- result = result.replace(/^# (.+)$/gm, "<h1>$1</h1>");
613
622
  // ── Callouts / blockquotes (before inline formatting) ──
614
623
  result = result.replace(/(?:^>\s*.+\n?)+/gm, (block) => {
615
624
  const lines = block.split("\n").filter(Boolean);
616
- const inner = lines.map((l) => l.replace(/^>\s?/, "")).join("\n");
625
+ const inner = restoreMarkdownHeadingOpeningTags(lines.map((l) => l.replace(/^>\s?/, "")).join("\n"), headingOpeningTags);
617
626
  const ghMatch = inner.match(/^\[!(NOTE|WARNING|TIP|IMPORTANT|CAUTION)\]\s*\n?([\s\S]*)/i);
618
627
  if (ghMatch) {
619
628
  const type = ghMatch[1].toLowerCase();
620
629
  const calloutContent = ghMatch[2].trim();
621
- const placeholder = `%%CALLOUT_${calloutBlocks.length}%%`;
622
- calloutBlocks.push(renderCallout(type, calloutContent));
630
+ const placeholder = allocateBlockPlaceholder("CALLOUT");
631
+ calloutBlocks.push({
632
+ html: renderCallout(type, calloutContent, undefined, referenceDefinitions),
633
+ token: placeholder,
634
+ });
623
635
  return placeholder;
624
636
  }
625
637
  const boldMatch = inner.match(/^\*\*(Note|Warning|Tip|Important|Caution):\*\*\s*([\s\S]*)/i);
626
638
  if (boldMatch) {
627
639
  const type = boldMatch[1].toLowerCase();
628
640
  const calloutContent = boldMatch[2].trim();
629
- const placeholder = `%%CALLOUT_${calloutBlocks.length}%%`;
630
- calloutBlocks.push(renderCallout(type, calloutContent));
641
+ const placeholder = allocateBlockPlaceholder("CALLOUT");
642
+ calloutBlocks.push({
643
+ html: renderCallout(type, calloutContent, undefined, referenceDefinitions),
644
+ token: placeholder,
645
+ });
631
646
  return placeholder;
632
647
  }
633
- return `<blockquote><p>${inner}</p></blockquote>`;
648
+ const placeholder = allocateBlockPlaceholder("CALLOUT");
649
+ calloutBlocks.push({
650
+ html: `<blockquote>${renderMarkdownBlockContent(inner, referenceDefinitions)}</blockquote>`,
651
+ token: placeholder,
652
+ });
653
+ return placeholder;
634
654
  });
635
- // Inline formatting
636
- result = result.replace(/\*\*\*(.+?)\*\*\*/g, "<strong><em>$1</em></strong>");
637
- result = result.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
638
- result = result.replace(/\*(.+?)\*/g, "<em>$1</em>");
639
- // Images — before links so ![alt](url) is not captured as a link
640
- result = result.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, src) => `<img src="${src}" alt="${alt.replace(/"/g, "&quot;")}" class="fd-docs-content-img" loading="lazy" decoding="async" />`);
641
- // Links
642
- result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
655
+ result = renderMarkdownInline(result, referenceDefinitions);
643
656
  // Horizontal rules
644
657
  result = result.replace(/^---$/gm, "<hr />");
645
658
  // Tables
@@ -662,22 +675,38 @@ export async function renderMarkdown(content, options = {}) {
662
675
  return `<div class="fd-table-wrapper relative overflow-auto prose-no-margin my-6"><table><thead><tr>${headerHtml}</tr></thead><tbody>${rowsHtml}</tbody></table></div>`;
663
676
  });
664
677
  // Unordered lists
665
- result = result.replace(/(?:^- .+\n?)+/gm, (block) => {
666
- const items = block
667
- .split("\n")
668
- .filter((l) => l.startsWith("- "))
669
- .map((l) => `<li>${l.slice(2)}</li>`)
670
- .join("");
671
- return `<ul>${items}</ul>`;
678
+ result = result.replace(/(?:^[-+*] [^\r\n]+(?:\r?\n(?:(?: {2,}|\t)[^\r\n]+))*(?:\r?\n|$))+/gm, (block) => {
679
+ const items = [];
680
+ for (const line of block.trimEnd().split(/\r?\n/)) {
681
+ if (/^[-+*] /.test(line)) {
682
+ items.push(line.slice(2));
683
+ continue;
684
+ }
685
+ if (items.length > 0) {
686
+ items[items.length - 1] += `\n${line.replace(/^(?: {2}|\t)/, "")}`;
687
+ }
688
+ }
689
+ return `<ul>${items.map((item) => `<li>${item}</li>`).join("")}</ul>`;
672
690
  });
673
691
  // Ordered lists
674
- result = result.replace(/(?:^\d+\. .+\n?)+/gm, (block) => {
675
- const items = block
676
- .split("\n")
677
- .filter((l) => /^\d+\. /.test(l))
678
- .map((l) => `<li>${l.replace(/^\d+\. /, "")}</li>`)
679
- .join("");
680
- return `<ol>${items}</ol>`;
692
+ result = result.replace(/(?:^\d{1,9}[.)] [^\r\n]+(?:\r?\n(?:(?: {3,}|\t)[^\r\n]+))*(?:\r?\n|$))+/gm, (block) => {
693
+ const items = [];
694
+ let continuationIndent = 0;
695
+ for (const line of block.trimEnd().split(/\r?\n/)) {
696
+ const marker = /^(\d{1,9}[.)]) (.*)$/.exec(line);
697
+ if (marker) {
698
+ items.push(marker[2]);
699
+ continuationIndent = marker[1].length + 1;
700
+ continue;
701
+ }
702
+ if (items.length > 0) {
703
+ const content = line[0] === "\t"
704
+ ? line.slice(1)
705
+ : line.slice(Math.min(continuationIndent, /^ */.exec(line)?.[0].length ?? 0));
706
+ items[items.length - 1] += `\n${content}`;
707
+ }
708
+ }
709
+ return `<ol>${items.map((item) => `<li>${item}</li>`).join("")}</ol>`;
681
710
  });
682
711
  // Wrap remaining bare text in <p> tags
683
712
  result = result
@@ -688,26 +717,30 @@ export async function renderMarkdown(content, options = {}) {
688
717
  return "";
689
718
  if (/^<(h[1-6]|pre|ul|ol|blockquote|hr|table|div)/.test(block))
690
719
  return block;
691
- if (/^%%(CODEBLOCK|CALLOUT|TABS|PROMPT|HOVERLINK)_\d+%%$/.test(block))
720
+ if (/^%%FARMINGLABS_DOCS_HEADING_OPEN_\d+%%/.test(block))
721
+ return block;
722
+ if (/^%%(?:CODEBLOCK|CALLOUT|TABS|PROMPT|HOVERLINK)_\d+%%/.test(block)) {
692
723
  return block;
724
+ }
693
725
  return `<p>${block}</p>`;
694
726
  })
695
727
  .join("\n");
696
728
  // Restore placeholders
697
- for (let i = 0; i < codeBlocks.length; i++) {
698
- result = result.replace(`%%CODEBLOCK_${i}%%`, codeBlocks[i]);
729
+ for (const block of calloutBlocks) {
730
+ result = result.replace(block.token, () => block.html);
699
731
  }
700
- for (let i = 0; i < calloutBlocks.length; i++) {
701
- result = result.replace(`%%CALLOUT_${i}%%`, calloutBlocks[i]);
732
+ for (const block of tabsBlocks) {
733
+ result = result.replace(block.token, () => block.html);
702
734
  }
703
- for (let i = 0; i < tabsBlocks.length; i++) {
704
- result = result.replace(`%%TABS_${i}%%`, tabsBlocks[i]);
735
+ for (const block of hoverLinkBlocks) {
736
+ result = result.replace(block.token, () => block.html);
705
737
  }
706
- for (let i = 0; i < hoverLinkBlocks.length; i++) {
707
- result = result.replace(`%%HOVERLINK_${i}%%`, hoverLinkBlocks[i]);
738
+ for (const block of codeBlocks) {
739
+ result = result.replace(block.token, () => block.html);
708
740
  }
709
- for (let i = 0; i < promptBlocks.length; i++) {
710
- result = result.replace(`%%PROMPT_${i}%%`, promptBlocks[i]);
741
+ result = restoreMarkdownHeadingOpeningTags(stripPreparedMarkdownHeadingTokens(result), headingOpeningTags);
742
+ for (const block of promptBlocks) {
743
+ result = result.replace(block.token, () => renderPrompt(block.attributes, block.children, options));
711
744
  }
712
745
  return result;
713
746
  }
package/dist/server.js CHANGED
@@ -30,9 +30,9 @@
30
30
  import fs from "node:fs";
31
31
  import path from "node:path";
32
32
  import matter from "gray-matter";
33
- import { applySidebarFolderIndexBehavior, buildDocsAskAIContext, buildDocsAgentDiscoverySpec, buildDocsConfigMap, buildDocsDiagnostics, createDocsStandardsDiscoveryResponse, createDocsMarkdownResponse, createDocsRobotsResponse, createDocsSitemapResponse, createDocsAgentTraceContext, createDocsAgentTraceId, emitDocsAgentTraceEvent, emitDocsAnalyticsEvent, emitDocsTelemetryAgentSurfaceEvent, emitDocsTelemetryProjectEvent, formatDocsAskAIPackageHints, findDocsMarkdownPage, getDocsLlmsTxtMaxCharsIssue, getDocsAgentManifestLinkHeader, getDocsDiscoveryLinkHeader, isDocsAgentDiscoveryRequest, isDocsAgentsRequest, isDocsConfigRequest, isDocsDiagnosticsRequest, isDocsSkillRequest, normalizeDocsRelated, normalizePageAgentFrontmatter, parseDocsAgentFeedbackData, performDocsSearch, performDocsSearchWithMetadata, renderDocsMarkdownDocument, renderDocsLlmsTxt, renderDocsAgentsDocument, renderDocsSkillDocument, readDocsSitemapManifestFromContentMap, stripGeneratedAgentProvenance, resolveDocsAudienceMdxContent, resolveDocsAgentFeedbackConfig, resolveDocsAgentFeedbackRequest, resolvePageSidebarFolderIndexBehavior, resolveAskAISearchRequestConfig, resolveDocsSearchAudience, resolveDocsSearchFilters, resolveSearchRequestConfig, resolveDocsI18n, resolveDocsLlmsTxtRequest, resolveDocsLocale, resolveDocsMarkdownRequest, resolveDocsMetadataBaseUrl, resolveDocsRequestApiRoute, resolveDocsPublishedAgentSkill, resolveDocsStandardsDiscoveryRequest, resolveDocsPath, resolvePageReadingTime, resolveReadingTimeOptions, resolveDocsSitemapPageLastmod, resolveDocsAgentsFormat, resolveDocsSkillFormat, inferDocsTelemetryAgentSurface, renderDocsPageStructuredDataJson, selectDocsLlmsTxtContent, validateDocsAgentFeedbackPayload, } from "@farming-labs/docs";
33
+ import { applySidebarFolderIndexBehavior, buildDocsAskAIContext, buildDocsAgentDiscoverySpec, buildDocsConfigMap, buildDocsDiagnostics, createDocsStandardsDiscoveryResponse, createDocsMarkdownResponse, createDocsRobotsResponse, createDocsSitemapResponse, createDocsAgentTraceContext, createDocsAgentTraceId, emitDocsAgentTraceEvent, emitDocsAnalyticsEvent, emitDocsTelemetryAgentSurfaceEvent, emitDocsTelemetryProjectEvent, formatDocsAskAIPackageHints, findDocsMarkdownPage, getDocsLlmsTxtMaxCharsIssue, getDocsAgentManifestLinkHeader, getDocsDiscoveryLinkHeader, isDocsAgentDiscoveryRequest, isDocsAgentsRequest, isDocsConfigRequest, isDocsDiagnosticsRequest, isDocsSkillRequest, normalizeDocsRelated, normalizePageAgentFrontmatter, parseDocsAgentFeedbackData, performDocsSearch, performDocsSearchWithMetadata, renderDocsMarkdownDocument, renderDocsLlmsTxt, renderDocsAgentsDocument, renderDocsSkillDocument, readDocsSitemapManifestFromContentMap, stripGeneratedAgentProvenance, resolveDocsAudienceMdxContent, resolveDocsAgentFeedbackConfig, resolveDocsAgentFeedbackRequest, resolvePageSidebarFolderIndexBehavior, resolveAskAISearchRequestConfig, resolveDocsSearchAudience, resolveDocsSearchFilters, resolveSearchRequestConfig, resolveDocsI18n, resolveDocsLlmsTxtRequest, resolveDocsLocale, resolveDocsMarkdownRequest, resolveDocsMetadataBaseUrl, resolveDocsRequestApiRoute, resolveDocsRetrievalLastModified, resolveDocsPublishedAgentSkill, resolveDocsStandardsDiscoveryRequest, resolveDocsPath, resolvePageReadingTime, resolveReadingTimeOptions, resolveDocsSitemapPageLastmod, resolveDocsAgentsFormat, resolveDocsSkillFormat, inferDocsTelemetryAgentSurface, renderDocsPageStructuredDataJson, selectDocsLlmsTxtContent, validateDocsAgentFeedbackPayload, } from "@farming-labs/docs";
34
34
  import { buildApiReferenceOpenApiDocumentAsync, createDocsCloudAskAIResponse, createDocsMcpHttpHandler, isDocsCloudAskAIProvider, readDocsSitemapManifest, resolveApiReferenceConfig, resolveDocsMcpConfig, resolveConfiguredAgentSkills, serializeDocsIconRegistry, serializeOpenDocsProviders, } from "@farming-labs/docs/server";
35
- import { loadDocsNavTree, loadDocsContent, flattenNavTree } from "./content.js";
35
+ import { loadDocsNavTree, loadDocsContent, flattenNavTree, normalizeDocsFrontmatterLastmod, } from "./content.js";
36
36
  import { renderMarkdown } from "./markdown.js";
37
37
  export { createSvelteApiReference } from "./api-reference.js";
38
38
  function isApiReferenceOpenApiRequest(url) {
@@ -311,7 +311,7 @@ function navTreeFromMap(contentMap, dirPrefix, entry, ordering) {
311
311
  children.push(...buildLevel([]));
312
312
  return { name: "Docs", children };
313
313
  }
314
- function searchIndexFromMap(contentMap, dirPrefix, entry) {
314
+ function searchIndexFromMap(contentMap, dirPrefix, entry, locale, sitemapManifest) {
315
315
  const pages = [];
316
316
  for (const [key, raw] of Object.entries(contentMap)) {
317
317
  if (!key.startsWith(dirPrefix))
@@ -325,6 +325,9 @@ function searchIndexFromMap(contentMap, dirPrefix, entry) {
325
325
  const isIdx = base === "page" || base === "index" || base === "+page";
326
326
  const slug = isIdx ? segments.join("/") : [...segments, base].join("/");
327
327
  const url = slug ? `/${entry}/${slug}` : `/${entry}`;
328
+ const manifestLastmod = (locale
329
+ ? resolveDocsSitemapPageLastmod(sitemapManifest, `${url}?lang=${encodeURIComponent(locale)}`)
330
+ : undefined) ?? resolveDocsSitemapPageLastmod(sitemapManifest, url);
328
331
  const { data, content } = matter(raw);
329
332
  const humanRawContent = resolveDocsAudienceMdxContent(content, "human");
330
333
  const pageAgentRawContent = resolveDocsAudienceMdxContent(content, "agent");
@@ -339,6 +342,7 @@ function searchIndexFromMap(contentMap, dirPrefix, entry) {
339
342
  ...(related.length > 0 ? { related } : {}),
340
343
  agent: normalizePageAgentFrontmatter(data.agent),
341
344
  icon: data.icon,
345
+ lastmod: normalizeDocsFrontmatterLastmod(data.lastmod),
342
346
  locale: typeof data.locale === "string" ? data.locale : undefined,
343
347
  framework: typeof data.framework === "string" ? data.framework : undefined,
344
348
  version: typeof data.version === "string" ? data.version : undefined,
@@ -347,6 +351,7 @@ function searchIndexFromMap(contentMap, dirPrefix, entry) {
347
351
  : undefined,
348
352
  content: stripMarkdownText(humanRawContent),
349
353
  rawContent: humanRawContent,
354
+ ...(manifestLastmod ? { lastModified: `${manifestLastmod}T00:00:00.000Z` } : {}),
350
355
  ...(pageAgentRawContent !== humanRawContent
351
356
  ? {
352
357
  agentFallbackContent: stripMarkdownText(pageAgentRawContent),
@@ -630,7 +635,7 @@ export function createDocsServer(config = {}) {
630
635
  if (cached)
631
636
  return cached;
632
637
  const index = preloaded
633
- ? searchIndexFromMap(preloaded, ctx.dirPrefix, entry)
638
+ ? searchIndexFromMap(preloaded, ctx.dirPrefix, entry, ctx.locale, preloadedSitemapManifest)
634
639
  : loadDocsContent(ctx.contentDirAbs, entry);
635
640
  searchIndexByEntry.set(key, index);
636
641
  return index;
@@ -714,7 +719,7 @@ export function createDocsServer(config = {}) {
714
719
  return page
715
720
  ? {
716
721
  document: renderDocsMarkdownDocument(page, { origin, sitemap: config.sitemap }),
717
- lastModified: page.agentRawContent === undefined ? page.lastModified : undefined,
722
+ lastModified: resolveDocsRetrievalLastModified(page, "agent"),
718
723
  }
719
724
  : null;
720
725
  }
@@ -990,26 +995,14 @@ export function createDocsServer(config = {}) {
990
995
  const audience = resolveDocsSearchAudience(event.url.searchParams.get("audience"));
991
996
  const filters = resolveDocsSearchFilters(event.url.searchParams);
992
997
  const structured = event.url.searchParams.get("response") === "structured";
993
- if (!query) {
994
- const searchResponse = structured
995
- ? {
996
- format: "docs-search.v1",
997
- query: "",
998
- audience,
999
- filters,
1000
- resultCount: 0,
1001
- results: [],
1002
- warnings: [],
1003
- }
1004
- : [];
1005
- return new Response(JSON.stringify(searchResponse), {
998
+ if (!query && !structured) {
999
+ return new Response("[]", {
1006
1000
  headers: { "Content-Type": "application/json" },
1007
1001
  });
1008
1002
  }
1009
- const searchStartedAt = Date.now();
1010
1003
  const searchOptions = {
1011
1004
  pages: getSearchIndex(ctx),
1012
- query,
1005
+ query: query ?? "",
1013
1006
  search: resolveSearchRequestConfig(config.search, event.request.url),
1014
1007
  audience,
1015
1008
  filters,
@@ -1017,7 +1010,15 @@ export function createDocsServer(config = {}) {
1017
1010
  pathname: event.url.searchParams.get("pathname") ?? undefined,
1018
1011
  siteTitle: llmsTitle,
1019
1012
  baseUrl: markdownMetadataBaseUrl || event.url.origin,
1013
+ syncBaseUrl: markdownMetadataBaseUrl ?? null,
1020
1014
  };
1015
+ if (!query) {
1016
+ const searchResponse = structured ? await performDocsSearchWithMetadata(searchOptions) : [];
1017
+ return new Response(JSON.stringify(searchResponse), {
1018
+ headers: { "Content-Type": "application/json" },
1019
+ });
1020
+ }
1021
+ const searchStartedAt = Date.now();
1021
1022
  const searchResponse = structured
1022
1023
  ? await performDocsSearchWithMetadata(searchOptions)
1023
1024
  : await performDocsSearch(searchOptions);
@@ -1297,7 +1298,8 @@ export function createDocsServer(config = {}) {
1297
1298
  locale: ctx.locale,
1298
1299
  pathname: requestUrl.searchParams.get("pathname") ?? undefined,
1299
1300
  siteTitle: llmsTitle,
1300
- baseUrl: requestUrl.origin,
1301
+ baseUrl: markdownMetadataBaseUrl || requestUrl.origin,
1302
+ syncBaseUrl: markdownMetadataBaseUrl ?? null,
1301
1303
  limit: maxResults,
1302
1304
  });
1303
1305
  const scored = retrieval.results;
@@ -1581,6 +1583,8 @@ export function createDocsServer(config = {}) {
1581
1583
  source: {
1582
1584
  entry,
1583
1585
  siteTitle: mcpSiteTitle,
1586
+ baseUrl: markdownMetadataBaseUrl || undefined,
1587
+ resolveLocale: resolveLocaleForMcp,
1584
1588
  getPages(locale) {
1585
1589
  const ctx = resolveContextFromPath(`/${entry}`, resolveLocaleForMcp(locale));
1586
1590
  return getSearchIndex(ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farming-labs/svelte",
3
- "version": "0.2.72",
3
+ "version": "0.2.74",
4
4
  "description": "SvelteKit adapter for @farming-labs/docs — content loading and navigation utilities",
5
5
  "keywords": [
6
6
  "docs",
@@ -56,14 +56,17 @@
56
56
  "devDependencies": {
57
57
  "@types/node": "^22.10.0",
58
58
  "typescript": "^5.9.3",
59
- "@farming-labs/docs": "0.2.72"
59
+ "vitest": "^4.1.8",
60
+ "@farming-labs/docs": "0.2.74"
60
61
  },
61
62
  "peerDependencies": {
62
- "@farming-labs/docs": "*"
63
+ "@farming-labs/docs": ">=0.2.73"
63
64
  },
64
65
  "scripts": {
65
66
  "build": "tsc",
66
67
  "dev": "tsc --watch",
68
+ "test": "vitest run",
69
+ "test:watch": "vitest",
67
70
  "typecheck": "tsc --noEmit"
68
71
  }
69
72
  }