-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlink-extractor.ts
More file actions
196 lines (178 loc) · 5.13 KB
/
link-extractor.ts
File metadata and controls
196 lines (178 loc) · 5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkMdx from 'remark-mdx';
import { visit } from 'unist-util-visit';
import type { Link, Image } from 'mdast';
import { readFileSync } from 'fs';
/**
* Represents a link found in a markdown file
*
* @public
*/
export interface ExtractedLink {
/** Link URL or path */
url: string;
/** Link text or alt text */
text: string;
/** Source file path */
file: string;
/** Line number in source file */
line: number;
/** Link type */
type: 'link' | 'image' | 'html';
/** Whether this is an external URL */
isExternal: boolean;
/** Whether this is an anchor link */
isAnchor: boolean;
}
// ============================================================================
// Module-Private Helpers (True Privacy via ESM)
// ============================================================================
/**
* Check if a URL is external (http/https)
* Module-private helper - not exported, not accessible outside this module
*/
function isExternalUrl(url: string): boolean {
return /^https?:\/\//i.test(url);
}
/**
* Check if a URL is an anchor-only link
* Module-private helper - not exported, not accessible outside this module
*/
function isAnchorOnly(url: string): boolean {
return url.startsWith('#');
}
// ============================================================================
// Public API
// ============================================================================
/**
* Extract all links from a markdown file
*
* Extracts:
* - Markdown links: `[text](url)`
* - Images: ``
* - HTML links: `<a href="url">`
*
* @param filePath - Path to markdown file
* @returns Array of extracted links
*
* @example
* ```typescript
* const links = extractLinksFromFile('./docs/guide.md');
* links.forEach(link => {
* console.log(`${link.file}:${link.line} - ${link.url}`);
* });
* ```
*
* @public
*/
export function extractLinksFromFile(filePath: string): ExtractedLink[] {
const content = readFileSync(filePath, 'utf-8');
const links: ExtractedLink[] = [];
// Parse markdown with MDX support
const tree = unified().use(remarkParse).use(remarkMdx).parse(content);
// Extract markdown links and images
visit(tree, ['link', 'image'], (node: Link | Image, _index, _parent) => {
const url = node.url;
if (!url) return;
const position = node.position;
const line = position?.start.line || 0;
// Get link text
let text = '';
if (node.type === 'link') {
const linkNode = node as Link;
if (linkNode.children && linkNode.children.length > 0) {
const firstChild = linkNode.children[0];
if ('value' in firstChild) {
text = firstChild.value as string;
}
}
} else if (node.type === 'image') {
const imageNode = node as Image;
text = imageNode.alt || '';
}
links.push({
url,
text,
file: filePath,
line,
type: node.type === 'image' ? 'image' : 'link',
isExternal: isExternalUrl(url),
isAnchor: isAnchorOnly(url),
});
});
// Extract HTML links (basic regex for <a href="">)
// Use [^>]*? without nested \s+ to avoid catastrophic backtracking
const htmlLinkRegex = /<a\s[^>]*?href=["']([^"']+)["']/gi;
const lines = content.split('\n');
lines.forEach((lineContent, index) => {
let match;
while ((match = htmlLinkRegex.exec(lineContent)) !== null) {
const url = match[1];
links.push({
url,
text: '', // Would need HTML parsing to extract text
file: filePath,
line: index + 1,
type: 'html',
isExternal: isExternalUrl(url),
isAnchor: isAnchorOnly(url),
});
}
});
return links;
}
/**
* Extract links from multiple markdown files
*
* @param filePaths - Array of file paths
* @returns Array of all extracted links
*
* @example
* ```typescript
* const files = ['./docs/guide.md', './docs/api.md'];
* const allLinks = extractLinksFromFiles(files);
* console.log(`Found ${allLinks.length} links across ${files.length} files`);
* ```
*
* @public
*/
export function extractLinksFromFiles(filePaths: string[]): ExtractedLink[] {
const allLinks: ExtractedLink[] = [];
for (const file of filePaths) {
try {
const links = extractLinksFromFile(file);
allLinks.push(...links);
} catch (error) {
console.error(`Error extracting links from ${file}:`, error);
}
}
return allLinks;
}
/**
* Group links by type (internal, external, anchor)
*
* @param links - Array of links to group
* @returns Grouped links object
*
* @example
* ```typescript
* const grouped = groupLinksByType(links);
* console.log(`Internal: ${grouped.internal.length}`);
* console.log(`External: ${grouped.external.length}`);
* console.log(`Anchors: ${grouped.anchor.length}`);
* ```
*
* @public
*/
export function groupLinksByType(links: ExtractedLink[]): {
internal: ExtractedLink[];
external: ExtractedLink[];
anchor: ExtractedLink[];
} {
return {
internal: links.filter((l) => !l.isExternal && !l.isAnchor),
external: links.filter((l) => l.isExternal),
anchor: links.filter((l) => l.isAnchor),
};
}