forked from stdlib-js/stdlib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform.js
More file actions
268 lines (237 loc) · 7.03 KB
/
transform.js
File metadata and controls
268 lines (237 loc) · 7.03 KB
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
/**
* @license Apache-2.0
*
* Copyright (c) 2023 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
var startsWith = require( '@stdlib/string/starts-with' );
var contains = require( '@stdlib/assert/contains' );
var replace = require( '@stdlib/string/replace' );
var pkg2id = require( '@stdlib/error/tools/pkg2id' );
var msg2id = require( '@stdlib/error/tools/msg2id' );
var ENV = require( '@stdlib/process/env' );
// VARIABLES //
var debug = logger( 'scripts:transform' );
var pkg = ENV[ 'STDLIB_PKG' ];
var inputSourceMap = JSON.parse( readFileSync( ENV[ 'STDLIB_INPUT_SOURCE_MAP' ], 'utf8' ) );
var prefix = pkg2id( pkg );
var RE_INDENT = /(\r?\n) +/g;
var ERROR_NAMES = [
'Error',
'AssertionError',
'RangeError',
'ReferenceError',
'SyntaxError',
'TypeError',
'URIError'
];
// MAIN //
/**
* Transforms a file for a production build.
*
* ## Notes
*
* - This code is adapted from the respective stdlib [GitHub Action][1].
*
* [1]: https://github.com/stdlib-js/transform-errors-action
*
* @param {Object} fileInfo - file information
* @param {Object} api - JSCodeshift API
* @returns {Object} transformed file
*/
function transformer( fileInfo, api ) {
var formatRequire;
var replacement;
var formatVar;
var nRequires;
var requires;
var code;
var root;
var out;
var id;
var j;
j = api.jscodeshift;
root = j( fileInfo.source );
// We only need to keep a single "use strict" directive as all files are concatenated into a single bundle...
root
.find( j.ExpressionStatement, {
'expression': {
'type': 'Literal',
'value': 'use strict'
}
})
.filter( dropFirst )
.remove();
root
.find( j.VariableDeclarator )
.filter( onStringFormat )
.forEach( assignFormatVar );
requires = root.find( j.CallExpression, {
'callee': {
'name': 'require',
'type': 'Identifier'
}
});
debug( 'Transforming file: %s', fileInfo.path );
root
.find( j.Literal )
.forEach( onStringLiteral );
requires.forEach( rewriteRequire );
root
.find(j.Node)
.forEach( deleteComment );
out = root.toSource({
'quote': 'single',
'lineTerminator': '\n',
'inputSourceMap': inputSourceMap
});
return replace( out, RE_INDENT, '\n' );
/**
* Tests whether a variable declaration is for the `@stdlib/string-format` require.
*
* @private
* @param {Object} path - AST node path
* @returns {boolean} boolean indicating whether a variable declaration is for the `@stdlib/string-format` require
*/
function onStringFormat( path ) {
var node = path.node;
return node.init &&
node.init.type === 'CallExpression' &&
node.init.callee.name === 'require' &&
node.init.arguments[0].value === '@stdlib/string-format';
}
/**
* Assigns the variable name for the `@stdlib/string-format` require.
*
* @private
* @param {Object} path - AST node path
* @returns {void}
*/
function assignFormatVar( path ) {
formatVar = path.node.id.name;
}
/**
* Returns false if the node index is equal to zero and true otherwise.
*
* @private
* @param {Object} path - AST node path
* @param {number} idx - node index
* @returns {boolean} boolean indicating whether to keep the node
*/
function dropFirst( path, idx ) {
return idx !== 0;
}
/**
* Deletes the comments associated with a given node.
*
* @private
* @param {Object} path - AST node path
* @returns {void}
*/
function deleteComment( path ) {
var i;
if ( path.node.comments ) {
for ( i = 0; i < path.node.comments.length; i++ ) {
if ( contains( path.node.comments[ i ].value, '@license Apache-2.0' ) ) {
path.node.comments[ i ].value = '* @license Apache-2.0 ';
}
}
}
}
/**
* Rewrites a `require` statement to include the `/dist` directory if the module being required starts with `@stdlib`.
*
* @private
* @param {Object} path - AST node path
* @returns {void}
*/
function rewriteRequire( path ) {
if ( startsWith( path.value.arguments[0].value, '@stdlib' ) ) {
path.value.arguments[0].value += '/dist';
}
}
/**
* Callback invoked upon finding a string literal.
*
* @private
* @param {Object} path - AST node path
* @returns {void}
*/
function onStringLiteral( path ) {
if ( path.value.value === '@stdlib/string-format' ) {
debug( 'Replacing `@stdlib/string-format` with `@stdlib/error-tools-fmtprodmsg`...' );
j( path )
.replaceWith( j.stringLiteral( '@stdlib/error-tools-fmtprodmsg' ) );
}
// If the string literal is inside a NewExpression for an error, replace the string literal with the error message...
else if (
// Case: new Error( format( '...', ... ) )
path.parent.parent.value.type === 'NewExpression' &&
ERROR_NAMES.indexOf( path.parent.parent.value.callee.name ) !== -1
) {
id = msg2id( path.value.value );
if ( id ) {
code = prefix + id;
debug( 'Replacing format string "'+path.value.value+'" with error code "'+code+'"...' );
j( path )
.replaceWith( j.stringLiteral( code ) );
}
}
else if (
// Case: new Error( '...' )
path.parent.value.type === 'NewExpression' &&
ERROR_NAMES.indexof( path.parent.value.callee.name ) !== -1
) {
id = msg2id( path.value.value );
if ( id ) {
code = prefix + id;
debug( 'Replacing string literal "'+path.value.value+'" with error code "'+code+'"...' );
// Replace with call to `format` with the error code...
replacement = j.callExpression(j.identifier( formatVar ), [
j.stringLiteral( code )
]);
j( path ).replaceWith( replacement );
// Add `require` call to `@stdlib/error-tools-fmtprodmsg` if not already present...
nRequires = requires.size();
debug( 'Found ' + nRequires + ' `require` calls...' );
if ( !requires.some( hasRequire ) ) {
formatRequire = j.variableDeclaration('var', [
j.variableDeclarator(j.identifier( formatVar ), j.callExpression(j.identifier( 'require' ), [
j.stringLiteral( '@stdlib/error-tools-fmtprodmsg' )
]))
]);
debug( 'Adding `require` call to `@stdlib/error-tools-fmtprodmsg`...' );
j( root.find( j.Declaration ).at( 0 ).get() ).insertBefore( formatRequire );
}
}
}
}
/**
* Tests whether a path is a require call for `@stdlib/error-tools-fmtprodmsg`.
*
* @private
* @param {Object} path - AST node path
* @returns {boolean} boolean indicating whether a path is a require call for `@stdlib/error-tools-fmtprodmsg`
*/
function hasRequire( path ) {
return path.value.callee.name === 'require' &&
path.value.arguments[ 0 ].value === '@stdlib/error-tools-fmtprodmsg';
}
}
// EXPORTS //
module.exports = transformer;