@so1ve/eslint-plugin-sort-imports 3.26.0 → 4.0.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.
package/src/shared.js CHANGED
@@ -7,60 +7,60 @@ const NEWLINE = /(\r?\n)/;
7
7
  const hasNewline = (string) => NEWLINE.test(string);
8
8
 
9
9
  function guessNewline(sourceCode) {
10
- const match = NEWLINE.exec(sourceCode.text);
10
+ const match = NEWLINE.exec(sourceCode.text);
11
11
 
12
- return match == null ? "\n" : match[0];
12
+ return match == null ? "\n" : match[0];
13
13
  }
14
14
 
15
15
  function parseWhitespace(whitespace) {
16
- const allItems = whitespace.split(NEWLINE);
17
-
18
- // Remove blank lines. `allItems` contains alternating `spaces` (which can be
19
- // the empty string) and `newline` (which is either "\r\n" or "\n"). So in
20
- // practice `allItems` grows like this as there are more newlines in
21
- // `whitespace`:
22
- //
23
- // [spaces]
24
- // [spaces, newline, spaces]
25
- // [spaces, newline, spaces, newline, spaces]
26
- // [spaces, newline, spaces, newline, spaces, newline, spaces]
27
- //
28
- // If there are 5 or more items we have at least one blank line. If so, keep
29
- // the first `spaces`, the first `newline` and the last `spaces`.
30
- const items =
31
- allItems.length >= 5
32
- ? [...allItems.slice(0, 2), ...allItems.slice(-1)]
33
- : allItems;
34
-
35
- return (
36
- items
37
- .map((spacesOrNewline, index) =>
38
- index % 2 === 0
39
- ? { type: "Spaces", code: spacesOrNewline }
40
- : { type: "Newline", code: spacesOrNewline },
41
- )
42
- // Remove empty spaces since it makes debugging easier.
43
- .filter((token) => token.code !== "")
44
- );
16
+ const allItems = whitespace.split(NEWLINE);
17
+
18
+ // Remove blank lines. `allItems` contains alternating `spaces` (which can be
19
+ // the empty string) and `newline` (which is either "\r\n" or "\n"). So in
20
+ // practice `allItems` grows like this as there are more newlines in
21
+ // `whitespace`:
22
+ //
23
+ // [spaces]
24
+ // [spaces, newline, spaces]
25
+ // [spaces, newline, spaces, newline, spaces]
26
+ // [spaces, newline, spaces, newline, spaces, newline, spaces]
27
+ //
28
+ // If there are 5 or more items we have at least one blank line. If so, keep
29
+ // the first `spaces`, the first `newline` and the last `spaces`.
30
+ const items =
31
+ allItems.length >= 5
32
+ ? [...allItems.slice(0, 2), ...allItems.slice(-1)]
33
+ : allItems;
34
+
35
+ return (
36
+ items
37
+ .map((spacesOrNewline, index) =>
38
+ index % 2 === 0
39
+ ? { type: "Spaces", code: spacesOrNewline }
40
+ : { type: "Newline", code: spacesOrNewline },
41
+ )
42
+ // Remove empty spaces since it makes debugging easier.
43
+ .filter((token) => token.code !== "")
44
+ );
45
45
  }
46
46
 
47
47
  const naturalSort = natsort();
48
48
  function compare(path1, path2) {
49
- const path1Depth = path1.split("-").filter((p) => p === "__").length;
50
- const path2Depth = path2.split("-").filter((p) => p === "__").length;
51
- const path1IsDot = path1 === "_-,";
52
- const path2IsDot = path2 === "_-,";
53
-
54
- if (path1IsDot && !path2IsDot) {
55
- return 1;
56
- }
57
- if (path2IsDot && !path1IsDot) {
58
- return -1;
59
- }
60
-
61
- return path1Depth === path2Depth
62
- ? naturalSort(path1, path2)
63
- : path2Depth - path1Depth;
49
+ const path1Depth = path1.split("-").filter((p) => p === "__").length;
50
+ const path2Depth = path2.split("-").filter((p) => p === "__").length;
51
+ const path1IsDot = path1 === "_-,";
52
+ const path2IsDot = path2 === "_-,";
53
+
54
+ if (path1IsDot && !path2IsDot) {
55
+ return 1;
56
+ }
57
+ if (path2IsDot && !path1IsDot) {
58
+ return -1;
59
+ }
60
+
61
+ return path1Depth === path2Depth
62
+ ? naturalSort(path1, path2)
63
+ : path2Depth - path1Depth;
64
64
  }
65
65
 
66
66
  const isIdentifier = (node) => node.type === "Identifier";
@@ -68,7 +68,7 @@ const isIdentifier = (node) => node.type === "Identifier";
68
68
  const isKeyword = (node) => node.type === "Keyword";
69
69
 
70
70
  const isPunctuator = (node, value) =>
71
- node.type === "Punctuator" && node.value === value;
71
+ node.type === "Punctuator" && node.value === value;
72
72
 
73
73
  const isBlockComment = (node) => node.type === "Block";
74
74
 
@@ -79,58 +79,58 @@ const isSpaces = (node) => node.type === "Spaces";
79
79
  const isNewline = (node) => node.type === "Newline";
80
80
 
81
81
  const getImportExportKind = (node) =>
82
- node.importKind || node.exportKind || "value";
82
+ node.importKind || node.exportKind || "value";
83
83
 
84
84
  function getSource(node) {
85
- const source = node.source.value;
86
-
87
- return {
88
- // Sort by directory level rather than by string length.
89
- source: source
90
- // Treat `.` as `./`, `..` as `../`, `../..` as `../../` etc.
91
- .replace(/^[./]*\.$/, "$&/")
92
- // Make `../` sort after `../../` but before `../a` etc.
93
- // Why a comma? See the next comment.
94
- .replace(/^[./]*\/$/, "$&,")
95
- // Make `.` and `/` sort before any other punctation.
96
- // The default order is: _ - , x x x . x x x / x x x
97
- // We’re changing it to: . / , x x x _ x x x - x x x
98
- .replace(/[./_-]/g, (char) => {
99
- switch (char) {
100
- case ".": {
101
- return "_";
102
- }
103
- case "/": {
104
- return "-";
105
- }
106
- case "_": {
107
- return ".";
108
- }
109
- case "-": {
110
- return "/";
111
- }
112
- // istanbul ignore next
113
- default: {
114
- throw new Error(`Unknown source substitution character: ${char}`);
115
- }
116
- }
117
- }),
118
- originalSource: source,
119
- kind: getImportExportKind(node),
120
- };
85
+ const source = node.source.value;
86
+
87
+ return {
88
+ // Sort by directory level rather than by string length.
89
+ source: source
90
+ // Treat `.` as `./`, `..` as `../`, `../..` as `../../` etc.
91
+ .replace(/^[./]*\.$/, "$&/")
92
+ // Make `../` sort after `../../` but before `../a` etc.
93
+ // Why a comma? See the next comment.
94
+ .replace(/^[./]*\/$/, "$&,")
95
+ // Make `.` and `/` sort before any other punctation.
96
+ // The default order is: _ - , x x x . x x x / x x x
97
+ // We’re changing it to: . / , x x x _ x x x - x x x
98
+ .replace(/[./_-]/g, (char) => {
99
+ switch (char) {
100
+ case ".": {
101
+ return "_";
102
+ }
103
+ case "/": {
104
+ return "-";
105
+ }
106
+ case "_": {
107
+ return ".";
108
+ }
109
+ case "-": {
110
+ return "/";
111
+ }
112
+ // istanbul ignore next
113
+ default: {
114
+ throw new Error(`Unknown source substitution character: ${char}`);
115
+ }
116
+ }
117
+ }),
118
+ originalSource: source,
119
+ kind: getImportExportKind(node),
120
+ };
121
121
  }
