|
6 | 6 |
|
7 | 7 | const UPLOAD_PATH_PATTERN = |
8 | 8 | /^\/(?:-\/project\/(\d+)|((?:[\w.-]+\/)*[\w.-]+))\/uploads\/([0-9a-f]{32})\/([^/]+)$/iu; |
9 | | -/** A link destination, an HTML `src`/`href`, or a reference definition pointing at an upload. */ |
| 9 | +/** |
| 10 | + * An inline code span, kept as written, or a link destination, HTML `src`/`href`, or reference |
| 11 | + * definition pointing at an upload. |
| 12 | + */ |
10 | 13 | const RELATIVE_UPLOAD_PATTERN = |
11 | | - /(\]\(\s*<?|\b(?:src|href)\s*=\s*["']?|^ {0,3}\[[^\]\n]+\]:\s*<?)\/uploads\/(?=[0-9a-f]{32}\/)/gimu; |
| 14 | + /(`+)[^`]*?\1|(\]\(\s*<?|\b(?:src|href)\s*=\s*["']?|^ {0,3}\[[^\]\n]+\]:\s*<?)\/uploads\/(?=[0-9a-f]{32}\/)/giu; |
| 15 | +const FENCE_PATTERN = /^\s{0,3}(`{3,}|~{3,})(.*)$/u; |
12 | 16 |
|
13 | 17 | export interface GitLabUpload { |
14 | 18 | readonly origin: string; |
@@ -65,11 +69,30 @@ export function gitlabMediaFileName(fetchUrl: string): string { |
65 | 69 | return name.length > 0 ? name : "gitlab-upload"; |
66 | 70 | } |
67 | 71 |
|
68 | | -/** Rewrites GitLab's project-relative upload links against the project's web URL. */ |
| 72 | +/** Rewrites GitLab's project-relative upload links against the project's web URL, outside code. */ |
69 | 73 | export function resolveGitLabUploadLinks(markdown: string, projectUrl: string): string { |
70 | 74 | const base = projectUrl.replace(/\/+$/u, ""); |
71 | | - return markdown.replace( |
72 | | - RELATIVE_UPLOAD_PATTERN, |
73 | | - (_, prefix: string) => `${prefix}${base}/uploads/`, |
74 | | - ); |
| 75 | + let openFence: string | null = null; |
| 76 | + return markdown |
| 77 | + .split("\n") |
| 78 | + .map((line) => { |
| 79 | + const fence = FENCE_PATTERN.exec(line); |
| 80 | + if (fence !== null) { |
| 81 | + const marker = fence[1]!; |
| 82 | + if (openFence === null) openFence = marker; |
| 83 | + else if ( |
| 84 | + marker[0] === openFence[0] && |
| 85 | + marker.length >= openFence.length && |
| 86 | + fence[2]!.trim() === "" |
| 87 | + ) { |
| 88 | + openFence = null; |
| 89 | + } |
| 90 | + return line; |
| 91 | + } |
| 92 | + if (openFence !== null) return line; |
| 93 | + return line.replace(RELATIVE_UPLOAD_PATTERN, (match, _code, prefix: string | undefined) => |
| 94 | + prefix === undefined ? match : `${prefix}${base}/uploads/`, |
| 95 | + ); |
| 96 | + }) |
| 97 | + .join("\n"); |
75 | 98 | } |
0 commit comments