public DomEventInstance(DomNodeInstance node, EventInfo eventInfo = null)
        {
            Getter = new ClrFunctionInstance(node.Engine, (thisObject, arguments) => _function ?? JsValue.Null);
            Setter = new ClrFunctionInstance(node.Engine, (thisObject, arguments) =>
            {
                if (_handler != null)
                {
                    if (eventInfo != null)
                    {
                        eventInfo.RemoveEventHandler(node.Value, _handler);
                    }

                    _handler  = null;
                    _function = null;
                }

                if (arguments[0].Is <FunctionInstance>())
                {
                    _function = arguments[0].As <FunctionInstance>();
                    _handler  = (s, ev) =>
                    {
                        var sender = s.ToJsValue(node.Context);
                        var args   = ev.ToJsValue(node.Context);
                        _function.Call(sender, new [] { args });
                    };

                    if (eventInfo != null)
                    {
                        eventInfo.AddEventHandler(node.Value, _handler);
                    }
                }

                return(arguments[0]);
            });
        }
示例#2
0
        private static Object AsComplex(this JsValue value, Type targetType, EngineInstance engine)
        {
            var obj        = value.FromJsValue();
            var sourceType = obj.GetType();

            if (sourceType == targetType || sourceType.GetTypeInfo().IsSubclassOf(targetType) || targetType.GetTypeInfo().IsAssignableFrom(sourceType.GetTypeInfo()))
            {
                return(obj);
            }
            else if (targetType.GetTypeInfo().IsSubclassOf(typeof(Delegate)))
            {
                var f = obj as FunctionInstance;

                if (f == null && obj is String b)
                {
                    var e = engine.Jint;
                    var p = new[] { new JsValue(b) };
                    f = new ClrFunctionInstance(e, (_this, args) => e.Eval.Call(_this, p));
                }

                if (f != null)
                {
                    return(targetType.ToDelegate(f, engine));
                }
            }

            var method = sourceType.PrepareConvert(targetType) ??
                         throw new JavaScriptException("[Internal] Could not find corresponding cast target.");

            return(method.Invoke(obj, null));
        }
示例#3
0
 public DomEventInstance(EngineInstance engine, EventInfo eventInfo = null)
 {
     _engine    = engine;
     _eventInfo = eventInfo;
     Getter     = new ClrFunctionInstance(engine.Jint, GetEventHandler);
     Setter     = new ClrFunctionInstance(engine.Jint, SetEventHandler);
 }
