Esempio n. 1
0
 /// <summary>
 /// Loads any user-provided scripts. Only scripts that don't need JSX transformation can
 /// run immediately here. JSX files are loaded in ReactEnvironment.
 /// </summary>
 /// <param name="engine">Engine to load scripts into</param>
 private void LoadUserScripts(IJsEngine engine)
 {
     foreach (var file in _config.ScriptsWithoutTransform)
     {
         try
         {
             var contents = _fileSystem.ReadAsString(file);
             engine.Execute(contents);
         }
         catch (JsRuntimeException ex)
         {
             // We can't simply rethrow the exception here, as it's possible this is running
             // on a background thread (ie. as a response to a file changing). If we did
             // throw the exception here, it would terminate the entire process. Instead,
             // save the exception, and then just rethrow it later when getting the engine.
             _scriptLoadException = new ReactScriptLoadException(string.Format(
                                                                     "Error while loading \"{0}\": {1}\r\nLine: {2}\r\nColumn: {3}",
                                                                     file,
                                                                     ex.Message,
                                                                     ex.LineNumber,
                                                                     ex.ColumnNumber
                                                                     ));
         }
         catch (IOException ex)
         {
             _scriptLoadException = new ReactScriptLoadException(ex.Message);
         }
     }
 }
Esempio n. 2
0
        public async Task <JObject> GetMarkdownIt(string text)
        {
            _jsengine = _jsengine ?? JsEngineSwitcher.Instance.CreateDefaultEngine();

            var version = "8.4.0";

            if (_mardownit == null)
            {
                _mardownit = await _httpClient.GetStringAsync($"https://raw.githubusercontent.com/markdown-it/markdown-it/{version}/dist/markdown-it.min.js");

                _jsengine.Execute(_mardownit);
                _jsengine.Evaluate("var MarkdownIt = markdownit();");
            }

            var inputval = "input_" + Guid.NewGuid().ToString().Replace("-", "_");

            _jsengine.SetVariableValue(inputval, text);

            var script = $"MarkdownIt.render({inputval});";
            var result = _jsengine.Evaluate(script)?.ToString();

            _jsengine.RemoveVariable(inputval);

            var jsonResult = new JObject
            {
                ["name"]    = "markdown-it",
                ["version"] = version,
                ["html"]    = result
            };

            return(jsonResult);
        }
Esempio n. 3
0
        /// <summary>
        /// Tries to execute a code from JavaScript file with pre-compilation.
        /// </summary>
        /// <param name="engine">Engine to execute code from JavaScript file with pre-compilation</param>
        /// <param name="cache">Cache used for storing the pre-compiled scripts</param>
        /// <param name="fileSystem">File system wrapper</param>
        /// <param name="path">Path to the JavaScript file</param>
        /// <param name="scriptLoader">Delegate that loads a code from specified JavaScript file</param>
        /// <returns>true if can perform a script pre-compilation; otherwise, false.</returns>
        public static bool TryExecuteFileWithPrecompilation(this IJsEngine engine, ICache cache,
                                                            IFileSystem fileSystem, string path, Func <string, string> scriptLoader = null)
        {
            EnsurePrecompilationAvailability(engine, cache);

            var cacheKey          = string.Format(PRECOMPILED_JS_FILE_CACHE_KEY, path);
            var precompiledScript = cache.Get <IPrecompiledScript>(cacheKey);

            if (precompiledScript == null)
            {
                var contents = scriptLoader != null?scriptLoader(path) : fileSystem.ReadAsString(path);

                precompiledScript = engine.Precompile(contents, path);
                var fullPath = fileSystem.MapPath(path);
                cache.Set(
                    cacheKey,
                    precompiledScript,
                    slidingExpiration: PRECOMPILED_JS_CACHE_ENTRY_SLIDING_EXPIRATION,
                    cacheDependencyFiles: new[] { fullPath }
                    );
            }

            engine.Execute(precompiledScript);

            return(true);
        }
