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

fix: comment stripping should remove multiline comments (#279) #280

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
41 changes: 36 additions & 5 deletions src/syntax.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { promises as fsp } from "node:fs";
import { parse } from "acorn";
import { extname } from "pathe";
import { readPackageJSON } from "pkg-types";
import { ResolveOptions, resolvePath } from "./resolve";
Expand All @@ -10,8 +11,6 @@
const CJS_RE =
/([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m;

const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;

const BUILTIN_EXTENSIONS = new Set([".mjs", ".cjs", ".node", ".wasm"]);

/**
Expand All @@ -25,6 +24,38 @@
stripComments?: boolean;
};

interface TokenLocation {
start: number;
end: number;
}

function _getCommentLocations(code: string) {
const locations: TokenLocation[] = [];
parse(code, {
ecmaVersion: "latest",
allowHashBang: true,
allowAwaitOutsideFunction: true,
allowImportExportEverywhere: true,
onComment(_isBlock, _text, start, end) {
locations.push({ start, end });
},
});
return locations;
}

/**
* Strip comments from a string of source code
*
* @param code - The source code to remove comments from.
*/
export function stripComments(code: string) {
const locations = _getCommentLocations(code);
for (const location of locations.reverse()) {
code = code.slice(0, location.start) + code.slice(location.end);
}
return code;
}

/**
* Determines if a given code string contains ECMAScript module syntax.
*
Expand All @@ -37,7 +68,7 @@
opts: DetectSyntaxOptions = {},
): boolean {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
code = stripComments(code);

Check warning on line 71 in src/syntax.ts

View check run for this annotation

Codecov / codecov/patch

src/syntax.ts#L71

Added line #L71 was not covered by tests
}
return ESM_RE.test(code);
}
Expand All @@ -54,7 +85,7 @@
opts: DetectSyntaxOptions = {},
): boolean {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
code = stripComments(code);

Check warning on line 88 in src/syntax.ts

View check run for this annotation

Codecov / codecov/patch

src/syntax.ts#L88

Added line #L88 was not covered by tests
}
return CJS_RE.test(code);
}
Expand All @@ -68,7 +99,7 @@
*/
export function detectSyntax(code: string, opts: DetectSyntaxOptions = {}) {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
code = stripComments(code);
}
// We strip comments once hence not passing opts down to hasESMSyntax and hasCJSSyntax
const hasESM = hasESMSyntax(code, {});
Expand Down
25 changes: 24 additions & 1 deletion test/syntax.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { join } from "pathe";
import { describe, it, expect } from "vitest";
import { detectSyntax, isValidNodeImport } from "../src";
import { detectSyntax, isValidNodeImport, stripComments } from "../src";

const staticTests = {
// ESM
Expand Down Expand Up @@ -92,6 +92,21 @@ const staticTests = {
const staticTestsWithComments = {
'// They\'re exposed using "export import" so that types are passed along as expected\nmodule.exports={};':
{ hasESM: false, hasCJS: true, isMixed: false },
"/* export * */": { hasESM: false, hasCJS: false, isMixed: false },
"/* \n export * \n */": { hasESM: false, hasCJS: false, isMixed: false },
"/* \n export * \n */ export * from 'foo' /* \n export * \n */": {
hasESM: true,
hasCJS: false,
isMixed: false,
},
};

const commentStrippingTests = {
'// They\'re exposed using "export import" so that types are passed along as expected\nmodule.exports={};':
"\nmodule.exports={};",
"/* export * */": "",
"/* \n export * \n */": "",
"/* \n export * \n */ export * from 'foo' /* \n export * \n */": ` export * from 'foo' `,
};

describe("detectSyntax", () => {
Expand All @@ -112,6 +127,14 @@ describe("detectSyntax (with comment)", () => {
}
});

describe("stripComments", () => {
for (const [input, result] of Object.entries(commentStrippingTests)) {
it(input, () => {
expect(stripComments(input)).to.deep.equal(result);
});
}
});

const nodeImportTests = {
"node:fs": true,
fs: true,
Expand Down