@openmoca/moca-convert 0.0.0-stage → 0.7.0

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.
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ // Captures a YouTube video or playlist (metadata, description, captions) with
3
+ // yt-dlp, then runs moca-convert on the capture to build the package.
4
+ import { Command } from 'commander';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { UsageError } from '../lib/target.js';
11
+ import { capture } from '../lib/youtube/capture.js';
12
+ import { ytDlp } from '../lib/youtube/ytdlp.js';
13
+
14
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
15
+
16
+ const program = new Command();
17
+ program
18
+ .name('moca-youtube')
19
+ .description('Capture a YouTube video or playlist (metadata, description and captions) and convert it into a MOCA package.')
20
+ .version(version, '-V, --cli-version', "output moca-youtube's own version")
21
+ .argument('<url>', 'a YouTube video or playlist URL')
22
+ .option('-o, --output <dir>', 'output package directory (required unless --no-convert)')
23
+ .option('--id <uri>', 'package id: an absolute URI (required unless --no-convert)')
24
+ .option('--capture-dir <dir>', 'keep the capture here (default: a temporary directory, removed afterwards)')
25
+ .option('--title <string>', 'manifest title (default: the video or playlist title)')
26
+ .option('--version <semver>', 'manifest version for the package', '1.0.0')
27
+ .option('--type <type>', 'OKF type for each video node (default Video)')
28
+ .option('--language <bcp47>', 'content language, and the caption language to fetch', 'en')
29
+ .option('--license <spdx>', 'SPDX license expression for the package')
30
+ .option('--yt-dlp <path>', 'the yt-dlp executable (default: $YT_DLP, else yt-dlp on PATH)')
31
+ .option('--no-convert', 'only capture; do not run moca-convert')
32
+ .option('--force', 'overwrite a non-empty capture or output directory', false)
33
+ .option('-q, --quiet', 'suppress progress output', false)
34
+ .action(run);
35
+
36
+ program.exitOverride();
37
+ program.parseAsync(process.argv).catch((err) => {
38
+ if (err.code && err.code.startsWith('commander.')) {
39
+ process.exit(err.code === 'commander.helpDisplayed' || err.code === 'commander.version' ? 0 : 2);
40
+ }
41
+ throw err;
42
+ });
43
+
44
+ async function run(url, options) {
45
+ const log = options.quiet ? () => {} : (line) => console.error(`moca-youtube: ${line}`);
46
+ let captureDir = options.captureDir;
47
+ const temporary = !captureDir;
48
+ try {
49
+ if (options.convert && (!options.output || !options.id)) {
50
+ throw new UsageError('--output and --id are required to convert; pass --no-convert to only capture.');
51
+ }
52
+ if (!options.convert && temporary) throw new UsageError('--no-convert needs --capture-dir, or the capture is thrown away.');
53
+ if (temporary) captureDir = mkdtempSync(join(tmpdir(), 'moca-youtube-capture-'));
54
+
55
+ const result = await capture({
56
+ url,
57
+ captureDir,
58
+ language: options.language,
59
+ force: options.force,
60
+ ytdlp: ytDlp({ bin: options.ytDlp }),
61
+ log,
62
+ });
63
+ for (const warning of result.warnings) console.error(`moca-youtube: WARNING ${warning}`);
64
+ log(`captured ${result.videos} video(s) from a ${result.kind}${temporary ? '' : ` into ${captureDir}`}`);
65
+ if (!options.convert) return;
66
+
67
+ const args = [
68
+ fileURLToPath(new URL('./moca-convert.js', import.meta.url)),
69
+ captureDir, '--from', 'youtube',
70
+ '-o', options.output,
71
+ '--id', options.id,
72
+ '--version', options.version,
73
+ '--language', options.language,
74
+ ...(options.title ? ['--title', options.title] : []),
75
+ ...(options.type ? ['--type', options.type] : []),
76
+ ...(options.license ? ['--license', options.license] : []),
77
+ ...(options.force ? ['--force'] : []),
78
+ ...(options.quiet ? ['--quiet'] : []),
79
+ ];
80
+ const converted = spawnSync(process.execPath, args, { stdio: 'inherit' });
81
+ process.exitCode = converted.status ?? 1;
82
+ } catch (err) {
83
+ if (err instanceof UsageError) {
84
+ console.error(`moca-youtube: ${err.message}`);
85
+ process.exitCode = 2;
86
+ return;
87
+ }
88
+ console.error(`moca-youtube: ${err.message}`);
89
+ process.exitCode = 1;
90
+ } finally {
91
+ if (temporary && captureDir) rmSync(captureDir, { recursive: true, force: true });
92
+ }
93
+ }
@@ -0,0 +1,134 @@
1
+ // `directory` adapter: a folder of Markdown files (optionally nested) becomes
2
+ // one content node per file, at the same path under content/. The folders
3
+ // become the package's structure (package spec §5.6), as the pdf and youtube
4
+ // adapters write theirs: a concept per folder and per file, parts by
5
+ // dct:hasPart, and each folder's order (by name) as an ordered collection.
6
+ // Each file's node is bound to its own concept, unless its frontmatter already
7
+ // has a `moca` block. --no-structure leaves structure.ttl out.
8
+ import { existsSync, statSync } from 'node:fs';
9
+ import { basename, extname, join } from 'node:path';
10
+ import { walkFiles } from '../walk.js';
11
+ import { readContentFile, ensureOkf, deriveTitle } from '../frontmatter.js';
12
+ import { buildManifest } from '../manifest.js';
13
+ import { UsageError } from '../target.js';
14
+ import { iriPath, turtleString } from '../text.js';
15
+
16
+ export const name = 'directory';
17
+ export const DEFAULT_TYPE = 'Document';
18
+
19
+ // A folder's own page, whose title names the folder: OKF's index.md, or a README.
20
+ const FOLDER_PAGES = ['index.md', 'README.md', 'readme.md'];
21
+
22
+ /** @param {string} inputPath */
23
+ export function detect(inputPath) {
24
+ if (!existsSync(inputPath) || !statSync(inputPath).isDirectory()) return false;
25
+ return walkFiles(inputPath).some((f) => f.endsWith('.md'));
26
+ }
27
+
28
+ /**
29
+ * @param {{ inputPath: string, options: object }} ctx
30
+ * @returns {import('./index.js').PackageDraft}
31
+ */
32
+ export function convert({ inputPath, options }) {
33
+ const manifest = buildManifest(options);
34
+ const files = walkFiles(inputPath).filter((f) => f.endsWith('.md'));
35
+ if (files.length === 0) throw new UsageError(`No Markdown files found under ${inputPath}.`);
36
+ const type = options.type ?? DEFAULT_TYPE;
37
+ const withStructure = options.structure !== false;
38
+ const iri = (fragment) => `${manifest.id}#${fragment}`;
39
+ const warnings = [];
40
+ const titles = new Map();
41
+
42
+ const contentNodes = files.map((relPath) => {
43
+ const { data, content, raw } = readContentFile(join(inputPath, relPath));
44
+ const title = deriveTitle(data, content, basename(relPath, extname(relPath)));
45
+ titles.set(relPath, title);
46
+ let extra = {};
47
+ if (withStructure && !isFolderPage(relPath)) {
48
+ if (data.moca === undefined) {
49
+ extra = { moca: { concepts: [{ iri: iri(fileFragment(relPath)), role: 'primary' }] } };
50
+ } else {
51
+ warnings.push({
52
+ code: 'STRUCTURE_NOT_BOUND',
53
+ message: 'has its own moca block, so it is not bound to its concept in structure.ttl',
54
+ file: relPath,
55
+ });
56
+ }
57
+ }
58
+ return { path: `content/${relPath}`, body: ensureOkf(raw, data, { type, title }, extra) };
59
+ });
60
+
61
+ const result = { manifest, contentNodes, warnings };
62
+ if (withStructure) {
63
+ result.files = [{ path: 'structure.ttl', body: structure(manifest, files, titles, { iri, lang: options.language }) }];
64
+ }
65
+ return result;
66
+ }
67
+
68
+ /** A file's concept fragment: its path without .md, each segment percent-encoded. */
69
+ function fileFragment(relPath) {
70
+ return iriPath(relPath.replace(/\.md$/, ''));
71
+ }
72
+
73
+ function isFolderPage(relPath) {
74
+ return FOLDER_PAGES.includes(relPath.split('/').pop());
75
+ }
76
+
77
+ // Words that number a division of a document: "part-3-..." reads "Part 3: ...".
78
+ const NUMBERED = /^(part|chapter|section|schedule|module|unit|lesson|appendix|annex|article|volume) (\w+) (.+)$/i;
79
+
80
+ /**
81
+ * A folder's label: the title of its index.md or README, else its name without
82
+ * a leading order number, in sentence case ("011-resource-management" ->
83
+ * "Resource management"), with a numbered division read as one
84
+ * ("03-part-3-law-enforcement-processing" -> "Part 3: Law enforcement processing").
85
+ */
86
+ export function folderLabel(folder, titles) {
87
+ for (const page of FOLDER_PAGES) {
88
+ const title = titles.get(`${folder}/${page}`);
89
+ if (title) return title;
90
+ }
91
+ const last = folder.split('/').pop();
92
+ const words = last.replace(/^\d+[-_. ]+/, '').replace(/[-_]+/g, ' ').trim();
93
+ if (!words) return last;
94
+ const sentence = (s) => s[0].toUpperCase() + s.slice(1);
95
+ const numbered = NUMBERED.exec(words);
96
+ return numbered ? `${sentence(numbered[1].toLowerCase())} ${numbered[2].toUpperCase()}: ${sentence(numbered[3])}` : sentence(words);
97
+ }
98
+
99
+ /**
100
+ * The folders as structure: the package as a whole ("collection"), each
101
+ * folder and each file a concept, parts by dct:hasPart, and each container's
102
+ * children, folders and files together in name order, as an ordered collection.
103
+ */
104
+ function structure(manifest, files, titles, { iri, lang }) {
105
+ const label = (text) => `${turtleString(text)}${lang ? `@${lang}` : ''}`;
106
+ const ref = (fragment) => `<${iri(fragment)}>`;
107
+ const children = new Map([['', new Set()]]);
108
+ for (const file of files) {
109
+ if (isFolderPage(file)) continue;
110
+ const parts = file.split('/');
111
+ for (let i = 0; i < parts.length; i++) {
112
+ const parent = parts.slice(0, i).join('/');
113
+ const child = parts.slice(0, i + 1).join('/');
114
+ if (!children.has(parent)) children.set(parent, new Set());
115
+ children.get(parent).add(child);
116
+ }
117
+ }
118
+ const fragment = (path) => (path === '' ? 'collection' : path.endsWith('.md') ? fileFragment(path) : iriPath(path));
119
+ const order = (path) => [...children.get(path)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
120
+ const blocks = ['@prefix skos: <http://www.w3.org/2004/02/skos/core#> .\n@prefix dct: <http://purl.org/dc/terms/> .'];
121
+ for (const container of [...children.keys()].sort()) {
122
+ const members = order(container).map((c) => ref(fragment(c)));
123
+ if (members.length === 0) continue;
124
+ const name = container === '' ? manifest.title : folderLabel(container, titles);
125
+ blocks.push(`${ref(fragment(container))} a skos:Concept ;\n skos:prefLabel ${label(name)} ;\n dct:hasPart ${members.join(',\n ')} .`);
126
+ blocks.push(
127
+ `${ref(`${fragment(container)}-order`)} a skos:OrderedCollection ;\n skos:prefLabel ${label(`${name} (folder order)`)} ;\n skos:memberList (\n ${members.join('\n ')}\n ) .`,
128
+ );
129
+ }
130
+ for (const file of files) {
131
+ if (!isFolderPage(file)) blocks.push(`${ref(fileFragment(file))} a skos:Concept ;\n skos:prefLabel ${label(titles.get(file))} .`);
132
+ }
133
+ return `${blocks.join('\n\n')}\n`;
134
+ }
@@ -0,0 +1,60 @@
1
+ // Adapter registry. Every adapter module exports `name`, `detect(inputPath)`,
2
+ // and `convert({ inputPath, options })`, which returns a PackageDraft or a
3
+ // promise of one. `detect`/`convert` never touch disk
4
+ // outside reading the source tree; all output writing goes through
5
+ // lib/write.js so determinism and the fail-closed lint gate live in one
6
+ // place instead of being duplicated per adapter.
7
+ //
8
+ // @typedef {object} ContentNode
9
+ // @property {string} path - package-relative path under content/, forward slashes
10
+ // @property {string} body - full file contents, including any frontmatter block
11
+ //
12
+ // @typedef {object} ConversionWarning
13
+ // @property {string} code
14
+ // @property {string} message
15
+ // @property {string} [file] - source-relative path, for user-facing messages
16
+ //
17
+ // @typedef {object} PackageDraft
18
+ // @property {object} manifest
19
+ // @property {ContentNode[]} contentNodes
20
+ // @property {{ path: string, body: string|Buffer }[]} [files] - other package files:
21
+ // under sources/ or media/, or structure.ttl
22
+ // @property {ConversionWarning[]} warnings
23
+ import { UsageError } from '../target.js';
24
+ import * as directory from './directory.js';
25
+ import * as markdown from './markdown.js';
26
+ import * as obsidian from './obsidian.js';
27
+ import * as openapi from './openapi.js';
28
+ import * as pdf from './pdf.js';
29
+ import * as youtube from './youtube.js';
30
+
31
+ export const ADAPTER_NAMES = ['directory', 'markdown', 'obsidian', 'openapi', 'pdf', 'youtube'];
32
+
33
+ const IMPLEMENTED = {
34
+ directory,
35
+ markdown,
36
+ obsidian,
37
+ openapi,
38
+ pdf,
39
+ youtube,
40
+ };
41
+
42
+ /**
43
+ * @param {string} name
44
+ * @returns {{ name: string, detect: (inputPath: string) => boolean, convert: Function }}
45
+ */
46
+ export function getAdapter(name) {
47
+ const adapter = IMPLEMENTED[name];
48
+ if (!adapter) {
49
+ if (ADAPTER_NAMES.includes(name)) {
50
+ throw new UsageError(`The "${name}" adapter is not implemented yet.`);
51
+ }
52
+ throw new UsageError(`Unknown adapter "${name}"; expected one of: ${ADAPTER_NAMES.join(', ')}.`);
53
+ }
54
+ return adapter;
55
+ }
56
+
57
+ /** Adapters usable by lib/detect.js auto-detection, in priority order. */
58
+ export function implementedAdapters() {
59
+ return Object.values(IMPLEMENTED);
60
+ }
@@ -0,0 +1,65 @@
1
+ // `markdown` adapter: a single Markdown file, or a glob of files with no
2
+ // directory structure worth preserving. Each becomes content/<slug>.md,
3
+ // where the slug is derived from the file's title, not its source path.
4
+ import { existsSync, globSync, statSync } from 'node:fs';
5
+ import { basename, extname } from 'node:path';
6
+ import { readContentFile, ensureOkf, deriveTitle } from '../frontmatter.js';
7
+ import { buildManifest } from '../manifest.js';
8
+ import { slugify } from '../slug.js';
9
+ import { UsageError, isGlobPattern } from '../target.js';
10
+
11
+ export const name = 'markdown';
12
+ export const DEFAULT_TYPE = 'Document';
13
+
14
+
15
+ /**
16
+ * @param {string} inputPath
17
+ * @returns {boolean} true for a single .md/.markdown file (a directory or
18
+ * glob input is handled by the `directory` adapter or requires an
19
+ * explicit --from, respectively -- see lib/detect.js).
20
+ */
21
+ export function detect(inputPath) {
22
+ if (isGlobPattern(inputPath)) return false;
23
+ if (!existsSync(inputPath) || !statSync(inputPath).isFile()) return false;
24
+ return /\.(md|markdown)$/i.test(inputPath);
25
+ }
26
+
27
+ /**
28
+ * @param {object} ctx
29
+ * @param {string} ctx.inputPath
30
+ * @param {{ id?: string, title?: string, version?: string }} ctx.options
31
+ * @returns {import('./index.js').PackageDraft}
32
+ */
33
+ export function convert({ inputPath, options }) {
34
+ const manifest = buildManifest(options);
35
+ const files = resolveFiles(inputPath);
36
+ if (files.length === 0) {
37
+ throw new UsageError(`No Markdown files matched "${inputPath}".`);
38
+ }
39
+
40
+ const usedSlugs = new Map(); // slug -> count seen so far, for deterministic -2/-3 suffixes
41
+ const type = options.type ?? DEFAULT_TYPE;
42
+ const contentNodes = files.map((absPath) => buildContentNode(absPath, usedSlugs, type));
43
+
44
+ return { manifest, contentNodes, warnings: [] };
45
+ }
46
+
47
+ function resolveFiles(inputPath) {
48
+ const paths = isGlobPattern(inputPath) ? [...globSync(inputPath)] : [inputPath];
49
+ return paths
50
+ .filter((p) => statSync(p).isFile())
51
+ .sort();
52
+ }
53
+
54
+ function buildContentNode(absPath, usedSlugs, type) {
55
+ const { data, content, raw } = readContentFile(absPath);
56
+ const title = deriveTitle(data, content, basename(absPath, extname(absPath)));
57
+ const slug = uniqueSlug(slugify(title), usedSlugs);
58
+ return { path: `content/${slug}.md`, body: ensureOkf(raw, data, { type, title }) };
59
+ }
60
+
61
+ function uniqueSlug(baseSlug, usedSlugs) {
62
+ const count = usedSlugs.get(baseSlug) ?? 0;
63
+ usedSlugs.set(baseSlug, count + 1);
64
+ return count === 0 ? baseSlug : `${baseSlug}-${count + 1}`;
65
+ }
@@ -0,0 +1,206 @@
1
+ // `obsidian` adapter: an Obsidian vault directory becomes one content node
2
+ // per note, preserving the vault's folder structure under content/ and
3
+ // rewriting [[wikilink]] syntax to relative Markdown links.
4
+ import { existsSync, statSync } from 'node:fs';
5
+ import { basename, join, posix } from 'node:path';
6
+ import { splitFrontmatter } from '@openmoca/moca-core';
7
+ import { walkFiles } from '../walk.js';
8
+ import { readContentFile, ensureOkf, deriveTitle } from '../frontmatter.js';
9
+ import { buildManifest } from '../manifest.js';
10
+ import { matchesAny } from '../glob.js';
11
+ import { slugify } from '../slug.js';
12
+ import { UsageError } from '../target.js';
13
+
14
+ export const name = 'obsidian';
15
+ export const DEFAULT_TYPE = 'Note';
16
+
17
+ const WIKILINK = /(!?)\[\[([^\]|#]+)(#[^\]|]+)?(?:\|([^\]]+))?\]\]/g;
18
+
19
+ /**
20
+ * @param {string} inputPath
21
+ * @returns {boolean} true if `inputPath` is a directory containing a
22
+ * top-level `.obsidian/` folder -- Obsidian's own vault marker.
23
+ */
24
+ export function detect(inputPath) {
25
+ if (!existsSync(inputPath) || !statSync(inputPath).isDirectory()) return false;
26
+ const obsidianDir = join(inputPath, '.obsidian');
27
+ return existsSync(obsidianDir) && statSync(obsidianDir).isDirectory();
28
+ }
29
+
30
+ /**
31
+ * @param {object} ctx
32
+ * @param {string} ctx.inputPath
33
+ * @param {{ id?: string, title?: string, version?: string, exclude?: string[] }} ctx.options
34
+ * @returns {import('./index.js').PackageDraft}
35
+ */
36
+ export function convert({ inputPath, options }) {
37
+ const manifest = buildManifest({ ...options, title: options.title ?? basename(inputPath) });
38
+ const type = options.type ?? DEFAULT_TYPE;
39
+ const excludePatterns = options.exclude ?? [];
40
+ // walkFiles skips hidden folders: .obsidian/, and .trash/ where Obsidian keeps deleted notes.
41
+ const allNotePaths = walkFiles(inputPath).filter((f) => f.endsWith('.md'));
42
+
43
+ if (allNotePaths.length === 0) {
44
+ throw new UsageError(`No notes found under ${inputPath}.`);
45
+ }
46
+
47
+ const allNotes = allNotePaths.map((relPath) => ({
48
+ relPath,
49
+ excluded: matchesAny(relPath, excludePatterns),
50
+ ...readContentFile(join(inputPath, relPath)),
51
+ }));
52
+
53
+ const noteIndex = buildNoteIndex(allNotes);
54
+ const warnings = [];
55
+ const contentNodes = allNotes
56
+ .filter((note) => !note.excluded)
57
+ .map((note) => buildContentNode(note, noteIndex, warnings, type));
58
+
59
+ return { manifest, contentNodes, warnings };
60
+ }
61
+
62
+ function buildContentNode(note, noteIndex, warnings, type) {
63
+ const title = deriveTitle(note.data, note.content, basename(note.relPath, '.md'));
64
+ // Wikilinks are rewritten in the body only: the front matter is kept as it is.
65
+ const text = ensureOkf(note.raw, note.data, { type, title });
66
+ const split = splitFrontmatter(text);
67
+ const head = split.present && !split.error ? Buffer.from(text, 'utf8').subarray(0, split.bodyOffset).toString('utf8') : '';
68
+ const body = head + rewriteWikilinks(text.slice(head.length), note, noteIndex, warnings);
69
+ return { path: `content/${note.relPath}`, body };
70
+ }
71
+
72
+ /**
73
+ * Rewrites [[wikilink]] syntax line-by-line, skipping lines inside fenced
74
+ * (```) code blocks so link syntax that happens to appear in a code sample
75
+ * is never touched.
76
+ */
77
+ function rewriteWikilinks(text, sourceNote, noteIndex, warnings) {
78
+ let inFence = false;
79
+ return text
80
+ .split('\n')
81
+ .map((line) => {
82
+ if (/^\s*```/.test(line)) {
83
+ inFence = !inFence;
84
+ return line;
85
+ }
86
+ if (inFence) return line;
87
+ return line.replace(WIKILINK, (match, bang, rawTarget, heading, alias) =>
88
+ rewriteMatch({ match, bang, rawTarget, heading, alias, sourceNote, noteIndex, warnings })
89
+ );
90
+ })
91
+ .join('\n');
92
+ }
93
+
94
+ function rewriteMatch({ match, bang, rawTarget, heading, alias, sourceNote, noteIndex, warnings }) {
95
+ const target = rawTarget.trim();
96
+
97
+ if (bang === '!') {
98
+ warnings.push({
99
+ code: 'W_UNSUPPORTED_EMBED',
100
+ file: sourceNote.relPath,
101
+ message: `Embed "${match}" has no CommonMark equivalent; left as literal text.`,
102
+ });
103
+ return match;
104
+ }
105
+
106
+ const resolved = resolveNote(target, noteIndex);
107
+
108
+ if (!resolved) {
109
+ warnings.push({
110
+ code: 'W_UNRESOLVED_WIKILINK',
111
+ file: sourceNote.relPath,
112
+ message: `Wikilink to "${target}" does not match any note in the vault; left as literal text.`,
113
+ });
114
+ return match;
115
+ }
116
+
117
+ if (resolved.excluded) {
118
+ warnings.push({
119
+ code: 'W_EXCLUDED_WIKILINK',
120
+ file: sourceNote.relPath,
121
+ message: `Wikilink to "${target}" points to an excluded note ("${resolved.relPath}"); left as literal text.`,
122
+ });
123
+ return match;
124
+ }
125
+
126
+ const displayText = alias ?? target;
127
+ const relPath = relativeContentLink(sourceNote.relPath, resolved.relPath);
128
+ const anchor = heading ? `#${slugify(heading.slice(1))}` : '';
129
+ return `[${displayText}](${formatLinkDestination(relPath + anchor)})`;
130
+ }
131
+
132
+ /**
133
+ * A link destination with each path segment percent-encoded: vault file names
134
+ * often hold spaces ("Setup Guide.md") and may hold any other character, and
135
+ * an encoded destination is always one link. `.` and `..` segments are kept.
136
+ * @param {string} destination a relative path, with an optional #anchor
137
+ */
138
+ function formatLinkDestination(destination) {
139
+ const hash = destination.indexOf('#');
140
+ const path = hash === -1 ? destination : destination.slice(0, hash);
141
+ const anchor = hash === -1 ? '' : destination.slice(hash);
142
+ // Parentheses too: an unbalanced one would end a bare link destination.
143
+ const encode = (seg) => encodeURIComponent(seg).replace(/[()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
144
+ return path.split('/').map((seg) => (seg === '.' || seg === '..' ? seg : encode(seg))).join('/') + anchor;
145
+ }
146
+
147
+ /**
148
+ * @param {string} fromRelPath - the linking note's path, relative to content/
149
+ * @param {string} toRelPath - the target note's path, relative to content/
150
+ * @returns {string} a POSIX relative path from one to the other
151
+ */
152
+ function relativeContentLink(fromRelPath, toRelPath) {
153
+ const fromDir = posix.dirname(fromRelPath);
154
+ const rel = posix.relative(fromDir === '.' ? '' : fromDir, toRelPath);
155
+ return rel.startsWith('.') ? rel : `./${rel}`;
156
+ }
157
+
158
+ function buildNoteIndex(notes) {
159
+ const byPath = new Map(); // path without extension, lowercased -> note
160
+ const byBasename = new Map(); // basename without extension, lowercased -> note[] (sorted by relPath)
161
+ const byAlias = new Map(); // alias, lowercased -> note
162
+
163
+ for (const note of notes) {
164
+ const withoutExt = note.relPath.replace(/\.md$/i, '');
165
+ byPath.set(withoutExt.toLowerCase(), note);
166
+
167
+ const baseKey = basename(withoutExt).toLowerCase();
168
+ if (!byBasename.has(baseKey)) byBasename.set(baseKey, []);
169
+ byBasename.get(baseKey).push(note);
170
+
171
+ for (const alias of normalizeAliases(note.data.aliases)) {
172
+ const aliasKey = alias.toLowerCase();
173
+ if (!byAlias.has(aliasKey)) byAlias.set(aliasKey, note);
174
+ }
175
+ }
176
+
177
+ for (const list of byBasename.values()) {
178
+ list.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
179
+ }
180
+
181
+ return { byPath, byBasename, byAlias };
182
+ }
183
+
184
+ function normalizeAliases(aliases) {
185
+ if (Array.isArray(aliases)) return aliases.filter((a) => typeof a === 'string');
186
+ if (typeof aliases === 'string') return [aliases];
187
+ return [];
188
+ }
189
+
190
+ /**
191
+ * Resolves a raw wikilink target to a note, preferring an exact
192
+ * (possibly path-qualified) match, then an alias, then a basename match --
193
+ * the same fallback order Obsidian itself uses. When multiple notes share a
194
+ * basename, the lexicographically-first match is chosen deterministically.
195
+ */
196
+ function resolveNote(target, noteIndex) {
197
+ const normalized = target.replace(/\.md$/i, '');
198
+ const key = normalized.toLowerCase();
199
+
200
+ if (noteIndex.byPath.has(key)) return noteIndex.byPath.get(key);
201
+ if (noteIndex.byAlias.has(key)) return noteIndex.byAlias.get(key);
202
+
203
+ const baseKey = basename(normalized).toLowerCase();
204
+ const candidates = noteIndex.byBasename.get(baseKey);
205
+ return candidates ? candidates[0] : null;
206
+ }