public static CodeSettings GetSettings(Bundle bundle)
        {
            CodeSettings settings = new CodeSettings();

            settings.PreserveImportantComments = GetValue(bundle, "preserveImportantComments", true) == "True";
            settings.TermSemicolons = GetValue(bundle, "termSemicolons", true) == "True";

            if (GetValue(bundle, "renameLocals", true) == "False")
                settings.LocalRenaming = LocalRenaming.KeepAll;

            string evalTreatment = GetValue(bundle, "evalTreatment", "ignore");

            if (evalTreatment == "ignore")
                settings.EvalTreatment = EvalTreatment.Ignore;
            else if (evalTreatment == "makeAllSafe")
                settings.EvalTreatment = EvalTreatment.MakeAllSafe;
            else if (evalTreatment == "makeImmediateSafe")
                settings.EvalTreatment = EvalTreatment.MakeImmediateSafe;

            string outputMode = GetValue(bundle, "outputMode", "singleLine");

            if (outputMode == "multipleLines")
                settings.OutputMode = OutputMode.MultipleLines;
            else if (outputMode == "singleLine")
                settings.OutputMode = OutputMode.SingleLine;
            else if (outputMode == "none")
                settings.OutputMode = OutputMode.None;

            string indentSize = GetValue(bundle, "indentSize", 2);
            int size;
            if (int.TryParse(indentSize, out size))
                settings.IndentSize = size;

            return settings;
        }
        public static void Minify(string sourceFile, string minFile, bool isBundle)
        {
            if (sourceFile.EndsWith(".min.js"))
                return;

            try
            {
                CodeSettings settings = new CodeSettings()
                {
                    EvalTreatment = EvalTreatment.MakeImmediateSafe,
                    TermSemicolons = true,
                    PreserveImportantComments = WESettings.GetBoolean(WESettings.Keys.KeepImportantComments)
                };

                if (WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
                {
                    MinifyFileWithSourceMap(sourceFile, minFile, settings, isBundle);
                }
                else
                {
                    MinifyFile(sourceFile, minFile, settings, isBundle);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
示例#3
0
 public string Process()
 {
     CodeSettings = new CodeSettings
     {
         SourceMode = JavaScriptSourceMode.Program,
         MinifyCode = false,
     };
     var code = String.Format("function ___________({0}){{return {1};}};", Params.Select(t => t.Name).StringJoin(","), InlineCodeExpression);
     var block = ParseJavaScript(code);
     Func = ((FunctionObject)block[0]);
     var i = 0;
     foreach (var prm in Func.ParameterDeclarations)
     {
         var prm2 = prm as ParameterDeclaration;
         if (prm2 == null)
             continue;
         var binding = prm2.Binding as BindingIdentifier;
         if (binding == null)
             continue;
         var prm3 = Params[i];
         binding.VariableField.GetType().GetProperty("Name").SetValue(binding.VariableField, prm3.Code);
         i++;
     }
     if (ThisCode != null)
         Scan(Func.Body);
     var ret = Func.Body[0] as ReturnNode;
     if (ret == null)
         throw new Exception();
     var s = ToJavaScript(ret.Operand);
     return s;
 }
        private static void MinifyFile(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            Minifier minifier = new Minifier();

            if (!isBundle)
            {
                minifier.FileName = Path.GetFileName(file);
            }

            string content = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

            if (File.Exists(minFile) && content == File.ReadAllText(minFile))
                return;

            if (WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
            {
                content += "\r\n/*\r\n//# sourceMappingURL=" + Path.GetFileName(minFile) + ".map\r\n*/";
            }

            ProjectHelpers.CheckOutFileFromSourceControl(minFile);
            using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
            {
                writer.Write(content);
            }

            if (WESettings.GetBoolean(WESettings.Keys.JavaScriptEnableGzipping))
                CssSaveListener.GzipFile(file, minFile, content);
        }
        /// <summary>
        /// Get settings for the minification
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public static CodeSettings GetSettings(Config config)
        {
            CodeSettings settings = new CodeSettings();

            settings.PreserveImportantComments = GetValue(config, "preserveImportantComments") == "True";
            settings.TermSemicolons = GetValue(config, "termSemicolons") == "True";

            string evalTreatment = GetValue(config, "evanTreatment").ToLowerInvariant();

            if (evalTreatment == "ignore")
                settings.EvalTreatment = EvalTreatment.Ignore;
            else if (evalTreatment == "makeallsafe")
                settings.EvalTreatment = EvalTreatment.MakeAllSafe;
            else if (evalTreatment == "makeimmediatesafe")
                settings.EvalTreatment = EvalTreatment.MakeImmediateSafe;

            string outputMode = GetValue(config, "outputMode").ToLowerInvariant();

            if (outputMode == "multiplelines")
                settings.OutputMode = OutputMode.MultipleLines;
            else if (outputMode == "singleline")
                settings.OutputMode = OutputMode.SingleLine;
            else if (outputMode == "none")
                settings.OutputMode = OutputMode.None;

            string indentSize = GetValue(config, "indentSize");
            int size;
            if (int.TryParse(indentSize, out size))
                settings.IndentSize = size;

            return settings;
        }
    /// <summary>
    /// Minifies the specified JavaScript.
    /// </summary>
    /// <param name="resource">The JavaScript to minify.</param>
    /// <returns>The minified JavaScript, if minification was successful; otherwise, the original JavaScript with minification errors appended at the end.</returns>
    public string Minify(string resource)
    {
        if (String.IsNullOrEmpty(resource))
        {
            return resource;
        }

        var settings = new CodeSettings
        {
            AllowEmbeddedAspNetBlocks = false,
            EvalTreatment = EvalTreatment.MakeAllSafe
        };
        var minifier = new Minifier();
        try
        {
            resource = minifier.MinifyJavaScript(resource, settings);
        }
        catch
        {
            var minificationErrors = String.Join(Environment.NewLine, minifier.Errors);
            resource = AppendMinificationErrors(resource, minificationErrors);

            if (mLogErrors)
            {
                CoreServices.EventLog.LogEvent("W", "Resource minification", "JavaScriptMinificationFailed", minificationErrors);
            }
        }

        return resource;
    }
        public virtual string TransformText()
        {
            
            #line 5 "C:\Projects\sfdocsamples\SF\T4\Generar_javascript\T4Sample\JavascriptCruncher\JavascriptCruncherTemplate.tt"
 
EnvDTE.Project project = EnvDteHelper.GetProject(this.Host);
List<EnvDTE.ProjectItem> jsProjectItems = EnvDteHelper.GetJsProjectItems(project);

ScriptCruncher cruncher = new ScriptCruncher();
CodeSettings crunchSettings = new CodeSettings();
crunchSettings.CollapseToLiteral = true;
crunchSettings.LocalRenaming = LocalRenaming.CrunchAll;	
crunchSettings.StripDebugStatements=true;
foreach( EnvDTE.ProjectItem item in jsProjectItems)
{	
	string itemFileName = item.FileNames[0]; 
	string jsCode = File.ReadAllText(itemFileName);
	string jsMinified = cruncher.Crunch(jsCode, crunchSettings);
	
	EnvDteHelper.SaveMinifiedCode(item, jsMinified);
	this.WriteLine( "Processed: {0}", itemFileName);
}
this.WriteLine("done!");

            
            #line default
            #line hidden
            return this.GenerationEnvironment.ToString();
        }
示例#8
0
        public string Minify(string content)
        {
            var minifer = new Minifier();
            codeSettings = codeSettings ?? new CodeSettings();
            codeSettings.SetKnownGlobalNames(globalNames);

            return minifer.MinifyJavaScript(content, codeSettings);
        }
示例#9
0
        /// <summary>
        /// In addition to combining, also minifies the given Javascript.
        /// </summary>
        /// <returns>The combined and minified Javascript code for this bundle.</returns>
        public override string Combine()
        {
            var source = base.Combine();
            var result = string.Empty;
            var errorLines = string.Empty;
            var hasError = false;

            try
            {
                var jsParser = new JSParser(source);

                var settings = new CodeSettings()
                {
                    CombineDuplicateLiterals = true,
                    OutputMode = OutputMode.SingleLine,
                    RemoveUnneededCode = true,
                    TermSemicolons = false,
                    PreserveImportantComments = false,
                };

                jsParser.CompilerError += delegate(object sender, JScriptExceptionEventArgs args)
                {
                    // The 0 severity means errors.
                    // We can safely ignore the rest.
                    if (args.Error.Severity == 0)
                    {
                        hasError = true;
                        errorLines += string.Format("\r\n/* Javascript parse error when processing the bundle.\r\nStart: line {0} column {1}, end: line {2} column {3}.\r\nError message: {4} */",
                            args.Error.StartLine,
                            args.Error.StartColumn,
                            args.Error.EndLine,
                            args.Error.EndColumn,
                            args.Error.Message);
                    }
                };
                jsParser.UndefinedReference += delegate(object sender, UndefinedReferenceEventArgs args)
                {
                    // Let's just ignore undefined references.
                };

                var block = jsParser.Parse(settings);
                result = block.ToCode();
            }
            catch (Exception exc)
            {
                hasError = true;
                Logger.WriteException(exc);
            }

            // If there were errors, use the non-minified version and append the errors to the bottom,
            // so that the portal builder can debug it.
            if (hasError)
                result = source + "\r\n\r\n" + errorLines;

            return result;
        }
示例#10
0
        public void Minify()
        {
            var minifer = new Minifier();
            var codeSettings = new CodeSettings();

            var content = _fileSystem.BundleFiles(_files);
            var minified =  minifer.MinifyJavaScript(content, codeSettings);

            _fileSystem.File.WriteAllText(_outputPath, minified);
        }
示例#11
0
 public string Minify(string source)
 {
     CodeSettings settings = new CodeSettings
     {
         PreserveImportantComments = false,
         PreserveFunctionNames = true
     };
     Minifier doMin = new Minifier();
     string mind = doMin.MinifyJavaScript(source, settings);
     return mind;
 }
        /// <summary>
        /// Compressed the javascript content
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string Compress(string content)
        {
            // The CodeSettings object specifies how the content
            // will be minified
            var codeSettings = new CodeSettings();
            codeSettings.RemoveUnneededCode = true;
            codeSettings.LocalRenaming = LocalRenaming.CrunchAll;
            codeSettings.OutputMode = OutputMode.SingleLine;
            codeSettings.StripDebugStatements = true;
            codeSettings.IndentSize = 0;

            var value = new Minifier().MinifyJavaScript(content, codeSettings);
            return value;
        }
示例#13
0
        private static string MinifyJavaScript(string input)
        {
            Minifier minifier = new Minifier();
            CodeSettings settings = new CodeSettings();
            settings.RemoveUnneededCode = false;
            settings.PreserveFunctionNames = true;

            string output = minifier.MinifyJavaScript(input, settings);
            if (!String.IsNullOrEmpty(output))
            {
                output = output + ";";
            }

            return output;
        }
        /// <summary>
        /// Compressed the javascript content
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string Compress(string content)
        {
            // The CodeSettings object specifies how the content
            // will be minified
            var lCodeSettings = new CodeSettings();
            lCodeSettings.RemoveUnneededCode = true;
            lCodeSettings.LocalRenaming = LocalRenaming.CrunchAll;
            lCodeSettings.OutputMode = OutputMode.SingleLine;
            lCodeSettings.StripDebugStatements = true;
            lCodeSettings.W3CStrict = true;
            lCodeSettings.IndentSize = 0;

            var lValue = new ScriptCruncher().Crunch(content, lCodeSettings);
            return lValue;
        }
示例#15
0
        public static string ProcessFiles(string concatString, string rootPath)
        {
            var crunch = new ScriptCruncher();
            var cs = new CodeSettings();
            cs.RemoveUnneededCode = true;
            cs.CollapseToLiteral = true;
            cs.CombineDuplicateLiterals = true;
            cs.InlineSafeStrings = true;
            cs.StripDebugStatements = true;
            cs.LocalRenaming = LocalRenaming.CrunchAll;
            cs.OutputMode = OutputMode.SingleLine;

            var minifyJavaScript = crunch.MinifyJavaScript(concatString, cs);
            return minifyJavaScript;
        }
示例#16
0
    private static void Minify(HttpResponse response, string file, string ext)
    {
        string content = File.ReadAllText(file);
        Minifier minifier = new Minifier();

        if (ext == ".css")
        {
            CssSettings settings = new CssSettings() { CommentMode = CssComment.None };
            response.Write(minifier.MinifyStyleSheet(content, settings));
        }
        else if (ext == ".js")
        {
            CodeSettings settings = new CodeSettings() { PreserveImportantComments = false };
            response.Write(minifier.MinifyJavaScript(content, settings));
        }
    }
示例#17
0
 public void Process(BundleContext context, BundleResponse response)
 {
     var minifer = new Minifier();
     var cs = new CodeSettings {ManualRenamesProperties = false,LocalRenaming = LocalRenaming.KeepAll};
     var content = new StringBuilder();
     foreach (var file in response.Files)
     {
         var path = HttpContext.Current.Server.MapPath(file.IncludedVirtualPath);
         using (var reader = new StreamReader(path))
         {
             content.Append(reader.ReadToEnd());
         }
     }
     response.ContentType = "application/javascript";
     var responseContent = minifer.MinifyJavaScript(content.ToString(), cs);
     response.Content = responseContent;
 }
示例#18
0
        public override CombinedFileResult Parse(params string[] files)
        {
            var combined = CombineFiles(files);

            var settings = new CodeSettings {

            };

            var parser = new JSParser(combined);

            var block = parser.Parse(settings);
            var result = block.ToCode();

            var key = GenerateKey(result);

            return new CombinedFileResult {
                Content = result,
                Key = key,
            };
        }
示例#19
0
        public static string Minify(string fullFileName, string text, EnvDTE.ProjectItem projectItem,CodeSettings codeSettings)
        {
            Minifier minifier = new Minifier();

             string mini = minifier.MinifyJavaScript(text,codeSettings);

            foreach (var err in minifier.ErrorList)
            {
               if (TaskList.Instance == null)
                {
                    Console.WriteLine(string.Format("{0}({1},{2}){3}", fullFileName, 1, 1, err));
                }
                else
                {
                    TaskList.Instance.Add(projectItem.ContainingProject, Microsoft.VisualStudio.Shell.TaskErrorCategory.Error, fullFileName, err.StartLine, err.StartColumn, err.Message);
                }
            }

            return mini;
        }
示例#20
0
        private void Minify(TranslatorOutputItem output, CodeSettings minifierSettings)
        {
            if (output.OutputType != TranslatorOutputType.JavaScript)
            {
                return;
            }

            if (output.MinifiedVersion != null)
            {
                this.Log.Trace(output.Name + " has already a minified version " + output.MinifiedVersion.Name);
                return;
            }

            var formatted = output.IsEmpty ? null : output.Content.GetContentAsString();

            if (formatted == null)
            {
                this.Log.Trace("Content of " + output.Name + " is empty - skipping it a nothing to minifiy");
                return;
            }

            var minifiedName = FileHelper.GetMinifiedJSFileName(output.Name);

            var minifiedContent = this.Minify(new Minifier(), formatted, minifierSettings);

            output.MinifiedVersion = new TranslatorOutputItem
            {
                IsMinified = true,
                Name       = minifiedName,
                OutputType = output.OutputType,
                OutputKind = output.OutputKind | TranslatorOutputKind.Minified,
                Location   = output.Location,
                Content    = minifiedContent
            };

            if (this.AssemblyInfo.OutputFormatting == JavaScriptOutputType.Minified)
            {
                output.IsEmpty = true;
            }
        }
        /// <summary>
        /// Builds the required CodeSettings class needed for the Ajax Minifier.
        /// </summary>
        /// <returns></returns>
        private CodeSettings CreateCodeSettings()
        {
            var codeSettings = new CodeSettings();
            codeSettings.MinifyCode = false;
            codeSettings.OutputMode = (this.RemoveWhitespace ? OutputMode.SingleLine : OutputMode.MultipleLines);

            // MinifyCode needs to be set to true in order for anything besides whitespace removal
            // to be done on a script.
            codeSettings.MinifyCode = this.ShouldMinifyCode;
            if (this.ShouldMinifyCode)
            {

                switch (this.VariableMinification)
                {
                    case Core.VariableMinification.None:
                        codeSettings.LocalRenaming = LocalRenaming.KeepAll;
                        break;

                    case Core.VariableMinification.LocalVariablesOnly:
                        codeSettings.LocalRenaming = LocalRenaming.KeepLocalizationVars;
                        break;

                    case Core.VariableMinification.LocalVariablesAndFunctionArguments:
                        codeSettings.LocalRenaming = LocalRenaming.CrunchAll;
                        break;
                }
                // This is being set by default. A lot of scripts use eval to parse out various functions
                // and objects. These names need to be kept consistant with the actual arguments.
                codeSettings.EvalTreatment = EvalTreatment.MakeAllSafe;


                // This makes sure that function names on objects are kept exactly as they are. This is
                // so functions that other non-minified scripts rely on do not get renamed.
                codeSettings.PreserveFunctionNames = this.PreserveFunctionNames;

            }


            return codeSettings;
        }
示例#22
0
        public string Process(string includedVirtualPath, string input)
        {
            if (includedVirtualPath.EndsWith("min.js", StringComparison.OrdinalIgnoreCase))
            {
                return(input);
            }

            Minifier minifier     = new Minifier();
            var      codeSettings = new CodeSettings();

            codeSettings.EvalTreatment             = EvalTreatment.MakeImmediateSafe;
            codeSettings.PreserveImportantComments = false;

            string str = minifier.MinifyJavaScript(input, codeSettings);

            if (minifier.ErrorList.Count > 0)
            {
                return("/* " + string.Concat(minifier.Errors) + " */");
            }

            return(str);
        }
        private static void MinifyFile(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            Minifier minifier = new Minifier();

            if (!isBundle)
            {
                minifier.FileName = Path.GetFileName(file);
            }

            string content = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

            if (WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
            {
                content += Environment.NewLine + "//@ sourceMappingURL=" + Path.GetFileName(minFile) + ".map";
            }

            ProjectHelpers.CheckOutFileFromSourceControl(minFile);
            using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
            {
                writer.Write(content);
            }
        }
        private static void MinifyFile(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            Minifier minifier = new Minifier();

            if (!isBundle)
            {
                minifier.FileName = Path.GetFileName(file);
            }

            string content = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

            if (WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
            {
                content += Environment.NewLine + "//@ sourceMappingURL=" + Path.GetFileName(minFile) + ".map";
            }

            ProjectHelpers.CheckOutFileFromSourceControl(minFile);
            using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
            {
                writer.Write(content);
            }
        }
示例#25
0
    private static void Minify(HttpResponse response, string file, string ext)
    {
        string   content  = File.ReadAllText(file);
        Minifier minifier = new Minifier();

        if (ext == ".css")
        {
            CssSettings settings = new CssSettings()
            {
                CommentMode = CssComment.None
            };
            response.Write(minifier.MinifyStyleSheet(content, settings));
        }
        else if (ext == ".js")
        {
            CodeSettings settings = new CodeSettings()
            {
                PreserveImportantComments = false
            };
            response.Write(minifier.MinifyJavaScript(content, settings));
        }
    }
示例#26
0
        /// <summary>
        /// Builds the required CodeSettings class needed for the Ajax Minifier.
        /// </summary>
        /// <returns></returns>
        private CodeSettings CreateCodeSettings()
        {
            var codeSettings = new CodeSettings();

            codeSettings.MinifyCode = false;
            codeSettings.OutputMode = (this.RemoveWhitespace ? OutputMode.SingleLine : OutputMode.MultipleLines);

            // MinifyCode needs to be set to true in order for anything besides whitespace removal
            // to be done on a script.
            codeSettings.MinifyCode = this.ShouldMinifyCode;
            if (this.ShouldMinifyCode)
            {
                switch (this.VariableMinification)
                {
                case Core.VariableMinification.None:
                    codeSettings.LocalRenaming = LocalRenaming.KeepAll;
                    break;

                case Core.VariableMinification.LocalVariablesOnly:
                    codeSettings.LocalRenaming = LocalRenaming.KeepLocalizationVars;
                    break;

                case Core.VariableMinification.LocalVariablesAndFunctionArguments:
                    codeSettings.LocalRenaming = LocalRenaming.CrunchAll;
                    break;
                }
                // This is being set by default. A lot of scripts use eval to parse out various functions
                // and objects. These names need to be kept consistant with the actual arguments.
                codeSettings.EvalTreatment = EvalTreatment.MakeAllSafe;


                // This makes sure that function names on objects are kept exactly as they are. This is
                // so functions that other non-minified scripts rely on do not get renamed.
                codeSettings.PreserveFunctionNames = this.PreserveFunctionNames;
            }


            return(codeSettings);
        }
        public override async Task <IEnumerable <Asset> > TransformAsync(string extension, params Asset[] assets)
        {
            CssSettings cssSettings = new CssSettings()
            {
                CommentMode = CssComment.None
            };

            if (0 < this.MinificationOptions.Substitutions.Count)
            {
                cssSettings.ReplacementTokensApplyDefaults(this.MinificationOptions.Substitutions);
            }

            CodeSettings codeSettings = new CodeSettings()
            {
                AmdSupport                = true,
                ScriptVersion             = ScriptVersion.None,
                PreserveImportantComments = false
            };

            List <Asset> outputs = new List <Asset>();

            foreach (var asset in assets)
            {
                string code = await asset.ReadContentAsStringAsync();

                UglifyResult uglifyResult = Uglify.Css(code, cssSettings, codeSettings);

                if (uglifyResult.HasErrors)
                {
                    throw new AggregateException(uglifyResult.Errors.Select(x => new Exception(x.Message)));
                }

                Asset outputAsset = await asset.CloneWithContentAsync(uglifyResult.Code);

                outputs.Add(outputAsset);
            }
            return(outputs.AsEnumerable());
        }
        private static void MinifyFileWithSourceMap(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            string mapPath = minFile + ".map";
            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
            using (V3SourceMap sourceMap = new V3SourceMap(writer))
            {
                settings.SymbolsMap = sourceMap;

                sourceMap.StartPackage(Path.GetFileName(minFile), Path.GetFileName(mapPath));

                // This fails when debugger is attached. Bug raised with Ron Logan
                MinifyFile(file, minFile, settings, isBundle);

                sourceMap.EndPackage();

                if (!isBundle)
                {
                    ProjectHelpers.AddFileToProject(file, mapPath);
                }
            }
        }
示例#29
0
        public void ReplacementNodesJS()
        {
            // reuse the same parser object
            var parser = new JSParser();

            // default should leave tokens intact
            var settings = new CodeSettings();
            var source   = "var a = %My.Token:foo%;";
            var actual   = Parse(parser, settings, source);

            Assert.AreEqual("var a=%My.Token:foo%", actual);

            settings.ReplacementTokensApplyDefaults(new Dictionary <string, string> {
                { "my.token", "\"Now he's done it!\"" },
                { "num_token", "123" },
                { "my-json", "{\"a\": 1, \"b\": 2, \"c\": [ 1, 2, 3 ] }" },
            });
            settings.ReplacementFallbacks.Add("zero", "0");

            actual = Parse(parser, settings, source);
            Assert.AreEqual("var a=\"Now he's done it!\"", actual);

            actual = Parse(parser, settings, "var b = %Num_Token%;");
            Assert.AreEqual("var b=123", actual);

            actual = Parse(parser, settings, "var c = %My-JSON%;");
            Assert.AreEqual("var c={\"a\":1,\"b\":2,\"c\":[1,2,3]}", actual);

            actual = Parse(parser, settings, "var d = '*%MissingToken:zero%*';");
            Assert.AreEqual("var d=\"*0*\"", actual);

            actual = Parse(parser, settings, "var e = '*%MissingToken:ack%*';");
            Assert.AreEqual("var e=\"**\"", actual);

            actual = Parse(parser, settings, "var f = '*%MissingToken:%*';");
            Assert.AreEqual("var f=\"**\"", actual);
        }
示例#30
0
        /// <summary>
        /// Get settings for the minification
        /// </summary>
        /// <param name="config"></param>
        /// <returns>CodeSettings based on the config file.</returns>
        public static CodeSettings GetSettings(Config config)
        {
            LoadDefaultSettings(config, "javascript");

            CodeSettings settings = new CodeSettings();

            settings.PreserveImportantComments = GetValue(config, "preserveImportantComments", true) == "True";
            settings.TermSemicolons = GetValue(config, "termSemicolons", true) == "True";

            if (GetValue(config, "renameLocals", true) == "False")
                settings.LocalRenaming = LocalRenaming.KeepAll;

            string evalTreatment = GetValue(config, "evalTreatment", "ignore");

            if (evalTreatment.Equals("ignore", StringComparison.OrdinalIgnoreCase))
                settings.EvalTreatment = EvalTreatment.Ignore;
            else if (evalTreatment.Equals("makeAllSafe", StringComparison.OrdinalIgnoreCase))
                settings.EvalTreatment = EvalTreatment.MakeAllSafe;
            else if (evalTreatment.Equals("makeImmediateSafe", StringComparison.OrdinalIgnoreCase))
                settings.EvalTreatment = EvalTreatment.MakeImmediateSafe;

            string outputMode = GetValue(config, "outputMode", "singleLine");

            if (outputMode.Equals("multipleLines", StringComparison.OrdinalIgnoreCase))
                settings.OutputMode = OutputMode.MultipleLines;
            else if (outputMode.Equals("singleLine", StringComparison.OrdinalIgnoreCase))
                settings.OutputMode = OutputMode.SingleLine;
            else if (outputMode.Equals("none", StringComparison.OrdinalIgnoreCase))
                settings.OutputMode = OutputMode.None;

            string indentSize = GetValue(config, "indentSize", 2);
            int size;
            if (int.TryParse(indentSize, out size))
                settings.IndentSize = size;

            return settings;
        }
示例#31
0
        private static void CreateExporter(ExportPackageOptions exportPackageOptions, string path)
        {
            LogUtility.LogInfo("Creating Exporter");

            UpdateSettings();

            ModToolSettings modToolSettings = ModToolSettings.instance;
            CodeSettings    codeSettings    = CodeSettings.instance;

            string modToolDirectory = AssetUtility.GetModToolDirectory();
            string exporterPath     = Path.Combine(modToolDirectory, Path.Combine("Editor", "ModTool.Exporting.Editor.dll"));
            string fileName         = Path.Combine(path, Application.productName + " Mod Tools.unitypackage");

            List <string> assetPaths = new List <string>
            {
                AssetDatabase.GetAssetPath(modToolSettings),
                AssetDatabase.GetAssetPath(codeSettings),
                Path.Combine(modToolDirectory, Path.Combine("Editor", "ModTool.Exporting.Editor.dll")),
                Path.Combine(modToolDirectory, Path.Combine("Editor", "ModTool.Shared.Editor.dll")),
                Path.Combine(modToolDirectory, "ModTool.Shared.dll"),
                Path.Combine(modToolDirectory, "ModTool.Shared.xml"),
                Path.Combine(modToolDirectory, "ModTool.Interface.dll"),
                Path.Combine(modToolDirectory, "ModTool.Interface.xml"),
                Path.Combine(modToolDirectory, Path.Combine("Mono.Cecil", "Mono.Cecil.dll")),
                Path.Combine(modToolDirectory, Path.Combine("Mono.Cecil", "LICENSE.txt"))
            };

            List <string> assemblyPaths = GetApiAssemblyPaths(CodeSettings.apiAssemblies);

            AssetUtility.MoveAssets(assemblyPaths, modToolDirectory);
            assetPaths.AddRange(assemblyPaths);

            SetPluginEnabled(exporterPath, true);

            //TODO: ExportPackageOptions.IncludeLibraryAssets makes the package huge in Unity 2017.2
            AssetDatabase.ExportPackage(assetPaths.ToArray(), fileName, exportPackageOptions | ExportPackageOptions.IncludeLibraryAssets);
        }
        public void Process(BundleContext context, BundleResponse response)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            if (!context.EnableInstrumentation)
            {
                var codeSetting = new CodeSettings
                {
                    // Important to make it all safe, otherwise the function grapher would
                    // run to problems which extensively uses window.eval("some expression").
                    EvalTreatment             = EvalTreatment.MakeAllSafe,
                    PreserveImportantComments = false
                };

                var min     = new Minifier();
                var content = min.MinifyJavaScript(response.Content, codeSetting);

                if (min.ErrorList.Count > 0)
                {
                    GenerateErrorResponse(response, min.ErrorList);
                }
                else
                {
                    response.Content = content;
                }
            }

            response.ContentType = "text/javascript";
        }
示例#33
0
        /// <summary>
        /// Produces a code minifiction of JS content by using the Microsoft Ajax JS Minifier
        /// </summary>
        /// <param name="content">JS content</param>
        /// <param name="isInlineCode">Flag whether the content is inline code</param>
        /// <param name="encoding">Text encoding</param>
        /// <returns>Minification result</returns>
        public CodeMinificationResult Minify(string content, bool isInlineCode, Encoding encoding)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                return(new CodeMinificationResult(string.Empty));
            }

            CodeSettings originalJsSettings = isInlineCode ?
                                              _originalInlineJsSettings : _originalEmbeddedJsSettings;
            var originalMinifier = new Minifier
            {
                WarningLevel = 2
            };

            string newContent = originalMinifier.MinifyJavaScript(content, originalJsSettings);
            ICollection <ContextError> originalErrors = originalMinifier.ErrorList;

            var errors   = new List <MinificationErrorInfo>();
            var warnings = new List <MinificationErrorInfo>();

            MapErrors(originalErrors, errors, warnings);

            return(new CodeMinificationResult(newContent, errors, warnings));
        }
示例#34
0
        private static void MinifyFileWithSourceMap(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            string mapPath = minFile + ".map";

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
                using (V3SourceMap sourceMap = new V3SourceMap(writer))
                {
                    settings.SymbolsMap = sourceMap;

                    sourceMap.StartPackage(Path.GetFileName(minFile), Path.GetFileName(mapPath));

                    // This fails when debugger is attached. Bug raised with Ron Logan
                    MinifyFile(file, minFile, settings, isBundle);

                    sourceMap.EndPackage();

                    if (!isBundle)
                    {
                        MarginBase.AddFileToProject(file, mapPath);
                    }
                }
        }
示例#35
0
        /// <inheritdoc cref="IResourceMinifier.Minify" />
        public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent)
        {
            var localRenaming = (LocalRenaming)LocalRenaming.ConvertToType(
                typeof(LocalRenaming), Microsoft.Ajax.Utilities.LocalRenaming.CrunchAll);

            var outputMode = (OutputMode)OutputMode.ConvertToType(
                typeof(OutputMode), Microsoft.Ajax.Utilities.OutputMode.SingleLine);

            var evalTreatment = (EvalTreatment)EvalTreatment.ConvertToType(
                typeof(EvalTreatment), Microsoft.Ajax.Utilities.EvalTreatment.MakeAllSafe);

            var codeSettings = new CodeSettings
            {
                EvalTreatment        = evalTreatment,
                MacSafariQuirks      = MacSafariQuirks == null ? true : MacSafariQuirks.Value,
                CollapseToLiteral    = CollapseToLiteral == null ? true : CollapseToLiteral.Value,
                LocalRenaming        = localRenaming,
                OutputMode           = outputMode,
                RemoveUnneededCode   = RemoveUnneededCode == null ? true : RemoveUnneededCode.Value,
                StripDebugStatements = StripDebugStatements == null ? true : StripDebugStatements.Value
            };

            return(new Minifier().MinifyJavaScript(combinedContent, codeSettings));
        }
示例#36
0
 public SwitchParser(CodeSettings scriptSettings, CssSettings cssSettings)
 {
     // apply the switches to these two settings objects
     JSSettings = scriptSettings ?? new CodeSettings();
     CssSettings = cssSettings ?? new CssSettings();
 }
示例#37
0
 public WithScope(ActivationObject parent, CodeSettings settings)
     : base(parent, settings, ScopeType.With)
 {
     IsInWithScope = true;
 }
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
        {
            if (files == null)
            {
                return string.Empty;
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616
            var sourcePath = VirtualPathUtility.ToAbsolute(bundle.Path);
            var mapVirtualPath = string.Concat(bundle.Path, "map"); // don't use .map so it's picked up by the bundle module
            var mapPath = VirtualPathUtility.ToAbsolute(mapVirtualPath);

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcatedString = GetContentConcated(context, files);

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                var mapBuilder = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                using (var mapWriter = new StringWriter(mapBuilder))
                using (var sourceMap = new V3SourceMap(mapWriter))
                {
                    var settings = new CodeSettings()
                    {
                        EvalTreatment = EvalTreatment.MakeImmediateSafe,
                        PreserveImportantComments = false,
                        SymbolsMap = sourceMap,
                        TermSemicolons = true
                    };

                    sourceMap.StartPackage(sourcePath, mapPath);

                    var minifier = new Minifier();
                    string contentMinified = minifier.MinifyJavaScript(contentConcatedString, settings);
                    if (minifier.ErrorList.Count > 0)
                    {
                        return GenerateMinifierErrorsContent(contentConcatedString, minifier);
                    }

                    contentWriter.Write(contentMinified);
                }

                // Write the SourceMap to another Bundle
                AddContentToAdHocBundle(context, mapVirtualPath, mapBuilder.ToString());

                // Note: A current bug in AjaxMin reported by @LodewijkSioen here https://ajaxmin.codeplex.com/workitem/21834,
                // causes the MinifyJavascript method call to hang when debugger is attached if the following line is included.
                // To avoid more harm than good, don't support source mapping in this scenario until AjaxMin fixes it's bug.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    contentBuilder.Insert(0, sourceMappingDisabledMsg + "\r\n\r\n\r\n");
                }

                return contentBuilder.ToString();
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details.", ex, typeof(ScriptWithSourceMapBundleBuilder));
                return GenerateGenericErrorsContent(contentConcatedString);
            }
        }
示例#39
0
        /// <summary>
        /// Crunched JS string passed to it, returning crunched string.
        /// The ErrorList property will be set with any errors found during the minification process.
        /// </summary>
        /// <param name="source">source Javascript</param>
        /// <param name="fileName">File name to use in error reporting. Default is <c>input</c></param>
        /// <param name="codeSettings">code minification settings</param>
        /// <returns>minified Javascript</returns>
        public static UglifyResult Js(string source, string fileName = null, CodeSettings codeSettings = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            fileName     = fileName ?? "input";
            codeSettings = codeSettings ?? new CodeSettings();

            // default is an empty string
            string crunched;

            // reset the errors builder
            var errorList = new List <UglifyError>();

            // create the parser and hook the engine error event
            var parser = new JSParser();

            parser.CompilerError += (sender, e) =>
            {
                var error = e.Error;
                if (error.Severity <= codeSettings.WarningLevel)
                {
                    errorList.Add(error);
                }
            };

            var sb = StringBuilderPool.Acquire();

            try
            {
                var preprocessOnly = codeSettings.PreprocessOnly;
                using (var stringWriter = new StringWriter(sb, CultureInfo.InvariantCulture))
                {
                    if (preprocessOnly)
                    {
                        parser.EchoWriter = stringWriter;
                    }

                    // parse the input
                    var scriptBlock = parser.Parse(new DocumentContext(source)
                    {
                        FileContext = fileName
                    }, codeSettings);
                    if (scriptBlock != null && !preprocessOnly)
                    {
                        // we'll return the crunched code
                        if (codeSettings.Format == JavaScriptFormat.JSON)
                        {
                            // we're going to use a different output visitor -- one
                            // that specifically returns valid JSON.
                            if (!JsonOutputVisitor.Apply(stringWriter, scriptBlock, codeSettings))
                            {
                                errorList.Add(new UglifyError()
                                {
                                    Severity = 0,
                                    File     = fileName,
                                    Message  = CommonStrings.InvalidJSONOutput,
                                });
                            }
                        }
                        else
                        {
                            // just use the normal output visitor
                            OutputVisitor.Apply(stringWriter, scriptBlock, codeSettings);

                            codeSettings.SymbolsMap?.EndFile(stringWriter, codeSettings.LineTerminator);
                        }
                    }
                }

                crunched = sb.ToString();
            }
            catch (Exception e)
            {
                errorList.Add(new UglifyError()
                {
                    Severity = 0,
                    File     = fileName,
                    Message  = e.Message,
                });
                throw;
            }
            finally
            {
                sb.Release();
            }

            return(new UglifyResult(crunched, errorList));
        }
示例#40
0
        public static void Apply(AstNode node, CodeSettings codeSettings)
        {
            var logicalNot = new LogicalNotVisitor(node, codeSettings);

            logicalNot.Apply();
        }
示例#41
0
 public MsMinifier(CodeSettings codeSettings, string[] globalNames)
 {
     this.codeSettings = codeSettings;
     this.globalNames  = globalNames;
 }
示例#42
0
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            if (files == null)
            {
                return(string.Empty);
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616
            var sourcePath     = VirtualPathUtility.ToAbsolute(bundle.Path);
            var mapVirtualPath = string.Concat(bundle.Path, "map"); // don't use .map so it's picked up by the bundle module
            var mapPath        = VirtualPathUtility.ToAbsolute(mapVirtualPath);

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcatedString = GetContentConcated(context, files);

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                var mapBuilder     = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                    using (var mapWriter = new StringWriter(mapBuilder))
                        using (var sourceMap = new V3SourceMap(mapWriter))
                        {
                            var settings = new CodeSettings()
                            {
                                EvalTreatment             = EvalTreatment.MakeImmediateSafe,
                                PreserveImportantComments = false,
                                SymbolsMap     = sourceMap,
                                TermSemicolons = true,
                                MinifyCode     = minifyCode
                            };

                            sourceMap.StartPackage(sourcePath, mapPath);

                            var    minifier        = new Minifier();
                            string contentMinified = minifier.MinifyJavaScript(contentConcatedString, settings);
                            if (minifier.ErrorList.Count > 0)
                            {
                                return(GenerateMinifierErrorsContent(contentConcatedString, minifier));
                            }

                            contentWriter.Write(contentMinified);
                        }

                // Write the SourceMap to another Bundle
                AddContentToAdHocBundle(context, mapVirtualPath, mapBuilder.ToString());

                // Note: A current bug in AjaxMin reported by @LodewijkSioen here https://ajaxmin.codeplex.com/workitem/21834,
                // causes the MinifyJavascript method call to hang when debugger is attached if the following line is included.
                // To avoid more harm than good, don't support source mapping in this scenario until AjaxMin fixes it's bug.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    contentBuilder.Insert(0, sourceMappingDisabledMsg + "\r\n\r\n\r\n");
                }

                return(contentBuilder.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details.", ex, typeof(ScriptWithSourceMapBundleBuilder));
                return(GenerateGenericErrorsContent(contentConcatedString));
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var executingAssembly = Assembly.GetExecutingAssembly();

            var databaseEngine = Configuration["AppSettings:DatabaseEngine"];

            DbConfiguration.SetConfiguration(new DatabaseEngineDbConfiguration(databaseEngine));

            services.AddDbContext <AdminAppDbContext>(ConfigureForAdminDatabase);
            services.AddDbContext <AdminAppIdentityDbContext>(ConfigureForAdminDatabase);
            services.AddDbContext <AdminAppDataProtectionKeysDbContext>(ConfigureForAdminDatabase);

            services.AddIdentity <AdminAppUser, IdentityRole>()
            .AddEntityFrameworkStores <AdminAppIdentityDbContext>()
            .AddDefaultTokenProviders();

            services.AddControllersWithViews(options =>
            {
                options.Filters.Add(new AuthorizeFilter("UserMustExistPolicy"));
                options.Filters.Add <AutoValidateAntiforgeryTokenAttribute>();
                options.Filters.Add <JsonValidationFilter>();
                options.Filters.Add <SetupRequiredFilter>();
                options.Filters.Add <UserContextFilter>();
                options.Filters.Add <PasswordChangeRequiredFilter>();
                options.Filters.Add <InstanceContextFilter>();
            })
            .AddFluentValidation(
                opt =>
            {
                opt.RegisterValidatorsFromAssembly(executingAssembly);

                opt.ValidatorOptions.DisplayNameResolver = (type, memberInfo, expression)
                                                           => memberInfo?
                                                           .GetCustomAttribute <System.ComponentModel.DataAnnotations.DisplayAttribute>()?.GetName();
            });

            services.AddWebOptimizer(
                pipeline =>
            {
                var minifyJsSettings = new CodeSettings
                {
                    LocalRenaming = LocalRenaming.CrunchAll,
                    MinifyCode    = true
                };

                var minifyCssSettings = new CssSettings
                {
                    MinifyExpressions = true
                };

                pipeline.AddCssBundle("/bundles/bootstrap-multiselect.min.css", minifyCssSettings, "/content/css/bootstrap-multiselect.css");
                pipeline.AddCssBundle("/bundles/site.min.css", minifyCssSettings, "/content/css/Site.css");
                pipeline.AddJavaScriptBundle("/bundles/bootstrap-multiselect.min.js", minifyJsSettings, "/Scripts/bootstrap-multiselect.js");
                pipeline.AddJavaScriptBundle("/bundles/modernizr.min.js", minifyJsSettings, "/Scripts/modernizr-2.8.3.js");
                pipeline.AddJavaScriptBundle("/bundles/site.min.js", minifyJsSettings, "/Scripts/site.js", "/Scripts/site-form-handlers.js", "/Scripts/signalr-progress.js");
                pipeline.AddJavaScriptBundle("/bundles/claimset.min.js", minifyJsSettings, "/Scripts/resource-editor.js");
                pipeline.AddJavaScriptBundle("/bundles/authstrategy.min.js", minifyJsSettings, "/Scripts/auth-editor.js");
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserMustExistPolicy",
                                  policyBuilder =>
                {
                    policyBuilder.AddRequirements(new UserMustExistRequirement());
                });
            });

            services.AddScoped <IAuthorizationHandler, UserMustExistHandler>();

            services.Configure <IdentityOptions>(options =>
            {
                options.User.RequireUniqueEmail = true;
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath        = "/Identity/Login";
                options.LogoutPath       = "/Identity/LogOut";
                options.AccessDeniedPath = "/Identity/Login";
            });

            services.AddDataProtection().PersistKeysToDbContext <AdminAppDataProtectionKeysDbContext>();

            services.AddAutoMapper(executingAssembly, typeof(AdminManagementMappingProfile).Assembly);

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.Configure <ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

            services.AddSignalR();

            services.AddHttpClient();

            var appSettings = new AppSettings();

            Configuration.GetSection("AppSettings").Bind(appSettings);
            ConfigurationAppSettings = appSettings;

            var connectionStrings = new ConnectionStrings();

            Configuration.GetSection("ConnectionStrings").Bind(connectionStrings);
            ConfigurationConnectionStrings = connectionStrings;

            var appStartup = appSettings.AppStartup;

            if (appStartup == "OnPrem")
            {
                new OnPremInstaller().Install(services, appSettings);
            }

            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings());
            HangFireInstance.EnableWithoutSchemaMigration();
            services.AddHangfireServer();

            services.AddHealthCheck(Configuration.GetConnectionString("Admin"), IsSqlServer(databaseEngine));

            // This statement should be kept last to ensure that the IHttpClientFactory and IInferOdsApiVersion services are registered.
            CommonConfigurationInstaller.ConfigureLearningStandards(services).Wait();
        }
