1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
|
"use strict";
/**
* @license
* Copyright 2016 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var tsutils_1 = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var Rule = (function (_super) {
tslib_1.__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new Walker(sourceFile, this.ruleName, parseOptions(this.ruleArguments)));
};
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "ordered-imports",
description: "Requires that import statements be alphabetized.",
descriptionDetails: (_a = ["\n Enforce a consistent ordering for ES6 imports:\n - Named imports must be alphabetized (i.e. \"import {A, B, C} from \"foo\";\")\n - The exact ordering can be controlled by the named-imports-order option.\n - \"longName as name\" imports are ordered by \"longName\".\n - Import sources must be alphabetized within groups, i.e.:\n import * as foo from \"a\";\n import * as bar from \"b\";\n - Groups of imports are delineated by blank lines. You can use these to group imports\n however you like, e.g. by first- vs. third-party or thematically."], _a.raw = ["\n Enforce a consistent ordering for ES6 imports:\n - Named imports must be alphabetized (i.e. \"import {A, B, C} from \"foo\";\")\n - The exact ordering can be controlled by the named-imports-order option.\n - \"longName as name\" imports are ordered by \"longName\".\n - Import sources must be alphabetized within groups, i.e.:\n import * as foo from \"a\";\n import * as bar from \"b\";\n - Groups of imports are delineated by blank lines. You can use these to group imports\n however you like, e.g. by first- vs. third-party or thematically."], Lint.Utils.dedent(_a)),
hasFix: true,
optionsDescription: (_b = ["\n You may set the `\"import-sources-order\"` option to control the ordering of source\n imports (the `\"foo\"` in `import {A, B, C} from \"foo\"`).\n\n Possible values for `\"import-sources-order\"` are:\n\n * `\"case-insensitive'`: Correct order is `\"Bar\"`, `\"baz\"`, `\"Foo\"`. (This is the default.)\n * `\"lowercase-first\"`: Correct order is `\"baz\"`, `\"Bar\"`, `\"Foo\"`.\n * `\"lowercase-last\"`: Correct order is `\"Bar\"`, `\"Foo\"`, `\"baz\"`.\n * `\"any\"`: Allow any order.\n\n You may set the `\"named-imports-order\"` option to control the ordering of named\n imports (the `{A, B, C}` in `import {A, B, C} from \"foo\"`).\n\n Possible values for `\"named-imports-order\"` are:\n\n * `\"case-insensitive'`: Correct order is `{A, b, C}`. (This is the default.)\n * `\"lowercase-first\"`: Correct order is `{b, A, C}`.\n * `\"lowercase-last\"`: Correct order is `{A, C, b}`.\n * `\"any\"`: Allow any order.\n\n "], _b.raw = ["\n You may set the \\`\"import-sources-order\"\\` option to control the ordering of source\n imports (the \\`\"foo\"\\` in \\`import {A, B, C} from \"foo\"\\`).\n\n Possible values for \\`\"import-sources-order\"\\` are:\n\n * \\`\"case-insensitive'\\`: Correct order is \\`\"Bar\"\\`, \\`\"baz\"\\`, \\`\"Foo\"\\`. (This is the default.)\n * \\`\"lowercase-first\"\\`: Correct order is \\`\"baz\"\\`, \\`\"Bar\"\\`, \\`\"Foo\"\\`.\n * \\`\"lowercase-last\"\\`: Correct order is \\`\"Bar\"\\`, \\`\"Foo\"\\`, \\`\"baz\"\\`.\n * \\`\"any\"\\`: Allow any order.\n\n You may set the \\`\"named-imports-order\"\\` option to control the ordering of named\n imports (the \\`{A, B, C}\\` in \\`import {A, B, C} from \"foo\"\\`).\n\n Possible values for \\`\"named-imports-order\"\\` are:\n\n * \\`\"case-insensitive'\\`: Correct order is \\`{A, b, C}\\`. (This is the default.)\n * \\`\"lowercase-first\"\\`: Correct order is \\`{b, A, C}\\`.\n * \\`\"lowercase-last\"\\`: Correct order is \\`{A, C, b}\\`.\n * \\`\"any\"\\`: Allow any order.\n\n "], Lint.Utils.dedent(_b)),
options: {
type: "object",
properties: {
"import-sources-order": {
type: "string",
enum: ["case-insensitive", "lowercase-first", "lowercase-last", "any"],
},
"named-imports-order": {
type: "string",
enum: ["case-insensitive", "lowercase-first", "lowercase-last", "any"],
},
},
additionalProperties: false,
},
optionExamples: [
true,
[true, { "import-sources-order": "lowercase-last", "named-imports-order": "lowercase-first" }],
],
type: "style",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */
Rule.IMPORT_SOURCES_UNORDERED = "Import sources within a group must be alphabetized.";
Rule.NAMED_IMPORTS_UNORDERED = "Named imports must be alphabetized.";
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var TRANSFORMS = new Map([
["any", function () { return ""; }],
["case-insensitive", function (x) { return x.toLowerCase(); }],
["lowercase-first", flipCase],
["lowercase-last", function (x) { return x; }],
]);
function parseOptions(ruleArguments) {
var optionSet = ruleArguments[0];
var _a = optionSet === undefined ? {} : optionSet, _b = _a["import-sources-order"], sources = _b === void 0 ? "case-insensitive" : _b, _c = _a["named-imports-order"], named = _c === void 0 ? "case-insensitive" : _c;
return {
importSourcesOrderTransform: TRANSFORMS.get(sources),
namedImportsOrderTransform: TRANSFORMS.get(named),
};
}
var Walker = (function (_super) {
tslib_1.__extends(Walker, _super);
function Walker() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.currentImportsBlock = new ImportsBlock();
return _this;
}
Walker.prototype.walk = function (sourceFile) {
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
this.checkStatement(statement);
}
this.endBlock();
};
Walker.prototype.checkStatement = function (statement) {
if (!(tsutils_1.isImportDeclaration(statement) || tsutils_1.isImportEqualsDeclaration(statement)) ||
/\r?\n\r?\n/.test(this.sourceFile.text.slice(statement.getFullStart(), statement.getStart(this.sourceFile)))) {
this.endBlock();
}
if (tsutils_1.isImportDeclaration(statement)) {
this.checkImportDeclaration(statement);
}
else if (tsutils_1.isImportEqualsDeclaration(statement)) {
this.checkImportEqualsDeclaration(statement);
}
else if (tsutils_1.isModuleDeclaration(statement)) {
var body = moduleDeclarationBody(statement);
if (body !== undefined) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var subStatement = _a[_i];
this.checkStatement(subStatement);
}
this.endBlock();
}
}
};
Walker.prototype.checkImportDeclaration = function (node) {
if (!tsutils_1.isStringLiteral(node.moduleSpecifier)) {
// Ignore grammar error
return;
}
var source = this.options.importSourcesOrderTransform(removeQuotes(node.moduleSpecifier.text));
this.checkSource(source, node);
var importClause = node.importClause;
if (importClause !== undefined && importClause.namedBindings !== undefined && tsutils_1.isNamedImports(importClause.namedBindings)) {
this.checkNamedImports(importClause.namedBindings);
}
};
Walker.prototype.checkImportEqualsDeclaration = function (node) {
// only allowed `import x = require('y');`
var moduleReference = node.moduleReference;
if (!tsutils_1.isExternalModuleReference(moduleReference)) {
return;
}
var expression = moduleReference.expression;
if (expression === undefined || !tsutils_1.isStringLiteral(expression)) {
return;
}
var source = this.options.importSourcesOrderTransform(removeQuotes(expression.text));
this.checkSource(source, node);
};
Walker.prototype.checkSource = function (source, node) {
var previousSource = this.currentImportsBlock.getLastImportSource();
this.currentImportsBlock.addImportDeclaration(this.sourceFile, node, source);
if (previousSource !== null && compare(source, previousSource) === -1) {
this.lastFix = [];
this.addFailureAtNode(node, Rule.IMPORT_SOURCES_UNORDERED, this.lastFix);
}
};
Walker.prototype.endBlock = function () {
if (this.lastFix !== undefined) {
var replacement = this.currentImportsBlock.getReplacement();
if (replacement !== undefined) {
this.lastFix.push(replacement);
}
this.lastFix = undefined;
}
this.currentImportsBlock = new ImportsBlock();
};
Walker.prototype.checkNamedImports = function (node) {
var _this = this;
var imports = node.elements;
var pair = findUnsortedPair(imports, this.options.namedImportsOrderTransform);
if (pair !== undefined) {
var a = pair[0], b = pair[1];
var sortedDeclarations = sortByKey(imports, function (x) {
return _this.options.namedImportsOrderTransform(x.getText());
}).map(function (x) { return x.getText(); });
// replace in reverse order to preserve earlier offsets
for (var i = imports.length - 1; i >= 0; i--) {
var start = imports[i].getStart();
var length = imports[i].getText().length;
// replace the named imports one at a time to preserve whitespace
this.currentImportsBlock.replaceNamedImports(start, length, sortedDeclarations[i]);
}
this.lastFix = [];
this.addFailure(a.getStart(), b.getEnd(), Rule.NAMED_IMPORTS_UNORDERED, this.lastFix);
}
};
return Walker;
}(Lint.AbstractWalker));
var ImportsBlock = (function () {
function ImportsBlock() {
this.importDeclarations = [];
}
ImportsBlock.prototype.addImportDeclaration = function (sourceFile, node, sourcePath) {
var start = this.getStartOffset(node);
var end = this.getEndOffset(sourceFile, node);
var text = sourceFile.text.substring(start, end);
if (start > node.getStart() || end === 0) {
// skip block if any statements don't end with a newline to simplify implementation
this.importDeclarations = [];
return;
}
this.importDeclarations.push({
node: node,
nodeEndOffset: end,
nodeStartOffset: start,
sourcePath: sourcePath,
text: text,
});
};
// replaces the named imports on the most recent import declaration
ImportsBlock.prototype.replaceNamedImports = function (fileOffset, length, replacement) {
var importDeclaration = this.getLastImportDeclaration();
if (importDeclaration == null) {
// nothing to replace. This can happen if the block is skipped
return;
}
var start = fileOffset - importDeclaration.nodeStartOffset;
if (start < 0 || start + length > importDeclaration.node.getEnd()) {
throw new Error("Unexpected named import position");
}
var initialText = importDeclaration.text;
importDeclaration.text = initialText.substring(0, start) + replacement + initialText.substring(start + length);
};
ImportsBlock.prototype.getLastImportSource = function () {
if (this.importDeclarations.length === 0) {
return null;
}
return this.getLastImportDeclaration().sourcePath;
};
// creates a Lint.Replacement object with ordering fixes for the entire block
ImportsBlock.prototype.getReplacement = function () {
if (this.importDeclarations.length === 0) {
return undefined;
}
var sortedDeclarations = sortByKey(this.importDeclarations.slice(), function (x) { return x.sourcePath; });
var fixedText = sortedDeclarations.map(function (x) { return x.text; }).join("");
var start = this.importDeclarations[0].nodeStartOffset;
var end = this.getLastImportDeclaration().nodeEndOffset;
return new Lint.Replacement(start, end - start, fixedText);
};
// gets the offset immediately after the end of the previous declaration to include comment above
ImportsBlock.prototype.getStartOffset = function (node) {
if (this.importDeclarations.length === 0) {
return node.getStart();
}
return this.getLastImportDeclaration().nodeEndOffset;
};
// gets the offset of the end of the import's line, including newline, to include comment to the right
ImportsBlock.prototype.getEndOffset = function (sourceFile, node) {
return sourceFile.text.indexOf("\n", node.end) + 1;
};
ImportsBlock.prototype.getLastImportDeclaration = function () {
return this.importDeclarations[this.importDeclarations.length - 1];
};
return ImportsBlock;
}());
// Convert aBcD --> AbCd
function flipCase(str) {
return Array.from(str).map(function (char) {
if (char >= "a" && char <= "z") {
return char.toUpperCase();
}
else if (char >= "A" && char <= "Z") {
return char.toLowerCase();
}
return char;
}).join("");
}
// After applying a transformation, are the nodes sorted according to the text they contain?
// If not, return the pair of nodes which are out of order.
function findUnsortedPair(xs, transform) {
for (var i = 1; i < xs.length; i++) {
if (transform(xs[i].getText()) < transform(xs[i - 1].getText())) {
return [xs[i - 1], xs[i]];
}
}
return undefined;
}
// tslint:disable-next-line no-unsafe-any (fixed in 5.3)
function compare(a, b) {
function isLow(value) {
return value[0] === "." || value[0] === "/";
}
if (isLow(a) && !isLow(b)) {
return 1;
}
else if (!isLow(a) && isLow(b)) {
return -1;
}
else if (a > b) {
return 1;
}
else if (a < b) {
return -1;
}
return 0;
}
function removeQuotes(value) {
// strip out quotes
if (value.length > 1 && (value[0] === "'" || value[0] === "\"")) {
value = value.substr(1, value.length - 2);
}
return value;
}
function sortByKey(xs, getSortKey) {
return xs.slice().sort(function (a, b) { return compare(getSortKey(a), getSortKey(b)); });
}
function moduleDeclarationBody(node) {
var body = node.body;
while (body !== undefined && body.kind === ts.SyntaxKind.ModuleDeclaration) {
body = body.body;
}
return body !== undefined && body.kind === ts.SyntaxKind.ModuleBlock ? body : undefined;
}
var _a, _b;
|