示例#4
0
        public virtual void Initialize(bool debugMode)
        {
            if (_behaviorFunctions != null)
            {
                _behaviorFunctionsRun = Database.Scripts.GetScriptRunner(_behaviorFunctions, true, out BehaviorsScript);

                if (debugMode)
                {
                    BehaviorsScript.DebugMode = true;
                }
            }

            _returnMainRun = Database.Scripts.GetScriptRunner(_mainScript, true, out DocumentScript);
            if (DocumentScript == null)
            {
                return;
            }

            if (debugMode)
            {
                DocumentScript.DebugMode = true;
            }

            DocumentScript.ScriptEngine.SetValue(Transformation.LoadTo, new ClrFunctionInstance(DocumentScript.ScriptEngine, Transformation.LoadTo, LoadToFunctionTranslator));

            for (var i = 0; i < LoadToDestinations.Length; i++)
            {
                var collection          = LoadToDestinations[i];
                var name                = Transformation.LoadTo + collection;
                var clrFunctionInstance = new ClrFunctionInstance(DocumentScript.ScriptEngine, name, (value, values) => LoadToFunctionTranslator(collection, value, values));
                DocumentScript.ScriptEngine.SetValue(name, clrFunctionInstance);
            }

            DocumentScript.ScriptEngine.SetValue(Transformation.LoadAttachment, new ClrFunctionInstance(DocumentScript.ScriptEngine, Transformation.LoadAttachment, LoadAttachment));

            const string loadCounter = Transformation.CountersTransformation.Load;

            DocumentScript.ScriptEngine.SetValue(loadCounter, new ClrFunctionInstance(DocumentScript.ScriptEngine, loadCounter, LoadCounter));

            const string loadTimeSeries = Transformation.TimeSeriesTransformation.LoadTimeSeries.Name;

            DocumentScript.ScriptEngine.SetValue(loadTimeSeries, new ClrFunctionInstance(DocumentScript.ScriptEngine, loadTimeSeries, LoadTimeSeries));

            DocumentScript.ScriptEngine.SetValue("getAttachments", new ClrFunctionInstance(DocumentScript.ScriptEngine, "getAttachments", GetAttachments));

            DocumentScript.ScriptEngine.SetValue("hasAttachment", new ClrFunctionInstance(DocumentScript.ScriptEngine, "hasAttachment", HasAttachment));

            DocumentScript.ScriptEngine.SetValue("getCounters", new ClrFunctionInstance(DocumentScript.ScriptEngine, "getCounters", GetCounters));

            DocumentScript.ScriptEngine.SetValue("hasCounter", new ClrFunctionInstance(DocumentScript.ScriptEngine, "hasCounter", HasCounter));

            const string hasTimeSeries = Transformation.TimeSeriesTransformation.HasTimeSeries.Name;

            DocumentScript.ScriptEngine.SetValue(hasTimeSeries, new ClrFunctionInstance(DocumentScript.ScriptEngine, hasTimeSeries, HasTimeSeries));

            const string getTimeSeries = Transformation.TimeSeriesTransformation.GetTimeSeries.Name;

            DocumentScript.ScriptEngine.SetValue(getTimeSeries, new ClrFunctionInstance(DocumentScript.ScriptEngine, getTimeSeries, GetTimeSeries));
        }
示例#5
0
 public DomEventInstance(EngineInstance engine, MethodInfo addHandler, MethodInfo removeHandler)
 {
     _engine        = engine;
     _addHandler    = addHandler;
     _removeHandler = removeHandler;
     Getter         = new ClrFunctionInstance(engine.Jint, GetEventHandler);
     Setter         = new ClrFunctionInstance(engine.Jint, SetEventHandler);
 }
        public DomFunctionInstance(EngineInstance engine, MethodInfo method)
            : base(engine.Jint, method.GetParameterNames(), null, false)
        {
            var toString = new ClrFunctionInstance(Engine, ToString);

            _engine = engine;
            _method = method;
            FastAddProperty("toString", toString, true, false, true);
        }
        public DomDelegateInstance(EngineInstance engine, String officialName, Func <JsValue, JsValue[], JsValue> func)
            : base(engine.Jint, Array.Empty <String>(), null, false)
        {
            var toString = new ClrFunctionInstance(Engine, ToString);

            _instance     = engine;
            _func         = func;
            _officialName = officialName;
            FastAddProperty("toString", toString, true, false, true);
        }
        public DomConstructorInstance(EngineInstance engine, Type type)
            : base(engine.Jint, null, null, false)
        {
            var toString = new ClrFunctionInstance(Engine, ToString);

            _objectPrototype = engine.GetDomPrototype(type);
            _instance        = engine;
            FastAddProperty("toString", toString, true, false, true);
            FastAddProperty("prototype", _objectPrototype, false, false, false);
            _objectPrototype.FastAddProperty("constructor", this, true, false, true);
        }