示例#44
0
 /// <summary>
 /// Constructs instance of NUglify JS Minifier
 /// </summary>
 /// <param name="settings">NUglify JS Minifier settings</param>
 public NUglifyJsMinifier(NUglifyJsMinificationSettings settings)
 {
     _originalEmbeddedJsSettings = CreateOriginalJsMinifierSettings(settings, false);
     _originalInlineJsSettings = CreateOriginalJsMinifierSettings(settings, true);
 }
示例#45
0
        /// <summary>
        /// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
        /// The ErrorList property will be set with any errors found during the minification process.
        /// </summary>
        /// <param name="source">CSS Source</param>
        /// <param name="fileName">File name to use in error reporting. Default is <c>input</c></param>
        /// <param name="settings">CSS minification settings</param>
        /// <param name="scriptSettings">JS minification settings to use for expression-minification</param>
        /// <returns>Minified StyleSheet</returns>
        public static UglifyResult Css(string source, string fileName, CssSettings settings = null, CodeSettings scriptSettings = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            fileName       = fileName ?? "input";
            settings       = settings ?? new CssSettings();
            scriptSettings = scriptSettings ?? new CodeSettings();

            // initialize some values, including the error list (which shoudl start off empty)
            string minifiedResults;
            var    errorList = new List <UglifyError>();

            // create the parser object and if we specified some settings,
            // use it to set the Parser's settings object
            var parser = new CssParser
            {
                FileContext = fileName,
                Settings    = settings,
                JSSettings  = scriptSettings
            };

            // hook the error handler
            parser.CssError += (sender, e) =>
            {
                var error = e.Error;
                if (error.Severity <= settings.WarningLevel)
                {
                    errorList.Add(error);
                }
            };

            // try parsing the source and return the results
            try
            {
                minifiedResults = parser.Parse(source);
            }
            catch (Exception e)
            {
                errorList.Add(new UglifyError()
                {
                    Severity = 0,
                    File     = fileName,
                    Message  = e.Message,
                });
                throw;
            }
            return(new UglifyResult(minifiedResults, errorList));
        }
