@catheadowl/md-tools 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +94 -2
- package/cli/config.mjs +86 -0
- package/cli/doc-link.mjs +145 -0
- package/cli/kernel.mjs +86 -0
- package/cli/normalize.mjs +91 -0
- package/cli/rename.mjs +390 -0
- package/conformance/cases.json +55 -0
- package/lib/gate-check.d.ts +87 -0
- package/lib/gate-check.js +233 -0
- package/lib/index.d.ts +8 -0
- package/lib/index.js +8 -0
- package/lib/links/anchors.d.ts +43 -0
- package/lib/links/anchors.js +93 -0
- package/lib/links/cli.d.ts +33 -0
- package/lib/links/cli.js +86 -0
- package/lib/links/git.d.ts +156 -0
- package/lib/links/git.js +329 -0
- package/lib/links/index.d.ts +33 -0
- package/lib/links/index.js +25 -0
- package/lib/links/markdown.d.ts +127 -0
- package/lib/links/markdown.js +253 -0
- package/lib/links/normalize.d.ts +40 -0
- package/lib/links/normalize.js +102 -0
- package/lib/links/rebase.d.ts +24 -0
- package/lib/links/rebase.js +44 -0
- package/lib/links/rename.d.ts +257 -0
- package/lib/links/rename.js +864 -0
- package/lib/links/resolve.d.ts +145 -0
- package/lib/links/resolve.js +297 -0
- package/lib/links/scheme.d.ts +115 -0
- package/lib/links/scheme.js +209 -0
- package/lib/links/textual.d.ts +26 -0
- package/lib/links/textual.js +144 -0
- package/lib/measure/count.d.ts +47 -0
- package/lib/measure/count.js +91 -0
- package/lib/measure/document.d.ts +105 -0
- package/lib/measure/document.js +173 -0
- package/lib/measure/index.d.ts +22 -0
- package/lib/measure/index.js +18 -0
- package/lib/measure/sections.d.ts +38 -0
- package/lib/measure/sections.js +37 -0
- package/lib/measure/structure.d.ts +53 -0
- package/lib/measure/structure.js +186 -0
- package/package.json +82 -4
- package/skills/md-tools/SKILL.md +42 -0
- package/skills/md-tools/references/freeze.md +17 -0
- package/skills/md-tools/references/payload.md +28 -0
package/lib/links/git.js
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git scan source (self-written). The data plane asks git for
|
|
3
|
+
* the repository file list instead of walking the file system, so gitignored
|
|
4
|
+
* artifacts and submodule contents (gitlinks only) never enter the scan.
|
|
5
|
+
*
|
|
6
|
+
* Every spawn here rides the shared CLI capture primitives (`cli.ts`):
|
|
7
|
+
* stdout/stderr through temp files, never pipes — pipe capture is
|
|
8
|
+
* EPERM under sandboxed hosts, and a temp file is equally valid for a
|
|
9
|
+
* one-shot synchronous read. Pure over node + git — no host deps, so it stays
|
|
10
|
+
* node:test-able.
|
|
11
|
+
*/
|
|
12
|
+
import { join, resolve } from 'node:path';
|
|
13
|
+
import { captureCliExit, captureCliStdout } from './cli.js';
|
|
14
|
+
/**
|
|
15
|
+
* Single safe-spawn primitive, git-flavored: prepends `-C root` to every
|
|
16
|
+
* invocation and delegates to the shared CLI capture (`cli.ts`). Exported so
|
|
17
|
+
* the rename kernel (git grep / git mv) and any future consumer share one
|
|
18
|
+
* source — never hand-roll another spawn in per-item loops.
|
|
19
|
+
*/
|
|
20
|
+
export function captureGitStdout(root, args, tempName) {
|
|
21
|
+
return captureCliStdout('git', ['-C', root, ...args], tempName);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Non-throwing spawn twin for probes whose non-zero exits are answers, not
|
|
25
|
+
* failures — same shared capture, git-flavored. Spawn-level errors that never
|
|
26
|
+
* produced a subprocess (binary missing) still throw through `cli.ts`.
|
|
27
|
+
*/
|
|
28
|
+
function captureGitExit(root, args, tempName) {
|
|
29
|
+
return captureCliExit('git', ['-C', root, ...args], tempName);
|
|
30
|
+
}
|
|
31
|
+
const discoveryCache = new Map();
|
|
32
|
+
/**
|
|
33
|
+
* Discover the worktree root for a session cwd or any path inside the
|
|
34
|
+
* worktree, as a structured outcome — `undefined`-free, exception-free for
|
|
35
|
+
* the two shapes a session routinely hits (no worktree, no git binary);
|
|
36
|
+
* anything else (unreadable path, exotic git failure) still throws. Memoized
|
|
37
|
+
* per resolved path like `gitTopLevel`, and a memoized failure answers repeat
|
|
38
|
+
* calls without re-spawning git — a consumer re-checking in the same session
|
|
39
|
+
* gets the same verdict at zero cost.
|
|
40
|
+
*/
|
|
41
|
+
export function discoverRepositoryRoot(root) {
|
|
42
|
+
const key = resolve(root);
|
|
43
|
+
const cached = discoveryCache.get(key);
|
|
44
|
+
if (cached !== undefined)
|
|
45
|
+
return cached;
|
|
46
|
+
const discovery = probeRepositoryRoot(root);
|
|
47
|
+
discoveryCache.set(key, discovery);
|
|
48
|
+
if (discovery.discovered) {
|
|
49
|
+
// Register under both the input path and the canonical top-level so a later
|
|
50
|
+
// call with either form (session cwd vs. repositoryRoot) hits the same entry.
|
|
51
|
+
topLevelCache.set(key, discovery.topLevel);
|
|
52
|
+
topLevelCache.set(resolve(discovery.topLevel), discovery.topLevel);
|
|
53
|
+
}
|
|
54
|
+
return discovery;
|
|
55
|
+
}
|
|
56
|
+
function probeRepositoryRoot(root) {
|
|
57
|
+
let captured;
|
|
58
|
+
try {
|
|
59
|
+
captured = captureGitExit(root, ['rev-parse', '--show-toplevel'], 'toplevel');
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code === 'ENOENT') {
|
|
63
|
+
return { discovered: false, code: 'git-unavailable', message: 'git is not available on PATH — the file set cannot be discovered' };
|
|
64
|
+
}
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
if (captured.status === 0) {
|
|
68
|
+
return { discovered: true, topLevel: captured.stdout.trim() };
|
|
69
|
+
}
|
|
70
|
+
if (/not a git repository/i.test(captured.stderr)) {
|
|
71
|
+
return { discovered: false, code: 'not-a-git-repository', message: 'the workspace is not inside a git repository — the file set is discovered through git, so the scan does not apply' };
|
|
72
|
+
}
|
|
73
|
+
throw new Error(`git rev-parse --show-toplevel exited ${captured.status}: ${captured.stderr.trim()}`);
|
|
74
|
+
}
|
|
75
|
+
/** `gitTopLevel` failed — carries the classified code so callers branch without string matching. */
|
|
76
|
+
export class RepositoryRootError extends Error {
|
|
77
|
+
/** Which discovery failure this was (`not-a-git-repository` / `git-unavailable`). */
|
|
78
|
+
code;
|
|
79
|
+
constructor(code, message) {
|
|
80
|
+
super(message);
|
|
81
|
+
this.name = 'RepositoryRootError';
|
|
82
|
+
this.code = code;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Resolved-path → canonical top-level memo, fed by `discoverRepositoryRoot` on success. */
|
|
86
|
+
const topLevelCache = new Map();
|
|
87
|
+
/**
|
|
88
|
+
* Absolute git worktree root for a session cwd or any path inside the worktree,
|
|
89
|
+
* throwing `RepositoryRootError` when discovery is answered structurally
|
|
90
|
+
* (no worktree / no git binary) — callers that prefer the non-throwing shape
|
|
91
|
+
* use `discoverRepositoryRoot`. Memoized per resolved path: `rev-parse
|
|
92
|
+
* --show-toplevel` spawns a fresh `git` subprocess (~60–250ms on Windows), and
|
|
93
|
+
* the gate scan calls this once per missing reference through `gitLinkPaths`
|
|
94
|
+
* (see `temporarilyUnverifiable`). Without the cache that turns dozens of dead
|
|
95
|
+
* wikilinks into seconds of redundant subprocess spawns. The worktree root
|
|
96
|
+
* never moves within a session, so caching is safe; a different input path
|
|
97
|
+
* (another repo) gets its own key. Success feeds the shared discovery memo;
|
|
98
|
+
* failure reads from it without re-spawning.
|
|
99
|
+
*/
|
|
100
|
+
export function gitTopLevel(root) {
|
|
101
|
+
const key = resolve(root);
|
|
102
|
+
const cached = topLevelCache.get(key);
|
|
103
|
+
if (cached !== undefined)
|
|
104
|
+
return cached;
|
|
105
|
+
const discovery = discoverRepositoryRoot(root);
|
|
106
|
+
if (!discovery.discovered)
|
|
107
|
+
throw new RepositoryRootError(discovery.code, discovery.message);
|
|
108
|
+
return discovery.topLevel;
|
|
109
|
+
}
|
|
110
|
+
const gitlinkCache = new Map();
|
|
111
|
+
/** Absolute paths recorded as gitlinks (mode 160000) in the current worktree. */
|
|
112
|
+
export function gitLinkPaths(root) {
|
|
113
|
+
const topLevel = gitTopLevel(root);
|
|
114
|
+
const cached = gitlinkCache.get(topLevel);
|
|
115
|
+
if (cached)
|
|
116
|
+
return cached;
|
|
117
|
+
const output = captureGitStdout(topLevel, ['ls-files', '--cached', '--stage', '-z'], 'stage');
|
|
118
|
+
const links = new Set();
|
|
119
|
+
for (const record of output.split('\0')) {
|
|
120
|
+
if (record === '')
|
|
121
|
+
continue;
|
|
122
|
+
const tab = record.indexOf('\t');
|
|
123
|
+
if (tab === -1)
|
|
124
|
+
continue;
|
|
125
|
+
const mode = record.slice(0, record.indexOf(' '));
|
|
126
|
+
if (mode !== '160000')
|
|
127
|
+
continue;
|
|
128
|
+
links.add(join(topLevel, record.slice(tab + 1)));
|
|
129
|
+
}
|
|
130
|
+
gitlinkCache.set(topLevel, links);
|
|
131
|
+
return links;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Tracked files plus untracked-not-ignored files (`--cached --others
|
|
135
|
+
* --exclude-standard`), NUL-separated so any filename survives. The command
|
|
136
|
+
* first canonicalizes `root` to git's toplevel so paths are always repository
|
|
137
|
+
* root-relative, even when invoked from a subdirectory.
|
|
138
|
+
*/
|
|
139
|
+
export function gitLsFiles(root) {
|
|
140
|
+
const topLevel = gitTopLevel(root);
|
|
141
|
+
return captureGitStdout(topLevel, ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], 'ls-files')
|
|
142
|
+
.split('\0')
|
|
143
|
+
.filter(Boolean);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Tracked Markdown files whose content contains the fixed string `pattern`
|
|
147
|
+
* (candidate localization for rename in-links: 1 spawn, then per-candidate
|
|
148
|
+
* resolution filters to real targets). Fixed-string (`-F`) so a basename with
|
|
149
|
+
* `.`/`-`/`(` never acts as a regex. Absolute paths, sorted.
|
|
150
|
+
*/
|
|
151
|
+
export function gitGrep(root, pattern) {
|
|
152
|
+
const topLevel = gitTopLevel(root);
|
|
153
|
+
let output;
|
|
154
|
+
try {
|
|
155
|
+
output = captureGitStdout(topLevel, ['grep', '-l', '-z', '-F', '-e', pattern, '--', '*.md'], 'grep');
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
// `git grep` exits 1 on zero matches (not an error); anything else rethrows.
|
|
159
|
+
if (error.status === 1)
|
|
160
|
+
return [];
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
return output
|
|
164
|
+
.split('\0')
|
|
165
|
+
.filter(Boolean)
|
|
166
|
+
.map(file => resolve(topLevel, file))
|
|
167
|
+
.sort();
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Worktree state as `git status --porcelain -z` records (1 spawn). Renames and
|
|
171
|
+
* copies carry their original path as the next NUL-separated entry. This is
|
|
172
|
+
* the post-hoc repair evidence data plane: git witnessing that an old path was
|
|
173
|
+
* tracked and is now gone (`R old→new` staged, or `D old` in either column).
|
|
174
|
+
*/
|
|
175
|
+
export function gitStatusPorcelain(root) {
|
|
176
|
+
const topLevel = gitTopLevel(root);
|
|
177
|
+
const output = captureGitStdout(topLevel, ['status', '--porcelain', '-z'], 'status');
|
|
178
|
+
const records = [];
|
|
179
|
+
const entries = output.split('\0');
|
|
180
|
+
for (let i = 0; i < entries.length; i++) {
|
|
181
|
+
const entry = entries[i];
|
|
182
|
+
if (entry === '')
|
|
183
|
+
continue;
|
|
184
|
+
const record = { xy: entry.slice(0, 2), path: entry.slice(3) };
|
|
185
|
+
if (record.xy.charAt(0) === 'R' || record.xy.charAt(0) === 'C') {
|
|
186
|
+
record.origPath = entries[++i];
|
|
187
|
+
}
|
|
188
|
+
records.push(record);
|
|
189
|
+
}
|
|
190
|
+
return records;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Whether `<revision>:<repoRelativePath>` resolves in that tree — the post-hoc
|
|
194
|
+
* HEAD-tier evidence (D1 ②): old is recorded in HEAD while absent from the
|
|
195
|
+
* worktree, i.e. the worktree status cannot witness the move (e.g. a
|
|
196
|
+
* skip-worktree-hidden deletion). One spawn, no stdout; a non-zero exit (also
|
|
197
|
+
* `fatal: invalid object name` in a commit-less repo) simply means "no record".
|
|
198
|
+
*/
|
|
199
|
+
export function gitTreeHas(root, revision, repoRelativePath) {
|
|
200
|
+
const topLevel = gitTopLevel(root);
|
|
201
|
+
try {
|
|
202
|
+
captureGitStdout(topLevel, ['cat-file', '-e', `${revision}:${repoRelativePath}`], 'cat-file');
|
|
203
|
+
return true;
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Tracked (index) files at or under the given repo-root-relative paths, one
|
|
211
|
+
* spawn for the whole list — the rename plan's source-tracking probe: `git mv`
|
|
212
|
+
* refuses a source with nothing tracked at/under it ('not under version
|
|
213
|
+
* control' / 'source directory is empty'), so an empty match for a pair's old
|
|
214
|
+
* path means the move cannot stage. Pathspecs are literal (`:(literal)`), so a
|
|
215
|
+
* filename carrying glob characters is probed as itself, never as a pattern.
|
|
216
|
+
*/
|
|
217
|
+
export function gitTrackedUnder(root, repoRelativePaths) {
|
|
218
|
+
const topLevel = gitTopLevel(root);
|
|
219
|
+
if (repoRelativePaths.length === 0)
|
|
220
|
+
return [];
|
|
221
|
+
return captureGitStdout(topLevel, ['ls-files', '--cached', '-z', '--', ...repoRelativePaths.map(p => `:(literal)${p}`)], 'ls-cached')
|
|
222
|
+
.split('\0')
|
|
223
|
+
.filter(Boolean);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Rename records from history (`git log -M --diff-filter=R --name-status -z`,
|
|
227
|
+
* one spawn, newest first). Pathspec ground truth: an R record surfaces only
|
|
228
|
+
* when BOTH of its sides fall under the pathspec — a single-side pathspec
|
|
229
|
+
* never matches an R entry (probed: `-M --diff-filter=R -- <old>` alone stays
|
|
230
|
+
* empty even for a twice-renamed path) — so pair queries pass both sides.
|
|
231
|
+
* Output shape per record: `<commit>\0\nR100\0<newPath>\0<oldPath>\0`.
|
|
232
|
+
* `limit` caps the commit walk (history defense); ambiguity beyond the cap is
|
|
233
|
+
* a cost bound, not a verdict — callers list what is found, never adjudicate.
|
|
234
|
+
*/
|
|
235
|
+
export function gitLogRenameRecords(root, repoRelativePaths, limit = 50) {
|
|
236
|
+
const topLevel = gitTopLevel(root);
|
|
237
|
+
if (repoRelativePaths.length === 0)
|
|
238
|
+
return [];
|
|
239
|
+
let output;
|
|
240
|
+
try {
|
|
241
|
+
output = captureGitStdout(topLevel, ['log', '-M', '--diff-filter=R', '--name-status', '-z', '--format=%H', '-n', String(limit), '--', ...repoRelativePaths.map(p => `:(literal)${p}`)], 'log-renames');
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
// A commit-less repo has no history to report (git log exits 128 there).
|
|
245
|
+
// The payload this feeds is informational, so an unreachable log degrades
|
|
246
|
+
// to "no findings" instead of failing the refusal it accompanies.
|
|
247
|
+
return [];
|
|
248
|
+
}
|
|
249
|
+
const records = [];
|
|
250
|
+
const tokens = output.split('\0');
|
|
251
|
+
let commit = '';
|
|
252
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
253
|
+
const token = tokens[i];
|
|
254
|
+
if (token === '')
|
|
255
|
+
continue;
|
|
256
|
+
const status = token.startsWith('\n') ? token.slice(1) : token;
|
|
257
|
+
if (/^R\d+$/.test(status)) {
|
|
258
|
+
// -z name-status order (probed): status, OLD side, NEW side — unlike
|
|
259
|
+
// `status --porcelain -z`, which leads with the current path.
|
|
260
|
+
const oldPath = tokens[++i];
|
|
261
|
+
const newPath = tokens[++i];
|
|
262
|
+
if (newPath !== undefined && oldPath !== undefined)
|
|
263
|
+
records.push({ commit, oldPath, newPath });
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
commit = token.trim();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return records;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The newest commit that touched the repo-root-relative path, or `undefined`
|
|
273
|
+
* when the path has no history at all (one spawn: `git log --format=%H -n 1`).
|
|
274
|
+
* The never-existed probe: an old path with no history was never tracked —
|
|
275
|
+
* the strongest typo signal the informational refusal payload can carry.
|
|
276
|
+
*/
|
|
277
|
+
export function gitLogLastTouched(root, repoRelativePath) {
|
|
278
|
+
const topLevel = gitTopLevel(root);
|
|
279
|
+
let output;
|
|
280
|
+
try {
|
|
281
|
+
output = captureGitStdout(topLevel, ['log', '--format=%H', '-n', '1', '--', `:(literal)${repoRelativePath}`], 'log-touch');
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
// Commit-less repo: no history (same degradation rule as gitLogRenameRecords).
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
const hash = output.trim();
|
|
288
|
+
return hash === '' ? undefined : hash;
|
|
289
|
+
}
|
|
290
|
+
/** `git mv` exited non-zero — carries git's own stderr so callers relay it instead of a raw spawn error. */
|
|
291
|
+
export class GitMoveError extends Error {
|
|
292
|
+
/** Repo-root-relative source of the failed move. */
|
|
293
|
+
from;
|
|
294
|
+
/** Repo-root-relative destination of the failed move. */
|
|
295
|
+
to;
|
|
296
|
+
/** git's stderr, trimmed (e.g. `fatal: not under version control, source=…`). */
|
|
297
|
+
stderr;
|
|
298
|
+
constructor(from, to, stderr) {
|
|
299
|
+
super(`git mv ${from} -> ${to}: ${stderr !== '' ? stderr : 'git exited non-zero'}`);
|
|
300
|
+
this.name = 'GitMoveError';
|
|
301
|
+
this.from = from;
|
|
302
|
+
this.to = to;
|
|
303
|
+
this.stderr = stderr;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Move one tracked path (file or directory) with `git mv`, staging the rename
|
|
308
|
+
* so git remains the state (no runtime). `fromRepoRelative`/`toRepoRelative`
|
|
309
|
+
* are repo-root-relative. On a failed move (non-zero git exit — e.g.
|
|
310
|
+
* destination parent missing, path not under version control — or git never
|
|
311
|
+
* launching) throws `GitMoveError` with the captured stderr, never a raw
|
|
312
|
+
* spawn error.
|
|
313
|
+
*/
|
|
314
|
+
export function gitMove(root, fromRepoRelative, toRepoRelative) {
|
|
315
|
+
const topLevel = gitTopLevel(root);
|
|
316
|
+
try {
|
|
317
|
+
const captured = captureCliExit('git', ['-C', topLevel, 'mv', fromRepoRelative, toRepoRelative], 'mv');
|
|
318
|
+
if (captured.status !== 0) {
|
|
319
|
+
throw new GitMoveError(fromRepoRelative, toRepoRelative, captured.stderr.trim());
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
if (error instanceof GitMoveError)
|
|
324
|
+
throw error;
|
|
325
|
+
// Spawn-level failure: no subprocess, no stderr — same typed exit as a
|
|
326
|
+
// failed move, never a raw spawn error.
|
|
327
|
+
throw new GitMoveError(fromRepoRelative, toRepoRelative, '');
|
|
328
|
+
}
|
|
329
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @catheadowl/md-tools — pure Markdown reference kernel: classify, extract,
|
|
3
|
+
* resolve, anchor-check and rebase document references over a git tree.
|
|
4
|
+
* Reference forms: Markdown links/images/definitions, `[[wikilinks]]`
|
|
5
|
+
* (GitHub-wiki/Obsidian style), and registered scheme addresses (ukp is the
|
|
6
|
+
* first resident).
|
|
7
|
+
* Seam map: `markdown.ts` (parse + wikilink scan), `anchors.ts` (heading
|
|
8
|
+
* anchors), `resolve.ts` (reference resolution + wiki candidate
|
|
9
|
+
* enumeration), `git.ts` (git-tree scan seams), `scheme.ts` (scheme
|
|
10
|
+
* registry + resolvers), `rebase.ts` (byte-preserving rewrites),
|
|
11
|
+
* `rename.ts` (rename planning/apply), `textual.ts` (non-link textual
|
|
12
|
+
* occurrences), `normalize.ts` (root-relative normalization), `cli.ts`
|
|
13
|
+
* (shared temp-file spawn primitives).
|
|
14
|
+
* @module @catheadowl/md-tools
|
|
15
|
+
*/
|
|
16
|
+
export { parseMarkdown, visitMarkdown, markdownDestination, markdownLabel, scanWikiLinks, markdownCodeRanges, splitMarkdownUrlTarget, isExternalOrAbsoluteMarkdownUrl, isWindowsDriveUrl, markdownHeadingLines, } from './markdown.js';
|
|
17
|
+
export type { MarkdownDestination, MarkdownDestinationNode, MarkdownHeadingLine, MarkdownLabel, MarkdownProseLine, WikiLink, MarkdownCodeRange } from './markdown.js';
|
|
18
|
+
export { captureCliExit } from './cli.js';
|
|
19
|
+
export { githubSlug, documentAnchors, documentAnchorPairs, anchorCache } from './anchors.js';
|
|
20
|
+
export type { DocumentAnchorPair } from './anchors.js';
|
|
21
|
+
export { gitTopLevel, discoverRepositoryRoot, gitLinkPaths, gitLsFiles, gitTrackedUnder, gitGrep, gitMove, GitMoveError, RepositoryRootError, captureGitStdout, gitStatusPorcelain, gitTreeHas, gitLogRenameRecords, gitLogLastTouched, } from './git.js';
|
|
22
|
+
export type { GitLsFiles, GitStatusRecord, GitRenameRecord, RepositoryRootDiscovery, RepositoryUnavailableCode } from './git.js';
|
|
23
|
+
export { REASON_ANCHOR_MISSING, REASON_TARGET_MISSING, REASON_OUTSIDE_REPOSITORY, pathInside, posixRelative, canonicalPath, collectAllFiles, collectMarkdownSources, repositoryRoot, extractReferences, resolveReference, resolveReferenceLexically, enumerateWikiCandidates, targetProbeCache, checkRepository, } from './resolve.js';
|
|
24
|
+
export type { CheckRepositoryOptions, LinkReference, Resolution, LinkViolation, ReferenceKind, TargetProbe, WikiCandidateOptions } from './resolve.js';
|
|
25
|
+
export { recognizeSchemeReference, registeredSchemes, resolveSchemeReference, parseUkpListJson, fetchUkpRegistry, resolveUkpWith, } from './scheme.js';
|
|
26
|
+
export type { SchemeReference, SchemeResolution, SchemeResolver, SchemeOptions, UkpEndpoint, UkpRegistry } from './scheme.js';
|
|
27
|
+
export { rebaseDestination, rebaseLabel } from './rebase.js';
|
|
28
|
+
export { rebaseHref, planRename, planSink, applyRenamePlan, RenameApplyError, relabelFor, REASON_NO_RENAME_EVIDENCE, RENAME_CONFLICT_CODES, RENAME_CONFLICT_MESSAGES, POSTHOC_WITNESS_SHAPES, RENAME_HISTORY_EVIDENCE_SHAPES, } from './rename.js';
|
|
29
|
+
export type { PlanRenameOptions, RenameConflictCode, RenameSkip, RenameConflict, RenameHistoryRecord, RenameHistoryEvidence, RenameRelabel, RenameTextual, RenamePair, RenamePlan, RenamePlanResult, RenameApplyResult, } from './rename.js';
|
|
30
|
+
export { scanTextualOccurrences } from './textual.js';
|
|
31
|
+
export type { TextualEdit, TextualShift } from './textual.js';
|
|
32
|
+
export { planRootRelativeNormalization, applyRootRelativeNormalization } from './normalize.js';
|
|
33
|
+
export type { RootRelativeRewrite, RootRelativeSkip, RootRelativePlan, RootRelativeApplyResult, } from './normalize.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @catheadowl/md-tools — pure Markdown reference kernel: classify, extract,
|
|
3
|
+
* resolve, anchor-check and rebase document references over a git tree.
|
|
4
|
+
* Reference forms: Markdown links/images/definitions, `[[wikilinks]]`
|
|
5
|
+
* (GitHub-wiki/Obsidian style), and registered scheme addresses (ukp is the
|
|
6
|
+
* first resident).
|
|
7
|
+
* Seam map: `markdown.ts` (parse + wikilink scan), `anchors.ts` (heading
|
|
8
|
+
* anchors), `resolve.ts` (reference resolution + wiki candidate
|
|
9
|
+
* enumeration), `git.ts` (git-tree scan seams), `scheme.ts` (scheme
|
|
10
|
+
* registry + resolvers), `rebase.ts` (byte-preserving rewrites),
|
|
11
|
+
* `rename.ts` (rename planning/apply), `textual.ts` (non-link textual
|
|
12
|
+
* occurrences), `normalize.ts` (root-relative normalization), `cli.ts`
|
|
13
|
+
* (shared temp-file spawn primitives).
|
|
14
|
+
* @module @catheadowl/md-tools
|
|
15
|
+
*/
|
|
16
|
+
export { parseMarkdown, visitMarkdown, markdownDestination, markdownLabel, scanWikiLinks, markdownCodeRanges, splitMarkdownUrlTarget, isExternalOrAbsoluteMarkdownUrl, isWindowsDriveUrl, markdownHeadingLines, } from './markdown.js';
|
|
17
|
+
export { captureCliExit } from './cli.js';
|
|
18
|
+
export { githubSlug, documentAnchors, documentAnchorPairs, anchorCache } from './anchors.js';
|
|
19
|
+
export { gitTopLevel, discoverRepositoryRoot, gitLinkPaths, gitLsFiles, gitTrackedUnder, gitGrep, gitMove, GitMoveError, RepositoryRootError, captureGitStdout, gitStatusPorcelain, gitTreeHas, gitLogRenameRecords, gitLogLastTouched, } from './git.js';
|
|
20
|
+
export { REASON_ANCHOR_MISSING, REASON_TARGET_MISSING, REASON_OUTSIDE_REPOSITORY, pathInside, posixRelative, canonicalPath, collectAllFiles, collectMarkdownSources, repositoryRoot, extractReferences, resolveReference, resolveReferenceLexically, enumerateWikiCandidates, targetProbeCache, checkRepository, } from './resolve.js';
|
|
21
|
+
export { recognizeSchemeReference, registeredSchemes, resolveSchemeReference, parseUkpListJson, fetchUkpRegistry, resolveUkpWith, } from './scheme.js';
|
|
22
|
+
export { rebaseDestination, rebaseLabel } from './rebase.js';
|
|
23
|
+
export { rebaseHref, planRename, planSink, applyRenamePlan, RenameApplyError, relabelFor, REASON_NO_RENAME_EVIDENCE, RENAME_CONFLICT_CODES, RENAME_CONFLICT_MESSAGES, POSTHOC_WITNESS_SHAPES, RENAME_HISTORY_EVIDENCE_SHAPES, } from './rename.js';
|
|
24
|
+
export { scanTextualOccurrences } from './textual.js';
|
|
25
|
+
export { planRootRelativeNormalization, applyRootRelativeNormalization } from './normalize.js';
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse seam of doc-core — locates Markdown link/image/definition
|
|
3
|
+
* destinations as byte offsets over mdast. This module keeps only the
|
|
4
|
+
* parse/locate primitives the kernel needs.
|
|
5
|
+
*
|
|
6
|
+
* `markdownLabel` locates the label span of a reference (the `[text]` part
|
|
7
|
+
* of a link/image/definition); it is a self-written extension and reuses the
|
|
8
|
+
* module's own `labelBounds` scanner. `scanWikiLinks` is a self-written
|
|
9
|
+
* extension too: a raw-text `[[wikilink]]` scan, excluded inside the code
|
|
10
|
+
* ranges `markdownCodeRanges` supplies — a parse change re-flows those
|
|
11
|
+
* exclusions automatically. `isExternalOrAbsoluteMarkdownUrl` gates Windows
|
|
12
|
+
* drive letters before the scheme test.
|
|
13
|
+
*/
|
|
14
|
+
import type { Nodes } from 'mdast';
|
|
15
|
+
/** One authored Markdown line outside fenced code and rendered-away HTML comments. */
|
|
16
|
+
export interface MarkdownProseLine {
|
|
17
|
+
/** 1-based source line number. */
|
|
18
|
+
index: number;
|
|
19
|
+
/** Source text without normalization. */
|
|
20
|
+
raw: string;
|
|
21
|
+
}
|
|
22
|
+
/** One parsed Markdown heading, retaining its authored first line and rendered text. */
|
|
23
|
+
export interface MarkdownHeadingLine extends MarkdownProseLine {
|
|
24
|
+
/** Parsed ATX or Setext heading depth. */
|
|
25
|
+
depth: 1 | 2 | 3 | 4 | 5 | 6;
|
|
26
|
+
/** Rendered heading text, excluding raw HTML such as comments. */
|
|
27
|
+
text: string;
|
|
28
|
+
}
|
|
29
|
+
/** Parse GitHub-flavored Markdown with the repository's standard extensions. */
|
|
30
|
+
export declare function parseMarkdown(source: string): Nodes;
|
|
31
|
+
/**
|
|
32
|
+
* Visit a Markdown tree depth-first; returning false prunes a node's children.
|
|
33
|
+
* @param node - current tree node.
|
|
34
|
+
* @param visitor - callback invoked before each node's children.
|
|
35
|
+
*/
|
|
36
|
+
export declare function visitMarkdown(node: Nodes, visitor: (node: Nodes) => boolean | void): void;
|
|
37
|
+
/** Markdown nodes whose authored destination occupies a replaceable source range. */
|
|
38
|
+
export type MarkdownDestinationNode = Extract<Nodes, {
|
|
39
|
+
type: 'link' | 'image' | 'definition';
|
|
40
|
+
}>;
|
|
41
|
+
/** One authored Markdown destination and its absolute source offsets. */
|
|
42
|
+
export interface MarkdownDestination {
|
|
43
|
+
start: number;
|
|
44
|
+
end: number;
|
|
45
|
+
url: string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Single letter + ':' + '/' or '\' is a Windows drive, never a scheme: the
|
|
49
|
+
* IANA registry (~450 entries) holds no single-letter scheme, and RFC 8089
|
|
50
|
+
* fixes `file:///<drive>/…` as the global unambiguous local-absolute form.
|
|
51
|
+
* A bare `D:` without a separator still classifies as a scheme. Pandoc and
|
|
52
|
+
* docling-core fixed the same drive-as-scheme bug the same way.
|
|
53
|
+
*/
|
|
54
|
+
export declare function isWindowsDriveUrl(url: string): boolean;
|
|
55
|
+
/** Whether a Markdown URL is external, repository-root absolute, or purely in-page. */
|
|
56
|
+
export declare function isExternalOrAbsoluteMarkdownUrl(url: string): boolean;
|
|
57
|
+
/** Split one Markdown URL without normalizing its query or fragment suffix. */
|
|
58
|
+
export declare function splitMarkdownUrlTarget(url: string): {
|
|
59
|
+
path: string;
|
|
60
|
+
suffix: string;
|
|
61
|
+
};
|
|
62
|
+
/** Locate one parsed destination in the original Markdown without reserializing it. */
|
|
63
|
+
export declare function markdownDestination(source: string, node: MarkdownDestinationNode): MarkdownDestination;
|
|
64
|
+
/** One authored Markdown label and its absolute source offsets. */
|
|
65
|
+
export interface MarkdownLabel {
|
|
66
|
+
/** Byte offset of the first character after the opening `[`. */
|
|
67
|
+
start: number;
|
|
68
|
+
/** Byte offset of the closing `]` (exclusive end of the label text). */
|
|
69
|
+
end: number;
|
|
70
|
+
/** Label source text exactly as authored — markup and escapes included. */
|
|
71
|
+
text: string;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Locate one parsed node's label in the original Markdown, the way
|
|
75
|
+
* `markdownDestination` locates its destination. Textual only: whether a label
|
|
76
|
+
* may be rewritten is the caller's judgment, taken next to the AST (it needs
|
|
77
|
+
* the node's children and the reference kind).
|
|
78
|
+
*/
|
|
79
|
+
export declare function markdownLabel(source: string, node: MarkdownDestinationNode): MarkdownLabel;
|
|
80
|
+
/** Text a reader sees from one Markdown node; raw HTML itself contributes none. */
|
|
81
|
+
export declare function renderedText(node: Nodes): string;
|
|
82
|
+
/** Return every parsed Markdown heading with its rendered text and source line. */
|
|
83
|
+
export declare function markdownHeadingLines(source: string): MarkdownHeadingLine[];
|
|
84
|
+
/** One authored `[[wiki-link]]`, located byte-exactly in the source. */
|
|
85
|
+
export interface WikiLink {
|
|
86
|
+
/** Byte offset of the opening `[[`. */
|
|
87
|
+
start: number;
|
|
88
|
+
/** Exclusive byte offset just past the closing `]]`. */
|
|
89
|
+
end: number;
|
|
90
|
+
/** Target text as written, trimmed — everything before `#fragment` / `|alias`. */
|
|
91
|
+
target: string;
|
|
92
|
+
/** Byte offset of the trimmed target's first character — the replaceable span a rename rewrites. */
|
|
93
|
+
targetStart: number;
|
|
94
|
+
/** Exclusive byte offset of the trimmed target's last character. */
|
|
95
|
+
targetEnd: number;
|
|
96
|
+
/** Fragment text as written (`[[note#Heading]]` → `'Heading'`), or null. */
|
|
97
|
+
fragment: string | null;
|
|
98
|
+
/** Alias text as written (`[[note|shown]]` → `'shown'`), or null. */
|
|
99
|
+
alias: string | null;
|
|
100
|
+
}
|
|
101
|
+
/** One fenced code block or inline code span, as absolute byte offsets in the source. */
|
|
102
|
+
export interface MarkdownCodeRange {
|
|
103
|
+
/** Byte offset of the range's first character (the fence or opening backtick). */
|
|
104
|
+
start: number;
|
|
105
|
+
/** Exclusive byte offset just past the range's last character. */
|
|
106
|
+
end: number;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Byte ranges of fenced code blocks and inline code spans — the
|
|
110
|
+
* mention-protection law as one producing function: a match inside these
|
|
111
|
+
* ranges is the syntax being mentioned as a term, not a reference. Consumers
|
|
112
|
+
* (wiki scanning here, prose lints elsewhere) share this one truth by import
|
|
113
|
+
* instead of re-deriving the exclusion set from the parse, so the law can
|
|
114
|
+
* never drift between them. The shape is deliberately the narrow current
|
|
115
|
+
* law — if the mention protection ever widens (e.g. to rendered-away HTML
|
|
116
|
+
* comments), it widens in this function and every consumer inherits.
|
|
117
|
+
*/
|
|
118
|
+
export declare function markdownCodeRanges(source: string): MarkdownCodeRange[];
|
|
119
|
+
/**
|
|
120
|
+
* Scan every `[[wiki-link]]` in document order. Wiki syntax is raw text the
|
|
121
|
+
* GFM parse does not model, so the scan is a regex over the source — but a
|
|
122
|
+
* match inside fenced code or a code span is the syntax being mentioned as a
|
|
123
|
+
* term, not a reference: `markdownCodeRanges` supplies those ranges, and
|
|
124
|
+
* matches inside them are skipped. Offset-bearing output only; whether a
|
|
125
|
+
* target resolves, and what an ambiguous one means, is the caller's judgment.
|
|
126
|
+
*/
|
|
127
|
+
export declare function scanWikiLinks(source: string): WikiLink[];
|