示例#9
0
        protected override void Initialize()
        {
            _canReturnToPool = false;
            var args = _args;

            DefinePropertyOrThrow(CommonProperties.Length, new PropertyDescriptor(_args.Length, PropertyFlag.NonEnumerable));

            if (_func is null)
            {
                // unmapped
                ParameterMap = null;

                for (uint i = 0; i < (uint)args.Length; i++)
                {
                    var val = args[i];
                    CreateDataProperty(JsNumber.Create(i), val);
                }

                DefinePropertyOrThrow(CommonProperties.Callee, _engine._callerCalleeArgumentsThrowerNonConfigurable);
            }
            else
            {
                ObjectInstance map = null;
                if (args.Length > 0)
                {
                    var mappedNamed = _mappedNamed.Value;
                    mappedNamed.Clear();

                    map = Engine.Object.Construct(Arguments.Empty);

                    for (uint i = 0; i < (uint)args.Length; i++)
                    {
                        SetOwnProperty(i, new PropertyDescriptor(args[i], PropertyFlag.ConfigurableEnumerableWritable));
                        if (i < _names.Length)
                        {
                            var name = _names[i];
                            if (mappedNamed.Add(name))
                            {
                                map.SetOwnProperty(i, new ClrAccessDescriptor(_env, Engine, name));
                            }
                        }
                    }
                }

                ParameterMap = map;

                // step 13
                DefinePropertyOrThrow(CommonProperties.Callee, new PropertyDescriptor(_func, PropertyFlag.NonEnumerable));
            }

            var iteratorFunction = new ClrFunctionInstance(Engine, "iterator", _engine.Array.PrototypeObject.Values, 0, PropertyFlag.Configurable);

            DefinePropertyOrThrow(GlobalSymbolRegistry.Iterator, new PropertyDescriptor(iteratorFunction, PropertyFlag.Writable | PropertyFlag.Configurable));
        }
示例#10
0
            public bool TryGetCallable(Engine engine, object callee, out JsValue value)
            {
                if (callee is Reference reference)
                {
                    var name = reference.GetReferencedName().AsString();
                    if (name == "filter")
                    {
                        value = new ClrFunctionInstance(engine, "map", (thisObj, values) => engine.Realm.Intrinsics.Array.ArrayCreate(0));
                        return(true);
                    }
                }

                value = new ClrFunctionInstance(engine, "anonymous", (thisObj, values) => thisObj);
                return(true);
            }
示例#11
0
        private List <MapMetadata> InitializeEngine(IndexDefinition definition, List <string> maps, string mapCode)
        {
            OnInitializeEngine(_engine);

            var loadFunc = new ClrFunctionInstance(_engine, JavaScriptIndex.Load, LoadDocument);

            ObjectInstance noTrackingObject = new ObjectInstance(_engine);

            noTrackingObject.FastAddProperty(JavaScriptIndex.Load, loadFunc, false, false, false);
            _engine.SetValue(JavaScriptIndex.NoTracking, noTrackingObject);

            _engine.SetValue(JavaScriptIndex.Load, loadFunc);
            _engine.SetValue(JavaScriptIndex.CmpXchg, new ClrFunctionInstance(_engine, JavaScriptIndex.CmpXchg, LoadCompareExchangeValue));
            _engine.SetValue("tryConvertToNumber", new ClrFunctionInstance(_engine, "tryConvertToNumber", TryConvertToNumber));
            _engine.SetValue("recurse", new ClrFunctionInstance(_engine, "recurse", Recurse));

            _engine.ExecuteWithReset(Code);
            _engine.ExecuteWithReset(mapCode);

            var sb = new StringBuilder();

            if (definition.AdditionalSources != null)
            {
                foreach (var script in definition.AdditionalSources.Values)
                {
                    _engine.ExecuteWithReset(script);

                    sb.Append(Environment.NewLine);
                    sb.AppendLine(script);
                }
            }

            var mapReferencedCollections = new List <MapMetadata>();
            var additionalSources        = sb.ToString();

            foreach (var map in maps)
            {
                var result = ExecuteCodeAndCollectReferencedCollections(map, additionalSources);
                mapReferencedCollections.Add(result);
            }

            if (definition.Reduce != null)
            {
                _engine.ExecuteWithReset(definition.Reduce);
            }

            return(mapReferencedCollections);
        }
