@murky-web/oxlint-plugin-solid 1.2.0 → 1.4.0

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.
@@ -1,11 +1,13 @@
1
+ import { appendImports, canTakeSpecifier, insertImports } from "../utils.mjs";
2
+
1
3
  const FALSE_SENTINEL = false;
2
4
  const FIRST_INDEX = 0;
3
- const LAST_INDEX = -1;
4
- const FILE_START_RANGE = [FIRST_INDEX, FIRST_INDEX];
5
5
  const NO_PARAMETERS = 0;
6
+ const NO_ITEMS = 0;
6
7
  const ONE_PARAMETER = 1;
7
8
  const PASCAL_CASE_COMPONENT_NAME = /^[A-Z][A-Za-z0-9]*$/;
8
9
  const SOLID_IMPORT_SOURCE = "solid-js";
10
+ const SOLID_COMPONENT_TYPES = ["Component", "ParentComponent"];
9
11
 
10
12
  function isAstNode(value) {
11
13
  return (
@@ -24,12 +26,15 @@ function hasJsxElementReturnType(node) {
24
26
  rt.typeName?.type === "TSQualifiedName" &&
25
27
  rt.typeName.left?.name === "JSX" &&
26
28
  rt.typeName.right?.name === "Element"
27
- ) return true;
29
+ )
30
+ return true;
28
31
  // JSX.Element via plain identifier (rare but possible)
29
- if (rt.type === "TSTypeReference" && rt.typeName?.name === "JSXElement") return true;
32
+ if (rt.type === "TSTypeReference" && rt.typeName?.name === "JSXElement")
33
+ return true;
30
34
  // Solid 2.0: `Element` from solid-js is the renderer-neutral return type,
31
35
  // and `JSX` now lives in the renderer package.
32
- if (rt.type === "TSTypeReference" && rt.typeName?.name === "Element") return true;
36
+ if (rt.type === "TSTypeReference" && rt.typeName?.name === "Element")
37
+ return true;
33
38
  return false;
34
39
  }
35
40
 
@@ -39,7 +44,8 @@ function isFunctionComponent(node) {
39
44
  node.async === true ||
40
45
  node.generator === true ||
41
46
  node.typeParameters
42
- ) return false;
47
+ )
48
+ return false;
43
49
 
44
50
  if (node.id?.type !== "Identifier") return false;
45
51
 
@@ -53,9 +59,6 @@ function isFunctionComponent(node) {
53
59
  return false;
54
60
  }
55
61
 
56
- // Keep old name as alias so call sites don't need changing
57
- const isExportedFunctionComponent = isFunctionComponent;
58
-
59
62
  function isJsxLikeNode(node) {
60
63
  return node?.type === "JSXElement" || node?.type === "JSXFragment";
61
64
  }
@@ -236,147 +239,67 @@ function usesPropsChildren(functionNode, propsIdentifierName) {
236
239
  return found;
237
240
  }
238
241
 
