1
0
mirror of https://github.com/S2-/minifyfromhtml.git synced 2025-08-02 20:00:05 +02:00

add some babel stuff

This commit is contained in:
s2
2018-05-05 15:35:25 +02:00
parent d17c4fe70c
commit e76e795120
604 changed files with 103725 additions and 62 deletions

87
node_modules/babel-minify/README.md generated vendored Normal file
View File

@@ -0,0 +1,87 @@
# babel-minify
Node API and CLI
[![npm](https://img.shields.io/npm/v/babel-minify.svg?maxAge=2592000)](https://www.npmjs.com/package/babel-minify)
Use `babel-minify` if you don't already use babel (as a preset) or want to run it standalone.
## Installation
```sh
npm install babel-minify --save-dev
```
## Usage
### Node API
```js
const minify = require("babel-minify");
const {code, map} = minify("input code", {
mangle: {
keepClassName: true
}
});
```
### CLI
```sh
minify input.js --out-file input.min.js --mangle.keepClassName
```
## Node API
```js
const minify = require("babel-minify");
minify(input, minifyOptions, overrides)
```
### minifyOptions
Refer [babel-preset-minify options](https://github.com/babel/minify/tree/master/packages/babel-preset-minify#options)
### overrides
+ `babel`: Custom babel
+ `minifyPreset`: Custom minify preset
+ `inputSourceMap`: Input Sourcemap
+ `sourceMaps`: [Boolean]
## CLI Options
```
minify input.js [options]
```
### Simple preset options
For simple options, use `--optionName` in CLI
Refer [preset's 1-1 options](https://github.com/babel/minify/tree/master/packages/babel-preset-minify#1-1-mapping-with-plugin) for the list of options
Example:
```
minify input.js --mangle false
```
### Nested preset options
Usage: `--optionName.featureName`
Example:
```sh
minify input.js --mangle.keepClassName --deadcode.keepFnArgs --outFile input.min.js
```
Refer the corresponding plugins to know the list of options it takes
### IO options
+ `--out-file path/to/file.min.js`: Output filename. Used only when reading from STDIN / a single input file
+ `--out-dir path/to/dir`: Output Directory.

3
node_modules/babel-minify/bin/minify.js generated vendored Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
require("../lib/cli");

213
node_modules/babel-minify/lib/cli.js generated vendored Normal file
View File

@@ -0,0 +1,213 @@
"use strict";
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _next(value) { step("next", value); } function _throw(err) { step("throw", err); } _next(); }); }; }
const yargsParser = require("yargs-parser");
const optionsParser = require("./options-parser");
const _require = require("../package.json"),
version = _require.version;
const _require2 = require("./fs"),
handleStdin = _require2.handleStdin,
handleFile = _require2.handleFile,
handleArgs = _require2.handleArgs,
isFile = _require2.isFile;
const plugins = ["booleans", "builtIns", "consecutiveAdds", "deadcode", "evaluate", "flipComparisons", "guards", "infinity", "mangle", "memberExpressions", "mergeVars", "numericLiterals", "propertyLiterals", "regexpConstructors", "removeConsole", "removeDebugger", "removeUndefined", "replace", "simplify", "simplifyComparisons", "typeConstructors", "undefinedToVoid"];
const proxies = ["keepFnName", "keepClassName", "tdz"];
const dceBooleanOpts = ["deadcode.keepFnName", "deadcode.keepFnArgs", "deadcode.keepClassName"];
const mangleBooleanOpts = ["mangle.eval", "mangle.keepFnName", "mangle.topLevel", "mangle.keepClassName"];
const mangleArrayOpts = ["mangle.exclude"];
const typeConsOpts = ["typeConstructors.array", "typeConstructors.boolean", "typeConstructors.number", "typeConstructors.object", "typeConstructors.string"];
const cliBooleanOpts = ["help", "version"];
const cliOpts = ["out-file", "out-dir"];
const alias = {
outFile: "o",
outDir: "d",
version: "V"
};
function aliasArr(obj) {
const r = Object.keys(obj).reduce((acc, val) => {
return acc.concat(val, obj[val]);
}, []);
return r;
}
function printHelpInfo({
exitCode = 0
} = {}) {
const msg = `
Usage: minify index.js [options]
IO Options:
--out-file, -o Output to a specific file
--out-dir, -d Output to a specific directory
Transform Options:
--mangle Context and scope aware variable renaming
--simplify Simplifies code for minification by reducing statements into
expressions
--booleans Transform boolean literals into !0 for true and !1 for false
--builtIns Minify standard built-in objects
--consecutiveAdds Inlines consecutive property assignments, array pushes, etc.
--deadcode Inlines bindings and tries to evaluate expressions.
--evaluate Tries to evaluate expressions and inline the result. Deals
with numbers and strings
--flipComparisons Optimize code for repetition-based compression algorithms
such as gzip.
--infinity Minify Infinity to 1/0
--memberExpressions Convert valid member expression property literals into plain
identifiers
--mergeVars Merge sibling variables into single variable declaration
--numericLiterals Shortening of numeric literals via scientific notation
--propertyLiterals Transform valid identifier property key literals into identifiers
--regexpConstructors Change RegExp constructors into literals
--removeConsole Removes all console.* calls
--removeDebugger Removes all debugger statements
--removeUndefined Removes rval's for variable assignments, return arguments from
functions that evaluate to undefined
--replace Replaces matching nodes in the tree with a given replacement node
--simplifyComparisons Convert === and !== to == and != if their types are inferred
to be the same
--typeConstructors Minify constructors to equivalent version
--undefinedToVoid Transforms undefined into void 0
Other Options:
--keepFnName Preserve Function Name (useful for code depending on fn.name)
--keepClassName Preserve Class Name (useful for code depending on c.name)
--keepFnArgs Don't remove unused fn arguments (useful for code depending on fn.length)
--tdz Detect usages of variables in the Temporal Dead Zone
Nested Options:
To use nested options (plugin specfic options) simply use the pattern
--pluginName.featureName.
For example,
minify index.js --mangle.keepClassName --deadcode.keepFnArgs --outFile index.min.js
`;
log(msg, exitCode);
}
function log(msg, exitCode = 0) {
process.stdout.write(msg + "\n");
process.exit(exitCode);
}
function error(err) {
if (err.file) {
process.stderr.write("Error minifying file: " + err.file + "\n");
}
process.stderr.write(err + "\n");
process.exit(1);
}
function getArgv(args) {
const presetOpts = [...plugins, ...proxies];
const booleanOpts = [...presetOpts, ...dceBooleanOpts, ...mangleBooleanOpts, ...typeConsOpts, ...cliBooleanOpts];
const booleanDefaults = booleanOpts.reduce((acc, cur) => Object.assign(acc, {
[cur]: void 0
}), {});
const arrayOpts = [...mangleArrayOpts];
const arrayDefaults = arrayOpts.reduce((acc, cur) => Object.assign(acc, {
[cur]: []
}), {});
return yargsParser(args, {
boolean: booleanOpts,
array: mangleArrayOpts,
default: Object.assign({}, arrayDefaults, booleanDefaults),
alias,
configuration: {
"dot-notation": false
}
});
}
function getMinifyOpts(argv) {
const inputOpts = Object.keys(argv).filter(key => {
if (Array.isArray(argv[key])) return argv[key].length > 0;
return argv[key] !== void 0;
}).reduce((acc, cur) => Object.assign(acc, {
[cur]: argv[cur]
}), {});
const invalidOpts = validate(inputOpts);
if (invalidOpts.length > 0) {
throw new Error("Invalid Options passed: " + invalidOpts.join(","));
}
const options = optionsParser(inputOpts); // delete unncessary options to minify preset
delete options["_"];
delete options.d;
delete options["out-dir"];
delete options.o;
delete options["out-file"];
delete options.outFile;
delete options.outDir;
return options;
}
function validate(opts) {
const allOpts = [...plugins, ...proxies, ...dceBooleanOpts, ...mangleBooleanOpts, ...typeConsOpts, ...mangleArrayOpts, ...cliBooleanOpts, ...cliOpts, ...aliasArr(alias)];
return Object.keys(opts).filter(opt => opt !== "_" && allOpts.indexOf(opt) === -1);
}
function runStdin(argv, options) {
if (argv._.length > 0) {
throw new Error("Reading input from STDIN. Cannot take file params");
}
return handleStdin(argv.outFile, options);
}
function runFile(argv, options) {
const file = argv._[0]; // prefer outFile
if (argv.outFile) {
return handleFile(file, argv.outFile, options);
} else if (argv.outDir) {
return handleArgs([file], argv.outDir, options);
} else {
// prints to STDOUT
return handleFile(file, void 0, options);
}
}
function runArgs(argv, options) {
return handleArgs(argv._, argv.outDir, options);
}
function run(_x) {
return _run.apply(this, arguments);
}
function _run() {
_run = _asyncToGenerator(function* (args) {
const argv = getArgv(args); // early exits
if (argv.help) printHelpInfo();
if (argv.V) log(version);
const options = getMinifyOpts(argv);
if (argv._.length <= 0) {
if (!process.stdin.isTTY) {
return runStdin(argv, options);
} else {
return printHelpInfo({
exitCode: 1
});
}
} else if (argv._.length === 1 && (yield isFile(argv._[0]))) {
return runFile(argv, options);
} else {
return runArgs(argv, options);
}
});
return _run.apply(this, arguments);
}
run(process.argv.slice(2)).catch(e => error(e));