示例#46
0
 public static UglifyResult Css(string source, CssSettings settings = null,
                                CodeSettings scriptSettings         = null)
 {
     return(Css(source, null, settings, scriptSettings));
 }
示例#47
0
 public MsMinifier(CodeSettings codeSettings)
 {
     this.codeSettings = codeSettings;
 }
示例#48
0
 public JavaScriptMinifier(CodeSettings settings)
 {
     Settings = settings;
 }
示例#49
0
        public SwitchParser()
        {
            // initialize with default values
            JSSettings = new CodeSettings();
            CssSettings = new CssSettings();

            // see if this is running under the Mono runtime (on UNIX)
            m_isMono = Type.GetType("Mono.Runtime") != null;
        }
示例#50
0
 /// <summary>
 /// Runs the JavaScript minifier on the content.
 /// </summary>
 public static IEnumerable <IAsset> MinifyJavaScript(this IEnumerable <IAsset> assets, CodeSettings settings)
 {
     return(assets.AddProcessor(asset => asset.MinifyJavaScript(settings)));
 }
示例#51
0
 /// <summary>
 /// Minifies tje specified .js files.
 /// </summary>
 public static IEnumerable <IAsset> MinifyJsFiles(this IAssetPipeline pipeline, CodeSettings settings, params string[] sourceFiles)
 {
     return(pipeline.AddFiles("text/javascript; charset=UTF-8", sourceFiles)
            .AddResponseHeader("X-Content-Type-Options", "nosniff")
            .MinifyJavaScript(settings));
 }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Read setName, contentType and version. All are required. They are
            // used as cache key
            string setName = request["s"] ?? string.Empty;
            string contentType = request["t"] ?? string.Empty;
            string version = request["v"] ?? string.Empty;

            // Decide if browser supports compressed response
            bool isCompressed = DO_GZIP && this.CanGZip(context.Request);

            // Response is written as UTF8 encoding. If you are using languages like
            // Arabic, you should change this to proper encoding
            UTF8Encoding encoding = new UTF8Encoding(false);

            // If the set has already been cached, write the response directly from
            // cache. Otherwise generate the response and cache it
            if (!this.WriteFromCache(context, setName, version, isCompressed, contentType)) {

                using (MemoryStream memoryStream = new MemoryStream(5000)) {

                    // Decide regular stream or GZipStream based on whether the response
                    // can be cached or not
                    using (Stream writer = isCompressed ?
                        (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream) {

                        // Load the files defined in and process each file
                        string setDefinition = GetFilelist(setName) ?? "";

                        string[] fileNames = setDefinition.Split(new char[] { ',' },
                            StringSplitOptions.RemoveEmptyEntries);

                        string minifiedString = string.Empty;
                        var minifier = new Minifier();
                        StringBuilder allScripts = new StringBuilder();

                        if (contentType == JS_TYPE) {
                            foreach (string fileName in fileNames) {
                                byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
                                allScripts.Append(Encoding.UTF8.GetString(fileBytes));
                                //writer.Write(fileBytes, 0, fileBytes.Length);
                            }

                            var codeSettings = new CodeSettings();
                            codeSettings.MinifyCode = true;
                            codeSettings.OutputMode = OutputMode.SingleLine;
                            //codeSettings.OutputMode = OutputMode.MultipleLines;
                            codeSettings.InlineSafeStrings = true;
                            codeSettings.MacSafariQuirks = true;
                            codeSettings.RemoveUnneededCode = true;
                            codeSettings.LocalRenaming = LocalRenaming.CrunchAll;
                            codeSettings.EvalTreatment = EvalTreatment.MakeAllSafe;
                            //codeSettings.CombineDuplicateLiterals = true;
                            codeSettings.PreserveFunctionNames = false;
                            minifiedString = minifier.MinifyJavaScript(allScripts.ToString(), codeSettings);
                        }

                        if (contentType == CSS_TYPE) {
                            CssParser parser = new CssParser();
                            foreach (string fileName in fileNames) {
                                byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
                                string crunchedStyles = parser.Parse(Encoding.UTF8.GetString(fileBytes));
                                allScripts.Append(crunchedStyles);
                            }

                            var cssSettings = new CssSettings();
                            cssSettings.CommentMode = CssComment.None;
                            cssSettings.ColorNames = CssColor.Strict;
                            //cssSettings.ExpandOutput = true;
                            cssSettings.TermSemicolons = true;
                            minifiedString = minifier.MinifyStyleSheet(allScripts.ToString(), cssSettings);
                        }

                        byte[] rikiki = Encoding.UTF8.GetBytes(minifiedString);
                        writer.Write(rikiki, 0, rikiki.Length);
                        writer.Close();
                    }

                    // Cache the combined response so that it can be directly written
                    // in subsequent calls
                    byte[] responseBytes = memoryStream.ToArray();
                    context.Cache.Insert(
                        GetCacheKey(setName, version, isCompressed),
                        responseBytes,
                        null,
                        Cache.NoAbsoluteExpiration,
                        CACHE_DURATION);

                    // Generate the response
                    this.WriteBytes(responseBytes, context, isCompressed, contentType);
                }
            }
        }
