ts-checker-rspack-plugin 1.7.1 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1552,6 +1552,8 @@ var __webpack_exports__ = {};
1552
1552
  }
1553
1553
  });
1554
1554
  }
1555
+ const external_node_fs_namespaceObject = require("node:fs");
1556
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
1555
1557
  const external_chokidar_namespaceObject = require("chokidar");
1556
1558
  var external_chokidar_default = /*#__PURE__*/ __webpack_require__.n(external_chokidar_namespaceObject);
1557
1559
  const balanced = (a, b, str)=>{
@@ -3323,217 +3325,529 @@ var __webpack_exports__ = {};
3323
3325
  if ((0, external_node_path_namespaceObject.isAbsolute)(relativePart)) return false;
3324
3326
  return true;
3325
3327
  }
3326
- function _define_property(obj, key, value) {
3327
- if (key in obj) Object.defineProperty(obj, key, {
3328
- value: value,
3329
- enumerable: true,
3330
- configurable: true,
3331
- writable: true
3332
- });
3333
- else obj[key] = value;
3334
- return obj;
3335
- }
3336
- const BUILTIN_IGNORED_DIRS = [
3337
- '.git'
3338
- ];
3339
- function createIsIgnored(ignored, excluded) {
3340
- const ignoredPatterns = ignored ? Array.isArray(ignored) ? [
3341
- ...ignored
3342
- ] : [
3343
- ignored
3344
- ] : [];
3345
- const filteredExcluded = excluded.filter((pattern)=>{
3346
- if (is_glob_default()(pattern)) {
3347
- const shouldAppendStar = pattern.includes('**') && !pattern.endsWith('*');
3348
- if (shouldAppendStar) ignoredPatterns.push(pattern.endsWith('/') ? `${pattern}**` : `${pattern}/**`);
3349
- else ignoredPatterns.push(pattern);
3350
- return false;
3351
- }
3352
- return true;
3353
- });
3354
- const ignoredFunctions = ignoredPatterns.map((pattern)=>{
3355
- if ('string' == typeof pattern) return (path)=>minimatch(path, pattern);
3356
- else if (pattern instanceof RegExp) return (path)=>pattern.test(path);
3357
- else if ('function' == typeof pattern) return pattern;
3358
- else return ()=>false;
3359
- });
3360
- ignoredFunctions.push((path)=>filteredExcluded.some((excludedPath)=>isInsideAnotherPath(excludedPath, path)));
3361
- ignoredFunctions.push((path)=>BUILTIN_IGNORED_DIRS.some((ignoredDir)=>path.includes(`/${ignoredDir}/`) || path.includes(`\\${ignoredDir}\\`)));
3362
- return function(path) {
3363
- return ignoredFunctions.some((ignoredFunction)=>ignoredFunction(path));
3364
- };
3365
- }
3366
- class InclusiveNodeWatchFileSystem {
3367
- get watcher() {
3368
- return this.watchFileSystem.watcher || this.watchFileSystem.wfs?.watcher;
3328
+ const external_node_child_process_namespaceObject = require("node:child_process");
3329
+ const external_node_url_namespaceObject = require("node:url");
3330
+ const external_node_util_namespaceObject = require("node:util");
3331
+ class AbortError extends Error {
3332
+ static throwIfAborted(signal) {
3333
+ if (signal?.aborted) throw new AbortError();
3369
3334
  }
3370
- constructor(watchFileSystem, compiler, pluginState){
3371
- _define_property(this, "watchFileSystem", void 0);
3372
- _define_property(this, "compiler", void 0);
3373
- _define_property(this, "pluginState", void 0);
3374
- _define_property(this, "dirsWatchers", void 0);
3375
- _define_property(this, "paused", void 0);
3376
- _define_property(this, "deletedFiles", void 0);
3377
- _define_property(this, "watch", void 0);
3378
- this.watchFileSystem = watchFileSystem;
3379
- this.compiler = compiler;
3380
- this.pluginState = pluginState;
3381
- this.paused = true;
3382
- this.watch = (files, dirs, missing, startTime, options, callback, callbackUndelayed)=>{
3383
- const { debug } = getInfrastructureLogger(this.compiler);
3384
- clearFilesChange(this.compiler);
3385
- const isIgnored = createIsIgnored(options?.ignored, this.pluginState.lastDependencies?.excluded || []);
3386
- const standardWatcher = this.watchFileSystem.watch(files, dirs, missing, startTime, options, callback, callbackUndelayed);
3387
- this.watcher?.on('change', (file)=>{
3388
- if ('string' != typeof file) return;
3389
- if (isIgnored(file)) debug("Detected file change but it's ignored", file);
3390
- else {
3391
- debug('Detected file change', file);
3392
- this.deletedFiles.delete(file);
3393
- updateFilesChange(this.compiler, {
3394
- changedFiles: [
3395
- file
3396
- ]
3397
- });
3398
- }
3399
- });
3400
- this.watcher?.on('remove', (file)=>{
3401
- if ('string' != typeof file) return;
3402
- if (this.deletedFiles.has(file)) return void debug('Skipping duplicated remove event.');
3403
- if (isIgnored(file)) debug("Detected file remove but it's ignored", file);
3404
- else {
3405
- debug('Detected file remove', file);
3406
- this.deletedFiles.add(file);
3407
- updateFilesChange(this.compiler, {
3408
- deletedFiles: [
3409
- file
3410
- ]
3411
- });
3412
- }
3413
- });
3414
- const prevDirs = Array.from(this.dirsWatchers.keys());
3415
- const nextDirs = Array.from(this.pluginState.lastDependencies?.dirs || []);
3416
- const dirsToUnwatch = prevDirs.filter((prevDir)=>!nextDirs.includes(prevDir));
3417
- const dirsToWatch = nextDirs.filter((nextDir)=>!prevDirs.includes(nextDir) && !isIgnored(nextDir));
3418
- dirsToUnwatch.forEach((dirToUnwatch)=>{
3419
- this.dirsWatchers.get(dirToUnwatch)?.close();
3420
- this.dirsWatchers.delete(dirToUnwatch);
3421
- });
3422
- dirsToWatch.forEach((dirToWatch)=>{
3423
- const interval = 'number' == typeof options?.poll ? options.poll : void 0;
3424
- const dirWatcher = external_chokidar_default().watch(dirToWatch, {
3425
- ignoreInitial: true,
3426
- ignorePermissionErrors: true,
3427
- ignored: (path)=>isIgnored(path),
3428
- usePolling: options?.poll ? true : void 0,
3429
- ...void 0 !== interval && {
3430
- interval,
3431
- binaryInterval: interval
3432
- },
3433
- alwaysStat: true,
3434
- atomic: true,
3435
- awaitWriteFinish: true
3436
- });
3437
- dirWatcher.on('add', (file, stats)=>{
3438
- if (this.paused) return;
3439
- const extension = (0, external_node_path_namespaceObject.extname)(file);
3440
- const supportedExtensions = this.pluginState.lastDependencies?.extensions || [];
3441
- if (!supportedExtensions.includes(extension)) return void debug('Detected new file add but extension is not supported', file);
3442
- debug('Detected new file add', file);
3443
- this.deletedFiles.delete(file);
3444
- updateFilesChange(this.compiler, {
3445
- changedFiles: [
3446
- file
3447
- ]
3448
- });
3449
- this.watcher?._onChange(file, stats?.mtimeMs || stats?.ctimeMs || 1, file, 'rename');
3450
- });
3451
- dirWatcher.on('unlink', (file)=>{
3452
- if (this.paused) return;
3453
- const extension = (0, external_node_path_namespaceObject.extname)(file);
3454
- const supportedExtensions = this.pluginState.lastDependencies?.extensions || [];
3455
- if (!supportedExtensions.includes(extension)) return void debug('Detected new file remove but extension is not supported', file);
3456
- if (this.deletedFiles.has(file)) return void debug('Skipping duplicated unlink event.');
3457
- debug('Detected new file remove', file);
3458
- this.deletedFiles.add(file);
3459
- updateFilesChange(this.compiler, {
3460
- deletedFiles: [
3461
- file
3462
- ]
3463
- });
3464
- this.watcher?._onRemove(dirToWatch, file, 'rename');
3465
- });
3466
- this.dirsWatchers.set(dirToWatch, dirWatcher);
3467
- });
3468
- this.paused = false;
3469
- return {
3470
- ...standardWatcher,
3471
- close: ()=>{
3472
- clearFilesChange(this.compiler);
3473
- if (standardWatcher) standardWatcher.close();
3474
- this.dirsWatchers.forEach((dirWatcher)=>{
3475
- dirWatcher?.close();
3476
- });
3477
- this.dirsWatchers.clear();
3478
- this.paused = true;
3479
- },
3480
- pause: ()=>{
3481
- if (standardWatcher) standardWatcher.pause();
3482
- this.paused = true;
3483
- }
3484
- };
3485
- };
3486
- this.dirsWatchers = new Map();
3487
- this.deletedFiles = new Set();
3335
+ constructor(message = 'Task aborted.'){
3336
+ super(message);
3337
+ this.name = 'AbortError';
3488
3338
  }
3489
3339
  }
3490
- function tapAfterEnvironmentToPatchWatching(compiler, state) {
3491
- const { debug } = getInfrastructureLogger(compiler);
3492
- compiler.hooks.afterEnvironment.tap('TsCheckerRspackPlugin', ()=>{
3493
- const watchFileSystem = compiler.watchFileSystem;
3494
- if (watchFileSystem) {
3495
- debug("Overwriting Rspack's watch file system.");
3496
- compiler.watchFileSystem = new InclusiveNodeWatchFileSystem(watchFileSystem, compiler, state);
3497
- } else debug('No watch file system found - plugin may not work correctly.');
3498
- });
3340
+ const TYPESCRIPT_PACKAGE = "typescript";
3341
+ const TYPESCRIPT_PACKAGE_JSON = `${TYPESCRIPT_PACKAGE}/package.json`;
3342
+ const TYPESCRIPT_PREVIEW_PACKAGE = "@typescript/native-preview";
3343
+ const TYPESCRIPT_PREVIEW_PACKAGE_JSON = `${TYPESCRIPT_PREVIEW_PACKAGE}/package.json`;
3344
+ function resolveTypeScriptGoPackageJsonPath(config) {
3345
+ if (!external_node_path_default().isAbsolute(config.typescriptPath) || 'package.json' !== external_node_path_default().basename(config.typescriptPath)) throw new Error("The typescriptPath option must be an absolute path to a package.json file when tsgo is enabled.");
3346
+ if (!config.tsgoPackage) throw new Error(`The typescriptPath option must point to "${TYPESCRIPT_PREVIEW_PACKAGE_JSON}" or "${TYPESCRIPT_PACKAGE}@>=7".`);
3347
+ return config.typescriptPath;
3499
3348
  }
3500
- var external_picocolors_ = __webpack_require__("picocolors");
3501
- var external_picocolors_default = /*#__PURE__*/ __webpack_require__.n(external_picocolors_);
3502
- const lite_tapable_namespaceObject = require("@rspack/lite-tapable");
3503
- const compilerHookMap = new WeakMap();
3504
- function createPluginHooks() {
3349
+ async function resolveTypeScriptGoNativeExecutablePath(packageJsonPath, packageName) {
3350
+ const getExePathPath = external_node_path_default().resolve(external_node_path_default().dirname(packageJsonPath), './lib/getExePath.js');
3351
+ const getExePathUrl = (0, external_node_url_namespaceObject.pathToFileURL)(getExePathPath).href;
3352
+ const getExePathModule = await import(getExePathUrl);
3353
+ const getExePath = getExePathModule.default || getExePathModule.getExePath;
3354
+ if ('function' != typeof getExePath) throw new Error(`Cannot resolve the native TypeScript executable from "${packageName}".`);
3355
+ const executablePath = getExePath();
3356
+ if ('string' != typeof executablePath || !external_node_fs_default().existsSync(executablePath)) throw new Error('Executable not found');
3357
+ return executablePath;
3358
+ }
3359
+ async function resolveTypeScriptGoBinPath(config) {
3360
+ const packageJsonPath = resolveTypeScriptGoPackageJsonPath(config);
3361
+ if ("typescript" === config.tsgoPackage) return resolveTypeScriptGoNativeExecutablePath(packageJsonPath, TYPESCRIPT_PACKAGE);
3362
+ return resolveTypeScriptGoNativeExecutablePath(packageJsonPath, TYPESCRIPT_PREVIEW_PACKAGE);
3363
+ }
3364
+ async function resolveTypeScriptGoExecutable(config) {
3365
+ const binPath = await resolveTypeScriptGoBinPath(config);
3505
3366
  return {
3506
- start: new lite_tapable_namespaceObject.AsyncSeriesWaterfallHook([
3507
- 'change',
3508
- 'compilation'
3509
- ]),
3510
- waiting: new lite_tapable_namespaceObject.SyncHook([
3511
- 'compilation'
3512
- ]),
3513
- canceled: new lite_tapable_namespaceObject.SyncHook([
3514
- 'compilation'
3515
- ]),
3516
- error: new lite_tapable_namespaceObject.SyncHook([
3517
- 'error',
3518
- 'compilation'
3519
- ]),
3520
- issues: new lite_tapable_namespaceObject.SyncWaterfallHook([
3521
- 'issues',
3522
- 'compilation'
3523
- ])
3367
+ command: binPath,
3368
+ args: []
3524
3369
  };
3525
3370
  }
3526
- function forwardPluginHooks(source, target) {
3527
- source.start.tapPromise('TsCheckerRspackPlugin', target.start.promise);
3528
- source.waiting.tap('TsCheckerRspackPlugin', target.waiting.call);
3529
- source.canceled.tap('TsCheckerRspackPlugin', target.canceled.call);
3530
- source.error.tap('TsCheckerRspackPlugin', target.error.call);
3531
- source.issues.tap('TsCheckerRspackPlugin', target.issues.call);
3371
+ async function runTypeScriptGoShowConfig(executable, configFile) {
3372
+ const { stdout } = await (0, external_node_util_namespaceObject.promisify)(external_node_child_process_namespaceObject.execFile)(executable.command, [
3373
+ ...executable.args,
3374
+ '--project',
3375
+ configFile,
3376
+ '--showConfig',
3377
+ '--pretty',
3378
+ 'false'
3379
+ ], {
3380
+ cwd: external_node_path_default().dirname(configFile),
3381
+ encoding: 'utf8',
3382
+ maxBuffer: 67108864
3383
+ });
3384
+ const parsedConfig = JSON.parse(stdout);
3385
+ if (!parsedConfig || 'object' != typeof parsedConfig || Array.isArray(parsedConfig)) throw new TypeError('Invalid tsgo --showConfig output.');
3386
+ return parsedConfig;
3532
3387
  }
3533
- function getPluginHooks(compiler) {
3534
- let hooks = compilerHookMap.get(compiler);
3535
- if (void 0 === hooks) {
3536
- hooks = createPluginHooks();
3388
+ function toComparisonPath(file) {
3389
+ const normalizedPath = external_node_path_default().normalize(file);
3390
+ return 'win32' === process.platform ? normalizedPath.toLowerCase() : normalizedPath;
3391
+ }
3392
+ function shouldRefreshTypeScriptGoDependencies(dependencies, { changedFiles = [], deletedFiles = [] }) {
3393
+ if (!dependencies) return true;
3394
+ const dependencyKeys = dependencies.files.map((file)=>toComparisonPath(file));
3395
+ return changedFiles.some((file)=>{
3396
+ const key = toComparisonPath(file);
3397
+ const extension = external_node_path_default().extname(file).toLowerCase();
3398
+ return '.json' === extension || dependencies.extensions.includes(extension) && !dependencyKeys.includes(key);
3399
+ }) || deletedFiles.some((file)=>dependencyKeys.includes(toComparisonPath(file)));
3400
+ }
3401
+ function createTypeScriptGoArgs(config) {
3402
+ const args = config.build ? [
3403
+ '--build',
3404
+ config.configFile
3405
+ ] : [
3406
+ '--project',
3407
+ config.configFile
3408
+ ];
3409
+ if (config.build && 'write-references' === config.mode) args.push('--noEmit', 'false');
3410
+ else args.push('--noEmit');
3411
+ args.push('--pretty');
3412
+ return args;
3413
+ }
3414
+ function logOutput(logger, output) {
3415
+ if (!output.trim()) return;
3416
+ logger.error(output.trimEnd());
3417
+ }
3418
+ function stripAnsi(output) {
3419
+ return output.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '');
3420
+ }
3421
+ function getTypeScriptGoErrorCount(output) {
3422
+ const plainOutput = stripAnsi(output);
3423
+ const matches = Array.from(plainOutput.matchAll(/\bFound\s+(\d+)\s+errors?\b/g));
3424
+ const lastMatch = matches[matches.length - 1];
3425
+ if (!lastMatch) return;
3426
+ return Number(lastMatch[1]);
3427
+ }
3428
+ function getTypeScriptGoIssueSeverity(severity, defaultSeverity) {
3429
+ return 'auto' === defaultSeverity ? severity : defaultSeverity;
3430
+ }
3431
+ function createTypeScriptGoIssue(message) {
3432
+ return {
3433
+ severity: 'error',
3434
+ code: "TSGO",
3435
+ message
3436
+ };
3437
+ }
3438
+ function getTypeScriptGoDiagnosticMessage(code, message, config) {
3439
+ if ('6310' === code && config.build && ('readonly' === config.mode || 'write-tsbuildinfo' === config.mode)) return [
3440
+ message,
3441
+ "In build mode, set `typescript.mode` to `write-references` to write the required outputs to disk, or build the project graph separately first."
3442
+ ].join(' ');
3443
+ return message;
3444
+ }
3445
+ const diagnosticPattern = /^(.*?):(\d+):(\d+)\s+-\s+(error|warning)\s+TS(\d+):\s+(.+)$/;
3446
+ const globalDiagnosticPattern = /^(error|warning)\s+TS(\d+):\s+(.+)$/;
3447
+ function getTypeScriptGoMarkerLength(output, startIndex) {
3448
+ const lines = output.slice(startIndex).split(/\r?\n/);
3449
+ for (const line of lines){
3450
+ if (diagnosticPattern.test(line) || globalDiagnosticPattern.test(line) || /^Found\s+\d+\s+errors?\b/.test(line)) break;
3451
+ const marker = line.match(/^\s*([~^]+)\s*$/);
3452
+ if (marker) return marker[1].length;
3453
+ }
3454
+ }
3455
+ function parseTypeScriptGoIssues(output, config, defaultSeverity = 'auto') {
3456
+ const issues = [];
3457
+ const plainOutput = stripAnsi(output);
3458
+ const diagnosticPatternWithGlobal = new RegExp(diagnosticPattern, 'gm');
3459
+ const globalDiagnosticPatternWithGlobal = new RegExp(globalDiagnosticPattern, 'gm');
3460
+ for (const match of plainOutput.matchAll(diagnosticPatternWithGlobal)){
3461
+ const [, file, line, column, severity, code, message] = match;
3462
+ const startColumn = Number(column);
3463
+ const markerLength = getTypeScriptGoMarkerLength(plainOutput, (match.index || 0) + match[0].length);
3464
+ const position = {
3465
+ line: Number(line),
3466
+ column: startColumn
3467
+ };
3468
+ issues.push({
3469
+ severity: getTypeScriptGoIssueSeverity(severity, defaultSeverity),
3470
+ code: `TS${code}`,
3471
+ message: getTypeScriptGoDiagnosticMessage(code, message, config),
3472
+ file: external_node_path_default().isAbsolute(file) ? file : external_node_path_default().resolve(config.context, file),
3473
+ location: {
3474
+ start: position,
3475
+ end: {
3476
+ line: position.line,
3477
+ column: markerLength ? startColumn + markerLength : startColumn
3478
+ }
3479
+ }
3480
+ });
3481
+ }
3482
+ for (const match of plainOutput.matchAll(globalDiagnosticPatternWithGlobal)){
3483
+ const [, severity, code, message] = match;
3484
+ issues.push({
3485
+ severity: getTypeScriptGoIssueSeverity(severity, defaultSeverity),
3486
+ code: `TS${code}`,
3487
+ message: getTypeScriptGoDiagnosticMessage(code, message, config)
3488
+ });
3489
+ }
3490
+ return issues;
3491
+ }
3492
+ function createTypeScriptGoExitIssues(output, signal, config, defaultSeverity = 'auto') {
3493
+ const parsedIssues = parseTypeScriptGoIssues(output, config, defaultSeverity);
3494
+ const errorCount = getTypeScriptGoErrorCount(output);
3495
+ if (parsedIssues.length && (void 0 === errorCount || parsedIssues.length >= errorCount)) return parsedIssues;
3496
+ if (void 0 !== errorCount) return Array.from({
3497
+ length: Math.max(errorCount, 1)
3498
+ }, ()=>createTypeScriptGoIssue('tsgo check failed. See the output above for diagnostics.'));
3499
+ if (null !== signal) return [
3500
+ createTypeScriptGoIssue(`tsgo check interrupted by ${signal}. See the output above for diagnostics.`)
3501
+ ];
3502
+ return [
3503
+ createTypeScriptGoIssue('tsgo check failed. See the output above for diagnostics.')
3504
+ ];
3505
+ }
3506
+ function isTypeScriptGoIssue(issue) {
3507
+ return "TSGO" === issue.code;
3508
+ }
3509
+ function isTypeScriptGoStatsError(error) {
3510
+ const issue = error?.issue;
3511
+ if (issue && isTypeScriptGoIssue(issue)) return true;
3512
+ const message = error?.message;
3513
+ return 'string' == typeof message && message.includes("TSGO:");
3514
+ }
3515
+ async function runTypeScriptGo(config, logger, defaultSeverity = 'auto', signal, emittedFiles) {
3516
+ AbortError.throwIfAborted(signal);
3517
+ const executable = await resolveTypeScriptGoExecutable(config);
3518
+ const args = createTypeScriptGoArgs(config);
3519
+ if (emittedFiles) args.push('--listEmittedFiles');
3520
+ AbortError.throwIfAborted(signal);
3521
+ return new Promise((resolve, reject)=>{
3522
+ let settled = false;
3523
+ let output = '';
3524
+ const childProcess = (0, external_node_child_process_namespaceObject.spawn)(executable.command, [
3525
+ ...executable.args,
3526
+ ...args
3527
+ ], {
3528
+ cwd: config.context,
3529
+ stdio: [
3530
+ 'inherit',
3531
+ 'pipe',
3532
+ 'pipe'
3533
+ ]
3534
+ });
3535
+ const cleanup = ()=>{
3536
+ signal?.removeEventListener('abort', abort);
3537
+ childProcess.stdout?.removeAllListeners();
3538
+ childProcess.stderr?.removeAllListeners();
3539
+ childProcess.removeAllListeners();
3540
+ };
3541
+ const finish = (callback)=>{
3542
+ if (settled) return;
3543
+ settled = true;
3544
+ cleanup();
3545
+ callback();
3546
+ };
3547
+ const abort = ()=>{
3548
+ childProcess.kill('SIGKILL');
3549
+ };
3550
+ signal?.addEventListener('abort', abort, {
3551
+ once: true
3552
+ });
3553
+ childProcess.stdout?.on('data', (data)=>{
3554
+ output += data.toString();
3555
+ });
3556
+ childProcess.stderr?.on('data', (data)=>{
3557
+ output += data.toString();
3558
+ });
3559
+ childProcess.on('error', (error)=>{
3560
+ finish(()=>reject(error));
3561
+ });
3562
+ childProcess.on('close', (exitCode, exitSignal)=>{
3563
+ output = output.replace(/^TSFILE: (.+?)\r?$/gm, (_, file)=>{
3564
+ try {
3565
+ emittedFiles?.set(toComparisonPath(file), external_node_fs_default().statSync(file).mtimeMs);
3566
+ } catch {}
3567
+ return '';
3568
+ });
3569
+ finish(()=>{
3570
+ if (signal?.aborted) return void reject(new AbortError());
3571
+ if (0 === exitCode && null === exitSignal) {
3572
+ logOutput(logger, output);
3573
+ resolve([]);
3574
+ return;
3575
+ }
3576
+ const issues = createTypeScriptGoExitIssues(output, exitSignal, config, defaultSeverity);
3577
+ if (issues.some(isTypeScriptGoIssue)) logOutput(logger, output);
3578
+ resolve(issues);
3579
+ });
3580
+ });
3581
+ });
3582
+ }
3583
+ async function getTypeScriptGoDependencies(config) {
3584
+ const executable = await resolveTypeScriptGoExecutable(config);
3585
+ const files = new Set();
3586
+ const dirs = new Set();
3587
+ const excluded = new Set();
3588
+ const visitedConfigs = new Set();
3589
+ const collectConfigDependencies = async (configFile, fallbackRoot, collectExcluded)=>{
3590
+ const normalizedConfigFile = external_node_path_default().normalize(configFile);
3591
+ const configKey = toComparisonPath(normalizedConfigFile);
3592
+ if (visitedConfigs.has(configKey)) return;
3593
+ visitedConfigs.add(configKey);
3594
+ const configDir = external_node_path_default().dirname(normalizedConfigFile);
3595
+ const normalizedRoot = external_node_path_default().normalize(fallbackRoot);
3596
+ files.add(normalizedConfigFile);
3597
+ if (!Array.from(dirs).some((dir)=>'' === external_node_path_default().relative(dir, normalizedRoot) || isInsideAnotherPath(dir, normalizedRoot))) dirs.add(normalizedRoot);
3598
+ excluded.add(external_node_path_default().join(normalizedRoot, 'node_modules'));
3599
+ let parsedConfig;
3600
+ try {
3601
+ parsedConfig = await runTypeScriptGoShowConfig(executable, normalizedConfigFile);
3602
+ } catch {
3603
+ return;
3604
+ }
3605
+ for (const file of parsedConfig.files || [])files.add(external_node_path_default().normalize(external_node_path_default().resolve(configDir, file)));
3606
+ if (collectExcluded && !parsedConfig.references?.length) for (const exclude of parsedConfig.exclude || [])excluded.add(external_node_path_default().normalize(external_node_path_default().resolve(configDir, exclude)));
3607
+ for (const reference of parsedConfig.references || [])if (reference.path) {
3608
+ const resolvedReference = external_node_path_default().resolve(configDir, reference.path);
3609
+ const referenceConfig = '.json' === external_node_path_default().extname(resolvedReference).toLowerCase() ? resolvedReference : external_node_path_default().join(resolvedReference, 'tsconfig.json');
3610
+ await collectConfigDependencies(referenceConfig, external_node_path_default().dirname(referenceConfig), false);
3611
+ }
3612
+ };
3613
+ await collectConfigDependencies(config.configFile, config.context, true);
3614
+ return {
3615
+ files: Array.from(files),
3616
+ dirs: Array.from(dirs),
3617
+ excluded: Array.from(excluded),
3618
+ extensions: [
3619
+ '.ts',
3620
+ '.tsx',
3621
+ '.mts',
3622
+ '.cts',
3623
+ '.js',
3624
+ '.jsx',
3625
+ '.mjs',
3626
+ '.cjs',
3627
+ '.json'
3628
+ ]
3629
+ };
3630
+ }
3631
+ function _define_property(obj, key, value) {
3632
+ if (key in obj) Object.defineProperty(obj, key, {
3633
+ value: value,
3634
+ enumerable: true,
3635
+ configurable: true,
3636
+ writable: true
3637
+ });
3638
+ else obj[key] = value;
3639
+ return obj;
3640
+ }
3641
+ const BUILTIN_IGNORED_DIRS = [
3642
+ '.git'
3643
+ ];
3644
+ function createIsIgnored(ignored, excluded) {
3645
+ const ignoredPatterns = ignored ? Array.isArray(ignored) ? [
3646
+ ...ignored
3647
+ ] : [
3648
+ ignored
3649
+ ] : [];
3650
+ const filteredExcluded = excluded.filter((pattern)=>{
3651
+ if (is_glob_default()(pattern)) {
3652
+ const shouldAppendStar = pattern.includes('**') && !pattern.endsWith('*');
3653
+ if (shouldAppendStar) ignoredPatterns.push(pattern.endsWith('/') ? `${pattern}**` : `${pattern}/**`);
3654
+ else ignoredPatterns.push(pattern);
3655
+ return false;
3656
+ }
3657
+ return true;
3658
+ });
3659
+ const ignoredFunctions = ignoredPatterns.map((pattern)=>{
3660
+ if ('string' == typeof pattern) return (path)=>minimatch(path, pattern);
3661
+ else if (pattern instanceof RegExp) return (path)=>pattern.test(path);
3662
+ else if ('function' == typeof pattern) return pattern;
3663
+ else return ()=>false;
3664
+ });
3665
+ ignoredFunctions.push((path)=>filteredExcluded.some((excludedPath)=>isInsideAnotherPath(excludedPath, path)));
3666
+ ignoredFunctions.push((path)=>BUILTIN_IGNORED_DIRS.some((ignoredDir)=>path.includes(`/${ignoredDir}/`) || path.includes(`\\${ignoredDir}\\`)));
3667
+ return function(path) {
3668
+ return ignoredFunctions.some((ignoredFunction)=>ignoredFunction(path));
3669
+ };
3670
+ }
3671
+ class InclusiveNodeWatchFileSystem {
3672
+ get watcher() {
3673
+ return this.watchFileSystem.watcher || this.watchFileSystem.wfs?.watcher;
3674
+ }
3675
+ constructor(watchFileSystem, compiler, pluginState){
3676
+ _define_property(this, "watchFileSystem", void 0);
3677
+ _define_property(this, "compiler", void 0);
3678
+ _define_property(this, "pluginState", void 0);
3679
+ _define_property(this, "dirsWatchers", void 0);
3680
+ _define_property(this, "paused", void 0);
3681
+ _define_property(this, "deletedFiles", void 0);
3682
+ _define_property(this, "watch", void 0);
3683
+ this.watchFileSystem = watchFileSystem;
3684
+ this.compiler = compiler;
3685
+ this.pluginState = pluginState;
3686
+ this.paused = true;
3687
+ this.watch = (files, dirs, missing, startTime, options, callback, callbackUndelayed)=>{
3688
+ const { debug } = getInfrastructureLogger(this.compiler);
3689
+ clearFilesChange(this.compiler);
3690
+ const isIgnored = createIsIgnored(options?.ignored, this.pluginState.lastDependencies?.excluded || []);
3691
+ const standardWatcher = this.watchFileSystem.watch(files, dirs, missing, startTime, options, callback, callbackUndelayed);
3692
+ this.watcher?.on('change', (file)=>{
3693
+ if ('string' != typeof file) return;
3694
+ if (isIgnored(file)) debug("Detected file change but it's ignored", file);
3695
+ else {
3696
+ debug('Detected file change', file);
3697
+ this.deletedFiles.delete(file);
3698
+ updateFilesChange(this.compiler, {
3699
+ changedFiles: [
3700
+ file
3701
+ ]
3702
+ });
3703
+ }
3704
+ });
3705
+ this.watcher?.on('remove', (file)=>{
3706
+ if ('string' != typeof file) return;
3707
+ if (this.deletedFiles.has(file)) return void debug('Skipping duplicated remove event.');
3708
+ if (isIgnored(file)) debug("Detected file remove but it's ignored", file);
3709
+ else {
3710
+ debug('Detected file remove', file);
3711
+ this.deletedFiles.add(file);
3712
+ updateFilesChange(this.compiler, {
3713
+ deletedFiles: [
3714
+ file
3715
+ ]
3716
+ });
3717
+ }
3718
+ });
3719
+ const prevDirs = Array.from(this.dirsWatchers.keys());
3720
+ const nextDirs = Array.from(this.pluginState.lastDependencies?.dirs || []);
3721
+ const dirsToUnwatch = prevDirs.filter((prevDir)=>!nextDirs.includes(prevDir));
3722
+ const dirsToWatch = nextDirs.filter((nextDir)=>!prevDirs.includes(nextDir) && !isIgnored(nextDir));
3723
+ dirsToUnwatch.forEach((dirToUnwatch)=>{
3724
+ this.dirsWatchers.get(dirToUnwatch)?.close();
3725
+ this.dirsWatchers.delete(dirToUnwatch);
3726
+ });
3727
+ dirsToWatch.forEach((dirToWatch)=>{
3728
+ const interval = 'number' == typeof options?.poll ? options.poll : void 0;
3729
+ const dirWatcher = external_chokidar_default().watch(dirToWatch, {
3730
+ ignoreInitial: true,
3731
+ ignorePermissionErrors: true,
3732
+ ignored: (path)=>isIgnored(path),
3733
+ usePolling: options?.poll ? true : void 0,
3734
+ ...void 0 !== interval && {
3735
+ interval,
3736
+ binaryInterval: interval
3737
+ },
3738
+ alwaysStat: true,
3739
+ atomic: true,
3740
+ awaitWriteFinish: true
3741
+ });
3742
+ dirWatcher.on('add', async (file, stats)=>{
3743
+ if (this.paused) return;
3744
+ const extension = (0, external_node_path_namespaceObject.extname)(file);
3745
+ const supportedExtensions = this.pluginState.lastDependencies?.extensions || [];
3746
+ if (!supportedExtensions.includes(extension)) return void debug('Detected new file add but extension is not supported', file);
3747
+ this.deletedFiles.delete(file);
3748
+ if (this.pluginState.emittedFiles) {
3749
+ await this.pluginState.issuesPromise.catch(()=>void 0);
3750
+ if (this.dirsWatchers.get(dirToWatch) !== dirWatcher || this.deletedFiles.has(file)) return;
3751
+ const emittedMtime = this.pluginState.emittedFiles.get(toComparisonPath(file));
3752
+ try {
3753
+ if (void 0 !== emittedMtime && external_node_fs_default().statSync(file).mtimeMs === emittedMtime) return;
3754
+ } catch {}
3755
+ }
3756
+ debug('Detected new file add', file);
3757
+ updateFilesChange(this.compiler, {
3758
+ changedFiles: [
3759
+ file
3760
+ ]
3761
+ });
3762
+ this.watcher?._onChange(file, stats?.mtimeMs || stats?.ctimeMs || 1, file, 'rename');
3763
+ });
3764
+ dirWatcher.on('unlink', (file)=>{
3765
+ if (this.paused) return;
3766
+ this.pluginState.emittedFiles?.delete(toComparisonPath(file));
3767
+ const extension = (0, external_node_path_namespaceObject.extname)(file);
3768
+ const supportedExtensions = this.pluginState.lastDependencies?.extensions || [];
3769
+ if (!supportedExtensions.includes(extension)) return void debug('Detected new file remove but extension is not supported', file);
3770
+ if (this.deletedFiles.has(file)) return void debug('Skipping duplicated unlink event.');
3771
+ debug('Detected new file remove', file);
3772
+ this.deletedFiles.add(file);
3773
+ updateFilesChange(this.compiler, {
3774
+ deletedFiles: [
3775
+ file
3776
+ ]
3777
+ });
3778
+ this.watcher?._onRemove(dirToWatch, file, 'rename');
3779
+ });
3780
+ this.dirsWatchers.set(dirToWatch, dirWatcher);
3781
+ });
3782
+ this.paused = false;
3783
+ return {
3784
+ ...standardWatcher,
3785
+ close: ()=>{
3786
+ clearFilesChange(this.compiler);
3787
+ if (standardWatcher) standardWatcher.close();
3788
+ this.dirsWatchers.forEach((dirWatcher)=>{
3789
+ dirWatcher?.close();
3790
+ });
3791
+ this.dirsWatchers.clear();
3792
+ this.paused = true;
3793
+ },
3794
+ pause: ()=>{
3795
+ if (standardWatcher) standardWatcher.pause();
3796
+ this.paused = true;
3797
+ }
3798
+ };
3799
+ };
3800
+ this.dirsWatchers = new Map();
3801
+ this.deletedFiles = new Set();
3802
+ }
3803
+ }
3804
+ function tapAfterEnvironmentToPatchWatching(compiler, state) {
3805
+ const { debug } = getInfrastructureLogger(compiler);
3806
+ compiler.hooks.afterEnvironment.tap('TsCheckerRspackPlugin', ()=>{
3807
+ const watchFileSystem = compiler.watchFileSystem;
3808
+ if (watchFileSystem) {
3809
+ debug("Overwriting Rspack's watch file system.");
3810
+ compiler.watchFileSystem = new InclusiveNodeWatchFileSystem(watchFileSystem, compiler, state);
3811
+ } else debug('No watch file system found - plugin may not work correctly.');
3812
+ });
3813
+ }
3814
+ var external_picocolors_ = __webpack_require__("picocolors");
3815
+ var external_picocolors_default = /*#__PURE__*/ __webpack_require__.n(external_picocolors_);
3816
+ const lite_tapable_namespaceObject = require("@rspack/lite-tapable");
3817
+ const compilerHookMap = new WeakMap();
3818
+ function createPluginHooks() {
3819
+ return {
3820
+ start: new lite_tapable_namespaceObject.AsyncSeriesWaterfallHook([
3821
+ 'change',
3822
+ 'compilation'
3823
+ ]),
3824
+ waiting: new lite_tapable_namespaceObject.SyncHook([
3825
+ 'compilation'
3826
+ ]),
3827
+ canceled: new lite_tapable_namespaceObject.SyncHook([
3828
+ 'compilation'
3829
+ ]),
3830
+ error: new lite_tapable_namespaceObject.SyncHook([
3831
+ 'error',
3832
+ 'compilation'
3833
+ ]),
3834
+ issues: new lite_tapable_namespaceObject.SyncWaterfallHook([
3835
+ 'issues',
3836
+ 'compilation'
3837
+ ])
3838
+ };
3839
+ }
3840
+ function forwardPluginHooks(source, target) {
3841
+ source.start.tapPromise('TsCheckerRspackPlugin', target.start.promise);
3842
+ source.waiting.tap('TsCheckerRspackPlugin', target.waiting.call);
3843
+ source.canceled.tap('TsCheckerRspackPlugin', target.canceled.call);
3844
+ source.error.tap('TsCheckerRspackPlugin', target.error.call);
3845
+ source.issues.tap('TsCheckerRspackPlugin', target.issues.call);
3846
+ }
3847
+ function getPluginHooks(compiler) {
3848
+ let hooks = compilerHookMap.get(compiler);
3849
+ if (void 0 === hooks) {
3850
+ hooks = createPluginHooks();
3537
3851
  compilerHookMap.set(compiler, hooks);
3538
3852
  if ('compilers' in compiler) compiler.compilers.forEach((childCompiler)=>{
3539
3853
  const childHooks = getPluginHooks(childCompiler);
@@ -3617,7 +3931,6 @@ var __webpack_exports__ = {};
3617
3931
  function uuid() {
3618
3932
  return new Array(4).fill(0).map(()=>Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join('-');
3619
3933
  }
3620
- const external_node_child_process_namespaceObject = require("node:child_process");
3621
3934
  const WORKER_DATA_ENV_KEY = 'WORKER_DATA';
3622
3935
  function createRpcWorker(modulePath, data, memoryLimit) {
3623
3936
  const options = {
@@ -3670,380 +3983,93 @@ var __webpack_exports__ = {};
3670
3983
  return remoteMethod(...args);
3671
3984
  }, worker);
3672
3985
  }
3673
- class AbortError extends Error {
3674
- static throwIfAborted(signal) {
3675
- if (signal?.aborted) throw new AbortError();
3676
- }
3677
- constructor(message = 'Task aborted.'){
3678
- super(message);
3679
- this.name = 'AbortError';
3680
- }
3681
- }
3682
- function tapErrorToLogMessage(compiler, config) {
3683
- const hooks = getPluginHooks(compiler);
3684
- hooks.error.tap('TsCheckerRspackPlugin', (error)=>{
3685
- if (error instanceof AbortError) return;
3686
- config.logger.error(String(error));
3687
- if (error instanceof RpcExitError) if ('SIGINT' === error.signal) config.logger.error(external_picocolors_default().red("[type-check] Issues checking service interrupted - If running in a docker container, this may be caused by the container running out of memory. If so, try increasing the container's memory limit or lowering the `memoryLimit` value in the TsCheckerRspackPlugin configuration."));
3688
- else config.logger.error(external_picocolors_default().red("[type-check] Issues checking service aborted - probably out of memory. Check the `memoryLimit` option in the TsCheckerRspackPlugin configuration.\nIf increasing the memory doesn't solve the issue, it's most probably a bug in the TypeScript."));
3689
- });
3690
- }
3691
- const external_node_os_namespaceObject = require("node:os");
3692
- var external_node_os_default = /*#__PURE__*/ __webpack_require__.n(external_node_os_namespaceObject);
3693
- function createPool(size) {
3694
- let pendingPromises = [];
3695
- const pool = {
3696
- async submit (task, signal) {
3697
- while(pendingPromises.length >= pool.size){
3698
- AbortError.throwIfAborted(signal);
3699
- await Promise.race(pendingPromises).catch(()=>void 0);
3700
- }
3701
- AbortError.throwIfAborted(signal);
3702
- const taskPromise = task(signal).finally(()=>{
3703
- pendingPromises = pendingPromises.filter((pendingPromise)=>pendingPromise !== taskPromise);
3704
- });
3705
- pendingPromises.push(taskPromise);
3706
- return taskPromise;
3707
- },
3708
- size,
3709
- get pending () {
3710
- return pendingPromises.length;
3711
- },
3712
- get drained () {
3713
- return new Promise(async (resolve)=>{
3714
- while(pendingPromises.length > 0)await Promise.race(pendingPromises).catch(()=>void 0);
3715
- resolve(void 0);
3716
- });
3717
- }
3718
- };
3719
- return pool;
3720
- }
3721
- const issuesPool = createPool(Math.max(1, external_node_os_namespaceObject.cpus().length));
3722
- const dependenciesPool = createPool(Math.max(1, external_node_os_namespaceObject.cpus().length));
3723
- function interceptDoneToGetDevServerTap(compiler, config, state) {
3724
- const { debug } = getInfrastructureLogger(compiler);
3725
- compiler.hooks.done.intercept({
3726
- register: (tap)=>{
3727
- if ([
3728
- 'webpack-dev-server',
3729
- 'rsbuild-dev-server',
3730
- 'rspack-dev-server'
3731
- ].includes(tap.name) && 'sync' === tap.type && config.devServer) {
3732
- debug('Intercepting dev-server tap.');
3733
- state.DevServerDoneTap = tap;
3734
- }
3735
- return tap;
3736
- }
3737
- });
3738
- }
3739
- function forwardSlash(input) {
3740
- return external_node_path_default().normalize(input).replace(/\\+/g, '/');
3741
- }
3742
- function relativeToContext(file, context) {
3743
- let fileInContext = forwardSlash(external_node_path_default().relative(context, file));
3744
- if (!fileInContext.startsWith('../')) fileInContext = './' + fileInContext;
3745
- return fileInContext;
3746
- }
3747
- function formatIssueLocation(location) {
3748
- return `${location.start.line}:${location.start.column}`;
3749
- }
3750
- function issue_rspack_error_define_property(obj, key, value) {
3751
- if (key in obj) Object.defineProperty(obj, key, {
3752
- value: value,
3753
- enumerable: true,
3754
- configurable: true,
3755
- writable: true
3756
- });
3757
- else obj[key] = value;
3758
- return obj;
3759
- }
3760
- class IssueRspackError extends Error {
3761
- constructor(message, pathType, issue){
3762
- super(message), issue_rspack_error_define_property(this, "issue", void 0), issue_rspack_error_define_property(this, "hideStack", void 0), issue_rspack_error_define_property(this, "file", void 0), this.issue = issue, this.hideStack = true;
3763
- if (issue.file) {
3764
- this.file = 'absolute' === pathType ? forwardSlash(external_node_path_default().resolve(issue.file)) : relativeToContext(issue.file, process.cwd());
3765
- if (issue.location) this.file += `:${formatIssueLocation(issue.location)}`;
3766
- }
3767
- Error.captureStackTrace(this, this.constructor);
3768
- }
3769
- }
3770
- const external_node_fs_namespaceObject = require("node:fs");
3771
- var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
3772
- const external_node_url_namespaceObject = require("node:url");
3773
- const external_node_util_namespaceObject = require("node:util");
3774
- const TYPESCRIPT_PACKAGE = "typescript";
3775
- const TYPESCRIPT_PACKAGE_JSON = `${TYPESCRIPT_PACKAGE}/package.json`;
3776
- const TYPESCRIPT_PREVIEW_PACKAGE = "@typescript/native-preview";
3777
- const TYPESCRIPT_PREVIEW_PACKAGE_JSON = `${TYPESCRIPT_PREVIEW_PACKAGE}/package.json`;
3778
- function resolveTypeScriptGoPackageJsonPath(config) {
3779
- if (!external_node_path_default().isAbsolute(config.typescriptPath) || 'package.json' !== external_node_path_default().basename(config.typescriptPath)) throw new Error("The typescriptPath option must be an absolute path to a package.json file when tsgo is enabled.");
3780
- if (!config.tsgoPackage) throw new Error(`The typescriptPath option must point to "${TYPESCRIPT_PREVIEW_PACKAGE_JSON}" or "${TYPESCRIPT_PACKAGE}@>=7".`);
3781
- return config.typescriptPath;
3782
- }
3783
- async function resolveTypeScriptGoNativeExecutablePath(packageJsonPath, packageName) {
3784
- const getExePathPath = external_node_path_default().resolve(external_node_path_default().dirname(packageJsonPath), './lib/getExePath.js');
3785
- const getExePathUrl = (0, external_node_url_namespaceObject.pathToFileURL)(getExePathPath).href;
3786
- const getExePathModule = await import(getExePathUrl);
3787
- const getExePath = getExePathModule.default || getExePathModule.getExePath;
3788
- if ('function' != typeof getExePath) throw new Error(`Cannot resolve the native TypeScript executable from "${packageName}".`);
3789
- const executablePath = getExePath();
3790
- if ('string' != typeof executablePath || !external_node_fs_default().existsSync(executablePath)) throw new Error('Executable not found');
3791
- return executablePath;
3792
- }
3793
- async function resolveTypeScriptGoBinPath(config) {
3794
- const packageJsonPath = resolveTypeScriptGoPackageJsonPath(config);
3795
- if ("typescript" === config.tsgoPackage) return resolveTypeScriptGoNativeExecutablePath(packageJsonPath, TYPESCRIPT_PACKAGE);
3796
- return resolveTypeScriptGoNativeExecutablePath(packageJsonPath, TYPESCRIPT_PREVIEW_PACKAGE);
3797
- }
3798
- async function resolveTypeScriptGoExecutable(config) {
3799
- const binPath = await resolveTypeScriptGoBinPath(config);
3800
- return {
3801
- command: binPath,
3802
- args: []
3803
- };
3804
- }
3805
- async function runTypeScriptGoShowConfig(executable, configFile) {
3806
- const { stdout } = await (0, external_node_util_namespaceObject.promisify)(external_node_child_process_namespaceObject.execFile)(executable.command, [
3807
- ...executable.args,
3808
- '--project',
3809
- configFile,
3810
- '--showConfig',
3811
- '--pretty',
3812
- 'false'
3813
- ], {
3814
- cwd: external_node_path_default().dirname(configFile),
3815
- encoding: 'utf8',
3816
- maxBuffer: 67108864
3817
- });
3818
- const parsedConfig = JSON.parse(stdout);
3819
- if (!parsedConfig || 'object' != typeof parsedConfig || Array.isArray(parsedConfig)) throw new TypeError('Invalid tsgo --showConfig output.');
3820
- return parsedConfig;
3821
- }
3822
- function toComparisonPath(file) {
3823
- const normalizedPath = external_node_path_default().normalize(file);
3824
- return 'win32' === process.platform ? normalizedPath.toLowerCase() : normalizedPath;
3825
- }
3826
- function shouldRefreshTypeScriptGoDependencies(dependencies, { changedFiles = [], deletedFiles = [] }) {
3827
- if (!dependencies) return true;
3828
- const dependencyKeys = dependencies.files.map((file)=>toComparisonPath(file));
3829
- return changedFiles.some((file)=>{
3830
- const key = toComparisonPath(file);
3831
- const extension = external_node_path_default().extname(file).toLowerCase();
3832
- return '.json' === extension || dependencies.extensions.includes(extension) && !dependencyKeys.includes(key);
3833
- }) || deletedFiles.some((file)=>dependencyKeys.includes(toComparisonPath(file)));
3834
- }
3835
- function createTypeScriptGoArgs(config) {
3836
- const args = config.build ? [
3837
- '--build',
3838
- config.configFile
3839
- ] : [
3840
- '--project',
3841
- config.configFile
3842
- ];
3843
- args.push('--noEmit', '--pretty');
3844
- return args;
3845
- }
3846
- function logOutput(logger, output) {
3847
- if (!output.trim()) return;
3848
- logger.error(output.trimEnd());
3849
- }
3850
- function stripAnsi(output) {
3851
- return output.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '');
3852
- }
3853
- function getTypeScriptGoErrorCount(output) {
3854
- const plainOutput = stripAnsi(output);
3855
- const matches = Array.from(plainOutput.matchAll(/\bFound\s+(\d+)\s+errors?\b/g));
3856
- const lastMatch = matches[matches.length - 1];
3857
- if (!lastMatch) return;
3858
- return Number(lastMatch[1]);
3859
- }
3860
- function getTypeScriptGoIssueSeverity(severity, defaultSeverity) {
3861
- return 'auto' === defaultSeverity ? severity : defaultSeverity;
3986
+ function tapErrorToLogMessage(compiler, config) {
3987
+ const hooks = getPluginHooks(compiler);
3988
+ hooks.error.tap('TsCheckerRspackPlugin', (error)=>{
3989
+ if (error instanceof AbortError) return;
3990
+ config.logger.error(String(error));
3991
+ if (error instanceof RpcExitError) if ('SIGINT' === error.signal) config.logger.error(external_picocolors_default().red("[type-check] Issues checking service interrupted - If running in a docker container, this may be caused by the container running out of memory. If so, try increasing the container's memory limit or lowering the `memoryLimit` value in the TsCheckerRspackPlugin configuration."));
3992
+ else config.logger.error(external_picocolors_default().red("[type-check] Issues checking service aborted - probably out of memory. Check the `memoryLimit` option in the TsCheckerRspackPlugin configuration.\nIf increasing the memory doesn't solve the issue, it's most probably a bug in the TypeScript."));
3993
+ });
3862
3994
  }
3863
- function createTypeScriptGoIssue(message) {
3864
- return {
3865
- severity: 'error',
3866
- code: "TSGO",
3867
- message
3995
+ const external_node_os_namespaceObject = require("node:os");
3996
+ var external_node_os_default = /*#__PURE__*/ __webpack_require__.n(external_node_os_namespaceObject);
3997
+ function createPool(size) {
3998
+ let pendingPromises = [];
3999
+ const pool = {
4000
+ async submit (task, signal) {
4001
+ while(pendingPromises.length >= pool.size){
4002
+ AbortError.throwIfAborted(signal);
4003
+ await Promise.race(pendingPromises).catch(()=>void 0);
4004
+ }
4005
+ AbortError.throwIfAborted(signal);
4006
+ const taskPromise = task(signal).finally(()=>{
4007
+ pendingPromises = pendingPromises.filter((pendingPromise)=>pendingPromise !== taskPromise);
4008
+ });
4009
+ pendingPromises.push(taskPromise);
4010
+ return taskPromise;
4011
+ },
4012
+ size,
4013
+ get pending () {
4014
+ return pendingPromises.length;
4015
+ },
4016
+ get drained () {
4017
+ return new Promise(async (resolve)=>{
4018
+ while(pendingPromises.length > 0)await Promise.race(pendingPromises).catch(()=>void 0);
4019
+ resolve(void 0);
4020
+ });
4021
+ }
3868
4022
  };
4023
+ return pool;
3869
4024
  }
3870
- const diagnosticPattern = /^(.*?):(\d+):(\d+)\s+-\s+(error|warning)\s+TS(\d+):\s+(.+)$/;
3871
- const globalDiagnosticPattern = /^(error|warning)\s+TS(\d+):\s+(.+)$/;
3872
- function getTypeScriptGoMarkerLength(output, startIndex) {
3873
- const lines = output.slice(startIndex).split(/\r?\n/);
3874
- for (const line of lines){
3875
- if (diagnosticPattern.test(line) || globalDiagnosticPattern.test(line) || /^Found\s+\d+\s+errors?\b/.test(line)) break;
3876
- const marker = line.match(/^\s*([~^]+)\s*$/);
3877
- if (marker) return marker[1].length;
3878
- }
3879
- }
3880
- function parseTypeScriptGoIssues(output, config, defaultSeverity = 'auto') {
3881
- const issues = [];
3882
- const plainOutput = stripAnsi(output);
3883
- const diagnosticPatternWithGlobal = new RegExp(diagnosticPattern, 'gm');
3884
- const globalDiagnosticPatternWithGlobal = new RegExp(globalDiagnosticPattern, 'gm');
3885
- for (const match of plainOutput.matchAll(diagnosticPatternWithGlobal)){
3886
- const [, file, line, column, severity, code, message] = match;
3887
- const startColumn = Number(column);
3888
- const markerLength = getTypeScriptGoMarkerLength(plainOutput, (match.index || 0) + match[0].length);
3889
- const position = {
3890
- line: Number(line),
3891
- column: startColumn
3892
- };
3893
- issues.push({
3894
- severity: getTypeScriptGoIssueSeverity(severity, defaultSeverity),
3895
- code: `TS${code}`,
3896
- message,
3897
- file: external_node_path_default().isAbsolute(file) ? file : external_node_path_default().resolve(config.context, file),
3898
- location: {
3899
- start: position,
3900
- end: {
3901
- line: position.line,
3902
- column: markerLength ? startColumn + markerLength : startColumn
3903
- }
4025
+ const issuesPool = createPool(Math.max(1, external_node_os_namespaceObject.cpus().length));
4026
+ const dependenciesPool = createPool(Math.max(1, external_node_os_namespaceObject.cpus().length));
4027
+ function interceptDoneToGetDevServerTap(compiler, config, state) {
4028
+ const { debug } = getInfrastructureLogger(compiler);
4029
+ compiler.hooks.done.intercept({
4030
+ register: (tap)=>{
4031
+ if ([
4032
+ 'webpack-dev-server',
4033
+ 'rsbuild-dev-server',
4034
+ 'rspack-dev-server'
4035
+ ].includes(tap.name) && 'sync' === tap.type && config.devServer) {
4036
+ debug('Intercepting dev-server tap.');
4037
+ state.DevServerDoneTap = tap;
3904
4038
  }
3905
- });
3906
- }
3907
- for (const match of plainOutput.matchAll(globalDiagnosticPatternWithGlobal)){
3908
- const [, severity, code, message] = match;
3909
- issues.push({
3910
- severity: getTypeScriptGoIssueSeverity(severity, defaultSeverity),
3911
- code: `TS${code}`,
3912
- message
3913
- });
3914
- }
3915
- return issues;
4039
+ return tap;
4040
+ }
4041
+ });
3916
4042
  }
3917
- function createTypeScriptGoExitIssues(output, signal, config, defaultSeverity = 'auto') {
3918
- const parsedIssues = parseTypeScriptGoIssues(output, config, defaultSeverity);
3919
- const errorCount = getTypeScriptGoErrorCount(output);
3920
- if (parsedIssues.length && (void 0 === errorCount || parsedIssues.length >= errorCount)) return parsedIssues;
3921
- if (void 0 !== errorCount) return Array.from({
3922
- length: Math.max(errorCount, 1)
3923
- }, ()=>createTypeScriptGoIssue('tsgo check failed. See the output above for diagnostics.'));
3924
- if (null !== signal) return [
3925
- createTypeScriptGoIssue(`tsgo check interrupted by ${signal}. See the output above for diagnostics.`)
3926
- ];
3927
- return [
3928
- createTypeScriptGoIssue('tsgo check failed. See the output above for diagnostics.')
3929
- ];
4043
+ function forwardSlash(input) {
4044
+ return external_node_path_default().normalize(input).replace(/\\+/g, '/');
3930
4045
  }
3931
- function isTypeScriptGoIssue(issue) {
3932
- return "TSGO" === issue.code;
4046
+ function relativeToContext(file, context) {
4047
+ let fileInContext = forwardSlash(external_node_path_default().relative(context, file));
4048
+ if (!fileInContext.startsWith('../')) fileInContext = './' + fileInContext;
4049
+ return fileInContext;
3933
4050
  }
3934
- function isTypeScriptGoStatsError(error) {
3935
- const issue = error?.issue;
3936
- if (issue && isTypeScriptGoIssue(issue)) return true;
3937
- const message = error?.message;
3938
- return 'string' == typeof message && message.includes("TSGO:");
4051
+ function formatIssueLocation(location) {
4052
+ return `${location.start.line}:${location.start.column}`;
3939
4053
  }
3940
- async function runTypeScriptGo(config, logger, defaultSeverity = 'auto', signal) {
3941
- AbortError.throwIfAborted(signal);
3942
- const executable = await resolveTypeScriptGoExecutable(config);
3943
- const args = createTypeScriptGoArgs(config);
3944
- return new Promise((resolve, reject)=>{
3945
- let settled = false;
3946
- let output = '';
3947
- const childProcess = (0, external_node_child_process_namespaceObject.spawn)(executable.command, [
3948
- ...executable.args,
3949
- ...args
3950
- ], {
3951
- cwd: config.context,
3952
- stdio: [
3953
- 'inherit',
3954
- 'pipe',
3955
- 'pipe'
3956
- ]
3957
- });
3958
- const cleanup = ()=>{
3959
- signal?.removeEventListener('abort', abort);
3960
- childProcess.stdout?.removeAllListeners();
3961
- childProcess.stderr?.removeAllListeners();
3962
- childProcess.removeAllListeners();
3963
- };
3964
- const finish = (callback)=>{
3965
- if (settled) return;
3966
- settled = true;
3967
- cleanup();
3968
- callback();
3969
- };
3970
- const abort = ()=>{
3971
- childProcess.kill('SIGKILL');
3972
- finish(()=>reject(new AbortError()));
3973
- };
3974
- signal?.addEventListener('abort', abort, {
3975
- once: true
3976
- });
3977
- childProcess.stdout?.on('data', (data)=>{
3978
- output += data.toString();
3979
- });
3980
- childProcess.stderr?.on('data', (data)=>{
3981
- output += data.toString();
3982
- });
3983
- childProcess.on('error', (error)=>{
3984
- finish(()=>reject(error));
3985
- });
3986
- childProcess.on('close', (exitCode, exitSignal)=>{
3987
- finish(()=>{
3988
- if (0 === exitCode && null === exitSignal) {
3989
- logOutput(logger, output);
3990
- resolve([]);
3991
- return;
3992
- }
3993
- const issues = createTypeScriptGoExitIssues(output, exitSignal, config, defaultSeverity);
3994
- if (issues.some(isTypeScriptGoIssue)) logOutput(logger, output);
3995
- resolve(issues);
3996
- });
3997
- });
4054
+ function issue_rspack_error_define_property(obj, key, value) {
4055
+ if (key in obj) Object.defineProperty(obj, key, {
4056
+ value: value,
4057
+ enumerable: true,
4058
+ configurable: true,
4059
+ writable: true
3998
4060
  });
4061
+ else obj[key] = value;
4062
+ return obj;
3999
4063
  }
4000
- async function getTypeScriptGoDependencies(config) {
4001
- const executable = await resolveTypeScriptGoExecutable(config);
4002
- const files = new Set();
4003
- const dirs = new Set();
4004
- const excluded = new Set();
4005
- const visitedConfigs = new Set();
4006
- const collectConfigDependencies = async (configFile, fallbackRoot, collectExcluded)=>{
4007
- const normalizedConfigFile = external_node_path_default().normalize(configFile);
4008
- const configKey = toComparisonPath(normalizedConfigFile);
4009
- if (visitedConfigs.has(configKey)) return;
4010
- visitedConfigs.add(configKey);
4011
- const configDir = external_node_path_default().dirname(normalizedConfigFile);
4012
- const normalizedRoot = external_node_path_default().normalize(fallbackRoot);
4013
- files.add(normalizedConfigFile);
4014
- if (!Array.from(dirs).some((dir)=>'' === external_node_path_default().relative(dir, normalizedRoot) || isInsideAnotherPath(dir, normalizedRoot))) dirs.add(normalizedRoot);
4015
- excluded.add(external_node_path_default().join(normalizedRoot, 'node_modules'));
4016
- let parsedConfig;
4017
- try {
4018
- parsedConfig = await runTypeScriptGoShowConfig(executable, normalizedConfigFile);
4019
- } catch {
4020
- return;
4021
- }
4022
- for (const file of parsedConfig.files || [])files.add(external_node_path_default().normalize(external_node_path_default().resolve(configDir, file)));
4023
- if (collectExcluded && !parsedConfig.references?.length) for (const exclude of parsedConfig.exclude || [])excluded.add(external_node_path_default().normalize(external_node_path_default().resolve(configDir, exclude)));
4024
- for (const reference of parsedConfig.references || [])if (reference.path) {
4025
- const resolvedReference = external_node_path_default().resolve(configDir, reference.path);
4026
- const referenceConfig = '.json' === external_node_path_default().extname(resolvedReference).toLowerCase() ? resolvedReference : external_node_path_default().join(resolvedReference, 'tsconfig.json');
4027
- await collectConfigDependencies(referenceConfig, external_node_path_default().dirname(referenceConfig), false);
4064
+ class IssueRspackError extends Error {
4065
+ constructor(message, pathType, issue){
4066
+ super(message), issue_rspack_error_define_property(this, "issue", void 0), issue_rspack_error_define_property(this, "hideStack", void 0), issue_rspack_error_define_property(this, "file", void 0), this.issue = issue, this.hideStack = true;
4067
+ if (issue.file) {
4068
+ this.file = 'absolute' === pathType ? forwardSlash(external_node_path_default().resolve(issue.file)) : relativeToContext(issue.file, process.cwd());
4069
+ if (issue.location) this.file += `:${formatIssueLocation(issue.location)}`;
4028
4070
  }
4029
- };
4030
- await collectConfigDependencies(config.configFile, config.context, true);
4031
- return {
4032
- files: Array.from(files),
4033
- dirs: Array.from(dirs),
4034
- excluded: Array.from(excluded),
4035
- extensions: [
4036
- '.ts',
4037
- '.tsx',
4038
- '.mts',
4039
- '.cts',
4040
- '.js',
4041
- '.jsx',
4042
- '.mjs',
4043
- '.cjs',
4044
- '.json'
4045
- ]
4046
- };
4071
+ Error.captureStackTrace(this, this.constructor);
4072
+ }
4047
4073
  }
4048
4074
  function tapAfterCompileToGetIssues(compiler, config, state) {
4049
4075
  const hooks = getPluginHooks(compiler);
@@ -4374,6 +4400,7 @@ var __webpack_exports__ = {};
4374
4400
  await assertTypeScriptGoExecutableOnce();
4375
4401
  state.initialized = true;
4376
4402
  state.watching = true;
4403
+ if (config.typescript.build && 'write-references' === config.typescript.mode) state.emittedFiles = new Map();
4377
4404
  if (config.async) {
4378
4405
  debug('Initializing tsgo for watch run (async).');
4379
4406
  tapDoneToAsyncGetIssues(compiler, config, state);
@@ -4422,12 +4449,10 @@ var __webpack_exports__ = {};
4422
4449
  }
4423
4450
  canReuseIssues = false;
4424
4451
  const iteration = ++state.iteration;
4425
- if (state.abortController) {
4452
+ if (state.abortController && !state.emittedFiles) {
4426
4453
  debug(`Aborting tsgo iteration ${iteration - 1}.`);
4427
4454
  state.abortController.abort();
4428
4455
  }
4429
- const abortController = new AbortController();
4430
- state.abortController = abortController;
4431
4456
  state.watching ? log([
4432
4457
  'Calling tsgo for incremental check.',
4433
4458
  ` Changed files: ${JSON.stringify(filesChange.changedFiles)}`,
@@ -4469,29 +4494,34 @@ var __webpack_exports__ = {};
4469
4494
  state.aggregatedFilesChange = aggregatedFilesChange;
4470
4495
  canReuseIssues = true;
4471
4496
  state.issuesPromise = (state.issuesPromise || Promise.resolve()).catch(()=>void 0).then(()=>{
4472
- if (abortController.signal.aborted) return;
4497
+ if (iteration !== state.iteration) return;
4498
+ const abortController = new AbortController();
4499
+ state.abortController = abortController;
4473
4500
  debug(`Submitting tsgo to the pool, iteration ${iteration}.`);
4474
4501
  return issuesPool.submit(async (signal)=>{
4475
4502
  try {
4503
+ if (iteration !== state.iteration) return;
4476
4504
  debug(`Running tsgo, iteration ${iteration}.`);
4477
- const issues = await runTypeScriptGo(config.typescript, config.logger, config.issue.defaultSeverity, signal);
4505
+ const issues = await runTypeScriptGo(config.typescript, config.logger, config.issue.defaultSeverity, signal, state.emittedFiles);
4506
+ if (iteration !== state.iteration) return;
4478
4507
  if (state.aggregatedFilesChange === aggregatedFilesChange) state.aggregatedFilesChange = void 0;
4479
4508
  if (state.abortController === abortController) {
4480
4509
  if (issues.some(isTypeScriptGoIssue)) canReuseIssues = false;
4481
4510
  state.abortController = void 0;
4482
4511
  }
4483
4512
  return issues;
4484
- } catch (error) {
4485
- if (state.abortController === abortController) canReuseIssues = false;
4486
- hooks.error.call(error, compilation);
4487
- return;
4488
4513
  } finally{
4489
4514
  debug(`tsgo finished its job, iteration ${iteration}.`);
4490
4515
  }
4491
- }, abortController.signal);
4516
+ }, abortController.signal).catch((error)=>{
4517
+ if (error instanceof AbortError && abortController.signal.aborted) return;
4518
+ if (state.abortController === abortController) canReuseIssues = false;
4519
+ hooks.error.call(error, compilation);
4520
+ });
4492
4521
  });
4493
4522
  });
4494
4523
  const abortTypeScriptGo = ()=>{
4524
+ ++state.iteration;
4495
4525
  if (state.abortController) {
4496
4526
  debug('Compiler is going to close - terminating tsgo...');
4497
4527
  state.abortController.abort();