/
transpile.ts
191 lines (176 loc) · 6.76 KB
/
transpile.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
import type * as d from '@stencil/core/declarations';
import { mockBuildCtx, mockCompilerCtx, mockValidatedConfig } from '@stencil/core/testing';
import ts from 'typescript';
import { convertDecoratorsToStatic } from '../decorators-to-static/convert-decorators';
import { updateModule } from '../static-to-meta/parse-static';
import { convertStaticToMeta } from '../static-to-meta/visitor';
import { getScriptTarget } from '../transform-utils';
/**
* Testing utility for transpiling provided string containing valid Stencil code
*
* @param input the code to transpile
* @param config a Stencil configuration to apply during the transpilation
* @param compilerCtx a compiler context to use in the transpilation process
* @param beforeTransformers TypeScript transformers that should be applied before the code is emitted
* @param afterTransformers TypeScript transformers that should be applied after the code is emitted
* @param afterDeclarations TypeScript transformers that should be applied
* after declarations are generated
* @param tsConfig optional typescript compiler options to use
* @param inputFileName a dummy filename to use for the module (defaults to `module.tsx`)
* @returns the result of the transpilation step
*/
export function transpileModule(
input: string,
config?: d.ValidatedConfig | null,
compilerCtx?: d.CompilerCtx | null,
beforeTransformers: ts.TransformerFactory<ts.SourceFile>[] = [],
afterTransformers: ts.TransformerFactory<ts.SourceFile>[] = [],
afterDeclarations: ts.TransformerFactory<ts.SourceFile | ts.Bundle>[] = [],
tsConfig: ts.CompilerOptions = {},
inputFileName = 'module.tsx',
) {
const options: ts.CompilerOptions = {
...ts.getDefaultCompilerOptions(),
allowNonTsExtensions: true,
composite: undefined,
declaration: undefined,
declarationDir: undefined,
experimentalDecorators: true,
isolatedModules: true,
jsx: ts.JsxEmit.React,
jsxFactory: 'h',
jsxFragmentFactory: 'Fragment',
lib: undefined,
module: ts.ModuleKind.ESNext,
noEmit: undefined,
noEmitHelpers: true,
noEmitOnError: undefined,
noLib: true,
noResolve: true,
out: undefined,
outFile: undefined,
paths: undefined,
removeComments: false,
rootDirs: undefined,
suppressOutputPathCheck: true,
target: getScriptTarget(),
types: undefined,
// add in possible default config overrides
...tsConfig,
};
config = config || mockValidatedConfig();
compilerCtx = compilerCtx || mockCompilerCtx(config);
const sourceFile = ts.createSourceFile(inputFileName, input, options.target);
let outputText: string;
let declarationOutputText: string;
const emitCallback: ts.WriteFileCallback = (emitFilePath, data, _w, _e, tsSourceFiles) => {
if (emitFilePath.endsWith('.js')) {
outputText = prettifyTSOutput(data);
updateModule(config, compilerCtx, buildCtx, tsSourceFiles[0], data, emitFilePath, tsTypeChecker, null);
}
if (emitFilePath.endsWith('.d.ts')) {
declarationOutputText = prettifyTSOutput(data);
}
};
const compilerHost: ts.CompilerHost = {
getSourceFile: (fileName) => (fileName === inputFileName ? sourceFile : undefined),
writeFile: emitCallback,
getDefaultLibFileName: () => 'lib.d.ts',
useCaseSensitiveFileNames: () => false,
getCanonicalFileName: (fileName) => fileName,
getCurrentDirectory: () => '',
getNewLine: () => '',
fileExists: (fileName) => fileName === inputFileName,
readFile: () => '',
directoryExists: () => true,
getDirectories: () => [],
};
const tsProgram = ts.createProgram([inputFileName], options, compilerHost);
const tsTypeChecker = tsProgram.getTypeChecker();
const buildCtx = mockBuildCtx(config, compilerCtx);
const transformOpts: d.TransformOptions = {
coreImportPath: '@stencil/core',
componentExport: 'lazy',
componentMetadata: null,
currentDirectory: '/',
proxy: null,
style: 'static',
styleImportData: 'queryparams',
};
tsProgram.emit(undefined, undefined, undefined, undefined, {
before: [convertDecoratorsToStatic(config, buildCtx.diagnostics, tsTypeChecker, tsProgram), ...beforeTransformers],
after: [
convertStaticToMeta(config, compilerCtx, buildCtx, tsTypeChecker, null, transformOpts),
...afterTransformers,
],
afterDeclarations,
});
const moduleFile: d.Module = compilerCtx.moduleMap.values().next().value;
const cmps = moduleFile ? moduleFile.cmps : null;
const cmp = Array.isArray(cmps) && cmps.length > 0 ? cmps[0] : null;
const tagName = cmp ? cmp.tagName : null;
const componentClassName = cmp ? cmp.componentClassName : null;
const properties = cmp ? cmp.properties : null;
const virtualProperties = cmp ? cmp.virtualProperties : null;
const property = properties ? properties[0] : null;
const states = cmp ? cmp.states : null;
const state = states ? states[0] : null;
const listeners = cmp ? cmp.listeners : null;
const listener = listeners ? listeners[0] : null;
const events = cmp ? cmp.events : null;
const event = events ? events[0] : null;
const methods = cmp ? cmp.methods : null;
const method = methods ? methods[0] : null;
const elementRef = cmp ? cmp.elementRef : null;
return {
buildCtx,
cmp,
cmps,
compilerCtx,
componentClassName,
declarationOutputText,
diagnostics: buildCtx.diagnostics,
elementRef,
event,
events,
listener,
listeners,
method,
methods,
moduleFile,
outputText,
properties,
property,
state,
states,
tagName,
virtualProperties,
};
}
/**
* Rewrites any stretches of whitespace in the TypeScript output to take up a
* single space instead. This makes it a little more readable to write out strings
* in spec files for comparison.
*
* @param tsOutput the string to process
* @returns that string with any stretches of whitespace shrunk down to one space
*/
const prettifyTSOutput = (tsOutput: string): string => tsOutput.replace(/\s+/gm, ' ');
/**
* Helper function for tests that converts stringified JavaScript to a runtime value.
* A value from the generated JavaScript is returned based on the provided property name.
* @param stringifiedJs the stringified JavaScript
* @param propertyName the property name to pull off the generated JavaScript
* @returns the value associated with the provided property name. Returns undefined if an error occurs while converting
* the stringified JS to JavaScript, or if the property does not exist on the generated JavaScript.
*/
export function getStaticGetter(stringifiedJs: string, propertyName: string): string | void {
const toEvaluate = `return ${stringifiedJs.replace('export', '')}`;
try {
const Obj = new Function(toEvaluate);
return Obj()[propertyName];
} catch (e) {
console.error(e);
console.error(toEvaluate);
}
}