UNPKG

8.46 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.findClass = exports.addMethod = exports.addParameterToConstructor = exports.replaceNodeValue = exports.getImport = exports.addGlobal = exports.insertImport = exports.removeChange = exports.replaceChange = exports.insertChange = void 0;
4const ts = require("typescript");
5const typescript_1 = require("./typescript");
6const find_nodes_1 = require("./typescript/find-nodes");
7function nodesByPosition(first, second) {
8 return first.getStart() - second.getStart();
9}
10function updateTsSourceFile(host, sourceFile, filePath) {
11 const newFileContents = host.read(filePath).toString('utf-8');
12 return sourceFile.update(newFileContents, {
13 newLength: newFileContents.length,
14 span: {
15 length: sourceFile.text.length,
16 start: 0,
17 },
18 });
19}
20function insertChange(host, sourceFile, filePath, insertPosition, contentToInsert) {
21 const content = host.read(filePath).toString();
22 const prefix = content.substring(0, insertPosition);
23 const suffix = content.substring(insertPosition);
24 host.write(filePath, `${prefix}${contentToInsert}${suffix}`);
25 return updateTsSourceFile(host, sourceFile, filePath);
26}
27exports.insertChange = insertChange;
28function replaceChange(host, sourceFile, filePath, insertPosition, contentToInsert, oldContent) {
29 const content = host.read(filePath, 'utf-8');
30 const prefix = content.substring(0, insertPosition);
31 const suffix = content.substring(insertPosition + oldContent.length);
32 const text = content.substring(insertPosition, insertPosition + oldContent.length);
33 if (text !== oldContent) {
34 throw new Error(`Invalid replace: "${text}" != "${oldContent}".`);
35 }
36 host.write(filePath, `${prefix}${contentToInsert}${suffix}`);
37 return updateTsSourceFile(host, sourceFile, filePath);
38}
39exports.replaceChange = replaceChange;
40function removeChange(host, sourceFile, filePath, removePosition, contentToRemove) {
41 const content = host.read(filePath).toString();
42 const prefix = content.substring(0, removePosition);
43 const suffix = content.substring(removePosition + contentToRemove.length);
44 host.write(filePath, `${prefix}${suffix}`);
45 return updateTsSourceFile(host, sourceFile, filePath);
46}
47exports.removeChange = removeChange;
48function insertImport(host, source, fileToEdit, symbolName, fileName, isDefault = false) {
49 const rootNode = source;
50 const allImports = (0, find_nodes_1.findNodes)(rootNode, ts.SyntaxKind.ImportDeclaration);
51 // get nodes that map to import statements from the file fileName
52 const relevantImports = allImports.filter((node) => {
53 // StringLiteral of the ImportDeclaration is the import file (fileName in this case).
54 const importFiles = node
55 .getChildren()
56 .filter((child) => child.kind === ts.SyntaxKind.StringLiteral)
57 .map((n) => n.text);
58 return importFiles.filter((file) => file === fileName).length === 1;
59 });
60 if (relevantImports.length > 0) {
61 let importsAsterisk = false;
62 // imports from import file
63 const imports = [];
64 relevantImports.forEach((n) => {
65 Array.prototype.push.apply(imports, (0, find_nodes_1.findNodes)(n, ts.SyntaxKind.Identifier));
66 if ((0, find_nodes_1.findNodes)(n, ts.SyntaxKind.AsteriskToken).length > 0) {
67 importsAsterisk = true;
68 }
69 });
70 // if imports * from fileName, don't add symbolName
71 if (importsAsterisk) {
72 return source;
73 }
74 const importTextNodes = imports.filter((n) => n.text === symbolName);
75 // insert import if it's not there
76 if (importTextNodes.length === 0) {
77 const fallbackPos = (0, find_nodes_1.findNodes)(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
78 (0, find_nodes_1.findNodes)(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();
79 return insertAfterLastOccurrence(host, source, imports, `, ${symbolName}`, fileToEdit, fallbackPos);
80 }
81 return source;
82 }
83 // no such import declaration exists
84 const useStrict = (0, find_nodes_1.findNodes)(rootNode, ts.SyntaxKind.StringLiteral).filter((n) => n.text === 'use strict');
85 let fallbackPos = 0;
86 if (useStrict.length > 0) {
87 fallbackPos = useStrict[0].end;
88 }
89 const open = isDefault ? '' : '{ ';
90 const close = isDefault ? '' : ' }';
91 // if there are no imports or 'use strict' statement, insert import at beginning of file
92 const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
93 const separator = insertAtBeginning ? '' : ';\n';
94 const toInsert = `${separator}import ${open}${symbolName}${close}` +
95 ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`;
96 return insertAfterLastOccurrence(host, source, allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral);
97}
98exports.insertImport = insertImport;
99function insertAfterLastOccurrence(host, sourceFile, nodes, toInsert, pathToFile, fallbackPos, syntaxKind) {
100 // sort() has a side effect, so make a copy so that we won't overwrite the parent's object.
101 let lastItem = [...nodes].sort(nodesByPosition).pop();
102 if (!lastItem) {
103 throw new Error();
104 }
105 if (syntaxKind) {
106 lastItem = (0, find_nodes_1.findNodes)(lastItem, syntaxKind).sort(nodesByPosition).pop();
107 }
108 if (!lastItem && fallbackPos == undefined) {
109 throw new Error(`tried to insert ${toInsert} as first occurrence with no fallback position`);
110 }
111 const lastItemPosition = lastItem ? lastItem.getEnd() : fallbackPos;
112 return insertChange(host, sourceFile, pathToFile, lastItemPosition, toInsert);
113}
114function addGlobal(host, source, modulePath, statement) {
115 const allImports = (0, find_nodes_1.findNodes)(source, ts.SyntaxKind.ImportDeclaration);
116 if (allImports.length > 0) {
117 const lastImport = allImports[allImports.length - 1];
118 return insertChange(host, source, modulePath, lastImport.end + 1, `\n${statement}\n`);
119 }
120 else {
121 return insertChange(host, source, modulePath, 0, `${statement}\n`);
122 }
123}
124exports.addGlobal = addGlobal;
125function getImport(source, predicate) {
126 const allImports = (0, find_nodes_1.findNodes)(source, ts.SyntaxKind.ImportDeclaration);
127 const matching = allImports.filter((i) => predicate(i.moduleSpecifier.getText()));
128 return matching.map((i) => {
129 const moduleSpec = i.moduleSpecifier
130 .getText()
131 .substring(1, i.moduleSpecifier.getText().length - 1);
132 const t = i.importClause.namedBindings.getText();
133 const bindings = t
134 .replace('{', '')
135 .replace('}', '')
136 .split(',')
137 .map((q) => q.trim());
138 return { moduleSpec, bindings };
139 });
140}
141exports.getImport = getImport;
142function replaceNodeValue(host, sourceFile, modulePath, node, content) {
143 return replaceChange(host, sourceFile, modulePath, node.getStart(node.getSourceFile()), content, node.getText());
144}
145exports.replaceNodeValue = replaceNodeValue;
146function addParameterToConstructor(tree, source, modulePath, opts) {
147 const clazz = findClass(source, opts.className);
148 const constructor = clazz.members.filter((m) => m.kind === ts.SyntaxKind.Constructor)[0];
149 if (constructor) {
150 throw new Error('Should be tested'); // TODO: check this
151 }
152 return addMethod(tree, source, modulePath, {
153 className: opts.className,
154 methodHeader: `constructor(${opts.param})`,
155 });
156}
157exports.addParameterToConstructor = addParameterToConstructor;
158function addMethod(tree, source, modulePath, opts) {
159 const clazz = findClass(source, opts.className);
160 const body = opts.body
161 ? `
162${opts.methodHeader} {
163${opts.body}
164}
165`
166 : `
167${opts.methodHeader} {}
168`;
169 return insertChange(tree, source, modulePath, clazz.end - 1, body);
170}
171exports.addMethod = addMethod;
172function findClass(source, className, silent = false) {
173 const nodes = (0, typescript_1.getSourceNodes)(source);
174 const clazz = nodes.filter((n) => n.kind === ts.SyntaxKind.ClassDeclaration &&
175 n.name.text === className)[0];
176 if (!clazz && !silent) {
177 throw new Error(`Cannot find class '${className}'.`);
178 }
179 return clazz;
180}
181exports.findClass = findClass;
182//# sourceMappingURL=ast-utils.js.map
\No newline at end of file