Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add error code extract and transform #138

Merged
merged 11 commits into from
Jul 11, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
],
"dependencies": {
"@babel/core": "^7.4.4",
"@babel/helper-module-imports": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.4.4",
"@babel/polyfill": "^7.4.4",
"@babel/preset-env": "^7.4.4",
Expand All @@ -40,6 +41,8 @@
"babel-plugin-dev-expression": "^0.2.1",
"babel-plugin-transform-async-to-promises": "^0.8.11",
"babel-plugin-transform-rename-import": "^2.3.0",
"babel-traverse": "^6.26.0",
"babylon": "^6.18.0",
"camelcase": "^5.0.0",
"chalk": "^2.4.2",
"cross-env": "5.2.0",
Expand Down
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ export const paths = {
testsSetup: resolveApp('test/setupTests.ts'),
appRoot: resolveApp('.'),
appSrc: resolveApp('src'),
appErrorsJson: resolveApp('./codes.json'),
appDist: resolveApp('dist'),
};
13 changes: 13 additions & 0 deletions src/createRollupConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ import resolve from 'rollup-plugin-node-resolve';
import sourceMaps from 'rollup-plugin-sourcemaps';
import typescript from 'rollup-plugin-typescript2';
import shebangPlugin from '@jaredpalmer/rollup-plugin-preserve-shebang';
import { extractErrors } from './errors/extractErrors';

const replacements = [{ original: 'lodash', replacement: 'lodash-es' }];

const errorCodeOpts = {
errorMapFilePath: paths.appRoot + '/codes.json',
};

const babelOptions = (
format: 'cjs' | 'es' | 'umd',
target: 'node' | 'browser'
Expand Down Expand Up @@ -46,6 +51,7 @@ const babelOptions = (
require.resolve('@babel/plugin-proposal-class-properties'),
{ loose: true },
],
require('./errors/transformErrorMessages'),
].filter(Boolean),
});

Expand All @@ -61,6 +67,7 @@ export function createRollupConfig(
tsconfig?: string;
}
) {
const findAndRecordErrorCodes = extractErrors(errorCodeOpts);
return {
// Tell Rollup the entry point to the package
input: opts.input,
Expand Down Expand Up @@ -110,6 +117,12 @@ export function createRollupConfig(
exports: 'named',
},
plugins: [
{
transform(source: any) {
findAndRecordErrorCodes(source);
return source;
},
},
resolve({
mainFields: [
'module',
Expand Down
3 changes: 3 additions & 0 deletions src/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ declare module 'rollup-plugin-babel';
declare module 'rollup-plugin-size-snapshot';
declare module 'rollup-plugin-terser';
declare module 'camelcase';
declare module 'babel-traverse';
declare module 'babylon';
declare module '@babel/helper-module-imports';
7 changes: 7 additions & 0 deletions src/errors/Error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function ReactError(message) {
const error = new Error(message);
error.name = 'Invariant Violation';
return error;
}

export default ReactError;
25 changes: 25 additions & 0 deletions src/errors/ErrorProd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* 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.
*
*/

// Do not require this module directly! Use a normal error constructor with
// template literal strings. The messages will be converted to ReactError during
// build, and in production they will be minified.

function ReactErrorProd(code) {
let url = 'https://reactjs.org/docs/error-decoder.html?invariant=' + code;
for (let i = 1; i < arguments.length; i++) {
url += '&args[]=' + encodeURIComponent(arguments[i]);
}
return new Error(
`Minified React error #${code}; visit ${url} for the full message or ` +
'use the non-minified dev environment for full errors and additional ' +
'helpful warnings. '
);
}

export default ReactErrorProd;
13 changes: 13 additions & 0 deletions src/errors/evalToString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function evalToString(ast: any): string {
switch (ast.type) {
case 'StringLiteral':
return ast.value;
case 'BinaryExpression': // `+`
if (ast.operator !== '+') {
throw new Error('Unsupported binary operator ' + ast.operator);
}
return evalToString(ast.left) + evalToString(ast.right);
default:
throw new Error('Unsupported type ' + ast.type);
}
}
105 changes: 105 additions & 0 deletions src/errors/extractErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* 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.
*/
'use strict';

import fs from 'fs';
import path from 'path';
import * as babylon from 'babylon';
import traverse from 'babel-traverse';
import { invertObject } from './invertObject';
import { evalToString } from './evalToString';

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`.'
);
}

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(
path.join(__dirname, path.basename(errorMapFilePath)),
swyxio marked this conversation as resolved.
Show resolved Hide resolved
'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) {
fs.writeFileSync(
errorMapFilePath,
JSON.stringify(invertObject(existingErrorMap), null, 2) + '\n',
'utf-8'
);
}

return function extractErrors(source: any) {
transform(source);
flush();
};
}
24 changes: 24 additions & 0 deletions src/errors/invertObject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* turns
* { 'MUCH ERROR': '0', 'SUCH WRONG': '1' }
* into
* { 0: 'MUCH ERROR', 1: 'SUCH WRONG' }
*/

type Dict = { [key: string]: any };

export function invertObject(
targetObj: Dict /* : ErrorMap */
) /* : ErrorMap */ {
const result: Dict = {};
const mapKeys = Object.keys(targetObj);

// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (const originalKey of mapKeys) {
const originalVal = targetObj[originalKey];

result[originalVal] = originalKey;
}

return result;
}
Loading