{{ message }}
Repository navigation
Expand file tree
/
Copy pathcheck-links-external.ts
More file actions
602 lines (520 loc) · 17.9 KB
/
Copy pathcheck-links-external.ts
File metadata and controls
602 lines (520 loc) · 17.9 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
// Validates external URLs in content and reusable files with caching for weekly runs.
// Usage: npm run check-links-external
// Usage: npm run check-links-external -- --max 100
// GITHUB_TOKEN creates issue reports and checks GitHub API repo URLs.
// ACTION_RUN_URL links to the action run.
// CREATE_REPORT creates an issue report when true, default false.
// REPORT_REPOSITORY sets the repository for report issues.
// CACHE_MAX_AGE_DAYS sets how long to cache URL results, default 7.
// DOMAIN_CONCURRENCY sets how many domains run concurrently, default 10.
import { program } from 'commander'
import chalk from 'chalk'
import fs from 'fs'
import { JSONFilePreset } from 'lowdb/node'
import { extractLinksFromMarkdown } from '@/links/lib/extract-links'
import {
type BrokenLink,
generateExternalLinkReport,
reportToMarkdown,
} from '@/links/lib/link-report'
import { uploadArtifact } from '@/links/scripts/upload-artifact'
import { createReportIssue, linkReports } from '@/workflows/issue-report'
import github from '@/workflows/github'
import excludedLinks from '@/links/lib/excluded-links'
import * as coreLib from '@actions/core'
const CACHE_FILE = process.env.EXTERNAL_LINK_CACHE_FILE || 'external-link-cache.json'
const CACHE_MAX_AGE_DAYS = parseInt(process.env.CACHE_MAX_AGE_DAYS || '7', 10)
const CACHE_MAX_AGE_MS = CACHE_MAX_AGE_DAYS * 24 * 60 * 60 * 1000
const REQUEST_TIMEOUT_MS = 30000
const REQUEST_DELAY_MS = 100 // Spaces requests to avoid rate limiting a single domain.
const DEFAULT_DOMAIN_CONCURRENCY = 10
const excludedLinksSet = new Set(excludedLinks.map(({ is }) => is).filter(Boolean))
const excludedLinksPrefixes = excludedLinks.map(({ startsWith }) => startsWith).filter(Boolean)
// The REST changelog sync overwrites this file with upstream absolute docs.github.com URLs, so editors cannot convert them.
const SELF_REFERENTIAL_EXEMPT_FILES = new Set([
'data/reusables/rest-api/breaking-changes-changelog.md',
])
function isExcludedLink(href: string): boolean {
if (excludedLinksSet.has(href)) return true
return excludedLinksPrefixes.some((prefix) => prefix && href.startsWith(prefix))
}
interface CacheEntry {
timestamp: number
ok: boolean
statusCode?: number
error?: string
}
interface CacheData {
urls: Record<string, CacheEntry>
}
interface LinkOccurrence {
file: string
line: number
href: string
}
// Normalizes URLs for deduplication by dropping fragments and root trailing slashes.
// Example: https://www.githubstatus.com/ becomes https://www.githubstatus.com.
function normalizeUrl(href: string): string {
const withoutFragment = href.split('#')[0]
try {
const parsed = new URL(withoutFragment)
if (parsed.pathname === '/' && !parsed.search) {
return parsed.origin
}
} catch {
// Malformed URLs stay unchanged so the checker can report them later.
}
return withoutFragment
}
function isDocsGithubUrl(url: string): boolean {
try {
return new URL(url).hostname === 'docs.github.com'
} catch {
return false
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function checkUrl(
url: string,
cache: CacheData,
): Promise<{ ok: boolean; statusCode?: number; error?: string; cached: boolean }> {
const cached = cache.urls[url]
if (cached) {
const age = Date.now() - cached.timestamp
if (age < CACHE_MAX_AGE_MS) {
return { ok: cached.ok, statusCode: cached.statusCode, error: cached.error, cached: true }
}
}
const headers = { 'User-Agent': 'GitHub-Docs-Link-Checker/1.0' }
// HEAD transfers less data, so try it before GET.
let response = await fetchWithTimeout(url, 'HEAD', headers)
// Some servers reject HEAD, so retry failing HTTP responses with GET.
if (response && !response.ok && response.status >= 400) {
response = await fetchWithTimeout(url, 'GET', headers)
}
if (!response) {
return { ok: false, error: 'Request timed out or failed', cached: false }
}
const result = {
ok: response.ok,
statusCode: response.status,
error: response.ok ? undefined : `HTTP ${response.status}`,
cached: false,
}
cache.urls[url] = {
timestamp: Date.now(),
ok: result.ok,
statusCode: result.statusCode,
error: result.error,
}
return result
}
async function fetchWithTimeout(
url: string,
method: 'HEAD' | 'GET',
headers: Record<string, string>,
): Promise<Response | null> {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
const response = await fetch(url, {
method,
signal: controller.signal,
headers,
redirect: 'follow',
})
clearTimeout(timeout)
return response
} catch {
clearTimeout(timeout)
return null
}
}
function isGithubRepoRootUrl(url: string): { owner: string; repo: string } | null {
try {
const parsed = new URL(url)
if (parsed.hostname !== 'github.com') return null
const segments = parsed.pathname.split('/').filter(Boolean)
if (segments.length === 2) return { owner: segments[0], repo: segments[1] }
} catch {
// Malformed URLs are not GitHub repo-root URLs.
}
return null
}
// GitHub repo-root URLs use the REST API to check that the repository exists and is public.
async function checkGithubRepoUrl(
url: string,
owner: string,
repo: string,
cache: CacheData,
): Promise<{
ok: boolean
statusCode?: number
error?: string
cached: boolean
fallbackAllowed?: boolean
}> {
const cached = cache.urls[url]
if (cached) {
const age = Date.now() - cached.timestamp
if (age < CACHE_MAX_AGE_MS) {
return {
ok: cached.ok,
statusCode: cached.statusCode,
error: cached.error,
cached: true,
}
}
}
const apiUrl = `https://api.github.com/repos/${owner}/${repo}`
const headers: Record<string, string> = {
'User-Agent': 'GitHub-Docs-Link-Checker/1.0',
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
}
if (process.env.GITHUB_TOKEN) {
headers['Authorization'] = `Bearer ${process.env.GITHUB_TOKEN}`
}
const controller = new AbortController()
const timeoutHandle = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
const response = await fetch(apiUrl, {
method: 'GET',
signal: controller.signal,
headers,
})
clearTimeout(timeoutHandle)
let result: {
ok: boolean
statusCode?: number
error?: string
cached: boolean
fallbackAllowed?: boolean
}
if (response.ok) {
const data = (await response.json()) as { html_url?: string; private?: boolean }
if (data.private) {
result = {
ok: false,
statusCode: response.status,
error: 'Repository is private',
cached: false,
fallbackAllowed: true,
}
} else {
result = {
ok: true,
statusCode: response.status,
cached: false,
fallbackAllowed: false,
}
}
} else {
result = {
ok: false,
statusCode: response.status,
error: `HTTP ${response.status}`,
cached: false,
fallbackAllowed: [401, 403, 404, 429].includes(response.status) || response.status >= 500,
}
}
// Cache only successful API repo checks; direct HTTP classifies non-repo URLs like github.com/settings/tokens.
if (result.ok) {
cache.urls[url] = {
timestamp: Date.now(),
ok: result.ok,
statusCode: result.statusCode,
error: result.error,
}
}
return result
} catch {
clearTimeout(timeoutHandle)
return {
ok: false,
error: 'Request timed out or failed',
cached: false,
fallbackAllowed: true,
}
}
}
async function extractAllExternalLinks(): Promise<Map<string, LinkOccurrence[]>> {
const links = new Map<string, LinkOccurrence[]>()
const files = await Array.fromAsync(
// Generated CodeQL query tables add hundreds of codeql.github.com URLs that editors cannot fix by hand.
fs.promises.glob(['content/**/*.md', 'data/reusables/**/*.md'], {
exclude: ['**/README.md', 'data/reusables/**/codeql-query-tables/**'],
}),
)
console.log(`Found ${files.length} Markdown files to scan`)
const extractStart = Date.now()
for (let i = 0; i < files.length; i++) {
const file = files[i]
const fileStart = Date.now()
const content = fs.readFileSync(file, 'utf-8')
const result = extractLinksFromMarkdown(content)
const fileMs = Date.now() - fileStart
// A slow file may mean a pathological regex in the extractor.
if (fileMs > 1000) {
console.warn(` ⚠️ Slow extraction: ${file} took ${(fileMs / 1000).toFixed(1)}s`)
}
for (const link of result.externalLinks) {
if (!link.href.startsWith('https://')) continue
if (isExcludedLink(link.href)) continue
const url = normalizeUrl(link.href)
if (!links.has(url)) {
links.set(url, [])
}
links.get(url)!.push({ file, line: link.line, href: link.href })
}
if ((i + 1) % 500 === 0) {
const elapsed = ((Date.now() - extractStart) / 1000).toFixed(0)
console.log(` Scanned ${i + 1}/${files.length} files (${elapsed}s elapsed)`)
}
}
const totalElapsed = ((Date.now() - extractStart) / 1000).toFixed(1)
console.log(`Extraction complete in ${totalElapsed}s`)
return links
}
async function main() {
program
.name('check-links-external')
.description('External link checker with caching')
.option('--max <number>', 'Maximum number of URLs to check', parseInt)
.option(
'--domain-concurrency <number>',
'Number of domains to process concurrently',
String(DEFAULT_DOMAIN_CONCURRENCY),
)
.option('--verbose', 'Verbose output')
.option('--dry-run', "Extract links but don't check them")
.parse()
const options = program.opts()
const startTime = Date.now()
console.log(chalk.blue('🌐 External Link Checker'))
console.log('')
const defaultData: CacheData = { urls: {} }
const db = await JSONFilePreset<CacheData>(CACHE_FILE, defaultData)
await db.read()
const now = Date.now()
let freshCount = 0
let staleCount = 0
for (const entry of Object.values(db.data.urls)) {
if (now - entry.timestamp < CACHE_MAX_AGE_MS) {
freshCount++
} else {
staleCount++
}
}
console.log(`Cache: ${freshCount} fresh, ${staleCount} stale entries`)
console.log('')
console.log('Extracting external links from content and reusable files...')
const allLinks = await extractAllExternalLinks()
// Report docs.github.com links separately because they can become internal links.
const selfReferentialLinks = new Map<string, LinkOccurrence[]>()
for (const [url, occurrences] of allLinks) {
if (isDocsGithubUrl(url)) {
const convertible = occurrences.filter((occ) => !SELF_REFERENTIAL_EXEMPT_FILES.has(occ.file))
if (convertible.length > 0) selfReferentialLinks.set(url, convertible)
allLinks.delete(url)
}
}
console.log(`Found ${allLinks.size} unique external URLs`)
console.log(`Found ${selfReferentialLinks.size} self-referential docs.github.com URLs`)
console.log('')
if (options.dryRun) {
console.log('Dry run mode - not checking URLs')
const sample = Array.from(allLinks.keys()).slice(0, 20)
for (const url of sample) {
console.log(` ${url}`)
}
if (allLinks.size > 20) {
console.log(` ... and ${allLinks.size - 20} more`)
}
process.exit(0)
}
const brokenLinks: BrokenLink[] = []
let checkedCount = 0
let cachedCount = 0
const urls = Array.from(allLinks.keys())
const maxUrls = options.max ? Math.min(options.max, urls.length) : urls.length
const domainConcurrency = Math.max(
1,
parseInt(process.env.DOMAIN_CONCURRENCY || options.domainConcurrency, 10),
)
let malformedCount = 0
// Group by hostname to check domains in parallel without overlapping requests to one domain.
const urlsByDomain = new Map<string, string[]>()
for (let i = 0; i < maxUrls; i++) {
const url = urls[i]
try {
const hostname = new URL(url).hostname
if (!urlsByDomain.has(hostname)) urlsByDomain.set(hostname, [])
urlsByDomain.get(hostname)!.push(url)
} catch {
malformedCount++
checkedCount++
const occurrences = allLinks.get(url)!
for (const occ of occurrences) {
brokenLinks.push({
href: occ.href,
file: occ.file,
lines: [occ.line],
errorMessage: 'Malformed URL',
})
}
}
}
const queuedUrlCount = Array.from(urlsByDomain.values()).reduce(
(count, domainUrls) => count + domainUrls.length,
0,
)
const plannedTotal = queuedUrlCount + malformedCount
console.log(
`Checking ${plannedTotal} URLs across ${urlsByDomain.size} domains (up to ${domainConcurrency} domains at once)...`,
)
// One domain runs sequentially to respect REQUEST_DELAY_MS.
async function checkDomainUrls(domainUrls: string[]): Promise<void> {
for (const url of domainUrls) {
const occurrences = allLinks.get(url)!
const repoInfo = isGithubRepoRootUrl(url)
let result: {
ok: boolean
statusCode?: number
error?: string
cached: boolean
fallbackAllowed?: boolean
}
if (repoInfo && process.env.GITHUB_TOKEN) {
result = await checkGithubRepoUrl(url, repoInfo.owner, repoInfo.repo, db.data)
// Fall back to direct HTTP for API, network, or private-repo failures.
if (!result.ok && result.fallbackAllowed) {
result = await checkUrl(url, db.data)
}
} else {
result = await checkUrl(url, db.data)
}
checkedCount++
if (result.cached) cachedCount++
if (!result.ok) {
for (const occ of occurrences) {
brokenLinks.push({
href: url,
file: occ.file,
lines: [occ.line],
statusCode: result.statusCode,
errorMessage: result.error,
})
}
if (options.verbose) {
console.log(` ❌ ${url} - ${result.error || `HTTP ${result.statusCode}`}`)
}
} else if (options.verbose && !result.cached) {
console.log(` ✅ ${url}`)
}
if (checkedCount % 100 === 0) {
const elapsed = ((Date.now() - startTime) / 1000).toFixed(0)
const rate = (checkedCount / (Date.now() - startTime)) * 1000 * 60
const remaining = plannedTotal - checkedCount
const etaMin = (remaining / rate).toFixed(0)
console.log(
` Checked ${checkedCount}/${plannedTotal} URLs (${cachedCount} cached) — ${elapsed}s elapsed, ~${etaMin}m remaining`,
)
}
if (!result.cached) {
await sleep(REQUEST_DELAY_MS)
}
}
}
// Round-robin domains across workers for parallelism without overlapping one domain.
const domainQueues = Array.from(urlsByDomain.values())
const workers: string[][][] = Array.from({ length: domainConcurrency }, () => [])
for (let i = 0; i < domainQueues.length; i++) {
workers[i % domainConcurrency].push(domainQueues[i])
}
async function runWorker(workerDomains: string[][]): Promise<void> {
for (const domainUrls of workerDomains) {
await checkDomainUrls(domainUrls)
}
}
await Promise.all(workers.map(runWorker))
await db.write()
const duration = ((Date.now() - startTime) / 1000).toFixed(1)
console.log('')
console.log(
chalk.blue(`Checked ${checkedCount} URLs in ${duration}s (${cachedCount} from cache)`),
)
const selfReferentialBrokenLinks: BrokenLink[] = []
for (const occurrences of selfReferentialLinks.values()) {
for (const occ of occurrences) {
selfReferentialBrokenLinks.push({ href: occ.href, file: occ.file, lines: [occ.line] })
}
}
if (brokenLinks.length === 0 && selfReferentialBrokenLinks.length === 0) {
console.log(chalk.green('✅ All external links valid!'))
process.exit(0)
}
const report = generateExternalLinkReport(brokenLinks, {
actionUrl: process.env.ACTION_RUN_URL,
selfReferentialLinks: selfReferentialBrokenLinks,
})
if (brokenLinks.length === 0) {
console.log(chalk.green('✅ All external links valid!'))
console.log(
chalk.blue(
`ℹ️ Found ${selfReferentialBrokenLinks.length} docs.github.com absolute link occurrence(s) to convert.`,
),
)
} else {
console.log('')
console.log(chalk.red(`❌ ${report.uniqueTargets} domain(s) with broken links`))
console.log(chalk.red(` ${report.totalOccurrences} total occurrence(s)`))
console.log('')
console.log('Broken links by domain:')
for (const group of report.groups.slice(0, 10)) {
console.log(` ${group.target}: ${group.occurrences.length} occurrence(s)`)
}
if (report.groups.length > 10) {
console.log(` ... and ${report.groups.length - 10} more domains`)
}
}
const markdown = reportToMarkdown(report, true)
await uploadArtifact('external-link-report.md', markdown)
await uploadArtifact('external-link-report.json', JSON.stringify(report, null, 2))
const createReport = process.env.CREATE_REPORT === 'true'
const reportRepository = process.env.REPORT_REPOSITORY || 'github/docs-content'
if (brokenLinks.length > 0 && createReport && process.env.GITHUB_TOKEN) {
console.log('')
console.log('Creating issue report...')
const octokit = github()
const reportLabel = process.env.REPORT_LABEL || 'broken link report'
const reportAuthor = process.env.REPORT_AUTHOR || 'docs-bot'
const newReport = await createReportIssue({
core: coreLib,
octokit,
reportTitle: report.title,
reportBody: markdown,
reportRepository,
reportLabel,
})
await linkReports({
core: coreLib,
octokit,
newReport,
reportRepository,
reportAuthor,
reportLabel,
})
console.log(`Created report issue: ${newReport.html_url}`)
}
}
;(async () => {
try {
await main()
} catch (err: unknown) {
console.error('Fatal error:', err)
process.exit(1)
}
})()
You can’t perform that action at this time.
