@dogsbay/format-dogsbay-md 0.2.0-beta.14 → 0.2.0-beta.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/attributes.d.ts +16 -2
  2. package/dist/attributes.js +14 -3
  3. package/dist/browser.d.ts +27 -0
  4. package/dist/browser.js +27 -0
  5. package/dist/capabilities.d.ts +25 -0
  6. package/dist/capabilities.js +91 -0
  7. package/dist/cli.d.ts +1 -1
  8. package/dist/cli.js +176 -30
  9. package/dist/code-regions.d.ts +88 -0
  10. package/dist/code-regions.js +214 -0
  11. package/dist/container-rule.d.ts +83 -0
  12. package/dist/container-rule.js +280 -0
  13. package/dist/data-directives.d.ts +43 -0
  14. package/dist/data-directives.js +248 -0
  15. package/dist/data-files.d.ts +99 -0
  16. package/dist/data-files.js +370 -0
  17. package/dist/diagnostics.d.ts +51 -0
  18. package/dist/diagnostics.js +388 -0
  19. package/dist/directive-guard.d.ts +10 -0
  20. package/dist/directive-guard.js +15 -0
  21. package/dist/directive-preserve.d.ts +71 -0
  22. package/dist/directive-preserve.js +426 -0
  23. package/dist/directive-props.d.ts +15 -0
  24. package/dist/directive-props.js +50 -0
  25. package/dist/directives.d.ts +2 -1
  26. package/dist/directives.js +39 -6
  27. package/dist/escape.d.ts +26 -8
  28. package/dist/escape.js +103 -31
  29. package/dist/frontmatter.d.ts +11 -0
  30. package/dist/frontmatter.js +66 -0
  31. package/dist/headings.d.ts +43 -0
  32. package/dist/headings.js +156 -0
  33. package/dist/index.d.ts +16 -3
  34. package/dist/index.js +16 -3
  35. package/dist/inline.d.ts +0 -4
  36. package/dist/inline.js +248 -13
  37. package/dist/minja-mask.d.ts +59 -0
  38. package/dist/minja-mask.js +139 -0
  39. package/dist/nav-file.d.ts +26 -4
  40. package/dist/nav-file.js +91 -15
  41. package/dist/nav.d.ts +7 -1
  42. package/dist/nav.js +36 -6
  43. package/dist/parse-attrs.d.ts +15 -1
  44. package/dist/parse-attrs.js +45 -1
  45. package/dist/parse.d.ts +37 -2
  46. package/dist/parse.js +886 -52
  47. package/dist/plugin-block-leaf.d.ts +0 -1
  48. package/dist/plugin-block-leaf.js +3 -16
  49. package/dist/plugin-containers.d.ts +23 -6
  50. package/dist/plugin-containers.js +71 -4
  51. package/dist/plugin-inline-directives.d.ts +10 -1
  52. package/dist/plugin-inline-directives.js +59 -29
  53. package/dist/plugin-mark.d.ts +12 -0
  54. package/dist/plugin-mark.js +74 -0
  55. package/dist/plugin-math.d.ts +22 -0
  56. package/dist/plugin-math.js +90 -0
  57. package/dist/project.d.ts +63 -0
  58. package/dist/project.js +112 -0
  59. package/dist/renderers/diagrams.d.ts +28 -0
  60. package/dist/renderers/diagrams.js +92 -0
  61. package/dist/renderers/mermaid.d.ts +23 -0
  62. package/dist/renderers/mermaid.js +151 -0
  63. package/dist/renderers/pele.d.ts +13 -0
  64. package/dist/renderers/pele.js +42 -0
  65. package/dist/serialize.d.ts +1 -2
  66. package/dist/serialize.js +736 -80
  67. package/dist/template-filters.d.ts +29 -0
  68. package/dist/template-filters.js +72 -0
  69. package/dist/template-pages.d.ts +92 -0
  70. package/dist/template-pages.js +336 -0
  71. package/dist/types.d.ts +9 -1
  72. package/dist/types.js +19 -2
  73. package/dist/yaml.d.ts +9 -4
  74. package/dist/yaml.js +159 -15
  75. package/package.json +28 -12
  76. package/dist/attributes.d.ts.map +0 -1
  77. package/dist/attributes.js.map +0 -1
  78. package/dist/cli.d.ts.map +0 -1
  79. package/dist/cli.js.map +0 -1
  80. package/dist/directives.d.ts.map +0 -1
  81. package/dist/directives.js.map +0 -1
  82. package/dist/escape.d.ts.map +0 -1
  83. package/dist/escape.js.map +0 -1
  84. package/dist/index.d.ts.map +0 -1
  85. package/dist/index.js.map +0 -1
  86. package/dist/inline.d.ts.map +0 -1
  87. package/dist/inline.js.map +0 -1
  88. package/dist/nav-file.d.ts.map +0 -1
  89. package/dist/nav-file.js.map +0 -1
  90. package/dist/nav.d.ts.map +0 -1
  91. package/dist/nav.js.map +0 -1
  92. package/dist/parse-attrs.d.ts.map +0 -1
  93. package/dist/parse-attrs.js.map +0 -1
  94. package/dist/parse.d.ts.map +0 -1
  95. package/dist/parse.js.map +0 -1
  96. package/dist/plugin-block-leaf.d.ts.map +0 -1
  97. package/dist/plugin-block-leaf.js.map +0 -1
  98. package/dist/plugin-containers.d.ts.map +0 -1
  99. package/dist/plugin-containers.js.map +0 -1
  100. package/dist/plugin-inline-directives.d.ts.map +0 -1
  101. package/dist/plugin-inline-directives.js.map +0 -1
  102. package/dist/serialize.d.ts.map +0 -1
  103. package/dist/serialize.js.map +0 -1
  104. package/dist/types.d.ts.map +0 -1
  105. package/dist/types.js.map +0 -1
  106. package/dist/yaml.d.ts.map +0 -1
  107. package/dist/yaml.js.map +0 -1
