diff --git a/.gitignore b/.gitignore index 57872d0..bc8a670 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -/vendor/ +.idea/* \ No newline at end of file diff --git a/README.md b/README.md index 7a5f8c7..3dd0be2 100644 --- a/README.md +++ b/README.md @@ -9,38 +9,41 @@ This is simply compress your final out of Larvel Application and serve to the br ### How to activate this compression middleware in your application -Update your `app/Http/Kernel.php` file with below line - -~~~php -protected $middleware = [ - ... - \Vrkansagara\Http\Middleware\AfterMiddleware::class, - ... -]; +Add the ServiceProvider to the providers array in `config/app.php` + +```php + Vrkansagara\LaraOutPress\ServiceProvider::class, +``` + +Copy the package config to your local config with the publish command: + +```shell +php artisan vendor:publish --provider="Vrkansagara\LaraOutPress\ServiceProvider" +``` + +Enable on single environment `.env` + +~~~bash + VRKANSAGARA_COMPRESS_ENVIRONMENT='${APP_ENV}' ~~~ -Add your target environment into `.env` +Enable on multiple environment `.env` + ~~~bash - VRKANSAGARA_COMPRESS_ENVIRONMENT='prod,testing,dev,local' - - OR - - VRKANSAGARA_COMPRESS_ENVIRONMENT='${APP_ENV}' + VRKANSAGARA_COMPRESS_ENVIRONMENT='prod,testing,dev,local' ~~~ -If you want to see how much you compress on each page, set bellow line in `.env` +Enable this compressor by placing bellow code in `.env` file. ~~~bash - VRKANSAGARA_COMPRESS_DEBUG = 0 + VRKANSAGARA_COMPRESS_ENABLED = true ~~~ - ### Display usage on each page. Set ` $debug = 1; ` in ` AfterMiddleware.php ` - ### TO Do List - [x] Compress browser output. @@ -53,8 +56,9 @@ Set ` $debug = 1; ` in ` AfterMiddleware.php ` ### Task - [x] Add analytics before compress and after compress. +- [x] Migrate code to laravel package format. ### Code Assumption This code is developed with the mind set of each request is filtered by this middleware. So most of the code will not be flexi. -Improvement and suggestion are always welcome. +Improvement and suggestion are always welcome. \ No newline at end of file diff --git a/composer.json b/composer.json index e7d114a..0f07343 100644 --- a/composer.json +++ b/composer.json @@ -20,10 +20,41 @@ }, "autoload": { "psr-4": { - "Vrkansagara\\": "src/" - } + "Vrkansagara\\LaraOutPress\\": "src/" + }, + "files": [ + "src/helper.php" + ] }, "support": { - "email": "vrkansagara@gmail.com" + "email": "vrkansagara@gmail.com", + "issues": "https://github.com/vrkansagara/LaraOutPress/issues", + "source": "https://github.com/vrkansagara/LaraOutPress" + }, + "minimum-stability": "dev", + "prefer-stable": true, + "extra": { + "laravel": { + "branch-alias": { + "dev-master": "develop" + }, + "providers": [ + "Vrkansagara\\LaraOutPress\\ServiceProvider" + ], + "aliases": { + "LaraOutPress": "Vrkansagara\\LaraOutPress\\Facade" + } + } + }, + "require": { + "php": ">=7.0" + }, + "require-dev": { + "laravel/framework": "5.5.x" + }, + "scripts": { + "post-autoload-dump": [ + "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump" + ] } } diff --git a/config/laraoutpress.php b/config/laraoutpress.php new file mode 100644 index 0000000..d6ae1cf --- /dev/null +++ b/config/laraoutpress.php @@ -0,0 +1,18 @@ + env('VRKANSAGARA_COMPRESS_ENABLED', false), + + 'debug' => env('VRKANSAGARA_COMPRESS_DEBUG', false), + + 'target_environment' => env('VRKANSAGARA_COMPRESS_ENVIRONMENT', '') + +]; diff --git a/src/Facade.php b/src/Facade.php new file mode 100644 index 0000000..34dae9b --- /dev/null +++ b/src/Facade.php @@ -0,0 +1,18 @@ + + * @license https://opensource.org/licenses/BSD-3-Clause New BSD License + */ + +class Facade extends \Illuminate\Support\Facades\Facade +{ + /** + * {@inheritDoc} + */ + protected static function getFacadeAccessor() + { + return LaraOutPress::class; + } +} \ No newline at end of file diff --git a/src/LraOutPress.php b/src/LraOutPress.php new file mode 100644 index 0000000..c81fda1 --- /dev/null +++ b/src/LraOutPress.php @@ -0,0 +1,127 @@ + + * @license https://opensource.org/licenses/BSD-3-Clause New BSD License + */ +class LaraOutPress +{ + + /** + * The Laravel application instance. + * + * @var \Illuminate\Foundation\Application + */ + protected $app; + + /** + * Normalized Laravel Version + * + * @var string + */ + protected $version; + + /** + * True when enabled, false disabled an null for still unknown + * + * @var bool + */ + protected $enabled; + + + /** + * @var null + */ + protected $config; + + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * @param string $version + */ + public function setVersion($version) + { + $this->version = $version; + } + + /** + * @return \Illuminate\Foundation\Application + */ + public function getApp() + { + return $this->app; + } + + /** + * @param \Illuminate\Foundation\Application $app + */ + public function setApp($app) + { + $this->app = $app; + } + + + /** + * @param Application $app + */ + public function __construct($app = null) + { + if (!$app) { + $app = app(); //Fallback when $app is not given + } + $this->setApp($app); + $this->setConfig(); + $this->setEnabled(); + $this->setVersion($app->version()); + } + + /** + * @return null + */ + public function getConfig() + { + return $this->config; + } + + /** + * @param null $config + */ + public function setConfig() + { + $applicationConfig = $this->app['config']; + $this->config = $applicationConfig->get('laraoutpress'); + } + + /** + * @return bool + */ + public function isEnabled() + { + return $this->enabled; + } + + /** + * @return bool + */ + public function setEnabled() + { + if ($this->enabled === null) { + $config = $this->config; + $configEnabled = value($config['enabled']); + $this->enabled = ($configEnabled && !$this->app->runningInConsole()) ? $configEnabled : false; + } + return $this->enabled; + } + + +} \ No newline at end of file diff --git a/src/Http/Middleware/AfterMiddleware.php b/src/Middleware/AfterMiddleware.php similarity index 66% rename from src/Http/Middleware/AfterMiddleware.php rename to src/Middleware/AfterMiddleware.php index d7dd54c..398930b 100644 --- a/src/Http/Middleware/AfterMiddleware.php +++ b/src/Middleware/AfterMiddleware.php @@ -1,51 +1,76 @@ + * @copyright Copyright (c) 2015-2019 Vallabh Kansagara * @license https://opensource.org/licenses/BSD-3-Clause New BSD License */ -namespace Vrkansagara\Http\Middleware; use Closure; +use Vrkansagara\LaraOutPress\LaraOutPress; class AfterMiddleware { public $bufferOldSize; + public $bufferNewSize; - public $debug = 0; + + + /** + * @var LaraOutPress + */ + protected $laraOutPress; + + /** + * Create a new middleware instance. + * AfterMiddleware constructor. + * + * @param LaraOutPress $laraOutPress + */ + public function __construct(LaraOutPress $laraOutPress) + { + $this->laraOutPress = $laraOutPress; + } + /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { + if (!$this->laraOutPress->isEnabled()) { + return $next($request); + } + $config = $this->laraOutPress->getConfig(); + $isDebug = $config['debug']; + $targetEnvironment = explode(',', $config['target_environment']); + $appEnvironment = getenv('APP_ENV'); + + $response = $next($request); + + $buffer = $response->getContent(); - $isDebug = null !== getenv('VRKANSAGARA_COMPRESS_DEBUG') - ? getenv('VRKANSAGARA_COMPRESS_DEBUG') - : 0; if ($isDebug) { $this->debug = 1; + $this->bufferOldSize = strlen($buffer); } - $targetEnvironment = explode( - ',', getenv('VRKANSAGARA_COMPRESS_ENVIRONMENT') - ); - $appEnvironment = getenv('APP_ENV'); - if ( ! in_array($appEnvironment, $targetEnvironment)) { + + if (!in_array($appEnvironment, $targetEnvironment)) { return $next($request); } - $response = $next($request); - $buffer = $response->getContent(); - $this->bufferOldSize = strlen($buffer); - $whiteSpaceRules = array( - '/(\s)+/s' => '\\1',// shorten multiple whitespace sequences - "#>\s+<#" => ">\n<", // Strip excess whitespace using new line - "#\n\s+<#" => "\n<",// strip excess whitespace using new line + + $whiteSpaceRules = array( + '/(\s)+/s' => '\\1',// shorten multiple whitespace sequences + "#>\s+<#" => ">\n<", // Strip excess whitespace using new line + "#\n\s+<#" => "\n<",// strip excess whitespace using new line '/\>[^\S ]+/s' => '>', // Strip all whitespaces after tags, except space '/[^\S ]+\ '<',// strip whitespaces before tags, except space @@ -59,31 +84,32 @@ public function handle($request, Closure $next) */ // '/\s+(?![^<>]*>)/x' => '', //Remove all whitespaces except content between html tags. //MOST DANGEROUS ); - $commentRules = array( + $commentRules = array( "//ms" => '',// Remove all html comment., ); - $replaceWords = array( + $replaceWords = array( //OldWord will be replaced by the NewWord // '/\bOldWord\b/i' =>'NewWord' // OldWord <-> NewWord DO NOT REMOVE THIS LINE. {REFERENCE LINE} ); - $allRules = array_merge( + $allRules = array_merge( $replaceWords, $commentRules, $whiteSpaceRules ); - $buffer = $this->compressJscript($buffer); - $buffer = preg_replace( + $buffer = $this->compressJscript($buffer); + $buffer = preg_replace( array_keys($allRules), array_values($allRules), $buffer ); $this->bufferNewSize = strlen($buffer); - if ($this->debug) { - $old = $this->formatSizeUnits($this->bufferOldSize); - $new = $this->formatSizeUnits($this->bufferNewSize); + + if ($isDebug) { + $old = $this->formatSizeUnits($this->bufferOldSize); + $new = $this->formatSizeUnits($this->bufferNewSize); $percent = round( ($this->bufferNewSize / $this->bufferOldSize) * 100, 2 ); $buffer - .= <<< EOF + .= <<< EOF Before : $old
After : $new
@@ -140,7 +166,7 @@ public static function compress($buffer) * %ix */ $regexRemoveWhiteSpace - = '%(?>[^\S ]\s*| \s{2,})(?=(?:(?:[^<]++| <(?!/?(?:textarea|pre)\b))*+)(?:<(?>textarea|pre)\b|\z))%ix'; + = '%(?>[^\S ]\s*| \s{2,})(?=(?:(?:[^<]++| <(?!/?(?:textarea|pre)\b))*+)(?:<(?>textarea|pre)\b|\z))%ix'; $new_buffer = preg_replace($regexRemoveWhiteSpace, '', $buffer); // We are going to check if processing has working if ($new_buffer === null) { @@ -152,7 +178,7 @@ public static function compress($buffer) public function formatSizeUnits($size) { - $base = log($size) / log(1024); + $base = log($size) / log(1024); $suffix = array('', 'KB', 'MB', 'GB', 'TB'); $f_base = floor($base); @@ -167,43 +193,43 @@ public function compressJscript($buffer) // remove comments from ' strings '#\"([^\n\"]*?)/\*([^\n\"]*)\"#' => '"\1/"+\'\'+"*\2"', // remove comments from " strings - '#/\*.*?\*/#s' => "",// strip C style comments - '#[\r\n]+#' => "\n", + '#/\*.*?\*/#s' => "",// strip C style comments + '#[\r\n]+#' => "\n", // remove blank lines and \r's - '#\n([ \t]*//.*?\n)*#s' => "\n", + '#\n([ \t]*//.*?\n)*#s' => "\n", // strip line comments (whole line only) - '#([^\\])//([^\'"\n]*)\n#s' => "\\1\n", + '#([^\\])//([^\'"\n]*)\n#s' => "\\1\n", // strip line comments // (that aren't possibly in strings or regex's) - '#\n\s+#' => "\n",// strip excess whitespace - '#\s+\n#' => "\n",// strip excess whitespace - '#(//[^\n]*\n)#s' => "\\1\n", + '#\n\s+#' => "\n",// strip excess whitespace + '#\s+\n#' => "\n",// strip excess whitespace + '#(//[^\n]*\n)#s' => "\\1\n", // extra line feed after any comments left // (important given later replacements) - '#/([\'"])\+\'\'\+([\'"])\*#' => "/*" + '#/([\'"])\+\'\'\+([\'"])\*#' => "/*" // restore comments in strings ); - $script = preg_replace(array_keys($replace), $replace, $buffer); + $script = preg_replace(array_keys($replace), $replace, $buffer); $replace = array( "&&\n" => "&&", "||\n" => "||", - "(\n" => "(", - ")\n" => ")", - "[\n" => "[", - "]\n" => "]", - "+\n" => "+", - ",\n" => ",", - "?\n" => "?", - ":\n" => ":", - ";\n" => ";", - "{\n" => "{", + "(\n" => "(", + ")\n" => ")", + "[\n" => "[", + "]\n" => "]", + "+\n" => "+", + ",\n" => ",", + "?\n" => "?", + ":\n" => ":", + ";\n" => ";", + "{\n" => "{", // "}\n" => "}", (because I forget to put semicolons after function assignments) - "\n]" => "]", - "\n)" => ")", - "\n}" => "}", + "\n]" => "]", + "\n)" => ")", + "\n}" => "}", "\n\n" => "\n", ); - $script = str_replace(array_keys($replace), $replace, $script); + $script = str_replace(array_keys($replace), $replace, $script); return trim($script); diff --git a/src/ServiceProvider.php b/src/ServiceProvider.php new file mode 100644 index 0000000..782fd25 --- /dev/null +++ b/src/ServiceProvider.php @@ -0,0 +1,85 @@ + + * @license https://opensource.org/licenses/BSD-3-Clause New BSD License + */ + +use Vrkansagara\LaraOutPress\Middleware\AfterMiddleware; +use Illuminate\Contracts\Http\Kernel; + +class ServiceProvider extends \Illuminate\Support\ServiceProvider +{ + /** + * Indicates if loading of the provider is deferred. + * + * @var bool + */ + protected $defer = false; + + /** + * Register the service provider. + * + * @return void + */ + public function register() + { + $configPath = __DIR__ . '/../config/laraoutpress.php'; + $this->mergeConfigFrom($configPath, 'laraoutpress'); + } + + /** + * Bootstrap the application events. + * + * @return void + */ + public function boot() + { + $configPath = __DIR__ . '/../config/laraoutpress.php'; + $this->publishes([$configPath => $this->getConfigPath()], 'config'); + $this->registerMiddleware(AfterMiddleware::class); + } + + /** + * Get the active router. + * + * @return Router + */ + protected function getRouter() + { + return $this->app['router']; + } + + /** + * Get the config path + * + * @return string + */ + protected function getConfigPath() + { + return config_path('laraoutpress.php'); + } + + /** + * Publish the config file + * + * @param string $configPath + */ + protected function publishConfig($configPath) + { + $this->publishes([$configPath => config_path('laraoutpress.php')], 'config'); + } + + /** + * Register the LaraOutPress Middleware + * + * @param string $middleware + */ + protected function registerMiddleware($middleware) + { + $kernel = $this->app[Kernel::class]; + $kernel->pushMiddleware($middleware); + } + +} diff --git a/src/helper.php b/src/helper.php new file mode 100644 index 0000000..d1c5da8 --- /dev/null +++ b/src/helper.php @@ -0,0 +1,10 @@ + + * @license https://opensource.org/licenses/BSD-3-Clause New BSD License + */ + +/** + * Helper file + */ \ No newline at end of file diff --git a/vendor/google/closure-compiler/COPYING b/vendor/google/closure-compiler/COPYING new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/vendor/google/closure-compiler/COPYING @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/google/closure-compiler/README.md b/vendor/google/closure-compiler/README.md new file mode 100644 index 0000000..bd04cc7 --- /dev/null +++ b/vendor/google/closure-compiler/README.md @@ -0,0 +1,500 @@ +# [Google Closure Compiler](https://developers.google.com/closure/compiler/) + +[![Build Status](https://travis-ci.org/google/closure-compiler.svg?branch=master)](https://travis-ci.org/google/closure-compiler) +[![Open Source Helpers](https://www.codetriage.com/google/closure-compiler/badges/users.svg)](https://www.codetriage.com/google/closure-compiler) + +The [Closure Compiler](https://developers.google.com/closure/compiler/) is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls. + +## Getting Started + * [Download the latest version](https://dl.google.com/closure-compiler/compiler-latest.zip) ([Release details here](https://github.com/google/closure-compiler/wiki/Releases)) + * [Download a specific version](https://github.com/google/closure-compiler/wiki/Binary-Downloads). Also available via: + - [Maven](https://github.com/google/closure-compiler/wiki/Maven) + - [NPM](https://www.npmjs.com/package/google-closure-compiler) - includes java, native and javascript versions. + * See the [Google Developers Site](https://developers.google.com/closure/compiler/docs/gettingstarted_app) for documentation including instructions for running the compiler from the command line. + +## Options for Getting Help +1. Post in the [Closure Compiler Discuss Group](https://groups.google.com/forum/#!forum/closure-compiler-discuss). +2. Ask a question on [Stack Overflow](https://stackoverflow.com/questions/tagged/google-closure-compiler). +3. Consult the [FAQ](https://github.com/google/closure-compiler/wiki/FAQ). + +## Building it Yourself + +Note: The Closure Compiler requires [Java 8 or higher](https://www.java.com/). + +### Using [Maven](https://maven.apache.org/) + +1. Download [Maven](https://maven.apache.org/download.cgi). + +2. Add sonatype snapshots repository to `~/.m2/settings.xml`: + ```xml + + allow-snapshots + true + + + snapshots-repo + https://oss.sonatype.org/content/repositories/snapshots + false + true + + + + ``` + +3. On the command line, at the root of this project, run `mvn -DskipTests` (omit the `-DskipTests` if you want to run all the +unit tests too). + + This will produce a jar file called `target/closure-compiler-1.0-SNAPSHOT.jar`. You can run this jar + as per the [Running section](#running) of this Readme. If you want to depend on the compiler via + Maven in another Java project, use the `com.google.javascript/closure-compiler-unshaded` artifact. + + Running `mvn -DskipTests -pl externs/pom.xml,pom-main.xml,pom-main-shaded.xml` + will skip building the GWT version of the compiler. This can speed up the build process significantly. + +### Using [Eclipse](https://www.eclipse.org/) + +1. Download and open [Eclipse IDE](https://www.eclipse.org/). Disable `Project > Build automatically` during this process. +2. On the command line, at the root of this project, run `mvn eclipse:eclipse -DdownloadSources=true` to download JARs and build Eclipse project configuration. +3. Run `mvn clean` and `mvn -DskipTests` to ensure AutoValues are generated and updated. +4. In Eclipse, navigate to `File > Import > Maven > Existing Maven Projects` and browse to closure-compiler. +5. Import both closure-compiler and the nested externs project. +6. Disregard the warnings about maven-antrun-plugin and build errors. +7. Configure the project to use the [Google Eclipse style guide](https://github.com/google/styleguide/blob/gh-pages/eclipse-java-google-style.xml) +8. Edit `.classpath` in closure-compiler-parent. Delete the `` line, then add: + ```xml + + + ``` +9. Ensure the Eclipse project settings specify 1.8 compliance level in "Java Compiler". +10. Build project in Eclipse (right click on the project `closure-compiler-parent` and select `Build Project`). +11. See *Using Maven* above to build the JAR. + +## Running + +On the command line, at the root of this project, type + +``` +java -jar target/closure-compiler-1.0-SNAPSHOT.jar +``` + +This starts the compiler in interactive mode. Type + +```javascript +var x = 17 + 25; +``` + +then hit "Enter", then hit "Ctrl-Z" (on Windows) or "Ctrl-D" (on Mac or Linux) +and "Enter" again. The Compiler will respond: + +```javascript +var x=42; +``` + +The Closure Compiler has many options for reading input from a file, writing +output to a file, checking your code, and running optimizations. To learn more, +type + +``` +java -jar compiler.jar --help +``` + +More detailed information about running the Closure Compiler is available in the +[documentation](https://developers.google.com/closure/compiler/docs/gettingstarted_app). + + +### Run using Eclipse + +1. Open the class `src/com/google/javascript/jscomp/CommandLineRunner.java` or create your own extended version of the class. +2. Run the class in Eclipse. +3. See the instructions above on how to use the interactive mode - but beware of the [bug](https://stackoverflow.com/questions/4711098/passing-end-of-transmission-ctrl-d-character-in-eclipse-cdt-console) regarding passing "End of Transmission" in the Eclipse console. + + +## Compiling Multiple Scripts + +If you have multiple scripts, you should compile them all together with one +compile command. + +```bash +java -jar compiler.jar --js_output_file=out.js in1.js in2.js in3.js ... +``` + +You can also use minimatch-style globs. + +```bash +# Recursively include all js files in subdirs +java -jar compiler.jar --js_output_file=out.js 'src/**.js' + +# Recursively include all js files in subdirs, excluding test files. +# Use single-quotes, so that bash doesn't try to expand the '!' +java -jar compiler.jar --js_output_file=out.js 'src/**.js' '!**_test.js' +``` + +The Closure Compiler will concatenate the files in the order they're passed at +the command line. + +If you're using globs or many files, you may start to run into +problems with managing dependencies between scripts. In this case, you should +use the [Closure Library](https://developers.google.com/closure/library/). It +contains functions for enforcing dependencies between scripts, and Closure Compiler +will re-order the inputs automatically. + +## How to Contribute +### Reporting a bug +1. First make sure that it is really a bug and not simply the way that Closure Compiler works (especially true for ADVANCED_OPTIMIZATIONS). + * Check the [official documentation](https://developers.google.com/closure/compiler/) + * Consult the [FAQ](https://github.com/google/closure-compiler/wiki/FAQ) + * Search on [Stack Overflow](https://stackoverflow.com/questions/tagged/google-closure-compiler) and in the [Closure Compiler Discuss Group](https://groups.google.com/forum/#!forum/closure-compiler-discuss) +2. If you still think you have found a bug, make sure someone hasn't already reported it. See the list of [known issues](https://github.com/google/closure-compiler/issues). +3. If it hasn't been reported yet, post a new issue. Make sure to add enough detail so that the bug can be recreated. The smaller the reproduction code, the better. + +### Suggesting a Feature +1. Consult the [FAQ](https://github.com/google/closure-compiler/wiki/FAQ) to make sure that the behaviour you would like isn't specifically excluded (such as string inlining). +2. Make sure someone hasn't requested the same thing. See the list of [known issues](https://github.com/google/closure-compiler/issues). +3. Read up on [what type of feature requests are accepted](https://github.com/google/closure-compiler/wiki/FAQ#how-do-i-submit-a-feature-request-for-a-new-type-of-optimization). +4. Submit your request as an issue. + +### Submitting patches +1. All contributors must sign a contributor license agreement (CLA). + A CLA basically says that you own the rights to any code you contribute, + and that you give us permission to use that code in Closure Compiler. + You maintain the copyright on that code. + If you own all the rights to your code, you can fill out an + [individual CLA](https://code.google.com/legal/individual-cla-v1.0.html). + If your employer has any rights to your code, then they also need to fill out + a [corporate CLA](https://code.google.com/legal/corporate-cla-v1.0.html). + If you don't know if your employer has any rights to your code, you should + ask before signing anything. + By default, anyone with an @google.com email address already has a CLA + signed for them. +2. To make sure your changes are of the type that will be accepted, ask about your patch on the [Closure Compiler Discuss Group](https://groups.google.com/forum/#!forum/closure-compiler-discuss) +3. Fork the repository. +4. Make your changes. Check out our + [coding conventions](https://github.com/google/closure-compiler/wiki/Contributors#coding-conventions) + for details on making sure your code is in correct style. +5. Submit a pull request for your changes. A project developer will review your work and then merge your request into the project. + +## Closure Compiler License + +Copyright 2009 The Closure Compiler 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. + +## Dependency Licenses + +### Rhino + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Code Path + src/com/google/javascript/rhino, test/com/google/javascript/rhino +
URLhttps://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino
Version1.5R3, with heavy modifications
LicenseNetscape Public License and MPL / GPL dual license
DescriptionA partial copy of Mozilla Rhino. Mozilla Rhino is an +implementation of JavaScript for the JVM. The JavaScript +parse tree data structures were extracted and modified +significantly for use by Google's JavaScript compiler.
Local ModificationsThe packages have been renamespaced. All code not +relevant to the parse tree has been removed. A JsDoc parser and static typing +system have been added.
+ +### Args4j + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttp://args4j.kohsuke.org/
Version2.33
LicenseMIT
Descriptionargs4j is a small Java class library that makes it easy to parse command line +options/arguments in your CUI application.
Local ModificationsNone
+ +### Guava Libraries + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttps://github.com/google/guava
Version20.0
LicenseApache License 2.0
DescriptionGoogle's core Java libraries.
Local ModificationsNone
+ +### JSR 305 + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttps://github.com/findbugsproject/findbugs
Version3.0.1
LicenseBSD License
DescriptionAnnotations for software defect detection.
Local ModificationsNone
+ +### JUnit + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttp://junit.org/junit4/
Version4.12
LicenseCommon Public License 1.0
DescriptionA framework for writing and running automated tests in Java.
Local ModificationsNone
+ +### Protocol Buffers + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttps://github.com/google/protobuf
Version3.0.2
LicenseNew BSD License
DescriptionSupporting libraries for protocol buffers, +an encoding of structured data.
Local ModificationsNone
+ +### Truth + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttps://github.com/google/truth
Version0.32
LicenseApache License 2.0
DescriptionAssertion/Proposition framework for Java unit tests
Local ModificationsNone
+ +### Ant + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttps://ant.apache.org/bindownload.cgi
Version1.9.7
LicenseApache License 2.0
DescriptionAnt is a Java based build tool. In theory it is kind of like "make" +without make's wrinkles and with the full portability of pure java code.
Local ModificationsNone
+ +### GSON + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLhttps://github.com/google/gson
Version2.7
LicenseApache license 2.0
DescriptionA Java library to convert JSON to Java objects and vice-versa
Local ModificationsNone
+ +### Node.js Closure Compiler Externs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Code Pathcontrib/nodejs
URLhttps://github.com/dcodeIO/node.js-closure-compiler-externs
Versione891b4fbcf5f466cc4307b0fa842a7d8163a073a
LicenseApache 2.0 license
DescriptionType contracts for NodeJS APIs
Local ModificationsSubstantial changes to make them compatible with NpmCommandLineRunner.
diff --git a/vendor/google/closure-compiler/closure-compiler-v20181210.jar b/vendor/google/closure-compiler/closure-compiler-v20181210.jar new file mode 100644 index 0000000..3dd4c89 Binary files /dev/null and b/vendor/google/closure-compiler/closure-compiler-v20181210.jar differ