Esempio n. 4
0
        public async Task <JObject> GetCommonMarkJs(string text)
        {
            _jsengine = _jsengine ?? JsEngineSwitcher.Instance.CreateDefaultEngine();

            var version = "0.28.1";

            if (_commonmarkjs == null)
            {
                _commonmarkjs = await _httpClient.GetStringAsync($"https://raw.githubusercontent.com/commonmark/commonmark.js/{version}/dist/commonmark.min.js");

                _jsengine.Execute(_commonmarkjs);
            }

            var inputval = "input_" + Guid.NewGuid().ToString().Replace("-", "_");

            _jsengine.SetVariableValue(inputval, text);

            var script = $"(new commonmark.HtmlRenderer()).render((new commonmark.Parser()).parse({inputval}));";
            var result = _jsengine.Evaluate(script)?.ToString();

            _jsengine.RemoveVariable(inputval);

            var jsonResult = new JObject
            {
                ["name"]    = "commonmark.js",
                ["version"] = version,
                ["html"]    = result
            };

            return(jsonResult);
        }
        /// <summary>
        /// Loads standard React and JSXTransformer scripts into the engine.
        /// </summary>
        protected virtual void InitialiseEngine(IJsEngine engine)
        {
            var thisAssembly = typeof(ReactEnvironment).Assembly;

            engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
            engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
            engine.Execute("var React = global.React");
            engine.ExecuteResource("React.Resources.JSXTransformer.js", thisAssembly);
        }
        /// <summary>
        /// Executes a code from embedded JS resource
        /// </summary>
        /// <param name="source">JS engine</param>
        /// <param name="resourceName">The case-sensitive resource name</param>
        /// <param name="assembly">The assembly, which contains the embedded resource</param>
        /// <param name="useCache">Flag for whether to use the cache for script code retrieved from
        /// the embedded resource</param>
        /// <exception cref="ObjectDisposedException"/>
        /// <exception cref="ArgumentNullException"/>
        /// <exception cref="ArgumentException"/>
        /// <exception cref="NullReferenceException"/>
        /// <exception cref="JsUsageException"/>
        /// <exception cref="JsCompilationException"/>
        /// <exception cref="JsTimeoutException"/>
        /// <exception cref="JsInterruptedException"/>
        /// <exception cref="JsRuntimeException"/>
        /// <exception cref="JsException"/>
        public static void ExecuteResource(this IJsEngine source, string resourceName, Assembly assembly, bool useCache)
        {
            if (useCache)
            {
                if (resourceName == null)
                {
                    throw new ArgumentNullException(
                              nameof(resourceName),
                              string.Format(CoreStrings.Common_ArgumentIsNull, nameof(resourceName))
                              );
                }

                if (assembly == null)
                {
                    throw new ArgumentNullException(
                              nameof(assembly),
                              string.Format(CoreStrings.Common_ArgumentIsNull, nameof(assembly))
                              );
                }

                if (string.IsNullOrWhiteSpace(resourceName))
                {
                    throw new ArgumentException(
                              string.Format(CoreStrings.Common_ArgumentIsEmpty, nameof(resourceName)),
                              nameof(resourceName)
                              );
                }

                if (!ValidationHelpers.CheckDocumentNameFormat(resourceName))
                {
                    throw new ArgumentException(
                              string.Format(CoreStrings.Usage_InvalidResourceNameFormat, resourceName),
                              nameof(resourceName)
                              );
                }

                if (!_scriptCodeCacheInitialized)
                {
                    lock (_scriptCodeCacheInitializationSynchronizer)
                    {
                        if (!_scriptCodeCacheInitialized)
                        {
                            _scriptCodeCache            = new ConcurrentDictionary <string, string>();
                            _scriptCodeCacheInitialized = true;
                        }
                    }
                }

                string scriptCode = _scriptCodeCache.GetOrAdd(resourceName, key => ReadResourceAsString(key, assembly));
                source.Execute(scriptCode, resourceName);
            }
            else
            {
                source.ExecuteResource(resourceName, assembly);
            }
        }