示例#53
0
        public static string MinifyString(string extension, string content)
        {
            if (extension == ".css")
            {
                Minifier minifier = new Minifier();
                CssSettings settings = new CssSettings();
                settings.CommentMode = CssComment.None;

                if (WESettings.GetBoolean(WESettings.Keys.KeepImportantComments))
                {
                    settings.CommentMode = CssComment.Important;
                }

                return minifier.MinifyStyleSheet(content, settings);
            }
            else if (extension == ".js")
            {
                Minifier minifier = new Minifier();
                CodeSettings settings = new CodeSettings()
                {
                    EvalTreatment = EvalTreatment.MakeImmediateSafe,
                    PreserveImportantComments = WESettings.GetBoolean(WESettings.Keys.KeepImportantComments)
                };

                return minifier.MinifyJavaScript(content, settings);
            }

            return null;
        }
示例#54
0
 /// <summary>
 /// Crunched JS string passed to it, returning crunched string.
 /// The ErrorList property will be set with any errors found during the minification process.
 /// </summary>
 /// <param name="source">source Javascript</param>
 /// <param name="codeSettings">code minification settings</param>
 /// <returns>minified Javascript</returns>
 public static UglifyResult Js(string source, CodeSettings codeSettings)
 {
     // just pass in default settings
     return(Js(source, null, codeSettings));
 }