122
122
 
123
123
  // Like `Array.prototype.findIndex`, but searches from the end.
124
124
  function findLastIndex(array, fn) {
125
- for (let index = array.length - 1; index >= 0; index--) {
126
- if (fn(array[index], index, array)) {
127
- return index;
128
- }
129
- }
130
-
131
- // There are currently no usages of `findLastIndex` where nothing is found.
132
- // istanbul ignore next
133
- return -1;
125
+ for (let index = array.length - 1; index >= 0; index--) {
126
+ if (fn(array[index], index, array)) {
127
+ return index;
128
+ }
129
+ }
130
+
131
+ // There are currently no usages of `findLastIndex` where nothing is found.
132
+ // istanbul ignore next
133
+ return -1;
134
134
  }
135
135
 
136
136
  // Like `Array.prototype.flatMap`, had it been available.
@@ -139,38 +139,38 @@ const flatMap = (array, fn) => array.flatMap(fn);
139
139
  // Returns `sourceCode.getTokens(node)` plus whitespace and comments. All tokens
140
140
  // have a `code` property with `sourceCode.getText(token)`.
141
141
  function getAllTokens(node, sourceCode) {
142
- const tokens = sourceCode.getTokens(node);
143
- const lastTokenIndex = tokens.length - 1;
144
-
145
- return flatMap(tokens, (token, tokenIndex) => {
146
- const newToken = { ...token, code: sourceCode.getText(token) };
147
-
148
- if (tokenIndex === lastTokenIndex) {
149
- return [newToken];
150
- }
151
-
152
- const comments = sourceCode.getCommentsAfter(token);
153
- const last = comments.length > 0 ? comments[comments.length - 1] : token;
154
- const nextToken = tokens[tokenIndex + 1];
155
-
156
- return [
157
- newToken,
158
- ...flatMap(comments, (comment, commentIndex) => {
159
- const previous =
160
- commentIndex === 0 ? token : comments[commentIndex - 1];
161
-
162
- return [
163
- ...parseWhitespace(
164
- sourceCode.text.slice(previous.range[1], comment.range[0]),
165
- ),
166
- { ...comment, code: sourceCode.getText(comment) },
167
- ];
168
- }),
169
- ...parseWhitespace(
170
- sourceCode.text.slice(last.range[1], nextToken.range[0]),
171
- ),
172
- ];
173
- });
142
+ const tokens = sourceCode.getTokens(node);
143
+ const lastTokenIndex = tokens.length - 1;
144
+
145
+ return flatMap(tokens, (token, tokenIndex) => {
146
+ const newToken = { ...token, code: sourceCode.getText(token) };
147
+
148
+ if (tokenIndex === lastTokenIndex) {
149
+ return [newToken];
150
+ }
151
+
152
+ const comments = sourceCode.getCommentsAfter(token);
153
+ const last = comments.length > 0 ? comments[comments.length - 1] : token;
154
+ const nextToken = tokens[tokenIndex + 1];
155
+
156
+ return [
157
+ newToken,
158
+ ...flatMap(comments, (comment, commentIndex) => {
159
+ const previous =
160
+ commentIndex === 0 ? token : comments[commentIndex - 1];
161
+
162
+ return [
163
+ ...parseWhitespace(
164
+ sourceCode.text.slice(previous.range[1], comment.range[0]),
165
+ ),
166
+ { ...comment, code: sourceCode.getText(comment) },
167
+ ];
168
+ }),
169
+ ...parseWhitespace(
170
+ sourceCode.text.slice(last.range[1], nextToken.range[0]),
171
+ ),
172
+ ];
173
+ });
174
174
  }
175
175
 
176
176
  // Prints tokens that are enhanced with a `code` property – like those returned