Esempio n. 7
0
        private static string EncodeData(string data, string key, int keyId, out string Ctkey)
        {
            IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;

            engineSwitcher.EngineFactories.Add(new JurassicJsEngineFactory());
            engineSwitcher.DefaultEngineName = JurassicJsEngine.EngineName;
            using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
            {
                engine.Execute(DedeDataJsCode);
                if (keyId == 1)
                {
                    engine.Execute("var this_UrlKey1 = 'db0FaVXtwixFUGGQ1Iq9dN7yMrJ9DFHQ';var this_UrlKey2 = 'R8nD2B0DRcT0IoFrA5UqHeHLeFsbrOBvXIVhKmgcXXcDLDrQemyyQLdDpAom9N'");
                }
                var publickey = engine.CallFunction("getCtKey", key);
                Ctkey = publickey.ToString();
                string PostjsonStr = engine.CallFunction("encode", data, publickey).ToString();
                return(PostjsonStr);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Loads standard React and Babel scripts into the engine.
        /// </summary>
        protected virtual void InitialiseEngine(IJsEngine engine)
        {
            var thisAssembly = typeof(ReactEnvironment).Assembly;

            engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
            if (_config.LoadReact)
            {
                engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
                engine.Execute("React = global.React");
                // Expose ReactDOM as some scripts may be using it. #yolo
                engine.Execute("ReactDOM = React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED");
            }

            LoadUserScripts(engine);
            if (!_config.LoadReact)
            {
                // We expect to user to have loaded their own version of React in the scripts that
                // were loaded above, let's ensure that's the case.
                EnsureReactLoaded(engine);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Initializes JS packer
        /// </summary>
        private void Initialize()
        {
            if (_initializedFlag.Set())
            {
                _jsEngine.ExecuteResource(RESOURCES_NAMESPACE + "." + PACKER_LIBRARY_FILE_NAME, GetType().Assembly);
                _jsEngine.Execute(
                    string.Format(@"var {0} = function(code, base62Encode, shrinkVariables) {{
	var packer = new Packer();

	return packer.pack(code, base62Encode, shrinkVariables);
}}", PACKING_FUNCTION_NAME));
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Loads standard React and JSXTransformer scripts into the engine.
        /// </summary>
        private void InitialiseEngine(IJsEngine engine)
        {
            var thisAssembly = GetType().Assembly;

            engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
            engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
            engine.Execute("var React = global.React");

            // Only load JSX Transformer if engine supports it
            if (engine.SupportsJsxTransformer())
            {
                engine.ExecuteResource("React.Resources.JSXTransformer.js", thisAssembly);
            }
        }
Esempio n. 11
0
        private void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            var type = GetType();

            _jsEngine.Execute("this.window = this;");
            _jsEngine.ExecuteResource("MarkN.Scripts.marked.min.js", type);
            _jsEngine.ExecuteResource("MarkN.Scripts.highlight.pack.js", type);

            _initialized = true;
        }
Esempio n. 12
0
        private static JObject DecodeData(string data, string key, out int keyId)
        {
            keyId = 0;
            IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;

            engineSwitcher.EngineFactories.Add(new JurassicJsEngineFactory());
            engineSwitcher.DefaultEngineName = JurassicJsEngine.EngineName;
            using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
            {
                engine.Execute(DedeDataJsCode);
                var     publickey   = engine.CallFunction("getCtKey", key);
                string  PostjsonStr = engine.CallFunction("decode", data, publickey).ToString();
                JObject jo;
                if (PostjsonStr.StartsWith("{"))
                {
                    jo = JsonStringToJsonObj(PostjsonStr);
                    if (jo != null)
                    {
                        return(jo);
                    }
                }
                keyId = 1;
                engine.Execute("var this_UrlKey1 = 'db0FaVXtwixFUGGQ1Iq9dN7yMrJ9DFHQ';var this_UrlKey2 = 'R8nD2B0DRcT0IoFrA5UqHeHLeFsbrOBvXIVhKmgcXXcDLDrQemyyQLdDpAom9N'");
                publickey   = engine.CallFunction("getCtKey", key);
                PostjsonStr = engine.CallFunction("decode", data, publickey).ToString();
                if (PostjsonStr.StartsWith("{"))
                {
                    jo = JsonStringToJsonObj(PostjsonStr);
                    if (jo != null)
                    {
                        return(jo);
                    }
                }
                return(null);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Initializes a Sass compiler
        /// </summary>
        private void InitializeCompiler()
        {
            if (_initialized)
            {
                return;
            }

            lock (_initializationSynchronizer)
            {
                if (_initialized)
                {
                    return;
                }

                string serializedOptions = _jsonSerializer.SerializeObject(_options);

                try
                {
                    _jsEngine = _createJsEngineInstance();
                    _jsEngine.EmbedHostObject(FILE_MANAGER_VARIABLE_NAME, _fileManager);
                    _jsEngine.SetVariableValue(CURRENT_OS_PLATFORM_NAME, GetCurrentOSPlatformName());

                    Assembly assembly = this.GetType()
#if !NET40
                                        .GetTypeInfo()
#endif
                                        .Assembly
                    ;

                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(ES6_POLYFILLS_FILE_NAME), assembly, true);
                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(SASS_LIBRARY_FILE_NAME), assembly, true);
                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(SASS_HELPER_FILE_NAME), assembly, true);
                    _jsEngine.Execute($"var sassHelper = new SassHelper({serializedOptions});");

                    _version = _jsEngine.Evaluate <string>("SassHelper.getVersion();");
                }
                catch (JsEngineLoadException e)
                {
                    throw SassErrorHelpers.WrapCompilerLoadException(e);
                }
                catch (JsException e)
                {
                    throw SassErrorHelpers.WrapCompilerLoadException(e, true);
                }

                _initialized = true;
            }
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var engineSwitcher = JsEngineSwitcher.Current;

            engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
            engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
            IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine();

            engine.EmbedHostType("Test", typeof(Test));
            var t = new Test();

            engine.EmbedHostObject("TestA", t);
            engine.Execute("var a=1+3;if(1)a=5;TestA.Name=a");
            Console.WriteLine(t.Name);
            Console.ReadKey();
        }
Esempio n. 15
0
        /// <summary>
        /// Loads standard React and Babel scripts into the engine.
        /// </summary>
        protected virtual void InitialiseEngine(IJsEngine engine)
        {
            var thisAssembly = typeof(ReactEnvironment).Assembly;

            engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
            if (_config.LoadReact)
            {
                engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
                engine.Execute("React = global.React");
            }

            LoadUserScripts(engine);
            if (!_config.LoadReact)
            {
                // We expect to user to have loaded their own versino of React in the scripts that
                // were loaded above, let's ensure that's the case.
                EnsureReactLoaded(engine);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Tries to execute a code from embedded JavaScript resource with pre-compilation.
        /// </summary>
        /// <param name="engine">Engine to execute a code from embedded JavaScript resource with pre-compilation</param>
        /// <param name="cache">Cache used for storing the pre-compiled scripts</param>
        /// <param name="resourceName">The case-sensitive resource name</param>
        /// <param name="assembly">The assembly, which contains the embedded resource</param>
        /// <returns>true if can perform a script pre-compilation; otherwise, false.</returns>
        public static bool TryExecuteResourceWithPrecompilation(this IJsEngine engine, ICache cache,
                                                                string resourceName, Assembly assembly)
        {
            var cacheKey          = string.Format(PRECOMPILED_JS_RESOURCE_CACHE_KEY, resourceName);
            var precompiledScript = cache.Get <IPrecompiledScript>(cacheKey);

            if (precompiledScript == null)
            {
                precompiledScript = engine.PrecompileResource(resourceName, assembly);
                cache.Set(
                    cacheKey,
                    precompiledScript,
                    slidingExpiration: PRECOMPILED_JS_CACHE_ENTRY_SLIDING_EXPIRATION
                    );
            }

            engine.Execute(precompiledScript);

            return(true);
        }
Esempio n. 17
0
 /// <summary>
 /// Loads any user-provided scripts. Only scripts that don't need JSX transformation can
 /// run immediately here. JSX files are loaded in ReactEnvironment.
 /// </summary>
 /// <param name="engine">Engine to load scripts into</param>
 private void LoadUserScripts(IJsEngine engine)
 {
     foreach (var file in _config.ScriptsWithoutTransform)
     {
         try
         {
             var contents = _fileSystem.ReadAsString(file);
             engine.Execute(contents);
         }
         catch (JsRuntimeException ex)
         {
             throw new ReactScriptLoadException(string.Format(
                                                    "Error while loading \"{0}\": {1}\r\nLine: {2}\r\nColumn: {3}",
                                                    file,
                                                    ex.Message,
                                                    ex.LineNumber,
                                                    ex.ColumnNumber
                                                    ));
         }
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Initializes a Autoprefixer
        /// </summary>
        private void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            lock (_initializationSynchronizer)
            {
                if (_initialized)
                {
                    return;
                }

                try
                {
                    _jsEngine.EmbedHostObject(COUNTRY_STATISTICS_SERVICE_VARIABLE_NAME,
                                              CountryStatisticsService.Instance);

                    Assembly assembly = this.GetType()
#if !NET40
                                        .GetTypeInfo()
#endif
                                        .Assembly
                    ;

                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(AUTOPREFIXER_LIBRARY_FILE_NAME),
                                              assembly);
                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(AUTOPREFIXER_HELPER_FILE_NAME),
                                              assembly);
                    _jsEngine.Execute($"var autoprefixerHelper = new AutoprefixerHelper({_serializedOptions});");
                }
                catch (JsException e)
                {
                    throw AutoprefixerErrorHelpers.WrapAutoprefixerLoadException(e, true);
                }

                _initialized = true;
            }
        }
Esempio n. 19
0
		/// <summary>
		/// Loads any user-provided scripts. Only scripts that don't need JSX transformation can 
		/// run immediately here. JSX files are loaded in ReactEnvironment.
		/// </summary>
		/// <param name="engine">Engine to load scripts into</param>
		private void LoadUserScripts(IJsEngine engine)
		{
			foreach (var file in _config.ScriptsWithoutTransform)
			{
				try
				{
					var contents = _fileSystem.ReadAsString(file);
					engine.Execute(contents);
				}
				catch (JsRuntimeException ex)
				{
					throw new ReactScriptLoadException(string.Format(
						"Error while loading \"{0}\": {1}\r\nLine: {2}\r\nColumn: {3}",
						file,
						ex.Message,
						ex.LineNumber,
						ex.ColumnNumber
					));
				}
			}
		}
 private void ProcessScript(IContext context, IReader reader, Script script)
 {
     script.Content = ReadScript(context, reader, script);
     _engine.Execute(script.Content);
 }
Esempio n. 21
0
        public virtual void ExecutionOfCodeIsCorrect()
        {
            // Arrange
            const string functionCode = @"function add(num1, num2) {
				return (num1 + num2);
			}"            ;
            const string input        = "add(7, 9);";
            const int    targetOutput = 16;

            // Act
            _jsEngine.Execute(functionCode);
            var output = _jsEngine.Evaluate <int>(input);

            // Assert
            Assert.AreEqual(targetOutput, output);
        }
Esempio n. 22
0
        public virtual void ArrayEveryMethodIsSupported()
        {
            // Arrange
            const string initCode = "var engines = ['Chakra', 'V8', 'SpiderMonkey', 'Jurassic'];";

            const string input1        = "engines.every(function (value, index, array) { return value.length > 1; });";
            const bool   targetOutput1 = true;

            const string input2        = "engines.every(function (value, index, array) { return value.length < 10; });";
            const bool   targetOutput2 = false;

            // Act
            _jsEngine.Execute(initCode);

            var output1 = _jsEngine.Evaluate <bool>(input1);
            var output2 = _jsEngine.Evaluate <bool>(input2);

            // Assert
            Assert.AreEqual(targetOutput1, output1);
            Assert.AreEqual(targetOutput2, output2);
        }
Esempio n. 23
0
 public void Execute(string code)
 {
     CheckDisposed();
     _engine.Execute(code);
 }
Esempio n. 24
0
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            HtmlParser parser = new HtmlParser();

            using (IJsEnginePool enginePool = context.GetJsEnginePool(x =>
            {
                if (string.IsNullOrWhiteSpace(_highlightJsFile))
                {
                    x.ExecuteResource("highlight-all.js", typeof(Highlight));
                }
                else
                {
                    x.ExecuteFile(_highlightJsFile);
                }
            }))
            {
                return(inputs.AsParallel().Select(context, input =>
                {
                    // We materialize the list before exiting the using statement, so safe to access enginePool
                    // ReSharper disable once AccessToDisposedClosure
                    using (IJsEngine engine = enginePool.GetEngine())
                    {
                        try
                        {
                            using (Stream stream = input.GetStream())
                                using (IHtmlDocument htmlDocument = parser.Parse(stream))
                                {
                                    foreach (AngleSharp.Dom.IElement element in htmlDocument.QuerySelectorAll(_codeQuerySelector))
                                    {
                                        // Don't highlight anything that potentially is already highlighted
                                        if (element.ClassList.Contains("hljs"))
                                        {
                                            continue;
                                        }


                                        // Make sure to use TextContent, otherwise you'll get escaped html which highlight.js won't parse
                                        engine.SetVariableValue("input", element.TextContent);

                                        // Check if they specified a language in their code block
                                        string language = element.ClassList.FirstOrDefault(i => i.StartsWith("language"));

                                        try
                                        {
                                            if (language != null)
                                            {
                                                engine.SetVariableValue("language", language.Replace("language-", ""));
                                                engine.Execute("result = hljs.highlight(language, input)");
                                            }
                                            else
                                            {
                                                language = "(auto)"; // set this to auto in case there is an exception below
                                                engine.Execute("result = hljs.highlightAuto(input)");
                                                string detectedLanguage = engine.Evaluate <string>("result.language");
                                                if (string.IsNullOrWhiteSpace(detectedLanguage) == false)
                                                {
                                                    element.ClassList.Add("language-" + detectedLanguage);
                                                }
                                            }

                                            element.ClassList.Add("hljs");
                                            string formatted = engine.Evaluate <string>("result.value");
                                            element.InnerHtml = formatted;
                                        }
                                        catch (Exception innerEx)
                                        {
                                            if (innerEx.Message.Contains("Unknown language: ") && _warnOnMissingLanguage)
                                            {
                                                Trace.Warning("Exception while highlighting source code for {0} using language {1}: {2}", input.SourceString(), language, innerEx.Message);
                                            }
                                            else
                                            {
                                                Trace.Information("Exception while highlighting source code for {0} using language {1}: {2}", input.SourceString(), language, innerEx.Message);
                                            }
                                        }
                                    }
                                    string content = htmlDocument.ToHtml();
                                    return context.GetDocument(input, content);
                                }
                        }
                        catch (Exception ex)
                        {
                            Trace.Warning("Exception while highlighting source code for {0}: {1}", input.SourceString(), ex.Message);
                            return input;
                        }
                    }
                }).ToList());
            }
        }
		/// <summary>
		/// Loads any user-provided scripts. Only scripts that don't need JSX transformation can 
		/// run immediately here. JSX files are loaded in ReactEnvironment.
		/// </summary>
		/// <param name="engine">Engine to load scripts into</param>
		private void LoadUserScripts(IJsEngine engine)
		{
			foreach (var file in _config.ScriptsWithoutTransform)
			{
				try
				{
					var contents = _fileSystem.ReadAsString(file);
					engine.Execute(contents);
				}
				catch (JsRuntimeException ex)
				{
					// We can't simply rethrow the exception here, as it's possible this is running
					// on a background thread (ie. as a response to a file changing). If we did
					// throw the exception here, it would terminate the entire process. Instead,
					// save the exception, and then just rethrow it later when getting the engine.
					_scriptLoadException = new ReactScriptLoadException(string.Format(
						"Error while loading \"{0}\": {1}\r\nLine: {2}\r\nColumn: {3}",
						file,
						ex.Message,
						ex.LineNumber,
						ex.ColumnNumber
					));
				}
			}
		}
Esempio n. 26
0
		/// <summary>
		/// Loads standard React and Babel scripts into the engine.
		/// </summary>
		protected virtual void InitialiseEngine(IJsEngine engine)
		{
			var thisAssembly = typeof(ReactEnvironment).Assembly;
			engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
			if (_config.LoadReact)
			{
				engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
				engine.Execute("React = global.React");
				// Expose ReactDOM as some scripts may be using it. #yolo
				engine.Execute("ReactDOM = React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED");
			}

			LoadUserScripts(engine);
			if (!_config.LoadReact)
			{
				// We expect to user to have loaded their own version of React in the scripts that
				// were loaded above, let's ensure that's the case. 
				EnsureReactLoaded(engine);
			}
		}
Esempio n. 27
0
        public virtual void CreationOfEngineWithoutDisposingIsCorrect()
        {
            IJsEngine jsEngine = CreateJsEngine();

            jsEngine.Execute("var a = 1 + 1;");
        }
Esempio n. 28
0
		/// <summary>
		/// Loads standard React and JSXTransformer scripts into the engine.
		/// </summary>
		protected virtual void InitialiseEngine(IJsEngine engine)
		{
			var thisAssembly = typeof(ReactEnvironment).Assembly;
			engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
			if (_config.LoadReact)
			{
				engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
				engine.Execute("React = global.React");
				// TODO: Make this configurable, so we don't load Babel if it's not needed.
				engine.ExecuteResource("React.node_modules.babel_core.browser.js", thisAssembly);
			}

			LoadUserScripts(engine);
			if (!_config.LoadReact)
			{
				// We expect to user to have loaded their own versino of React in the scripts that
				// were loaded above, let's ensure that's the case. 
				EnsureReactLoaded(engine);
			}
		}
Esempio n. 29
0
		/// <summary>
		/// Loads standard React and Babel scripts into the engine.
		/// </summary>
		protected virtual void InitialiseEngine(IJsEngine engine)
		{
			var thisAssembly = typeof(ReactEnvironment).Assembly;
			engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
			if (_config.LoadReact)
			{
				engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
				engine.Execute("React = global.React");
			}

			LoadUserScripts(engine);
			if (!_config.LoadReact)
			{
				// We expect to user to have loaded their own versino of React in the scripts that
				// were loaded above, let's ensure that's the case. 
				EnsureReactLoaded(engine);
			}
		}
Esempio n. 30
0
        /// <summary>
        /// Executes a code from JavaScript file.
        /// </summary>
        /// <param name="engine">Engine to execute code from JavaScript file</param>
        /// <param name="fileSystem">File system wrapper</param>
        /// <param name="path">Path to the JavaScript file</param>
        public static void ExecuteFile(this IJsEngine engine, IFileSystem fileSystem, string path)
        {
            var contents = fileSystem.ReadAsString(path);

            engine.Execute(contents, path);
        }
Esempio n. 31
0
 public void injectJS(string js)
 {
     jsEngine.Execute(js);
 }