示例#55
0
 /// <summary>
 /// Creates a JavaScript bundle on the specified route and minifies the output.
 /// </summary>
 public static IAsset AddJavaScriptBundle(this IAssetPipeline pipeline, string route, CodeSettings settings, params string[] sourceFiles)
 {
     return(pipeline.AddBundle(route, "text/javascript; charset=UTF-8", sourceFiles)
            .EnforceFileExtensions(".js", ".jsx", ".es5", ".es6")
            .Concatenate()
            .AddResponseHeader("X-Content-Type-Options", "nosniff")
            .MinifyJavaScript(settings));
 }
 /// <summary>
 /// Creates a JavaScript bundle on the specified route and minifies the output.
 /// </summary>
 public static IAsset AddJavaScriptBundle(this IAssetPipeline pipeline, string route, CodeSettings settings, params string[] sourceFiles)
 {
     return(pipeline.AddBundle(route, "application/javascript; charset=UTF-8", sourceFiles)
            .EnforceFileExtensions(".js", ".jsx", ".es5", ".es6")
            .Concatenate()
            .MinifyJavaScript(settings));
 }
示例#57
0
 /// <summary>
 /// Minifies any .js file requested.
 /// </summary>
 public static IEnumerable <IAsset> MinifyJsFiles(this IAssetPipeline pipeline, CodeSettings settings)
 {
     return(pipeline.MinifyJsFiles(settings, "**/*.js"));
 }
 /// <summary>
 /// Minifies tje specified .js files.
 /// </summary>
 public static IEnumerable <IAsset> MinifyJsFiles(this IAssetPipeline pipeline, CodeSettings settings, params string[] sourceFiles)
 {
     return(pipeline.AddFiles("application/javascript; charset=UTF-8", sourceFiles)
            .MinifyJavaScript(settings));
 }
示例#59
0
 internal CatchScope(ActivationObject parent, CodeSettings settings)
     : base(parent, settings, ScopeType.Catch)
 {
 }
示例#60
0
 /// <summary>
 /// Constructs an instance of the Microsoft Ajax CSS Minifier
 /// </summary>
 /// <param name="settings">Microsoft Ajax CSS Minifier settings</param>
 public MsAjaxCssMinifier(MsAjaxCssMinificationSettings settings)
 {
     _originalEmbeddedCssSettings = CreateOriginalCssMinifierSettings(settings, false);
     _originalInlineCssSettings = CreateOriginalCssMinifierSettings(settings, true);
     _originalJsSettings = new CodeSettings();
 }