示例#12
0
    /// <summary>
    /// https://tc39.es/ecma262/#sec-execute-async-module
    /// </summary>
    private Completion ExecuteAsyncModule()
    {
        if (Status != ModuleStatus.Evaluating && Status != ModuleStatus.EvaluatingAsync || !_hasTLA)
        {
            ExceptionHelper.ThrowInvalidOperationException("Error while evaluating module: Module is in an invalid state");
        }

        var capability = PromiseConstructor.NewPromiseCapability(_engine, _realm.Intrinsics.Promise);

        var onFullfilled = new ClrFunctionInstance(_engine, "fulfilled", AsyncModuleExecutionFulfilled, 1, PropertyFlag.Configurable);
        var onRejected   = new ClrFunctionInstance(_engine, "rejected", AsyncModuleExecutionRejected, 1, PropertyFlag.Configurable);

        PromiseOperations.PerformPromiseThen(_engine, (PromiseInstance)capability.PromiseInstance, onFullfilled, onRejected, null);

        return(ExecuteModule(capability));
    }
示例#13
0
        public void Initalize()
        {
            _returnRun = Database.Scripts.GetScriptRunner(_key, true, out SingleRun);
            if (SingleRun == null)
            {
                return;
            }
            SingleRun.ScriptEngine.SetValue(Transformation.LoadTo, new ClrFunctionInstance(SingleRun.ScriptEngine, LoadToFunctionTranslator));

            SingleRun.ScriptEngine.SetValue(Transformation.LoadAttachment, new ClrFunctionInstance(SingleRun.ScriptEngine, LoadAttachment));

            for (var i = 0; i < LoadToDestinations.Length; i++)
            {
                var collection          = LoadToDestinations[i];
                var clrFunctionInstance = new ClrFunctionInstance(SingleRun.ScriptEngine, (value, values) => LoadToFunctionTranslator(collection, value, values));
                SingleRun.ScriptEngine.SetValue(Transformation.LoadTo + collection, clrFunctionInstance);
            }
        }
示例#14
0
        public virtual void Initialize(bool debugMode)
        {
            if (_behaviorFunctions != null)
            {
                _behaviorFunctionsRun = Database.Scripts.GetScriptRunner(_behaviorFunctions, true, out BehaviorsScript);

                if (debugMode)
                {
                    BehaviorsScript.DebugMode = true;
                }
            }

            _returnMainRun = Database.Scripts.GetScriptRunner(_mainScript, true, out DocumentScript);
            if (DocumentScript == null)
            {
                return;
            }

            if (debugMode)
            {
                DocumentScript.DebugMode = true;
            }

            DocumentScript.ScriptEngine.SetValue(Transformation.LoadTo, new ClrFunctionInstance(DocumentScript.ScriptEngine, LoadToFunctionTranslator));

            for (var i = 0; i < LoadToDestinations.Length; i++)
            {
                var collection          = LoadToDestinations[i];
                var clrFunctionInstance = new ClrFunctionInstance(DocumentScript.ScriptEngine, (value, values) => LoadToFunctionTranslator(collection, value, values));
                DocumentScript.ScriptEngine.SetValue(Transformation.LoadTo + collection, clrFunctionInstance);
            }

            DocumentScript.ScriptEngine.SetValue(Transformation.LoadAttachment, new ClrFunctionInstance(DocumentScript.ScriptEngine, LoadAttachment));

            DocumentScript.ScriptEngine.SetValue(Transformation.LoadCounter, new ClrFunctionInstance(DocumentScript.ScriptEngine, LoadCounter));

            DocumentScript.ScriptEngine.SetValue("getAttachments", new ClrFunctionInstance(DocumentScript.ScriptEngine, GetAttachments));

            DocumentScript.ScriptEngine.SetValue("hasAttachment", new ClrFunctionInstance(DocumentScript.ScriptEngine, HasAttachment));

            DocumentScript.ScriptEngine.SetValue("getCounters", new ClrFunctionInstance(DocumentScript.ScriptEngine, GetCounters));

            DocumentScript.ScriptEngine.SetValue("hasCounter", new ClrFunctionInstance(DocumentScript.ScriptEngine, HasCounter));
        }
