woodstone 0.1.8 → 0.1.9

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.
@@ -0,0 +1,80 @@
1
+ import { Project, SourceFile, ImportDeclaration, ImportSpecifier } from "ts-morph";
2
+ export default class Scaffold {
3
+ file;
4
+ project;
5
+ sourceFile;
6
+ constructor(file) {
7
+ this.file = file;
8
+ this.project = new Project({
9
+ compilerOptions: { allowJs: true }
10
+ });
11
+ this.sourceFile =
12
+ this.project.getSourceFile(this.file) ||
13
+ this.project.createSourceFile(this.file, "", { overwrite: false });
14
+ }
15
+ getImport(module) {
16
+ return this.sourceFile
17
+ .getImportDeclarations()
18
+ .find((d) => d.getModuleSpecifierValue() === module);
19
+ }
20
+ async commit() {
21
+ await this.project.save();
22
+ }
23
+ addNamedImport(name, module) {
24
+ const existing = this.getImport(module);
25
+ if (existing) {
26
+ const alreadyExists = existing
27
+ .getNamedImports()
28
+ .some((i) => i.getName() === name);
29
+ if (!alreadyExists) {
30
+ existing.addNamedImport(name);
31
+ }
32
+ }
33
+ else {
34
+ this.sourceFile.addImportDeclaration({
35
+ namedImports: [name],
36
+ moduleSpecifier: module
37
+ });
38
+ }
39
+ }
40
+ addDefaultImport(name, module) {
41
+ const existing = this.getImport(module);
42
+ if (existing) {
43
+ const currentDefault = existing.getDefaultImport();
44
+ if (!currentDefault) {
45
+ existing.setDefaultImport(name);
46
+ }
47
+ else if (currentDefault.getText() !== name) {
48
+ throw new Error(`Module "${module}" already has default import "${currentDefault.getText()}"`);
49
+ }
50
+ }
51
+ else {
52
+ this.sourceFile.addImportDeclaration({
53
+ defaultImport: name,
54
+ moduleSpecifier: module
55
+ });
56
+ }
57
+ }
58
+ removeNamedImport(name, module) {
59
+ const existing = this.getImport(module);
60
+ if (!existing)
61
+ return;
62
+ const named = existing
63
+ .getNamedImports()
64
+ .find((i) => i.getName() === name);
65
+ if (!named)
66
+ return;
67
+ named.remove();
68
+ if (existing.getNamedImports().length === 0 &&
69
+ !existing.getDefaultImport() &&
70
+ !existing.getNamespaceImport()) {
71
+ existing.remove();
72
+ }
73
+ }
74
+ removeImport(module) {
75
+ const existing = this.getImport(module);
76
+ if (!existing)
77
+ return;
78
+ existing.remove();
79
+ }
80
+ }