ts-checker-rspack-plugin 1.7.0 → 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,238 +3325,552 @@ 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
- interval: interval,
3430
- binaryInterval: interval,
3431
- alwaysStat: true,
3432
- atomic: true,
3433
- awaitWriteFinish: true
3434
- });
3435
- dirWatcher.on('add', (file, stats)=>{
3436
- if (this.paused) return;
3437
- const extension = (0, external_node_path_namespaceObject.extname)(file);
3438
- const supportedExtensions = this.pluginState.lastDependencies?.extensions || [];
3439
- if (!supportedExtensions.includes(extension)) return void debug('Detected new file add but extension is not supported', file);
3440
- debug('Detected new file add', file);
3441
- this.deletedFiles.delete(file);
3442
- updateFilesChange(this.compiler, {
3443
- changedFiles: [
3444
- file
3445
- ]
3446
- });
3447
- this.watcher?._onChange(file, stats?.mtimeMs || stats?.ctimeMs || 1, file, 'rename');
3448
- });
3449
- dirWatcher.on('unlink', (file)=>{
3450
- if (this.paused) return;
3451
- const extension = (0, external_node_path_namespaceObject.extname)(file);
3452
- const supportedExtensions = this.pluginState.lastDependencies?.extensions || [];
3453
- if (!supportedExtensions.includes(extension)) return void debug('Detected new file remove but extension is not supported', file);
3454
- if (this.deletedFiles.has(file)) return void debug('Skipping duplicated unlink event.');
3455
- debug('Detected new file remove', file);
3456
- this.deletedFiles.add(file);
3457
- updateFilesChange(this.compiler, {
3458
- deletedFiles: [
3459
- file
3460
- ]
3461
- });
3462
- this.watcher?._onRemove(dirToWatch, file, 'rename');
3463
- });
3464
- this.dirsWatchers.set(dirToWatch, dirWatcher);
3465
- });
3466
- this.paused = false;
3467
- return {
3468
- ...standardWatcher,
3469
- close: ()=>{
3470
- clearFilesChange(this.compiler);
3471
- if (standardWatcher) standardWatcher.close();
3472
- this.dirsWatchers.forEach((dirWatcher)=>{
3473
- dirWatcher?.close();
3474
- });
3475
- this.dirsWatchers.clear();
3476
- this.paused = true;
3477
- },
3478
- pause: ()=>{
3479
- if (standardWatcher) standardWatcher.pause();
3480
- this.paused = true;
3481
- }
3482
- };
3483
- };
3484
- this.dirsWatchers = new Map();
3485
- this.deletedFiles = new Set();
3335
+ constructor(message = 'Task aborted.'){
3336
+ super(message);
3337
+ this.name = 'AbortError';
3486
3338
  }
3487
3339
  }
3488
- function tapAfterEnvironmentToPatchWatching(compiler, state) {
3489
- const { debug } = getInfrastructureLogger(compiler);
3490
- compiler.hooks.afterEnvironment.tap('TsCheckerRspackPlugin', ()=>{
3491
- const watchFileSystem = compiler.watchFileSystem;
3492
- if (watchFileSystem) {
3493
- debug("Overwriting Rspack's watch file system.");
3494
- compiler.watchFileSystem = new InclusiveNodeWatchFileSystem(watchFileSystem, compiler, state);
3495
- } else debug('No watch file system found - plugin may not work correctly.');
3496
- });
3497
- }
3498
- var external_picocolors_ = __webpack_require__("picocolors");
3499
- var external_picocolors_default = /*#__PURE__*/ __webpack_require__.n(external_picocolors_);
3500
- const lite_tapable_namespaceObject = require("@rspack/lite-tapable");
3501
- const compilerHookMap = new WeakMap();
3502
- function createPluginHooks() {
3503
- return {
3504
- start: new lite_tapable_namespaceObject.AsyncSeriesWaterfallHook([
3505
- 'change',
3506
- 'compilation'
3507
- ]),
3508
- waiting: new lite_tapable_namespaceObject.SyncHook([
3509
- 'compilation'
3510
- ]),
3511
- canceled: new lite_tapable_namespaceObject.SyncHook([
3512
- 'compilation'
3513
- ]),
3514
- error: new lite_tapable_namespaceObject.SyncHook([
3515
- 'error',
3516
- 'compilation'
3517
- ]),
3518
- issues: new lite_tapable_namespaceObject.SyncWaterfallHook([
3519
- 'issues',
3520
- 'compilation'
3521
- ])
3522
- };
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;
3523
3348
  }