@@ -8,12 +8,27 @@
8
8
  export interface RenderedAttrs {
9
9
  id?: string;
10
10
  classes?: string[];
11
- props?: Record<string, string | number | boolean | undefined>;
11
+ /**
12
+ * Props captured from `TreeNode.props`. Primitive values (string,
13
+ * number, boolean) round-trip through inline `{key="value"}` form.
14
+ * Arrays / plain objects are preserved here too — `renderAttrs`
15
+ * skips them (inline form can't represent them) but the
16
+ * directive renderer's `shouldUseYaml` branch picks them up and
17
+ * routes the directive to YAML body form, where complex values
18
+ * survive intact.
19
+ */
20
+ props?: Record<string, unknown>;
12
21
  }
13
22
  /**
14
23
  * Render an attribute block.
15
24
  * Returns `{ #id .a .b key="value" }` or "" if no attrs.
16
25
  * Leading space included so callers can append directly to content.
26
+ *
27
+ * Inline form can only carry primitive values. Arrays / objects in
28
+ * `props` are silently skipped here — the caller is expected to have
29
+ * already routed those to YAML body form (see `shouldUseYaml` in
30
+ * directives.ts). If a non-primitive does reach this point, dropping
31
+ * it is the safest fallback (there's no inline syntax for it).
17
32
  */
18
33
  export declare function renderAttrs(attrs: RenderedAttrs): string;
19
34
  /**
@@ -30,4 +45,3 @@ export declare function escapeAttrValue(value: string): string;
30
45
  * This is the common glue between TreeNode.props and attribute output.
31
46
  */
32
47
  export declare function splitProps(props: Record<string, unknown> | undefined, excludeKeys?: string[]): RenderedAttrs;
33
- //# sourceMappingURL=attributes.d.ts.map
@@ -9,6 +9,12 @@
9
9
  * Render an attribute block.
10
10
  * Returns `{ #id .a .b key="value" }` or "" if no attrs.
11
11
  * Leading space included so callers can append directly to content.
12
+ *
13
+ * Inline form can only carry primitive values. Arrays / objects in
14
+ * `props` are silently skipped here — the caller is expected to have
15
+ * already routed those to YAML body form (see `shouldUseYaml` in
16
+ * directives.ts). If a non-primitive does reach this point, dropping
17
+ * it is the safest fallback (there's no inline syntax for it).
12
18
  */
13
19
  export function renderAttrs(attrs) {
14
20
  const parts = [];
@@ -29,6 +35,10 @@ export function renderAttrs(attrs) {
29
35
  parts.push(key);
30
36
  continue;
31
37
  }
38
+ // Skip arrays / plain objects — inline form can't represent
39
+ // them. They survive via the YAML body branch upstream.
40
+ if (typeof value === "object")
41
+ continue;
32
42
  parts.push(`${key}=${escapeAttrValue(String(value))}`);
33
43
  }
34
44
  }
@@ -71,8 +81,10 @@ export function splitProps(props, excludeKeys = []) {
71
81
  }
72
82
  if (value === null || value === undefined)
73
83
  continue;
74
- if (typeof value === "object")
75
- continue; // skip nested structures
84
+ // Pass arrays / objects through. Inline-form rendering will skip
85
+ // them (`renderAttrs`); YAML-body rendering preserves them
86
+ // (`attrsToYaml`). The `shouldUseYaml` heuristic in directives.ts
87
+ // detects their presence and routes the directive accordingly.
76
88
  cleanProps[key] = value;
77
89
  }
78
90
  if (Object.keys(cleanProps).length > 0) {
@@ -80,4 +92,3 @@ export function splitProps(props, excludeKeys = []) {
80
92
  }
81
93
  return result;
82
94
  }
