Use regular imports instead of require where possible (#59017)

This commit is contained in:
Jake Bailey 2024-06-25 13:56:05 -07:00 committed by GitHub
parent e70904a24f
commit ef339af128
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 47 additions and 122 deletions

13
package-lock.json generated
View File

@ -18,6 +18,7 @@
"@esfx/canceltoken": "^1.0.0",
"@octokit/rest": "^20.1.1",
"@types/chai": "^4.3.16",
"@types/diff": "^5.2.1",
"@types/minimist": "^1.2.5",
"@types/mocha": "^10.0.6",
"@types/ms": "^0.7.34",
@ -991,6 +992,12 @@
"integrity": "sha512-PatH4iOdyh3MyWtmHVFXLWCCIhUbopaltqddG9BzB+gMIzee2MJrvd+jouii9Z3wzQJruGWAm7WOMjgfG8hQlQ==",
"dev": true
},
"node_modules/@types/diff": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/@types/diff/-/diff-5.2.1.tgz",
"integrity": "sha512-uxpcuwWJGhe2AR1g8hD9F5OYGCqjqWnBUQFD8gMZsDbv8oPHzxJF6iMO6n8Tk0AdzlxoaaoQhOYlIg/PukVU8g==",
"dev": true
},
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
@ -5008,6 +5015,12 @@
"integrity": "sha512-PatH4iOdyh3MyWtmHVFXLWCCIhUbopaltqddG9BzB+gMIzee2MJrvd+jouii9Z3wzQJruGWAm7WOMjgfG8hQlQ==",
"dev": true
},
"@types/diff": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/@types/diff/-/diff-5.2.1.tgz",
"integrity": "sha512-uxpcuwWJGhe2AR1g8hD9F5OYGCqjqWnBUQFD8gMZsDbv8oPHzxJF6iMO6n8Tk0AdzlxoaaoQhOYlIg/PukVU8g==",
"dev": true
},
"@types/istanbul-lib-coverage": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",

View File

@ -44,6 +44,7 @@
"@esfx/canceltoken": "^1.0.0",
"@octokit/rest": "^20.1.1",
"@types/chai": "^4.3.16",
"@types/diff": "^5.2.1",
"@types/minimist": "^1.2.5",
"@types/mocha": "^10.0.6",
"@types/ms": "^0.7.34",

View File

