forked from dsherret/ts-morph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImportDeclaration.ts
480 lines (419 loc) · 17.3 KB
/
ImportDeclaration.ts
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import * as errors from "../../../errors";
import { getNodesToReturn, insertIntoCommaSeparatedNodes, insertIntoParentTextRange, removeChildren, verifyAndGetIndex } from "../../../manipulation";
import { ImportSpecifierStructure, ImportDeclarationStructure } from "../../../structures";
import { WriterFunction } from "../../../types";
import { SyntaxKind, ts } from "../../../typescript";
import { ArrayUtils, ModuleUtils, StringUtils, TypeGuards } from "../../../utils";
import { Node } from "../common";
import { StringLiteral } from "../literal";
import { Statement } from "../statement";
import { ImportSpecifier } from "./ImportSpecifier";
import { SourceFile } from "./SourceFile";
import { callBaseGetStructure } from "../callBaseGetStructure";
import { callBaseSet } from "../callBaseSet";
export const ImportDeclarationBase = Statement;
export class ImportDeclaration extends ImportDeclarationBase<ts.ImportDeclaration> {
/**
* Sets the import specifier.
* @param text - Text to set as the module specifier.
*/
setModuleSpecifier(text: string): this;
/**
* Sets the import specifier.
* @param sourceFile - Source file to set the module specifier from.
*/
setModuleSpecifier(sourceFile: SourceFile): this;
setModuleSpecifier(textOrSourceFile: string | SourceFile) {
const text = typeof textOrSourceFile === "string" ? textOrSourceFile : this._sourceFile.getRelativePathAsModuleSpecifierTo(textOrSourceFile);
this.getModuleSpecifier().setLiteralValue(text);
return this;
}
/**
* Gets the module specifier.
*/
getModuleSpecifier(): StringLiteral {
const moduleSpecifier = this._getNodeFromCompilerNode(this.compilerNode.moduleSpecifier);
if (!TypeGuards.isStringLiteral(moduleSpecifier))
throw new errors.InvalidOperationError("Expected the module specifier to be a string literal.");
return moduleSpecifier;
}
/**
* Gets the module specifier string literal value.
*/
getModuleSpecifierValue() {
return this.getModuleSpecifier().getLiteralValue();
}
/**
* Gets the source file referenced in the module specifier or throws if it can't find it.
*/
getModuleSpecifierSourceFileOrThrow() {
return errors.throwIfNullOrUndefined(this.getModuleSpecifierSourceFile(), `A module specifier source file was expected.`);
}
/**
* Gets the source file referenced in the module specifier or returns undefined if it can't find it.
*/
getModuleSpecifierSourceFile() {
const symbol = this.getModuleSpecifier().getSymbol();
if (symbol == null)
return undefined;
return ModuleUtils.getReferencedSourceFileFromSymbol(symbol);
}
/**
* Gets if the module specifier starts with `./` or `../`.
*/
isModuleSpecifierRelative() {
return ModuleUtils.isModuleSpecifierRelative(this.getModuleSpecifierValue());
}
/**
* Sets the default import.
* @param text - Text to set as the default import.
* @remarks Use renameDefaultImport to rename.
*/
setDefaultImport(text: string) {
if (StringUtils.isNullOrWhitespace(text))
return this.removeDefaultImport();
const defaultImport = this.getDefaultImport();
if (defaultImport != null) {
defaultImport.replaceWithText(text);
return this;
}
const importKeyword = this.getFirstChildByKindOrThrow(SyntaxKind.ImportKeyword);
const importClause = this.getImportClause();
if (importClause == null) {
insertIntoParentTextRange({
insertPos: importKeyword.getEnd(),
parent: this,
newText: ` ${text} from`
});
return this;
}
// a namespace import or named import must exist... insert it beforehand
insertIntoParentTextRange({
insertPos: importKeyword.getEnd(),
parent: importClause,
newText: ` ${text},`
});
return this;
}
/**
* Renames or sets the provided default import.
* @param text - Text to set or rename the default import with.
*/
renameDefaultImport(text: string) {
if (StringUtils.isNullOrWhitespace(text))
return this.removeDefaultImport();
const defaultImport = this.getDefaultImport();
if (defaultImport != null) {
defaultImport.rename(text);
return this;
}
this.setDefaultImport(text);
return this;
}
/**
* Gets the default import or throws if it doesn't exit.
*/
getDefaultImportOrThrow() {
return errors.throwIfNullOrUndefined(this.getDefaultImport(), "Expected to find a default import.");
}
/**
* Gets the default import or returns undefined if it doesn't exist.
*/
getDefaultImport() {
const importClause = this.getImportClause();
if (importClause == null)
return undefined;
return importClause.getDefaultImport();
}
/**
* Sets the namespace import.
* @param text - Text to set as the namespace import.
* @throws - InvalidOperationError if a named import exists.
*/
setNamespaceImport(text: string) {
if (StringUtils.isNullOrWhitespace(text))
return this.removeNamespaceImport();
const namespaceImport = this.getNamespaceImport();
if (namespaceImport != null) {
namespaceImport.rename(text);
return this;
}
if (this.getNamedImports().length > 0)
throw new errors.InvalidOperationError("Cannot add a namespace import to an import declaration that has named imports.");
const defaultImport = this.getDefaultImport();
if (defaultImport != null) {
insertIntoParentTextRange({
insertPos: defaultImport.getEnd(),
parent: this.getImportClause()!,
newText: `, * as ${text}`
});
return this;
}
insertIntoParentTextRange({
insertPos: this.getFirstChildByKindOrThrow(SyntaxKind.ImportKeyword).getEnd(),
parent: this,
newText: ` * as ${text} from`
});
return this;
}
/**
* Removes the namespace import.
*/
removeNamespaceImport() {
const namespaceImport = this.getNamespaceImport();
if (namespaceImport == null)
return this;
removeChildren({
children: getChildrenToRemove.call(this),
removePrecedingSpaces: true,
removePrecedingNewLines: true
});
return this;
function getChildrenToRemove(this: ImportDeclaration) {
const defaultImport = this.getDefaultImport();
if (defaultImport == null)
return [this.getImportClauseOrThrow(), this.getLastChildByKindOrThrow(SyntaxKind.FromKeyword)];
else
return [defaultImport.getNextSiblingIfKindOrThrow(SyntaxKind.CommaToken), namespaceImport!];
}
}
/**
* Removes the default import.
*/
removeDefaultImport() {
const importClause = this.getImportClause();
if (importClause == null)
return this;
const defaultImport = importClause.getDefaultImport();
if (defaultImport == null)
return this;
const hasOnlyDefaultImport = importClause.getChildCount() === 1;
if (hasOnlyDefaultImport)
removeChildren({
children: [importClause, importClause.getNextSiblingIfKindOrThrow(SyntaxKind.FromKeyword)],
removePrecedingSpaces: true,
removePrecedingNewLines: true
});
else
removeChildren({
children: [defaultImport, defaultImport.getNextSiblingIfKindOrThrow(SyntaxKind.CommaToken)],
removePrecedingSpaces: true,
removePrecedingNewLines: true
});
return this;
}
/**
* Gets the namespace import if it exists or throws.
*/
getNamespaceImportOrThrow() {
return errors.throwIfNullOrUndefined(this.getNamespaceImport(), "Expected to find a namespace import.");
}
/**
* Gets the namespace import identifier, if it exists.
*/
getNamespaceImport() {
const importClause = this.getImportClause();
if (importClause == null)
return undefined;
return importClause.getNamespaceImport();
}
/**
* Adds a named import.
* @param namedImport - Name, structure, or writer to write the named import with.
*/
addNamedImport(namedImport: ImportSpecifierStructure | string | WriterFunction) {
return this.addNamedImports([namedImport])[0];
}
/**
* Adds named imports.
* @param namedImport - Structures, names, or writer function to write the named import with.
*/
addNamedImports(namedImports: ReadonlyArray<ImportSpecifierStructure | string | WriterFunction> | WriterFunction) {
return this.insertNamedImports(this.getNamedImports().length, namedImports);
}
/**
* Inserts a named import.
* @param index - Child index to insert at.
* @param namedImport - Structure, name, or writer function to write the named import with.
*/
insertNamedImport(index: number, namedImport: ImportSpecifierStructure | string | WriterFunction) {
return this.insertNamedImports(index, [namedImport])[0];
}
/**
* Inserts named imports into the import declaration.
* @param index - Child index to insert at.
* @param namedImports - Structures, names, or writer function to write the named import with.
*/
insertNamedImports(index: number, namedImports: ReadonlyArray<ImportSpecifierStructure | string | WriterFunction> | WriterFunction) {
if (!(namedImports instanceof Function) && ArrayUtils.isNullOrEmpty(namedImports))
return [];
const originalNamedImports = this.getNamedImports();
const writer = this._getWriterWithQueuedIndentation();
const namedImportStructurePrinter = this._context.structurePrinterFactory.forNamedImportExportSpecifier();
const importClause = this.getImportClause();
index = verifyAndGetIndex(index, originalNamedImports.length);
if (originalNamedImports.length === 0) {
namedImportStructurePrinter.printTextsWithBraces(writer, namedImports);
if (importClause == null)
insertIntoParentTextRange({
insertPos: this.getFirstChildByKindOrThrow(SyntaxKind.ImportKeyword).getEnd(),
parent: this,
newText: ` ${writer.toString()} from`
});
else if (this.getNamespaceImport() != null)
throw getErrorWhenNamespaceImportsExist();
else if (importClause.getNamedBindings() != null) {
const namedBindings = importClause.getNamedBindingsOrThrow();
insertIntoParentTextRange({
insertPos: namedBindings.getStart(),
replacing: {
textLength: namedBindings.getWidth()
},
parent: importClause,
newText: writer.toString()
});
}
else
insertIntoParentTextRange({
insertPos: this.getDefaultImport()!.getEnd(),
parent: importClause,
newText: `, ${writer.toString()}`
});
}
else {
if (importClause == null)
throw new errors.NotImplementedError("Expected to have an import clause.");
namedImportStructurePrinter.printTexts(writer, namedImports);
insertIntoCommaSeparatedNodes({
parent: importClause.getFirstChildByKindOrThrow(SyntaxKind.NamedImports).getFirstChildByKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: originalNamedImports,
insertIndex: index,
newText: writer.toString(),
surroundWithSpaces: this._context.getFormatCodeSettings().insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces
});
}
const newNamedImports = this.getNamedImports();
return getNodesToReturn(newNamedImports, index, newNamedImports.length - originalNamedImports.length);
}
/**
* Gets the named imports.
*/
getNamedImports(): ImportSpecifier[] {
const importClause = this.getImportClause();
if (importClause == null)
return [];
return importClause.getNamedImports();
}
/**
* Removes all the named imports.
*/
removeNamedImports(): this {
const importClause = this.getImportClause();
if (importClause == null)
return this;
const namedImportsNode = importClause.getNamedBindings();
if (namedImportsNode == null || namedImportsNode.getKind() !== SyntaxKind.NamedImports)
return this;
// ex. import defaultExport, { Export1 } from "module-name";
const defaultImport = this.getDefaultImport();
if (defaultImport != null) {
const commaToken = defaultImport.getNextSiblingIfKindOrThrow(SyntaxKind.CommaToken);
removeChildren({ children: [commaToken, namedImportsNode] });
return this;
}
// ex. import { Export1 } from "module-name";
const fromKeyword = importClause.getNextSiblingIfKindOrThrow(SyntaxKind.FromKeyword);
removeChildren({ children: [importClause, fromKeyword], removePrecedingSpaces: true });
return this;
}
/**
* Gets the import clause or throws if it doesn't exist.
*/
getImportClauseOrThrow() {
return errors.throwIfNullOrUndefined(this.getImportClause(), "Expected to find an import clause.");
}
/**
* Gets the import clause or returns undefined if it doesn't exist.
*/
getImportClause() {
return this._getNodeFromCompilerNodeIfExists(this.compilerNode.importClause);
}
/**
* Sets the node from a structure.
* @param structure - Structure to set the node with.
*/
set(structure: Partial<ImportDeclarationStructure>) {
callBaseSet(ImportDeclarationBase.prototype, this, structure);
if (structure.defaultImport != null)
this.setDefaultImport(structure.defaultImport);
else if (structure.hasOwnProperty(nameof(structure.defaultImport)))
this.removeDefaultImport();
if (structure.hasOwnProperty(nameof(structure.namedImports)))
this.removeNamedImports();
if (structure.namespaceImport != null)
this.setNamespaceImport(structure.namespaceImport);
else if (structure.hasOwnProperty(nameof(structure.namespaceImport)))
this.removeNamespaceImport();
if (structure.namedImports != null) {
setEmptyNamedImport(this);
this.addNamedImports(structure.namedImports);
}
if (structure.moduleSpecifier != null)
this.setModuleSpecifier(structure.moduleSpecifier);
return this;
}
/**
* Gets the structure equivalent to this node.
*/
getStructure(): ImportDeclarationStructure {
const namespaceImport = this.getNamespaceImport();
const defaultImport = this.getDefaultImport();
return callBaseGetStructure<ImportDeclarationStructure>(ImportDeclarationBase.prototype, this, {
defaultImport: defaultImport ? defaultImport.getText() : undefined,
moduleSpecifier: this.getModuleSpecifier().getLiteralText(),
namedImports: this.getNamedImports().map(node => node.getStructure()),
namespaceImport: namespaceImport ? namespaceImport.getText() : undefined
});
}
}
function setEmptyNamedImport(node: ImportDeclaration) {
const importClause = node.getNodeProperty("importClause");
const writer = node._getWriterWithQueuedChildIndentation();
const namedImportStructurePrinter = node._context.structurePrinterFactory.forNamedImportExportSpecifier();
namedImportStructurePrinter.printTextsWithBraces(writer, []);
const emptyBracesText = writer.toString();
if (node.getNamespaceImport() != null)
throw getErrorWhenNamespaceImportsExist();
if (importClause == null) {
insertIntoParentTextRange({
insertPos: node.getFirstChildByKindOrThrow(SyntaxKind.ImportKeyword).getEnd(),
parent: node,
newText: ` ${emptyBracesText} from`
});
return;
}
const replaceNode = importClause.getNamedBindings();
if (replaceNode != null) {
insertIntoParentTextRange({
parent: importClause,
newText: emptyBracesText,
insertPos: replaceNode.getStart(),
replacing: {
textLength: replaceNode.getWidth()
}
});
return;
}
const defaultImport = importClause.getDefaultImport();
if (defaultImport != null) {
insertIntoParentTextRange({
insertPos: defaultImport.getEnd(),
parent: importClause,
newText: `, ${emptyBracesText}`
});
return;
}
}
function getErrorWhenNamespaceImportsExist() {
return new errors.InvalidOperationError("Cannot add a named import to an import declaration that has a namespace import.");
}