83
- //# sourceMappingURL=attributes.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Browser-safe entry point — the pure TreeNode round-trip and text
3
+ * helpers, with NO `node:fs` in the module graph.
4
+ *
5
+ * The main barrel (`.`) re-exports nav / nav-file / mermaid, which
6
+ * import `node:fs` at module load and so break browser/extension
7
+ * bundling. Consumers that only need parse/serialize (the editing
8
+ * engine, extension contexts) import from `@dogsbay/format-dogsbay-md/browser`
9
+ * instead. `parse.ts` and `serialize.ts` transit only browser-safe deps
10
+ * (markdown-it, js-yaml). Frontmatter is split by the local `frontmatter.ts`
11
+ * (js-yaml only) rather than gray-matter, whose entry `require('fs')`s at
12
+ * module load and would drag `node:fs` back into this graph.
13
+ */
14
+ export { dogsbayMdToTree, parseInline, containerOpenBefore, type ParseResult, type ParseOptions } from "./parse.js";
15
+ export { KNOWN_INLINE_DIRECTIVES, type ParseDiagnostic } from "./diagnostics.js";
16
+ export { KNOWN_BLOCK_DIRECTIVES, LEAF_ONLY_DIRECTIVES, BLOCK_LEAF_DIRECTIVES } from "./plugin-containers.js";
17
+ export { treeToDogsbayMd, nodeToDogsbayMd } from "./serialize.js";
18
+ export type { SerializeOptions } from "./types.js";
19
+ export { inlineToDogsbayMd } from "./inline.js";
20
+ export { transformCodeRegions, transformProseLines, transformProseSegments, fenceOpenBefore, createFenceTracker, } from "./code-regions.js";
21
+ export { maskMinjaInCode, unmaskMinjaInCode, maskAllMinjaOpeners, isMinjaProcessedFence, stripInlineMinjaMarkers, stripFenceMinjaMarkers } from "./minja-mask.js";
22
+ export { extractHeadings, slugifyHeadingText, type HeadingInfo } from "./headings.js";
23
+ export { splitFrontmatter, type Frontmatter } from "./frontmatter.js";
24
+ export { DataFiles, DataCache, DataFileError, parseDataFile, parseDelimited, DEFAULT_DATA_LIMITS, UNTRUSTED_DATA_LIMITS, DATA_EXTENSIONS, type DataLimits, type DataFilesOptions, type DataExtension, } from "./data-files.js";
25
+ export { resolveDataDirectives, hasDataDirectives, DATA_DIRECTIVES, NO_PROJECT_MESSAGE, type DataProblem, type DataDirectivesResult, } from "./data-directives.js";
26
+ export { TemplatePages, TemplatePageError, declaresParams, ATTRIBUTE_BLOCK_OPEN, type TemplatePagesOptions } from "./template-pages.js";
27
+ export { dogsbayMdPageFiles, dogsbayMdPagePath, mountCopies, carriedFrontmatter, MEDIA_EXTS, type AssetMount } from "./project.js";
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Browser-safe entry point — the pure TreeNode round-trip and text
3
+ * helpers, with NO `node:fs` in the module graph.
4
+ *
5
+ * The main barrel (`.`) re-exports nav / nav-file / mermaid, which
6
+ * import `node:fs` at module load and so break browser/extension
7
+ * bundling. Consumers that only need parse/serialize (the editing
8
+ * engine, extension contexts) import from `@dogsbay/format-dogsbay-md/browser`
9
+ * instead. `parse.ts` and `serialize.ts` transit only browser-safe deps
10
+ * (markdown-it, js-yaml). Frontmatter is split by the local `frontmatter.ts`
11
+ * (js-yaml only) rather than gray-matter, whose entry `require('fs')`s at
12
+ * module load and would drag `node:fs` back into this graph.
13
+ */
14
+ export { dogsbayMdToTree, parseInline, containerOpenBefore } from "./parse.js";
15
+ export { KNOWN_INLINE_DIRECTIVES } from "./diagnostics.js";
16
+ // The `:::name` blocks the parser knows (an editor completes names from it)
17
+ export { KNOWN_BLOCK_DIRECTIVES, LEAF_ONLY_DIRECTIVES, BLOCK_LEAF_DIRECTIVES } from "./plugin-containers.js";
18
+ export { treeToDogsbayMd, nodeToDogsbayMd } from "./serialize.js";
19
+ export { inlineToDogsbayMd } from "./inline.js";
20
+ export { transformCodeRegions, transformProseLines, transformProseSegments, fenceOpenBefore, createFenceTracker, } from "./code-regions.js";
21
+ export { maskMinjaInCode, unmaskMinjaInCode, maskAllMinjaOpeners, isMinjaProcessedFence, stripInlineMinjaMarkers, stripFenceMinjaMarkers } from "./minja-mask.js";
22
+ export { extractHeadings, slugifyHeadingText } from "./headings.js";
23
+ export { splitFrontmatter } from "./frontmatter.js";
24
+ export { DataFiles, DataCache, DataFileError, parseDataFile, parseDelimited, DEFAULT_DATA_LIMITS, UNTRUSTED_DATA_LIMITS, DATA_EXTENSIONS, } from "./data-files.js";
25
+ export { resolveDataDirectives, hasDataDirectives, DATA_DIRECTIVES, NO_PROJECT_MESSAGE, } from "./data-directives.js";
26
+ export { TemplatePages, TemplatePageError, declaresParams, ATTRIBUTE_BLOCK_OPEN } from "./template-pages.js";
27
+ export { dogsbayMdPageFiles, dogsbayMdPagePath, mountCopies, carriedFrontmatter, MEDIA_EXTS } from "./project.js";
@@ -0,0 +1,25 @@
1
+ /**
2
+ * What the Dogsbay MD exporter can and cannot represent — a CONTRACT (the
3
+ * format-docusaurus pattern): one cell per `MATRIX_ROWS` type of the
4
+ * component × format matrix, checked by `validateCapabilities` and by
5
+ * tests/capabilities.test.ts.
6
+ *
7
+ * Dogsbay MD is the CANONICAL source format, so the bar for `full` is a
8
+ * round trip: `treeToDogsbayMd` → `dogsbayMdToTree` gives back the same tree
9
+ * (modulo canonical spelling — `:::tab[One]` comes back as the deflist tab
10
+ * form, a trailing newline on raw HTML). Each `full` below was measured that
11
+ * way, not assumed.
12
+ *
13
+ * Support levels: full — round-trips · partial — survives with reduced
14
+ * fidelity (the note says how) · none — dropped or flattened (the note says
15
+ * what is lost).
16
+ *
17
+ * Types with no `case` in `renderNode` fall to `renderUnknown`: with the
18
+ * default `unknownNodes: "html"` it writes `node.html` if present, else the
19
+ * children (the wrapper and its props are lost), else
20
+ * `<!-- unsupported: <type> -->`. Nothing is recorded — there is no export
21
+ * ledger in this package yet — so every partial/none here is a loss the
22
+ * exporter does not report.
23
+ */
24
+ import type { CapabilityDeclaration } from "@dogsbay/serialize-core";
25
+ export declare const DOGSBAY_MD_CAPABILITIES: CapabilityDeclaration[];
@@ -0,0 +1,91 @@
1
+ export const DOGSBAY_MD_CAPABILITIES = [
2
+ // ── Blocks ───────────────────────────────────────────────
3
+ { feature: "heading", support: "full", rendersAs: "`#`–`######` with `{#id .class}` attrs" },
4
+ { feature: "paragraph", support: "full" },
5
+ { feature: "blockquote", support: "full", rendersAs: "`> …`" },
6
+ { feature: "unordered-list", support: "full", rendersAs: "`- item`" },
7
+ { feature: "ordered-list", support: "full", rendersAs: "`1. item`" },
8
+ { feature: "hr", support: "full", rendersAs: "`---`" },
9
+ {
10
+ feature: "table",
11
+ support: "partial",
12
+ rendersAs: "GFM pipe table + `{caption=\"…\"}`; an HTML `<table>` when a cell holds blocks, a row has `th` cells, or the table is headerless",
13
+ note: "A simple table round-trips. The HTML fallback re-parses as a raw `html` node, not a `table`; inside it blocks other than paragraph/list/code/callout/table collapse to their content and kbd/icon/math/footnote-ref degrade to text.",
14
+ },
15
+ { feature: "code", support: "full", rendersAs: "fenced block with language, `title=\"…\"` and line-highlight meta" },
16
+ { feature: "math-block", support: "full", rendersAs: "`$$ … $$`" },
17
+ { feature: "deflist", support: "full", rendersAs: "`Term` / `: definition`" },
18
+ { feature: "figure", support: "full", rendersAs: "`:::figure{caption=\"…\"}`; a captionless figure is written as its content" },
19
+ { feature: "footnote-list", support: "full", rendersAs: "`[^label]: …` definitions" },
20
+ { feature: "html", support: "full", rendersAs: "the raw HTML, verbatim" },
21
+ {
22
+ feature: "html-container",
23
+ support: "partial",
24
+ rendersAs: "`node.html` verbatim, or the container's children as blocks",
25
+ note: "Content is kept; a children-only container (the shape the mkdocs md_in_html, asciidoc and mdx importers produce) loses its wrapper tag and attributes.",
26
+ },
27
+ {
28
+ feature: "diagram",
29
+ support: "partial",
30
+ rendersAs: "a ```mermaid fence with the diagram source",
31
+ note: "The source round-trips (it re-parses as a code fence, which the build turns back into a diagram); a pre-rendered SVG is not kept.",
32
+ },
33
+ { feature: "youtube", support: "full", rendersAs: "`::youtube{#id title=\"…\"}`" },
34
+ // ── Components ───────────────────────────────────────────
35
+ { feature: "callout", support: "full", rendersAs: "GitHub alert `> [!NOTE]`; `:::type[Title]{…}` for a custom title or a non-GitHub type" },
36
+ { feature: "details", support: "full", rendersAs: "`:::details{title=\"…\"}`" },
37
+ { feature: "details-sheet", support: "full", rendersAs: "`:::details{title=\"…\" sheet}`" },
38
+ { feature: "theme", support: "full", rendersAs: "`:::theme{name=\"dark\"}` around the content" },
39
+ { feature: "tabs-variant", support: "full", rendersAs: "`:::tabs{variant=\"pills\"}`" },
40
+ { feature: "tone", support: "full", rendersAs: "`tone=\"…\"` on `:::cards` or `:::card`" },
41
+ { feature: "tabs", support: "full", rendersAs: "`:::tabs` with the deflist tab form (`Label` / `: body`)" },
42
+ { feature: "steps", support: "full", rendersAs: "`:::steps` around an ordered list" },
43
+ { feature: "accordion", support: "full", rendersAs: "`:::accordion` with deflist items" },
44
+ { feature: "cards", support: "full", rendersAs: "`:::cards` — compact YAML list when every card body is paragraphs, `:::card` directives otherwise" },
45
+ { feature: "card", support: "full", rendersAs: "`:::card{title href …}`" },
46
+ { feature: "link-card", support: "full", rendersAs: "`:::link-card{title href}` with the description as body" },
47
+ { feature: "files", support: "full", rendersAs: "`:::files` around the nested list" },
48
+ { feature: "grid", support: "full", rendersAs: "`::::grid` / `:::grid-item`" },
49
+ { feature: "link-button", support: "full", rendersAs: "`:::button{href}`" },
50
+ { feature: "related", support: "full", rendersAs: "bold caption + `{._additional-resources}` + the link list (the shape the parser folds back)" },
51
+ {
52
+ feature: "example",
53
+ support: "partial",
54
+ rendersAs: "its children, unwrapped",
55
+ note: "No case: `renderUnknown` writes the children only. The `:::example` wrapper (live preview + shown source) is lost and the content re-parses as ordinary blocks; unrecorded.",
56
+ },
57
+ {
58
+ feature: "container",
59
+ support: "partial",
60
+ rendersAs: "`:::name` for this format's own generic containers; the children otherwise",
61
+ note: "A container parsed from Dogsbay MD (`meta.container` + `meta.name`) round-trips. A `container` from another importer has no name to write: its wrapper and props (class, id) are dropped and only the children survive; unrecorded.",
62
+ },
63
+ {
64
+ feature: "annotation-list",
65
+ support: "partial",
66
+ rendersAs: "each item's content as a separate paragraph",
67
+ note: "No case: `renderUnknown` writes the children, and the list items render without list markers — numbering and the link to the code block's `(n)` markers are lost; unrecorded.",
68
+ },
69
+ // ── API reference ────────────────────────────────────────
70
+ {
71
+ feature: "endpoint",
72
+ support: "partial",
73
+ rendersAs: "`## METHOD /path` + summary/description + Parameters table + request-body/response lists + code-sample fences",
74
+ note: "Readable Markdown, but not a structure: it re-parses as headings/tables/lists, never an `endpoint`. Schemas beyond name/type/required/description, and spec raw HTML (escaped as `&lt;`), are not carried.",
75
+ },
76
+ { feature: "api-doc", support: "full", rendersAs: "`:::api-doc{…}`" },
77
+ { feature: "api-class", support: "full", rendersAs: "`:::api-class{…}`" },
78
+ { feature: "api-member", support: "full", rendersAs: "`:::api-member{…}`" },
79
+ { feature: "api-params", support: "full", rendersAs: "`:::api-params` with a YAML `params:` body" },
80
+ { feature: "api-source", support: "full", rendersAs: "`:::api-source{…}`" },
81
+ // ── Inline ───────────────────────────────────────────────
82
+ { feature: "link", support: "full", rendersAs: "`[text](href \"title\")`" },
83
+ { feature: "image", support: "full", rendersAs: "`![alt](src \"title\"){attrs}`" },
84
+ { feature: "kbd", support: "full", rendersAs: "`:kbd[Ctrl+S]`" },
85
+ { feature: "math", support: "full", rendersAs: "`$…$`" },
86
+ { feature: "highlight", support: "full", rendersAs: "`==…==`" },
87
+ { feature: "badge", support: "full", rendersAs: "`:badge[Text]{variant=…}`" },
88
+ { feature: "icon", support: "full", rendersAs: "`:icon[name]`" },
89
+ { feature: "footnote-ref", support: "full", rendersAs: "`[^label]`" },
90
+ { feature: "html-inline", support: "full", rendersAs: "the raw HTML, verbatim" },
91
+ ];
package/dist/cli.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import type { FormatPlugin } from "@dogsbay/types";
2
+ export { carriedFrontmatter } from "./project.js";
2
3
  export declare const plugin: FormatPlugin;