@@ -178,220 +178,220 @@ function getAllTokens(node, sourceCode) {
178
178
  const printTokens = (tokens) => tokens.map((token) => token.code).join("");
179
179
 
180
180
  const removeBlankLines = (whitespace) =>
181
- printTokens(parseWhitespace(whitespace));
181
+ printTokens(parseWhitespace(whitespace));
182
182
 
183
183
  // `comments` is a list of comments that occur before `node`. Print those and
184
184
  // the whitespace between themselves and between `node`.
185
185
  function printCommentsBefore(node, comments, sourceCode) {
186
- const lastIndex = comments.length - 1;
187
-
188
- return comments
189
- .map((comment, index) => {
190
- const next = index === lastIndex ? node : comments[index + 1];
191
-
192
- return (
193
- sourceCode.getText(comment) +
194
- removeBlankLines(sourceCode.text.slice(comment.range[1], next.range[0]))
195
- );
196
- })
197
- .join("");
186
+ const lastIndex = comments.length - 1;
187
+
188
+ return comments
189
+ .map((comment, index) => {
190
+ const next = index === lastIndex ? node : comments[index + 1];
191
+
192
+ return (
193
+ sourceCode.getText(comment) +
194
+ removeBlankLines(sourceCode.text.slice(comment.range[1], next.range[0]))
195
+ );
196
+ })
197
+ .join("");
198
198
  }
199
199
 
200
200
  // `comments` is a list of comments that occur after `node`. Print those and
201
201
  // the whitespace between themselves and between `node`.
202
202
  const printCommentsAfter = (node, comments, sourceCode) =>
203
- comments
204
- .map((comment, index) => {
205
- const previous = index === 0 ? node : comments[index - 1];
206
-
207
- return (
208
- removeBlankLines(
209
- sourceCode.text.slice(previous.range[1], comment.range[0]),
210
- ) + sourceCode.getText(comment)
211
- );
212
- })
213
- .join("");
203
+ comments
204
+ .map((comment, index) => {
205
+ const previous = index === 0 ? node : comments[index - 1];
206
+
207
+ return (
208
+ removeBlankLines(
209
+ sourceCode.text.slice(previous.range[1], comment.range[0]),
210
+ ) + sourceCode.getText(comment)
211
+ );
212
+ })
213
+ .join("");
214
214
 
215
215
  function getIndentation(node, sourceCode) {
216
- const tokenBefore = sourceCode.getTokenBefore(node, {
217
- includeComments: true,
218
- });
219
- if (tokenBefore == null) {
220
- const text = sourceCode.text.slice(0, node.range[0]);
221
- const lines = text.split(NEWLINE);
222
-
223
- return lines[lines.length - 1];
224
- }
225
- const text = sourceCode.text.slice(tokenBefore.range[1], node.range[0]);
226
- const lines = text.split(NEWLINE);
227
-
228
- return lines.length > 1 ? lines[lines.length - 1] : "";
216
+ const tokenBefore = sourceCode.getTokenBefore(node, {
217
+ includeComments: true,
218
+ });
219
+ if (tokenBefore == null) {
220
+ const text = sourceCode.text.slice(0, node.range[0]);
221
+ const lines = text.split(NEWLINE);
222
+
223
+ return lines[lines.length - 1];
224
+ }
225
+ const text = sourceCode.text.slice(tokenBefore.range[1], node.range[0]);
226
+ const lines = text.split(NEWLINE);
227
+
228
+ return lines.length > 1 ? lines[lines.length - 1] : "";
229
229
  }
230
230
 
231
231
  function getTrailingSpaces(node, sourceCode) {
232
- const tokenAfter = sourceCode.getTokenAfter(node, {
233
- includeComments: true,
234
- });
235
- if (tokenAfter == null) {
236
- const text = sourceCode.text.slice(node.range[1]);
237
- const lines = text.split(NEWLINE);
238
-
239
- return lines[0];
240
- }
241
- const text = sourceCode.text.slice(node.range[1], tokenAfter.range[0]);
242
- const lines = text.split(NEWLINE);
243
-
244
- return lines[0];
232
+ const tokenAfter = sourceCode.getTokenAfter(node, {
233
+ includeComments: true,
234
+ });
235
+ if (tokenAfter == null) {
236
+ const text = sourceCode.text.slice(node.range[1]);
237
+ const lines = text.split(NEWLINE);
238
+
239
+ return lines[0];
240
+ }
241
+ const text = sourceCode.text.slice(node.range[1], tokenAfter.range[0]);
242
+ const lines = text.split(NEWLINE);
243
+
244
+ return lines[0];
245
245
  }
246
246
 
247
247
  const sortImportExportItems = (items) =>
248
- [...items].sort((itemA, itemB) =>
249
- // If both items are side effect imports, keep their original order.
250
- itemA.isSideEffectImport && itemB.isSideEffectImport
251
- ? itemA.index - itemB.index
252
- : // If one of the items is a side effect import, move it first.
253
- itemA.isSideEffectImport
254
- ? -1
255
- : itemB.isSideEffectImport
256
- ? 1
257
- : // Compare the `from` part.
258
- compare(itemA.source.source, itemB.source.source) ||
259
- // The `.source` has been slightly tweaked. To stay fully deterministic,
260
- // also sort on the original value.
261
- compare(itemA.source.originalSource, itemB.source.originalSource) ||
262
- // Then put type imports/exports before regular ones.
263
- compare(itemA.source.kind, itemB.source.kind) ||
264
- // Keep the original order if the sources are the same. It’s not worth
265
- // trying to compare anything else, and you can use `import/no-duplicates`
266
- // to get rid of the problem anyway.
267
- itemA.index - itemB.index,
268
- );
248
+ [...items].sort((itemA, itemB) =>
249
+ // If both items are side effect imports, keep their original order.
250
+ itemA.isSideEffectImport && itemB.isSideEffectImport
251
+ ? itemA.index - itemB.index
252
+ : // If one of the items is a side effect import, move it first.
253
+ itemA.isSideEffectImport
254
+ ? -1
255
+ : itemB.isSideEffectImport
256
+ ? 1
257
+ : // Compare the `from` part.
258
+ compare(itemA.source.source, itemB.source.source) ||
259
+ // The `.source` has been slightly tweaked. To stay fully deterministic,
260
+ // also sort on the original value.
261
+ compare(itemA.source.originalSource, itemB.source.originalSource) ||
262
+ // Then put type imports/exports before regular ones.
263
+ compare(itemA.source.kind, itemB.source.kind) ||
264
+ // Keep the original order if the sources are the same. It’s not worth
265
+ // trying to compare anything else, and you can use `import/no-duplicates`
266
+ // to get rid of the problem anyway.
267
+ itemA.index - itemB.index,
268
+ );
269
269
 
270
270
  const sortSpecifierItems = (items) =>
271
- [...items].sort(
272
- (itemA, itemB) =>
273
- // Compare by imported or exported name (external interface name).
274
- // import { a as b } from "a"
275
- // ^
276
- // export { b as a }
277
- // ^
278
- compare(
279
- (itemA.node.imported || itemA.node.exported).name,
280
- (itemB.node.imported || itemB.node.exported).name,
281
- ) ||
282
- // Then compare by the file-local name.
283
- // import { a as b } from "a"
284
- // ^
285
- // export { b as a }
286
- // ^
287
- compare(itemA.node.local.name, itemB.node.local.name) ||
288
- // Then put type specifiers before regular ones.
289
- compare(
290
- getImportExportKind(itemA.node),
291
- getImportExportKind(itemB.node),
292
- ) ||
293
- // Keep the original order if the names are the same. It’s not worth
294
- // trying to compare anything else, `import {a, a} from "mod"` is a syntax
295
- // error anyway (but @babel/eslint-parser kind of supports it).
296
- // istanbul ignore next
297
- itemA.index - itemB.index,
298
- );
271
+ [...items].sort(
272
+ (itemA, itemB) =>
273
+ // Compare by imported or exported name (external interface name).
274
+ // import { a as b } from "a"
275
+ // ^
276
+ // export { b as a }
277
+ // ^
278
+ compare(
279
+ (itemA.node.imported || itemA.node.exported).name,
280
+ (itemB.node.imported || itemB.node.exported).name,
281
+ ) ||
282
+ // Then compare by the file-local name.
283
+ // import { a as b } from "a"
284
+ // ^
285
+ // export { b as a }
286
+ // ^
287
+ compare(itemA.node.local.name, itemB.node.local.name) ||
288
+ // Then put type specifiers before regular ones.
289
+ compare(
290
+ getImportExportKind(itemA.node),
291
+ getImportExportKind(itemB.node),
292
+ ) ||
293
+ // Keep the original order if the names are the same. It’s not worth
294
+ // trying to compare anything else, `import {a, a} from "mod"` is a syntax
295
+ // error anyway (but @babel/eslint-parser kind of supports it).
296
+ // istanbul ignore next
297
+ itemA.index - itemB.index,
298
+ );
299
299
 
300
300
  // A “chunk” is a sequence of statements of a certain type with only comments
301
301
  // and whitespace between.
302
302
  function extractChunks(parentNode, isPartOfChunk) {
303
- const chunks = [];
304
- let chunk = [];
305
- let lastNode;
306
-
307
- for (const node of parentNode.body) {
308
- const result = isPartOfChunk(node, lastNode);
309
- switch (result) {
310
- case "PartOfChunk": {
311
- chunk.push(node);
312
- break;
313
- }
314
-
315
- case "PartOfNewChunk": {
316
- if (chunk.length > 0) {
317
- chunks.push(chunk);
318
- }
319
- chunk = [node];
320
- break;
321
- }
322
-
323
- case "NotPartOfChunk": {
324
- if (chunk.length > 0) {
325
- chunks.push(chunk);
326
- chunk = [];
327
- }
328
- break;
329
- }
330
-
331
- // istanbul ignore next
332
- default: {
333
- throw new Error(`Unknown chunk result: ${result}`);
334
- }
335
- }
336
-
337
- lastNode = node;
338
- }
339
-
340
- if (chunk.length > 0) {
341
- chunks.push(chunk);
342
- }
343
-
344
- return chunks;
303
+ const chunks = [];
304
+ let chunk = [];
305
+ let lastNode;
306
+
307
+ for (const node of parentNode.body) {
308
+ const result = isPartOfChunk(node, lastNode);
309
+ switch (result) {
310
+ case "PartOfChunk": {
311
+ chunk.push(node);
312
+ break;
313
+ }
314
+
315
+ case "PartOfNewChunk": {
316
+ if (chunk.length > 0) {
317
+ chunks.push(chunk);
318
+ }
319
+ chunk = [node];
320
+ break;
321
+ }
322
+
323
+ case "NotPartOfChunk": {
324
+ if (chunk.length > 0) {
325
+ chunks.push(chunk);
326
+ chunk = [];
327
+ }
328
+ break;
329
+ }
330
+
331
+ // istanbul ignore next
332
+ default: {
333
+ throw new Error(`Unknown chunk result: ${result}`);
334
+ }
335
+ }
336
+
337
+ lastNode = node;
338
+ }
339
+
340
+ if (chunk.length > 0) {
341
+ chunks.push(chunk);
342
+ }
343
+
344
+ return chunks;
345
345
  }
346
346
 
347
347
  function maybeReportSorting(context, sorted, start, end) {
348
- const sourceCode = context.sourceCode;
349
- const original = sourceCode.getText().slice(start, end);
350
- if (original !== sorted) {
351
- context.report({
352
- messageId: "sort",
353
- loc: {
354
- start: sourceCode.getLocFromIndex(start),
355
- end: sourceCode.getLocFromIndex(end),
356
- },
357
- fix: (fixer) => fixer.replaceTextRange([start, end], sorted),
358
- });
359
- }
348
+ const sourceCode = context.sourceCode;
349
+ const original = sourceCode.getText().slice(start, end);
350
+ if (original !== sorted) {
351
+ context.report({
352
+ messageId: "sort",
353
+ loc: {
354
+ start: sourceCode.getLocFromIndex(start),
355
+ end: sourceCode.getLocFromIndex(end),
356
+ },
357
+ fix: (fixer) => fixer.replaceTextRange([start, end], sorted),
358
+ });
359
+ }
360
360
  }
361
361
 
362
362
  function printSortedItems(sortedItems, originalItems, sourceCode) {
363
- const newline = guessNewline(sourceCode);
364
-
365
- const sorted = sortedItems
366
- .map((groups) =>
367
- groups
368
- .map((groupItems) => groupItems.map((item) => item.code).join(newline))
369
- .join(newline),
370
- )
371
- .join(newline + newline);
372
-
373
- // Edge case: If the last import/export (after sorting) ends with a line
374
- // comment and there’s code (or a multiline block comment) on the same line,
375
- // add a newline so we don’t accidentally comment stuff out.
376
- const flattened = flatMap(sortedItems, (groups) => groups.flat());
377
- const lastSortedItem = flattened[flattened.length - 1];
378
- const lastOriginalItem = originalItems[originalItems.length - 1];
379
- const nextToken = lastSortedItem.needsNewline
380
- ? sourceCode.getTokenAfter(lastOriginalItem.node, {
381
- includeComments: true,
382
- filter: (token) =>
383
- !isLineComment(token) &&
384
- (!isBlockComment(token) ||
385
- token.loc.end.line !== lastOriginalItem.node.loc.end.line),
386
- })
387
- : undefined;
388
- const maybeNewline =
389
- nextToken != null &&
390
- nextToken.loc.start.line === lastOriginalItem.node.loc.end.line
391
- ? newline
392
- : "";
393
-
394
- return sorted + maybeNewline;
363
+ const newline = guessNewline(sourceCode);
364
+
365
+ const sorted = sortedItems
366
+ .map((groups) =>
367
+ groups
368
+ .map((groupItems) => groupItems.map((item) => item.code).join(newline))
369
+ .join(newline),
370
+ )
371
+ .join(newline + newline);
372
+
373
+ // Edge case: If the last import/export (after sorting) ends with a line
374
+ // comment and there’s code (or a multiline block comment) on the same line,
375
+ // add a newline so we don’t accidentally comment stuff out.
376
+ const flattened = flatMap(sortedItems, (groups) => groups.flat());
377
+ const lastSortedItem = flattened[flattened.length - 1];
378
+ const lastOriginalItem = originalItems[originalItems.length - 1];
379
+ const nextToken = lastSortedItem.needsNewline
380
+ ? sourceCode.getTokenAfter(lastOriginalItem.node, {
381
+ includeComments: true,
382
+ filter: (token) =>
383
+ !isLineComment(token) &&
384
+ (!isBlockComment(token) ||
385
+ token.loc.end.line !== lastOriginalItem.node.loc.end.line),
386
+ })
387
+ : undefined;
388
+ const maybeNewline =
389
+ nextToken != null &&
390
+ nextToken.loc.start.line === lastOriginalItem.node.loc.end.line
391
+ ? newline
392
+ : "";
393
+
394
+ return sorted + maybeNewline;
395
395
  }
396
396
 
397
397
  // Wrap the import/export nodes in `passedChunk` in objects with more data about
@@ -399,86 +399,86 @@ function printSortedItems(sortedItems, originalItems, sourceCode) {
399
399
  // the node as a string, with comments (if any). Finding the corresponding
400
400
  // comments is the hard part.
401
401
  function getImportExportItems(
402
- passedChunk,
403
- sourceCode,
404
- isSideEffectImport,
405
- getSpecifiers,
402
+ passedChunk,
403
+ sourceCode,
404
+ isSideEffectImport,
405
+ getSpecifiers,
406
406
  ) {
407
- const chunk = handleLastSemicolon(passedChunk, sourceCode);
408
-
409
- return chunk.map((node, nodeIndex) => {
410
- const lastLine =
411
- nodeIndex === 0
412
- ? node.loc.start.line - 1
413
- : chunk[nodeIndex - 1].loc.end.line;
414
-
415
- // Get all comments before the import/export, except:
416
- //
417
- // - Comments on another line for the first import/export.
418
- // - Comments that belong to the previous import/export (if any) – that is,
419
- // comments that are on the same line as the previous import/export. But
420
- // multiline block comments always belong to this import/export, not the
421
- // previous.
422
- const commentsBefore = sourceCode
423
- .getCommentsBefore(node)
424
- .filter(
425
- (comment) =>
426
- comment.loc.start.line <= node.loc.start.line &&
427
- comment.loc.end.line > lastLine &&
428
- (nodeIndex > 0 || comment.loc.start.line > lastLine),
429
- );
430
-
431
- // Get all comments after the import/export that are on the same line.
432
- // Multiline block comments belong to the _next_ import/export (or the
433
- // following code in case of the last import/export).
434
- const commentsAfter = sourceCode
435
- .getCommentsAfter(node)
436
- .filter((comment) => comment.loc.end.line === node.loc.end.line);
437
-
438
- const before = printCommentsBefore(node, commentsBefore, sourceCode);
439
- const after = printCommentsAfter(node, commentsAfter, sourceCode);
440
-
441
- // Print the indentation before the import/export or its first comment, if
442
- // any, to support indentation in `<script>` tags.
443
- const indentation = getIndentation(
444
- commentsBefore.length > 0 ? commentsBefore[0] : node,
445
- sourceCode,
446
- );
447
-
448
- // Print spaces after the import/export or its last comment, if any, to
449
- // avoid producing a sort error just because you accidentally added a few
450
- // trailing spaces among the imports/exports.
451
- const trailingSpaces = getTrailingSpaces(
452
- commentsAfter.length > 0 ? commentsAfter[commentsAfter.length - 1] : node,
453
- sourceCode,
454
- );
455
-
456
- const code =
457
- indentation +
458
- before +
459
- printWithSortedSpecifiers(node, sourceCode, getSpecifiers) +
460
- after +
461
- trailingSpaces;
462
-
463
- const all = [...commentsBefore, node, ...commentsAfter];
464
- const [start] = all[0].range;
465
- const [, end] = all[all.length - 1].range;
466
-
467
- const source = getSource(node);
468
-
469
- return {
470
- node,
471
- code,
472
- start: start - indentation.length,
473
- end: end + trailingSpaces.length,
474
- isSideEffectImport: isSideEffectImport(node, sourceCode),
475
- source,
476
- index: nodeIndex,
477
- needsNewline:
478
- commentsAfter.length > 0 &&
479
- isLineComment(commentsAfter[commentsAfter.length - 1]),
480
- };
481
- });
407
+ const chunk = handleLastSemicolon(passedChunk, sourceCode);
408
+
409
+ return chunk.map((node, nodeIndex) => {
410
+ const lastLine =
411
+ nodeIndex === 0
412
+ ? node.loc.start.line - 1
413
+ : chunk[nodeIndex - 1].loc.end.line;
414
+
415
+ // Get all comments before the import/export, except:
416
+ //
417
+ // - Comments on another line for the first import/export.
418
+ // - Comments that belong to the previous import/export (if any) – that is,
419
+ // comments that are on the same line as the previous import/export. But
420
+ // multiline block comments always belong to this import/export, not the
421
+ // previous.
422
+ const commentsBefore = sourceCode
423
+ .getCommentsBefore(node)
424
+ .filter(
425
+ (comment) =>
426
+ comment.loc.start.line <= node.loc.start.line &&
427
+ comment.loc.end.line > lastLine &&
428
+ (nodeIndex > 0 || comment.loc.start.line > lastLine),
429
+ );
430
+
431
+ // Get all comments after the import/export that are on the same line.
432
+ // Multiline block comments belong to the _next_ import/export (or the
433
+ // following code in case of the last import/export).
434
+ const commentsAfter = sourceCode
435
+ .getCommentsAfter(node)
436
+ .filter((comment) => comment.loc.end.line === node.loc.end.line);
437
+
438
+ const before = printCommentsBefore(node, commentsBefore, sourceCode);
439
+ const after = printCommentsAfter(node, commentsAfter, sourceCode);
440
+
441
+ // Print the indentation before the import/export or its first comment, if
442
+ // any, to support indentation in `<script>` tags.
443
+ const indentation = getIndentation(
444
+ commentsBefore.length > 0 ? commentsBefore[0] : node,
445
+ sourceCode,
446
+ );
447
+
448
+ // Print spaces after the import/export or its last comment, if any, to
449
+ // avoid producing a sort error just because you accidentally added a few
450
+ // trailing spaces among the imports/exports.
451
+ const trailingSpaces = getTrailingSpaces(
452
+ commentsAfter.length > 0 ? commentsAfter[commentsAfter.length - 1] : node,
453
+ sourceCode,
454
+ );
455
+
456
+ const code =
457
+ indentation +
458
+ before +
459
+ printWithSortedSpecifiers(node, sourceCode, getSpecifiers) +
460
+ after +
461
+ trailingSpaces;
462
+
463
+ const all = [...commentsBefore, node, ...commentsAfter];
464
+ const [start] = all[0].range;
465
+ const [, end] = all[all.length - 1].range;
466
+
467
+ const source = getSource(node);
468
+
469
+ return {
470
+ node,
471
+ code,
472
+ start: start - indentation.length,
473
+ end: end + trailingSpaces.length,
474
+ isSideEffectImport: isSideEffectImport(node, sourceCode),
475
+ source,
476
+ index: nodeIndex,
477
+ needsNewline:
478
+ commentsAfter.length > 0 &&
479
+ isLineComment(commentsAfter[commentsAfter.length - 1]),
480
+ };
481
+ });
482
482
  }
483
483
 
484
484
  // Parsers think that a semicolon after a statement belongs to that statement.
@@ -493,141 +493,141 @@ function getImportExportItems(
493
493
  //
494
494
  // In the above example, the import is adjusted to end after `"x"`.
495
495
  function handleLastSemicolon(chunk, sourceCode) {
496
- const lastIndex = chunk.length - 1;
497
- const lastNode = chunk[lastIndex];
498
- const [nextToLastToken, lastToken] = sourceCode.getLastTokens(lastNode, {
499
- count: 2,
500
- });
501
- const lastIsSemicolon = isPunctuator(lastToken, ";");
502
-
503
- if (!lastIsSemicolon) {
504
- return chunk;
505
- }
506
-
507
- const semicolonBelongsToNode =
508
- nextToLastToken.loc.end.line === lastToken.loc.start.line ||
509
- // If there’s no more code after the last import/export the semicolon has to
510
- // belong to the import/export, even if it is not on the same line.
511
- sourceCode.getTokenAfter(lastToken) == null;
512
-
513
- if (semicolonBelongsToNode) {
514
- return chunk;
515
- }
516
-
517
- // Preserve the start position, but use the end position of the `from` string.
518
- const newLastNode = {
519
- ...lastNode,
520
- range: [lastNode.range[0], nextToLastToken.range[1]],
521
- loc: {
522
- start: lastNode.loc.start,
523
- end: nextToLastToken.loc.end,
524
- },
525
- };
526
-
527
- return [...chunk.slice(0, lastIndex), newLastNode];
496
+ const lastIndex = chunk.length - 1;
497
+ const lastNode = chunk[lastIndex];
498
+ const [nextToLastToken, lastToken] = sourceCode.getLastTokens(lastNode, {
499
+ count: 2,
500
+ });
501
+ const lastIsSemicolon = isPunctuator(lastToken, ";");
502
+
503
+ if (!lastIsSemicolon) {
504
+ return chunk;
505
+ }
506
+
507
+ const semicolonBelongsToNode =
508
+ nextToLastToken.loc.end.line === lastToken.loc.start.line ||
509
+ // If there’s no more code after the last import/export the semicolon has to
510
+ // belong to the import/export, even if it is not on the same line.
511
+ sourceCode.getTokenAfter(lastToken) == null;
512
+
513
+ if (semicolonBelongsToNode) {
514
+ return chunk;
515
+ }
516
+
517
+ // Preserve the start position, but use the end position of the `from` string.
518
+ const newLastNode = {
519
+ ...lastNode,
520
+ range: [lastNode.range[0], nextToLastToken.range[1]],
521
+ loc: {
522
+ start: lastNode.loc.start,
523
+ end: nextToLastToken.loc.end,
524
+ },
525
+ };
526
+
527
+ return [...chunk.slice(0, lastIndex), newLastNode];
528
528
  }
529
529
 
530
530
  function printWithSortedSpecifiers(node, sourceCode, getSpecifiers) {
531
- const allTokens = getAllTokens(node, sourceCode);
532
- const openBraceIndex = allTokens.findIndex((token) =>
533
- isPunctuator(token, "{"),
534
- );
535
- const closeBraceIndex = allTokens.findIndex((token) =>
536
- isPunctuator(token, "}"),
537
- );
538
-
539
- const specifiers = getSpecifiers(node);
540
-
541
- if (
542
- openBraceIndex === -1 ||
543
- closeBraceIndex === -1 ||
544
- specifiers.length <= 1
545
- ) {
546
- return printTokens(allTokens);
547
- }
548
-
549
- const specifierTokens = allTokens.slice(openBraceIndex + 1, closeBraceIndex);
550
- const itemsResult = getSpecifierItems(specifierTokens, sourceCode);
551
-
552
- const items = itemsResult.items.map((originalItem, index) => ({
553
- ...originalItem,
554
- node: specifiers[index],
555
- }));
556
-
557
- const sortedItems = sortSpecifierItems(items);
558
-
559
- const newline = guessNewline(sourceCode);
560
-
561
- // `allTokens[closeBraceIndex - 1]` wouldn’t work because `allTokens` contains
562
- // comments and whitespace.
563
- const hasTrailingComma = isPunctuator(
564
- sourceCode.getTokenBefore(allTokens[closeBraceIndex]),
565
- ",",
566
- );
567
-
568
- const lastIndex = sortedItems.length - 1;
569
- const sorted = flatMap(sortedItems, (item, index) => {
570
- const previous = index === 0 ? undefined : sortedItems[index - 1];
571
-
572
- // Add a newline if the item needs one, unless the previous item (if any)
573
- // already ends with a newline.
574
- const maybeNewline =
575
- previous != null &&
576
- needsStartingNewline(item.before) &&
577
- (previous.after.length <= 0 ||
578
- !isNewline(previous.after[previous.after.length - 1]))
579
- ? [{ type: "Newline", code: newline }]
580
- : [];
581
-
582
- if (index < lastIndex || hasTrailingComma) {
583
- return [
584
- ...maybeNewline,
585
- ...item.before,
586
- ...item.specifier,
587
- { type: "Comma", code: "," },
588
- ...item.after,
589
- ];
590
- }
591
-
592
- const nonBlankIndex = item.after.findIndex(
593
- (token) => !isNewline(token) && !isSpaces(token),
594
- );
595
-
596
- // Remove whitespace and newlines at the start of `.after` if the item had a
597
- // comma before, but now hasn’t to avoid blank lines and excessive
598
- // whitespace before `}`.
599
- const after = item.hadComma
600
- ? nonBlankIndex === -1
601
- ? []
602
- : item.after.slice(nonBlankIndex)
603
- : item.after;
604
-
605
- return [...maybeNewline, ...item.before, ...item.specifier, ...after];
606
- });
607
-
608
- const maybeNewline =
609
- needsStartingNewline(itemsResult.after) &&
610
- !isNewline(sorted[sorted.length - 1])
611
- ? [{ type: "Newline", code: newline }]
612
- : [];
613
-
614
- return printTokens([
615
- ...allTokens.slice(0, openBraceIndex + 1),
616
- ...itemsResult.before,
617
- ...sorted,
618
- ...maybeNewline,
619
- ...itemsResult.after,
620
- ...allTokens.slice(closeBraceIndex),
621
- ]);
531
+ const allTokens = getAllTokens(node, sourceCode);
532
+ const openBraceIndex = allTokens.findIndex((token) =>
533
+ isPunctuator(token, "{"),
534
+ );
535
+ const closeBraceIndex = allTokens.findIndex((token) =>
536
+ isPunctuator(token, "}"),
537
+ );
538
+
539
+ const specifiers = getSpecifiers(node);
540
+
541
+ if (
542
+ openBraceIndex === -1 ||
543
+ closeBraceIndex === -1 ||
544
+ specifiers.length <= 1
545
+ ) {
546
+ return printTokens(allTokens);
547
+ }
548
+
549
+ const specifierTokens = allTokens.slice(openBraceIndex + 1, closeBraceIndex);
550
+ const itemsResult = getSpecifierItems(specifierTokens, sourceCode);
551
+
552
+ const items = itemsResult.items.map((originalItem, index) => ({
553
+ ...originalItem,
554
+ node: specifiers[index],
555
+ }));
556
+
557
+ const sortedItems = sortSpecifierItems(items);
558
+
559
+ const newline = guessNewline(sourceCode);
560
+
561
+ // `allTokens[closeBraceIndex - 1]` wouldn’t work because `allTokens` contains
562
+ // comments and whitespace.
563
+ const hasTrailingComma = isPunctuator(
564
+ sourceCode.getTokenBefore(allTokens[closeBraceIndex]),
565
+ ",",
566
+ );
567
+
568
+ const lastIndex = sortedItems.length - 1;
569
+ const sorted = flatMap(sortedItems, (item, index) => {
570
+ const previous = index === 0 ? undefined : sortedItems[index - 1];
571
+
572
+ // Add a newline if the item needs one, unless the previous item (if any)
573
+ // already ends with a newline.
574
+ const maybeNewline =
575
+ previous != null &&
576
+ needsStartingNewline(item.before) &&
577
+ (previous.after.length <= 0 ||
578
+ !isNewline(previous.after[previous.after.length - 1]))
579
+ ? [{ type: "Newline", code: newline }]
580
+ : [];
581
+
582
+ if (index < lastIndex || hasTrailingComma) {
583
+ return [
584
+ ...maybeNewline,
585
+ ...item.before,
586
+ ...item.specifier,
587
+ { type: "Comma", code: "," },
588
+ ...item.after,
589
+ ];
590
+ }
591
+
592
+ const nonBlankIndex = item.after.findIndex(
593
+ (token) => !isNewline(token) && !isSpaces(token),
594
+ );
595
+
596
+ // Remove whitespace and newlines at the start of `.after` if the item had a
597
+ // comma before, but now hasn’t to avoid blank lines and excessive
598
+ // whitespace before `}`.
599
+ const after = item.hadComma
600
+ ? nonBlankIndex === -1
601
+ ? []
602
+ : item.after.slice(nonBlankIndex)
603
+ : item.after;
604
+
605
+ return [...maybeNewline, ...item.before, ...item.specifier, ...after];
606
+ });
607
+
608
+ const maybeNewline =
609
+ needsStartingNewline(itemsResult.after) &&
610
+ !isNewline(sorted[sorted.length - 1])
611
+ ? [{ type: "Newline", code: newline }]
612
+ : [];
613
+
614
+ return printTokens([
615
+ ...allTokens.slice(0, openBraceIndex + 1),
616
+ ...itemsResult.before,
617
+ ...sorted,
618
+ ...maybeNewline,
619
+ ...itemsResult.after,
620
+ ...allTokens.slice(closeBraceIndex),
621
+ ]);
622
622
  }
623
623
 
624
624
  const makeEmptyItem = () => ({
625
- // "before" | "specifier" | "after"
626
- state: "before",
627
- before: [],
628
- after: [],
629
- specifier: [],
630
- hadComma: false,
625
+ // "before" | "specifier" | "after"
626
+ state: "before",
627
+ before: [],
628
+ after: [],
629
+ specifier: [],
630
+ hadComma: false,
631
631
  });
632
632
 
633
633
  // Turns a list of tokens between the `{` and `}` of an import/export specifiers
@@ -650,234 +650,234 @@ const makeEmptyItem = () => ({
650
650
  // We have to do carefully preserve all original whitespace this way in order to
651
651
  // be compatible with other stylistic ESLint rules.
652
652
  function getSpecifierItems(tokens) {
653
- const result = {
654
- before: [],
655
- after: [],
656
- items: [],
657
- };
658
-
659
- let current = makeEmptyItem();
660
-
661
- for (const token of tokens) {
662
- switch (current.state) {
663
- case "before": {
664
- switch (token.type) {
665
- case "Newline": {
666
- current.before.push(token);
667
-
668
- // All whitespace and comments before the first newline or
669
- // identifier belong to the `{`, not the first specifier.
670
- if (result.before.length === 0 && result.items.length === 0) {
671
- result.before = current.before;
672
- current = makeEmptyItem();
673
- }
674
- break;
675
- }
676
-
677
- case "Spaces":
678
- case "Block":
679
- case "Line": {
680
- current.before.push(token);
681
- break;
682
- }
683
-
684
- // We’ve reached an identifier.
685
- default: {
686
- // All whitespace and comments before the first newline or
687
- // identifier belong to the `{`, not the first specifier.
688
- if (result.before.length === 0 && result.items.length === 0) {
689
- result.before = current.before;
690
- current = makeEmptyItem();
691
- }
692
-
693
- current.state = "specifier";
694
- current.specifier.push(token);
695
- }
696
- }
697
- break;
698
- }
699
-
700
- case "specifier": {
701
- switch (token.type) {
702
- case "Punctuator": {
703
- // There can only be comma punctuators, but future-proof by checking.
704
- // istanbul ignore else
705
- if (isPunctuator(token, ",")) {
706
- current.hadComma = true;
707
- current.state = "after";
708
- } else {
709
- current.specifier.push(token);
710
- }
711
- break;
712
- }
713
-
714
- // When consuming the specifier part, we eat every token until a comma
715
- // or to the end, basically.
716
- default: {
717
- current.specifier.push(token);
718
- }
719
- }
720
- break;
721
- }
722
-
723
- case "after": {
724
- switch (token.type) {
725
- // Only whitespace and comments after a specifier that are on the same
726
- // belong to the specifier.
727
- case "Newline": {
728
- current.after.push(token);
729
- result.items.push(current);
730
- current = makeEmptyItem();
731
- break;
732
- }
733
-
734
- case "Spaces":
735
- case "Line": {
736
- current.after.push(token);
737
- break;
738
- }
739
-
740
- case "Block": {
741
- // Multiline block comments belong to the next specifier.
742
- if (hasNewline(token.code)) {
743
- result.items.push(current);
744
- current = makeEmptyItem();
745
- current.before.push(token);
746
- } else {
747
- current.after.push(token);
748
- }
749
- break;
750
- }
751
-
752
- // We’ve reached another specifier – time to process that one.
753
- default: {
754
- result.items.push(current);
755
- current = makeEmptyItem();
756
- current.state = "specifier";
757
- current.specifier.push(token);
758
- }
759
- }
760
- break;
761
- }
762
-
763
- // istanbul ignore next
764
- default: {
765
- throw new Error(`Unknown state: ${current.state}`);
766
- }
767
- }
768
- }
769
-
770
- // We’ve reached the end of the tokens. Handle what’s currently in `current`.
771
- switch (current.state) {
772
- // If the last specifier has a trailing comma and some of the remaining
773
- // whitespace and comments are on the same line we end up here. If so we
774
- // want to put that whitespace and comments in `result.after`.
775
- case "before": {
776
- result.after = current.before;
777
- break;
778
- }
779
-
780
- // If the last specifier has no trailing comma we end up here. Move all
781
- // trailing comments and whitespace from `.specifier` to `.after`, and
782
- // comments and whitespace that don’t belong to the specifier to
783
- // `result.after`. The last non-comment and non-whitespace token is usually
784
- // an identifier, but in this case it’s a keyword:
785
- //
786
- // export { z, d as default } from "a"
787
- case "specifier": {
788
- const lastIdentifierIndex = findLastIndex(
789
- current.specifier,
790
- (token2) => isIdentifier(token2) || isKeyword(token2),
791
- );
792
-
793
- const specifier = current.specifier.slice(0, lastIdentifierIndex + 1);
794
- const after = current.specifier.slice(lastIdentifierIndex + 1);
795
-
796
- // If there’s a newline, put everything up to and including (hence the `+
797
- // 1`) that newline in the specifiers’s `.after`.
798
- const newlineIndexRaw = after.findIndex((token2) => isNewline(token2));
799
- const newlineIndex = newlineIndexRaw === -1 ? -1 : newlineIndexRaw + 1;
800
-
801
- // If there’s a multiline block comment, put everything _befor_ that
802
- // comment in the specifiers’s `.after`.
803
- const multilineBlockCommentIndex = after.findIndex(
804
- (token2) => isBlockComment(token2) && hasNewline(token2.code),
805
- );
806
-
807
- const sliceIndex =
808
- // If both a newline and a multiline block comment exists, choose the
809
- // earlier one.
810
- newlineIndex >= 0 && multilineBlockCommentIndex !== -1
811
- ? Math.min(newlineIndex, multilineBlockCommentIndex)
812
- : newlineIndex >= 0
813
- ? newlineIndex
814
- : multilineBlockCommentIndex === -1
815
- ? endsWithSpaces(after)
816
- ? after.length - 1
817
- : -1
818
- : // If there are no newlines, move the last whitespace into `result.after`.
819
- multilineBlockCommentIndex;
820
-
821
- current.specifier = specifier;
822
- current.after = sliceIndex === -1 ? after : after.slice(0, sliceIndex);
823
- result.items.push(current);
824
- result.after = sliceIndex === -1 ? [] : after.slice(sliceIndex);
825
-
826
- break;
827
- }
828
-
829
- // If the last specifier has a trailing comma and all remaining whitespace
830
- // and comments are on the same line we end up here. If so we want to move
831
- // the final whitespace to `result.after`.
832
- case "after": {
833
- if (endsWithSpaces(current.after)) {
834
- const last = current.after.pop();
835
- result.after = [last];
836
- }
837
- result.items.push(current);
838
- break;
839
- }
840
-
841
- // istanbul ignore next
842
- default: {
843
- throw new Error(`Unknown state: ${current.state}`);
844
- }
845
- }
846
-
847
- return result;
653
+ const result = {
654
+ before: [],
655
+ after: [],
656
+ items: [],
657
+ };
658
+
659
+ let current = makeEmptyItem();
660
+
661
+ for (const token of tokens) {
662
+ switch (current.state) {
663
+ case "before": {
664
+ switch (token.type) {
665
+ case "Newline": {
666
+ current.before.push(token);
667
+
668
+ // All whitespace and comments before the first newline or
669
+ // identifier belong to the `{`, not the first specifier.
670
+ if (result.before.length === 0 && result.items.length === 0) {
671
+ result.before = current.before;
672
+ current = makeEmptyItem();
673
+ }
674
+ break;
675
+ }
676
+
677
+ case "Spaces":
678
+ case "Block":
679
+ case "Line": {
680
+ current.before.push(token);
681
+ break;
682
+ }
683
+
684
+ // We’ve reached an identifier.
685
+ default: {
686
+ // All whitespace and comments before the first newline or
687
+ // identifier belong to the `{`, not the first specifier.
688
+ if (result.before.length === 0 && result.items.length === 0) {
689
+ result.before = current.before;
690
+ current = makeEmptyItem();
691
+ }
692
+
693
+ current.state = "specifier";
694
+ current.specifier.push(token);
695
+ }
696
+ }
697
+ break;
698
+ }
699
+
700
+ case "specifier": {
701
+ switch (token.type) {
702
+ case "Punctuator": {
703
+ // There can only be comma punctuators, but future-proof by checking.
704
+ // istanbul ignore else
705
+ if (isPunctuator(token, ",")) {
706
+ current.hadComma = true;
707
+ current.state = "after";
708
+ } else {
709
+ current.specifier.push(token);
710
+ }
711
+ break;
712
+ }
713
+
714
+ // When consuming the specifier part, we eat every token until a comma
715
+ // or to the end, basically.
716
+ default: {
717
+ current.specifier.push(token);
718
+ }
719
+ }
720
+ break;
721
+ }
722
+
723
+ case "after": {
724
+ switch (token.type) {
725
+ // Only whitespace and comments after a specifier that are on the same
726
+ // belong to the specifier.
727
+ case "Newline": {
728
+ current.after.push(token);
729
+ result.items.push(current);
730
+ current = makeEmptyItem();
731
+ break;
732
+ }
733
+
734
+ case "Spaces":
735
+ case "Line": {
736
+ current.after.push(token);
737
+ break;
738
+ }
739
+
740
+ case "Block": {
741
+ // Multiline block comments belong to the next specifier.
742
+ if (hasNewline(token.code)) {
743
+ result.items.push(current);
744
+ current = makeEmptyItem();
745
+ current.before.push(token);
746
+ } else {
747
+ current.after.push(token);
748
+ }
749
+ break;
750
+ }
751
+
752
+ // We’ve reached another specifier – time to process that one.
753
+ default: {
754
+ result.items.push(current);
755
+ current = makeEmptyItem();
756
+ current.state = "specifier";
757
+ current.specifier.push(token);
758
+ }
759
+ }
760
+ break;
761
+ }
762
+
763
+ // istanbul ignore next
764
+ default: {
765
+ throw new Error(`Unknown state: ${current.state}`);
766
+ }
767
+ }
768
+ }
769
+
770
+ // We’ve reached the end of the tokens. Handle what’s currently in `current`.
771
+ switch (current.state) {
772
+ // If the last specifier has a trailing comma and some of the remaining
773
+ // whitespace and comments are on the same line we end up here. If so we
774
+ // want to put that whitespace and comments in `result.after`.
775
+ case "before": {
776
+ result.after = current.before;
777
+ break;
778
+ }
779
+
780
+ // If the last specifier has no trailing comma we end up here. Move all
781
+ // trailing comments and whitespace from `.specifier` to `.after`, and
782
+ // comments and whitespace that don’t belong to the specifier to
783
+ // `result.after`. The last non-comment and non-whitespace token is usually
784
+ // an identifier, but in this case it’s a keyword:
785
+ //
786
+ // export { z, d as default } from "a"
787
+ case "specifier": {
788
+ const lastIdentifierIndex = findLastIndex(
789
+ current.specifier,
790
+ (token2) => isIdentifier(token2) || isKeyword(token2),
791
+ );
792
+
793
+ const specifier = current.specifier.slice(0, lastIdentifierIndex + 1);
794
+ const after = current.specifier.slice(lastIdentifierIndex + 1);
795
+
796
+ // If there’s a newline, put everything up to and including (hence the `+
797
+ // 1`) that newline in the specifiers’s `.after`.
798
+ const newlineIndexRaw = after.findIndex((token2) => isNewline(token2));
799
+ const newlineIndex = newlineIndexRaw === -1 ? -1 : newlineIndexRaw + 1;
800
+
801
+ // If there’s a multiline block comment, put everything _befor_ that
802
+ // comment in the specifiers’s `.after`.
803
+ const multilineBlockCommentIndex = after.findIndex(
804
+ (token2) => isBlockComment(token2) && hasNewline(token2.code),
805
+ );
806
+
807
+ const sliceIndex =
808
+ // If both a newline and a multiline block comment exists, choose the
809
+ // earlier one.
810
+ newlineIndex >= 0 && multilineBlockCommentIndex !== -1
811
+ ? Math.min(newlineIndex, multilineBlockCommentIndex)
812
+ : newlineIndex >= 0
813
+ ? newlineIndex
814
+ : multilineBlockCommentIndex === -1
815
+ ? endsWithSpaces(after)
816
+ ? after.length - 1
817
+ : -1
818
+ : // If there are no newlines, move the last whitespace into `result.after`.
819
+ multilineBlockCommentIndex;
820
+
821
+ current.specifier = specifier;
822
+ current.after = sliceIndex === -1 ? after : after.slice(0, sliceIndex);
823
+ result.items.push(current);
824
+ result.after = sliceIndex === -1 ? [] : after.slice(sliceIndex);
825
+
826
+ break;
827
+ }
828
+
829
+ // If the last specifier has a trailing comma and all remaining whitespace
830
+ // and comments are on the same line we end up here. If so we want to move
831
+ // the final whitespace to `result.after`.
832
+ case "after": {
833
+ if (endsWithSpaces(current.after)) {
834
+ const last = current.after.pop();
835
+ result.after = [last];
836
+ }
837
+ result.items.push(current);
838
+ break;
839
+ }
840
+
841
+ // istanbul ignore next
842
+ default: {
843
+ throw new Error(`Unknown state: ${current.state}`);
844
+ }
845
+ }
846
+
847
+ return result;
848
848
  }
849
849
 
850
850
  // If a specifier item starts with a line comment or a singleline block comment
851
851
  // it needs a newline before that. Otherwise that comment can end up belonging
852
852
  // to the _previous_ specifier after sorting.
853
853
  function needsStartingNewline(tokens) {
854
- const before = tokens.filter((token) => !isSpaces(token));
854
+ const before = tokens.filter((token) => !isSpaces(token));
855
855
 
856
- if (before.length === 0) {
857
- return false;
858
- }
856
+ if (before.length === 0) {
857
+ return false;
858
+ }
859
859
 
860
- const firstToken = before[0];
860
+ const firstToken = before[0];
861
861
 
862
- return (
863
- isLineComment(firstToken) ||
864
- (isBlockComment(firstToken) && !hasNewline(firstToken.code))
865
- );
862
+ return (
863
+ isLineComment(firstToken) ||
864
+ (isBlockComment(firstToken) && !hasNewline(firstToken.code))
865
+ );
866
866
  }
867
867
 
868
868
  function endsWithSpaces(tokens) {
869
- const last = tokens.length > 0 ? tokens[tokens.length - 1] : undefined;
869
+ const last = tokens.length > 0 ? tokens[tokens.length - 1] : undefined;
870
870
 
871
- return last == null ? false : isSpaces(last);
871
+ return last == null ? false : isSpaces(last);
872
872
  }
873
873
 
874
874
  module.exports = {
875
- extractChunks,
876
- flatMap,
877
- getImportExportItems,
878
- isPunctuator,
879
- maybeReportSorting,
880
- printSortedItems,
881
- printWithSortedSpecifiers,
882
- sortImportExportItems,
875
+ extractChunks,
876
+ flatMap,
877
+ getImportExportItems,
878
+ isPunctuator,
879
+ maybeReportSorting,
880
+ printSortedItems,
881
+ printWithSortedSpecifiers,
882
+ sortImportExportItems,
883
883
  };