238
node_modules/babel-minify/lib/fs.js generated vendored Normal file
View File

@@ -0,0 +1,238 @@
"use strict";
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _next(value) { step("next", value); } function _throw(err) { step("throw", err); } _next(); }); }; }
const fs = require("fs");
const path = require("path");
const readdir = require("fs-readdir-recursive");
const promisify = require("util.promisify");
const mkdirp = promisify(require("mkdirp"));
const minify = require("./");
const EXTENSIONS = [".js", ".mjs"];
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);
const lstat = promisify(fs.lstat);
class MinifyFileError extends Error {
constructor(message, {
file
}) {
super(message);
this.file = file;
}
} // set defaults
const readFile = file => readFileAsync(file, {
encoding: "utf-8"
});
const writeFile = (file, data) => writeFileAsync(file, data, {
encoding: "utf-8"
});
function isJsFile(file) {
return EXTENSIONS.some(ext => path.extname(file) === ext);
}
function isDir(_x) {
return _isDir.apply(this, arguments);
}
function _isDir() {
_isDir = _asyncToGenerator(function* (p) {
try {
return (yield lstat(p)).isDirectory();
} catch (e) {
return false;
}
});
return _isDir.apply(this, arguments);
}
function isFile(_x2) {
return _isFile.apply(this, arguments);
} // the async keyword simply exists to denote we are returning a promise
// even though we don't use await inside it
function _isFile() {
_isFile = _asyncToGenerator(function* (p) {
try {
return (yield lstat(p)).isFile();
} catch (e) {
return false;
}
});
return _isFile.apply(this, arguments);
}
function readStdin() {
return _readStdin.apply(this, arguments);
}
function _readStdin() {
_readStdin = _asyncToGenerator(function* () {
let code = "";
const stdin = process.stdin;
return new Promise(resolve => {
stdin.setEncoding("utf8");
stdin.on("readable", () => {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
stdin.on("end", () => {
resolve(code);
});
});
});
return _readStdin.apply(this, arguments);
}
function handleStdin(_x3, _x4) {
return _handleStdin.apply(this, arguments);
}
function _handleStdin() {
_handleStdin = _asyncToGenerator(function* (outputFilename, options) {
const _minify = minify((yield readStdin()), options),
code = _minify.code;
if (outputFilename) {
yield writeFile(outputFilename, code);
} else {
process.stdout.write(code);
}
});
return _handleStdin.apply(this, arguments);
}
function handleFile(_x5, _x6, _x7) {
return _handleFile.apply(this, arguments);
}
function _handleFile() {
_handleFile = _asyncToGenerator(function* (filename, outputFilename, options) {
const _minify2 = minify((yield readFile(filename)), options),
code = _minify2.code;
if (outputFilename) {
yield writeFile(outputFilename, code);
} else {
process.stdout.write(code);
}
});
return _handleFile.apply(this, arguments);
}
function handleFiles(_x8, _x9, _x10) {
return _handleFiles.apply(this, arguments);
}
function _handleFiles() {
_handleFiles = _asyncToGenerator(function* (files, outputDir, options) {
if (!outputDir) {
throw new TypeError(`outputDir is falsy. Got "${outputDir}"`);
}
return Promise.all(files.map(file => {
const outputFilename = path.join(outputDir, path.basename(file));
return mkdirp(path.dirname(outputFilename)).then(() => handleFile(file, outputFilename, options)).catch(e => Promise.reject(new MinifyFileError(e.message, {
file
})));
}));
});
return _handleFiles.apply(this, arguments);
}
function handleDir(_x11, _x12, _x13) {
return _handleDir.apply(this, arguments);
}
function _handleDir() {
_handleDir = _asyncToGenerator(function* (dir, outputDir, options) {
if (!outputDir) {
throw new TypeError(`outputDir is falsy`);
} // relative paths
const files = readdir(dir);
return Promise.all(files.filter(file => isJsFile(file)).map(file => {
const outputFilename = path.join(outputDir, file);
const inputFilename = path.join(dir, file);
return mkdirp(path.dirname(outputFilename)).then(() => handleFile(inputFilename, outputFilename, options)).catch(e => Promise.reject(new MinifyFileError(e.message, {
file: inputFilename
})));
}));
});
return _handleDir.apply(this, arguments);
}
function handleArgs(_x14, _x15, _x16) {
return _handleArgs.apply(this, arguments);
}
function _handleArgs() {
_handleArgs = _asyncToGenerator(function* (args, outputDir, options) {
const files = [];
const dirs = [];
if (!Array.isArray(args)) {
throw new TypeError(`Expected Array. Got ${JSON.stringify(args)}`);
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const arg = _step.value;
if (yield isFile(arg)) {
files.push(arg);
} else if (yield isDir(arg)) {
dirs.push(arg);
} else {
throw new TypeError(`Input "${arg}" is neither a file nor a directory.`);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return Promise.all([handleFiles(files, outputDir, options), ...dirs.map(dir => handleDir(dir, outputDir, options))]);
});
return _handleArgs.apply(this, arguments);
}
module.exports = {
handleFile,
handleStdin,
handleFiles,
handleDir,
handleArgs,
isFile,
isDir,
isJsFile,
readFile,
writeFile
};

30
node_modules/babel-minify/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
"use strict";
const babelCore = require("@babel/core");
const babelPresetMinify = require("babel-preset-minify");
module.exports = function babelMinify(input, // Minify options passed to minifyPreset
// defaults are handled in preset
options = {}, // overrides and other options
{
minified = true,
inputSourceMap,
sourceMaps = false,
sourceType = "script",
// to override the default babelCore used
babel = babelCore,
// to override the default minify preset used
minifyPreset = babelPresetMinify
} = {}) {
return babel.transformSync(input, {
babelrc: false,
configFile: false,
presets: [[minifyPreset, options]],
comments: false,
inputSourceMap,
sourceMaps,
minified,
sourceType
});
};

82
node_modules/babel-minify/lib/options-parser.js generated vendored Normal file
View File

@@ -0,0 +1,82 @@
"use strict";
const DELIMITTER = ".";
module.exports = function parseOpts(argv) {
return dotsToObject(argv);
};
/**
* Converts and Object of the form - {key<dot-notation>: value} to deep object
* following rules of minify preset options
*
* A preset option can be `true` | `object` which enables the particular plugin
* `false` disables the plugin
*
* @param input - An Object with dot-notation keys
*/
function dotsToObject(input) {
const dots = Object.keys(input).map(key => [...key.split(DELIMITTER), input[key]]); // sort to ensure dot notation occurs after parent key
dots.sort((a, b) => {
if (a.length === b.length) {
return a[0] > b[0];
}
return a.length > b.length;
});
const obj = {};
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = dots[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const parts = _step.value;
add(obj, ...parts);
} // make object
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
function add(o, first, ...rest) {
if (rest.length < 1) {
// something went wrong
throw new Error("Option Parse Error");
} else if (rest.length === 1) {
// there is only a key and a value
// for example: mangle: true
o[first] = rest[0];
} else {
// create the current path and recurse if the plugin is enabled
if (!hop(o, first) || o[first] === true) {
// if the plugin is enabled
o[first] = {};
}
if (o[first] !== false) {
// if the plugin is NOT disabled then recurse
add(o[first], ...rest);
}
}
}
return obj;
}
function hop(o, key) {
return Object.prototype.hasOwnProperty.call(o, key);
}

61
node_modules/babel-minify/package.json generated vendored Normal file
View File

@@ -0,0 +1,61 @@
{
"_from": "babel-minify",
"_id": "babel-minify@0.4.1",
"_inBundle": false,
"_integrity": "sha1-9+QHlrtavnPmbMl0Ipw3ZhP+Xsc=",
"_location": "/babel-minify",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "babel-minify",
"name": "babel-minify",
"escapedName": "babel-minify",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/babel-minify/-/babel-minify-0.4.1.tgz",
"_shasum": "f7e40796bb5abe73e66cc974229c376613fe5ec7",
"_spec": "babel-minify",
"_where": "/home/s2/Documents/Code/minifyfromhtml",
"author": {
"name": "amasad"
},
"bin": {
"babel-minify": "./bin/minify.js",
"minify": "./bin/minify.js"
},
"bugs": {
"url": "https://github.com/babel/minify/issues"
},
"bundleDependencies": false,
"dependencies": {
"@babel/core": "^7.0.0-beta.46",
"babel-preset-minify": "^0.4.1",
"fs-readdir-recursive": "^1.1.0",
"mkdirp": "^0.5.1",
"util.promisify": "^1.0.0",
"yargs-parser": "^10.0.0"
},
"deprecated": false,
"description": "✂️ An ES6+ aware minifier based on the Babel toolchain (beta)",
"homepage": "https://github.com/babel/minify#readme",
"keywords": [
"babel-minify",
"babel-preset",
"minify"
],
"license": "MIT",
"main": "lib/index.js",
"name": "babel-minify",
"repository": {
"type": "git",
"url": "https://github.com/babel/minify/tree/master/packages/babel-minify"
},
"version": "0.4.1"
}