public CCFixture()
 {
     runtime = JsRuntime.Create(JsRuntimeAttributes.AllowScriptInterrupt);
     context = runtime.CreateContext();
     context.AddRef();
     typeMapper = new TypeMapper();
 }
Esempio n. 2
0
        public async Task <T> BuildContext <T>(Func <Runtime, JsContext, TypeMapper, T> initializer) where T : BaseProgram
        {
            var buildTask = Function(() =>
            {
                var context = runtime.CreateContext();
                using (new JsContext.Scope(context))
                {
                    // TODO: Configure promise callback. Promises should be added to be executed along main queue of work.
                    JsContext.SetPromiseContinuationCallback(PromiseContinuationCallback, IntPtr.Zero);
                }
                return(context);
            }, priority: JsTaskPriority.INITIALIZATION);
            var context = await buildTask;
            var program = initializer(this, context, typeMapper);

            program.InitializeState();
            programs.Add(program);
            return(program);
        }
Esempio n. 3
0
        /// <summary>
        /// Constructs an instance of adapter for the ChakraCore JS engine
        /// </summary>
        /// <param name="settings">Settings of the ChakraCore JS engine</param>
        public ChakraCoreJsEngine(ChakraCoreSettings settings)
        {
            ChakraCoreSettings chakraCoreSettings = settings ?? new ChakraCoreSettings();

            JsRuntimeAttributes attributes = JsRuntimeAttributes.None;

            if (chakraCoreSettings.DisableBackgroundWork)
            {
                attributes |= JsRuntimeAttributes.DisableBackgroundWork;
            }
            if (chakraCoreSettings.DisableNativeCodeGeneration)
            {
                attributes |= JsRuntimeAttributes.DisableNativeCodeGeneration;
            }
            if (chakraCoreSettings.DisableEval)
            {
                attributes |= JsRuntimeAttributes.DisableEval;
            }
            if (chakraCoreSettings.EnableExperimentalFeatures)
            {
                attributes |= JsRuntimeAttributes.EnableExperimentalFeatures;
            }

            _externalObjectFinalizeCallback = ExternalObjectFinalizeCallback;

            _dispatcher.Invoke(() =>
            {
                try
                {
                    _jsRuntime = JsRuntime.Create(attributes, null);
                    _jsContext = _jsRuntime.CreateContext();
                    _jsContext.AddRef();
                }
                catch (Exception e)
                {
                    throw new JsEngineLoadException(
                        string.Format(CoreStrings.Runtime_JsEngineNotLoaded,
                                      EngineName, e.Message), EngineName, EngineVersion, e);
                }
            });
        }
Esempio n. 4
0
        /// <summary>
        /// Constructs an instance of adapter for the ChakraCore JS engine
        /// </summary>
        /// <param name="settings">Settings of the ChakraCore JS engine</param>
        public ChakraCoreJsEngine(ChakraCoreSettings settings)
        {
#if NETFULL
            Initialize();
#endif
            ChakraCoreSettings chakraCoreSettings = settings ?? new ChakraCoreSettings();

            JsRuntimeAttributes attributes = JsRuntimeAttributes.AllowScriptInterrupt;
            if (chakraCoreSettings.DisableBackgroundWork)
            {
                attributes |= JsRuntimeAttributes.DisableBackgroundWork;
            }
            if (chakraCoreSettings.DisableEval)
            {
                attributes |= JsRuntimeAttributes.DisableEval;
            }
            if (chakraCoreSettings.DisableExecutablePageAllocation)
            {
                attributes |= JsRuntimeAttributes.DisableExecutablePageAllocation;
            }
            if (chakraCoreSettings.DisableFatalOnOOM)
            {
                attributes |= JsRuntimeAttributes.DisableFatalOnOOM;
            }
            if (chakraCoreSettings.DisableNativeCodeGeneration)
            {
                attributes |= JsRuntimeAttributes.DisableNativeCodeGeneration;
            }
            if (chakraCoreSettings.EnableExperimentalFeatures)
            {
                attributes |= JsRuntimeAttributes.EnableExperimentalFeatures;
            }

#if NETSTANDARD1_3
            _dispatcher = new ScriptDispatcher();
#else
            _dispatcher = new ScriptDispatcher(chakraCoreSettings.MaxStackSize);
#endif
            _promiseContinuationCallback = PromiseContinuationCallback;

            try
            {
                _dispatcher.Invoke(() =>
                {
                    _jsRuntime             = JsRuntime.Create(attributes, null);
                    _jsRuntime.MemoryLimit = settings.MemoryLimit;

                    _jsContext = _jsRuntime.CreateContext();
                    if (_jsContext.IsValid)
                    {
                        _jsContext.AddRef();
                    }
                });
            }
            catch (DllNotFoundException e)
            {
                throw WrapDllNotFoundException(e);
            }
            catch (Exception e)
            {
                throw CoreErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true);
            }
            finally
            {
                if (!_jsContext.IsValid)
                {
                    Dispose();
                }
            }
        }
