Class Compressor

java.lang.Object
com.iizix.js.build.Compressor

public class Compressor extends Object
Compressor class to compress CSS and JavaScript.

The JavaScript compressor uses Google closure-compiler-v20261108, run as a process.

CSS is minified by lightningcss, run through Node, first: when the environment variable NODE_HOME is set and lightningcss is installed globally for that Node (LightningCSS; one Node process per call, for all its files). Where either is not so, CSSCompressor minifies it in this JVM: the fallback, logged as a warning that says which requirement is not met and who called, once per distinct caller (CSSMinifiers). Both keep the meaning of the CSS. A stylesheet lightningcss refuses fails the call and is not handed to the fallback.

Author:
Christopher Mindus
  • Method Details

    • getInstance

      public static Compressor getInstance(File root) throws IOException
      Returns the singleton of the compressor.
      Parameters:
      root - The root for the webserver, i.e. "js/root" in this project.
      Returns:
      The compressor.
      Throws:
      IOException - If the compressor is not found.
    • invokeCSSCompressor

      public File invokeCSSCompressor(File htmlFile, List<String> files) throws IOException
      Compresses the CSS files an HTML file lists into one temporary file.

      The files are minified each on its own - by lightningcss through Node, one process for all of them, or by CSSCompressor in this JVM where Node cannot be used - and written one after the other in the order of the list.

      Parameters:
      htmlFile - The HTML file.
      files - The list of files to compress.
      Returns:
      The file output, a temporary file that must be deleted to clean-up.
      Throws:
      IOException - For I/O errors, or a file that cannot be compressed (the message names it).
    • invokeCSSCompressor

      public void invokeCSSCompressor(File inputCSS, File outputCSS) throws IOException
      Compresses a single CSS file.
      Parameters:
      inputCSS - The input CSS file.
      outputCSS - The output CSS file.
      Throws:
      IOException - For I/O errors, or a file that cannot be compressed (the message names it).
    • invokeCSSCompressor

      public void invokeCSSCompressor(File currDir, File outputCSS, List<String> files) throws IOException
      Invokes the CSS compressor in the specified directory.
      Parameters:
      currDir - The current directory.
      outputCSS - The output CSS file.
      files - The list of CSS files.
      Throws:
      IOException - For I/O errors, or a file that cannot be compressed (the message names it).
    • invokeCSSCompressorWithNode

      public void invokeCSSCompressorWithNode(File inputCSS, File outputCSS) throws IOException
      Compresses a single CSS file with lightningcss through Node only, and only with the version of lightningcss IIZI pins: where Node cannot be used, the call fails and names the requirement that is not met, it does not fall back to CSSCompressor; where the lightningcss installed is another version, the call fails and names both versions. For a build that may require Node: www.zip of RuntimeBuilderCompressor, whose bytes are versioned.
      Parameters:
      inputCSS - The input CSS file.
      outputCSS - The output CSS file.
      Throws:
      IOException - For I/O errors, a file lightningcss refuses (the message names the file, the line and the column), when lightningcss cannot be used through Node (the message says which requirement is not met), or when it is another version than the pinned one (the message names both).
    • compressCSS

      public static String compressCSS(String css) throws IOException
      Compresses CSS: by lightningcss through Node first, and where Node cannot be used by CSSCompressor in this JVM.
      Parameters:
      css - The CSS to compress.
      Returns:
      The compressed CSS.
      Throws:
      IOException - If the CSS is null or cannot be compressed (the message says what is wrong and where).
    • compressCSS

      public static String compressCSS(String css, String sourceName) throws IOException
      Compresses CSS and names its source in a failure: by lightningcss through Node first (one process for the call), and where Node cannot be used by CSSCompressor in this JVM. The CSS is never returned unminified, except with the debug switch of this class on.
      Parameters:
      css - The CSS to compress.
      sourceName - The name of the source of the CSS for the message of a failure, typically the path of its file, null for none.
      Returns:
      The compressed CSS.
      Throws:
      IOException - If the CSS is null or cannot be compressed (the message names the source and says what is wrong and where).
    • getCSSNodeProblem

      public static String getCSSNodeProblem()
      Tells why lightningcss cannot be used through Node in this JVM: which of the two requirements is not met (NODE_HOME set and a Node; lightningcss installed globally for that Node).
      Returns:
      The reason on one line, null when it can be used.
    • requireNodeForCSS

      public static void requireNodeForCSS() throws IOException
      Fails when lightningcss cannot be used through Node in this JVM, or is not the version IIZI pins (BuildEnvironment.VER_LIGHTNINGCSS): for a build that must not fall back and whose bytes are versioned, before it starts its work.
      Throws:
      IOException - If it cannot be used (the message says which requirement is not met), or if it is another version than the pinned one (the message names both versions and where the installed one is).
    • invokeJSCompressor

      public File invokeJSCompressor(File htmlFile, List<String> files, Compressor.Level optimizeLevel) throws IOException
      Invokes the Google Closure Compiler and returns the output.

      Options:

       --angular_pass                         : Generate $inject properties for AngularJS for functions annotated with @ngInject
       
       --charset VAL                          : Input and output charset for all files. By default, we accept UTF-8 as input and output US_ASCII
       
       --checks-only                          : Don't generate output. Run checks, but no compiler passes.
       
       --closure_entry_point VAL              : Entry points to the program. Must be goog.provide'd symbols. Any goog.provide'd symbols that are not a transitive
                                                dependency of the entry points will be removed. Files without goog.provides, and their dependencies, will
                                                always be left in. If any entry points are specified, then the manage_closure_dependencies option
                                                will be set to true and all files will be sorted in dependency order.
                                                
       --common_js_entry_module VAL           : Root of your common JS dependency hierarchy. Your main script.
       
       --common_js_module_path_prefix VAL     : Path prefix to be removed from CommonJS module names.
       
       --compilation_level (-O) VAL           : Specifies the compilation level to use. Options: WHITESPACE_ONLY, SIMPLE, ADVANCED
       
       --conformance_configs VAL              : A list of JS Conformance configurations in text protocol buffer format.
       
       --create_renaming_reports              : If true, variable renaming and property renaming report files will be produced as {binary name}_vars_renaming_report.out
                                                and {binary name}_props_renaming_report.out. Note that this flag cannot be used in conjunction with either variable_renaming_report
                                                or property_renaming_report
                                                
       --create_source_map VAL                : If specified, a source map file mapping the generated source files back to the original source file will be output to the specified path. The
                                                %outname% placeholder will expand to the name of the output file that the source map corresponds to.
                                                
       --dart_pass                            : Rewrite Dart Dev Compiler output to be compiler-friendly.
       
       --debug                                : Enable debugging options
       
       --define (--D, -D) VAL                 : Override the value of a variable annotated @define. The format is [name][=[val]], where [name] is the name of a @define variable and [val]
                                                is a boolean, number, or a single-quoted string that contains no single quotes. If [=[val]] is omitted, the variable is marked true
                                                
       --env [BROWSER | CUSTOM]               : Determines the set of builtin externs to load. Options: BROWSER, CUSTOM. Defaults to BROWSER.
       
       --export_local_property_definitions    : Generates export code for local properties marked with @export
       
       --externs VAL                          : The file containing JavaScript externs. You may specify multiple
       
       --extra_annotation_name VAL            : A whitelist of tag names in JSDoc. You may specify multiple
       
       --flagfile VAL                         : A file containing additional command-line options.
       
       --formatting [PRETTY_PRINT | PRINT_INPUT_DELIMITER | SINGLE_QUOTES] :
                                                Specifies which formatting options, if any, should be applied to the output JS. Options: PRETTY_PRINT, PRINT_INPUT_DELIMITER, SINGLE_QUOTES
                                                
       --generate_exports                     : Generates export code for those marked with @export
       
       --help                                 : Displays this message on stdout and exit
       
       --instrumentation_template VAL         : A file containing an instrumentation template.
       
       --js VAL                               : The JavaScript filename. You may specify multiple. The flag name is optional, because args are interpreted as files by default. You may also use
                                                minimatch-style glob patterns. For example, use --js='**.js' --js='!**_test.js' to recursively include all js files that do not end in _test.js
                                                
       --js_module_root VAL                   : Path prefixes to be removed from ES6 & CommonJS modules.
       
       --js_output_file VAL                   : Primary output filename. If not specified, output is written to stdout
       
       --jscomp_error VAL                     : Make the named class of warnings an error. Options: accessControls, ambiguousFunctionDecl, checkEventfulObjectDisposal, checkRegExp, checkTypes,
                                                checkVars, conformanceViolations, const, constantProperty, deprecated, deprecatedAnnotations, duplicateMessage, es3, es5Strict, externsValidation,
                                                fileoverviewTags, globalThis, inferredConstCheck, internetExplorerChecks, invalidCasts, misplacedTypeAnnotation, missingGetCssName, missingProperties,
                                                missingProvide, missingRequire, missingReturn, msgDescriptionsnewCheckTypes, nonStandardJsDocs, reportUnknownTypes, suspiciousCode, strictModuleDepCheck,
                                                typeInvalidation, undefinedNames, undefinedVars, unknownDefines, unnecessaryCasts, uselessCode, useOfGoogBase, visibility.
                                                '*' adds all supported.
                                                
       --jscomp_off VAL                       : Turn off the named class of warnings. Options: accessControls, ambiguousFunctionDecl, checkEventfulObjectDisposal,
                                                checkRegExp, checkTypes, checkVars, conformanceViolations, const, constantProperty, deprecated, deprecatedAnnotations, duplicateMessage,
                                                es3, es5Strict, externsValidation, fileoverviewTags, globalThis, inferredConstCheck, internetExplorerChecks, invalidCasts, misplacedTypeAnnotation,
                                                missingGetCssName, missingProperties, missingProvide, missingRequire, missingReturn, msgDescriptionsnewCheckTypes, nonStandardJsDocs, reportUnknownTypes,
                                                suspiciousCode, strictModuleDepCheck, typeInvalidation, undefinedNames, undefinedVars, unknownDefines, unnecessaryCasts, uselessCode,
                                                useOfGoogBase, visibility.
                                                '*' adds all supported.
                                                
       --jscomp_warning VAL                   : Make the named class of warnings a normal warning. Options: accessControls, ambiguousFunctionDecl, checkEventfulObjectDisposal, checkRegExp, checkTypes,
                                                checkVars, conformanceViolations, const, constantProperty, deprecated, deprecatedAnnotations, duplicateMessage, es3, es5Strict, externsValidation,
                                                fileoverviewTags, globalThis, inferredConstCheck, internetExplorerChecks, invalidCasts, misplacedTypeAnnotation, missingGetCssName, missingProperties,
                                                missingProvide, missingRequire, missingReturn, msgDescriptionsnewCheckTypes, nonStandardJsDocs, reportUnknownTypes, suspiciousCode, strictModuleDepCheck,
                                                typeInvalidation, undefinedNames, undefinedVars, unknownDefines, unnecessaryCasts, uselessCode, useOfGoogBase, visibility.
                                                '*' adds all supported.
                                                
       --jszip VAL                            : The JavaScript zip filename. You may specify multiple.
       
       --language_in VAL                      : Sets what language spec that input sources conform.
                                                Options: ECMASCRIPT3 (default), ECMASCRIPT5, ECMASCRIPT5_STRICT, ECMASCRIPT6, ECMASCRIPT6_STRICT, ...
                                                
       --language_out VAL                     : Sets what language spec the output should conform to. If omitted, defaults to the value of language_in.
                                                Options: ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT, ...
                                                
       --logging_level VAL                    : The logging level (standard java.util.logging.Level values) for Compiler progress. Does not control errors or
                                                warnings for the JavaScript code under compilation
                                                
       --manage_closure_dependencies          : Automatically sort dependencies so that a file that goog.provides symbol X will always come before a file that
                                                goog.requires symbol X. If an input provides symbols, and those symbols are never required, then that input
                                                will not be included in the compilation.
                                                
       --module VAL                           : A JavaScript module specification. The format is [name]:[num-js-files][:[[dep],...][:]]]. Module names must be unique. Each dep is the name of a
                                                module that this module depends on. Modules must be listed in dependency order, and JS source files must be listed in the corresponding order.
                                                Where --module flags occur in relation to --js flags is unimportant. [num-js-files] may be set to 'auto' for the first module if it has no
                                                dependencies. Provide the value 'auto' to trigger module creation from CommonJSmodules.
                                                
       --module_output_path_prefix VAL        : Prefix for filenames of compiled JS modules. [module-name].js will be appended to this prefix. Directories will be created as needed.
                                                Use with --module
                                                
       --module_wrapper VAL                   : An output wrapper for a JavaScript module (optional). The format is [name]:[wrapper]. The module name must correspond with a module
                                                specified using --module. The wrapper must contain %s as the code placeholder. The %basename% placeholder can also be used to substitute the base
                                                name of the module output file.
                                                
       --new_type_inf                         : Checks for type errors using the new type inference algorithm.
       
       --only_closure_dependencies            : Only include files in the transitive dependency of the entry points (specified by closure_entry_point).
                                                Files that do not provide dependencies will be removed. This supersedes manage_closure_dependencies
                                                
       --output_manifest VAL                  : Prints out a list of all the files in the compilation. If --manage_closure_dependencies is on, this will not include files that got dropped
                                                because they were not required. The %outname% placeholder expands to the JS output file. If you're using modularization, using %outname% will
                                                create a manifest for each module.
                                                
       --output_module_dependencies VAL       : Prints out a JSON file of dependencies between modules.
       
       --output_wrapper VAL                   : Interpolate output into this string at the place denoted by the marker token %output%. Use marker token %output|jsstring% to do js string
                                                escaping on the output.
                                                
       --output_wrapper_file VAL              : Loads the specified file and passes the file contents to the --output_wrap per flag, replacing the value if it exists.
       
       --polymer_pass                         : Rewrite Polymer classes to be compiler-friendly.
       
       --print_ast                            : Prints a dot file describing the internal abstract syntax tree and exits
       
       --print_pass_graph                     : Prints a dot file describing the passes that will get run and exits
       
       --print_tree                           : Prints out the parse tree and exits
       
       --process_closure_primitives           : Processes built-ins from the Closure library, such as goog.require(), goog.provide(), and goog.exportSymbol(). True by default.
       
       --process_common_js_modules            : Process CommonJS modules to a concatenable form.
       
       --process_jquery_primitives            : Processes built-ins from the Jquery library, such as jQuery.fn and jQuery.extend()
       
       --property_renaming_report VAL         : File where the serialized version of the property renaming map produced should be saved
       
       --rename_prefix_namespace VAL          : Specifies the name of an object that will be used to store all non-extern globals
       
       --source_map_format [DEFAULT | V3]     : The source map format to produce. Options are V3 and DEFAULT, which are equivalent.
       
       --source_map_input VAL                 : Source map locations for input files, separated by a '|', (i.e. input-file-path|input-source-map)
       
       --source_map_location_mapping VAL      : Source map location mapping separated by a '|' (i.e. filesystem-path|webserver-path)
       
       --summary_detail_level N               : Controls how detailed the compilation summary is. Values: 0 (never print summary), 1 (print summary only if
                                                there are errors or warnings), 2 (print summary if the 'checkTypes' diagnostic  group is enabled, see
                                                --jscomp_warning), 3 (always print summary). The default level is 1
                                                
       --third_party                          : Check source validity but do not enforce Closure style rules and conventions
       
       --tracer_mode [ALL | RAW_SIZE | TIMING_ONLY | OFF] :
                                                Shows the duration of each compiler pass and the impact to the compiled output size.
                                                Options: ALL, RAW_SIZE, TIMING_ONLY, OFF
                                                
       --transform_amd_modules                : Transform AMD to CommonJS modules.
       
       --translations_file VAL                : Source of translated messages. Currently only supports XTB.
       
       --translations_project VAL             : Scopes all translations to the specified project.When specified, we will use different message ids so
                                                that messages in different projects can have different translations.
                                                
       --use_types_for_optimization           : Enable or disable the optimizations based on available type information. Inaccurate type annotations may
                                                result in incorrect results.
                                                
       --variable_renaming_report VAL         : File where the serialized version of the variable renaming map produced should be saved
       
       --version                              : Prints the compiler version to stdout and exit.
       
       --warning_level (-W) [QUIET | DEFAULT | VERBOSE] :
                                                Specifies the warning level to use.
                                                Options: QUIET, DEFAULT, VERBOSE
                                                
       --warnings_whitelist_file VAL          : A file containing warnings to suppress. Each line should be of the form
                                                [file-name]:[line-number]?  [warning-description]
      

      Parameters:
      htmlFile - The HTML file.
      files - The list of files to compress.
      Returns:
      The file output, a temporary file that must be deleted to clean-up.
      Throws:
      IOException - For process errors.
    • invokeJSCompressor

      public void invokeJSCompressor(File inputJS, File outputJS, Compressor.Level optimizeLevel) throws IOException
      Compresses a single JS file.
      Parameters:
      inputJS - The input JS file.
      outputJS - The output JS file.
      optimizeLevel - Optimize level: 0=WHITESPACE_ONLY, 1=SIMPLE, 2=ADVANCED.
      Throws:
      IOException - For process errors.
    • invokeJSCompressor

      public void invokeJSCompressor(File currDir, File outputJS, Compressor.Level optimizeLevel, List<String> files) throws IOException
      Invokes the JS compressor in the specified current directory.
      Parameters:
      currDir - The current directory.
      outputJS - The
      optimizeLevel - Optimize level: 0=WHITESPACE_ONLY, 1=SIMPLE, 2=ADVANCED.
      files - The JS files to compress.
      Throws:
      IOException - For process errors.
    • compressHTML

      public static void compressHTML(File inputHTML, File outputHTML, Charset charset) throws IOException
      Compresses HTML.
      Parameters:
      inputHTML - Input HTML file to compress.
      outputHTML - Output HTML file to write compressed HTML into, and can be the same as the inputHTML file in which case the uncompressed contents will be overwritten without question.
      charset - The Character set to use, null = UTF-8.
      Throws:
      IOException - For I/O errors.
    • compressHTML

      public static String compressHTML(String html) throws IOException
      Compresses HTML.
      Parameters:
      html - The HTML to compress.
      Returns:
      The compressed HTML.
      Throws:
      IOException - For compression errors or I/O errors.