@ -1,3 +1,4 @@
import sourceMapSupport from "source-map-support";
import * as fakes from "./_namespaces/fakes.js";
import * as FourSlashInterface from "./_namespaces/FourSlashInterface.js";
import * as Harness from "./_namespaces/Harness.js";
@ -4659,22 +4660,9 @@ function runCode(code: string, state: TestState, fileName: string): void {
const generatedFile = ts.changeExtension(fileName, ".js");
const wrappedCode = `(function(ts, test, goTo, config, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled, ignoreInterpolations) {${code}\n//# sourceURL=${ts.getBaseFileName(generatedFile)}\n})`;
type SourceMapSupportModule = typeof import("source-map-support") & {
// TODO(rbuckton): This is missing from the DT definitions and needs to be added.
resetRetrieveHandlers(): void;
};
// Provide the content of the current test to 'source-map-support' so that it can give us the correct source positions
// for test failures.
let sourceMapSupportModule: SourceMapSupportModule | undefined;
try {
sourceMapSupportModule = require("source-map-support");
}
catch {
// do nothing
}
sourceMapSupportModule?.install({
sourceMapSupport.install({
retrieveFile: path => {
return path === generatedFile ? wrappedCode :
undefined!;
@ -4700,7 +4688,7 @@ function runCode(code: string, state: TestState, fileName: string): void {
throw err;
}
finally {
sourceMapSupportModule?.resetRetrieveHandlers();
sourceMapSupport.resetRetrieveHandlers();
}
}

View File

@ -1,3 +1,6 @@
import * as Diff from "diff";
import fs from "fs";
import pathModule from "path";
import * as compiler from "./_namespaces/compiler.js";
import * as documents from "./_namespaces/documents.js";
import * as fakes from "./_namespaces/fakes.js";
@ -54,14 +57,6 @@ export const virtualFileSystemRoot = "/";
function createNodeIO(): IO {
const workspaceRoot = Utils.findUpRoot();
let fs: any, pathModule: any;
if (require) {
fs = require("fs");
pathModule = require("path");
}
else {
fs = pathModule = {};
}
function deleteFile(path: string) {
try {
@ -1022,7 +1017,6 @@ export namespace Compiler {
}
else if (original.text !== doc.text) {
jsCode += `\r\n\r\n!!!! File ${Utils.removeTestPathPrefixes(doc.file)} differs from original emit in noCheck emit\r\n`;
const Diff = require("diff");
const expected = original.text;
const actual = doc.text;
const patch = Diff.createTwoFilesPatch("Expected", "Actual", expected, actual, "The full check baseline", "with noCheck set");
@ -1518,8 +1512,7 @@ export namespace Baseline {
IO.writeFile(actualFileName, encodedActual);
}
const errorMessage = getBaselineFileChangedErrorMessage(relativeFileName);
if (!!require && opts && opts.PrintDiff) {
const Diff = require("diff");
if (opts && opts.PrintDiff) {
const patch = Diff.createTwoFilesPatch("Expected", "Actual", expected, actual, "The current baseline", "The new version");
throw new Error(`${errorMessage}${ts.ForegroundColorEscapeSequences.Grey}\n\n${patch}`);
}

View File

@ -1,3 +1,4 @@
import vm from "vm";
import * as Harness from "./_namespaces/Harness.js";
import * as ts from "./_namespaces/ts.js";
@ -6,7 +7,6 @@ export function encodeString(s: string): string {
}
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
const vm = require("vm");
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, fileName);
}

View File

@ -1,3 +1,11 @@
import { fork } from "child_process";
import { statSync } from "fs";
import Mocha from "mocha";
import ms from "ms";
import os from "os";
import path from "path";
import readline from "readline";
import tty from "tty";
import {
configOption,
globalTimeout,
@ -26,20 +34,12 @@ import * as ts from "../_namespaces/ts.js";
import * as Utils from "../_namespaces/Utils.js";
export function start(importTests: () => Promise<unknown>) {
const Mocha = require("mocha") as typeof import("mocha");
const Base = Mocha.reporters.Base;
const color = Base.color;
const cursor = Base.cursor;
const ms = require("ms") as typeof import("ms");
const readline = require("readline") as typeof import("readline");
const os = require("os") as typeof import("os");
const tty = require("tty") as typeof import("tty");
const isatty = tty.isatty(1) && tty.isatty(2);
const path = require("path") as typeof import("path");
const { fork } = require("child_process") as typeof import("child_process");
const { statSync } = require("fs") as typeof import("fs");
// NOTE: paths for module and types for FailedTestReporter _do not_ line up due to our use of --outFile for run.js
// NOTE: paths for module and types for FailedTestReporter _do not_ line up when bundled
const FailedTestReporter = require(Utils.findUpFile("scripts/failed-tests.cjs")) as typeof import("../../../scripts/failed-tests.cjs");
const perfdataFileNameFragment = ".parallelperf";

View File

@ -1,3 +1,4 @@
import Mocha from "mocha";
import {
createRunner,
globalTimeout,
@ -39,9 +40,6 @@ export function start(importTests: () => Promise<unknown>) {
let exceptionsHooked = false;
hookUncaughtExceptions();
// Capitalization is aligned with the global `Mocha` namespace for typespace/namespace references.
const Mocha = require("mocha") as typeof import("mocha");
/**
* Mixin helper.
* @param base The base class constructor.

View File

@ -1,10 +1,9 @@
import * as Diff from "diff";
import * as Harness from "../_namespaces/Harness.js";
import * as ts from "../_namespaces/ts.js";
import * as Utils from "../_namespaces/Utils.js";
describe("unittests:: skipJSDocParsing", () => {
const Diff = require("diff");
const kinds = [
ts.JSDocParsingMode.ParseAll,
ts.JSDocParsingMode.ParseForTypeErrors,

View File

@ -1,3 +1,8 @@
import childProcess from "child_process";
import fs from "fs";
import net from "net";
import os from "os";
import readline from "readline";
import {
CharacterCodes,
combinePaths,
@ -9,7 +14,6 @@ import {
getDirectoryPath,
getRootLength,
LanguageServiceMode,
MapLike,
noop,
noopFileWatcher,
normalizePath,
@ -37,24 +41,6 @@ interface LogOptions {
logToFile?: boolean;
}
interface NodeChildProcess {
send(message: any, sendHandle?: any): void;
on(message: "message" | "exit", f: (m: any) => void): void;
kill(): void;
pid: number;
}
interface ReadLineOptions {
input: NodeJS.ReadableStream;
output?: NodeJS.WritableStream;
terminal?: boolean;
historySize?: number;
}
interface NodeSocket {
write(data: string, encoding: string): boolean;
}
function parseLoggingEnvironmentString(logEnvStr: string | undefined): LogOptions {
if (!logEnvStr) {
return {};
@ -123,41 +109,6 @@ function parseServerMode(): LanguageServiceMode | string | undefined {
/** @internal */
export function initializeNodeSystem(): StartInput {
const sys = Debug.checkDefined(ts.sys) as ts.server.ServerHost;
const childProcess: {
execFileSync(file: string, args: string[], options: { stdio: "ignore"; env: MapLike<string>; }): string | Buffer;
} = require("child_process");
interface Stats {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: Date;
mtime: Date;
ctime: Date;
birthtime: Date;
}
const fs: {
openSync(path: string, options: string): number;
close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void;
writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number;
statSync(path: string): Stats;
stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;
} = require("fs");
class Logger implements Logger {
private seq = 0;
@ -231,7 +182,7 @@ export function initializeNodeSystem(): StartInput {
if (this.fd >= 0) {
const buf = Buffer.from(s);
// eslint-disable-next-line no-restricted-syntax
fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null!); // TODO: GH#18217
fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null);
}
if (this.traceToConsole) {
console.warn(s);
@ -326,7 +277,7 @@ export function initializeNodeSystem(): StartInput {
let cancellationToken: ts.server.ServerCancellationToken;
try {
const factory = require("./cancellationToken");
const factory = require("./cancellationToken.js");
cancellationToken = factory(sys.args);
}
catch (e) {
@ -439,23 +390,6 @@ function parseEventPort(eventPortStr: string | undefined) {
return eventPort !== undefined && !isNaN(eventPort) ? eventPort : undefined;
}
function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken) {
const childProcess: {
fork(modulePath: string, args: string[], options?: { execArgv: string[]; env?: MapLike<string>; }): NodeChildProcess;
} = require("child_process");
const os: {
homedir?(): string;
tmpdir(): string;
} = require("os");
const net: {
connect(options: { port: number; }, onConnect?: () => void): NodeSocket;
} = require("net");
const readline: {
createInterface(options: ReadLineOptions): NodeJS.EventEmitter;
} = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
@ -463,7 +397,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger
});
class NodeTypingsInstallerAdapter extends ts.server.TypingsInstallerAdapter {
protected override installer!: NodeChildProcess;
protected override installer!: childProcess.ChildProcess;
// This number is essentially arbitrary. Processing more than one typings request
// at a time makes sense, but having too many in the pipe results in a hang
// (see https://github.com/nodejs/node/issues/7657).
@ -533,7 +467,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger
const typingsInstaller = combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typingsInstaller.js");
this.installer = childProcess.fork(typingsInstaller, args, { execArgv });
this.installer.on("message", m => this.handleMessage(m));
this.installer.on("message", m => this.handleMessage(m as any));
// We have to schedule this event to the next tick
// cause this fn will be called during
@ -550,7 +484,7 @@ function startNodeSession(options: StartSessionOptions, logger: ts.server.Logger
class IOSession extends ts.server.Session {
private eventPort: number | undefined;
private eventSocket: NodeSocket | undefined;
private eventSocket: net.Socket | undefined;
private socketEventQueue: { body: any; eventName: string; }[] | undefined;
/** No longer needed if syntax target is es6 or above. Any access to "this" before initialized will be a runtime error. */
private constructed: boolean | undefined;

View File

@ -1,3 +1,4 @@
import os from "os";
import * as ts from "../typescript/typescript.js";
import { StartInput } from "./common.js";
import { initializeNodeSystem } from "./nodeServer.js";
@ -53,4 +54,4 @@ function start({ args, logger, cancellationToken, serverMode, unknownServerMode,
}
ts.setStackTraceLimit();
start(initializeNodeSystem(), require("os").platform());
start(initializeNodeSystem(), os.platform());

View File

@ -1,3 +1,4 @@
import { execFileSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
@ -79,10 +80,8 @@ interface ExecSyncOptions {
cwd: string;
encoding: "utf-8";
}
type ExecSync = (command: string, options: ExecSyncOptions) => string;
export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInstaller {
private readonly nodeExecSync: ExecSync;
private readonly npmPath: string;
readonly typesRegistry: Map<string, MapLike<string>>;
@ -109,7 +108,6 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst
this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${ts.server.Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`);
this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation}`);
}
({ execSync: this.nodeExecSync } = require("child_process"));
this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
@ -174,7 +172,7 @@ export class NodeTypingsInstaller extends ts.server.typingsInstaller.TypingsInst
this.log.writeLine(`Exec: ${command}`);
}
try {
const stdout = this.nodeExecSync(command, { ...options, encoding: "utf-8" });
const stdout = execFileSync(command, { ...options, encoding: "utf-8" });
if (this.log.isEnabled()) {
this.log.writeLine(` Succeeded. stdout:${indent(sys.newLine, stdout)}`);
}