3524
- function forwardPluginHooks(source, target) {
3525
- source.start.tapPromise('TsCheckerRspackPlugin', target.start.promise);
3526
- source.waiting.tap('TsCheckerRspackPlugin', target.waiting.call);
3527
- source.canceled.tap('TsCheckerRspackPlugin', target.canceled.call);
3528
- source.error.tap('TsCheckerRspackPlugin', target.error.call);
3529
- source.issues.tap('TsCheckerRspackPlugin', target.issues.call);
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;
3530
3358
  }
3531
- function getPluginHooks(compiler) {
3532
- let hooks = compilerHookMap.get(compiler);
3533
- if (void 0 === hooks) {
3534
- hooks = createPluginHooks();
3535
- compilerHookMap.set(compiler, hooks);
3536
- if ('compilers' in compiler) compiler.compilers.forEach((childCompiler)=>{
3537
- const childHooks = getPluginHooks(childCompiler);
3538
- if (hooks) forwardPluginHooks(childHooks, hooks);
3539
- });
3540
- }
3541
- return hooks;
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);
3542
3363
  }
3543
- const external_node_process_namespaceObject = require("node:process");
3544
- function createControlledPromise() {
3545
- let resolve = ()=>void 0;
3546
- let reject = ()=>void 0;
3547
- const promise = new Promise((aResolve, aReject)=>{
3548
- resolve = aResolve;
3549
- reject = aReject;
3550
- });
3364
+ async function resolveTypeScriptGoExecutable(config) {
3365
+ const binPath = await resolveTypeScriptGoBinPath(config);
3551
3366
  return {
3552
- promise,
3553
- resolve,
3554
- reject
3367
+ command: binPath,
3368
+ args: []
3555
3369
  };
3556
3370
  }
3557
- function rpc_error_define_property(obj, key, value) {
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;
3387
+ }
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();
3851
+ compilerHookMap.set(compiler, hooks);
3852
+ if ('compilers' in compiler) compiler.compilers.forEach((childCompiler)=>{
3853
+ const childHooks = getPluginHooks(childCompiler);
3854
+ if (hooks) forwardPluginHooks(childHooks, hooks);
3855
+ });
3856
+ }
3857
+ return hooks;
3858
+ }
3859
+ const external_node_process_namespaceObject = require("node:process");
3860
+ function createControlledPromise() {
3861
+ let resolve = ()=>void 0;
3862
+ let reject = ()=>void 0;
3863
+ const promise = new Promise((aResolve, aReject)=>{
3864
+ resolve = aResolve;
3865
+ reject = aReject;
3866
+ });
3867
+ return {
3868
+ promise,
3869
+ resolve,
3870
+ reject
3871
+ };
3872
+ }
3873
+ function rpc_error_define_property(obj, key, value) {
3558
3874
  if (key in obj) Object.defineProperty(obj, key, {
3559
3875
  value: value,
3560
3876
  enumerable: true,
@@ -3615,7 +3931,6 @@ var __webpack_exports__ = {};
3615
3931
  function uuid() {
3616
3932
  return new Array(4).fill(0).map(()=>Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join('-');
3617
3933
  }
3618
- const external_node_child_process_namespaceObject = require("node:child_process");
3619
3934
  const WORKER_DATA_ENV_KEY = 'WORKER_DATA';
3620
3935
  function createRpcWorker(modulePath, data, memoryLimit) {
3621
3936
  const options = {
@@ -3668,380 +3983,93 @@ var __webpack_exports__ = {};
3668
3983
  return remoteMethod(...args);
3669
3984
  }, worker);
3670
3985
  }
3671
- class AbortError extends Error {
3672
- static throwIfAborted(signal) {
3673
- if (signal?.aborted) throw new AbortError();
3674
- }
3675
- constructor(message = 'Task aborted.'){
3676
- super(message);
3677
- this.name = 'AbortError';
3678
- }
3679
- }
3680
- function tapErrorToLogMessage(compiler, config) {
3681
- const hooks = getPluginHooks(compiler);
3682
- hooks.error.tap('TsCheckerRspackPlugin', (error)=>{
3683
- if (error instanceof AbortError) return;
3684
- config.logger.error(String(error));
3685
- 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."));
3686
- 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."));
3687
- });
3688
- }
3689
- const external_node_os_namespaceObject = require("node:os");
3690
- var external_node_os_default = /*#__PURE__*/ __webpack_require__.n(external_node_os_namespaceObject);
3691
- function createPool(size) {
3692
- let pendingPromises = [];
3693
- const pool = {
3694
- async submit (task, signal) {
3695
- while(pendingPromises.length >= pool.size){
3696
- AbortError.throwIfAborted(signal);
3697
- await Promise.race(pendingPromises).catch(()=>void 0);
3698
- }
3699
- AbortError.throwIfAborted(signal);
3700
- const taskPromise = task(signal).finally(()=>{
3701
- pendingPromises = pendingPromises.filter((pendingPromise)=>pendingPromise !== taskPromise);
3702
- });
3703
- pendingPromises.push(taskPromise);
3704
- return taskPromise;
3705
- },
3706
- size,
3707
- get pending () {
3708
- return pendingPromises.length;
3709
- },
3710
- get drained () {
3711
- return new Promise(async (resolve)=>{
3712
- while(pendingPromises.length > 0)await Promise.race(pendingPromises).catch(()=>void 0);
3713
- resolve(void 0);
3714
- });
3715
- }
3716
- };
3717
- return pool;
3718
- }
3719
- const issuesPool = createPool(Math.max(1, external_node_os_namespaceObject.cpus().length));
3720
- const dependenciesPool = createPool(Math.max(1, external_node_os_namespaceObject.cpus().length));
3721
- function interceptDoneToGetDevServerTap(compiler, config, state) {
3722
- const { debug } = getInfrastructureLogger(compiler);
3723
- compiler.hooks.done.intercept({
3724
- register: (tap)=>{
3725
- if ([
3726
- 'webpack-dev-server',
3727
- 'rsbuild-dev-server',
3728
- 'rspack-dev-server'
3729
- ].includes(tap.name) && 'sync' === tap.type && config.devServer) {
3730
- debug('Intercepting dev-server tap.');
3731
- state.DevServerDoneTap = tap;
3732
- }
3733
- return tap;
3734
- }
3735
- });
3736
- }
3737
- function forwardSlash(input) {
3738
- return external_node_path_default().normalize(input).replace(/\\+/g, '/');
3739
- }
3740
- function relativeToContext(file, context) {
3741
- let fileInContext = forwardSlash(external_node_path_default().relative(context, file));
3742
- if (!fileInContext.startsWith('../')) fileInContext = './' + fileInContext;
3743
- return fileInContext;
3744
- }
3745
- function formatIssueLocation(location) {
3746
- return `${location.start.line}:${location.start.column}`;
3747
- }
3748
- function issue_rspack_error_define_property(obj, key, value) {
3749
- if (key in obj) Object.defineProperty(obj, key, {
3750
- value: value,
3751
- enumerable: true,
3752
- configurable: true,
3753
- writable: true
3754
- });
3755
- else obj[key] = value;
3756
- return obj;
3757
- }
3758
- class IssueRspackError extends Error {
3759
- constructor(message, pathType, issue){
3760
- 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;
3761
- if (issue.file) {
3762
- this.file = 'absolute' === pathType ? forwardSlash(external_node_path_default().resolve(issue.file)) : relativeToContext(issue.file, process.cwd());
3763
- if (issue.location) this.file += `:${formatIssueLocation(issue.location)}`;
3764
- }
3765
- Error.captureStackTrace(this, this.constructor);
3766
- }
3767
- }
3768
- const external_node_fs_namespaceObject = require("node:fs");
3769
- var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
3770
- const external_node_url_namespaceObject = require("node:url");
3771
- const external_node_util_namespaceObject = require("node:util");
3772
- const TYPESCRIPT_PACKAGE = "typescript";
3773
- const TYPESCRIPT_PACKAGE_JSON = `${TYPESCRIPT_PACKAGE}/package.json`;
3774
- const TYPESCRIPT_PREVIEW_PACKAGE = "@typescript/native-preview";
3775
- const TYPESCRIPT_PREVIEW_PACKAGE_JSON = `${TYPESCRIPT_PREVIEW_PACKAGE}/package.json`;
3776
- function resolveTypeScriptGoPackageJsonPath(config) {
3777
- 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.");
3778
- if (!config.tsgoPackage) throw new Error(`The typescriptPath option must point to "${TYPESCRIPT_PREVIEW_PACKAGE_JSON}" or "${TYPESCRIPT_PACKAGE}@>=7".`);
3779
- return config.typescriptPath;
3780
- }
3781
- async function resolveTypeScriptGoNativeExecutablePath(packageJsonPath, packageName) {
3782
- const getExePathPath = external_node_path_default().resolve(external_node_path_default().dirname(packageJsonPath), './lib/getExePath.js');
3783
- const getExePathUrl = (0, external_node_url_namespaceObject.pathToFileURL)(getExePathPath).href;
3784
- const getExePathModule = await import(getExePathUrl);
3785
- const getExePath = getExePathModule.default || getExePathModule.getExePath;
3786
- if ('function' != typeof getExePath) throw new Error(`Cannot resolve the native TypeScript executable from "${packageName}".`);
3787
- const executablePath = getExePath();
3788
- if ('string' != typeof executablePath || !external_node_fs_default().existsSync(executablePath)) throw new Error('Executable not found');
3789
- return executablePath;
3790
- }
3791
- async function resolveTypeScriptGoBinPath(config) {
3792
- const packageJsonPath = resolveTypeScriptGoPackageJsonPath(config);
3793
- if ("typescript" === config.tsgoPackage) return resolveTypeScriptGoNativeExecutablePath(packageJsonPath, TYPESCRIPT_PACKAGE);
3794
- return resolveTypeScriptGoNativeExecutablePath(packageJsonPath, TYPESCRIPT_PREVIEW_PACKAGE);
3795
- }
3796
- async function resolveTypeScriptGoExecutable(config) {
3797
- const binPath = await resolveTypeScriptGoBinPath(config);
3798
- return {
3799
- command: binPath,
3800
- args: []
3801
- };
3802
- }
3803
- async function runTypeScriptGoShowConfig(executable, configFile) {
3804
- const { stdout } = await (0, external_node_util_namespaceObject.promisify)(external_node_child_process_namespaceObject.execFile)(executable.command, [
3805
- ...executable.args,
3806
- '--project',
3807
- configFile,
3808
- '--showConfig',
3809
- '--pretty',
3810
- 'false'
3811
- ], {
3812
- cwd: external_node_path_default().dirname(configFile),
3813
- encoding: 'utf8',
3814
- maxBuffer: 67108864
3815
- });
3816
- const parsedConfig = JSON.parse(stdout);
3817
- if (!parsedConfig || 'object' != typeof parsedConfig || Array.isArray(parsedConfig)) throw new TypeError('Invalid tsgo --showConfig output.');
3818
- return parsedConfig;
3819
- }
3820
- function toComparisonPath(file) {
3821
- const normalizedPath = external_node_path_default().normalize(file);
3822
- return 'win32' === process.platform ? normalizedPath.toLowerCase() : normalizedPath;
3823
- }
3824
- function shouldRefreshTypeScriptGoDependencies(dependencies, { changedFiles = [], deletedFiles = [] }) {
3825
- if (!dependencies) return true;
3826
- const dependencyKeys = dependencies.files.map((file)=>toComparisonPath(file));
3827
- return changedFiles.some((file)=>{
3828
- const key = toComparisonPath(file);
3829
- const extension = external_node_path_default().extname(file).toLowerCase();
3830
- return '.json' === extension || dependencies.extensions.includes(extension) && !dependencyKeys.includes(key);
3831
- }) || deletedFiles.some((file)=>dependencyKeys.includes(toComparisonPath(file)));
3832
- }
3833
- function createTypeScriptGoArgs(config) {
3834
- const args = config.build ? [
3835
- '--build',
3836
- config.configFile
3837
- ] : [
3838
- '--project',
3839
- config.configFile
3840
- ];
3841
- args.push('--noEmit', '--pretty');
3842
- return args;
3843
- }
3844
- function logOutput(logger, output) {
3845
- if (!output.trim()) return;
3846
- logger.error(output.trimEnd());
3847
- }
3848
- function stripAnsi(output) {
3849
- return output.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '');
3850
- }
3851
- function getTypeScriptGoErrorCount(output) {
3852
- const plainOutput = stripAnsi(output);
3853
- const matches = Array.from(plainOutput.matchAll(/\bFound\s+(\d+)\s+errors?\b/g));
3854
- const lastMatch = matches[matches.length - 1];
3855
- if (!lastMatch) return;
3856
- return Number(lastMatch[1]);
3857
- }
3858
- function getTypeScriptGoIssueSeverity(severity, defaultSeverity) {
3859
- 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
+ });
3860
3994
  }