Esempio n. 5
0
        private async Task <string> parseChapterPageAsync(ChapterDataDetailed chapter, HtmlDocument document)
        {
            // var preview = "7966638.html",next = "7966640.html",bid = "11341",book="剑娘",zid = "7966639",chapter = "第893章 舰娘再现";document.onkeydown= jumpPage;
            var rscript = document.DocumentNode.SelectNodes("/html/head/script").Last(n => !n.GetInnerText().IsNullOrWhiteSpace());
            var prop    = Helpers.ParseJsKvp(rscript.GetInnerText());

            chapter.Key   = prop["zid"];
            chapter.Title = prop["chapter"];
            var nk = prop["next"]; // 123567.html

            if (nk.Contains('.'))
            {
                nk = nk.Substring(0, nk.IndexOf('.'));
            }
            else
            {
                nk = null; //the last chapter
            }
            var center = document.GetElementbyId("center");

            chapter.UpdateTime = DateTime.Parse(center.SelectSingleNode("./div[@class='title']/span[last()]").GetInnerText());
            chapter.WordCount  = int.Parse(center.SelectSingleNode("./div[@class='title']/span[last()-1]").GetInnerText());

            var displayTitle = center.SelectSingleNode("./div[@class='title']/h1").GetInnerText();

            if (displayTitle != chapter.Title && displayTitle.EndsWith(chapter.Title))
            {
                chapter.VolumeTitle = displayTitle.Substring(0, displayTitle.Length - chapter.Title.Length).Trim();
            }

            var script  = center.SelectSingleNode("./script");
            var content = document.GetElementbyId("content");

            if (script != null)
            {
                var scr  = script.GetInnerText();
                var uri  = "/ajax/content/";
                var data = default(Dictionary <string, string>);
                IJsValue post(IJsFunction callee, IJsObject caller, bool isConstructCall, IReadOnlyList <IJsValue> arguments)
                {
                    uri  = arguments[0].ToString().CoalesceNullOrEmpty("/ajax/content/");
                    data = ((IDictionary <string, IJsValue>)arguments[1]).ToDictionary(kv => kv.Key, kv => kv.Value.ToString());
                    return(JsUndefined.Instance);
                }

                using (jsrt.CreateContext().Use(true))
                {
                    var jq = JsObject.Create();
                    jq["post"] = JsFunction.Create(post);
                    JsValue.GlobalObject["$"] = jq;
                    JsContext.RunScript(scr);
                }
                var realContent = await Post(new Uri(uri, UriKind.RelativeOrAbsolute), new HttpFormUrlEncodedContent(data));

                var contentDoc = new HtmlDocument();
                contentDoc.Load((await realContent.Content.ReadAsBufferAsync()).AsStream(), document.DeclaredEncoding);
                content = contentDoc.DocumentNode;
            }
            chapter.Content = string.Join("\n", content.Elements("p").EmptyIfNull().Select(p => p.GetInnerText()));

            return(nk);
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            using (JsRuntime runtime = JsRuntime.Create())
            {
                JsContext context = runtime.CreateContext();
                context.AddRef();

                JsSourceContext sourceContext = JsSourceContext.FromIntPtr(IntPtr.Zero);
                var             moduleManager = new EsModuleManager(() => sourceContext++);
                var             scope         = new JsScope(context);

                try
                {
                    JsValue moduleNamespace;

                    // It's not working. Always returns a result equal to `undefined`.
                    JsValue resultValue = moduleManager.EvaluateModuleCode(
                        @"import * as geometry from './geometry/geometry.js';
new geometry.Square(15).area;",
                        "Files/main-with-return-value.js",
                        out moduleNamespace
                        );
                    WriteLine("Return value: {0}", resultValue.ConvertToString().ToString());

                    // It's works. We can return the result value by using the default export.
                    moduleManager.EvaluateModuleCode(
                        @"import * as geometry from './geometry/geometry.js';
export default new geometry.Square(20).area;",
                        "Files/main-with-default-export.js",
                        out moduleNamespace
                        );
                    JsPropertyId defaultPropertyId    = JsPropertyId.FromString("default");
                    JsValue      defaultPropertyValue = moduleNamespace.GetProperty(defaultPropertyId);
                    WriteLine("Default export: {0}", defaultPropertyValue.ConvertToString().ToString());

                    // It's works. We can return the result value by using the named export.
                    moduleManager.EvaluateModuleCode(
                        @"import * as geometry from './geometry/geometry.js';
export let squareArea = new geometry.Square(25).area;",
                        "Files/main-with-named-export.js",
                        out moduleNamespace
                        );
                    JsPropertyId squareAreaPropertyId    = JsPropertyId.FromString("squareArea");
                    JsValue      squareAreaPropertyValue = moduleNamespace.GetProperty(squareAreaPropertyId);
                    WriteLine("Named export: {0}", squareAreaPropertyValue.ConvertToString().ToString());
                }
                catch (JsException e)
                {
                    WriteLine("During working of JavaScript engine an error occurred.");
                    WriteLine();
                    Write(e.Message);

                    var scriptException = e as JsScriptException;
                    if (scriptException != null)
                    {
                        WriteLine();

                        JsValue     errorValue     = scriptException.Metadata.GetProperty("exception");
                        JsValueType errorValueType = errorValue.ValueType;

                        if (errorValueType == JsValueType.Error || errorValueType == JsValueType.Object)
                        {
                            JsValue      messageValue;
                            JsPropertyId stackPropertyId = JsPropertyId.FromString("stack");

                            if (errorValue.HasProperty(stackPropertyId))
                            {
                                messageValue = errorValue.GetProperty(stackPropertyId);
                            }
                            else
                            {
                                messageValue = errorValue.GetProperty("message");
                            }

                            WriteLine(messageValue.ToString());
                        }
                        else if (errorValueType == JsValueType.String)
                        {
                            WriteLine(errorValue.ToString());
                        }
                        else
                        {
                            WriteLine(errorValue.ConvertToString().ToString());
                        }
                    }
                }
                finally
                {
                    scope.Dispose();
                    moduleManager?.Dispose();
                    context.Release();
                }
            }
        }