using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; namespace Umbraco.Web.WebAssets { /// /// Creates a JavaScript block to initialize the back office /// public class BackOfficeJavaScriptInitializer { // deal with javascript functions inside of json (not a supported json syntax) private const string PrefixJavaScriptObject = "@@@@"; private static readonly Regex JsFunctionParser = new Regex($"(\"{PrefixJavaScriptObject}(.*?)\")+", RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled); // replace tokens in the js main private static readonly Regex Token = new Regex("(\"##\\w+?##\")", RegexOptions.Compiled); /// /// Gets the JS initialization script to boot the back office application /// /// /// /// The angular module name to boot /// /// /// /// public static string GetJavascriptInitialization(IEnumerable scripts, string angularModule, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { var jarray = new StringBuilder(); jarray.AppendLine("["); var first = true; foreach (var file in scripts) { if (first) first = false; else jarray.AppendLine(","); jarray.Append("\""); jarray.Append(file); jarray.Append("\""); } jarray.Append("]"); return WriteScript(jarray.ToString(), hostingEnvironment.ToAbsolute(globalSettings.UmbracoPath), angularModule); } /// /// Parses the JsResources.Main and replaces the replacement tokens accordingly /// /// /// /// /// internal static string WriteScript(string scripts, string umbracoPath, string angularModule) { var count = 0; var replacements = new[] { scripts, umbracoPath, angularModule }; // replace, catering for the special syntax when we have // js function() objects contained in the json return Token.Replace(Resources.Main, match => { var replacement = replacements[count++]; return JsFunctionParser.Replace(replacement, "$2"); }); } } }