3861
- function createTypeScriptGoIssue(message) {
3862
- return {
3863
- severity: 'error',
3864
- code: "TSGO",
3865
- 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
+ }
3866
4022
  };
4023
+ return pool;
3867
4024
  }
3868
- const diagnosticPattern = /^(.*?):(\d+):(\d+)\s+-\s+(error|warning)\s+TS(\d+):\s+(.+)$/;
3869
- const globalDiagnosticPattern = /^(error|warning)\s+TS(\d+):\s+(.+)$/;
3870
- function getTypeScriptGoMarkerLength(output, startIndex) {
3871
- const lines = output.slice(startIndex).split(/\r?\n/);
3872
- for (const line of lines){
3873
- if (diagnosticPattern.test(line) || globalDiagnosticPattern.test(line) || /^Found\s+\d+\s+errors?\b/.test(line)) break;
3874
- const marker = line.match(/^\s*([~^]+)\s*$/);
3875
- if (marker) return marker[1].length;
3876
- }
3877
- }
3878
- function parseTypeScriptGoIssues(output, config, defaultSeverity = 'auto') {
3879
- const issues = [];
3880
- const plainOutput = stripAnsi(output);
3881
- const diagnosticPatternWithGlobal = new RegExp(diagnosticPattern, 'gm');
3882
- const globalDiagnosticPatternWithGlobal = new RegExp(globalDiagnosticPattern, 'gm');
3883
- for (const match of plainOutput.matchAll(diagnosticPatternWithGlobal)){
3884
- const [, file, line, column, severity, code, message] = match;
3885
- const startColumn = Number(column);
3886
- const markerLength = getTypeScriptGoMarkerLength(plainOutput, (match.index || 0) + match[0].length);
3887
- const position = {
3888
- line: Number(line),
3889
- column: startColumn
3890
- };
3891
- issues.push({
3892
- severity: getTypeScriptGoIssueSeverity(severity, defaultSeverity),
3893
- code: `TS${code}`,
3894
- message,
3895
- file: external_node_path_default().isAbsolute(file) ? file : external_node_path_default().resolve(config.context, file),
3896
- location: {
3897
- start: position,
3898
- end: {
3899
- line: position.line,
3900
- column: markerLength ? startColumn + markerLength : startColumn
3901
- }
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;
3902
4038
  }
3903
- });
3904
- }
3905
- for (const match of plainOutput.matchAll(globalDiagnosticPatternWithGlobal)){
3906
- const [, severity, code, message] = match;
3907
- issues.push({
3908
- severity: getTypeScriptGoIssueSeverity(severity, defaultSeverity),
3909
- code: `TS${code}`,
3910
- message
3911
- });
3912
- }
3913
- return issues;
4039
+ return tap;
4040
+ }
4041
+ });
3914
4042
  }
