Repository navigation
Expand file tree
/
Copy pathplugin-creator.ts
More file actions
259 lines (207 loc) · 8.42 KB
/
Copy pathplugin-creator.ts
File metadata and controls
259 lines (207 loc) · 8.42 KB
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
namespace tsp {
const crypto = require('crypto');
/* ********************************************************* */
// region: Types
/* ********************************************************* */
/** @internal */
interface CreateTransformersFromPatternOptions {
factory: PluginFactory;
config: PluginConfig;
registerConfig: RegisterConfig;
program: tsShim.Program;
ls?: tsShim.LanguageService;
}
export namespace PluginCreator {
export interface Options {
resolveBaseDir: string;
}
}
// endregion
/* ********************************************************* */
// region: Helpers
/* ********************************************************* */
function createTransformersFromPattern(opt: CreateTransformersFromPatternOptions): TransformerBasePlugin {
const { factory, config, program, ls, registerConfig } = opt;
const { transform, after, afterDeclarations, name, type, transformProgram, ...cleanConfig } = config;
if (!transform) throw new TsPatchError('Not a valid config entry: "transform" key not found');
// @formatter:off
const transformerKind =
after ? 'after' :
afterDeclarations ? 'afterDeclarations' :
'before';
// @formatter:on
let pluginFactoryResult: TransformerPlugin;
switch (config.type) {
case 'ls':
if (!ls) throw new TsPatchError(`Plugin ${transform} needs a LanguageService`);
pluginFactoryResult = (factory as LSPattern)(ls, cleanConfig);
break;
case 'config':
pluginFactoryResult = (factory as ConfigPattern)(cleanConfig);
break;
case 'compilerOptions':
pluginFactoryResult = (factory as CompilerOptionsPattern)(program.getCompilerOptions(), cleanConfig);
break;
case 'checker':
pluginFactoryResult = (factory as TypeCheckerPattern)(program.getTypeChecker(), cleanConfig);
break;
case undefined:
case 'program':
const { addDiagnostic, removeDiagnostic, diagnostics } = diagnosticExtrasFactory(program);
pluginFactoryResult = (factory as ProgramPattern)(program, cleanConfig, {
ts: tsp.getTsInstance(),
addDiagnostic,
removeDiagnostic,
diagnostics,
library: tsp.currentLibrary
});
break;
case 'raw':
pluginFactoryResult = (ctx: tsShim.TransformationContext) => (factory as RawPattern)(ctx, program, cleanConfig);
break;
default:
throw new TsPatchError(`Invalid plugin type found in tsconfig.json: '${config.type}'`);
}
/* Extract factories */
let transformerFactories: TsTransformerFactory[];
// noinspection FallThroughInSwitchStatementJS
switch (typeof pluginFactoryResult) {
// Single transformer factory
case 'function':
transformerFactories = [ pluginFactoryResult ];
break;
// TransformerBasePlugin
case 'object':
const factoryOrFactories = pluginFactoryResult[transformerKind];
// Single transformer factory
if (typeof factoryOrFactories === 'function') {
transformerFactories = [ pluginFactoryResult[transformerKind] ];
break;
}
// Array of transformer factories
else if (Array.isArray(factoryOrFactories)) {
transformerFactories = [ ...factoryOrFactories ];
break;
}
// Deliberate fall-through
default:
throw new TsPatchError(`Invalid plugin result: expected a function or an object with a '${transformerKind}' property`);
}
/* Wrap factories */
const wrappedFactories: TsTransformerFactory[] = [];
for (const transformerFactory of transformerFactories) {
if (!transformerFactory || typeof transformerFactory !== 'function')
throw new TsPatchError(
`Invalid plugin entry point! Expected a transformer factory function or an object with a '${transformerKind}' property`
);
/* Wrap w/ register */
const wrapper = wrapTransformerFactory(transformerFactory, registerConfig, true);
wrappedFactories.push(wrapper);
}
const res: TransformerBasePlugin = {
[transformerKind]: wrappedFactories
};
return res;
}
function wrapTransformerFactory(
transformerFn: TsTransformerFactory,
requireConfig: RegisterConfig,
wrapInnerFunction: boolean
): TsTransformerFactory {
const wrapper: TsTransformerFactory = function tspWrappedFactory(...args: any[]) {
let res: any;
try {
registerPlugin(requireConfig);
if (!wrapInnerFunction) {
res = (transformerFn as Function)(...args);
} else {
const resFn = (transformerFn as Function)(...args);
if (typeof resFn !== 'function') throw new TsPatchError('Invalid plugin: expected a function');
res = wrapTransformerFactory(resFn, requireConfig, false);
}
}
catch (e) {
const hint = describeEsmInCjsError(e);
if (hint) throw new TsPatchError(hint);
throw e;
}
finally {
unregisterPlugin();
}
return res;
}
return wrapper;
}
// endregion
/* ********************************************************* *
* PluginCreator (Class)
* ********************************************************* */
export class PluginCreator {
public readonly plugins: TspPlugin[] = [];
public readonly options: PluginCreator.Options;
public readonly needsTscJsDocParsing: boolean;
private readonly configs: PluginConfig[];
constructor(configs: PluginConfig[], options: PluginCreator.Options) {
this.configs = configs;
this.options = options;
const { resolveBaseDir } = options;
/* Create plugins */
this.plugins = configs
.filter(config => config.transform !== undefined)
.map(config => new TspPlugin(config, { resolveBaseDir }));
/* Check if we need to parse all JSDoc comments */
this.needsTscJsDocParsing = this.plugins.some(plugin => plugin.packageConfig?.tscOptions?.parseAllJsDoc === true);
}
private mergeTransformers(into: TransformerList, source: tsShim.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;
}
public createSourceTransformers(
params: { program: tsShim.Program } | { ls: tsShim.LanguageService },
customTransformers?: tsShim.CustomTransformers
): TransformerList {
const transformers: TransformerList = { before: [], after: [], afterDeclarations: [] };
const [ ls, program ] = ('ls' in params) ? [ params.ls, params.ls.getProgram()! ] : [ void 0, params.program ];
for (const plugin of this.plugins) {
if (plugin.kind !== 'SourceTransformer') continue;
const { config } = plugin;
const createFactoryResult = plugin.createFactory();
if (!createFactoryResult) continue;
const { factory, registerConfig } = createFactoryResult;
this.mergeTransformers(
transformers,
createTransformersFromPattern({
factory: factory as PluginFactory,
registerConfig,
config,
program,
ls
})
);
}
// Chain custom transformers at the end
if (customTransformers) this.mergeTransformers(transformers, customTransformers);
return transformers;
}
public createProgramTransformers(): Map<string, [ ProgramTransformer, PluginConfig ]> {
const res = new Map<string, [ ProgramTransformer, PluginConfig ]>();
for (const plugin of this.plugins) {
if (plugin.kind !== 'ProgramTransformer') continue;
const { config } = plugin;
const createFactoryResult = plugin.createFactory();
if (createFactoryResult === undefined) continue;
const { registerConfig, factory: unwrappedFactory } = createFactoryResult;
const factory = wrapTransformerFactory(unwrappedFactory as ProgramTransformer, registerConfig, false);
const transformerKey = crypto
.createHash('md5')
.update(JSON.stringify({ factory, config }))
.digest('hex');
res.set(transformerKey, [ factory, config ]);
}
return res;
}
}
}