Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape all regex special characters in identifiers #596

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/knip/src/typescript/getImportsAndExports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
UnresolvedImport,
} from '../types/serializable-map.js';
import { timerify } from '../util/Performance.js';
import { escapeRegex } from '../util/regex.js';
import { isStartsLikePackageName, sanitizeSpecifier } from '../util/modules.js';
import { extname, isInNodeModules } from '../util/path.js';
import { shouldIgnore } from '../util/tag.js';
Expand Down Expand Up @@ -400,7 +401,7 @@ const getImportsAndExports = (
const setRefs = (item: SerializableExport | SerializableExportMember) => {
if (!item.symbol) return;
const symbols = new Set<ts.Symbol>();
for (const match of sourceFile.text.matchAll(new RegExp(item.identifier.replace(/\$/g, '\\$'), 'g'))) {
for (const match of sourceFile.text.matchAll(new RegExp(escapeRegex(item.identifier), 'g'))) {
const isDeclaration = match.index === item.pos || match.index === item.pos + 1; // off-by-one from `stripQuotes`
if (!isDeclaration) {
// @ts-expect-error ts.getTokenAtPosition is internal fn
Expand Down
9 changes: 9 additions & 0 deletions packages/knip/src/util/regex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,12 @@ export const toRegexOrString = (value: string | RegExp) =>

export const findMatch = (haystack: undefined | (string | RegExp)[], needle: string) =>
haystack?.find(n => (typeof n === 'string' ? n === needle : n.test(needle)));

/**
* Escapes a string to be used in a regular expression.
*
* Escapes all characters that have a special meaning in regular expressions.
*/
export function escapeRegex(str: string): string {
return str.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
}