@nx/eslint 0.0.0-pr-29636-0cd26ed → 0.0.0-pr-29720-6055188

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.
@@ -10,12 +10,7 @@ export declare function hasOverride(content: string, lookup: (override: Linter.C
10
10
  */
11
11
  export declare function replaceOverride(content: string, root: string, lookup: (override: Linter.ConfigOverride<Linter.RulesRecord>) => boolean, update?: (override: Partial<Linter.ConfigOverride<Linter.RulesRecord>>) => Partial<Linter.ConfigOverride<Linter.RulesRecord>>): string;
12
12
  /**
13
- * Adding import statement to the top of the file
14
- * The imports are added based on a few rules:
15
- * 1. If it's a default import and matches the variable, return content unchanged.
16
- * 2. If it's a named import and the variables are not part of the import object, add them.
17
- * 3. If no existing import and variable is a string, add a default import.
18
- * 4. If no existing import and variable is an array, add it as an object import.
13
+ * Adding require statement to the top of the file
19
14
  */
20
15
  export declare function addImportToFlatConfig(content: string, variable: string | string[], imp: string): string;
21
16
  /**
@@ -23,7 +18,7 @@ export declare function addImportToFlatConfig(content: string, variable: string
23
18
  */
24
19
  export declare function removeImportFromFlatConfig(content: string, variable: string, imp: string): string;
25
20
  /**
26
- * Injects new ts.expression to the end of the module.exports or export default array.
21
+ * Injects new ts.expression to the end of the module.exports array.
27
22
  */
28
23
  export declare function addBlockToFlatConfigExport(content: string, config: ts.Expression | ts.SpreadElement, options?: {
29
24
  insertAtTheEnd?: boolean;
@@ -48,7 +43,7 @@ export declare function addFlatCompatToFlatConfig(content: string): string;
48
43
  * Generate node list representing the imports and the exports blocks
49
44
  * Optionally add flat compat initialization
50
45
  */
51
- export declare function createNodeList(importsMap: Map<string, string>, exportElements: ts.Expression[], format: 'mjs' | 'cjs'): ts.NodeArray<ts.VariableStatement | ts.Identifier | ts.ExpressionStatement | ts.SourceFile>;
46
+ export declare function createNodeList(importsMap: Map<string, string>, exportElements: ts.Expression[]): ts.NodeArray<ts.VariableStatement | ts.Identifier | ts.ExpressionStatement | ts.SourceFile>;
52
47
  export declare function generateSpreadElement(name: string): ts.SpreadElement;
53
48
  export declare function generatePluginExtendsElement(plugins: string[]): ts.SpreadElement;
54
49
  export declare function generatePluginExtendsElementWithCompatFixup(plugin: string): ts.SpreadElement;
@@ -60,7 +55,6 @@ export declare function stringifyNodeList(nodes: ts.NodeArray<ts.VariableStateme
60
55
  * generates AST require statement
61
56
  */
62
57
  export declare function generateRequire(variableName: string | ts.ObjectBindingPattern, imp: string): ts.VariableStatement;
63
- export declare function generateESMImport(variableName: string | ts.ObjectBindingPattern, imp: string): ts.ImportDeclaration;
64
58
  export declare function overrideNeedsCompat(override: Partial<Linter.ConfigOverride<Linter.RulesRecord>>): string | string[] | {
65
59
  [name: string]: boolean;
66
60
  };
@@ -70,7 +64,7 @@ export declare function overrideNeedsCompat(override: Partial<Linter.ConfigOverr
70
64
  */
71
65
  export declare function generateFlatOverride(_override: Partial<Linter.ConfigOverride<Linter.RulesRecord>> & {
72
66
  ignores?: Linter.FlatConfig['ignores'];
73
- }, format: 'mjs' | 'cjs'): ts.ObjectLiteralExpression | ts.SpreadElement;
67
+ }): ts.ObjectLiteralExpression | ts.SpreadElement;
74
68
  export declare function generateFlatPredefinedConfig(predefinedConfigName: string, moduleName?: string, spread?: boolean): ts.ObjectLiteralExpression | ts.SpreadElement | ts.ElementAccessExpression;
75
69
  export declare function mapFilePaths<T extends Partial<Linter.ConfigOverride<Linter.RulesRecord>>>(_override: T): T;
76
70
  /**
@@ -17,7 +17,6 @@ exports.generatePluginExtendsElement = generatePluginExtendsElement;
17
17
  exports.generatePluginExtendsElementWithCompatFixup = generatePluginExtendsElementWithCompatFixup;
18
18
  exports.stringifyNodeList = stringifyNodeList;
19
19
  exports.generateRequire = generateRequire;
20
- exports.generateESMImport = generateESMImport;
21
20
  exports.overrideNeedsCompat = overrideNeedsCompat;
22
21
  exports.generateFlatOverride = generateFlatOverride;
23
22
  exports.generateFlatPredefinedConfig = generateFlatPredefinedConfig;
@@ -36,8 +35,7 @@ const SPREAD_ELEMENTS_REGEXP = /\s*\.\.\.[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*,?\n?/g;
36
35
  */
37
36
  function removeOverridesFromLintConfig(content) {
38
37
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
39
- const format = content.includes('export default') ? 'mjs' : 'cjs';
40
- const exportsArray = format === 'mjs' ? findExportDefault(source) : findModuleExports(source);
38
+ const exportsArray = findAllBlocks(source);
41
39
  if (!exportsArray) {
42
40
  return content;
43
41
  }
@@ -54,16 +52,7 @@ function removeOverridesFromLintConfig(content) {
54
52
  });
55
53
  return (0, devkit_1.applyChangesToString)(content, changes);
56
54
  }
57
- // TODO Change name
58
- function findExportDefault(source) {
59
- return ts.forEachChild(source, function analyze(node) {
60
- if (ts.isExportAssignment(node) &&
61
- ts.isArrayLiteralExpression(node.expression)) {
62
- return node.expression.elements;
63
- }
64
- });
65
- }
66
- function findModuleExports(source) {
55
+ function findAllBlocks(source) {
67
56
  return ts.forEachChild(source, function analyze(node) {
68
57
  if (ts.isExpressionStatement(node) &&
69
58
  ts.isBinaryExpression(node.expression) &&
@@ -85,8 +74,7 @@ function isOverride(node) {
85
74
  }
86
75
  function hasOverride(content, lookup) {
87
76
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
88
- const format = content.includes('export default') ? 'mjs' : 'cjs';
89
- const exportsArray = format === 'mjs' ? findExportDefault(source) : findModuleExports(source);
77
+ const exportsArray = findAllBlocks(source);
90
78
  if (!exportsArray) {
91
79
  return false;
92
80
  }
@@ -117,16 +105,14 @@ function parseTextToJson(text) {
117
105
  .replace(/'/g, '"')
118
106
  .replace(/\s([a-zA-Z0-9_]+)\s*:/g, ' "$1": ')
119
107
  // stringify any require calls to avoid JSON parsing errors, turn them into just the string value being required
120
- .replace(/require\(['"]([^'"]+)['"]\)/g, '"$1"')
121
- .replace(/\(?await import\(['"]([^'"]+)['"]\)\)?/g, '"$1"'));
108
+ .replace(/require\(['"]([^'"]+)['"]\)/g, '"$1"'));
122
109
  }
123
110
  /**
124
111
  * Finds an override matching the lookup function and applies the update function to it
125
112
  */
126
113
  function replaceOverride(content, root, lookup, update) {
127
114
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
128
- const format = content.includes('export default') ? 'mjs' : 'cjs';
129
- const exportsArray = format === 'mjs' ? findExportDefault(source) : findModuleExports(source);
115
+ const exportsArray = findAllBlocks(source);
130
116
  if (!exportsArray) {
131
117
  return content;
132
118
  }
@@ -159,17 +145,19 @@ function replaceOverride(content, root, lookup, update) {
159
145
  let updatedData = update(data);
160
146
  if (updatedData) {
161
147
  updatedData = mapFilePaths(updatedData);
162
- const parserReplacement = format === 'mjs'
163
- ? (parser) => `(await import('${parser}'))`
164
- : (parser) => `require('${parser}')`;
165
148
  changes.push({
166
149
  type: devkit_1.ChangeType.Insert,
167
150
  index: start,
151
+ // NOTE: Indentation added to format without formatting tools like Prettier.
168
152
  text: ' ' +
169
153
  JSON.stringify(updatedData, null, 2)
170
- .replace(/"parser": "([^"]+)"/g, (_, parser) => `"parser": ${parserReplacement(parser)}`)
171
- .slice(2, -2) // Remove curly braces and start/end line breaks
172
- .replaceAll(/\n/g, '\n '), // Maintain indentation
154
+ // restore any parser require calls that were stripped during JSON parsing
155
+ .replace(/"parser": "([^"]+)"/g, (_, parser) => {
156
+ return `"parser": require('${parser}')`;
157
+ })
158
+ .slice(2, -2) // remove curly braces and start/end line breaks since we are injecting just properties
159
+ // Append indentation so file is formatted without Prettier
160
+ .replaceAll(/\n/g, '\n '),
173
161
  });
174
162
  }
175
163
  }
@@ -178,89 +166,11 @@ function replaceOverride(content, root, lookup, update) {
178
166
  return (0, devkit_1.applyChangesToString)(content, changes);
179
167
  }
180
168
  /**
181
- * Adding import statement to the top of the file
182
- * The imports are added based on a few rules:
183
- * 1. If it's a default import and matches the variable, return content unchanged.
184
- * 2. If it's a named import and the variables are not part of the import object, add them.
185
- * 3. If no existing import and variable is a string, add a default import.
186
- * 4. If no existing import and variable is an array, add it as an object import.
169
+ * Adding require statement to the top of the file
187
170
  */
188
171
  function addImportToFlatConfig(content, variable, imp) {
189
172
  const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
190
173
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
191
- const format = content.includes('export default') ? 'mjs' : 'cjs';
192
- if (format === 'mjs') {
193
- return addESMImportToFlatConfig(source, printer, content, variable, imp);
194
- }
195
- return addCJSImportToFlatConfig(source, printer, content, variable, imp);
196
- }
197
- function addESMImportToFlatConfig(source, printer, content, variable, imp) {
198
- let existingImport;
199
- ts.forEachChild(source, (node) => {
200
- if (ts.isImportDeclaration(node) &&
201
- ts.isStringLiteral(node.moduleSpecifier) &&
202
- node.moduleSpecifier.text === imp) {
203
- existingImport = node;
204
- }
205
- });
206
- // Rule 1:
207
- if (existingImport &&
208
- typeof variable === 'string' &&
209
- existingImport.importClause?.name?.getText() === variable) {
210
- return content;
211
- }
212
- // Rule 2:
213
- if (existingImport &&
214
- existingImport.importClause?.namedBindings &&
215
- Array.isArray(variable)) {
216
- const namedImports = existingImport.importClause
217
- .namedBindings;
218
- const existingElements = namedImports.elements;
219
- // Filter out variables that are already imported
220
- const newVariables = variable.filter((v) => !existingElements.some((e) => e.name.getText() === v));
221
- if (newVariables.length === 0) {
222
- return content;
223
- }
224
- const newImportSpecifiers = newVariables.map((v) => ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(v)));
225
- const lastElement = existingElements[existingElements.length - 1];
226
- const insertIndex = lastElement
227
- ? lastElement.getEnd()
228
- : namedImports.getEnd();
229
- const insertText = printer.printList(ts.ListFormat.NamedImportsOrExportsElements, ts.factory.createNodeArray(newImportSpecifiers), source);
230
- return (0, devkit_1.applyChangesToString)(content, [
231
- {
232
- type: devkit_1.ChangeType.Insert,
233
- index: insertIndex,
234
- text: `, ${insertText}`,
235
- },
236
- ]);
237
- }
238
- // Rule 3:
239
- if (!existingImport && typeof variable === 'string') {
240
- const defaultImport = ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, ts.factory.createIdentifier(variable), undefined), ts.factory.createStringLiteral(imp));
241
- const insert = printer.printNode(ts.EmitHint.Unspecified, defaultImport, source);
242
- return (0, devkit_1.applyChangesToString)(content, [
243
- {
244
- type: devkit_1.ChangeType.Insert,
245
- index: 0,
246
- text: `${insert}\n`,
247
- },
248
- ]);
249
- }
250
- // Rule 4:
251
- if (!existingImport && Array.isArray(variable)) {
252
- const objectImport = ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports(variable.map((v) => ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(v))))), ts.factory.createStringLiteral(imp));
253
- const insert = printer.printNode(ts.EmitHint.Unspecified, objectImport, source);
254
- return (0, devkit_1.applyChangesToString)(content, [
255
- {
256
- type: devkit_1.ChangeType.Insert,
257
- index: 0,
258
- text: `${insert}\n`,
259
- },
260
- ]);
261
- }
262
- }
263
- function addCJSImportToFlatConfig(source, printer, content, variable, imp) {
264
174
  const foundBindingVars = ts.forEachChild(source, function analyze(node) {
265
175
  // we can only combine object binding patterns
266
176
  if (!Array.isArray(variable)) {
@@ -329,48 +239,11 @@ function addCJSImportToFlatConfig(source, printer, content, variable, imp) {
329
239
  },
330
240
  ]);
331
241
  }
332
- function existsAsNamedOrDefaultImport(node, variable) {
333
- const isNamed = node.importClause.namedBindings &&
334
- ts.isNamedImports(node.importClause.namedBindings);
335
- if (Array.isArray(variable)) {
336
- return isNamed || variable.includes(node.importClause?.name?.getText());
337
- }
338
- return ((node.importClause.namedBindings &&
339
- ts.isNamedImports(node.importClause.namedBindings)) ||
340
- node.importClause?.name?.getText() === variable);
341
- }
342
242
  /**
343
243
  * Remove an import from flat config
344
244
  */
345
245
  function removeImportFromFlatConfig(content, variable, imp) {
346
246
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
347
- const format = content.includes('export default') ? 'mjs' : 'cjs';
348
- if (format === 'mjs') {
349
- return removeImportFromFlatConfigESM(source, content, variable, imp);
350
- }
351
- else {
352
- return removeImportFromFlatConfigCJS(source, content, variable, imp);
353
- }
354
- }
355
- function removeImportFromFlatConfigESM(source, content, variable, imp) {
356
- const changes = [];
357
- ts.forEachChild(source, (node) => {
358
- // we can only combine object binding patterns
359
- if (ts.isImportDeclaration(node) &&
360
- ts.isStringLiteral(node.moduleSpecifier) &&
361
- node.moduleSpecifier.text === imp &&
362
- node.importClause &&
363
- existsAsNamedOrDefaultImport(node, variable)) {
364
- changes.push({
365
- type: devkit_1.ChangeType.Delete,
366
- start: node.pos,
367
- length: node.end - node.pos,
368
- });
369
- }
370
- });
371
- return (0, devkit_1.applyChangesToString)(content, changes);
372
- }
373
- function removeImportFromFlatConfigCJS(source, content, variable, imp) {
374
247
  const changes = [];
375
248
  ts.forEachChild(source, (node) => {
376
249
  // we can only combine object binding patterns
@@ -393,44 +266,13 @@ function removeImportFromFlatConfigCJS(source, content, variable, imp) {
393
266
  return (0, devkit_1.applyChangesToString)(content, changes);
394
267
  }
395
268
  /**
396
- * Injects new ts.expression to the end of the module.exports or export default array.
269
+ * Injects new ts.expression to the end of the module.exports array.
397
270
  */
398
271
  function addBlockToFlatConfigExport(content, config, options = {
399
272
  insertAtTheEnd: true,
400
273
  }) {
401
274
  const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
402
275
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
403
- const format = content.includes('export default') ? 'mjs' : 'cjs';
404
- // find the export default array statement
405
- if (format === 'mjs') {
406
- return addBlockToFlatConfigExportESM(content, config, source, printer, options);
407
- }
408
- else {
409
- return addBlockToFlatConfigExportCJS(content, config, source, printer, options);
410
- }
411
- }
412
- function addBlockToFlatConfigExportESM(content, config, source, printer, options = {
413
- insertAtTheEnd: true,
414
- }) {
415
- const exportDefaultStatement = source.statements.find((statement) => ts.isExportAssignment(statement) &&
416
- ts.isArrayLiteralExpression(statement.expression));
417
- if (!exportDefaultStatement)
418
- return content;
419
- const exportArrayLiteral = exportDefaultStatement.expression;
420
- const updatedArrayElements = options.insertAtTheEnd
421
- ? [...exportArrayLiteral.elements, config]
422
- : [config, ...exportArrayLiteral.elements];
423
- const updatedExportDefault = ts.factory.createExportAssignment(undefined, false, ts.factory.createArrayLiteralExpression(updatedArrayElements, true));
424
- // update the existing export default array
425
- const updatedStatements = source.statements.map((statement) => statement === exportDefaultStatement ? updatedExportDefault : statement);
426
- const updatedSource = ts.factory.updateSourceFile(source, updatedStatements);
427
- return printer
428
- .printFile(updatedSource)
429
- .replace(/export default/, '\nexport default');
430
- }
431
- function addBlockToFlatConfigExportCJS(content, config, source, printer, options = {
432
- insertAtTheEnd: true,
433
- }) {
434
276
  const exportsArray = ts.forEachChild(source, function analyze(node) {
435
277
  if (ts.isExpressionStatement(node) &&
436
278
  ts.isBinaryExpression(node.expression) &&
@@ -473,47 +315,28 @@ function addBlockToFlatConfigExportCJS(content, config, source, printer, options
473
315
  }
474
316
  function removePlugin(content, pluginName, pluginImport) {
475
317
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
476
- const format = content.includes('export default') ? 'mjs' : 'cjs';
477
318
  const changes = [];
478
- if (format === 'mjs') {
479
- ts.forEachChild(source, function analyze(node) {
480
- if (ts.isImportDeclaration(node) &&
481
- ts.isStringLiteral(node.moduleSpecifier) &&
482
- node.moduleSpecifier.text === pluginImport) {
483
- const importClause = node.importClause;
484
- if ((importClause && importClause.name) ||
485
- (importClause.namedBindings &&
486
- ts.isNamedImports(importClause.namedBindings))) {
487
- changes.push({
488
- type: devkit_1.ChangeType.Delete,
489
- start: node.pos,
490
- length: node.end - node.pos,
491
- });
492
- }
493
- }
494
- });
495
- }
496
- else {
497
- ts.forEachChild(source, function analyze(node) {
498
- if (ts.isVariableStatement(node) &&
499
- ts.isVariableDeclaration(node.declarationList.declarations[0]) &&
500
- ts.isCallExpression(node.declarationList.declarations[0].initializer) &&
501
- node.declarationList.declarations[0].initializer.arguments.length &&
502
- ts.isStringLiteral(node.declarationList.declarations[0].initializer.arguments[0]) &&
503
- node.declarationList.declarations[0].initializer.arguments[0].text ===
504
- pluginImport) {
505
- changes.push({
506
- type: devkit_1.ChangeType.Delete,
507
- start: node.pos,
508
- length: node.end - node.pos,
509
- });
510
- }
511
- });
512
- }
513
319
  ts.forEachChild(source, function analyze(node) {
514
- if (ts.isExportAssignment(node) &&
515
- ts.isArrayLiteralExpression(node.expression)) {
516
- const blockElements = node.expression.elements;
320
+ if (ts.isVariableStatement(node) &&
321
+ ts.isVariableDeclaration(node.declarationList.declarations[0]) &&
322
+ ts.isCallExpression(node.declarationList.declarations[0].initializer) &&
323
+ node.declarationList.declarations[0].initializer.arguments.length &&
324
+ ts.isStringLiteral(node.declarationList.declarations[0].initializer.arguments[0]) &&
325
+ node.declarationList.declarations[0].initializer.arguments[0].text ===
326
+ pluginImport) {
327
+ changes.push({
328
+ type: devkit_1.ChangeType.Delete,
329
+ start: node.pos,
330
+ length: node.end - node.pos,
331
+ });
332
+ }
333
+ });
334
+ ts.forEachChild(source, function analyze(node) {
335
+ if (ts.isExpressionStatement(node) &&
336
+ ts.isBinaryExpression(node.expression) &&
337
+ node.expression.left.getText() === 'module.exports' &&
338
+ ts.isArrayLiteralExpression(node.expression.right)) {
339
+ const blockElements = node.expression.right.elements;
517
340
  blockElements.forEach((element) => {
518
341
  if (ts.isObjectLiteralExpression(element)) {
519
342
  const pluginsElem = element.properties.find((prop) => prop.name?.getText() === 'plugins');
@@ -603,12 +426,7 @@ function removePlugin(content, pluginName, pluginImport) {
603
426
  function removeCompatExtends(content, compatExtends) {
604
427
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
605
428
  const changes = [];
606
- const format = content.includes('export default') ? 'mjs' : 'cjs';
607
- const exportsArray = format === 'mjs' ? findExportDefault(source) : findModuleExports(source);
608
- if (!exportsArray) {
609
- return content;
610
- }
611
- exportsArray.forEach((node) => {
429
+ findAllBlocks(source)?.forEach((node) => {
612
430
  if (ts.isSpreadElement(node) &&
613
431
  ts.isCallExpression(node.expression) &&
614
432
  ts.isArrowFunction(node.expression.arguments[0]) &&
@@ -642,14 +460,9 @@ function removeCompatExtends(content, compatExtends) {
642
460
  }
643
461
  function removePredefinedConfigs(content, moduleImport, moduleVariable, configs) {
644
462
  const source = ts.createSourceFile('', content, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
645
- const format = content.includes('export default') ? 'mjs' : 'cjs';
646
463
  const changes = [];
647
464
  let removeImport = true;
648
- const exportsArray = format === 'mjs' ? findExportDefault(source) : findModuleExports(source);
649
- if (!exportsArray) {
650
- return content;
651
- }
652
- exportsArray.forEach((node) => {
465
+ findAllBlocks(source)?.forEach((node) => {
653
466
  if (ts.isSpreadElement(node) &&
654
467
  ts.isElementAccessExpression(node.expression) &&
655
468
  ts.isPropertyAccessExpression(node.expression.expression) &&
@@ -694,22 +507,14 @@ function addPluginsToExportsBlock(content, plugins) {
694
507
  * Adds compat if missing to flat config
695
508
  */
696
509
  function addFlatCompatToFlatConfig(content) {
697
- const result = addImportToFlatConfig(content, 'js', '@eslint/js');
698
- const format = content.includes('export default') ? 'mjs' : 'cjs';
510
+ let result = content;
511
+ result = addImportToFlatConfig(result, 'js', '@eslint/js');
699
512
  if (result.includes('const compat = new FlatCompat')) {
700
513
  return result;
701
514
  }
702
- if (format === 'mjs') {
703
- return addFlatCompatToFlatConfigESM(result);
704
- }
705
- else {
706
- return addFlatCompatToFlatConfigCJS(result);
707
- }
708
- }
709
- function addFlatCompatToFlatConfigCJS(content) {
710
- content = addImportToFlatConfig(content, ['FlatCompat'], '@eslint/eslintrc');
711
- const index = content.indexOf('module.exports');
712
- return (0, devkit_1.applyChangesToString)(content, [
515
+ result = addImportToFlatConfig(result, ['FlatCompat'], '@eslint/eslintrc');
516
+ const index = result.indexOf('module.exports');
517
+ return (0, devkit_1.applyChangesToString)(result, [
713
518
  {
714
519
  type: devkit_1.ChangeType.Insert,
715
520
  index: index - 1,
@@ -722,62 +527,25 @@ const compat = new FlatCompat({
722
527
  },
723
528
  ]);
724
529
  }
725
- function addFlatCompatToFlatConfigESM(content) {
726
- const importsToAdd = [
727
- { variable: 'js', module: '@eslint/js' },
728
- { variable: ['fileURLToPath'], module: 'url' },
729
- { variable: ['dirname'], module: 'path' },
730
- { variable: ['FlatCompat'], module: '@eslint/eslintrc' },
731
- ];
732
- for (const { variable, module } of importsToAdd) {
733
- content = addImportToFlatConfig(content, variable, module);
734
- }
735
- const index = content.indexOf('export default');
736
- return (0, devkit_1.applyChangesToString)(content, [
737
- {
738
- type: devkit_1.ChangeType.Insert,
739
- index: index - 1,
740
- text: `
741
- const compat = new FlatCompat({
742
- baseDirectory: dirname(fileURLToPath(import.meta.url)),
743
- recommendedConfig: js.configs.recommended,
744
- });\n
745
- `,
746
- },
747
- ]);
748
- }
749
530
  /**
750
531
  * Generate node list representing the imports and the exports blocks
751
532
  * Optionally add flat compat initialization
752
533
  */
753
- function createNodeList(importsMap, exportElements, format) {
534
+ function createNodeList(importsMap, exportElements) {
754
535
  const importsList = [];
536
+ // generateRequire(varName, imp, ts.factory);
755
537
  Array.from(importsMap.entries()).forEach(([imp, varName]) => {
756
- if (format === 'mjs') {
757
- importsList.push(generateESMImport(varName, imp));
758
- }
759
- else {
760
- importsList.push(generateRequire(varName, imp));
761
- }
538
+ importsList.push(generateRequire(varName, imp));
762
539
  });
763
- const exports = format === 'mjs'
764
- ? generateESMExport(exportElements)
765
- : generateCJSExport(exportElements);
766
540
  return ts.factory.createNodeArray([
767
541
  // add plugin imports
768
542
  ...importsList,
769
543
  ts.createSourceFile('', '', ts.ScriptTarget.Latest, false, ts.ScriptKind.JS),
770
- exports,
544
+ // creates:
545
+ // module.exports = [ ... ];
546
+ ts.factory.createExpressionStatement(ts.factory.createBinaryExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('module'), ts.factory.createIdentifier('exports')), ts.factory.createToken(ts.SyntaxKind.EqualsToken), ts.factory.createArrayLiteralExpression(exportElements, true))),
771
547
  ]);
772
548
  }
773
- function generateESMExport(elements) {
774
- // creates: export default = [...]
775
- return ts.factory.createExportAssignment(undefined, false, ts.factory.createArrayLiteralExpression(elements, true));
776
- }
777
- function generateCJSExport(elements) {
778
- // creates: module.exports = [...]
779
- return ts.factory.createExpressionStatement(ts.factory.createBinaryExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('module'), ts.factory.createIdentifier('exports')), ts.factory.createToken(ts.SyntaxKind.EqualsToken), ts.factory.createArrayLiteralExpression(elements, true)));
780
- }
781
549
  function generateSpreadElement(name) {
782
550
  return ts.factory.createSpreadElement(ts.factory.createIdentifier(name));
783
551
  }
@@ -795,17 +563,12 @@ function generatePluginExtendsElementWithCompatFixup(plugin) {
795
563
  function stringifyNodeList(nodes) {
796
564
  const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
797
565
  const resultFile = ts.createSourceFile('', '', ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
798
- const result = printer
566
+ return (printer
799
567
  .printList(ts.ListFormat.MultiLine, nodes, resultFile)
800
568
  // add new line before compat initialization
801
- .replace(/const compat = new FlatCompat/, '\nconst compat = new FlatCompat');
802
- if (result.includes('export default')) {
803
- return result // add new line before export default = ...
804
- .replace(/export default/, '\nexport default');
805
- }
806
- else {
807
- return result.replace(/module.exports/, '\nmodule.exports');
808
- }
569
+ .replace(/const compat = new FlatCompat/, '\nconst compat = new FlatCompat')
570
+ // add new line before module.exports = ...
571
+ .replace(/module\.exports/, '\nmodule.exports'));
809
572
  }
810
573
  /**
811
574
  * generates AST require statement
@@ -815,26 +578,6 @@ function generateRequire(variableName, imp) {
815
578
  ts.factory.createVariableDeclaration(variableName, undefined, undefined, ts.factory.createCallExpression(ts.factory.createIdentifier('require'), undefined, [ts.factory.createStringLiteral(imp)])),
816
579
  ], ts.NodeFlags.Const));
817
580
  }
818
- // Top level imports
819
- function generateESMImport(variableName, imp) {
820
- let importClause;
821
- if (typeof variableName === 'string') {
822
- // For single variable import e.g import foo from 'module';
823
- importClause = ts.factory.createImportClause(false, ts.factory.createIdentifier(variableName), undefined);
824
- }
825
- else {
826
- // For object binding pattern import e.g import { a, b, c } from 'module';
827
- importClause = ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports(variableName.elements.map((element) => {
828
- const propertyName = element.propertyName
829
- ? ts.isIdentifier(element.propertyName)
830
- ? element.propertyName
831
- : ts.factory.createIdentifier(element.propertyName.getText())
832
- : undefined;
833
- return ts.factory.createImportSpecifier(false, propertyName, element.name);
834
- })));
835
- }
836
- return ts.factory.createImportDeclaration(undefined, importClause, ts.factory.createStringLiteral(imp));
837
- }
838
581
  /**
839
582
  * FROM: https://github.com/eslint/rewrite/blob/e2a7ec809db20e638abbad250d105ddbde88a8d5/packages/migrate-config/src/migrate-config.js#L222
840
583
  *
@@ -860,7 +603,7 @@ function overrideNeedsCompat(override) {
860
603
  * Generates an AST object or spread element representing a modern flat config entry,
861
604
  * based on a given legacy eslintrc JSON override object
862
605
  */
863
- function generateFlatOverride(_override, format) {
606
+ function generateFlatOverride(_override) {
864
607
  const override = mapFilePaths(_override);
865
608
  // We do not need the compat tooling for this override
866
609
  if (!overrideNeedsCompat(override)) {
@@ -916,10 +659,12 @@ function generateFlatOverride(_override, format) {
916
659
  return propertyAssignment;
917
660
  }
918
661
  else {
919
- // Change parser to import statement.
920
- return format === 'mjs'
921
- ? generateESMParserImport(override)
922
- : generateCJSParserImport(override);
662
+ // Change parser to require statement.
663
+ return ts.factory.createPropertyAssignment('parser', ts.factory.createCallExpression(ts.factory.createIdentifier('require'), undefined, [
664
+ ts.factory.createStringLiteral(override['languageOptions']?.['parserOptions']?.parser ??
665
+ override['languageOptions']?.parser ??
666
+ override.parser),
667
+ ]));
923
668
  }
924
669
  },
925
670
  });
@@ -974,20 +719,6 @@ function generateFlatOverride(_override, format) {
974
719
  ], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createParenthesizedExpression(ts.factory.createObjectLiteralExpression(objectLiteralElements, true))),
975
720
  ]));
976
721
  }
977
- function generateESMParserImport(override) {
978
- return ts.factory.createPropertyAssignment('parser', ts.factory.createAwaitExpression(ts.factory.createCallExpression(ts.factory.createIdentifier('import'), undefined, [
979
- ts.factory.createStringLiteral(override['languageOptions']?.['parserOptions']?.parser ??
980
- override['languageOptions']?.parser ??
981
- override.parser),
982
- ])));
983
- }
984
- function generateCJSParserImport(override) {
985
- return ts.factory.createPropertyAssignment('parser', ts.factory.createCallExpression(ts.factory.createIdentifier('require'), undefined, [
986
- ts.factory.createStringLiteral(override['languageOptions']?.['parserOptions']?.parser ??
987
- override['languageOptions']?.parser ??
988
- override.parser),
989
- ]));
990
- }
991
722
  function generateFlatPredefinedConfig(predefinedConfigName, moduleName = 'nx', spread = true) {
992
723
  const node = ts.factory.createElementAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(moduleName), ts.factory.createIdentifier('configs')), ts.factory.createStringLiteral(predefinedConfigName));
993
724
  return spread ? ts.factory.createSpreadElement(node) : node;
@@ -230,7 +230,7 @@ function getRootForDirectory(directory, roots) {
230
230
  function getProjectUsingESLintConfig(configFilePath, projectRoot, eslintVersion, options, context) {
231
231
  const rootEslintConfig = [
232
232
  config_file_1.baseEsLintConfigFile,
233
- ...config_file_1.BASE_ESLINT_CONFIG_FILENAMES,
233
+ config_file_1.baseEsLintFlatConfigFile,
234
234
  ...config_file_1.ESLINT_CONFIG_FILENAMES,
235
235
  ].find((f) => (0, node_fs_1.existsSync)((0, posix_1.join)(context.workspaceRoot, f)));
236
236
  // Add a lint target for each child project without an eslint config, with the root level config as an input
@@ -1,9 +1,8 @@
1
1
  export declare const ESLINT_FLAT_CONFIG_FILENAMES: string[];
2
2
  export declare const ESLINT_OLD_CONFIG_FILENAMES: string[];
3
3
  export declare const ESLINT_CONFIG_FILENAMES: string[];
4
- export declare const BASE_ESLINT_CONFIG_FILENAMES: string[];
5
4
  export declare const baseEsLintConfigFile = ".eslintrc.base.json";
6
- export declare const baseEsLintFlatConfigFile = "eslint.base.config.mjs";
5
+ export declare const baseEsLintFlatConfigFile = "eslint.base.config.cjs";
7
6
  export declare const legacyBaseEsLintFlatConfigFile = "eslint.base.config.js";
8
7
  export declare function isFlatConfig(configFilePath: string): boolean;
9
8
  export declare function findFlatConfigFile(directory: string, workspaceRoot: string): string | null;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.legacyBaseEsLintFlatConfigFile = exports.baseEsLintFlatConfigFile = exports.baseEsLintConfigFile = exports.BASE_ESLINT_CONFIG_FILENAMES = exports.ESLINT_CONFIG_FILENAMES = exports.ESLINT_OLD_CONFIG_FILENAMES = exports.ESLINT_FLAT_CONFIG_FILENAMES = void 0;
3
+ exports.legacyBaseEsLintFlatConfigFile = exports.baseEsLintFlatConfigFile = exports.baseEsLintConfigFile = exports.ESLINT_CONFIG_FILENAMES = exports.ESLINT_OLD_CONFIG_FILENAMES = exports.ESLINT_FLAT_CONFIG_FILENAMES = void 0;
4
4
  exports.isFlatConfig = isFlatConfig;
5
5
  exports.findFlatConfigFile = findFlatConfigFile;
6
6
  exports.findOldConfigFile = findOldConfigFile;
@@ -20,9 +20,8 @@ exports.ESLINT_CONFIG_FILENAMES = [
20
20
  ...exports.ESLINT_OLD_CONFIG_FILENAMES,
21
21
  ...exports.ESLINT_FLAT_CONFIG_FILENAMES,
22
22
  ];
23
- exports.BASE_ESLINT_CONFIG_FILENAMES = flat_config_1.baseEslintConfigFilenames;
24
23
  exports.baseEsLintConfigFile = '.eslintrc.base.json';
25
- exports.baseEsLintFlatConfigFile = 'eslint.base.config.mjs';
24
+ exports.baseEsLintFlatConfigFile = 'eslint.base.config.cjs';
26
25
  // Make sure we can handle previous file extension as well for migrations or custom generators.
27
26
  exports.legacyBaseEsLintFlatConfigFile = 'eslint.base.config.js';
28
27
  function isFlatConfig(configFilePath) {
@@ -1,5 +1,4 @@
1
1
  import { Tree } from '@nx/devkit';
2
2
  export declare const eslintFlatConfigFilenames: string[];
3
- export declare const baseEslintConfigFilenames: string[];
4
3
  export declare function getRootESLintFlatConfigFilename(tree: Tree): string;
5
4
  export declare function useFlatConfig(tree?: Tree): boolean;