3
- //# sourceMappingURL=cli.d.ts.map
package/dist/cli.js CHANGED
@@ -4,11 +4,17 @@
4
4
  * Reads a directory of .md files, parses each via dogsbayMdToTree, builds nav
5
5
  * from directory structure + frontmatter, returns ExportPage[] + NavItem[].
6
6
  */
7
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
8
- import { join, relative, basename } from "node:path";
7
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
8
+ import { join, relative, basename, dirname } from "node:path";
9
+ import { extractHeadings } from "./headings.js";
9
10
  import { parseMeta } from "@dogsbay/types";
10
11
  import { dogsbayMdToTree } from "./parse.js";
11
12
  import { buildNavFromDirectory } from "./nav.js";
13
+ import { renderDiagrams } from "./renderers/diagrams.js";
14
+ import { DOGSBAY_MD_CAPABILITIES } from "./capabilities.js";
15
+ import { dogsbayMdPageFiles, mountCopies } from "./project.js";
16
+ import { readFolder } from "@dogsbay/corpus/folder";
17
+ export { carriedFrontmatter } from "./project.js";
12
18
  /**
13
19
  * Detect whether a directory contains a Dogsbay MD source tree.
14
20
  *
@@ -30,16 +36,76 @@ function detectDogsbayMdSource(path) {
30
36
  return false;
31
37
  }
32
38
  }
39
+ /**
40
+ * Conventional content-asset roots, in probe order. Mounted under their own
41
+ * name so an author's `/images/logo.png` resolves, and excluded from the page
42
+ * walk so their contents are assets rather than also being pages.
43
+ */
44
+ const ASSET_ROOTS = ["images", "assets", "_assets"];
45
+ /**
46
+ * Does this directory hold any markdown, at any depth?
47
+ *
48
+ * Distinguishes a media-only asset root (skip it: its files are assets, and a
49
+ * stray .md would become both a page and a raw copy in public/) from a docs
50
+ * SECTION that merely shares the name (walk it: those are pages).
51
+ */
52
+ function containsMarkdown(dir) {
53
+ let entries;
54
+ try {
55
+ entries = readdirSync(dir, { withFileTypes: true });
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ for (const e of entries) {
61
+ if (e.isDirectory()) {
62
+ if (containsMarkdown(join(dir, e.name)))
63
+ return true;
64
+ }
65
+ else if (e.name.endsWith(".md")) {
66
+ return true;
67
+ }
68
+ }
69
+ return false;
70
+ }
33
71
  function walkMdFiles(dir, root, out = []) {
34
72
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
73
+ // `_`-prefixed files/dirs are include targets (fragments), not routable
74
+ // pages — the standard Jekyll/Docusaurus convention. The build-time Minja
75
+ // preprocessor `{% include %}`s them into pages; they get no route of their
76
+ // own. (e.g. structural Docusaurus import writes `_includes/**` fragments.)
77
+ if (entry.name.startsWith("_"))
78
+ continue;
79
+ // A conventional asset root carrying only media is not a page tree, and
80
+ // leaving it in the walk would make a stray .md there BOTH a routable
81
+ // page and a file copied verbatim into public/.
82
+ //
83
+ // But `images/` is also a perfectly ordinary section name. Skipping it
84
+ // unconditionally silently dropped every page under it — "Imported 1
85
+ // pages" where there were 2, no warning. So skip only a root that
86
+ // carries NO markdown at all, and only at the content root.
87
+ if (dir === root &&
88
+ ASSET_ROOTS.includes(entry.name) &&
89
+ !containsMarkdown(join(dir, entry.name))) {
90
+ continue;
91
+ }
35
92
  const full = join(dir, entry.name);
36
93
  if (entry.isDirectory()) {
37
94
  walkMdFiles(full, root, out);
38
95
  }
39
96
  else if (entry.name.endsWith(".md")) {
40
97
  const rel = relative(root, full).replace(/\\/g, "/");
41
- const slug = rel.replace(/\.md$/, "");
42
- out.push({ filePath: full, slug });
98
+ let slug = rel.replace(/\.md$/, "");
99
+ // A `<dir>/index.md` page is the directory's landing page: its slug
100
+ // is the directory, not `<dir>/index`. This MUST match how the nav
101
+ // layer normalizes the same file (nav-file.ts `fileToHref` strips
102
+ // `/index`), or `routablesFrom: nav`'s `filterPagesToNav` drops the
103
+ // page and the section landing 404s. The bare root `index.md` keeps
104
+ // slug `index` — format-astro's root-home + `.md`-mirror special-case
105
+ // keys off `slug === "index"`. See plans/dir-index-slug-nav-drop.md.
106
+ if (slug.endsWith("/index"))
107
+ slug = slug.slice(0, -"/index".length);
108
+ out.push({ filePath: full, slug, sourcePath: rel });
43
109
  }
44
110
  }
45
111
  return out;
@@ -61,30 +127,38 @@ async function importDogsbayMd(source, opts) {
61
127
  const taxonomyNames = Array.isArray(opts.taxonomyNames)
62
128
  ? opts.taxonomyNames
63
129
  : undefined;
64
- for (const { filePath, slug } of files) {
130
+ // Pre-parse pass — opt-out via `diagrams: false`. When enabled
131
+ // (default), `code` fences with `lang: mermaid` get transformed
132
+ // to `diagram` nodes with pre-rendered SVG. Fail-open: if mmdc
133
+ // (mermaid-cli) isn't installed the code block is left as-is and
134
+ // a one-line warning is printed. See plans/mermaid-dogsbay-md.md.
135
+ const diagramsOn = opts.diagrams !== false;
136
+ // `content.diagrams: pele` draws them with Pele; `true` (the default) with mmdc
137
+ const diagramEngine = opts.diagrams === "pele" ? "pele" : "mermaid-cli";
138
+ for (const { filePath, slug, sourcePath } of files) {
65
139
  const content = readFileSync(filePath, "utf-8");
66
140
  const { tree, frontmatter } = dogsbayMdToTree(content);
141
+ if (diagramsOn) {
142
+ await renderDiagrams(tree, { engine: diagramEngine });
143
+ }
67
144
  const title = String(frontmatter.title
68
145
  ?? prettifyName(basename(slug)));
69
- // Extract heading metadata for TOC
70
- const headings = [];
71
- for (const node of tree) {
72
- if (node.type === "heading" && node.inline) {
73
- const text = node.inline
74
- .map((n) => (n.type === "text" ? n.text : ""))
75
- .join("")
76
- .trim();
77
- headings.push({
78
- depth: node.props?.level ?? 1,
79
- slug: node.props?.slug ?? slugify(text),
80
- text,
81
- });
82
- }
83
- }
146
+ // Extract heading metadata for TOC AND backfill `node.props.slug`
147
+ // so format-astro's headingToAstro emits a matching `id` on the
148
+ // rendered `<h2>` / `<h3>`. Without this, the TOC's
149
+ // `<a href="#quick-start">` had nothing to scroll to — the
150
+ // heading was emitted without an id because the tree didn't
151
+ // carry the slug. Mirrors format-mkdocs/src/loader.ts:312.
152
+ //
153
+ // Duplicate slugs get `-1`, `-2` suffixes so two `## Foo`
154
+ // headings on the same page produce distinct anchors. Same
155
+ // collision-handling shape as MkDocs.
156
+ const headings = extractHeadings(tree);
84
157
  const redirect = frontmatter.redirect;
85
158
  const meta = parseMeta(frontmatter, { slug, taxonomyNames });
86
159
  pages.push({
87
160
  slug,
161
+ sourcePath,
88
162
  title,
89
163
  tree,
90
164
  headings,
@@ -95,8 +169,42 @@ async function importDogsbayMd(source, opts) {
95
169
  }
96
170
  const navFilePath = opts.nav || undefined;
97
171
  const hrefPrefix = typeof opts.hrefPrefix === "string" ? opts.hrefPrefix : undefined;
98
- const nav = buildNavFromDirectory(source, { navFilePath, hrefPrefix });
99
- return { pages, nav };
172
+ // `--strict` at the CLI layer maps to "fail" here. `loadNavFile`
173
+ // already throws on the first miss in fail mode; the build
174
+ // surfaces the throw as a fatal error and exits non-zero.
175
+ // See plans/site-build-strict.md.
176
+ const missingNavTargets = opts.missingNavTargets === "fail"
177
+ ? "fail"
178
+ : undefined;
179
+ const nav = buildNavFromDirectory(source, {
180
+ navFilePath,
181
+ hrefPrefix,
182
+ missingFile: missingNavTargets,
183
+ });
184
+ // Declare where this corpus's media lives, so an exporter copies the FILES
185
+ // that the `_assets/…` references in the pages point at.
186
+ //
187
+ // Without this the reference survives the conversion and the file does not,
188
+ // which looks exactly like success: the page count, the retention score and
189
+ // a clean exit are all unaffected while every image 404s. `dogsbay site
190
+ // build` has its own asset pass, so this was invisible there and only bit
191
+ // `convert` — an OpenShift vault shipped with 294 dead image references.
192
+ // Conventional asset roots, in probe order. `_assets` is what every
193
+ // importer rewrites its refs to and stays the documented convention
194
+ // (docs/images.md). Hand-authored content is not written by an
195
+ // importer, though: someone starting a site types `/images/logo.png`,
196
+ // which silently resolved nowhere because only `_assets` was probed.
197
+ //
198
+ // Each root that exists mounts under its OWN name, so the reference the
199
+ // author wrote is the path the file lands at. Recognising several costs
200
+ // nothing: an absent directory is simply not mounted.
201
+ const assetMounts = [];
202
+ for (const root of ASSET_ROOTS) {
203
+ const dir = join(source, root);
204
+ if (existsSync(dir))
205
+ assetMounts.push({ dir, root });
206
+ }
207
+ return assetMounts.length ? { pages, nav, assetMounts } : { pages, nav };
100
208
  }
101
209
  function prettifyName(slug) {
102
210
  return slug
@@ -104,17 +212,53 @@ function prettifyName(slug) {
104
212
  .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
105
213
  .join(" ");
106
214
  }
107
- function slugify(text) {
108
- return text
109
- .toLowerCase()
110
- .replace(/[^\w\s-]/g, "")
111
- .trim()
112
- .replace(/\s+/g, "-");
215
+ /**
216
+ * Export ExportPage[] + nav to a directory of Dogsbay-MD files.
217
+ *
218
+ * Each page's tree is serialized via `treeToDogsbayMd` (which preserves any
219
+ * Minja directives via `escapePreservingMinja`) and written to `<output>/<slug>.md`.
220
+ *
221
+ * Fragment pages (`page.fragment`) are include targets, not routable pages:
222
+ * written with NO frontmatter, NO title, and excluded from nav — their identity
223
+ * is the include path. Mirrors migrate-asciidoc's fragment convention so the
224
+ * build-time Minja preprocessor can `{% include %}` them.
225
+ */
226
+ async function exportDogsbayMd(pages, nav, output, opts) {
227
+ mkdirSync(output, { recursive: true });
228
+ // Copy mounted asset dirs (e.g. Docusaurus `static/`) into `content/_assets/`,
229
+ // the Dogsbay standard (docs/images.md). Preserves internal structure
230
+ // (static/img/x → <output>/_assets/img/x) so the parser's rewritten
231
+ // `/_assets/img/x` refs resolve, and a later `site build`'s asset pass copies
232
+ // `content/_assets/**` through to `/_assets/**`. A mount may target an
233
+ // `_assets` subdir (`into`) and restrict itself to media files (`mediaOnly`) —
234
+ // used for docs-co-located images where the mount dir IS the docs tree.
235
+ // The copy is `mountCopies` over the mount read as a corpus — the list the browser import
236
+ // copies from its map, so both hosts copy the same files. A mount is someone else's repo:
237
+ // a symlink out of it (`public/leak.png -> ~/.ssh/id_rsa`) was copied as a link to that
238
+ // file, and `node_modules` / `.git` inside it were copied whole (2026-10-21).
239
+ if (Array.isArray(opts.assetMounts)) {
240
+ for (const mount of opts.assetMounts) {
241
+ if (!existsSync(mount.dir))
242
+ continue;
243
+ const folder = readFolder(mount.dir);
244
+ for (const { from, to } of mountCopies(folder.paths, [{ ...mount, dir: "" }])) {
245
+ const dst = join(output, to);
246
+ mkdirSync(dirname(dst), { recursive: true });
247
+ copyFileSync(folder.absolute(from), dst);
248
+ }
249
+ }
250
+ }
251
+ for (const [path, text] of dogsbayMdPageFiles(pages, nav)) {
252
+ const outPath = join(output, path);
253
+ mkdirSync(dirname(outPath), { recursive: true });
254
+ writeFileSync(outPath, text, "utf-8");
255
+ }
113
256
  }
114
257
  export const plugin = {
115
258
  name: "dogsbay-md",
116
259
  canImport: true,
117
- canExport: false,
260
+ canExport: true,
261
+ capabilities: DOGSBAY_MD_CAPABILITIES,
118
262
  detectSource: detectDogsbayMdSource,
119
263
  importOptions: [
120
264
  {
@@ -125,5 +269,7 @@ export const plugin = {
125
269
  async import(source, opts) {
126
270
  return importDogsbayMd(source, opts);
127
271
  },
272
+ async export(pages, nav, output, opts) {
273
+ return exportDogsbayMd(pages, nav, output, opts);
274
+ },
128
275
  };
129
- //# sourceMappingURL=cli.js.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Code-region walker — THE fence grammar shared by every tool that must
3
+ * treat code specially: the build preprocessor masks Minja openers
4
+ * inside code so template examples never evaluate, the workspace
5
+ * indexer blanks code so `{% include %}` examples never count as real
6
+ * includes, and the refactor commands edit only prose so code samples
7
+ * are never rewritten. One implementation, so none of them can drift.
8
+ *
9
+ * Fence rules (CommonMark): a fence opens with ``` or ~~~ (3+ chars,
10
+ * info string allowed) and closes only on a line of the SAME character
11
+ * with AT LEAST the opener's length and nothing but whitespace after —
12
+ * the serializer emits escalated fences (```` around content containing
13
+ * ```), so honoring the length rule is load-bearing. Fence-looking
14
+ * lines inside an open fence that don't close it are code content.
15
+ */
16
+ type LineKind = "prose" | "fence" | "code";
17
+ /** Context passed to a code transform: which fence the line belongs to. */
18
+ export interface CodeRegionContext {
19
+ /**
20
+ * Fence info string (e.g. `yaml {minja}`). For inline code spans:
21
+ * the markdown-it-attrs group immediately following the closing
22
+ * backticks when present (e.g. `{minja}` for `` `x`{minja} ``),
23
+ * empty otherwise — so `isMinjaProcessedFence` grades fences and
24
+ * marked inline spans with the same predicate.
25
+ */
26
+ fenceInfo: string;
27
+ }
28
+ /**
29
+ * Transform CODE content: every line inside a fence, and the inner
30
+ * content of inline code spans on prose lines (backticks kept). Fence
31
+ * marker lines themselves are untouched.
32
+ *
33
+ * `transformInlineAttrs` (optional) rewrites the attr group of an
34
+ * inline span at re-emission — return `""` to drop it. Only inline
35
+ * spans see it; fence info strings are never routed through it.
36
+ */
37
+ /**
38
+ * Line-by-line fence tracker on THE shared grammar — for tools that must
39
+ * walk a document themselves (the remote-include inliner) instead of
40
+ * transforming regions. A locally re-implemented open/close regex pair
41
+ * drifted immediately: it missed the deflist-hosted `: ```` opener the
42
+ * shared grammar just gained, took the indented closer for an opener,
43
+ * and re-created the exact phantom-fence inversion it was fixing
44
+ * (issue #039 review).
45
+ *
46
+ * step(line) returns what the line IS: "fence" (an opener or closer),
47
+ * "code" (content of an open fence), or "prose". open() reports the
48
+ * state AFTER the last step, so an opener steps "fence" with
49
+ * open()===true and its closer steps "fence" with open()===false.
50
+ */
51
+ export declare function createFenceTracker(): {
52
+ step(line: string): LineKind;
53
+ open(): boolean;
54
+ };
55
+ /**
56
+ * Transform only fence OPENING lines' info strings, on the same shared
57
+ * grammar — a fence-looking line inside an open fence is code content
58
+ * and is never touched. Used to strip the spent `{minja}` marker after
59
+ * the terminal Minja render (a fence marker that survives into the
60
+ * mirror leaks into serializers that round-trip fence info verbatim —
61
+ * the Obsidian vault showed literal ```` ```yaml {minja} ````).
62
+ */
63
+ export declare function transformFenceInfo(source: string, transform: (info: string) => string): string;
64
+ export declare function transformCodeRegions(source: string, transform: (codeText: string, ctx: CodeRegionContext) => string, transformInlineAttrs?: (attrs: string) => string): string;
65
+ /**
66
+ * The inverse walk: transform PROSE lines (outside fences), leaving
67
+ * fenced content and the fence lines untouched. Used by refactor
68
+ * commands that rewrite markdown structure line-wise (heading shifts,
69
+ * section splits) — a `# heading` inside a code example must never be
70
+ * treated as structure.
71
+ */
72
+ export declare function transformProseLines(source: string, transform: (line: string, lineIndex: number) => string): string;
73
+ /**
74
+ * Transform PROSE TEXT SEGMENTS: prose lines with their inline code
75
+ * spans protected (the transform sees only the non-code stretches of
76
+ * each prose line). This is the write-side counterpart of
77
+ * transformCodeRegions — refactor commands rewrite references through
78
+ * it so `[x](old.md)` or `{{ key }}` inside examples survive verbatim.
79
+ */
80
+ export declare function transformProseSegments(source: string, transform: (proseText: string) => string): string;
81
+ /**
82
+ * Fence state BEFORE each line: `openBefore[i]` is true when line i
83
+ * starts inside an unclosed fence. One extra trailing entry gives the
84
+ * state after the last line. Lets line-range refactors check "does
85
+ * this range start or end mid-fence" with the same grammar.
86
+ */
87
+ export declare function fenceOpenBefore(source: string): boolean[];
88
+ export {};