-
Notifications
You must be signed in to change notification settings - Fork 504
/
extractErrors.ts
154 lines (134 loc) · 4.48 KB
/
extractErrors.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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import fs from 'fs-extra';
import * as babylon from 'babylon';
import traverse from 'babel-traverse';
import { invertObject } from './invertObject';
import { evalToString } from './evalToString';
import { paths } from '../constants';
import { safeVariableName } from '../utils';
import pascalCase from 'pascal-case';
const babylonOptions = {
sourceType: 'module',
// As a parser, babylon has its own options and we can't directly
// import/require a babel preset. It should be kept **the same** as
// the `babel-plugin-syntax-*` ones specified in
// https://github.com/facebook/fbjs/blob/master/packages/babel-preset-fbjs/configure.js
plugins: [
'classProperties',
'flow',
'jsx',
'trailingFunctionCommas',
'objectRestSpread',
],
};
export function extractErrors(opts: any) {
if (!opts || !('errorMapFilePath' in opts)) {
throw new Error(
'Missing options. Ensure you pass an object with `errorMapFilePath`.'
);
}
if (!opts.name || !('name' in opts)) {
throw new Error('Missing options. Ensure you pass --name flag to tsdx');
}
if (typeof opts.extractErrors === 'boolean') {
throw new Error(
'No url passed to extractErrors flag.' +
'Ensure you pass a url, eg. `--extractErrors=https://reactjs.org/docs/error-decoder.html?invariant=`.'
);
}
const errorMapFilePath = opts.errorMapFilePath;
let existingErrorMap: any;
try {
// Using `fs.readFileSync` instead of `require` here, because `require()`
// calls are cached, and the cache map is not properly invalidated after
// file changes.
existingErrorMap = JSON.parse(fs.readFileSync(errorMapFilePath, 'utf8'));
} catch (e) {
existingErrorMap = {};
}
const allErrorIDs = Object.keys(existingErrorMap);
let currentID: any;
if (allErrorIDs.length === 0) {
// Map is empty
currentID = 0;
} else {
currentID = Math.max.apply(null, allErrorIDs as any) + 1;
}
// Here we invert the map object in memory for faster error code lookup
existingErrorMap = invertObject(existingErrorMap);
function transform(source: string) {
const ast = babylon.parse(source, babylonOptions);
traverse(ast, {
CallExpression: {
exit(astPath: any) {
if (astPath.get('callee').isIdentifier({ name: 'invariant' })) {
const node = astPath.node;
// error messages can be concatenated (`+`) at runtime, so here's a
// trivial partial evaluator that interprets the literal value
const errorMsgLiteral = evalToString(node.arguments[1]);
addToErrorMap(errorMsgLiteral);
}
},
},
});
}
function addToErrorMap(errorMsgLiteral: any) {
if (existingErrorMap.hasOwnProperty(errorMsgLiteral)) {
return;
}
existingErrorMap[errorMsgLiteral] = '' + currentID++;
}
function flush(cb?: any) {
const prettyName = pascalCase(safeVariableName(opts.name));
// Output messages to ./codes.json
fs.writeFileSync(
errorMapFilePath,
JSON.stringify(invertObject(existingErrorMap), null, 2) + '\n',
'utf-8'
);
// Ensure that the ./src/errors directory exists or create it
fs.ensureDirSync(paths.appRoot + '/errors');
// Write the error files, unless they already exist
fs.writeFileSync(
paths.appRoot + '/errors/ErrorDev.js',
`
function ErrorDev(message) {
const error = new Error(message);
error.name = 'Invariant Violation';
return error;
}
export default ErrorDev;
`,
'utf-8'
);
fs.writeFileSync(
paths.appRoot + '/errors/ErrorProd.js',
`// Do not require this module directly! Use a normal error constructor with
// template literal strings. The messages will be converted to ErrorProd during
// build, and in production they will be minified.
function ErrorProd(code) {
let url = '${opts.extractErrors}' + code;
for (let i = 1; i < arguments.length; i++) {
url += '&args[]=' + encodeURIComponent(arguments[i]);
}
return new Error(
\`Minified ${prettyName} error #$\{code}; visit $\{url} for the full message or \` +
'use the non-minified dev environment for full errors and additional ' +
'helpful warnings. '
);
}
export default ErrorProd;
`,
'utf-8'
);
}
return function extractErrors(source: any) {
transform(source);
flush();
};
}