@catheadowl/md-tools 0.0.0-stage → 0.1.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 +76 -2
- package/cli/config.mjs +86 -0
- package/cli/doc-link.mjs +139 -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 +83 -0
- package/lib/gate-check.js +212 -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 +20 -0
- package/lib/links/cli.js +72 -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 +125 -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 +143 -0
- package/lib/links/resolve.js +295 -0
- package/lib/links/scheme.d.ts +112 -0
- package/lib/links/scheme.js +206 -0
- package/lib/links/textual.d.ts +26 -0
- package/lib/links/textual.js +144 -0
- package/package.json +75 -4
- package/skills/md-tools/SKILL.md +42 -0
- package/skills/md-tools/references/freeze.md +16 -0
- package/skills/md-tools/references/payload.md +28 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve layer: turns extracted references into existence verdicts over a
|
|
3
|
+
* git worktree. Semantics: `//`, `/`, and scheme targets are skipped; a
|
|
4
|
+
* Windows drive (`D:/…`) is a local absolute path, resolved and judged like
|
|
5
|
+
* any internal target; a `#fragment` on an empty path resolves to the
|
|
6
|
+
* source file; document-relative targets resolve against the source
|
|
7
|
+
* directory; malformed `%zz` stays raw (fail-closed, the link reports
|
|
8
|
+
* broken rather than crashing). Extraction walks the mdast AST, not a regex
|
|
9
|
+
* state machine; anchors come from `anchors.ts`. Wiki targets are not
|
|
10
|
+
* document-relative — they enumerate over the whole file universe
|
|
11
|
+
* (`enumerateWikiCandidates`); their extraction lives in the markdown seam
|
|
12
|
+
* (`scanWikiLinks`).
|
|
13
|
+
*/
|
|
14
|
+
import { type GitLsFiles } from './git.js';
|
|
15
|
+
import { type MarkdownLabel } from './markdown.js';
|
|
16
|
+
/** Stable reason strings the doc-link gate branches its remedy on — reword here, never in the gate. */
|
|
17
|
+
export declare const REASON_ANCHOR_MISSING = "anchor does not exist";
|
|
18
|
+
export type ReferenceKind = 'link' | 'image' | 'definition';
|
|
19
|
+
/** One authored link/image/definition, located byte-exactly in the source. */
|
|
20
|
+
export interface LinkReference {
|
|
21
|
+
kind: ReferenceKind;
|
|
22
|
+
/** 1-based source line. */
|
|
23
|
+
line: number;
|
|
24
|
+
/** Parsed destination url (mdast `node.url`; angle brackets already stripped). */
|
|
25
|
+
url: string;
|
|
26
|
+
/** Byte offset of the destination start in the source; absent on autolinks and other forms with no destination substring to rewrite. */
|
|
27
|
+
start?: number;
|
|
28
|
+
/** Exclusive byte offset of the destination end; absent where `start` is absent. */
|
|
29
|
+
end?: number;
|
|
30
|
+
/**
|
|
31
|
+
* The reference's visible label, located byte-exactly — present only where
|
|
32
|
+
* rewriting it is safe: an inline link or image whose label is a single plain
|
|
33
|
+
* text run. Absent for definitions (the label is the reference KEY that
|
|
34
|
+
* `[label]` usages resolve through, not display text), for markup labels
|
|
35
|
+
* (`[\`x.md\`](…)`, emphasis — replacing those would drop formatting), and
|
|
36
|
+
* for forms with no label range at all.
|
|
37
|
+
*/
|
|
38
|
+
label?: MarkdownLabel;
|
|
39
|
+
}
|
|
40
|
+
/** One reference's resolution outcome; exactly one of `ignored` / `reason` / `abs` is set. */
|
|
41
|
+
export interface Resolution {
|
|
42
|
+
ignored?: boolean;
|
|
43
|
+
abs?: string;
|
|
44
|
+
fragment?: string | null;
|
|
45
|
+
reason?: string;
|
|
46
|
+
}
|
|
47
|
+
export interface LinkViolation {
|
|
48
|
+
file: string;
|
|
49
|
+
line: number;
|
|
50
|
+
url: string;
|
|
51
|
+
reason: string;
|
|
52
|
+
/** Absolute resolved target path — present when the target exists inside the repository (anchor-missing onto a Markdown target), absent for missing/outside targets. */
|
|
53
|
+
targetAbs?: string;
|
|
54
|
+
}
|
|
55
|
+
/** Whether `target` is at or below `root` (lexical containment). */
|
|
56
|
+
export declare function pathInside(root: string, target: string): boolean;
|
|
57
|
+
/** POSIX form of a root-relative path; keeps reports deterministic across platforms. */
|
|
58
|
+
export declare function posixRelative(root: string, target: string): string;
|
|
59
|
+
/**
|
|
60
|
+
* One per-scan existence/realpath probe. Scan targets repeat heavily (a
|
|
61
|
+
* 3.8k-reference scan resolves to ~750 distinct paths, 5:1), and per-reference
|
|
62
|
+
* `existsSync` + `realpathSync` dominates the resolve phase on Windows. A cache
|
|
63
|
+
* scoped to one `checkRepository` call — never module-level — keeps the verdict
|
|
64
|
+
* fresh across turns (files are created and deleted between gate runs). The
|
|
65
|
+
* frozen-worktree-within-a-scan premise is the one the scan already relies on
|
|
66
|
+
* when it reads each source exactly once; the `anchorCache()` factory created
|
|
67
|
+
* per `checkRepository` call is the precedent.
|
|
68
|
+
*/
|
|
69
|
+
export type TargetProbe = (absPath: string) => {
|
|
70
|
+
exists: boolean;
|
|
71
|
+
real?: string;
|
|
72
|
+
};
|
|
73
|
+
export declare function targetProbeCache(): TargetProbe;
|
|
74
|
+
/** Every git-visible file (tracked + untracked-not-ignored), absolute and sorted. */
|
|
75
|
+
export declare function collectAllFiles(root: string, git?: GitLsFiles): string[];
|
|
76
|
+
/** Repo-authored Markdown documents whose outbound references are checked. */
|
|
77
|
+
export declare function collectMarkdownSources(root: string, git?: GitLsFiles): string[];
|
|
78
|
+
/** Canonical repository root used for reports and containment. */
|
|
79
|
+
export declare function repositoryRoot(root: string): string;
|
|
80
|
+
/** Extract every Markdown link/image/definition in document order. */
|
|
81
|
+
export declare function extractReferences(source: string): LinkReference[];
|
|
82
|
+
/**
|
|
83
|
+
* Resolve one reference to an absolute path — the single resolution seam for
|
|
84
|
+
* `checkRepository`. External targets are ignored; a fragment on an empty path
|
|
85
|
+
* resolves to the source file; document-relative targets resolve against the
|
|
86
|
+
* source directory (`/` is skipped, never root-relative). `sourceFile` is an
|
|
87
|
+
* absolute path (resolution base is `dirname(sourceFile)`); `root` bounds the
|
|
88
|
+
* containment check. The optional `probe`
|
|
89
|
+
* is a per-scan existence/realpath cache (`targetProbeCache`); absent = direct
|
|
90
|
+
* syscalls per reference (the behavior every caller outside a full scan keeps).
|
|
91
|
+
*/
|
|
92
|
+
export declare function resolveReference(reference: LinkReference, sourceFile: string, root: string, probe?: TargetProbe): Resolution;
|
|
93
|
+
/**
|
|
94
|
+
* Lexical variant of `resolveReference` for post-hoc repair: resolves the same
|
|
95
|
+
* URL grammar (external skip, fragment-on-empty-path, percent decoding) but
|
|
96
|
+
* never gates on `existsSync` — the referenced old-path targets are already
|
|
97
|
+
* physically gone, so existence would silently drop every in-link. The caller
|
|
98
|
+
* judges relevance lexically (`pathInside(oldAbs, …)`).
|
|
99
|
+
*/
|
|
100
|
+
export declare function resolveReferenceLexically(reference: LinkReference, sourceFile: string): Resolution;
|
|
101
|
+
/**
|
|
102
|
+
* Canonical attribution key: absolute, `/`-separated, `.`/`..` resolved via
|
|
103
|
+
* `resolve`. Lexical only — symlink / parent-traversal filesystem identity and
|
|
104
|
+
* case folding are out of scope (the file-history path-identity boundary).
|
|
105
|
+
* Both the predicate seam below and the gate shim canonicalize through this
|
|
106
|
+
* one function, so `Set.has` membership between the change set and the scan's
|
|
107
|
+
* `sourceFile`/`targetAbs` is exact.
|
|
108
|
+
*/
|
|
109
|
+
export declare function canonicalPath(p: string, base: string): string;
|
|
110
|
+
/** Optional predicate seam on `checkRepository` (policy-free mechanism). */
|
|
111
|
+
export interface CheckRepositoryOptions {
|
|
112
|
+
/**
|
|
113
|
+
* Keep only violations the predicate accepts. `sourceFile` is the canonical
|
|
114
|
+
* absolute path of the source document (the file carrying the reference);
|
|
115
|
+
* `targetAbs` is the canonical absolute resolved target path, present when
|
|
116
|
+
* the target exists inside the repository — undefined for
|
|
117
|
+
* `target does not exist` and `outside repository`. Absent predicate = keep
|
|
118
|
+
* all (identical to the previous behavior).
|
|
119
|
+
*/
|
|
120
|
+
include?: (sourceFile: string, targetAbs?: string) => boolean;
|
|
121
|
+
}
|
|
122
|
+
/** Check every git-visible Markdown source in `root` and return deterministic violations. */
|
|
123
|
+
export declare function checkRepository(root: string, options?: CheckRepositoryOptions): LinkViolation[];
|
|
124
|
+
/** Options for `enumerateWikiCandidates`. */
|
|
125
|
+
export interface WikiCandidateOptions {
|
|
126
|
+
/**
|
|
127
|
+
* Extensions appended to the target when matching (default `['.md']` —
|
|
128
|
+
* `[[note]]` hits `note.md`). A target already carrying an extension
|
|
129
|
+
* matches literally; `[]` matches literally only.
|
|
130
|
+
*/
|
|
131
|
+
extensions?: readonly string[];
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Enumerate every file-universe candidate for one wiki target — the shared
|
|
135
|
+
* substrate every wiki host builds its resolution on: suffix matching over
|
|
136
|
+
* the whole universe (a bare name matches that basename anywhere; a slashed
|
|
137
|
+
* target matches that path suffix), with extension flexibility. All matches
|
|
138
|
+
* return, sorted and deduplicated — adjudication (zero candidates = missing,
|
|
139
|
+
* several = ambiguous, which one wins) is host policy and stays with the
|
|
140
|
+
* caller. Matching is byte-exact and case-sensitive; a host that folds case
|
|
141
|
+
* normalizes both sides itself before calling.
|
|
142
|
+
*/
|
|
143
|
+
export declare function enumerateWikiCandidates(target: string, files: readonly string[], options?: WikiCandidateOptions): string[];
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve layer: turns extracted references into existence verdicts over a
|
|
3
|
+
* git worktree. Semantics: `//`, `/`, and scheme targets are skipped; a
|
|
4
|
+
* Windows drive (`D:/…`) is a local absolute path, resolved and judged like
|
|
5
|
+
* any internal target; a `#fragment` on an empty path resolves to the
|
|
6
|
+
* source file; document-relative targets resolve against the source
|
|
7
|
+
* directory; malformed `%zz` stays raw (fail-closed, the link reports
|
|
8
|
+
* broken rather than crashing). Extraction walks the mdast AST, not a regex
|
|
9
|
+
* state machine; anchors come from `anchors.ts`. Wiki targets are not
|
|
10
|
+
* document-relative — they enumerate over the whole file universe
|
|
11
|
+
* (`enumerateWikiCandidates`); their extraction lives in the markdown seam
|
|
12
|
+
* (`scanWikiLinks`).
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
15
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
16
|
+
import { anchorCache } from './anchors.js';
|
|
17
|
+
import { gitLinkPaths, gitLsFiles, gitTopLevel } from './git.js';
|
|
18
|
+
import { markdownDestination, markdownLabel, parseMarkdown, visitMarkdown, isWindowsDriveUrl } from './markdown.js';
|
|
19
|
+
/** Stable reason strings the doc-link gate branches its remedy on — reword here, never in the gate. */
|
|
20
|
+
export const REASON_ANCHOR_MISSING = 'anchor does not exist';
|
|
21
|
+
/** Whether `target` is at or below `root` (lexical containment). */
|
|
22
|
+
export function pathInside(root, target) {
|
|
23
|
+
const rel = relative(root, target);
|
|
24
|
+
return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel));
|
|
25
|
+
}
|
|
26
|
+
/** POSIX form of a root-relative path; keeps reports deterministic across platforms. */
|
|
27
|
+
export function posixRelative(root, target) {
|
|
28
|
+
return relative(root, target).split(sep).join('/');
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Memoized `realpathSync` for the repository root. `existingPathInside` runs
|
|
32
|
+
* once per repository-inside reference, and an uncached root realpath turned
|
|
33
|
+
* that into thousands of redundant syscalls on Windows (~1s on a 3.8k-link
|
|
34
|
+
* scan). The worktree root never moves within a session — same caching
|
|
35
|
+
* premise as `gitTopLevel`'s memo — so one resolution per distinct root input
|
|
36
|
+
* is safe; a different input path gets its own key.
|
|
37
|
+
*/
|
|
38
|
+
const realRootCache = new Map();
|
|
39
|
+
function realRoot(root) {
|
|
40
|
+
const key = resolve(root);
|
|
41
|
+
const cached = realRootCache.get(key);
|
|
42
|
+
if (cached !== undefined)
|
|
43
|
+
return cached;
|
|
44
|
+
const real = realpathSync(root);
|
|
45
|
+
// Register under both the input path and the real path so a later call with
|
|
46
|
+
// either form hits the same entry.
|
|
47
|
+
realRootCache.set(key, real);
|
|
48
|
+
realRootCache.set(real, real);
|
|
49
|
+
return real;
|
|
50
|
+
}
|
|
51
|
+
function existingPathInside(root, target, probe) {
|
|
52
|
+
if (!pathInside(root, target))
|
|
53
|
+
return false;
|
|
54
|
+
const real = probe === undefined ? realpathSync(target) : probe(target).real;
|
|
55
|
+
return real !== undefined && pathInside(realRoot(root), real);
|
|
56
|
+
}
|
|
57
|
+
function temporarilyUnverifiable(root, target, probe) {
|
|
58
|
+
if (probe === undefined ? existsSync(target) : probe(target).exists)
|
|
59
|
+
return false;
|
|
60
|
+
for (const gitlink of gitLinkPaths(root)) {
|
|
61
|
+
if (pathInside(gitlink, target))
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
export function targetProbeCache() {
|
|
67
|
+
const cache = new Map();
|
|
68
|
+
return absPath => {
|
|
69
|
+
const cached = cache.get(absPath);
|
|
70
|
+
if (cached !== undefined)
|
|
71
|
+
return cached;
|
|
72
|
+
const exists = existsSync(absPath);
|
|
73
|
+
const entry = { exists, real: exists ? realpathSync(absPath) : undefined };
|
|
74
|
+
cache.set(absPath, entry);
|
|
75
|
+
return entry;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Every git-visible file (tracked + untracked-not-ignored), absolute and sorted. */
|
|
79
|
+
export function collectAllFiles(root, git = gitLsFiles) {
|
|
80
|
+
const repositoryRoot = git === gitLsFiles ? gitTopLevel(root) : root;
|
|
81
|
+
// A tracked file deleted from the working tree (still in the index until
|
|
82
|
+
// staged) is listed by `ls-files --cached` but cannot be read; filter it out
|
|
83
|
+
// so no consumer crashes on ENOENT.
|
|
84
|
+
return git(repositoryRoot)
|
|
85
|
+
.map(file => resolve(repositoryRoot, file))
|
|
86
|
+
.filter(existsSync)
|
|
87
|
+
.sort();
|
|
88
|
+
}
|
|
89
|
+
/** Repo-authored Markdown documents whose outbound references are checked. */
|
|
90
|
+
export function collectMarkdownSources(root, git = gitLsFiles) {
|
|
91
|
+
return collectAllFiles(root, git).filter(file => file.toLowerCase().endsWith('.md'));
|
|
92
|
+
}
|
|
93
|
+
/** Canonical repository root used for reports and containment. */
|
|
94
|
+
export function repositoryRoot(root) {
|
|
95
|
+
return gitTopLevel(root);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Whether a node's label is a plain single text run — the only label shape a
|
|
99
|
+
* rename may replace byte-for-byte. Definitions are keys (replacing one breaks
|
|
100
|
+
* every `[label]` usage), and markup labels carry formatting the replacement
|
|
101
|
+
* would silently drop. An image's `alt` is parsed as plain text by definition.
|
|
102
|
+
*/
|
|
103
|
+
function hasPlainLabel(node) {
|
|
104
|
+
if (node.type === 'definition')
|
|
105
|
+
return false;
|
|
106
|
+
if (node.type === 'image')
|
|
107
|
+
return true;
|
|
108
|
+
return node.children.length === 1 && node.children[0].type === 'text';
|
|
109
|
+
}
|
|
110
|
+
/** Extract every Markdown link/image/definition in document order. */
|
|
111
|
+
export function extractReferences(source) {
|
|
112
|
+
const out = [];
|
|
113
|
+
visitMarkdown(parseMarkdown(source), (node) => {
|
|
114
|
+
if (node.type !== 'link' && node.type !== 'image' && node.type !== 'definition')
|
|
115
|
+
return;
|
|
116
|
+
if (!('url' in node))
|
|
117
|
+
return;
|
|
118
|
+
const position = node.position;
|
|
119
|
+
const reference = {
|
|
120
|
+
kind: node.type,
|
|
121
|
+
line: position?.start.line ?? 0,
|
|
122
|
+
url: node.url,
|
|
123
|
+
};
|
|
124
|
+
// Byte offsets exist only for [label](dest) / [label]: dest forms that
|
|
125
|
+
// markdownDestination can locate; autolinks (<url>) and bare URLs have no
|
|
126
|
+
// destination substring to rewrite, so they carry no offsets but still resolve.
|
|
127
|
+
if (position?.start.offset !== undefined && position.end.offset !== undefined) {
|
|
128
|
+
const destinationNode = node;
|
|
129
|
+
try {
|
|
130
|
+
const destination = markdownDestination(source, destinationNode);
|
|
131
|
+
reference.start = destination.start;
|
|
132
|
+
reference.end = destination.end;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
// no byte offsets; url still resolves through resolveReference.
|
|
136
|
+
}
|
|
137
|
+
if (hasPlainLabel(destinationNode)) {
|
|
138
|
+
try {
|
|
139
|
+
reference.label = markdownLabel(source, destinationNode);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// no label range; the destination rewrite still stands on its own.
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
out.push(reference);
|
|
147
|
+
});
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
function isExternal(url) {
|
|
151
|
+
// An empty destination (`[x]()`, href "") renders as the current page —
|
|
152
|
+
// in-page class per the L0 corpus taxonomy, never a checkable or rebasable
|
|
153
|
+
// target. Skipping here also protects the lexical/rename seam from
|
|
154
|
+
// rewriting an empty destination into an explicit self-path.
|
|
155
|
+
if (url === '')
|
|
156
|
+
return true;
|
|
157
|
+
if (url.startsWith('//'))
|
|
158
|
+
return true;
|
|
159
|
+
if (url.startsWith('/'))
|
|
160
|
+
return true;
|
|
161
|
+
// A Windows drive (`D:/…`) is a local absolute path, never a scheme URL —
|
|
162
|
+
// it resolves into a target the containment check then judges.
|
|
163
|
+
if (isWindowsDriveUrl(url))
|
|
164
|
+
return false;
|
|
165
|
+
return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url);
|
|
166
|
+
}
|
|
167
|
+
function decodePart(value) {
|
|
168
|
+
try {
|
|
169
|
+
return decodeURIComponent(value);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Malformed escape names no path/anchors anyone meant; the raw text flows
|
|
173
|
+
// into the lookup and is reported missing (fail-closed).
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function pathPart(url) {
|
|
178
|
+
return decodePart(url.replace(/[#?].*$/, ''));
|
|
179
|
+
}
|
|
180
|
+
function fragmentPart(url) {
|
|
181
|
+
const hash = url.indexOf('#');
|
|
182
|
+
if (hash === -1)
|
|
183
|
+
return null;
|
|
184
|
+
return decodePart(url.slice(hash + 1).replace(/\?.*$/, ''));
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Resolve one reference to an absolute path — the single resolution seam for
|
|
188
|
+
* `checkRepository`. External targets are ignored; a fragment on an empty path
|
|
189
|
+
* resolves to the source file; document-relative targets resolve against the
|
|
190
|
+
* source directory (`/` is skipped, never root-relative). `sourceFile` is an
|
|
191
|
+
* absolute path (resolution base is `dirname(sourceFile)`); `root` bounds the
|
|
192
|
+
* containment check. The optional `probe`
|
|
193
|
+
* is a per-scan existence/realpath cache (`targetProbeCache`); absent = direct
|
|
194
|
+
* syscalls per reference (the behavior every caller outside a full scan keeps).
|
|
195
|
+
*/
|
|
196
|
+
export function resolveReference(reference, sourceFile, root, probe) {
|
|
197
|
+
const url = reference.url;
|
|
198
|
+
if (isExternal(url))
|
|
199
|
+
return { ignored: true };
|
|
200
|
+
const fragment = fragmentPart(url);
|
|
201
|
+
const target = pathPart(url);
|
|
202
|
+
const resolved = target === '' ? sourceFile : resolve(dirname(sourceFile), target);
|
|
203
|
+
const exists = probe === undefined ? existsSync(resolved) : probe(resolved).exists;
|
|
204
|
+
if (!exists) {
|
|
205
|
+
if (temporarilyUnverifiable(root, resolved, probe))
|
|
206
|
+
return { ignored: true };
|
|
207
|
+
return { reason: 'target does not exist', fragment };
|
|
208
|
+
}
|
|
209
|
+
if (!existingPathInside(root, resolved, probe))
|
|
210
|
+
return { reason: 'outside repository', fragment };
|
|
211
|
+
return { abs: resolved, fragment };
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Lexical variant of `resolveReference` for post-hoc repair: resolves the same
|
|
215
|
+
* URL grammar (external skip, fragment-on-empty-path, percent decoding) but
|
|
216
|
+
* never gates on `existsSync` — the referenced old-path targets are already
|
|
217
|
+
* physically gone, so existence would silently drop every in-link. The caller
|
|
218
|
+
* judges relevance lexically (`pathInside(oldAbs, …)`).
|
|
219
|
+
*/
|
|
220
|
+
export function resolveReferenceLexically(reference, sourceFile) {
|
|
221
|
+
const url = reference.url;
|
|
222
|
+
if (isExternal(url))
|
|
223
|
+
return { ignored: true };
|
|
224
|
+
const fragment = fragmentPart(url);
|
|
225
|
+
const target = pathPart(url);
|
|
226
|
+
const resolved = target === '' ? sourceFile : resolve(dirname(sourceFile), target);
|
|
227
|
+
return { abs: resolved, fragment };
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Canonical attribution key: absolute, `/`-separated, `.`/`..` resolved via
|
|
231
|
+
* `resolve`. Lexical only — symlink / parent-traversal filesystem identity and
|
|
232
|
+
* case folding are out of scope (the file-history path-identity boundary).
|
|
233
|
+
* Both the predicate seam below and the gate shim canonicalize through this
|
|
234
|
+
* one function, so `Set.has` membership between the change set and the scan's
|
|
235
|
+
* `sourceFile`/`targetAbs` is exact.
|
|
236
|
+
*/
|
|
237
|
+
export function canonicalPath(p, base) {
|
|
238
|
+
return resolve(base, p).split(sep).join('/');
|
|
239
|
+
}
|
|
240
|
+
/** Check every git-visible Markdown source in `root` and return deterministic violations. */
|
|
241
|
+
export function checkRepository(root, options = {}) {
|
|
242
|
+
const repoRoot = repositoryRoot(root);
|
|
243
|
+
const anchorsOf = anchorCache();
|
|
244
|
+
const probe = targetProbeCache();
|
|
245
|
+
const sources = collectMarkdownSources(repoRoot);
|
|
246
|
+
const violations = [];
|
|
247
|
+
const include = options.include;
|
|
248
|
+
for (const sourceFile of sources) {
|
|
249
|
+
const rel = posixRelative(repoRoot, sourceFile);
|
|
250
|
+
const source = readFileSync(sourceFile, 'utf8');
|
|
251
|
+
for (const reference of extractReferences(source)) {
|
|
252
|
+
const resolved = resolveReference(reference, sourceFile, repoRoot, probe);
|
|
253
|
+
if (resolved.ignored)
|
|
254
|
+
continue;
|
|
255
|
+
if (include !== undefined && !include(canonicalPath(sourceFile, repoRoot), resolved.abs === undefined ? undefined : canonicalPath(resolved.abs, repoRoot)))
|
|
256
|
+
continue;
|
|
257
|
+
if (resolved.reason) {
|
|
258
|
+
violations.push({ file: rel, line: reference.line, url: reference.url, reason: resolved.reason });
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
const fragment = resolved.fragment;
|
|
262
|
+
if (fragment != null && fragment !== '' && resolved.abs.endsWith('.md') && !anchorsOf(resolved.abs).has(fragment)) {
|
|
263
|
+
violations.push({ file: rel, line: reference.line, url: reference.url, reason: REASON_ANCHOR_MISSING, targetAbs: resolved.abs });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return violations;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Enumerate every file-universe candidate for one wiki target — the shared
|
|
271
|
+
* substrate every wiki host builds its resolution on: suffix matching over
|
|
272
|
+
* the whole universe (a bare name matches that basename anywhere; a slashed
|
|
273
|
+
* target matches that path suffix), with extension flexibility. All matches
|
|
274
|
+
* return, sorted and deduplicated — adjudication (zero candidates = missing,
|
|
275
|
+
* several = ambiguous, which one wins) is host policy and stays with the
|
|
276
|
+
* caller. Matching is byte-exact and case-sensitive; a host that folds case
|
|
277
|
+
* normalizes both sides itself before calling.
|
|
278
|
+
*/
|
|
279
|
+
export function enumerateWikiCandidates(target, files, options = {}) {
|
|
280
|
+
const normalized = target.split(/[\\/]/).join('/');
|
|
281
|
+
const suffixes = new Set([normalized]);
|
|
282
|
+
for (const extension of options.extensions ?? ['.md'])
|
|
283
|
+
suffixes.add(normalized + extension);
|
|
284
|
+
const matches = new Set();
|
|
285
|
+
for (const file of files) {
|
|
286
|
+
const path = file.split(/[\\/]/).join('/');
|
|
287
|
+
for (const suffix of suffixes) {
|
|
288
|
+
if (path === suffix || path.endsWith(`/${suffix}`)) {
|
|
289
|
+
matches.add(file);
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return [...matches].sort();
|
|
295
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** One `scheme://address` reference on the external plane, as the registry recognizes it. */
|
|
2
|
+
export interface SchemeReference {
|
|
3
|
+
/** Scheme name, lowercased (`ukp`). */
|
|
4
|
+
scheme: string;
|
|
5
|
+
/**
|
|
6
|
+
* Address after `://`: fragment stripped, percent escapes decoded,
|
|
7
|
+
* malformed escapes kept verbatim. Query stays in the address.
|
|
8
|
+
*/
|
|
9
|
+
address: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Resolution outcome for one scheme reference. The vocabulary starts
|
|
13
|
+
* ukp-shaped (endpoint-registry semantics); a future resident needing new
|
|
14
|
+
* outcome shapes widens this union — a kernel version event, never a silent
|
|
15
|
+
* reinterpretation of an existing status.
|
|
16
|
+
*/
|
|
17
|
+
export type SchemeResolution = {
|
|
18
|
+
status: 'ok';
|
|
19
|
+
}
|
|
20
|
+
/** The endpoint name is not in the registry — a dangling reference. */
|
|
21
|
+
| {
|
|
22
|
+
status: 'unknown-endpoint';
|
|
23
|
+
endpoint: string;
|
|
24
|
+
}
|
|
25
|
+
/** Local endpoint whose binding root is gone on disk — the registry snapshot is stale, a rebind is needed. */
|
|
26
|
+
| {
|
|
27
|
+
status: 'dead-binding';
|
|
28
|
+
endpoint: string;
|
|
29
|
+
}
|
|
30
|
+
/** Local endpoint live, but the referenced path under it does not exist. */
|
|
31
|
+
| {
|
|
32
|
+
status: 'missing-path';
|
|
33
|
+
endpoint: string;
|
|
34
|
+
path: string;
|
|
35
|
+
}
|
|
36
|
+
/** Registry unavailable — unchecked, downgraded to a warning. */
|
|
37
|
+
| {
|
|
38
|
+
status: 'degraded';
|
|
39
|
+
reason: string;
|
|
40
|
+
};
|
|
41
|
+
/** One registered scheme's resolution half: address in, outcome out. */
|
|
42
|
+
export type SchemeResolver = (address: string) => SchemeResolution;
|
|
43
|
+
/** Optional parameter seam: local-scheme resolvers merged over the kernel registry, overlay winning. */
|
|
44
|
+
export interface SchemeOptions {
|
|
45
|
+
resolvers?: Readonly<Record<string, SchemeResolver>>;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Recognize a registered `scheme://address` reference, or null. Null covers
|
|
49
|
+
* both non-scheme shapes and schemes no registry declared: an unregistered
|
|
50
|
+
* scheme-shaped URL is not a reference at all. The optional `resolvers`
|
|
51
|
+
* overlay registers local schemes for this call — policy flows in as a
|
|
52
|
+
* parameter, kernel residents and the overlay merge.
|
|
53
|
+
*/
|
|
54
|
+
export declare function recognizeSchemeReference(url: string, options?: SchemeOptions): SchemeReference | null;
|
|
55
|
+
/** Scheme names with a kernel-registered resolver, sorted. */
|
|
56
|
+
export declare function registeredSchemes(): string[];
|
|
57
|
+
/**
|
|
58
|
+
* Resolve one scheme address. A scheme without a resolver (never possible
|
|
59
|
+
* for kernel residents; reachable when a caller resolves a name its
|
|
60
|
+
* parameter overlay does not actually carry) returns `{ status:
|
|
61
|
+
* 'no-resolver' }` — a loud shape, never silence.
|
|
62
|
+
*/
|
|
63
|
+
export declare function resolveSchemeReference(scheme: string, address: string, options?: SchemeOptions): SchemeResolution | {
|
|
64
|
+
status: 'no-resolver';
|
|
65
|
+
};
|
|
66
|
+
/** One endpoint record as `ukp list --json` reports it. */
|
|
67
|
+
export interface UkpEndpoint {
|
|
68
|
+
name: string;
|
|
69
|
+
/** Absolute binding root for local endpoints; null for remote (ssh) ones. */
|
|
70
|
+
location: string | null;
|
|
71
|
+
remote: boolean;
|
|
72
|
+
}
|
|
73
|
+
/** A registry snapshot: available (endpoint map) or unavailable (degrade — warn, never error). */
|
|
74
|
+
export type UkpRegistry = {
|
|
75
|
+
status: 'available';
|
|
76
|
+
endpoints: Map<string, UkpEndpoint>;
|
|
77
|
+
} | {
|
|
78
|
+
status: 'unavailable';
|
|
79
|
+
reason: string;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Parse `ukp list --json` stdout into a registry snapshot. Tolerant of the
|
|
83
|
+
* envelope form (`{schema, command, endpoints: [...]}` with a structured
|
|
84
|
+
* `location` and `kind`-marked remoteness) and of contract-minimal forms
|
|
85
|
+
* (flat top-level array, flat `location` string, boolean `remote`) so
|
|
86
|
+
* earlier and later ukp builds both parse. Output that parses but carries
|
|
87
|
+
* no endpoint array is unavailability, not an empty registry — an empty
|
|
88
|
+
* registry is not a shape the CLI produces.
|
|
89
|
+
*/
|
|
90
|
+
export declare function parseUkpListJson(stdout: string): UkpRegistry;
|
|
91
|
+
/**
|
|
92
|
+
* Live fetch: one `ukp list --json -g` per process, memoized — resolution
|
|
93
|
+
* never spawns per reference. `-g` reads the whole registry, not the
|
|
94
|
+
* workspace-scoped view: whether a reference dangles is a whole-registry
|
|
95
|
+
* question, since a document may legitimately point at an endpoint outside
|
|
96
|
+
* the current workspace scope, and resolution must not inherit that scope.
|
|
97
|
+
* Builds predating the flag answer non-zero and land in the degrade path,
|
|
98
|
+
* same as no `--json`. Every failure mode — no ukp on PATH, a failed spawn,
|
|
99
|
+
* non-zero exit, unparseable output — is registry-unavailable, which
|
|
100
|
+
* downgrades resolution to a warning: a missing machine contract must not
|
|
101
|
+
* fail a repo.
|
|
102
|
+
*/
|
|
103
|
+
export declare function fetchUkpRegistry(): UkpRegistry;
|
|
104
|
+
/**
|
|
105
|
+
* ukp resolution, two tiers: endpoint existence is a registry lookup; path
|
|
106
|
+
* existence is an fs check against the binding root — never a content read.
|
|
107
|
+
* Remote (ssh) endpoints verify endpoint existence only; their paths are not
|
|
108
|
+
* locally checkable. A bare endpoint reference (`ukp://name`) has no path
|
|
109
|
+
* tier at all. Exposed against a caller-supplied snapshot so replay tests
|
|
110
|
+
* (and consumers re-judging a captured registry) never spawn.
|
|
111
|
+
*/
|
|
112
|
+
export declare function resolveUkpWith(address: string, registry: UkpRegistry): SchemeResolution;
|