示例#15
0
        public bool TryGetCallable(Engine engine, object callee, out JsValue value)
        {
            if (callee is Reference reference)
            {
                var baseValue = reference.GetBase();

                if (baseValue.IsUndefined() ||
                    baseValue.IsArray() && baseValue.AsArray().GetLength() == 0)
                {
                    var name = reference.GetReferencedName();
                    switch (name)
                    {
                    case "reduce":
                        value = new ClrFunctionInstance(engine, "reduce", (thisObj, values) => values.Length > 1 ? values[1] : JsValue.Null);
                        return(true);

                    case "concat":
                        value = new ClrFunctionInstance(engine, "concat", (thisObj, values) => values[0]);
                        return(true);

                    case "some":
                    case "includes":
                        value = new ClrFunctionInstance(engine, "some", (thisObj, values) => false);
                        return(true);

                    case "every":
                        value = new ClrFunctionInstance(engine, "every", (thisObj, values) => true);
                        return(true);

                    case "map":
                    case "filter":
                    case "reverse":
                        value = new ClrFunctionInstance(engine, "map", (thisObj, values) => engine.Array.Construct(Array.Empty <JsValue>()));
                        return(true);
                    }
                }
            }

            value = new ClrFunctionInstance(engine, "function", (thisObj, values) => thisObj);
            return(true);
        }
示例#16
0
        public bool TryGetCallable(Engine engine, object reference, out JsValue value)
        {
            value = new ClrFunctionInstance(engine, "anonymous", (thisObj, _) => thisObj);

            return(true);
        }
