forked from dsherret/ts-morph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExportDeclaration.ts
303 lines (267 loc) · 11.3 KB
/
ExportDeclaration.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
import * as errors from "../../../errors";
import { getNodesToReturn, insertIntoCommaSeparatedNodes, insertIntoParentTextRange, verifyAndGetIndex, removeChildren } from "../../../manipulation";
import { ExportSpecifierStructure, ExportDeclarationSpecificStructure, ExportDeclarationStructure, StructureKind, OptionalKind } from "../../../structures";
import { WriterFunction } from "../../../types";
import { SyntaxKind, ts } from "../../../typescript";
import { ArrayUtils, ModuleUtils, TypeGuards, StringUtils } from "../../../utils";
import { StringLiteral } from "../literal";
import { Node } from "../common";
import { Statement } from "../statement";
import { ExportSpecifier } from "./ExportSpecifier";
import { SourceFile } from "./SourceFile";
import { callBaseGetStructure } from "../callBaseGetStructure";
import { callBaseSet } from "../callBaseSet";
export const ExportDeclarationBase = Statement;
export class ExportDeclaration extends ExportDeclarationBase<ts.ExportDeclaration> {
/**
* 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);
if (StringUtils.isNullOrEmpty(text)) {
this.removeModuleSpecifier();
return this;
}
const stringLiteral = this.getModuleSpecifier();
if (stringLiteral == null) {
const semiColonToken = this.getLastChildIfKind(SyntaxKind.SemicolonToken);
const quoteKind = this._context.manipulationSettings.getQuoteKind();
insertIntoParentTextRange({
insertPos: semiColonToken != null ? semiColonToken.getPos() : this.getEnd(),
parent: this,
newText: ` from ${quoteKind}${text}${quoteKind}`
});
}
else {
stringLiteral.setLiteralValue(text);
}
return this;
}
/**
* Gets the module specifier or undefined if it doesn't exist.
*/
getModuleSpecifier(): StringLiteral | undefined {
const moduleSpecifier = this._getNodeFromCompilerNodeIfExists(this.compilerNode.moduleSpecifier);
if (moduleSpecifier == null)
return undefined;
if (!TypeGuards.isStringLiteral(moduleSpecifier))
throw new errors.InvalidOperationError("Expected the module specifier to be a string literal.");
return moduleSpecifier;
}
/**
* Gets the module specifier value or undefined if it doesn't exist.
*/
getModuleSpecifierValue() {
const moduleSpecifier = this.getModuleSpecifier();
return moduleSpecifier == null ? undefined : moduleSpecifier.getLiteralValue();
}
/**
* Gets the source file referenced in the module specifier or throws if it can't find it or it doesn't exist.
*/
getModuleSpecifierSourceFileOrThrow() {
return errors.throwIfNullOrUndefined(this.getModuleSpecifierSourceFile(), `A module specifier source file was expected.`);
}
/**
* Gets the source file referenced in the module specifier.
*/
getModuleSpecifierSourceFile() {
const stringLiteral = this.getLastChildByKind(SyntaxKind.StringLiteral);
if (stringLiteral == null)
return undefined;
const symbol = stringLiteral.getSymbol();
if (symbol == null)
return undefined;
const declaration = symbol.getDeclarations()[0];
return declaration != null && TypeGuards.isSourceFile(declaration) ? declaration : undefined;
}
/**
* Gets if the module specifier starts with `./` or `../`.
*/
isModuleSpecifierRelative() {
const moduleSpecifierValue = this.getModuleSpecifierValue();
if (moduleSpecifierValue == null)
return false;
return ModuleUtils.isModuleSpecifierRelative(moduleSpecifierValue);
}
/**
* Removes the module specifier.
*/
removeModuleSpecifier() {
const moduleSpecifier = this.getModuleSpecifier();
if (moduleSpecifier == null)
return this;
if (!this.hasNamedExports())
throw new errors.InvalidOperationError(`Cannot remove the module specifier from an export declaration that has no named exports.`);
removeChildren({
children: [this.getFirstChildByKindOrThrow(SyntaxKind.FromKeyword), moduleSpecifier],
removePrecedingNewLines: true,
removePrecedingSpaces: true
});
return this;
}
/**
* Gets if the module specifier exists
*/
hasModuleSpecifier() {
return this.getLastChildByKind(SyntaxKind.StringLiteral) != null;
}
/**
* Gets if this export declaration is a namespace export.
*/
isNamespaceExport() {
return !this.hasNamedExports();
}
/**
* Gets if the export declaration has named exports.
*/
hasNamedExports() {
return this.compilerNode.exportClause != null;
}
/**
* Adds a named export.
* @param namedExport - Structure, name, or writer function to write the named export.
*/
addNamedExport(namedExport: OptionalKind<ExportSpecifierStructure> | string | WriterFunction) {
return this.addNamedExports([namedExport])[0];
}
/**
* Adds named exports.
* @param namedExports - Structures, names, or writer function to write the named exports.
*/
addNamedExports(namedExports: ReadonlyArray<OptionalKind<ExportSpecifierStructure> | string | WriterFunction> | WriterFunction) {
return this.insertNamedExports(this.getNamedExports().length, namedExports);
}
/**
* Inserts a named export.
* @param index - Child index to insert at.
* @param namedExport - Structure, name, or writer function to write the named export.
*/
insertNamedExport(index: number, namedExport: OptionalKind<ExportSpecifierStructure> | string | WriterFunction) {
return this.insertNamedExports(index, [namedExport])[0];
}
/**
* Inserts named exports into the export declaration.
* @param index - Child index to insert at.
* @param namedExports - Structures, names, or writer funciton to write the named exports.
*/
insertNamedExports(index: number, namedExports: ReadonlyArray<OptionalKind<ExportSpecifierStructure> | string | WriterFunction> | WriterFunction) {
if (!(namedExports instanceof Function) && ArrayUtils.isNullOrEmpty(namedExports))
return [];
const originalNamedExports = this.getNamedExports();
const writer = this._getWriterWithIndentation();
const namedExportStructurePrinter = this._context.structurePrinterFactory.forNamedImportExportSpecifier();
index = verifyAndGetIndex(index, originalNamedExports.length);
if (this.getNodeProperty("exportClause") == null) {
namedExportStructurePrinter.printTextsWithBraces(writer, namedExports);
const asteriskToken = this.getFirstChildByKindOrThrow(SyntaxKind.AsteriskToken);
insertIntoParentTextRange({
insertPos: asteriskToken.getStart(),
parent: this,
newText: writer.toString(),
replacing: {
textLength: 1
}
});
}
else {
namedExportStructurePrinter.printTexts(writer, namedExports);
insertIntoCommaSeparatedNodes({
parent: this.getFirstChildByKindOrThrow(SyntaxKind.NamedExports).getFirstChildByKindOrThrow(SyntaxKind.SyntaxList),
currentNodes: originalNamedExports,
insertIndex: index,
newText: writer.toString(),
surroundWithSpaces: this._context.getFormatCodeSettings().insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces,
useTrailingCommas: false
});
}
const newNamedExports = this.getNamedExports();
return getNodesToReturn(originalNamedExports, newNamedExports, index, false);
}
/**
* Gets the named exports.
*/
getNamedExports(): ExportSpecifier[] {
const namedExports = this.compilerNode.exportClause;
if (namedExports == null)
return [];
return namedExports.elements.map(e => this._getNodeFromCompilerNode(e));
}
/**
* Changes the export declaration to namespace export. Removes all the named exports.
*/
toNamespaceExport(): this {
if (!this.hasModuleSpecifier())
throw new errors.InvalidOperationError("Cannot change to a namespace export when no module specifier exists.");
const namedExportsNode = this.getNodeProperty("exportClause");
if (namedExportsNode == null)
return this;
insertIntoParentTextRange({
parent: this,
newText: "*",
insertPos: namedExportsNode.getStart(),
replacing: {
textLength: namedExportsNode.getWidth()
}
});
return this;
}
/**
* Sets the node from a structure.
* @param structure - Structure to set the node with.
*/
set(structure: Partial<ExportDeclarationStructure>) {
callBaseSet(ExportDeclarationBase.prototype, this, structure);
if (structure.namedExports != null) {
setEmptyNamedExport(this);
this.addNamedExports(structure.namedExports);
}
else if (structure.hasOwnProperty(nameof(structure.namedExports)) && structure.moduleSpecifier == null) {
this.toNamespaceExport();
}
if (structure.moduleSpecifier != null)
this.setModuleSpecifier(structure.moduleSpecifier);
else if (structure.hasOwnProperty(nameof(structure.moduleSpecifier)))
this.removeModuleSpecifier();
if (structure.namedExports == null && structure.hasOwnProperty(nameof(structure.namedExports)))
this.toNamespaceExport();
return this;
}
/**
* Gets the structure equivalent to this node.
*/
getStructure(): ExportDeclarationStructure {
const moduleSpecifier = this.getModuleSpecifier();
return callBaseGetStructure<ExportDeclarationSpecificStructure>(ExportDeclarationBase.prototype, this, {
kind: StructureKind.ExportDeclaration,
moduleSpecifier: moduleSpecifier ? moduleSpecifier.getLiteralText() : undefined,
namedExports: this.getNamedExports().map(node => node.getStructure())
});
}
}
function setEmptyNamedExport(node: ExportDeclaration) {
const namedExportsNode = node.getNodeProperty("exportClause");
let replaceNode: Node;
if (namedExportsNode != null) {
if (node.getNamedExports().length === 0)
return;
replaceNode = namedExportsNode;
}
else {
replaceNode = node.getFirstChildByKindOrThrow(SyntaxKind.AsteriskToken);
}
insertIntoParentTextRange({
parent: node,
newText: "{ }",
insertPos: replaceNode.getStart(),
replacing: {
textLength: replaceNode.getWidth()
}
});
}