Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 120 lines 2.59 KB
Raw
1 import type { BasicBuilder } from './BasicBuilder';
2 import { Writer } from './Writer';
3
4 export type Import = NamespaceImport | BindingsImport | ModuleImport;
5
6 export class NamespaceImport implements BasicBuilder {
7 private type = false;
8
9 constructor(
10 readonly alias: string,
11 readonly from: string
12 ) {}
13
14 typeOnly() {
15 this.type = true;
16 return this;
17 }
18
19 write(writer: Writer<undefined>): void {
20 writer.write('import ');
21 if (this.type) {
22 writer.write('type ');
23 }
24 writer.write('* as ').write(this.alias).write(` from "${this.from}"`);
25 }
26 }
27
28 export class BindingsImport implements BasicBuilder {
29 private defaultImport: string | undefined;
30 private namedImports: NamedImport[] = [];
31 constructor(readonly from: string) {}
32
33 default(name: string) {
34 this.defaultImport = name;
35 return this;
36 }
37
38 named(namedImport: string | NamedImport) {
39 if (typeof namedImport === 'string') {
40 namedImport = new NamedImport(namedImport);
41 }
42 this.namedImports.push(namedImport);
43 return this;
44 }
45
46 write(writer: Writer): void {
47 writer.write('import ');
48 if (this.defaultImport) {
49 writer.write(this.defaultImport);
50 if (this.hasNamedImports()) {
51 writer.write(', ');
52 }
53 }
54
55 if (this.hasNamedImports()) {
56 writer.write('{ ').writeJoined(', ', this.namedImports).write(' }');
57 }
58
59 writer.write(` from "${this.from}"`);
60 }
61
62 private hasNamedImports() {
63 return this.namedImports.length > 0;
64 }
65 }
66
67 export class NamedImport implements BasicBuilder {
68 private alias: string | undefined;
69 private type = false;
70
71 constructor(readonly name: string) {}
72
73 as(alias: string) {
74 this.alias = alias;
75 return this;
76 }
77
78 typeOnly() {
79 this.type = true;
80 return this;
81 }
82
83 write(writer: Writer): void {
84 if (this.type) {
85 writer.write('type ');
86 }
87 writer.write(this.name);
88 if (this.alias) {
89 writer.write(' as ').write(this.alias);
90 }
91 }
92 }
93
94 export class ModuleImport implements BasicBuilder {
95 constructor(readonly from: string) {}
96
97 asNamespace(alias: string): NamespaceImport {
98 return new NamespaceImport(alias, this.from);
99 }
100
101 default(alias: string): BindingsImport {
102 return new BindingsImport(this.from).default(alias);
103 }
104
105 named(namedImport: string | NamedImport) {
106 return new BindingsImport(this.from).named(namedImport);
107 }
108
109 write(writer: Writer): void {
110 writer.write('import ').write(`"${this.from}"`);
111 }
112 }
113
114 export function moduleImport(from: string) {
115 return new ModuleImport(from);
116 }
117
118 export function namedImport(name: string) {
119 return new NamedImport(name);
120 }