示例#17
0
        private JsValue Replace(JsValue thisObj, JsValue[] arguments)
        {
            TypeConverter.CheckObjectCoercible(Engine, thisObj);

            var thisString   = TypeConverter.ToString(thisObj);
            var searchValue  = arguments.At(0);
            var replaceValue = arguments.At(1);

            // If the second parameter is not a function we create one
            var replaceFunction = replaceValue.TryCast <FunctionInstance>();

            if (replaceFunction == null)
            {
                replaceFunction = new ClrFunctionInstance(Engine, (self, args) =>
                {
                    var replaceString = TypeConverter.ToString(replaceValue);
                    var matchValue    = TypeConverter.ToString(args.At(0));
                    var matchIndex    = (int)TypeConverter.ToInteger(args.At(args.Length - 2));

                    // Check if the replacement string contains any patterns.
                    bool replaceTextContainsPattern = replaceString.IndexOf('$') >= 0;

                    // If there is no pattern, replace the pattern as is.
                    if (replaceTextContainsPattern == false)
                    {
                        return(replaceString);
                    }

                    // Patterns
                    // $$	Inserts a "$".
                    // $&	Inserts the matched substring.
                    // $`	Inserts the portion of the string that precedes the matched substring.
                    // $'	Inserts the portion of the string that follows the matched substring.
                    // $n or $nn	Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
                    var replacementBuilder = new StringBuilder();
                    for (int i = 0; i < replaceString.Length; i++)
                    {
                        char c = replaceString[i];
                        if (c == '$' && i < replaceString.Length - 1)
                        {
                            c = replaceString[++i];
                            if (c == '$')
                            {
                                replacementBuilder.Append('$');
                            }
                            else if (c == '&')
                            {
                                replacementBuilder.Append(matchValue);
                            }
                            else if (c == '`')
                            {
                                replacementBuilder.Append(thisString.Substring(0, matchIndex));
                            }
                            else if (c == '\'')
                            {
                                replacementBuilder.Append(thisString.Substring(matchIndex + matchValue.Length));
                            }
                            else if (c >= '0' && c <= '9')
                            {
                                int matchNumber1 = c - '0';

                                // The match number can be one or two digits long.
                                int matchNumber2 = 0;
                                if (i < replaceString.Length - 1 && replaceString[i + 1] >= '0' && replaceString[i + 1] <= '9')
                                {
                                    matchNumber2 = matchNumber1 * 10 + (replaceString[i + 1] - '0');
                                }

                                // Try the two digit capture first.
                                if (matchNumber2 > 0 && matchNumber2 < args.Length - 2)
                                {
                                    // Two digit capture replacement.
                                    replacementBuilder.Append(TypeConverter.ToString(args[matchNumber2]));
                                    i++;
                                }
                                else if (matchNumber1 > 0 && matchNumber1 < args.Length - 2)
                                {
                                    // Single digit capture replacement.
                                    replacementBuilder.Append(TypeConverter.ToString(args[matchNumber1]));
                                }
                                else
                                {
                                    // Capture does not exist.
                                    replacementBuilder.Append('$');
                                    i--;
                                }
                            }
                            else
                            {
                                // Unknown replacement pattern.
                                replacementBuilder.Append('$');
                                replacementBuilder.Append(c);
                            }
                        }
                        else
                        {
                            replacementBuilder.Append(c);
                        }
                    }

                    return(replacementBuilder.ToString());
                });
            }

            // searchValue is a regular expression

            if (searchValue.IsNull())
            {
                searchValue = new JsValue(Null.Text);
            }
            if (searchValue.IsUndefined())
            {
                searchValue = new JsValue(Undefined.Text);
            }

            var rx = TypeConverter.ToObject(Engine, searchValue) as RegExpInstance;

            if (rx != null)
            {
                // Replace the input string with replaceText, recording the last match found.
                string result = rx.Value.Replace(thisString, match =>
                {
                    var args = new List <JsValue>();

                    for (var k = 0; k < match.Groups.Count; k++)
                    {
                        var group = match.Groups[k];
                        if (group.Success)
                        {
                            args.Add(group.Value);
                        }
                    }

                    args.Add(match.Index);
                    args.Add(thisString);

                    var v = TypeConverter.ToString(replaceFunction.Call(Undefined.Instance, args.ToArray()));
                    return(v);
                }, rx.Global == true ? -1 : 1);

                // Set the deprecated RegExp properties if at least one match was found.
                //if (lastMatch != null)
                //    this.Engine.RegExp.SetDeprecatedProperties(input, lastMatch);

                return(result);
            }

            // searchValue is a string
            else
            {
                var substr = TypeConverter.ToString(searchValue);

                // Find the first occurrance of substr.
                int start = thisString.IndexOf(substr, StringComparison.Ordinal);
                if (start == -1)
                {
                    return(thisString);
                }
                int end = start + substr.Length;

                var args = new List <JsValue>();
                args.Add(substr);
                args.Add(start);
                args.Add(thisString);

                var replaceString = TypeConverter.ToString(replaceFunction.Call(Undefined.Instance, args.ToArray()));

                // Replace only the first match.
                var result = new StringBuilder(thisString.Length + (substr.Length - substr.Length));
                result.Append(thisString, 0, start);
                result.Append(replaceString);
                result.Append(thisString, end, thisString.Length - end);
                return(result.ToString());
            }
        }
示例#18
0
 public void ResolvePromise(JsValue promise, ClrFunctionInstance callback)
 {
     ManticoreJsObject.Get("asCallback").As <FunctionInstance>().Call(ManticoreJsObject, new JsValue[] { promise, callback });
 }
示例#19
0
 public bool TryGetCallable(Engine engine, object callee, out JsValue value)
 {
     value = new ClrFunctionInstance(engine, (thisObj, values) => thisObj);
     return(true);
 }