UNPKG

2.09 kBJavaScriptView Raw
1'use strict';
2
3var _ = require('lodash');
4
5/** The minimal copyright header template. */
6var headerTemplate = [
7 '/**',
8 ' * @license',
9 ' * lodash lodash.com/license | Underscore.js <%= underscore.VERSION %> underscorejs.org/LICENSE',
10 ' */'
11].join('\n');
12
13/*----------------------------------------------------------------------------*/
14
15/**
16 * Post-process `source` to prepare it for deployment.
17 *
18 * @param {string} source The source to process.
19 * @param {boolean} [isMapped] Specify whether `source` has a source map.
20 * @returns {string} Returns the processed source.
21 */
22function postprocess(source, isMapped) {
23 // Add trailing semicolon.
24 source = source.replace(/[\s;]*(\n\s*\/\/.*)?\s*$/, ';$1');
25
26 // Exit early if `source` has a source map.
27 if (isMapped) {
28 return source;
29 }
30 // Remove copyright header.
31 var header = _.get(/^\/\**[\s\S]+?\*\/\n/.exec(source), 0, '');
32 source = source.replace(header, '');
33
34 // Add new copyright header.
35 source = _.template(headerTemplate)({
36 'underscore': { 'VERSION': _.get(/\bUnderscore\.js ([.$\w\-]+)/i.exec(header), 1, '') }
37 }) + '\n;' + source;
38
39 // Replace `!0` and `!1` with `true` and `false`.
40 source = source.replace(/(.)(\![01])\b/g, function(match, chr, exp) {
41 return chr + (/[$\w]/.test(chr) ? ' ' : '') + (exp == '!0');
42 });
43
44 // Flip `typeof` expressions to help optimize Safari and
45 // correct the AMD module definition for AMD build optimizers
46 // (e.g. from `"number" == typeof x` to `typeof x == "number").
47 source = source.replace(/([$\w])?("[^"]+")\s*([!=]=)\s*(typeof(?:\s*\([^)]+\)|\s+[$\w]+(?:\s*\.\s*[$\w]+)*([[(])?))/g, function(match, left, type, equality, exp, right) {
48 return right ? match : (left ? left + ' ' : '') + exp + equality + type;
49 });
50
51 // Add a space so `define` is detected by the Dojo builder.
52 source = source.replace(/(.)(define\()/, function(match, prelude, define) {
53 return prelude + (/^\S/.test(prelude) ? ' ' : '') + define;
54 });
55
56 // Consolidate multiple newlines.
57 return source.replace(/\n{2,}/g, '\n');
58}
59
60module.exports = postprocess;