3915
- function createTypeScriptGoExitIssues(output, signal, config, defaultSeverity = 'auto') {
3916
- const parsedIssues = parseTypeScriptGoIssues(output, config, defaultSeverity);
3917
- const errorCount = getTypeScriptGoErrorCount(output);
3918
- if (parsedIssues.length && (void 0 === errorCount || parsedIssues.length >= errorCount)) return parsedIssues;
3919
- if (void 0 !== errorCount) return Array.from({
3920
- length: Math.max(errorCount, 1)
3921
- }, ()=>createTypeScriptGoIssue('tsgo check failed. See the output above for diagnostics.'));
3922
- if (null !== signal) return [
3923
- createTypeScriptGoIssue(`tsgo check interrupted by ${signal}. See the output above for diagnostics.`)
3924
- ];
3925
- return [
3926
- createTypeScriptGoIssue('tsgo check failed. See the output above for diagnostics.')
3927
- ];
4043
+ function forwardSlash(input) {
4044
+ return external_node_path_default().normalize(input).replace(/\\+/g, '/');
3928
4045
  }
3929
- function isTypeScriptGoIssue(issue) {
3930
- 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;
3931
4050
  }
3932
- function isTypeScriptGoStatsError(error) {
3933
- const issue = error?.issue;
3934
- if (issue && isTypeScriptGoIssue(issue)) return true;
3935
- const message = error?.message;
3936
- return 'string' == typeof message && message.includes("TSGO:");
4051
+ function formatIssueLocation(location) {
4052
+ return `${location.start.line}:${location.start.column}`;
3937
4053
  }
3938
- async function runTypeScriptGo(config, logger, defaultSeverity = 'auto', signal) {
3939
- AbortError.throwIfAborted(signal);
3940
- const executable = await resolveTypeScriptGoExecutable(config);
3941
- const args = createTypeScriptGoArgs(config);
3942
- return new Promise((resolve, reject)=>{
3943
- let settled = false;
3944
- let output = '';
3945
- const childProcess = (0, external_node_child_process_namespaceObject.spawn)(executable.command, [
3946
- ...executable.args,
3947
- ...args
3948
- ], {
3949
- cwd: config.context,
3950
- stdio: [
3951
- 'inherit',
3952
- 'pipe',
3953
- 'pipe'
3954
- ]
3955
- });
3956
- const cleanup = ()=>{
3957
- signal?.removeEventListener('abort', abort);
3958
- childProcess.stdout?.removeAllListeners();
3959
- childProcess.stderr?.removeAllListeners();
3960
- childProcess.removeAllListeners();
3961
- };
3962
- const finish = (callback)=>{
3963
- if (settled) return;
3964
- settled = true;
3965
- cleanup();
3966
- callback();
3967
- };
3968
- const abort = ()=>{
3969
- childProcess.kill('SIGKILL');
3970
- finish(()=>reject(new AbortError()));
3971
- };
3972
- signal?.addEventListener('abort', abort, {
3973
- once: true
3974
- });
3975
- childProcess.stdout?.on('data', (data)=>{
3976
- output += data.toString();
3977
- });
3978
- childProcess.stderr?.on('data', (data)=>{
3979
- output += data.toString();
3980
- });
3981
- childProcess.on('error', (error)=>{
3982
- finish(()=>reject(error));
3983
- });
3984
- childProcess.on('close', (exitCode, exitSignal)=>{
3985
- finish(()=>{
3986
- if (0 === exitCode && null === exitSignal) {
3987
- logOutput(logger, output);
3988
- resolve([]);
3989
- return;
3990
- }
3991
- const issues = createTypeScriptGoExitIssues(output, exitSignal, config, defaultSeverity);
3992
- if (issues.some(isTypeScriptGoIssue)) logOutput(logger, output);
3993
- resolve(issues);
3994
- });
3995
- });
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
3996
4060
  });
4061
+ else obj[key] = value;
4062
+ return obj;
3997
4063
  }
3998
- async function getTypeScriptGoDependencies(config) {
3999
- const executable = await resolveTypeScriptGoExecutable(config);
4000
- const files = new Set();
4001
- const dirs = new Set();
4002
- const excluded = new Set();
4003
- const visitedConfigs = new Set();
4004
- const collectConfigDependencies = async (configFile, fallbackRoot, collectExcluded)=>{
4005
- const normalizedConfigFile = external_node_path_default().normalize(configFile);
4006
- const configKey = toComparisonPath(normalizedConfigFile);
4007
- if (visitedConfigs.has(configKey)) return;
4008
- visitedConfigs.add(configKey);
4009
- const configDir = external_node_path_default().dirname(normalizedConfigFile);
4010
- const normalizedRoot = external_node_path_default().normalize(fallbackRoot);
4011
- files.add(normalizedConfigFile);
4012
- if (!Array.from(dirs).some((dir)=>'' === external_node_path_default().relative(dir, normalizedRoot) || isInsideAnotherPath(dir, normalizedRoot))) dirs.add(normalizedRoot);
4013
- excluded.add(external_node_path_default().join(normalizedRoot, 'node_modules'));
4014
- let parsedConfig;
4015
- try {
4016
- parsedConfig = await runTypeScriptGoShowConfig(executable, normalizedConfigFile);
4017
- } catch {
4018
- return;
4019
- }
4020
- for (const file of parsedConfig.files || [])files.add(external_node_path_default().normalize(external_node_path_default().resolve(configDir, file)));
4021
- 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)));
4022
- for (const reference of parsedConfig.references || [])if (reference.path) {
4023
- const resolvedReference = external_node_path_default().resolve(configDir, reference.path);
4024
- const referenceConfig = '.json' === external_node_path_default().extname(resolvedReference).toLowerCase() ? resolvedReference : external_node_path_default().join(resolvedReference, 'tsconfig.json');
4025
- 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)}`;
4026
4070
  }
4027
- };
4028
- await collectConfigDependencies(config.configFile, config.context, true);
4029
- return {
4030
- files: Array.from(files),
4031
- dirs: Array.from(dirs),
4032
- excluded: Array.from(excluded),
4033
- extensions: [
4034
- '.ts',
4035
- '.tsx',
4036
- '.mts',
4037
- '.cts',
4038
- '.js',
4039
- '.jsx',
4040
- '.mjs',
4041
- '.cjs',
4042
- '.json'
4043
- ]
4044
- };
4071
+ Error.captureStackTrace(this, this.constructor);
4072
+ }
4045
4073
  }
4046
4074
  function tapAfterCompileToGetIssues(compiler, config, state) {
4047
4075
  const hooks = getPluginHooks(compiler);
@@ -4372,6 +4400,7 @@ var __webpack_exports__ = {};
4372
4400
  await assertTypeScriptGoExecutableOnce();
4373
4401
  state.initialized = true;
4374
4402
  state.watching = true;
4403
+ if (config.typescript.build && 'write-references' === config.typescript.mode) state.emittedFiles = new Map();
4375
4404
  if (config.async) {
4376
4405
  debug('Initializing tsgo for watch run (async).');
4377
4406
  tapDoneToAsyncGetIssues(compiler, config, state);
@@ -4420,12 +4449,10 @@ var __webpack_exports__ = {};
4420
4449
  }
4421
4450
  canReuseIssues = false;
4422
4451
  const iteration = ++state.iteration;
4423
- if (state.abortController) {
4452
+ if (state.abortController && !state.emittedFiles) {
4424
4453
  debug(`Aborting tsgo iteration ${iteration - 1}.`);
4425
4454
  state.abortController.abort();
4426
4455
  }
4427
- const abortController = new AbortController();
4428
- state.abortController = abortController;
4429
4456
  state.watching ? log([
4430
4457
  'Calling tsgo for incremental check.',
4431
4458
  ` Changed files: ${JSON.stringify(filesChange.changedFiles)}`,
@@ -4467,29 +4494,34 @@ var __webpack_exports__ = {};
4467
4494
  state.aggregatedFilesChange = aggregatedFilesChange;
4468
4495
  canReuseIssues = true;
4469
4496
  state.issuesPromise = (state.issuesPromise || Promise.resolve()).catch(()=>void 0).then(()=>{
4470
- if (abortController.signal.aborted) return;
4497
+ if (iteration !== state.iteration) return;
4498
+ const abortController = new AbortController();
4499
+ state.abortController = abortController;
4471
4500
  debug(`Submitting tsgo to the pool, iteration ${iteration}.`);
4472
4501
  return issuesPool.submit(async (signal)=>{
4473
4502
  try {
4503
+ if (iteration !== state.iteration) return;
4474
4504
  debug(`Running tsgo, iteration ${iteration}.`);
4475
- 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;
4476
4507
  if (state.aggregatedFilesChange === aggregatedFilesChange) state.aggregatedFilesChange = void 0;
4477
4508
  if (state.abortController === abortController) {
4478
4509
  if (issues.some(isTypeScriptGoIssue)) canReuseIssues = false;
4479
4510
  state.abortController = void 0;
4480
4511
  }
4481
4512
  return issues;
4482
- } catch (error) {
4483
- if (state.abortController === abortController) canReuseIssues = false;
4484
- hooks.error.call(error, compilation);
4485
- return;
4486
4513
  } finally{
4487
4514
  debug(`tsgo finished its job, iteration ${iteration}.`);
4488
4515
  }
4489
- }, 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
+ });
4490
4521
  });
4491
4522
  });
4492
4523
  const abortTypeScriptGo = ()=>{
4524
+ ++state.iteration;
4493
4525
  if (state.abortController) {
4494
4526
  debug('Compiler is going to close - terminating tsgo...');
4495
4527
  state.abortController.abort();