@dogsbay/format-obsidian 0.2.0-beta.10 → 0.2.0-beta.102

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/serialize.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { walkInline, applyTextFlags, renderLeaf, prefixLines, pickCodeFence, stripHtml, inlineHtmlToMarkdown, } from "@dogsbay/serialize-core";
1
2
  /**
2
3
  * Transform an href for Obsidian vault paths.
3
4
  *
@@ -7,13 +8,68 @@
7
8
  * https://example.com → https://example.com (unchanged)
8
9
  * #local-anchor → #local-anchor (unchanged)
9
10
  */
11
+ /**
12
+ * `/_assets/x.png` → `_assets/x.png`.
13
+ *
14
+ * Importers rewrite media refs to the `/_assets/…` mount convention, which is
15
+ * right for a served site and wrong in a vault: Obsidian resolves a link
16
+ * against the vault, so a leading slash finds nothing — even though the
17
+ * exporter copied the file to `_assets/x.png`. External and data URIs are
18
+ * left alone.
19
+ */
20
+ /**
21
+ * Make asset references inside RAW HTML resolvable from the vault.
22
+ *
23
+ * A served site roots them (`/_assets/images/x.png`); a vault has no site
24
+ * root, so the same path resolves nowhere. `vaultAssetPath` already handles
25
+ * this for `image` inline nodes, but a complex AsciiDoc table is emitted as
26
+ * raw HTML and its cells carry their own `<img src>` — which never reaches
27
+ * that renderer. Five images in an OpenShift vault were dead for exactly this
28
+ * reason while the identical file resolved fine one paragraph earlier.
29
+ */
30
+ function vaultifyHtmlAssets(html) {
31
+ if (!html.includes("/_assets/"))
32
+ return html;
33
+ return html
34
+ .replace(/(\ssrc=")\/+(_assets\/)/g, "$1$2")
35
+ .replace(/(\shref=")\/+(_assets\/)/g, "$1$2");
36
+ }
37
+ function vaultAssetPath(src) {
38
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src))
39
+ return src;
40
+ return src.replace(/^\/+/, "");
41
+ }
42
+ /**
43
+ * Sanitize a slug into a valid Obsidian BLOCK IDENTIFIER.
44
+ *
45
+ * Obsidian block ids accept only letters, numbers and dashes. Anything else
46
+ * means the `^id` is not parsed as a block id at all — it renders as literal
47
+ * text in BOTH edit and reading view, and any `#^id` link pointing at it is
48
+ * dead.
49
+ *
50
+ * This is not a corner case: AsciiDoc ids join a module and its context with
51
+ * an underscore (`additional-resources_welcome-index`), so a real OpenShift
52
+ * vault had 21,509 unusable anchors across 82% of its notes, and 2,333 of its
53
+ * cross-references (21%) resolved to nothing. The visible tell is that a
54
+ * dash-only id like `^welcome-index` superscripts and hides correctly while
55
+ * its underscore sibling does not.
56
+ *
57
+ * MUST be applied to the anchor and to every link that targets it, or the two
58
+ * stop agreeing — which is worse than leaving both broken.
59
+ */
60
+ export function obsidianBlockId(slug) {
61
+ return slug
62
+ .replace(/[^A-Za-z0-9-]+/g, "-")
63
+ .replace(/-{2,}/g, "-")
64
+ .replace(/^-+|-+$/g, "");
65
+ }
10
66
  function obsidianHref(href) {
11
67
  // External URLs — leave as-is
12
68
  if (href.startsWith("http://") || href.startsWith("https://"))
13
69
  return href;
14
70
  // Local anchors — rewrite to block ID reference
15
71
  if (href.startsWith("#"))
16
- return `#^${href.slice(1)}`;
72
+ return `#^${obsidianBlockId(href.slice(1))}`;
17
73
  // Strip leading /
18
74
  let result = href.replace(/^\//, "");
19
75
  // Strip trailing /
@@ -21,13 +77,43 @@ function obsidianHref(href) {
21
77
  // Normalize /#anchor to #anchor (strip / before #)
22
78
  result = result.replace(/\/#/, "#");
23
79
  // Rewrite #slug anchors to #^slug block ID references
24
- result = result.replace(/#(.+)$/, "#^$1");
80
+ result = result.replace(/#(.+)$/, (_m, frag) => `#^${obsidianBlockId(frag)}`);
25
81
  return result;
26
82
  }
83
+ /**
84
+ * Block ids already emitted for the CURRENT page.
85
+ *
86
+ * Reset per page in `treeToObsidian` (project.ts calls it exactly once per
87
+ * page). Obsidian indexes a block id per note, so two headings sharing one id
88
+ * make every `#^id` link resolve to whichever comes first — silently.
89
+ *
90
+ * Measured on OpenShift 4.22: 1,855 duplicate ids were ALREADY present in the
91
+ * AsciiDoc source, and sanitizing added only 2 more. So this mostly cleans up
92
+ * a pre-existing source problem rather than one we introduced. Links keep
93
+ * targeting the un-suffixed id and therefore still land on the first heading —
94
+ * the same behaviour as before, but without Obsidian seeing a duplicate.
95
+ */
96
+ const usedBlockIds = new Set();
97
+ function uniqueBlockId(id) {
98
+ if (!id)
99
+ return id;
100
+ if (!usedBlockIds.has(id)) {
101
+ usedBlockIds.add(id);
102
+ return id;
103
+ }
104
+ for (let n = 1;; n++) {
105
+ const candidate = `${id}-${n}`;
106
+ if (!usedBlockIds.has(candidate)) {
107
+ usedBlockIds.add(candidate);
108
+ return candidate;
109
+ }
110
+ }
111
+ }
27
112
  /**
28
113
  * Convert TreeNode[] to Obsidian-flavored Markdown.
29
114
  */
30
115
  export function treeToObsidian(nodes) {
116
+ usedBlockIds.clear();
31
117
  return nodes.map(nodeToObsidian).filter(Boolean).join("\n\n");
32
118
  }
33
119
  // ── Block dispatcher ────────────────────────────────────
@@ -40,7 +126,7 @@ function nodeToObsidian(node) {
40
126
  case "heading":
41
127
  return headingToObsidian(node);
42
128
  case "paragraph":
43
- return childrenToObsidian(node);
129
+ return leafContent(node);
44
130
  case "prose":
45
131
  return proseToObsidian(node);
46
132
  case "callout":
@@ -68,9 +154,9 @@ function nodeToObsidian(node) {
68
154
  case "deflist":
69
155
  return deflistToObsidian(node);
70
156
  case "dt":
71
- return `**${childrenToObsidian(node)}**`;
157
+ return `**${leafContent(node)}**`;
72
158
  case "dd":
73
- return `: ${childrenToObsidian(node)}`;
159
+ return `: ${leafContent(node)}`;
74
160
  case "steps":
75
161
  return stepsToObsidian(node);
76
162
  case "step":
@@ -87,7 +173,7 @@ function nodeToObsidian(node) {
87
173
  case "hr":
88
174
  return "---";
89
175
  case "html":
90
- return node.html ?? "";
176
+ return vaultifyHtmlAssets(node.html ?? "");
91
177
  case "html-container":
92
178
  return childrenToObsidian(node);
93
179
  case "figure": {
@@ -115,72 +201,169 @@ function nodeToObsidian(node) {
115
201
  return footnoteListToObsidian(node);
116
202
  case "footnote-def":
117
203
  return footnoteDefToObsidian(node);
204
+ case "related": {
205
+ // "Additional resources" blocks — the parser models the labeled
206
+ // link-list as a `related` node carrying its TITLE in props. The
207
+ // default fallthrough emitted only the children, so every such
208
+ // label vanished from the vault (issue #064: first-of-two blocks,
209
+ // the 8 per-section labels on oadp-api, nodes-nodes-jobs' heading —
210
+ // links floated with no context). A missing serializer case is a
211
+ // silent loss.
212
+ const title = (node.props?.title ?? "").trim();
213
+ const body = childrenToObsidian(node);
214
+ // No invented default label (format-astro omits it too — and an
215
+ // English fallback is wrong for localized corpora); escape emphasis
216
+ // chars so a title containing `*` can't break the bold wrapper.
217
+ if (!title)
218
+ return body;
219
+ return `**${title.replace(/([*\\])/g, "\\$1")}**\n\n${body}`;
220
+ }
118
221
  default:
119
222
  if (node.html)
120
- return stripHtml(node.html);
223
+ return htmlToObsidian(node.html);
121
224
  if (node.children)
122
225
  return childrenToObsidian(node);
123
226
  return "";
124
227
  }
125
228
  }
126
229
  // ── Inline rendering ────────────────────────────────────
230
+ /**
231
+ * Obsidian's inline syntax, as emitters over serialize-core's shared walk.
232
+ *
233
+ * The traversal, the nesting recursion, and the bold/italic/strike flag order
234
+ * used to live here as a fourth copy of the same 11-variant switch. Only the
235
+ * leaf syntax below is Obsidian-specific; everything structural is now shared,
236
+ * so a variant added to `InlineNode` surfaces in one place instead of four.
237
+ *
238
+ * Emitters are exhaustive on purpose: an omission routes through the core's
239
+ * `onUnsupported` plain-text degradation, which is the right default for a new
240
+ * variant but the WRONG behaviour for one Obsidian genuinely supports.
241
+ */
242
+ const OBSIDIAN_INLINE = {
243
+ text: (node) =>
244
+ // Escape tag-like `<` in prose: markdown-it decoded the engine's
245
+ // `&lt;` entities into bare `<`, and Obsidian's reading view swallows
246
+ // `<cluster-name>` as an unknown HTML tag — the placeholder text
247
+ // silently disappears for the reader (issue #046). A backslash escape
248
+ // renders as the literal character.
249
+ applyTextFlags(node.text.replace(/<(?=[A-Za-z/])/g, "\\<"), node, {
250
+ bold: (s) => `**${s}**`,
251
+ italic: (s) => `*${s}*`,
252
+ strike: (s) => `~~${s}~~`,
253
+ }),
254
+ link: (node, ctx) => {
255
+ const title = node.title ? ` "${node.title}"` : "";
256
+ return `[${ctx.recurse(node.children)}](${obsidianHref(node.href)}${title})`;
257
+ },
258
+ // A leading slash is not a vault path — see vaultAssetPath.
259
+ image: (node) => `![${node.alt ?? ""}](${vaultAssetPath(node.src)})`,
260
+ code: (node) => `\`${node.text}\``,
261
+ highlight: (node, ctx) => `==${ctx.recurse(node.children)}==`,
262
+ "footnote-ref": (node) => `[^${node.label}]`,
263
+ kbd: (node) => node.keys.map((k) => `<kbd>${k}</kbd>`).join("+"),
264
+ math: (node) => `$${node.latex}$`,
265
+ icon: (node) => `:${node.name}:`,
266
+ "html-inline": (node) => node._composedRun
267
+ ? (node.html ?? "")
268
+ : vaultifyHtmlAssets(node.html ?? ""),
269
+ break: () => " \n",
270
+ };
127
271
  function inlineToObsidian(nodes) {
128
- return nodes.map(inlineNodeToObsidian).join("");
272
+ return walkInline(groupFormatRuns(nodes), { emitters: OBSIDIAN_INLINE });
129
273
  }
130
- function inlineNodeToObsidian(node) {
131
- switch (node.type) {
132
- case "text": {
133
- let text = node.text;
134
- if (node.bold && node.italic)
135
- text = `***${text}***`;
136
- else if (node.bold)
137
- text = `**${text}**`;
138
- else if (node.italic)
139
- text = `*${text}*`;
140
- if (node.strikethrough)
141
- text = `~~${text}~~`;
142
- return text;
274
+ /**
275
+ * Wrap CONSECUTIVE nodes sharing the same bold/italic/strike flags in one
276
+ * mark pair instead of per-node wrapping. The parser inherits strong/em
277
+ * flags onto code spans (`**`code` text**`, issue #045); per-node
278
+ * emission produced `` `code`** text** `` — the code span unbolded and
279
+ * `** text**` (space inside the opener) not even parsing as bold. Runs
280
+ * are emitted as a single html-inline-free group: flags stripped from the
281
+ * clones, marks around the whole run, run-edge spaces shifted OUTSIDE the
282
+ * marks (CommonMark flanking).
283
+ */
284
+ function groupFormatRuns(nodes) {
285
+ const flagsOf = (n) => {
286
+ const f = n;
287
+ return `${f.bold ? "b" : ""}${f.italic ? "i" : ""}${f.strikethrough ? "s" : ""}`;
288
+ };
289
+ const flaggable = (n) => n.type === "text" || n.type === "code";
290
+ const out = [];
291
+ let i = 0;
292
+ while (i < nodes.length) {
293
+ const key = flagsOf(nodes[i]);
294
+ if (!key || !flaggable(nodes[i])) {
295
+ out.push(nodes[i]);
296
+ i++;
297
+ continue;
143
298
  }
144
- case "link": {
145
- const text = inlineToObsidian(node.children);
146
- const title = node.title ? ` "${node.title}"` : "";
147
- return `[${text}](${obsidianHref(node.href)}${title})`;
299
+ let j = i;
300
+ while (j < nodes.length && flaggable(nodes[j]) && flagsOf(nodes[j]) === key)
301
+ j++;
302
+ // A single flagged TEXT node keeps the proven per-node path (its
303
+ // escaping and flag order are pinned by the byte-parity suite); the
304
+ // synthetic group exists only for the broken shapes — a flagged code
305
+ // span, or a run split across several nodes.
306
+ if (j === i + 1 && nodes[i].type === "text") {
307
+ out.push(nodes[i]);
308
+ i = j;
309
+ continue;
148
310
  }
149
- case "image": {
150
- const alt = node.alt ?? "";
151
- return `![${alt}](${node.src})`;
311
+ const run = nodes.slice(i, j).map((n) => {
312
+ const clone = { ...n };
313
+ delete clone.bold;
314
+ delete clone.italic;
315
+ delete clone.strikethrough;
316
+ return clone;
317
+ });
318
+ let inner = walkInline(run, { emitters: OBSIDIAN_INLINE });
319
+ const lead = inner.match(/^\s*/)[0];
320
+ const tail = inner.match(/\s*$/)[0];
321
+ inner = inner.slice(lead.length, inner.length - tail.length || undefined);
322
+ if (inner) {
323
+ let open = "";
324
+ let close = "";
325
+ if (key.includes("s")) {
326
+ open += "~~";
327
+ close = "~~" + close;
328
+ }
329
+ if (key.includes("i")) {
330
+ open += "*";
331
+ close = "*" + close;
332
+ }
333
+ if (key.includes("b")) {
334
+ open += "**";
335
+ close = "**" + close;
336
+ }
337
+ // _composedRun: this is already-serialized MARKDOWN riding the
338
+ // html-inline pass-through, not raw HTML — the emitter must not run
339
+ // vaultifyHtmlAssets over it (it would rewrite `src="/_assets/…"`
340
+ // even inside a code span within the run).
341
+ out.push({ type: "html-inline", html: lead + open + inner + close + tail, _composedRun: true });
152
342
  }
153
- case "code":
154
- return `\`${node.text}\``;
155
- case "highlight":
156
- return `==${inlineToObsidian(node.children)}==`;
157
- case "footnote-ref":
158
- return `[^${node.label}]`;
159
- case "kbd":
160
- return node.keys.map((k) => `<kbd>${k}</kbd>`).join("+");
161
- case "math":
162
- return `$${node.latex}$`;
163
- case "icon":
164
- return `:${node.name}:`;
165
- case "html-inline":
166
- return node.html;
167
- case "break":
168
- return " \n";
169
- default:
170
- return "";
343
+ else if (lead) {
344
+ // Whitespace-only run: lead and tail both matched the WHOLE string,
345
+ // so pushing lead+tail doubled the spaces. lead alone IS the run.
346
+ out.push({ type: "text", text: lead });
347
+ }
348
+ i = j;
171
349
  }
350
+ return out;
172
351
  }
173
352
  // ── Prose (inline or HTML fallback) ─────────────────────
174
353
  function proseToObsidian(node) {
175
354
  if (node.inline)
176
355
  return inlineToObsidian(node.inline);
177
356
  if (node.html)
178
- return stripHtml(node.html);
357
+ return htmlToObsidian(node.html);
179
358
  return "";
180
359
  }
181
360
  // ── Callouts (lossless mapping) ─────────────────────────
182
361
  function calloutToObsidian(node) {
183
- const variant = node.props?.variant ?? "note";
362
+ // Shape-tolerant: the dogsbay-md parser emits `props.type` for `:::tip`
363
+ // directives; importers emit `props.variant`. Reading only `variant`
364
+ // demoted EVERY parsed callout to note — 2,194 of the OpenShift vault's
365
+ // 7,926 admonitions (all its tips/warnings/importants) mislabeled.
366
+ const variant = (node.props?.variant ?? node.props?.type) ?? "note";
184
367
  const title = node.props?.title;
185
368
  let opener = `> [!${variant}]`;
186
369
  const autoTitle = variant.charAt(0).toUpperCase() + variant.slice(1);
@@ -194,7 +377,8 @@ function calloutToObsidian(node) {
194
377
  return `${opener}\n${prefixLines(inner, "> ")}`;
195
378
  }
196
379
  function detailsToObsidian(node) {
197
- const variant = node.props?.variant ?? "note";
380
+ // Shape-tolerant variant read — see calloutToObsidian.
381
+ const variant = (node.props?.variant ?? node.props?.type) ?? "note";
198
382
  const title = node.props?.title;
199
383
  const open = node.props?.open;
200
384
  const foldMarker = open ? "+" : "-";
@@ -236,7 +420,13 @@ function tabsToObsidian(node) {
236
420
  codeBlockNestingDepth++;
237
421
  const inner = node.children
238
422
  .map((tab) => {
239
- const title = tab.props?.title ?? "Tab";
423
+ // The parser labels a tab with `label`; older/other shapes use `title` or
424
+ // `value`. Mirror format-astro's tolerant cascade — reading only `title`
425
+ // (the old obsidian behaviour) makes every tab render as the literal "Tab".
426
+ const title = tab.props?.title ||
427
+ tab.props?.label ||
428
+ tab.props?.value ||
429
+ "Tab";
240
430
  const content = tabContentToObsidian(tab);
241
431
  if (!content)
242
432
  return `tab: ${title}\n---`;
@@ -252,8 +442,12 @@ function tabContentToObsidian(node) {
252
442
  }
253
443
  // ── Code blocks ─────────────────────────────────────────
254
444
  function codeToObsidian(node) {
255
- const lang = node.props?.lang ?? "";
256
- const code = (node.props?.code ?? "").replace(/\n$/, "");
445
+ // The parser emits `props.language` with the code text in `node.html`;
446
+ // importers use `props.lang`/`props.code`. Read BOTH (as format-astro does)
447
+ // — reading only `lang`/`code` produced an EMPTY, language-less fence for
448
+ // every code block parsed from real dogsbay-md.
449
+ const lang = node.props?.lang || node.props?.language || "";
450
+ const code = (node.props?.code ?? node.html ?? "").replace(/\n$/, "");
257
451
  const title = node.props?.title;
258
452
  const highlights = node.props?.highlights;
259
453
  const annotations = node.props?.annotations;
@@ -366,11 +560,17 @@ function orderedListToObsidian(node) {
366
560
  .map((child, i) => {
367
561
  const num = start + i;
368
562
  const text = nodeToObsidian(child);
369
- const first = `${num}. ${text.split("\n")[0]}`;
563
+ // Continuation indent must reach the item's CONTENT column, which is
564
+ // the marker's own width: `10. ` is 4 wide, `100. ` is 5. A fixed
565
+ // 3-space indent detached every table/callout attached to item 10+
566
+ // (CommonMark: one column short of the content column ends the item).
567
+ const marker = `${num}. `;
568
+ const pad = " ".repeat(marker.length);
569
+ const first = `${marker}${text.split("\n")[0]}`;
370
570
  const rest = text.split("\n").slice(1);
371
571
  if (rest.length === 0)
372
572
  return first;
373
- return `${first}\n${rest.map((l) => (l ? ` ${l}` : l)).join("\n")}`;
573
+ return `${first}\n${rest.map((l) => (l ? `${pad}${l}` : l)).join("\n")}`;
374
574
  })
375
575
  .join("\n");
376
576
  }
@@ -389,18 +589,77 @@ function unorderedListToObsidian(node) {
389
589
  .join("\n");
390
590
  }
391
591
  function listItemToObsidian(node) {
392
- if (!node.children)
393
- return "";
394
- const parts = node.children.map(nodeToObsidian).filter(Boolean);
395
- // Join with blank line between items to ensure Obsidian treats
396
- // consecutive blockquote-style elements (callouts, details) as separate
397
- return parts.join("\n\n");
592
+ // A list item's text is in `inline` (flat parser shape); nested blocks are
593
+ // in `children`. Reading only children returned "" for every plain bullet.
594
+ const parts = [];
595
+ if (node.inline && node.inline.length > 0)
596
+ parts.push(inlineToObsidian(node.inline));
597
+ if (node.children)
598
+ parts.push(...node.children.map(nodeToObsidian).filter(Boolean));
599
+ // Blank line between blocks so Obsidian treats consecutive blockquote-style
600
+ // elements (callouts, details) as separate.
601
+ return parts.filter(Boolean).join("\n\n");
398
602
  }
399
603
  // ── Definition lists (degraded) ─────────────────────────
604
+ /**
605
+ * Definition list → a `dogsbay-deflist` fence the vault plugin renders as a
606
+ * real `<dl>`.
607
+ *
608
+ * Obsidian has NO definition-list syntax. The previous emission used the
609
+ * common `**term**` / `: definition` convention, which Obsidian renders as
610
+ * literal text with a stray colon — 821 of 2,106 notes (28,946 lines) in a
611
+ * real OpenShift vault. And because the `dd` case flattened its body with
612
+ * `leafContent`, a definition carrying a TABLE was emitted as `: ` followed by
613
+ * pipe rows at column 0, so the table could not parse either.
614
+ *
615
+ * Definition bodies are serialized as full BLOCK markdown, so a table, list or
616
+ * code block inside a `dd` survives; the plugin renders each body through
617
+ * Obsidian's own markdown renderer.
618
+ */
400
619
  function deflistToObsidian(node) {
401
- if (!node.children)
620
+ if (!node.children?.length)
402
621
  return "";
403
- return node.children.map(nodeToObsidian).join("\n");
622
+ const entries = [];
623
+ let current = null;
624
+ // A definition body may itself contain a fenced code block, so the wrapper
625
+ // alternates fence characters by nesting depth (same rule as steps/tabs).
626
+ const fence = codeBlockNestingDepth % 2 === 0 ? "~~~" : "```";
627
+ codeBlockNestingDepth++;
628
+ for (const child of node.children) {
629
+ if (child.type === "dt") {
630
+ if (current)
631
+ entries.push(current);
632
+ current = { term: leafContent(child).trim(), definitions: [] };
633
+ continue;
634
+ }
635
+ if (child.type === "dd") {
636
+ // Block children first — `leafContent` is the fallback for the flat
637
+ // `inline` shape the dogsbay-md parser produces.
638
+ const body = (childrenToObsidian(child) || leafContent(child)).trim();
639
+ if (!current)
640
+ current = { term: "", definitions: [] };
641
+ if (body)
642
+ current.definitions.push(body);
643
+ continue;
644
+ }
645
+ // Anything else inside a deflist keeps its content rather than vanishing.
646
+ const other = nodeToObsidian(child).trim();
647
+ if (!other)
648
+ continue;
649
+ if (!current)
650
+ current = { term: "", definitions: [] };
651
+ current.definitions.push(other);
652
+ }
653
+ if (current)
654
+ entries.push(current);
655
+ codeBlockNestingDepth--;
656
+ const body = entries
657
+ .map((e) => {
658
+ const defs = e.definitions.join("\n\n---\n").trim();
659
+ return defs ? `term: ${e.term}\n---\n${defs}` : `term: ${e.term}\n---`;
660
+ })
661
+ .join("\n\n");
662
+ return `${fence}dogsbay-deflist\n${body}\n${fence}`;
404
663
  }
405
664
  // ── Steps (numbered list) ───────────────────────────────
406
665
  function stepsToObsidian(node) {
@@ -411,7 +670,14 @@ function stepsToObsidian(node) {
411
670
  // Use dogsbay-steps element for richer rendering
412
671
  const inner = node.children
413
672
  .map((child) => {
414
- const title = child.props?.title || "";
673
+ // A `step` node carries its TITLE as its own inline content (the parser's
674
+ // ordered-list recovery), with the body in `children` — the same shape
675
+ // format-astro renders via leafContent. Reading `props.title` (the old
676
+ // behaviour) dropped every step title. `props.title` remains a fallback
677
+ // for shapes that carry it there.
678
+ const title = (child.inline && child.inline.length ? inlineToObsidian(child.inline) : "") ||
679
+ child.props?.title ||
680
+ "";
415
681
  const content = childrenToObsidian(child);
416
682
  if (title) {
417
683
  return content ? `step: ${title}\n---\n${content}` : `step: ${title}\n---`;
@@ -428,7 +694,8 @@ function headingToObsidian(node) {
428
694
  const level = node.props?.level ?? 1;
429
695
  const slug = node.props?.slug ?? "";
430
696
  const hashes = "#".repeat(level);
431
- const blockId = slug ? ` ^${slug}` : "";
697
+ const id = uniqueBlockId(obsidianBlockId(slug));
698
+ const blockId = id ? ` ^${id}` : "";
432
699
  if (node.inline)
433
700
  return `${hashes} ${inlineToObsidian(node.inline)}${blockId}`;
434
701
  const text = childrenToObsidian(node) || (node.props?.text ?? "");
@@ -450,10 +717,33 @@ function referencesToObsidian(node) {
450
717
  .join("\n");
451
718
  }
452
719
  function youtubeToObsidian(node) {
453
- const id = node.props?.videoId ?? "";
720
+ // The parser emits `props.id`; importers may use `props.videoId`. Read BOTH
721
+ // (as format-astro reads `props.id`) — reading only `videoId` produced a
722
+ // broken embed URL (`.../vi//maxres...`, `watch?v=`) for every parsed video.
723
+ const id = node.props?.id || node.props?.videoId || "";
454
724
  const title = node.props?.title ?? "Video";
455
725
  return `[![${title}](https://img.youtube.com/vi/${id}/maxresdefault.jpg)](https://www.youtube.com/watch?v=${id})`;
456
726
  }
727
+ /**
728
+ * The icon value if a vault can show it, otherwise undefined.
729
+ *
730
+ * Renderable: an image path (the plugin builds an <img>), or an emoji — any
731
+ * non-ASCII glyph, which the plugin prints as text and which reads correctly.
732
+ * Not renderable: an ASCII slug naming an icon in a registry the vault does
733
+ * not have.
734
+ */
735
+ function renderableVaultIcon(icon) {
736
+ if (/\.(svg|png|jpe?g|webp|avif)$/i.test(icon))
737
+ return vaultAssetPath(icon);
738
+ // eslint-disable-next-line no-control-regex
739
+ return /^[\x00-\x7F]+$/.test(icon) ? undefined : icon;
740
+ }
741
+ /** Give an internal card target the `.md` its exact-path lookup needs. */
742
+ function cardHref(href) {
743
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#"))
744
+ return href;
745
+ return /\.[a-z0-9]+$/i.test(href) ? href : `${href}.md`;
746
+ }
457
747
  function cardToObsidian(node) {
458
748
  const title = node.props?.title || "";
459
749
  const href = node.props?.href;
@@ -462,10 +752,30 @@ function cardToObsidian(node) {
462
752
  const header = [];
463
753
  if (title)
464
754
  header.push(`title: ${title}`);
755
+ // `.md` REQUIRED here, unlike an ordinary markdown link.
756
+ //
757
+ // A `[text](path)` link is resolved by Obsidian's own linkpath lookup, which
758
+ // is forgiving about the extension. This href is consumed by the dogsbay-docs
759
+ // plugin, which resolves it with `vault.getFileByPath()` — an EXACT match.
760
+ // Extensionless, that returns null and the click does nothing at all: the
761
+ // cards rendered correctly and were simply inert, with no error anywhere.
465
762
  if (href)
466
- header.push(`href: ${obsidianHref(href)}`);
467
- if (icon)
468
- header.push(`icon: ${icon}`);
763
+ header.push(`href: ${cardHref(obsidianHref(href))}`);
764
+ // Only an icon the VAULT can render.
765
+ //
766
+ // The plugin draws an image when the icon is a file path and prints the
767
+ // value as text otherwise — which is right for an emoji and wrong for a
768
+ // registry NAME. Starlight names like `open-book`, `discord` and `x.com`
769
+ // have no file behind them and no registry in a vault, so they rendered as
770
+ // the literal word "discord" stacked one letter per line down the card's
771
+ // icon column.
772
+ //
773
+ // A name we cannot resolve is dropped rather than emitted: the card simply
774
+ // has no icon, which is what it would look like anyway if the reference
775
+ // worked and pointed at nothing.
776
+ const vaultIcon = icon ? renderableVaultIcon(icon) : undefined;
777
+ if (vaultIcon)
778
+ header.push(`icon: ${vaultIcon}`);
469
779
  if (header.length === 0 && !content)
470
780
  return "";
471
781
  const meta = header.join("\n");
@@ -487,7 +797,12 @@ function apiSymbolToObsidian(node) {
487
797
  const level = node.type === "api-class" ? 3 : 4;
488
798
  const hashes = "#".repeat(level);
489
799
  const sig = node.props?.signature ?? "";
490
- const bases = node.props?.bases;
800
+ // The parser emits `bases` as a string; the RST/autodoc importer (and
801
+ // format-astro's read) may use a string[]. Tolerate both.
802
+ const basesRaw = node.props?.bases;
803
+ const bases = Array.isArray(basesRaw)
804
+ ? basesRaw.join(", ")
805
+ : basesRaw;
491
806
  const parts = [];
492
807
  parts.push(`${hashes} ${kind} \`${name}\``);
493
808
  if (bases)
@@ -542,7 +857,7 @@ function apiDocToObsidian(node) {
542
857
  // api-doc has HTML content in props.html — convert to markdown
543
858
  const html = node.props?.html ?? "";
544
859
  if (html)
545
- return stripHtml(html);
860
+ return htmlToObsidian(html);
546
861
  return childrenToObsidian(node);
547
862
  }
548
863
  function apiSourceToObsidian(node) {
@@ -557,6 +872,15 @@ function apiSourceToObsidian(node) {
557
872
  if (code) {
558
873
  parts.push(`\`\`\`python\n${code.replace(/\n$/, "")}\n\`\`\``);
559
874
  }
875
+ else if (node.children && node.children.length > 0) {
876
+ // The dogsbay-md parser puts the fenced source into a child `code` node
877
+ // (props.language + node.html), not props.code — reading only props.code
878
+ // dropped the source block. Serialize children as a fallback; the
879
+ // props.code path stays for importers that carry it there.
880
+ const inner = childrenToObsidian(node);
881
+ if (inner)
882
+ parts.push(inner);
883
+ }
560
884
  return parts.join("\n\n");
561
885
  }
562
886
  // ── Footnotes ───────────────────────────────────────────
@@ -567,7 +891,12 @@ function footnoteListToObsidian(node) {
567
891
  }
568
892
  function footnoteDefToObsidian(node) {
569
893
  const label = node.props?.label ?? "1";
570
- const content = childrenToObsidian(node);
894
+ // The dogsbay-md parser puts the definition body on `inline` (flat
895
+ // shape); reading only `children` dropped every footnote body — the
896
+ // three-TreeNode-shapes lesson documented at leafContent below.
897
+ const content = node.inline && node.inline.length > 0
898
+ ? inlineToObsidian(node.inline)
899
+ : childrenToObsidian(node);
571
900
  return `[^${label}]: ${content}`;
572
901
  }
573
902
  // ── Utilities ───────────────────────────────────────────
@@ -576,50 +905,54 @@ function childrenToObsidian(node) {
576
905
  return "";
577
906
  return node.children.map(nodeToObsidian).filter(Boolean).join("\n\n");
578
907
  }
579
- function prefixLines(text, prefix) {
580
- return text
581
- .split("\n")
582
- .map((line) => (line ? `${prefix}${line}` : prefix.trimEnd()))
583
- .join("\n");
584
- }
585
- function indent(text, spaces) {
586
- const prefix = " ".repeat(spaces);
587
- return text
588
- .split("\n")
589
- .map((line) => (line ? `${prefix}${line}` : line))
590
- .join("\n");
591
- }
592
908
  /**
593
- * Choose a fence string (```) that doesn't conflict with content.
594
- * Scans for the longest run of backticks in the content and uses one more.
909
+ * Text-bearing content across all THREE TreeNode shapes.
910
+ *
911
+ * Was a local re-derivation handling only two of them (flat `inline` and
912
+ * `children`). It now goes through the core's `renderLeaf`, which adds the
913
+ * third — a node carrying only `html`, or a single wrapped `prose` child
914
+ * carrying `html` with no `inline` (what the MDX/Starlight/MkDocs importers
915
+ * emit). Reading only the first two rendered those nodes EMPTY; that is the
916
+ * bug that shipped in the Docusaurus exporter's first version and dropped
917
+ * every paragraph body on a real Mintlify conversion.
918
+ *
919
+ * The `join` is "\n\n" to preserve this serializer's paragraph spacing (the
920
+ * core defaults to "\n").
595
921
  */
596
- function chooseFence(content) {
597
- let max = 2;
598
- const matches = content.match(/`{3,}/g);
599
- if (matches) {
600
- for (const m of matches) {
601
- if (m.length > max)
602
- max = m.length;
603
- }
604
- }
605
- return "`".repeat(max + 1);
922
+ function leafContent(node) {
923
+ return renderLeaf(node, {
924
+ inline: inlineToObsidian,
925
+ children: (children) => children.map(nodeToObsidian).filter(Boolean).join("\n\n"),
926
+ html: htmlToObsidian,
927
+ join: "\n\n",
928
+ });
606
929
  }
607
930
  /**
608
- * Strip HTML tags, preserving text content.
609
- * Handles common inline HTML from prose nodes.
931
+ * Render pre-rendered prose HTML as Obsidian markdown.
932
+ *
933
+ * `stripHtml` alone DELETES tags, so every `<code>`, `<strong>`, `<em>` and
934
+ * `<a>` an importer hands us became plain text. That is invisible for sources
935
+ * whose prose nodes also carry `inline` (mkdocs), and catastrophic for those
936
+ * that carry ONLY html — the MDX/Mintlify shape. Measured on a full Mintlify
937
+ * export before this fix: 38,994 inline code spans in the source became 6,864
938
+ * in the vault, and 14,548 bold runs became 3,465. Roughly 80% of inline
939
+ * formatting, silently gone, on the export we point at as the back-out.
940
+ *
941
+ * `inlineHtmlToMarkdown` converts the unambiguous inline tags to real markdown
942
+ * first; `stripHtml` then removes whatever markup is left and decodes entities.
610
943
  */
611
- function stripHtml(html) {
612
- return html
613
- .replace(/<br\s*\/?>/gi, "\n")
614
- .replace(/<\/p>\s*<p[^>]*>/gi, "\n\n")
615
- .replace(/<\/?(?:p|div|span|strong|em|s|a|code|sup|sub|mark|kbd|abbr)[^>]*>/gi, "")
616
- .replace(/<img[^>]+alt="([^"]*)"[^>]*>/gi, "![$1]")
617
- .replace(/<[^>]+>/g, "")
618
- .replace(/&amp;/g, "&")
619
- .replace(/&lt;/g, "<")
620
- .replace(/&gt;/g, ">")
621
- .replace(/&quot;/g, '"')
622
- .replace(/&#39;/g, "'")
623
- .trim();
944
+ function htmlToObsidian(html) {
945
+ // Applied HERE because this is the shared path for prose, html-container and
946
+ // inline HTML. Raw `<img src="/_assets/…">` most often arrives inline inside
947
+ // a paragraph, not as a standalone `html` node — 39 vault images stayed
948
+ // site-rooted when only the block case was covered.
949
+ // BEFORE the html→markdown conversion: `inlineHtmlToMarkdown` turns
950
+ // `<img src>` into `![alt](src)`, after which there is no `src=` attribute
951
+ // left to rewrite.
952
+ return stripHtml(inlineHtmlToMarkdown(vaultifyHtmlAssets(html)));
953
+ }
954
+ /** Obsidian's code fence, via the core's shared longest-run picker. */
955
+ function chooseFence(content) {
956
+ return pickCodeFence(content);
624
957
  }
625
958
  //# sourceMappingURL=serialize.js.map