-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathtypescript.ts
344 lines (288 loc) · 10.1 KB
/
typescript.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import {
createLogger,
getLogLevel,
getMonorepoRoot,
} from '@design-systems/cli-utils';
import fs from 'fs';
import path from 'path';
import { camelCase } from 'change-case';
import ts from 'typescript';
import postcss from 'postcss';
import postcssIcssSelectors from 'postcss-icss-selectors';
import { extractICSS } from 'icss-utils';
import minimatch from 'minimatch';
import { BuildArgs } from '.';
import { getPostCssConfigSync } from './postcss';
interface DTsFile {
/** In a d.ts file this is the AST for the actual program */
externalModuleIndicator: ts.SourceFile;
}
interface TypescriptInternals {
/** Options that a solution builder with pass through to the program */
commonOptionsWithBuild: {
/** The name of the flag */
name: string;
}[];
}
interface WithAddDiagnostic {
/** A function to add a diagnostic error to the compilation */
addDiagnostic: (diagnostics: ts.Diagnostic) => void;
}
const CSS_EXTENSION_REGEX = /\.css['"]$/;
const FORMAT_HOST = {
/** Implement ts compiler getCurrentDirectory */
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
/** Implement ts compiler getNewLine */
getNewLine: () => ts.sys.newLine,
/** Implement ts compiler getCanonicalFileName */
getCanonicalFileName: (filename: string) =>
ts.sys.useCaseSensitiveFileNames ? filename : filename.toLowerCase(),
};
/** Determine the relative file name to the file */
function resolveCssPath(cssPath: string, { fileName }: ts.SourceFile): string {
const resolvedPath = cssPath.substring(1, cssPath.length - 1);
if (resolvedPath.startsWith('.')) {
const sourcePath = fileName;
return path.resolve(path.dirname(sourcePath), resolvedPath);
}
return resolvedPath;
}
/** Find a path relative to wherever the script was ran */
function relativeFile(file: ts.SourceFile) {
return {
...file,
fileName: path.relative(
process.env.INIT_CWD || process.cwd(),
file.fileName
),
};
}
/** Find and process all the css files in a typescript AST */
async function processCss(
processor: postcss.Processor,
project: ts.BuildInvalidedProject<ts.EmitAndSemanticDiagnosticsBuilderProgram>
) {
const ignore = ['node_modules', '.d.ts'];
const files = project
.getSourceFiles()
.filter((f) => !ignore.find((i) => f.fileName.includes(i)));
const pendingCssResults = new Map<string, postcss.LazyResult>();
const cssPromises = files.map(async (file) => {
const styles = new Map<string, Record<string, string>>();
const results: [string, postcss.LazyResult][] = [];
// 1. Find all css imports
file.forEachChild((node) => {
// Dealing with "import * as css from 'foo.css'" only since namedImports variables get mangled
if (
ts.isImportDeclaration(node) &&
node.importClause &&
CSS_EXTENSION_REGEX.test(node.moduleSpecifier.getText())
) {
const { importClause } = node;
const cssPath = resolveCssPath(node.moduleSpecifier.getText(), file);
// This is the "foo" from "import * as foo from 'foo.css'"
const importVar = importClause.getText();
if (!fs.existsSync(cssPath)) {
throw new Error(
ts.formatDiagnosticsWithColorAndContext(
[
{
category: 1,
messageText: `Could not find file ${node.moduleSpecifier.getText()}"`,
start: node.moduleSpecifier.getStart(),
length: node.moduleSpecifier.getText().length,
file: relativeFile(file),
code: 1337,
},
],
FORMAT_HOST
)
);
}
const pending = pendingCssResults.get(cssPath);
if (pending) {
results.push([importVar, pending]);
} else {
const promise = processor.process(fs.readFileSync(cssPath, 'utf8'), {
from: cssPath,
});
pendingCssResults.set(cssPath, promise);
results.push([importVar, promise]);
}
}
});
// 2. Process the css with postcss to an object containing all the classNames
await Promise.all(
results.map(async ([name, promise]) => {
const result = await promise;
styles.set(
name,
result.root ? extractICSS(result.root, false).icssExports : {}
);
})
);
return [file.fileName, styles] as const;
});
// 3. Return a map of ts sources file => styles in file
return new Map(await Promise.all(cssPromises));
}
/**
* Builds type definition for your source files. Will only emit definitions.
* Also tracks usage of css classnames and provides type errors.
*/
export default class TypescriptCompiler {
private logger = createLogger({ scope: 'build' });
private buildArgs: BuildArgs;
constructor(args: BuildArgs) {
this.buildArgs = args;
}
/** Build the types for the project */
buildTypes = async (watch: boolean) => {
const isTrace = getLogLevel() === 'trace';
if (!fs.existsSync(path.join(process.cwd(), 'tsconfig.json'))) {
this.logger.debug('No tsconfig.json found, skipping type build.');
return;
}
this.logger.trace('Generating Types...');
const ignoredPatterns = [
'**/*.snippet.*',
...(Array.isArray(this.buildArgs.ignore)
? this.buildArgs.ignore
: [this.buildArgs.ignore]),
];
/** Determine if a file should not be type-checked or emitted */
const isIgnored = (file: string) =>
ignoredPatterns.some((pattern) => minimatch(file, pattern));
try {
const diagnostics: ts.Diagnostic[] = [];
const host = ts.createSolutionBuilderHost(
{
...ts.sys,
writeFile(fileName, content) {
if (isIgnored(fileName)) {
return;
}
fs.writeFileSync(fileName, content);
},
readFile(fileName, encoding = 'utf8') {
if (fs.existsSync(fileName)) {
let content = fs.readFileSync(fileName, encoding);
if (isIgnored(fileName)) {
// Don't type check stories
content = '// @ts-nocheck';
}
return content;
}
},
},
undefined,
(d) => diagnostics.push(d),
(d) => this.logger.trace(d.messageText)
);
// The following options are not public but we want to override them
((ts as unknown) as TypescriptInternals).commonOptionsWithBuild.push(
{ name: 'emitDeclarationOnly' },
{ name: 'declarationMap' },
{ name: 'outDir' }
);
const solution = ts.createSolutionBuilder(host, ['./tsconfig.json'], {
verbose: isTrace,
listEmittedFiles: isTrace,
outDir: this.buildArgs.outputDirectory || '',
incremental: true,
declarationMap: true,
emitDeclarationOnly: true,
});
const postcssConfig = getPostCssConfigSync({
cwd: getMonorepoRoot(),
useModules: false,
reportError: false,
});
const cssProcessor = postcss([
...postcssConfig.plugins,
postcssIcssSelectors({
mode: 'local',
/** Create the scope for the css selectors */
generateScopedName: (name) => name,
}),
]);
let project = solution.getNextInvalidatedProject();
while (project) {
let css = new Map<string, Map<string, Record<string, string>>>();
if ('getSourceFiles' in project) {
css = await processCss(cssProcessor, project);
}
project.done(undefined, undefined, {
afterDeclarations: [this.findStyleUsage(css)],
});
project = solution.getNextInvalidatedProject();
}
if (diagnostics.length > 0) {
const formattedDiagnostics = ts.formatDiagnosticsWithColorAndContext(
diagnostics
.sort((a, b) => (a.start || 0) - (b.start || 0))
.map((d) => ({
...d,
file: d.file ? relativeFile(d.file) : undefined,
})),
FORMAT_HOST
);
throw new Error(formattedDiagnostics);
}
this.logger.complete('Generated Types');
} catch (e) {
this.logger.error('\n');
// If we don't do this there is a weird space on the first line of the errors
// eslint-disable-next-line no-console
console.log(e.message);
this.logger.debug(e.stack);
this.logger.error('Failed to generate types');
if (!watch) {
process.exit(1);
}
}
};
private findStyleUsage(
css: Map<string, Map<string, Record<string, string>>>
) {
return (
ctx: ts.TransformationContext
): ts.Transformer<ts.SourceFile | ts.Bundle> => (sf) => {
if (!('fileName' in sf)) {
return sf;
}
const styles = css.get(sf.fileName) || new Map();
/** Recursively visit all the node in the ts file looking for css usage and imports */
const visitor: ts.Visitor = (node: ts.Node): ts.Node => {
if (ts.isPropertyAccessExpression(node)) {
const variable = node.expression.getText();
const style = styles.get(variable);
if (style) {
const classes = Object.keys(style);
const camelClasses = classes.map((s) => camelCase(s));
const className = node.name.getText();
const exists = Boolean(
classes.includes(className) || camelClasses.includes(className)
);
if (!exists) {
// We're using internal APIs.... *shh*
((ctx as unknown) as WithAddDiagnostic).addDiagnostic({
category: 1,
messageText: `ClassName "${className}" does not exists in "${variable}"`,
start: node.name.getStart(),
length: className.length,
file: sf,
code: 1337,
});
}
}
}
return ts.visitEachChild(node, visitor, ctx);
};
// Must visit source file instead of the .d.ts file, since that contains no actual code
const external = ((sf as unknown) as DTsFile).externalModuleIndicator;
ts.visitNode(external ? external.parent : sf, visitor);
return sf;
};
}
}