| /** | |
| * @license | |
| * Copyright 2022 Google LLC | |
| * SPDX-License-Identifier: Apache-2.0 | |
| */ | |
| import {CommentLinkInfo, CommentLinks} from '../types/common'; | |
| import {getBaseUrl, sameOrigin} from './url-util'; | |
| /** | |
| * Finds links within the base string and convert them to HTML. Config-based | |
| * rewrites are only applied on text that is not linked by the default linking | |
| * library. | |
| */ | |
| export function linkifyUrlsAndApplyRewrite( | |
| base: string, | |
| repoCommentLinks: CommentLinks | |
| ): string { | |
| const rewriteResults = getRewriteResultsFromConfig(base, repoCommentLinks); | |
| return applyRewrites(base, rewriteResults); | |
| } | |
| /** | |
| * Generates a list of rewrites that would be applied to a base string. They are | |
| * not applied immediately to the base text because one rewrite may interfere or | |
| * overlap with a later rewrite. Only after all rewrites are known they are | |
| * carefully merged with `applyRewrites`. | |
| */ | |
| function getRewriteResultsFromConfig( | |
| base: string, | |
| repoCommentLinks: CommentLinks | |
| ): RewriteResult[] { | |
| const enabledRewrites = Object.values(repoCommentLinks).filter( | |
| commentLinkInfo => | |
| commentLinkInfo.enabled !== false && commentLinkInfo.link !== undefined | |
| ); | |
| return enabledRewrites.flatMap(rewrite => { | |
| const regexp = new RegExp(rewrite.match, 'g'); | |
| const partialResults: RewriteResult[] = []; | |
| let match: RegExpExecArray | null; | |
| while ((match = regexp.exec(base)) !== null) { | |
| const fullReplacementText = getReplacementText(match, rewrite); | |
| // The replacement may not be changing the entire matched substring so we | |
| // "trim" the replacement position and text to the part that is actually | |
| // different. This makes sure that unchanged portions are still eligible | |
| // for other rewrites without being rejected as overlaps during | |
| // `applyRewrites`. The new `replacementText` is not eligible for other | |
| // rewrites since it would introduce unexpected interactions between | |
| // rewrites depending on their order of definition/execution. | |
| const sharedPrefixLength = getSharedPrefixLength( | |
| match[0], | |
| fullReplacementText | |
| ); | |
| const sharedSuffixLength = getSharedSuffixLength( | |
| match[0], | |
| fullReplacementText | |
| ); | |
| const prefixIndex = sharedPrefixLength; | |
| const matchSuffixIndex = match[0].length - sharedSuffixLength; | |
| const fullReplacementSuffixIndex = | |
| fullReplacementText.length - sharedSuffixLength; | |
| partialResults.push({ | |
| replacedTextStartPosition: match.index + prefixIndex, | |
| replacedTextEndPosition: match.index + matchSuffixIndex, | |
| replacementText: fullReplacementText.substring( | |
| prefixIndex, | |
| fullReplacementSuffixIndex | |
| ), | |
| }); | |
| } | |
| return partialResults; | |
| }); | |
| } | |
| /** | |
| * Applies all the rewrites to the given base string. To resolve cases where | |
| * multiple rewrites target overlapping pieces of the base string, the rewrite | |
| * that ends latest is kept and the rest are not applied and discarded. | |
| */ | |
| function applyRewrites(base: string, rewriteResults: RewriteResult[]): string { | |
| const rewritesByEndPosition = [...rewriteResults].sort((a, b) => { | |
| if (b.replacedTextEndPosition !== a.replacedTextEndPosition) { | |
| return b.replacedTextEndPosition - a.replacedTextEndPosition; | |
| } | |
| return a.replacedTextStartPosition - b.replacedTextStartPosition; | |
| }); | |
| const filteredSortedRewrites: RewriteResult[] = []; | |
| let latestReplace = base.length; | |
| for (const rewrite of rewritesByEndPosition) { | |
| // Only accept rewrites that do not overlap with any previously accepted | |
| // rewrites. | |
| if (rewrite.replacedTextEndPosition <= latestReplace) { | |
| filteredSortedRewrites.push(rewrite); | |
| latestReplace = rewrite.replacedTextStartPosition; | |
| } | |
| } | |
| return filteredSortedRewrites.reduce( | |
| (text, rewrite) => | |
| text | |
| .substring(0, rewrite.replacedTextStartPosition) | |
| .concat(rewrite.replacementText) | |
| .concat(text.substring(rewrite.replacedTextEndPosition)), | |
| base | |
| ); | |
| } | |
| function resolveTemplate(template: string, match: RegExpExecArray): string { | |
| return template.replace(/\$(\$|&|\d+)/g, (placeholder, p1) => { | |
| if (p1 === '$') return '$'; | |
| if (p1 === '&') return match[0]; | |
| const index = parseInt(p1, 10); | |
| return index < match.length ? match[index] ?? '' : placeholder; | |
| }); | |
| } | |
| /** | |
| * For a given regexp match, apply the rewrite based on the rewrite's type and | |
| * return the resulting string. | |
| */ | |
| function getReplacementText( | |
| match: RegExpExecArray, | |
| rewrite: CommentLinkInfo | |
| ): string { | |
| const resolvedHref = resolveTemplate(rewrite.link, match); | |
| const resolvedText = resolveTemplate(rewrite.text ?? '$&', match); | |
| const resolvedPrefix = rewrite.prefix | |
| ? resolveTemplate(rewrite.prefix, match) | |
| : undefined; | |
| const resolvedSuffix = rewrite.suffix | |
| ? resolveTemplate(rewrite.suffix, match) | |
| : undefined; | |
| const replacementHref = resolvedHref.startsWith('/') | |
| ? `${getBaseUrl()}${resolvedHref}` | |
| : resolvedHref; | |
| return createLinkTemplate( | |
| replacementHref, | |
| resolvedText, | |
| resolvedPrefix, | |
| resolvedSuffix | |
| ); | |
| } | |
| function createLinkTemplate( | |
| href: string, | |
| displayText: string, | |
| prefix?: string, | |
| suffix?: string | |
| ) { | |
| const attributes = sameOrigin(href) | |
| ? '' | |
| : ' rel="noopener noreferrer" target="_blank"'; | |
| return `${prefix ?? ''}<a href="${href}"${attributes}>${displayText}</a>${ | |
| suffix ?? '' | |
| }`; | |
| } | |
| /** | |
| * Returns the number of characters that are identical at the start of both | |
| * strings. | |
| * | |
| * For example, `getSharedPrefixLength('12345678', '1234zz78')` would return 4 | |
| */ | |
| function getSharedPrefixLength(a: string, b: string) { | |
| let i = 0; | |
| for (; i < a.length && i < b.length; ++i) { | |
| if (a[i] !== b[i]) { | |
| return i; | |
| } | |
| } | |
| return i; | |
| } | |
| /** | |
| * Returns the number of characters that are identical at the end of both | |
| * strings. | |
| * | |
| * For example, `getSharedSuffixLength('12345678', '1234zz78')` would return 2 | |
| */ | |
| function getSharedSuffixLength(a: string, b: string) { | |
| let i = a.length; | |
| for (let j = b.length; i !== 0 && j !== 0; --i, --j) { | |
| if (a[i] !== b[j]) { | |
| return a.length - 1 - i; | |
| } | |
| } | |
| return a.length - i; | |
| } | |
| interface RewriteResult { | |
| replacedTextStartPosition: number; | |
| replacedTextEndPosition: number; | |
| replacementText: string; | |
| } |