@dogsbay/format-obsidian 0.2.0-beta.18 → 0.2.0-beta.180

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/project.js CHANGED
@@ -1,4 +1,18 @@
1
1
  import { treeToObsidian } from "./serialize.js";
2
+ /**
3
+ * Path of a section's folder note.
4
+ *
5
+ * Named `_<folder>.md`, not `_index.md`: Obsidian labels graph nodes and tabs
6
+ * by FILENAME, so a vault of 309 sections showed 309 identical `_index` nodes.
7
+ * The leading underscore keeps the note sorted to the top of its folder and
8
+ * distinguishes it from a content page that shares the folder's name — 20
9
+ * sections in the OpenShift corpus contain `<folder>/<folder>.md`, so the bare
10
+ * folder name would collide. No page in that corpus starts with `_`.
11
+ */
12
+ export function sectionNotePath(folderPath) {
13
+ const leaf = folderPath.slice(folderPath.lastIndexOf("/") + 1);
14
+ return `${folderPath}/_${leaf}.md`;
15
+ }
2
16
  /**
3
17
  * Export pages + nav to an Obsidian vault file map.
4
18
  */
@@ -16,23 +30,67 @@ export function exportObsidianVault(pages, nav, options = {}) {
16
30
  const pathPrefix = section || "";
17
31
  assignPaths(nav, pathPrefix, assignments, pageBySlug);
18
32
  // Generate pages
33
+ //
34
+ // A page the nav does not place used to be flattened to its BASENAME at the
35
+ // vault root, so any two pages sharing one — `agent/customize` and
36
+ // `assistant/customize`, or the es/fr/zh translations of the same page —
37
+ // wrote to the same path and the later one silently overwrote the earlier.
38
+ // Measured on a real Mintlify export: 988 pages produced 881 files, i.e. 107
39
+ // pages vanished with no error. An unplaced page now keeps its SLUG PATH,
40
+ // which mirrors the source tree and cannot collide unless the source did.
41
+ const taken = new Map();
42
+ const actualVaultPath = new Map();
43
+ const collisions = [];
19
44
  for (const page of pages) {
45
+ // A fragment is an include TARGET, not a note. `convert` realizes includes
46
+ // for this exporter, so the fragment's content is already spliced into
47
+ // every note that used it — emitting it again produced a duplicate,
48
+ // usually-untitled note sitting beside the real ones. (format-dogsbay-md
49
+ // does emit them, correctly: there the `{% include %}` is preserved, so the
50
+ // target file has to exist.)
51
+ if (page.fragment || page.frontmatter?._fragment === true)
52
+ continue;
20
53
  const assignment = assignments.get(page.slug);
21
54
  const fallbackFolder = section || "";
22
- const filePath = assignment
23
- ? `${assignment.folderPath}/${fileNameFromSlug(page.slug)}.md`
24
- : fallbackFolder
25
- ? `${fallbackFolder}/${fileNameFromSlug(page.slug)}.md`
26
- : `${fileNameFromSlug(page.slug)}.md`;
55
+ const unplaced = slugToVaultRelPath(page.slug);
56
+ // `folderPath` is "" for a root-level nav entry, so joining unconditionally
57
+ // produced a LEADING SLASH (`/index.md`). The write path tolerated it; the
58
+ // nav/link map re-derived its own path and silently did not. Now that both
59
+ // read one value, the join has to be correct.
60
+ let filePath = assignment
61
+ ? joinVaultPath(assignment.folderPath, `${fileNameFromSlug(page.slug)}.md`)
62
+ : joinVaultPath(fallbackFolder, `${unplaced}.md`);
63
+ // Even with slug paths, a nav placement can still collide (two nav entries
64
+ // pointing at the same folder + basename). Never overwrite silently:
65
+ // disambiguate with the slug and record it for the caller to report.
66
+ // Keyed CASE-INSENSITIVELY. macOS and Windows filesystems are, so
67
+ // `API/Overview` and `api/overview` are two keys in a case-sensitive Map,
68
+ // no collision is recorded, both are written — and the second silently
69
+ // overwrites the first. The vault is a page short, `_nav.yml` points both
70
+ // entries at the survivor, and the warning that exists to surface exactly
71
+ // this never fires.
72
+ const key = filePath.toLowerCase();
73
+ if (taken.has(key)) {
74
+ const alt = `${filePath.slice(0, -3)}--${page.slug.replace(/\//g, "-")}.md`;
75
+ collisions.push({ path: filePath, kept: taken.get(key), renamed: page.slug });
76
+ filePath = alt;
77
+ }
78
+ taken.set(filePath.toLowerCase(), page.slug);
79
+ // The single source of truth for "where did this page end up". The nav and
80
+ // link-rewrite maps below MUST read this rather than re-deriving the path:
81
+ // when they re-derived it they used the basename, so an unplaced nested
82
+ // page's links pointed at a file that no longer exists, and a collision
83
+ // rename left the renamed file unreachable from nav.
84
+ actualVaultPath.set(page.slug, filePath.replace(/\.md$/, ""));
27
85
  let content = treeToObsidian(page.tree);
28
86
  // Prepend frontmatter — always include title + alias, add sidebar_position if from nav
29
87
  if (assignment) {
30
- const fm = buildFrontmatter(page.title, assignment.position);
88
+ const fm = buildFrontmatter(page.title, assignment.position, assignment.categories);
31
89
  if (content.startsWith("---\n")) {
32
90
  const endIdx = content.indexOf("\n---\n", 4);
33
91
  if (endIdx !== -1) {
34
92
  const existingFm = content.substring(4, endIdx);
35
- content = `---\n${existingFm}\naliases:\n - ${yamlStr(page.title)}\nsidebar_position: ${assignment.position}\n---\n${content.substring(endIdx + 5)}`;
93
+ content = `---\n${existingFm}\naliases:\n - ${yamlStr(page.title)}\nsidebar_position: ${assignment.position}${categoryBlock(assignment.categories)}\n---\n${content.substring(endIdx + 5)}`;
36
94
  }
37
95
  }
38
96
  else {
@@ -48,8 +106,10 @@ export function exportObsidianVault(pages, nav, options = {}) {
48
106
  }
49
107
  files.set(filePath, content);
50
108
  }
51
- // Generate _index.md for nav sections (folders)
52
- generateSectionIndexes(nav, pathPrefix, files);
109
+ // Generate a folder note per nav section
110
+ if (options.sectionIndexes !== false) {
111
+ generateSectionIndexes(nav, pathPrefix, files, pageBySlug);
112
+ }
53
113
  // Build slug → vault path lookup (without .md extension) for nav yaml and link rewriting
54
114
  const slugToVaultPath = new Map();
55
115
  // Also build link rewrite map: keys are paths as they appear in content links
@@ -57,19 +117,10 @@ export function exportObsidianVault(pages, nav, options = {}) {
57
117
  const linkRewrites = new Map();
58
118
  for (const page of pages) {
59
119
  const assignment = assignments.get(page.slug);
60
- const fallbackFolder = section || "";
61
- const fileName = fileNameFromSlug(page.slug);
62
- let vaultPath;
63
- if (assignment) {
64
- vaultPath = assignment.folderPath
65
- ? `${assignment.folderPath}/${fileName}`
66
- : fileName;
67
- }
68
- else {
69
- vaultPath = fallbackFolder
70
- ? `${fallbackFolder}/${fileName}`
71
- : fileName;
72
- }
120
+ // Where the page ACTUALLY went, recorded when it was written.
121
+ const vaultPath = actualVaultPath.get(page.slug);
122
+ if (!vaultPath)
123
+ continue;
73
124
  slugToVaultPath.set(page.slug, vaultPath);
74
125
  // Links in content use section-prefixed paths (e.g. "ddos-protection/managed-rulesets")
75
126
  // The vault file path may differ (e.g. "ddos-protection/managed-rulesets/managed-rulesets")
@@ -77,6 +128,18 @@ export function exportObsidianVault(pages, nav, options = {}) {
77
128
  if (linkPath !== vaultPath) {
78
129
  linkRewrites.set(linkPath, vaultPath);
79
130
  }
131
+ // The importer strips `/index` from a directory-landing slug
132
+ // (`rest_api/objects/index.md` → slug `rest_api/objects`), but
133
+ // engine-emitted content links spell the FULL source path
134
+ // (`rest_api/objects/index#anchor`). Register the index spelling too —
135
+ // without it every schema cross-reference on every API page dangled
136
+ // (issue #041: 2,320 stale links in 267 files). NOT unconditional:
137
+ // format-vitepress keeps `/index` in slugs, so `foo` and `foo/index`
138
+ // can be DISTINCT pages — the alias must never capture links meant
139
+ // for the real `/index` page.
140
+ if (!pageBySlug.has(`${page.slug}/index`)) {
141
+ linkRewrites.set(`${linkPath}/index`, vaultPath);
142
+ }
80
143
  }
81
144
  // Rewrite internal links: source paths → vault file paths
82
145
  if (linkRewrites.size > 0) {
@@ -94,11 +157,263 @@ export function exportObsidianVault(pages, nav, options = {}) {
94
157
  }
95
158
  }
96
159
  }
160
+ // Rescue links that spell the ORIGINAL repo path (#051). An xref can
161
+ // name a DIFFERENT assembly of the same module than the one nav placed
162
+ // (`edge_computing/…/update-completing-the-control-plane-only-update`
163
+ // when the page lives under postinstallation-configuration/…) — the
164
+ // rewrite map above only knows nav-placed slugs. When the dangling
165
+ // path's BASENAME names exactly one vault page, that page is the
166
+ // target; ambiguous basenames stay dangling rather than guessing.
167
+ // Vault pages by BASENAME, for the two rescue passes below (links, then
168
+ // card/button hrefs).
169
+ const byBasename = new Map();
170
+ {
171
+ for (const f of files.keys()) {
172
+ if (!f.endsWith(".md") || f === sectionNotePath(f.slice(0, f.lastIndexOf("/"))))
173
+ continue;
174
+ const base = f.slice(f.lastIndexOf("/") + 1, -3);
175
+ const list = byBasename.get(base) ?? [];
176
+ list.push(f.slice(0, -3));
177
+ byBasename.set(base, list);
178
+ }
179
+ let rescued = 0;
180
+ // Anchored to LINK POSITION (`](…)`) — without the `](` prefix any
181
+ // parenthesized slash-token in prose was a candidate: the OpenShift
182
+ // corpus carries 1,533 shapes like `(POST/PUT/PATCH)`, `(read/write)`
183
+ // and `(CI/CD)` that pass every other guard, and one vault page named
184
+ // `write` or `patch` would have corrupted prose at scale (review,
185
+ // HIGH). Fence-masked for the same reason — code samples are full of
186
+ // `call(a/b)` shapes.
187
+ const linkRx = /\]\(([^()\s#]+)(#[^)\s]*)?\)/g;
188
+ for (const [filePath, content] of files) {
189
+ if (!filePath.endsWith(".md"))
190
+ continue;
191
+ const step = makeFenceTracker();
192
+ const updated = content
193
+ .split("\n")
194
+ .map((line) => {
195
+ if (step(line) !== "prose")
196
+ return line;
197
+ return line.replace(linkRx, (whole, dest, frag = "") => {
198
+ // Only vault-internal, multi-segment, non-resolving paths.
199
+ if (!dest.includes("/") || /^[a-z][a-z0-9+.-]*:/i.test(dest))
200
+ return whole;
201
+ if (dest.startsWith("_assets/") || /\.[a-z0-9]{2,4}$/i.test(dest))
202
+ return whole;
203
+ if (files.has(`${dest}.md`) || files.has(sectionNotePath(dest)))
204
+ return whole;
205
+ const base = dest.slice(dest.lastIndexOf("/") + 1);
206
+ const candidates = byBasename.get(base);
207
+ if (!candidates || candidates.length !== 1)
208
+ return whole;
209
+ rescued += 1;
210
+ return `](${candidates[0]}${frag})`;
211
+ });
212
+ })
213
+ .join("\n");
214
+ if (updated !== content)
215
+ files.set(filePath, updated);
216
+ }
217
+ if (rescued > 0) {
218
+ console.warn(`obsidian export: rescued ${rescued} link(s) spelling original repo paths (unique-basename match)`);
219
+ }
220
+ }
221
+ // Resolve `#^block` fragments against the TARGET file's actual block
222
+ // ids (#049). Cross-page xrefs name the SOURCE id, but the vault stamps
223
+ // anchors with the AsciiDoc `id_{context}` expansion — three mismatch
224
+ // shapes, all mechanical:
225
+ // 1. link bare, anchor suffixed → unique prefix match rewrites
226
+ // 2. link over-suffixed, anchor bare → unique longest-prefix strip
227
+ // 3. page-top id the vault never stamped → land on the H1's block id
228
+ // (the source intent was "this page"), or drop the fragment when
229
+ // the H1 carries none.
230
+ // The file half of these links already resolves — only the scroll
231
+ // position was lost. Obsidian resolves fragments literally, so a
232
+ // fragment the target cannot resolve is worthless to the reader.
233
+ {
234
+ const anchorIndex = new Map();
235
+ const indexFor = (file) => {
236
+ let entry = anchorIndex.get(file);
237
+ if (!entry) {
238
+ const content = files.get(file) ?? "";
239
+ const ids = new Set();
240
+ let h1 = null;
241
+ // Fence-aware: Obsidian does not create block ids inside code
242
+ // fences, so a code line ending ` ^word` (terminal transcripts,
243
+ // regex samples) must not become a phantom anchor that steals a
244
+ // prefix match from the real one (review).
245
+ const step = makeFenceTracker();
246
+ for (const line of content.split("\n")) {
247
+ if (step(line) !== "prose")
248
+ continue;
249
+ const m = line.match(/\s\^([A-Za-z0-9-]+)\s*$/);
250
+ if (!m)
251
+ continue;
252
+ ids.add(m[1]);
253
+ if (h1 === null && /^#\s/.test(line))
254
+ h1 = m[1];
255
+ }
256
+ entry = { ids, h1 };
257
+ anchorIndex.set(file, entry);
258
+ }
259
+ return entry;
260
+ };
261
+ let anchorRewrites = 0;
262
+ let anchorDrops = 0;
263
+ const blockLinkRx = /\(([^()\s#]*)#\^([A-Za-z0-9-]+)\)/g;
264
+ for (const [filePath, content] of files) {
265
+ if (!filePath.endsWith(".md"))
266
+ continue;
267
+ const updated = content.replace(blockLinkRx, (whole, dest, frag) => {
268
+ // An empty dest is a SAME-PAGE link — resolve against this file
269
+ // (cnf-talm's troubleshooting list carried 5 in-page fragments
270
+ // no anchor matched).
271
+ const targetFile = dest === ""
272
+ ? filePath
273
+ : files.has(`${dest}.md`)
274
+ ? `${dest}.md`
275
+ : files.has(sectionNotePath(dest))
276
+ ? sectionNotePath(dest)
277
+ : null;
278
+ // Unresolvable FILE half is a different defect (#051) — leave it
279
+ // visible rather than masking it here.
280
+ if (!targetFile)
281
+ return whole;
282
+ const { ids, h1 } = indexFor(targetFile);
283
+ if (ids.has(frag))
284
+ return whole;
285
+ // 1. Bare source id vs suffixed anchor: unambiguous when the
286
+ // bare id prefixes exactly one anchor. TWO OR MORE candidate
287
+ // section anchors are positive evidence the link targeted a
288
+ // SECTION — declining beats the H1 fallback, which would
289
+ // destroy that evidence and make the link look "valid" to any
290
+ // later checker (review; same doctrine as #051's
291
+ // ambiguous-stays-dangling).
292
+ const prefixed = [...ids].filter((a) => a.startsWith(`${frag}-`));
293
+ if (prefixed.length === 1) {
294
+ anchorRewrites += 1;
295
+ return `(${dest}#^${prefixed[0]})`;
296
+ }
297
+ if (prefixed.length > 1)
298
+ return whole;
299
+ // 2. Over-suffixed link vs bare anchor: longest anchor the
300
+ // fragment extends, unique at that length; a tie declines for
301
+ // the same reason.
302
+ const stripped = [...ids]
303
+ .filter((a) => frag.startsWith(`${a}-`))
304
+ .sort((a, b) => b.length - a.length);
305
+ if (stripped.length > 0) {
306
+ if (stripped.filter((a) => a.length === stripped[0].length).length > 1) {
307
+ return whole;
308
+ }
309
+ anchorRewrites += 1;
310
+ return `(${dest}#^${stripped[0]})`;
311
+ }
312
+ // A target with NO block ids gives no evidence about its anchor
313
+ // scheme — leave the link alone rather than guessing (unit
314
+ // fixtures and hand-authored pages hit this).
315
+ if (ids.size === 0)
316
+ return whole;
317
+ // 3. Page-top reference the vault cannot name: the H1's block id
318
+ // preserves "scroll to the top of that page"; no H1 id → plain
319
+ // page link.
320
+ if (h1) {
321
+ anchorRewrites += 1;
322
+ return `(${dest}#^${h1})`;
323
+ }
324
+ anchorDrops += 1;
325
+ return `(${dest})`;
326
+ });
327
+ if (updated !== content)
328
+ files.set(filePath, updated);
329
+ }
330
+ if (anchorRewrites + anchorDrops > 0) {
331
+ console.warn(`obsidian export: resolved ${anchorRewrites} cross-page anchor fragment(s) to real block ids` +
332
+ (anchorDrops > 0 ? `, dropped ${anchorDrops} unresolvable` : ""));
333
+ }
334
+ }
335
+ // Point every card at a file that EXISTS.
336
+ //
337
+ // A `dogsbay-card` href is resolved by the plugin with
338
+ // `vault.getFileByPath()` — an exact match — so unlike a markdown link it
339
+ // cannot be extensionless, and unlike a markdown link nothing about it
340
+ // degrades visibly when it is wrong: the card renders perfectly and the
341
+ // click silently does nothing.
342
+ //
343
+ // A card that targets a SECTION is the case the serializer cannot get right
344
+ // on its own: `ai-search/get-started` is a folder here, and the note is at
345
+ // `ai-search/get-started/_index.md`. Only this layer knows that, because
346
+ // only this layer decided it.
347
+ for (const [filePath, content] of files) {
348
+ if (!filePath.endsWith(".md"))
349
+ continue;
350
+ const updated = content.replace(/^href: (.+)$/gm, (line, raw) => {
351
+ const href = raw.trim();
352
+ if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#"))
353
+ return line;
354
+ if (files.has(href))
355
+ return line;
356
+ const bare = href.replace(/\.md$/, "");
357
+ for (const candidate of [`${bare}.md`, sectionNotePath(bare)]) {
358
+ if (files.has(candidate))
359
+ return `href: ${candidate}`;
360
+ }
361
+ // Same rescue as a markdown link: a Starlight `<LinkButton
362
+ // href="/getting-started/">` names the page by its route while the
363
+ // vault filed it under its nav section (`start-here/`). A unique
364
+ // basename is the page; an ambiguous one stays as written.
365
+ const base = bare.slice(bare.lastIndexOf("/") + 1);
366
+ const candidates = byBasename.get(base);
367
+ if (candidates?.length === 1)
368
+ return `href: ${candidates[0]}.md`;
369
+ return line;
370
+ });
371
+ if (updated !== content)
372
+ files.set(filePath, updated);
373
+ }
374
+ // A collision is content that would have been LOST — say so rather than
375
+ // leaving the operator to notice the file count is short.
376
+ if (collisions.length > 0) {
377
+ console.warn(` warning: ${collisions.length} page(s) collided on a vault path and were ` +
378
+ `written under a disambiguated name (previously they overwrote each other ` +
379
+ `silently). First: "${collisions[0].renamed}" vs "${collisions[0].kept}" ` +
380
+ `at ${collisions[0].path}.`);
381
+ }
382
+ // Fill each folder note with a listing of its children. Deferred to here
383
+ // because it needs `slugToVaultPath`, which is only complete once every page
384
+ // has been written — and the empty stubs must already exist above, since the
385
+ // link-rewriting pass keys off the folder note existing.
386
+ if (options.sectionIndexes !== false && options.sectionIndexLinks !== false) {
387
+ fillSectionIndexes(nav, pathPrefix, files, slugToVaultPath);
388
+ }
97
389
  // Generate _nav.yml with actual vault paths
98
390
  files.set("_nav.yml", navToYaml(nav, 0, slugToVaultPath));
99
391
  return { files };
100
392
  }
101
- function assignPaths(items, parentFolder, assignments, pageBySlug) {
393
+ // ── Nav → folder structure ──────────────────────────────
394
+ /**
395
+ * The category label for a nav section.
396
+ *
397
+ * Prefers the nav label — it is the authored wording. Falls back to the title
398
+ * of the section's own page when a nav entry carries no label, and finally to
399
+ * the folder slug, so a category is never blank. (Every one of the 2,105 nav
400
+ * entries in the OpenShift corpus has a label, so the fallbacks are for
401
+ * corpora whose nav is generated rather than authored.)
402
+ */
403
+ function sectionCategoryLabel(item, pageBySlug) {
404
+ if (item.label)
405
+ return item.label;
406
+ if (item.href) {
407
+ const slug = pageSlug(item.href, pageBySlug);
408
+ const page = slug ? pageBySlug.get(slug) : undefined;
409
+ if (page?.title)
410
+ return page.title;
411
+ if (slug)
412
+ return slug.slice(slug.lastIndexOf("/") + 1);
413
+ }
414
+ return "Untitled";
415
+ }
416
+ function assignPaths(items, parentFolder, assignments, pageBySlug, ancestors = []) {
102
417
  let position = 1;
103
418
  for (const item of items) {
104
419
  if (item.children && item.children.length > 0) {
@@ -108,65 +423,156 @@ function assignPaths(items, parentFolder, assignments, pageBySlug) {
108
423
  const folderName = item.href ? folderNameFromHref(item.href) : slugify(item.label);
109
424
  const folderPath = parentFolder ? `${parentFolder}/${folderName}` : folderName;
110
425
  // If section has its own page, assign it
426
+ // A section's label names the section, so a page that IS the section
427
+ // does not repeat it — its categories are the ancestors above it.
428
+ const sectionLabel = sectionCategoryLabel(item, pageBySlug);
111
429
  if (item.href) {
112
- const slug = hrefToSlug(item.href);
430
+ const slug = pageSlug(item.href, pageBySlug);
113
431
  if (slug && pageBySlug.has(slug)) {
114
- assignments.set(slug, { folderPath, position });
432
+ assignments.set(slug, { folderPath, position, categories: ancestors });
115
433
  position++;
116
434
  }
117
435
  }
118
436
  // Recurse into children
119
- assignPaths(item.children, folderPath, assignments, pageBySlug);
437
+ assignPaths(item.children, folderPath, assignments, pageBySlug, [
438
+ ...ancestors,
439
+ sectionLabel,
440
+ ]);
120
441
  position++;
121
442
  }
122
443
  else if (item.href) {
123
444
  // Leaf page
124
- const slug = hrefToSlug(item.href);
445
+ const slug = pageSlug(item.href, pageBySlug);
125
446
  if (slug && pageBySlug.has(slug)) {
126
- assignments.set(slug, { folderPath: parentFolder, position });
447
+ assignments.set(slug, { folderPath: parentFolder, position, categories: ancestors });
127
448
  }
128
449
  position++;
129
450
  }
130
451
  }
131
452
  }
132
- function generateSectionIndexes(items, parentFolder, files) {
453
+ function generateSectionIndexes(items, parentFolder, files, pageBySlug, ancestors = []) {
133
454
  for (const item of items) {
134
455
  if (item.children && item.children.length > 0) {
135
456
  const folderName = item.href ? folderNameFromHref(item.href) : slugify(item.label);
136
457
  const folderPath = parentFolder ? `${parentFolder}/${folderName}` : folderName;
137
- // Create _index.md for this section
138
- files.set(`${folderPath}/_index.md`, `---\ntitle: ${item.label}\n---\n`);
458
+ const sectionLabel = sectionCategoryLabel(item, pageBySlug);
459
+ // Create the folder note for this section. Its categories are the
460
+ // sections ABOVE it — its own label is already the title.
461
+ files.set(sectionNotePath(folderPath), `---\ntitle: ${yamlStr(sectionLabel)}${categoryBlock(ancestors)}\n---\n`);
139
462
  // Recurse
140
- generateSectionIndexes(item.children, folderPath, files);
463
+ generateSectionIndexes(item.children, folderPath, files, pageBySlug, [
464
+ ...ancestors,
465
+ sectionLabel,
466
+ ]);
467
+ }
468
+ }
469
+ }
470
+ /**
471
+ * Second pass over the nav: give each folder note a body listing its children.
472
+ *
473
+ * Links are root-relative and extension-less — the same shape `obsidianHref`
474
+ * produces for body links, so a section index resolves exactly like any other
475
+ * cross-reference in the vault.
476
+ */
477
+ function fillSectionIndexes(items, parentFolder, files, slugToVaultPath) {
478
+ for (const item of items) {
479
+ if (!item.children || item.children.length === 0)
480
+ continue;
481
+ const folderName = item.href ? folderNameFromHref(item.href) : slugify(item.label);
482
+ const folderPath = parentFolder ? `${parentFolder}/${folderName}` : folderName;
483
+ const indexPath = sectionNotePath(folderPath);
484
+ const lines = [];
485
+ for (const child of item.children) {
486
+ const target = sectionIndexTarget(child, folderPath, files, slugToVaultPath);
487
+ lines.push(target ? `- [${child.label}](${target})` : `- ${child.label}`);
488
+ }
489
+ const existing = files.get(indexPath);
490
+ if (existing !== undefined && lines.length > 0) {
491
+ files.set(indexPath, `${existing}\n${lines.join("\n")}\n`);
141
492
  }
493
+ fillSectionIndexes(item.children, folderPath, files, slugToVaultPath);
142
494
  }
143
495
  }
496
+ /**
497
+ * Where a nav child actually landed in the vault, as a root-relative
498
+ * extension-less path. Returns undefined when the child is an external link,
499
+ * a bare anchor, or a page that was never written — a label with no link beats
500
+ * a link that dangles.
501
+ */
502
+ function sectionIndexTarget(child, folderPath, files, slugToVaultPath) {
503
+ // A child that is itself a section resolves to that section's own index.
504
+ if (child.children && child.children.length > 0) {
505
+ const name = child.href ? folderNameFromHref(child.href) : slugify(child.label);
506
+ const nested = sectionNotePath(`${folderPath}/${name}`);
507
+ if (files.has(nested))
508
+ return nested.slice(0, -3);
509
+ }
510
+ if (!child.href)
511
+ return undefined;
512
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(child.href) || child.href.startsWith("mailto:"))
513
+ return undefined;
514
+ if (isAnchorOnly(child.href))
515
+ return undefined;
516
+ const vaultPath = slugToVaultPath.get(pageSlug(child.href, slugToVaultPath));
517
+ if (vaultPath && files.has(`${vaultPath}.md`))
518
+ return vaultPath;
519
+ return undefined;
520
+ }
144
521
  // ── _nav.yml generation ─────────────────────────────────
145
522
  function navToYaml(items, indent = 0, slugToVaultPath) {
146
523
  const prefix = " ".repeat(indent);
147
524
  const lines = [];
525
+ // A destination that is not a vault file (a URL, an in-page anchor) is written under `href:`,
526
+ // not `path:`: the plugin opens every `path:` with `vault.getFileByPath()`, so such a row was a
527
+ // dead click in the sidebar and a dead stop in prev/next. The plugin (dogsbay-obsidian
528
+ // feat/plugin-round-2) opens a URL in the browser, an anchor in the open note, and keeps both
529
+ // out of prev/next.
530
+ const target = (href) => {
531
+ if (isExternalHref(href))
532
+ return `href: ${yamlStr(href)}`;
533
+ // An anchor in any spelling (`#opts`, `/#opts`, `/docs#opts`) as the plugin reads it, `#opts`;
534
+ // one with no fragment (`/?tab=b`) has nowhere to go (review)
535
+ if (isAnchorOnly(href)) {
536
+ const fragment = href.includes("#") ? href.slice(href.indexOf("#") + 1) : "";
537
+ return fragment ? `href: ${yamlStr(`#${fragment}`)}` : undefined;
538
+ }
539
+ return `path: ${yamlStr(resolveNavPath(href, slugToVaultPath))}`;
540
+ };
148
541
  for (const item of items) {
149
542
  if (item.children && item.children.length > 0) {
150
543
  lines.push(`${prefix}- label: ${yamlStr(item.label)}`);
151
- if (item.href) {
152
- const path = resolveNavPath(item.href, slugToVaultPath);
153
- lines.push(`${prefix} path: ${yamlStr(path)}`);
154
- }
544
+ const to = item.href ? target(item.href) : undefined;
545
+ if (to)
546
+ lines.push(`${prefix} ${to}`);
155
547
  lines.push(`${prefix} children:`);
156
548
  lines.push(navToYaml(item.children, indent + 2, slugToVaultPath));
157
549
  }
158
550
  else if (item.href) {
159
- const path = resolveNavPath(item.href, slugToVaultPath);
551
+ const to = target(item.href);
552
+ if (!to)
553
+ continue;
160
554
  lines.push(`${prefix}- label: ${yamlStr(item.label)}`);
161
- lines.push(`${prefix} path: ${yamlStr(path)}`);
555
+ lines.push(`${prefix} ${to}`);
162
556
  }
163
557
  }
164
558
  return lines.join("\n");
165
559
  }
166
560
  /** Resolve an href to the actual vault path, falling back to hrefToPath. */
167
561
  function resolveNavPath(href, slugToVaultPath) {
562
+ // An external link is not a vault path. `hrefToPath` appended `.md` to it,
563
+ // so a nav entry pointing at https://learn.mintlify.com became
564
+ // "https://learn.mintlify.com.md" — a dangling path in every generated
565
+ // _nav.yml that has an external destination.
566
+ if (isExternalHref(href))
567
+ return href;
568
+ // An in-page anchor is not a vault path either — appending `.md` produced a
569
+ // `#options.md` nav row pointing at a file that is never written, and if the
570
+ // row had children it created a folder named `#options/`, which Obsidian
571
+ // cannot address at all (`#` is reserved in note names).
572
+ if (isAnchorOnly(href))
573
+ return href;
168
574
  if (slugToVaultPath) {
169
- const slug = hrefToSlug(href);
575
+ const slug = pageSlug(href, slugToVaultPath);
170
576
  const vaultPath = slugToVaultPath.get(slug);
171
577
  if (vaultPath)
172
578
  return `${vaultPath}.md`;
@@ -174,20 +580,103 @@ function resolveNavPath(href, slugToVaultPath) {
174
580
  return hrefToPath(href);
175
581
  }
176
582
  // ── Frontmatter ─────────────────────────────────────────
177
- function buildFrontmatter(title, position) {
178
- return `---\ntitle: ${yamlStr(title)}\naliases:\n - ${yamlStr(title)}\nsidebar_position: ${position}\n---`;
583
+ function buildFrontmatter(title, position, categories = []) {
584
+ return `---\ntitle: ${yamlStr(title)}\naliases:\n - ${yamlStr(title)}\nsidebar_position: ${position}${categoryBlock(categories)}\n---`;
585
+ }
586
+ /**
587
+ * `categories` + `tags` lines for a frontmatter block, or "" when there are none.
588
+ *
589
+ * Two renderings of the same hierarchy, doing different jobs:
590
+ * - `categories` keeps the authored labels, for reading and for Bases
591
+ * filters (`categories.contains("Virtualization")`). A LIST, not a
592
+ * "/"-joined string, so filtering is set membership rather than the
593
+ * substring matching `@dogsbay/chunk`'s facets.ts SC2 rejects.
594
+ * - `tags` is the same chain slugified into one nested tag. Obsidian tags
595
+ * cannot contain spaces, but nested tags give a collapsible tree in the
596
+ * tag pane and make `tag:#virtualization` a valid graph colour-group
597
+ * query — which is what lets graph groups be real facets instead of
598
+ * text-matching page bodies.
599
+ */
600
+ function categoryBlock(categories) {
601
+ if (categories.length === 0)
602
+ return "";
603
+ const list = categories.map((c) => `\n - ${yamlStr(c)}`).join("");
604
+ const tag = categories.map((c) => slugify(c)).filter(Boolean).join("/");
605
+ const tagLine = tag ? `\ntags:\n - ${tag}` : "";
606
+ return `\ncategories:${list}${tagLine}`;
179
607
  }
180
608
  // ── Utilities ───────────────────────────────────────────
609
+ /**
610
+ * Is this href an in-page anchor rather than a reference to a page?
611
+ *
612
+ * `#options`, `/#options`, `/docs#options` — every spelling whose PATH part is
613
+ * empty but which carries a fragment or query. They must not resolve to a
614
+ * slug: stripping the fragment left `""`, and the `|| "index"` fallback below
615
+ * turned that into the HOME note, so a decorative "on this page" nav row
616
+ * hijacked the homepage and dragged it into that row's folder. Checking only
617
+ * for a LEADING `#` missed the slash-prefixed spellings, which is how the
618
+ * first version of this guard let the same failure through.
619
+ */
620
+ function isAnchorOnly(href) {
621
+ if (!/[#?]/.test(href))
622
+ return false;
623
+ const path = href
624
+ .split(/[#?]/)[0]
625
+ .replace(/^\/docs\/?/, "")
626
+ .replace(/^\//, "")
627
+ .replace(/\/$/, "");
628
+ return path === "";
629
+ }
181
630
  function hrefToSlug(href) {
631
+ if (isAnchorOnly(href))
632
+ return href;
182
633
  return href
183
- .replace(/^\/docs\/?/, "")
634
+ // Otherwise an anchor or query string is not part of the slug. Left on,
635
+ // `hrefToPath` appended `.md` to the whole thing and produced
636
+ // `guide/install#configure.md` — a path matching no file, so that nav
637
+ // entry was dead.
638
+ .replace(/[#?].*$/, "")
639
+ .replace(/^\/docs\/?/, "") // legacy nav form
640
+ .replace(/^\//, "") // leading slash — a nav href is `/overview`, a page slug is `overview`
641
+ .replace(/\.md$/, "") // some navs carry the file extension
184
642
  .replace(/\/$/, "")
185
643
  || "index";
186
644
  }
645
+ /**
646
+ * The PAGE a nav href names. A folder's index is spelled `guides/index` by
647
+ * some navs (`site build`) and `guides` by others, and a page slug may use
648
+ * either (format-vitepress keeps `/index`). The exact slug wins; the other
649
+ * spelling is tried only when the exact one is not a page — a corpus can
650
+ * hold both `api` and `api/index`, and each must stay reachable.
651
+ */
652
+ function pageSlug(href, known) {
653
+ const slug = hrefToSlug(href);
654
+ if (known.has(slug))
655
+ return slug;
656
+ const bare = slug.replace(/\/index$/, "");
657
+ if (bare !== slug && known.has(bare))
658
+ return bare;
659
+ if (bare === slug && known.has(`${slug}/index`))
660
+ return `${slug}/index`;
661
+ return slug;
662
+ }
187
663
  function hrefToPath(href) {
188
664
  const slug = hrefToSlug(href);
189
665
  return slug === "index" ? "index.md" : `${slug}.md`;
190
666
  }
667
+ /** Join a vault folder and file name, tolerating an empty folder. */
668
+ function joinVaultPath(folder, name) {
669
+ const clean = folder.replace(/^\/+|\/+$/g, "");
670
+ return clean ? `${clean}/${name}` : name;
671
+ }
672
+ /**
673
+ * A page's vault-relative path when the nav does not place it — the slug,
674
+ * mirroring the source tree, rather than just its last segment.
675
+ */
676
+ function slugToVaultRelPath(slug) {
677
+ const parts = slug.split("/").filter(Boolean);
678
+ return parts.length > 0 ? parts.join("/") : "index";
679
+ }
191
680
  function fileNameFromSlug(slug) {
192
681
  // "tutorial/first-steps" → "first-steps" (folder handles parent)
193
682
  const parts = slug.split("/");
@@ -195,7 +684,9 @@ function fileNameFromSlug(slug) {
195
684
  }
196
685
  /** Extract the last path segment from an href to use as folder name. */
197
686
  function folderNameFromHref(href) {
198
- const slug = hrefToSlug(href);
687
+ // A folder is named after the section, never `index`: `site build` spells
688
+ // a folder's index `/guides/index`, and its children landed in `index/`.
689
+ const slug = hrefToSlug(href).replace(/\/index$/, "");
199
690
  const parts = slug.split("/");
200
691
  return parts[parts.length - 1] || parts[parts.length - 2] || slug;
201
692
  }
@@ -211,4 +702,30 @@ function yamlStr(s) {
211
702
  }
212
703
  return s;
213
704
  }
214
- //# sourceMappingURL=project.js.map
705
+ function isExternalHref(href) {
706
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(href) || /^mailto:/i.test(href);
707
+ }
708
+ // Minimal fence tracker for the two link passes below (format-obsidian
709
+ // may not depend on format-dogsbay-md at runtime — its tracker lives
710
+ // there). Open on a ```/~~~ run, close only on a run of the SAME char
711
+ // at >= the opener's length with nothing after it (a shorter run inside
712
+ // a longer fence is content).
713
+ function makeFenceTracker() {
714
+ let open = null;
715
+ return (line) => {
716
+ const m = line.match(/^\s*(`{3,}|~{3,})(.*)$/);
717
+ if (m) {
718
+ const [, run, rest] = m;
719
+ if (!open) {
720
+ open = { char: run[0], len: run.length };
721
+ return "fence";
722
+ }
723
+ if (run[0] === open.char && run.length >= open.len && rest.trim() === "") {
724
+ open = null;
725
+ return "fence";
726
+ }
727
+ return "code";
728
+ }
729
+ return open ? "code" : "prose";
730
+ };
731
+ }