Skip to content

Commit 05d5505

Browse files
committed
Port error extraction setup from master
1 parent 82ad636 commit 05d5505

File tree

5 files changed

+191
-2
lines changed

5 files changed

+191
-2
lines changed

errors.json

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function.",
3+
"1": "Expected the enhancer to be a function.",
4+
"2": "Expected the reducer to be a function.",
5+
"3": "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.",
6+
"4": "Expected the listener to be a function.",
7+
"5": "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.",
8+
"6": "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.",
9+
"7": "Actions must be plain objects. Use custom middleware for async actions.",
10+
"8": "Actions may not have an undefined \"type\" property. Have you misspelled a constant?",
11+
"9": "Reducers may not dispatch actions.",
12+
"10": "Expected the nextReducer to be a function.",
13+
"11": "Expected the observer to be an object.",
14+
"12": "bindActionCreators expected an object or a function, instead received . Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?",
15+
"13": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.",
16+
"14": "Reducer \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.",
17+
"15": "Reducer \"\" returned undefined when probed with a random type. Don't try to handle or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null."
18+
}

rollup.config.js

+5
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ export default [
3737
extensions,
3838
plugins: [
3939
['@babel/plugin-transform-runtime', { version: babelRuntimeVersion }],
40+
['./scripts/mangleErrors.js', { minify: false }]
4041
],
4142
babelHelpers: 'runtime'
4243
})
@@ -62,6 +63,7 @@ export default [
6263
'@babel/plugin-transform-runtime',
6364
{ version: babelRuntimeVersion, useESModules: true }
6465
],
66+
['./scripts/mangleErrors.js', { minify: false }]
6567
],
6668
babelHelpers: 'runtime'
6769
})
@@ -82,6 +84,7 @@ export default [
8284
babel({
8385
extensions,
8486
exclude: 'node_modules/**',
87+
plugins: [['./scripts/mangleErrors.js', { minify: true }]],
8588
skipPreflightCheck: true
8689
}),
8790
terser({
@@ -111,6 +114,7 @@ export default [
111114
babel({
112115
extensions,
113116
exclude: 'node_modules/**',
117+
plugins: [['./scripts/mangleErrors.js', { minify: false }]]
114118
}),
115119
replace({
116120
'process.env.NODE_ENV': JSON.stringify('development')
@@ -134,6 +138,7 @@ export default [
134138
babel({
135139
extensions,
136140
exclude: 'node_modules/**',
141+
plugins: [['./scripts/mangleErrors.js', { minify: true }]],
137142
skipPreflightCheck: true
138143
}),
139144
replace({

scripts/mangleErrors.js

+151
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
const fs = require('fs')
2+
const helperModuleImports = require('@babel/helper-module-imports')
3+
4+
/**
5+
* Converts an AST type into a javascript string so that it can be added to the error message lookup.
6+
*
7+
* Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some
8+
* adjustments
9+
*/
10+
const evalToString = ast => {
11+
switch (ast.type) {
12+
case 'StringLiteral':
13+
case 'Literal': // ESLint
14+
return ast.value
15+
case 'BinaryExpression': // `+`
16+
if (ast.operator !== '+') {
17+
throw new Error('Unsupported binary operator ' + ast.operator)
18+
}
19+
return evalToString(ast.left) + evalToString(ast.right)
20+
case 'TemplateLiteral':
21+
return ast.quasis.reduce(
22+
(concatenatedValue, templateElement) =>
23+
concatenatedValue + templateElement.value.raw,
24+
''
25+
)
26+
case 'Identifier':
27+
return ast.name
28+
default:
29+
throw new Error('Unsupported type ' + ast.type)
30+
}
31+
}
32+
33+
/**
34+
* Takes a `throw new error` statement and transforms it depending on the minify argument. Either option results in a
35+
* smaller bundle size in production for consumers.
36+
*
37+
* If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup.
38+
*
39+
* If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a
40+
* an error number index in production or the actual error message in development. This allows consumers using webpak
41+
* or another build tool to have these messages in development but have just the error index in production.
42+
*
43+
* E.g.
44+
* Before:
45+
* throw new Error("This is my error message.");
46+
* throw new Error("This is a second error message.");
47+
*
48+
* After (with minify):
49+
* throw new Error(0);
50+
* throw new Error(1);
51+
*
52+
* After: (without minify):
53+
* throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message.");
54+
* throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message.");
55+
*/
56+
module.exports = babel => {
57+
const t = babel.types
58+
// When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the
59+
// indexes do not change between builds.
60+
let errorsFiles = ''
61+
if (fs.existsSync('errors.json')) {
62+
errorsFiles = fs.readFileSync('errors.json').toString()
63+
}
64+
let errors = Object.values(JSON.parse(errorsFiles || '{}'))
65+
// This variable allows us to skip writing back to the file if the errors array hasn't changed
66+
let changeInArray = false
67+
68+
return {
69+
pre: () => {
70+
changeInArray = false
71+
},
72+
visitor: {
73+
ThrowStatement(path, file) {
74+
const arguments = path.node.argument.arguments
75+
const minify = file.opts.minify
76+
77+
if (arguments && arguments[0]) {
78+
// Skip running this logic when certain types come up:
79+
// Identifier comes up when a variable is thrown (E.g. throw new error(message))
80+
// NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed
81+
if (
82+
path.node.argument.arguments[0].type === 'Identifier' ||
83+
path.node.argument.arguments[0].type === 'NumericLiteral' ||
84+
path.node.argument.arguments[0].type === 'ConditionalExpression' ||
85+
path.node.argument.arguments[0].type === 'CallExpression'
86+
) {
87+
return
88+
}
89+
90+
const errorMsgLiteral = evalToString(path.node.argument.arguments[0])
91+
92+
if (errorMsgLiteral.includes('Super expression')) {
93+
// ignore Babel runtime error message
94+
return
95+
}
96+
97+
// Attempt to get the existing index of the error. If it is not found, add it to the array as a new error.
98+
let errorIndex = errors.indexOf(errorMsgLiteral)
99+
if (errorIndex === -1) {
100+
errors.push(errorMsgLiteral)
101+
errorIndex = errors.length - 1
102+
changeInArray = true
103+
}
104+
105+
// Import the error message function
106+
const formatProdErrorMessageIdentifier = helperModuleImports.addDefault(
107+
path,
108+
'src/utils/formatProdErrorMessage',
109+
{ nameHint: 'formatProdErrorMessage' }
110+
)
111+
112+
// Creates a function call to output the message to the error code page on the website
113+
const prodMessage = t.callExpression(
114+
formatProdErrorMessageIdentifier,
115+
[t.numericLiteral(errorIndex)]
116+
)
117+
118+
if (minify) {
119+
path.replaceWith(
120+
t.throwStatement(
121+
t.newExpression(t.identifier('Error'), [prodMessage])
122+
)
123+
)
124+
} else {
125+
path.replaceWith(
126+
t.throwStatement(
127+
t.newExpression(t.identifier('Error'), [
128+
t.conditionalExpression(
129+
t.binaryExpression(
130+
'===',
131+
t.identifier('process.env.NODE_ENV'),
132+
t.stringLiteral('production')
133+
),
134+
prodMessage,
135+
path.node.argument.arguments[0]
136+
)
137+
])
138+
)
139+
)
140+
}
141+
}
142+
}
143+
},
144+
post: () => {
145+
// If there is a new error in the array, convert it to an indexed object and write it back to the file.
146+
if (changeInArray) {
147+
fs.writeFileSync('errors.json', JSON.stringify({ ...errors }, null, 2))
148+
}
149+
}
150+
}
151+
}

src/createStore.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ export default function createStore(reducer, preloadedState, enhancer) {
126126
'You may not call store.subscribe() while the reducer is executing. ' +
127127
'If you would like to be notified after the store has been updated, subscribe from a ' +
128128
'component and invoke store.getState() in the callback to access the latest state. ' +
129-
'See https://redux.js.org/api-reference/store#subscribelistener for more details.'
129+
'See https://redux.js.org/api/store#subscribelistener for more details.'
130130
)
131131
}
132132

@@ -143,7 +143,7 @@ export default function createStore(reducer, preloadedState, enhancer) {
143143
if (isDispatching) {
144144
throw new Error(
145145
'You may not unsubscribe from a store listener while the reducer is executing. ' +
146-
'See https://redux.js.org/api-reference/store#subscribelistener for more details.'
146+
'See https://redux.js.org/api/store#subscribelistener for more details.'
147147
)
148148
}
149149

src/utils/formatProdErrorMessage.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
3+
*
4+
* Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
5+
* during build.
6+
* @param {number} code
7+
*/
8+
function formatProdErrorMessage(code) {
9+
return (
10+
`Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or ` +
11+
'use the non-minified dev environment for full errors. '
12+
)
13+
}
14+
15+
export default formatProdErrorMessage

0 commit comments

Comments
 (0)