-
Notifications
You must be signed in to change notification settings - Fork 0
/
PluginCreator.ts
260 lines (237 loc) · 8.63 KB
/
PluginCreator.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
import * as resolve from 'resolve';
import * as ts from 'typescript';
import { inspect } from 'util';
import { addDiagnosticFactory } from './patchCreateProgram';
export interface PluginConfig {
/**
* Language Server TypeScript Plugin name
*/
name?: string;
/**
* Path to transformer or transformer module name
*/
transform?: string;
/**
* The optional name of the exported transform plugin in the transform module.
*/
import?: string;
/**
* Plugin entry point format type, default is program
*/
type?: 'ls' | 'program' | 'config' | 'checker' | 'raw' | 'compilerOptions';
/**
* Should transformer applied after all ones
*/
after?: boolean;
/**
* Should transformer applied for d.ts files, supports from TS2.9
*/
afterDeclarations?: boolean;
}
export interface TransformerBasePlugin {
before?: ts.TransformerFactory<ts.SourceFile>;
after?: ts.TransformerFactory<ts.SourceFile>;
afterDeclarations?: ts.TransformerFactory<ts.SourceFile | ts.Bundle>;
}
export type TransformerList = Required<ts.CustomTransformers>;
export type TransformerPlugin = TransformerBasePlugin | ts.TransformerFactory<ts.SourceFile>;
export type LSPattern = (ls: ts.LanguageService, config: {}) => TransformerPlugin;
export type ProgramPattern = (
program: ts.Program,
config: {},
helpers?: { ts: typeof ts; addDiagnostic: (diag: ts.Diagnostic) => void }
) => TransformerPlugin;
export type CompilerOptionsPattern = (compilerOpts: ts.CompilerOptions, config: {}) => TransformerPlugin;
export type ConfigPattern = (config: {}) => TransformerPlugin;
export type TypeCheckerPattern = (checker: ts.TypeChecker, config: {}) => TransformerPlugin;
export type RawPattern = (
context: ts.TransformationContext,
program: ts.Program,
config: {}
) => ts.Transformer<ts.SourceFile>;
export type PluginFactory =
| LSPattern
| ProgramPattern
| ConfigPattern
| CompilerOptionsPattern
| TypeCheckerPattern
| RawPattern;
function createTransformerFromPattern({
typescript,
factory,
config,
program,
ls,
}: {
typescript: typeof ts;
factory: PluginFactory;
config: PluginConfig;
program: ts.Program;
ls?: ts.LanguageService;
}): TransformerBasePlugin {
const { transform, after, afterDeclarations, name, type, ...cleanConfig } = config;
if (!transform) throw new Error('Not a valid config entry: "transform" key not found');
let ret: TransformerPlugin;
switch (config.type) {
case 'ls':
if (!ls) throw new Error(`Plugin ${transform} need a LanguageService`);
ret = (factory as LSPattern)(ls, cleanConfig);
break;
case 'config':
ret = (factory as ConfigPattern)(cleanConfig);
break;
case 'compilerOptions':
ret = (factory as CompilerOptionsPattern)(program.getCompilerOptions(), cleanConfig);
break;
case 'checker':
ret = (factory as TypeCheckerPattern)(program.getTypeChecker(), cleanConfig);
break;
case undefined:
case 'program':
ret = (factory as ProgramPattern)(program, cleanConfig, {
ts: typescript,
addDiagnostic: addDiagnosticFactory(program),
});
break;
case 'raw':
ret = (ctx: ts.TransformationContext) => (factory as RawPattern)(ctx, program, cleanConfig);
break;
default:
return never(config.type);
}
if (typeof ret === 'function') {
if (after) return { after: ret };
else if (afterDeclarations) {
return { afterDeclarations: ret as ts.TransformerFactory<ts.SourceFile | ts.Bundle> };
} else return { before: ret };
}
return ret;
}
function never(n: never): never {
throw new Error('Unexpected type: ' + n);
}
let tsNodeIncluded = false;
// to fix recursion bug, see usage below
const requireStack: string[] = [];
/**
* @example
*
* new PluginCreator([
* {transform: '@zerollup/ts-transform-paths', someOption: '123'},
* {transform: '@zerollup/ts-transform-paths', type: 'ls', someOption: '123'},
* {transform: '@zerollup/ts-transform-paths', type: 'ls', after: true, someOption: '123'}
* ]).createTransformers({ program })
*/
export class PluginCreator {
constructor(
private typescript: typeof ts,
private configs: PluginConfig[],
private resolveBaseDir: string = process.cwd()
) {
this.validateConfigs(configs);
}
mergeTransformers(into: TransformerList, source: ts.CustomTransformers | TransformerBasePlugin) {
const slice = <T>(input: T | T[]) => (Array.isArray(input) ? input.slice() : [input]);
if (source.before) {
into.before.push(...slice(source.before));
}
if (source.after) {
into.after.push(...slice(source.after));
}
if (source.afterDeclarations) {
into.afterDeclarations.push(...slice(source.afterDeclarations));
}
return this;
}
createTransformers(
params: { program: ts.Program } | { ls: ts.LanguageService },
customTransformers?: ts.CustomTransformers
) {
const chain: TransformerList = {
before: [],
after: [],
afterDeclarations: [],
};
let ls;
let program;
if ('ls' in params) {
ls = params.ls;
program = ls.getProgram()!;
} else {
program = params.program;
}
for (const config of this.configs) {
if (!config.transform) {
continue;
}
const factory = this.resolveFactory(config.transform, config.import);
// if recursion
if (factory === undefined) continue;
const transformer = createTransformerFromPattern({
typescript: this.typescript,
factory,
config,
program,
ls,
});
this.mergeTransformers(chain, transformer);
}
// if we're given some custom transformers, they must be chained at the end
if (customTransformers) {
this.mergeTransformers(chain, customTransformers);
}
return chain;
}
private resolveFactory(transform: string, importKey: string = 'default'): PluginFactory | undefined {
if (
!tsNodeIncluded &&
transform.match(/\.tsx?$/) &&
(module.parent!.parent === null ||
module.parent!.parent!.parent === null ||
module.parent!.parent!.parent!.id.split(/[\/\\]/).indexOf('ts-node') === -1)
) {
require('ts-node').register({
transpileOnly: true,
skipProject: true,
compilerOptions: {
target: 'ES2018',
jsx: 'react',
esModuleInterop: true,
module: 'commonjs',
},
});
tsNodeIncluded = true;
}
const modulePath = resolve.sync(transform, { basedir: this.resolveBaseDir });
// in ts-node occurs error cause recursion:
// ts-node file.ts -> createTransformers -> require transformer.ts
// -> createTransformers -> require transformer.ts -> ...
// this happens cause ts-node uses to compile transformers the same config included this transformer
// so this stack checks that if we already required this file we are in the reqursion
if (requireStack.indexOf(modulePath) > -1) return;
requireStack.push(modulePath);
const commonjsModule: PluginFactory | { [key: string]: PluginFactory } = require(modulePath);
requireStack.pop();
const factoryModule = typeof commonjsModule === 'function' ? { default: commonjsModule } : commonjsModule;
const factory = factoryModule[importKey];
if (!factory) {
throw new Error(
`tsconfig.json > plugins: "${transform}" does not have an export "${importKey}": ` +
inspect(factoryModule)
);
}
if (typeof factory !== 'function') {
throw new Error(
`tsconfig.json > plugins: "${transform}" export "${importKey}" is not a plugin: "${inspect(factory)}"`
);
}
return factory;
}
private validateConfigs(configs: PluginConfig[]) {
for (const config of configs) {
if (!config.name && !config.transform) {
throw new Error('tsconfig.json plugins error: transform must be present');
}
}
}
}