@murky-web/oxlint-plugin-solid 1.3.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,16 +1,489 @@
1
+ // Ported from eslint-plugin-solid 0.20.0 (`validate-jsx-nesting`),
2
+ // https://github.com/solidjs-community/eslint-plugin-solid, and covered by its
3
+ // licence:
4
+ //
5
+ // MIT License
6
+ //
7
+ // Copyright (c) 2021 Josh Wilson
8
+ //
9
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ // of this software and associated documentation files (the "Software"), to deal
11
+ // in the Software without restriction, including without limitation the rights
12
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ // copies of the Software, and to permit persons to whom the Software is
14
+ // furnished to do so, subject to the following conditions:
15
+ //
16
+ // The above copyright notice and this permission notice shall be included in all
17
+ // copies or substantial portions of the Software.
18
+ //
19
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ // SOFTWARE.
26
+ //
27
+ // Like upstream it asks `validate-html-nesting` (ISC, a dependency) whether a
28
+ // pair is valid and parse5 what the HTML parser makes of it. Differences: plain
29
+ // JavaScript on the Oxlint AST without the typescript-eslint types, and a
30
+ // hidden `<input>` is allowed in a table (see `check`).
31
+ import { parse, parseFragment } from "parse5";
32
+ import { isValidHTMLNesting } from "validate-html-nesting";
33
+
34
+ import { isDOMElementName, jsxGetProp, jsxPropName } from "../utils.mjs";
35
+
36
+ // `<body>` from a parsed document, used as the parsing context so fragments are
37
+ // interpreted the way `innerHTML` would interpret them.
38
+ const htmlElement = parse(
39
+ "<!DOCTYPE html><html><head></head><body></body></html>",
40
+ ).childNodes[1];
41
+ const bodyContext = htmlElement.childNodes[1];
42
+
43
+ const rewriteCache = new Map();
44
+ const tableWrappers = {
45
+ caption: ["table"],
46
+ colgroup: ["table"],
47
+ tbody: ["table"],
48
+ thead: ["table"],
49
+ tfoot: ["table"],
50
+ tr: ["table", "tbody"],
51
+ td: ["table", "tbody", "tr"],
52
+ th: ["table", "tbody", "tr"],
53
+ };
54
+
55
+ // Rows, row groups and the table itself keep a hidden input as a child, any
56
+ // other `input` is moved in front of the table.
57
+ const TABLE_PARENTS = new Set(["table", "tbody", "tfoot", "thead", "tr"]);
58
+
59
+ // Void elements take no end tag, and the parser would read `</br>` as another
60
+ // `<br>`.
61
+ const voidElements = new Set([
62
+ "area",
63
+ "base",
64
+ "br",
65
+ "col",
66
+ "embed",
67
+ "hr",
68
+ "img",
69
+ "input",
70
+ "link",
71
+ "meta",
72
+ "param",
73
+ "source",
74
+ "track",
75
+ "wbr",
76
+ ]);
77
+
78
+ // parse5 lowercases tag names outside SVG, so `<foreignObject>` comes back as
79
+ // `foreignobject`.
80
+ const isTag = (node, tag) => node.nodeName.toLowerCase() === tag.toLowerCase();
81
+
82
+ // Does the HTML parser refuse to keep `child` as a direct child of `parent`?
83
+ //
84
+ // `validate-html-nesting` alone is not enough to answer this. Its tables encode
85
+ // the spec's *content model* (`<figcaption>` belongs in `<figure>`, `<summary>`
86
+ // in `<details>`, `<math>` takes only `<mrow>`), and conformance is a different
87
+ // question from what the parser does. A browser keeps `<div><figcaption />`
88
+ // exactly as written; it only rearranges a narrower set of cases. Reporting the
89
+ // conformance answer under a message that talks about the browser rewriting the
90
+ // DOM would be a false positive at error level.
91
+ //
92
+ // So the parser has the final say: the pair is only invalid when parse5, which
93
+ // implements the HTML parsing algorithm and is what Solid's own compiler uses to
94
+ // validate templates, fails to give back the same parent/child relationship.
95
+ // The library stays as the cheap pre-filter that decides when to ask.
96
+ const parserRewrites = (parent, child, namespace) => {
97
+ const key = `${namespace}:${parent}>${child}`;
98
+ const cached = rewriteCache.get(key);
99
+ if (cached !== undefined) {
100
+ return cached;
101
+ }
102
+
103
+ // A body fragment discards table-section tags without their table
104
+ // ancestors. Foreign content is parsed inside its `<svg>` or `<math>`,
105
+ // where those are plain elements.
106
+ const foreign = namespace !== "html";
107
+ const wrappers = foreign ? [namespace] : (tableWrappers[parent] ?? []);
108
+ const documentParent = !foreign && (parent === "head" || parent === "body");
109
+ const childMarkup = voidElements.has(child)
110
+ ? `<${child}>`
111
+ : `<${child}></${child}>`;
112
+ const markup = wrappers.reduceRight(
113
+ (content, tag) => `<${tag}>${content}</${tag}>`,
114
+ `<${parent}>${childMarkup}</${parent}>`,
115
+ );
116
+ let fragment = documentParent
117
+ ? parse(markup).childNodes.find((node) => node.nodeName === "html")
118
+ : parseFragment(bodyContext, markup, {});
119
+ for (const tag of wrappers) {
120
+ fragment = fragment?.childNodes.find((node) => node.nodeName === tag);
121
+ }
122
+ const roots = (fragment?.childNodes ?? []).filter(
123
+ (node) => node.nodeName !== "#text",
124
+ );
125
+ const root = documentParent
126
+ ? roots.find((node) => node.nodeName === parent)
127
+ : roots.length === 1 && isTag(roots[0], parent)
128
+ ? roots[0]
129
+ : undefined;
130
+ // `<template>` parks its children in `content`, not `childNodes`.
131
+ const container = root && "content" in root ? root.content : root;
132
+ const kids = (container?.childNodes ?? []).filter(
133
+ (node) => node.nodeName !== "#text",
134
+ );
135
+
136
+ // Foreign content can only clear a report the HTML reading makes, since
137
+ // `<svg>` keeps `<a><a />` as written. Tags breaking out of it are a scope
138
+ // rule, unreported like the rest.
139
+ const rewritten =
140
+ (!root || kids.length !== 1 || !isTag(kids[0], child)) &&
141
+ (!foreign || parserRewrites(parent, child, "html"));
142
+ rewriteCache.set(key, rewritten);
143
+ return rewritten;
144
+ };
145
+
146
+ // The DOM tag name of a JSX element, or `null` when the element isn't a plain
147
+ // lowercase tag: components (`<Foo />`), member expressions (`<Foo.Bar />`) and
148
+ // namespaced names carry unknown markup and can't be validated statically.
149
+ const getDOMTagName = (node) => {
150
+ const name = node.openingElement.name;
151
+ return name.type === "JSXIdentifier" && isDOMElementName(name.name)
152
+ ? name.name
153
+ : null;
154
+ };
155
+
156
+ // Wrappers that disappear at compile time, leaving the element where it was.
157
+ const isTransparent = (node) =>
158
+ node.type === "TSAsExpression" ||
159
+ node.type === "TSNonNullExpression" ||
160
+ node.type === "TSSatisfiesExpression";
161
+
162
+ // Walk up to the JSX element that will be this node's DOM parent.
163
+ //
164
+ // Everything traversed here compiles to the same parent/child pair: fragments
165
+ // flatten, an expression container is an `insert()` into the same element, and
166
+ // `&&`, ternaries and array literals only decide *whether* the child renders,
167
+ // never where. A `children` prop is the same insert as writing the element
168
+ // between the tags.
169
+ //
170
+ // Returns `null` when the chain leaves statically-known ground: a `.map()`
171
+ // callback, a call argument, a variable rendered elsewhere. What wraps those
172
+ // children is the caller's business, not this rule's.
173
+ const getDOMParent = (node) => {
174
+ let current = node;
175
+ let parent = current.parent;
176
+
177
+ while (parent) {
178
+ switch (parent.type) {
179
+ case "JSXElement":
180
+ return parent.children.includes(current) ? parent : null;
181
+ case "JSXAttribute":
182
+ // Only `children` names a child position; every other prop is
183
+ // data.
184
+ return parent.name.type === "JSXIdentifier" &&
185
+ parent.name.name === "children" &&
186
+ parent.parent?.type === "JSXOpeningElement" &&
187
+ parent.parent.parent?.type === "JSXElement"
188
+ ? parent.parent.parent
189
+ : null;
190
+ case "JSXFragment":
191
+ case "JSXExpressionContainer":
192
+ case "ArrayExpression":
193
+ current = parent;
194
+ parent = parent.parent;
195
+ break;
196
+ case "LogicalExpression":
197
+ // `cond && <hr />` renders the right side in place;
198
+ // `<hr /> && cond` doesn't render it.
199
+ if (parent.right !== current) {
200
+ return null;
201
+ }
202
+ current = parent;
203
+ parent = parent.parent;
204
+ break;
205
+ case "ConditionalExpression":
206
+ if (parent.test === current) {
207
+ return null;
208
+ }
209
+ current = parent;
210
+ parent = parent.parent;
211
+ break;
212
+ default:
213
+ if (!isTransparent(parent)) {
214
+ return null;
215
+ }
216
+ current = parent;
217
+ parent = parent.parent;
218
+ }
219
+ }
220
+
221
+ return null;
222
+ };
223
+
224
+ // Does `node` reach `parent` through an expression container or a `children`
225
+ // prop? Those compile to an `insert()`, which the client performs as written;
226
+ // only server-rendered HTML goes back through the parser.
227
+ const isInserted = (node, parent) => {
228
+ let current = node.parent;
229
+ while (current && current !== parent) {
230
+ if (
231
+ current.type === "JSXExpressionContainer" ||
232
+ current.type === "JSXAttribute"
233
+ ) {
234
+ return true;
235
+ }
236
+ current = current.parent;
237
+ }
238
+
239
+ return false;
240
+ };
241
+
242
+ // SVG elements whose children the parser reads as HTML again, by lowercase
243
+ // name.
244
+ const svgIntegrationPoints = new Set(["foreignobject", "desc", "title"]);
245
+
246
+ // MathML elements whose children the parser reads as HTML again.
247
+ const mathIntegrationPoints = new Set(["mi", "mo", "mn", "ms", "mtext"]);
248
+
249
+ // MathML tags that stay MathML right inside those, children included.
250
+ const mathTextLeaves = new Set(["mglyph", "malignmark"]);
251
+
252
+ // HTML tags that make the parser leave SVG or MathML wherever they appear in
253
+ // it. `<font>` only does with some attributes, so it's checked on its own
254
+ // below.
255
+ const foreignContentExits = new Set([
256
+ "b",
257
+ "big",
258
+ "blockquote",
259
+ "body",
260
+ "br",
261
+ "center",
262
+ "code",
263
+ "dd",
264
+ "div",
265
+ "dl",
266
+ "dt",
267
+ "em",
268
+ "embed",
269
+ "h1",
270
+ "h2",
271
+ "h3",
272
+ "h4",
273
+ "h5",
274
+ "h6",
275
+ "head",
276
+ "hr",
277
+ "i",
278
+ "img",
279
+ "li",
280
+ "listing",
281
+ "menu",
282
+ "meta",
283
+ "nobr",
284
+ "ol",
285
+ "p",
286
+ "pre",
287
+ "ruby",
288
+ "s",
289
+ "small",
290
+ "span",
291
+ "strike",
292
+ "strong",
293
+ "sub",
294
+ "sup",
295
+ "table",
296
+ "tt",
297
+ "u",
298
+ "ul",
299
+ "var",
300
+ ]);
301
+
302
+ // `<font>` leaves foreign content when it has one of these attributes.
303
+ const fontExitAttributes = new Set(["color", "face", "size"]);
304
+
305
+ // `<annotation-xml>` hands its children back to HTML with one of these
306
+ // encodings.
307
+ const htmlAnnotationEncodings = new Set(["text/html", "application/xhtml+xml"]);
308
+
309
+ // Does the parser read this element's children as HTML, although the element
310
+ // sits in SVG or MathML? Integration points only count in their own namespace:
311
+ // `<title>` is one in SVG and a plain element in MathML, and `<mi>` the other
312
+ // way around.
313
+ const switchesToHTML = (element, tag, namespace) => {
314
+ if (foreignContentExits.has(tag)) {
315
+ return true;
316
+ }
317
+ const { attributes } = element.openingElement;
318
+ if (tag === "font") {
319
+ return attributes.some(
320
+ (attr) =>
321
+ attr.type === "JSXAttribute" &&
322
+ fontExitAttributes.has(jsxPropName(attr).toLowerCase()),
323
+ );
324
+ }
325
+ if (namespace === "svg") {
326
+ return svgIntegrationPoints.has(tag);
327
+ }
328
+ if (tag === "annotation-xml") {
329
+ // The parser lowercases attribute names and keeps the first of a
330
+ // repeated one.
331
+ const encoding = attributes.find(
332
+ (attr) =>
333
+ attr.type === "JSXAttribute" &&
334
+ jsxPropName(attr).toLowerCase() === "encoding",
335
+ )?.value;
336
+ return (
337
+ encoding?.type === "Literal" &&
338
+ typeof encoding.value === "string" &&
339
+ htmlAnnotationEncodings.has(encoding.value.toLowerCase())
340
+ );
341
+ }
342
+ return mathIntegrationPoints.has(tag);
343
+ };
344
+
345
+ // Does the parser start SVG or MathML at this `<svg>` or `<math>`, written
346
+ // right inside `parentTag`? It does coming from HTML, and for `<svg>` in
347
+ // MathML's `<annotation-xml>`. Anywhere else in foreign content the tag is a
348
+ // plain element of the namespace around it, so the `<mi>` in
349
+ // `<svg><math><mi>` is an SVG element and keeps its children.
350
+ const startsNamespace = (tag, namespace, parentTag) =>
351
+ namespace === "html" ||
352
+ (tag === "svg" && namespace === "math" && parentTag === "annotation-xml");
353
+
354
+ // The namespace the parser is in when it reaches this element's start tag: SVG
355
+ // or MathML below an `<svg>` or `<math>` that starts it, HTML again below an
356
+ // integration point like `<foreignObject>` or a tag that leaves foreign content
357
+ // like `<p>`. Inside `<svg>`, `<a><a /></a>` and `<title><b /></title>` are
358
+ // kept as written, so judging them as HTML would report markup that is fine.
359
+ //
360
+ // The walk crosses expressions and components alike, although the compiler
361
+ // starts a new template there. A wrong guess here can only hide a report, never
362
+ // add one. An `<svg>` or `<math>` right behind one is the root of that
363
+ // template, which starts its own namespace.
364
+ const getParsingNamespace = (node) => {
365
+ // The element itself comes along, since `<mglyph>` can set its own
366
+ // namespace.
367
+ const elements = [];
368
+ for (let current = node; current; current = current.parent) {
369
+ if (current.type !== "JSXElement") {
370
+ continue;
371
+ }
372
+ const tag = getDOMTagName(current);
373
+ // The tokenizer lowercases tag names before any of the checks below.
374
+ if (tag) {
375
+ elements.push([current, tag.toLowerCase()]);
376
+ }
377
+ }
378
+ // Outermost first, since whether an element switches depends on the
379
+ // namespace it is in.
380
+ let namespace = "html";
381
+ let parent;
382
+ for (const [element, tag] of elements.reverse()) {
383
+ // Anything between two elements, like an expression or a component, is
384
+ // a boundary.
385
+ const outer =
386
+ parent && element.parent === parent[0] ? parent : undefined;
387
+ // The namespace this element's own start tag is parsed in.
388
+ const own =
389
+ outer &&
390
+ outer[2] === "math" &&
391
+ mathIntegrationPoints.has(outer[1]) &&
392
+ mathTextLeaves.has(tag)
393
+ ? "math"
394
+ : namespace;
395
+ if (element === node) {
396
+ return own;
397
+ }
398
+ if (tag === "svg" || tag === "math") {
399
+ namespace =
400
+ !outer || startsNamespace(tag, own, outer[1]) ? tag : own;
401
+ } else {
402
+ namespace =
403
+ own !== "html" && switchesToHTML(element, tag, own)
404
+ ? "html"
405
+ : own;
406
+ }
407
+ parent = [element, tag, own];
408
+ }
409
+ return namespace;
410
+ };
411
+
412
+ // `type="hidden"` and `type={"hidden"}`.
413
+ const isHiddenInput = (node) => {
414
+ const value = jsxGetProp(node.openingElement.attributes, "type")?.value;
415
+ const type =
416
+ value?.type === "JSXExpressionContainer" ? value.expression : value;
417
+ return (
418
+ type?.type === "Literal" &&
419
+ typeof type.value === "string" &&
420
+ type.value.toLowerCase() === "hidden"
421
+ );
422
+ };
423
+
1
424
  export default {
2
- defaultOptions: [],
3
425
  meta: {
426
+ type: "problem",
4
427
  docs: {
5
428
  description:
6
- "Placeholder for the upstream validate-jsx-nesting rule, which currently has no implementation in eslint-plugin-solid.",
7
- url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/src/rules/validate-jsx-nesting.ts",
429
+ "Disallow HTML nesting the browser refuses to keep, like `<p><div /></p>`, which silently renders a different DOM than the JSX describes.",
430
+ url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/validate-jsx-nesting.md",
431
+ },
432
+ messages: {
433
+ invalidNesting:
434
+ "Invalid HTML nesting: `<{{child}}>` cannot be a child of `<{{parent}}>`. The HTML parser restructures this, so the rendered DOM won't match this markup.",
435
+ invalidNestingInserted:
436
+ "Invalid HTML nesting: `<{{child}}>` cannot be a child of `<{{parent}}>`. The client inserts it as written, but the HTML parser restructures it in server-rendered HTML, so hydration won't match this markup.",
8
437
  },
9
- messages: {},
10
438
  schema: [],
11
- type: "problem",
12
439
  },
13
- create() {
14
- return {};
440
+ defaultOptions: [],
441
+ create(context) {
442
+ const check = (node, child, parentNode) => {
443
+ const parent = getDOMTagName(parentNode);
444
+ if (!parent) {
445
+ return;
446
+ }
447
+ if (isValidHTMLNesting(parent, child)) {
448
+ return;
449
+ }
450
+ if (
451
+ !parserRewrites(parent, child, getParsingNamespace(parentNode))
452
+ ) {
453
+ return;
454
+ }
455
+ // Not in upstream, which parses a bare `<input>` and so reports
456
+ // this one too: the parser only moves an input out of a table when
457
+ // its type is not "hidden".
458
+ if (
459
+ child === "input" &&
460
+ TABLE_PARENTS.has(parent) &&
461
+ isHiddenInput(node)
462
+ ) {
463
+ return;
464
+ }
465
+
466
+ context.report({
467
+ node: node.openingElement.name,
468
+ messageId: isInserted(node, parentNode)
469
+ ? "invalidNestingInserted"
470
+ : "invalidNesting",
471
+ data: { parent, child },
472
+ });
473
+ };
474
+
475
+ return {
476
+ JSXElement(node) {
477
+ const child = getDOMTagName(node);
478
+ if (!child) {
479
+ return;
480
+ }
481
+
482
+ const parentNode = getDOMParent(node);
483
+ if (parentNode) {
484
+ check(node, child, parentNode);
485
+ }
486
+ },
487
+ };
15
488
  },
16
489
  };
package/src/utils.mjs CHANGED
@@ -161,7 +161,9 @@ export function getCommentAfter(node, sourceCode) {
161
161
  // Solid 2.0 split the runtime across packages: `solid-js` keeps the core and
162
162
  // the store APIs, while `@solidjs/web`, `@solidjs/h`, `@solidjs/html` and
163
163
  // `@solidjs/universal` own the renderers. Match both layouts.
164
- export function trackImports(fromModule = /^(?:solid-js|@solidjs\/[a-z-]+)(?:\/|$)/) {
164
+ export function trackImports(
165
+ fromModule = /^(?:solid-js|@solidjs\/[a-z-]+)(?:\/|$)/,
166
+ ) {
165
167
  const importMap = new Map();
166
168
 
167
169
  function handleImportDeclaration(node) {
@@ -202,16 +204,27 @@ export function appendImports(fixer, sourceCode, importNode, identifiers) {
202
204
  return fixer.insertTextAfter(namedSpecifier, `, ${identifiersString}`);
203
205
  }
204
206
 
205
- const otherSpecifier = importNode.specifiers.find((specifier) => {
206
- return (
207
- specifier.type === "ImportDefaultSpecifier" ||
208
- specifier.type === "ImportNamespaceSpecifier"
207
+ // A namespace import cannot share a declaration with named imports
208
+ // (`import * as X, { a }` and `import X, { a }, * as Y` do not parse), so
209
+ // the names get a declaration of their own right after it.
210
+ if (
211
+ importNode.specifiers.some((specifier) => {
212
+ return specifier.type === "ImportNamespaceSpecifier";
213
+ })
214
+ ) {
215
+ return fixer.insertTextAfter(
216
+ importNode,
217
+ `\nimport ${importNode.importKind === "type" ? "type " : ""}{ ${identifiersString} } from ${sourceCode.getText(importNode.source)};`,
209
218
  );
219
+ }
220
+
221
+ const defaultSpecifier = importNode.specifiers.find((specifier) => {
222
+ return specifier.type === "ImportDefaultSpecifier";
210
223
  });
211
224
 
212
- if (otherSpecifier) {
225
+ if (defaultSpecifier) {
213
226
  return fixer.insertTextAfter(
214
- otherSpecifier,
227
+ defaultSpecifier,
215
228
  `, { ${identifiersString} }`,
216
229
  );
217
230
  }
@@ -262,10 +275,27 @@ export function insertImports(
262
275
  );
263
276
  }
264
277
 
265
- return fixer.insertTextBeforeRange(
266
- [0, 0],
267
- `import ${isType ? "type " : ""}{ ${identifiersString} } from "${source}";\n`,
268
- );
278
+ const importText = `import ${isType ? "type " : ""}{ ${identifiersString} } from "${source}";\n`;
279
+ // No import to go above: the new one goes in front of the first statement
280
+ // that is not a directive. In front of `"use client"` it would end the
281
+ // directive prologue, and the directive would stop being one.
282
+ const firstStatement = programNode.body.find((node) => {
283
+ return typeof node.directive !== "string";
284
+ });
285
+ if (firstStatement) {
286
+ return fixer.insertTextBeforeRange(
287
+ (getCommentBefore(firstStatement, sourceCode) ?? firstStatement)
288
+ .range,
289
+ importText,
290
+ );
291
+ }
292
+
293
+ const lastDirective = programNode.body.at(-1);
294
+ if (lastDirective) {
295
+ return fixer.insertTextAfter(lastDirective, `\n${importText}`);
296
+ }
297
+
298
+ return fixer.insertTextBeforeRange([0, 0], importText);
269
299
  }
270
300
 
271
301
  export function removeSpecifier(fixer, sourceCode, specifier, pure = true) {
@@ -276,12 +306,47 @@ export function removeSpecifier(fixer, sourceCode, specifier, pure = true) {
276
306
 
277
307
  const maybeComma = sourceCode.getTokenAfter(specifier);
278
308
  if (maybeComma?.value === ",") {
279
- return fixer.removeRange([specifier.range[0], maybeComma.range[1]]);
309
+ // The space after the comma goes too, or `{ a, b }` turns into `{ b }`.
310
+ const spaceAfter = /^\s*/u.exec(
311
+ sourceCode.text.slice(maybeComma.range[1]),
312
+ );
313
+ return fixer.removeRange([
314
+ specifier.range[0],
315
+ maybeComma.range[1] + (spaceAfter?.[0].length ?? 0),
316
+ ]);
317
+ }
318
+
319
+ // The last specifier without a trailing comma: the comma in front of it
320
+ // goes with it, or `{ a, b }` turns into `{ a, }`.
321
+ const maybeCommaBefore = sourceCode.getTokenBefore(specifier);
322
+ if (maybeCommaBefore?.value === ",") {
323
+ return fixer.removeRange([
324
+ maybeCommaBefore.range[0],
325
+ specifier.range[1],
326
+ ]);
280
327
  }
281
328
 
282
329
  return fixer.remove(specifier);
283
330
  }
284
331
 
332
+ /**
333
+ * Whether `declaration` can take one more named specifier of a kind: a value
334
+ * never goes into an `import type`, and `import type D, { T }` and `import type *
335
+ * as ns, { T }` do not exist.
336
+ */
337
+ export function canTakeSpecifier(declaration, isType) {
338
+ if (declaration.importKind !== "type") {
339
+ return true;
340
+ }
341
+
342
+ return (
343
+ isType &&
344
+ declaration.specifiers.every((specifier) => {
345
+ return specifier.type === "ImportSpecifier";
346
+ })
347
+ );
348
+ }
349
+
285
350
  export function jsxPropName(prop) {
286
351
  if (prop.name.type === "JSXNamespacedName") {
287
352
  return `${prop.name.namespace.name}:${prop.name.name.name}`;