239
- function getSolidTypeImportInfo(programNode, desiredTypeName) {
240
- const importDeclarations = getSolidImportDeclarations(programNode);
241
-
242
- return {
243
- importDeclaration: importDeclarations.at(FIRST_INDEX),
244
- localTypeName: findLocalTypeName(importDeclarations, desiredTypeName),
245
- };
246
- }
247
-
248
- function getNamedImportSpecifiers(importDeclaration) {
249
- return importDeclaration.specifiers.filter((specifier) => {
250
- return specifier.type === "ImportSpecifier";
251
- });
252
- }
253
-
254
- function getValueImportSpecifiers(importDeclaration) {
255
- return importDeclaration.specifiers.filter((specifier) => {
256
- return (
257
- specifier.type === "ImportDefaultSpecifier" ||
258
- specifier.type === "ImportNamespaceSpecifier"
259
- );
260
- });
261
- }
262
-
263
- function getTypeKeyword(importDeclaration, sourceCode) {
264
- if (sourceCode.getText(importDeclaration).startsWith("import type")) {
265
- return "";
266
- }
267
-
268
- return "type ";
269
- }
270
-
271
- function insertSolidTypeIntoExistingImport({
272
- desiredTypeName,
273
- fixer,
274
- importDeclaration,
275
- sourceCode,
276
- }) {
277
- const namedSpecifiers = getNamedImportSpecifiers(importDeclaration);
278
- if (namedSpecifiers.length > NO_PARAMETERS) {
279
- const lastNamedSpecifier = namedSpecifiers.at(LAST_INDEX);
280
- const typeKeyword = getTypeKeyword(importDeclaration, sourceCode);
281
- return fixer.insertTextAfter(
282
- lastNamedSpecifier,
283
- `, ${typeKeyword}${desiredTypeName}`,
284
- );
285
- }
242
+ // Names the file declares at the top level (imports, types, classes,
243
+ // functions, variables), exported or not.
244
+ function getTopLevelNames(programNode) {
245
+ const names = new Set();
246
+ for (const statement of programNode.body) {
247
+ if (statement.type === "ImportDeclaration") {
248
+ for (const specifier of statement.specifiers) {
249
+ names.add(specifier.local.name);
250
+ }
251
+ continue;
252
+ }
286
253
 
287
- const valueSpecifiers = getValueImportSpecifiers(importDeclaration);
288
- if (valueSpecifiers.length > NO_PARAMETERS) {
289
- const lastValueSpecifier = valueSpecifiers.at(LAST_INDEX);
290
- return fixer.insertTextAfter(
291
- lastValueSpecifier,
292
- `, { type ${desiredTypeName} }`,
293
- );
254
+ const declaration =
255
+ statement.type === "ExportNamedDeclaration" ||
256
+ statement.type === "ExportDefaultDeclaration"
257
+ ? statement.declaration
258
+ : statement;
259
+ if (declaration?.type === "VariableDeclaration") {
260
+ for (const declarator of declaration.declarations) {
261
+ if (declarator.id.type === "Identifier") {
262
+ names.add(declarator.id.name);
263
+ }
264
+ }
265
+ } else if (declaration?.id?.type === "Identifier") {
266
+ names.add(declaration.id.name);
267
+ }
294
268
  }
295
269
 
296
- return fixer.insertTextBefore(
297
- importDeclaration,
298
- `import type { ${desiredTypeName} } from "solid-js";\n`,
299
- );
270
+ return names;
300
271
  }
301
272
 
302
- function createImportFix({ desiredTypeName, fixer, programNode, sourceCode }) {
303
- const { importDeclaration, localTypeName } = getSolidTypeImportInfo(
304
- programNode,
305
- desiredTypeName,
306
- );
273
+ // What the module does in one walk: the position of the first JSX element of
274
+ // each name, and the Solid component types it writes as a type reference
275
+ // (`Component<Props>`) without declaring or importing them.
276
+ function scanProgram(programNode) {
277
+ const firstJsxUse = new Map();
278
+ const referencedTypes = new Set();
279
+ const declared = getTopLevelNames(programNode);
307
280
 
308
- if (localTypeName !== "") {
309
- return {
310
- localTypeName,
311
- operation: null,
312
- };
313
- }
314
-
315
- if (importDeclaration) {
316
- return {
317
- localTypeName: desiredTypeName,
318
- operation: insertSolidTypeIntoExistingImport({
319
- desiredTypeName,
320
- fixer,
321
- importDeclaration,
322
- sourceCode,
323
- }),
324
- };
325
- }
326
-
327
- return {
328
- localTypeName: desiredTypeName,
329
- operation: fixer.insertTextBeforeRange(
330
- FILE_START_RANGE,
331
- `import type { ${desiredTypeName} } from "solid-js";\n`,
332
- ),
333
- };
334
- }
335
-
336
- function buildReplacementText({
337
- componentName,
338
- localTypeName,
339
- propsParam,
340
- sourceCode,
341
- typeReference,
342
- usesChildren,
343
- functionNode,
344
- isExported,
345
- }) {
346
- const exportPrefix = isExported ? "export " : "";
347
- const propsSuffix = getPropsSuffix(typeReference);
348
- const paramsText = propsParam.text;
349
- const bodyText = sourceCode.getText(functionNode.body);
350
-
351
- return `${exportPrefix}const ${componentName}: ${localTypeName}${propsSuffix} = (${paramsText}) => ${bodyText}`;
352
- }
281
+ visitAstNode(programNode, (node) => {
282
+ if (
283
+ node.type === "JSXIdentifier" &&
284
+ (node.parent?.type === "JSXOpeningElement" ||
285
+ node.parent?.type === "JSXClosingElement" ||
286
+ node.parent?.type === "JSXMemberExpression") &&
287
+ !firstJsxUse.has(node.name)
288
+ ) {
289
+ firstJsxUse.set(node.name, node.range[FIRST_INDEX]);
290
+ }
353
291
 
354
- function createRuleFix({
355
- fixer,
356
- functionNode,
357
- localTypeName,
358
- propsParam,
359
- sourceCode,
360
- typeReference,
361
- usesChildren,
362
- }) {
363
- const isExported = functionNode.parent?.type === "ExportNamedDeclaration";
364
- const componentName = functionNode.id.name;
365
- const replacementText = buildReplacementText({
366
- componentName,
367
- functionNode,
368
- isExported,
369
- localTypeName,
370
- propsParam,
371
- sourceCode,
372
- typeReference,
373
- usesChildren,
292
+ if (
293
+ node.type === "TSTypeReference" &&
294
+ node.typeName?.type === "Identifier" &&
295
+ SOLID_COMPONENT_TYPES.includes(node.typeName.name) &&
296
+ !declared.has(node.typeName.name)
297
+ ) {
298
+ referencedTypes.add(node.typeName.name);
299
+ }
374
300
  });
375
301
 
376
- // For exported functions, replace the ExportNamedDeclaration (the parent).
377
- // For non-exported functions, replace only the FunctionDeclaration itself.
378
- const nodeToReplace = isExported ? functionNode.parent : functionNode;
379
- return fixer.replaceText(nodeToReplace, replacementText);
302
+ return { firstJsxUse, referencedTypes };
380
303
  }
381
304
 
382
305
  export const preferArrowComponentsRule = {
@@ -393,13 +316,173 @@ export const preferArrowComponentsRule = {
393
316
  create(context) {
394
317
  const sourceCode = context.sourceCode;
395
318
  const programNode = sourceCode.ast;
319
+ const candidates = [];
320
+
321
+ // `function F` is hoisted, `const F` is not: a read of `F` that stands
322
+ // before the declaration (`export const routes = [{ component: Home }]`
323
+ // above `export function Home`) throws a ReferenceError once the
324
+ // function is a const. Such a function is reported but not fixed.
325
+ // Reads inside other functions run later and would be fine, but
326
+ // whether they do is not decidable here, so they count too.
327
+ const isUsedBeforeDeclaration = (node, firstJsxUse) => {
328
+ const start = node.range[FIRST_INDEX];
329
+ const jsxStart = firstJsxUse.get(node.id.name);
330
+ if (jsxStart !== undefined && jsxStart < start) {
331
+ return true;
332
+ }
333
+
334
+ let variable = null;
335
+ for (
336
+ let scope =
337
+ sourceCode.scopeManager?.acquire(node)?.upper ?? null;
338
+ scope && variable === null;
339
+ scope = scope.upper
340
+ ) {
341
+ variable = scope.set.get(node.id.name) ?? null;
342
+ }
343
+
344
+ return (
345
+ variable?.references.some((reference) => {
346
+ return (
347
+ reference.identifier !== node.id &&
348
+ reference.identifier.range[FIRST_INDEX] < start
349
+ );
350
+ }) ?? false
351
+ );
352
+ };
353
+
354
+ const reportAll = () => {
355
+ if (candidates.length === NO_ITEMS) {
356
+ return;
357
+ }
358
+
359
+ const solidImports = getSolidImportDeclarations(programNode);
360
+ const { firstJsxUse, referencedTypes } = scanProgram(programNode);
361
+ const plans = candidates.map((candidate) => {
362
+ const localTypeName = findLocalTypeName(
363
+ solidImports,
364
+ candidate.desiredTypeName,
365
+ );
366
+
367
+ return {
368
+ ...candidate,
369
+ fixable: !isUsedBeforeDeclaration(
370
+ candidate.node,
371
+ firstJsxUse,
372
+ ),
373
+ resolvedTypeName:
374
+ localTypeName === ""
375
+ ? candidate.desiredTypeName
376
+ : localTypeName,
377
+ needsImport: localTypeName === "",
378
+ };
379
+ });
380
+
381
+ // The import of every name that a fix writes. Imports in the fix
382
+ // of every component would put one `import` next to each of them
383
+ // (and oxlint drops a fix that overlaps an earlier one), so the
384
+ // first fixable component carries the import for all of them, at
385
+ // the top of the file. A fix that was dropped leaves the others
386
+ // without their import: a type reference to `Component` that the
387
+ // module neither declares nor imports is imported by the next one.
388
+ const fixablePlans = plans.filter((plan) => plan.fixable);
389
+ const [carrier] = fixablePlans;
390
+ const namesToImport = [];
391
+ for (const name of [
392
+ ...fixablePlans
393
+ .filter((plan) => plan.needsImport)
394
+ .map((plan) => plan.desiredTypeName),
395
+ ...SOLID_COMPONENT_TYPES.filter((name) => {
396
+ return (
397
+ referencedTypes.has(name) &&
398
+ findLocalTypeName(solidImports, name) === ""
399
+ );
400
+ }),
401
+ ]) {
402
+ if (!namesToImport.includes(name)) {
403
+ namesToImport.push(name);
404
+ }
405
+ }
406
+
407
+ const importFix = (fixer) => {
408
+ // The names are types: a value import takes them as
409
+ // `type Name`, a type import (without a default or namespace
410
+ // specifier) as `Name`.
411
+ const target = solidImports.find((declaration) => {
412
+ return canTakeSpecifier(declaration, true);
413
+ });
414
+ if (target) {
415
+ const typeKeyword =
416
+ target.importKind === "type" ? "" : "type ";
417
+
418
+ return appendImports(
419
+ fixer,
420
+ sourceCode,
421
+ target,
422
+ namesToImport.map((name) => `${typeKeyword}${name}`),
423
+ );
424
+ }
425
+
426
+ return insertImports(
427
+ fixer,
428
+ sourceCode,
429
+ SOLID_IMPORT_SOURCE,
430
+ namesToImport,
431
+ undefined,
432
+ true,
433
+ );
434
+ };
435
+
436
+ const message =
437
+ "Prefer export const components typed as Component<Props> or ParentComponent<Props>.";
438
+ for (const plan of plans) {
439
+ const { node } = plan;
440
+ if (!plan.fixable) {
441
+ context.report({ message, node });
442
+ continue;
443
+ }
444
+
445
+ context.report({
446
+ fix(fixer) {
447
+ const exportKind = node.parent?.type;
448
+ const propsSuffix = getPropsSuffix(plan.typeReference);
449
+ const declaration = `const ${node.id.name}: ${plan.resolvedTypeName}${propsSuffix} = (${plan.propsParam.text}) => ${sourceCode.getText(node.body)};`;
450
+ let replacement = declaration;
451
+ let nodeToReplace = node;
452
+ if (exportKind === "ExportNamedDeclaration") {
453
+ replacement = `export ${declaration}`;
454
+ nodeToReplace = node.parent;
455
+ } else if (exportKind === "ExportDefaultDeclaration") {
456
+ // `export default const` does not parse.
457
+ replacement = `${declaration}\nexport default ${node.id.name};`;
458
+ nodeToReplace = node.parent;
459
+ }
460
+
461
+ const edits = [
462
+ fixer.replaceText(nodeToReplace, replacement),
463
+ ];
464
+ if (
465
+ plan === carrier &&
466
+ namesToImport.length > NO_ITEMS
467
+ ) {
468
+ const importEdit = importFix(fixer);
469
+ if (importEdit) {
470
+ edits.push(importEdit);
471
+ }
472
+ }
473
+
474
+ return edits;
475
+ },
476
+ message,
477
+ node,
478
+ });
479
+ }
480
+ };
396
481
 
397
482
  return {
483
+ "Program:exit": reportAll,
398
484
  FunctionDeclaration(node) {
399
- if (
400
- !isExportedFunctionComponent(node) ||
401
- !hasJsxReturn(node.body)
402
- ) {
485
+ if (!isFunctionComponent(node) || !hasJsxReturn(node.body)) {
403
486
  return;
404
487
  }
405
488
 
@@ -418,59 +501,12 @@ export const preferArrowComponentsRule = {
418
501
  const usesChildren =
419
502
  propsParam.name !== "" &&
420
503
  usesPropsChildren(node, propsParam.name);
421
- const desiredTypeName = getDesiredSolidTypeName(usesChildren);
422
-
423
- const { importDeclaration, localTypeName } = getSolidTypeImportInfo(
424
- programNode,
425
- desiredTypeName,
426
- );
427
- const resolvedTypeName = localTypeName !== "" ? localTypeName : desiredTypeName;
428
- const needsNewImport = localTypeName === "" && !importDeclaration;
429
-
430
- context.report({
431
- fix(fixer) {
432
- const isExported = node.parent?.type === "ExportNamedDeclaration";
433
- const componentName = node.id.name;
434
- const propsSuffix = getPropsSuffix(typeReference);
435
- const paramsText = propsParam.text;
436
- const bodyText = sourceCode.getText(node.body);
437
- const exportPrefix = isExported ? "export " : "";
438
-
439
- // If we need a new import AND the function is not exported,
440
- // prepend the import declaration directly into the replacement text
441
- // to avoid multi-range fix conflicts.
442
- const importPrefix = needsNewImport
443
- ? `import type { ${desiredTypeName} } from "solid-js";\n`
444
- : "";
445
-
446
- const replacementText = `${importPrefix}${exportPrefix}const ${componentName}: ${resolvedTypeName}${propsSuffix} = (${paramsText}) => ${bodyText}`;
447
- const nodeToReplace = isExported ? node.parent : node;
448
-
449
- if (!needsNewImport && localTypeName === "" && importDeclaration) {
450
- // Need to add to existing import — use two fixes only when
451
- // the import is AFTER the function (safe, no overlap).
452
- // Otherwise embed the import in the replacement.
453
- const importEnd = importDeclaration.range?.[1] ?? 0;
454
- const funcStart = nodeToReplace.range?.[0] ?? 0;
455
- if (importEnd < funcStart) {
456
- const typeKeyword = getTypeKeyword(importDeclaration, sourceCode);
457
- const namedSpecifiers = getNamedImportSpecifiers(importDeclaration);
458
- const lastSpec = namedSpecifiers.at(LAST_INDEX);
459
- const importOp = lastSpec
460
- ? fixer.insertTextAfter(lastSpec, `, ${typeKeyword}${desiredTypeName}`)
461
- : fixer.insertTextBefore(importDeclaration, `import type { ${desiredTypeName} } from "solid-js";\n`);
462
- return [
463
- fixer.replaceText(nodeToReplace, replacementText),
464
- importOp,
465
- ];
466
- }
467
- }
468
504
 
469
- return fixer.replaceText(nodeToReplace, replacementText);
470
- },
471
- message:
472
- "Prefer export const components typed as Component<Props> or ParentComponent<Props>.",
505
+ candidates.push({
506
+ desiredTypeName: getDesiredSolidTypeName(usesChildren),
473
507
  node,
508
+ propsParam,
509
+ typeReference,
474
510
  });
475
511
  },
476
512
  };
@@ -37,8 +37,7 @@ export default {
37
37
  },
38
38
  defaultOptions: [],
39
39
  create(context) {
40
- const classnames =
41
- context.options[0]?.classnames ?? DEFAULT_CLASSNAMES;
40
+ const classnames = context.options[0]?.classnames ?? DEFAULT_CLASSNAMES;
42
41
  return {
43
42
  JSXAttribute(node) {
44
43
  const name = jsxPropName(node);
@@ -48,11 +47,20 @@ export default {
48
47
  // the lowercase spelling missed every real Solid 1 call site —
49
48
  // which is the code this rule exists to migrate.
50
49
  if (name === "classList" || name === "classlist") {
50
+ // With a `class` attribute next to it, renaming would
51
+ // write the attribute twice (a parse error in TSX); the
52
+ // two have to be merged by hand.
53
+ const hasClassAttribute = node.parent.attributes.some(
54
+ (attribute) =>
55
+ attribute.type === "JSXAttribute" &&
56
+ jsxPropName(attribute) === "class",
57
+ );
51
58
  context.report({
52
59
  node,
53
60
  messageId: "classlistRemoved",
54
- fix: (fixer) =>
55
- fixer.replaceText(node.name, "class"),
61
+ fix: hasClassAttribute
62
+ ? null
63
+ : (fixer) => fixer.replaceText(node.name, "class"),
56
64
  });
57
65
  return;
58
66
  }