Esempio n. 1
0
        internal JToken ConvertBack(JTokenType type, JsValue value)
        {
            switch (type)
            {
            case JTokenType.Array:
                if (value.IsArray())
                {
                    var array = value.AsArray();
                    return(new JArray(array.Properties.Where(k => ArrayInstance.IsArrayIndex(new JsValue(k.Key))).Select(kvp => ConvertBack(kvp.Value.Value ?? JsValue.Null))));
                }
                break;

            case JTokenType.Boolean:
                if (value.IsBoolean())
                {
                    return(new JValue(value.AsBoolean()));
                }
                break;

            case JTokenType.Date:
                if (value.IsDate())
                {
                    return(new JValue(value.AsDate()));
                }
                break;

            case JTokenType.Float:
                if (value.IsNumber())
                {
                    return(new JValue((float)value.AsNumber()));
                }
                break;

            case JTokenType.Integer:
                if (value.IsNumber())
                {
                    return(new JValue((int)value.AsNumber()));
                }
                break;

            case JTokenType.String:
                if (value.IsString())
                {
                    return(JValue.CreateString(value.AsString()));
                }
                break;
            }
            return(ConvertBack(value));
        }
Esempio n. 2
0
        public static ObjectInstance ToObject(Engine engine, JsValue value)
        {
            if (value.IsObject())
            {
                return(value.AsObject());
            }

            if (value == Undefined.Instance)
            {
                throw new JavaScriptException(engine.TypeError);
            }

            if (value == Null.Instance)
            {
                throw new JavaScriptException(engine.TypeError);
            }

            if (value.IsBoolean())
            {
                return(engine.Boolean.Construct(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(engine.Number.Construct(value.AsNumber()));
            }

            if (value.IsString())
            {
                return(engine.String.Construct(value.AsString()));
            }

            throw new JavaScriptException(engine.TypeError);
        }
Esempio n. 3
0
        /// <inheritdoc/>
        public override AnalysisValueIntermediateResult ObjectResultForResultRow(ICrmDataSourceRow row)
        {
            var objectResultArray = new List <JsValue>();

            foreach (AnalysisValueFunction func in this.Arguments)
            {
                AnalysisValueIntermediateResult res = func.ObjectResultForResultRow(row);
                if (res == null || !res.Complete)
                {
                    objectResultArray.Add(new JsValue(0));
                }
                else
                {
                    objectResultArray.Add(res.JavascriptResult);
                }
            }

            JsValue resultValue = this.JavascriptFunction.Invoke(objectResultArray.ToArray());

            if (resultValue.IsString())
            {
                return(new AnalysisValueIntermediateResult(resultValue.ToString()));
            }
            else if (resultValue.IsNumber())
            {
                return(new AnalysisValueIntermediateResult(resultValue.ToDouble()));
            }
            else
            {
                return(new AnalysisValueIntermediateResult(resultValue));
            }
        }
Esempio n. 4
0
        public static Nullable <Int32> ToOptionalInt32(JsValue arg)
        {
            if (arg.IsNumber())
            {
                return(TypeConverter.ToInt32(arg));
            }

            return(null);
        }
        public static double AsNumber(this JsValue value)
        {
            if (!value.IsNumber())
            {
                ThrowWrongTypeException(value, "number");
            }

            return(((JsNumber)value)._value);
        }
        private JsValue ToNumberString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && (ReferenceEquals(thisObject.TryCast <NumberInstance>(), null)))
            {
                ExceptionHelper.ThrowTypeError(_engine);
            }

            var radix = arguments.At(0).IsUndefined()
                ? 10
                : (int)TypeConverter.ToInteger(arguments.At(0));

            if (radix < 2 || radix > 36)
            {
                ExceptionHelper.ThrowRangeError(_engine, "radix must be between 2 and 36");
            }

            var x = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(x))
            {
                return("NaN");
            }

            if (x == 0)
            {
                return(JsString.NumberZeroString);
            }

            if (double.IsPositiveInfinity(x) || x >= double.MaxValue)
            {
                return("Infinity");
            }

            if (x < 0)
            {
                return("-" + ToNumberString(-x, arguments));
            }

            if (radix == 10)
            {
                return(ToNumberString(x));
            }

            var integer  = (long)x;
            var fraction = x - integer;

            string result = ToBase(integer, radix);

            if (fraction != 0)
            {
                result += "." + ToFractionBase(fraction, radix);
            }

            return(result);
        }
Esempio n. 7
0
        public static RectOffset FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (int)obj.AsNumber();
                return(new RectOffset(num, num, num, num));
            }

            if (obj.IsArray())
            {
                var len = obj.AsArray().Length;

                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];
                var v2 = obj.AsArray()[2];
                var v3 = obj.AsArray()[3];

                var top    = v0.IsNumber() ? (int)v0.AsNumber() : 0;
                var right  = v1.IsNumber() ? (int)v1.AsNumber() : (len < 2 ? top : 0);
                var bottom = v2.IsNumber() ? (int)v2.AsNumber() : top;
                var left   = v3.IsNumber() ? (int)v3.AsNumber() : right;
                return(new RectOffset(left, right, top, bottom));
            }

            if (obj.IsObject())
            {
                var ob   = obj.AsObject();
                var vert = ob.Get("vertical");
                var hor  = ob.Get("horizontal");

                var v0 = ob.Get("top");
                var v1 = ob.Get("right");
                var v2 = ob.Get("bottom");
                var v3 = ob.Get("left");

                var val1 = vert.IsNumber() ? (int)vert.AsNumber() : 0;
                var val2 = hor.IsNumber() ? (int)hor.AsNumber() : 0;

                var top    = v0.IsNumber() ? (int)v0.AsNumber() : val1;
                var right  = v1.IsNumber() ? (int)v1.AsNumber() : val2;
                var bottom = v2.IsNumber() ? (int)v2.AsNumber() : val1;
                var left   = v3.IsNumber() ? (int)v3.AsNumber() : val2;

                return(new RectOffset(left, right, top, bottom));
            }

            return(null);
        }
Esempio n. 8
0
        private JsValue ToNumberString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && (thisObject.TryCast <NumberInstance>() == null))
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var radix = arguments.At(0) == JsValue.Undefined ? 10 : (int)TypeConverter.ToInteger(arguments.At(0));

            if (radix < 2 || radix > 36)
            {
                throw new JavaScriptException(Engine.RangeError, "radix must be between 2 and 36");
            }

            var x = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(x))
            {
                return("NaN");
            }

            if (x.Equals(0))
            {
                return("0");
            }

            if (double.IsPositiveInfinity(x) || x >= double.MaxValue)
            {
                return("Infinity");
            }

            if (x < 0)
            {
                return("-" + ToNumberString(-x, arguments));
            }

            if (radix == 10)
            {
                return(ToNumberString(x));
            }

            var integer  = (long)x;
            var fraction = x - integer;

            string result = ToBase(integer, radix);

            if (!fraction.Equals(0))
            {
                result += "." + ToFractionBase(fraction, radix);
            }

            return(result);
        }
Esempio n. 9
0
        public static object GetItem(this Jint.Native.Array.ArrayInstance a, int index)
        {
            JsValue l = a.Get(index.ToString());

            if (l.IsNull())
            {
                return(null);
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsBoolean())
            {
                return(l.AsBoolean());
            }
            if (l.IsString())
            {
                return(l.AsString());
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsUndefined())
            {
                return("undefined");
            }
            if (l.IsObject())
            {
                return(l.AsObject());
            }
            if (l.IsRegExp())
            {
                return(l.AsObject());
            }

            throw new ArgumentException(string.Format("Cannot deal with JsValue {0}", l));
        }
Esempio n. 10
0
 private string GetDebugValue(JsValue obj, bool recursive)
 {
     if (obj.IsString())
     {
         var debugValue = obj.ToString();
         return(recursive ? '"' + debugValue + '"' : debugValue);
     }
     if (obj.IsArray())
     {
         var sb      = new StringBuilder("[");
         var array   = obj.AsArray();
         var jsValue = (int)array.Get("length").AsNumber();
         for (var i = 0; i < jsValue; i++)
         {
             if (i != 0)
             {
                 sb.Append(",");
             }
             sb.Append(GetDebugValue(array.Get(i.ToString()), true));
         }
         sb.Append("]");
         return(sb.ToString());
     }
     if (obj.IsObject())
     {
         var result = new ScriptRunnerResult(this, obj);
         using (var jsonObj = result.TranslateToObject(_jsonCtx))
         {
             return(jsonObj.ToString());
         }
     }
     if (obj.IsBoolean())
     {
         return(obj.AsBoolean().ToString());
     }
     if (obj.IsNumber())
     {
         return(obj.AsNumber().ToString(CultureInfo.InvariantCulture));
     }
     if (obj.IsNull())
     {
         return("null");
     }
     if (obj.IsUndefined())
     {
         return("undefined");
     }
     return(obj.ToString());
 }
Esempio n. 11
0
        public object ConvertFromJs(JsValue jsValue)
        {
            if (jsValue == _getEngine().Global)
            {
                return(_global);
            }

            if (jsValue.IsUndefined())
            {
                return(null);
            }

            if (jsValue.IsObject())
            {
                switch (jsValue.AsObject())
                {
                case IObjectWrapper wrapper:
                    return(wrapper.Target);

                case ClrPrototype proto:
                    return(proto);

                case ObjectInstance objInst:

                    //todo: instantiate object instead of distionary
                    return(objInst.GetOwnProperties().ToDictionary(x => x.Key, x =>
                                                                   ConvertFromJs(objInst.Get(x.Key))));
                }

                return(jsValue);
            }

            if (jsValue.IsBoolean())
            {
                return(jsValue.AsBoolean());
            }

            if (jsValue.IsString())
            {
                return(jsValue.AsString());
            }

            if (jsValue.IsNumber())
            {
                return(jsValue.AsNumber());
            }

            return(null);
        }
Esempio n. 12
0
        public static Vector4?FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (float)obj.AsNumber();
                return(new Vector4(num, num, num, num));
            }

            if (obj.IsArray())
            {
                var len = obj.AsArray().Length;

                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];
                var v2 = obj.AsArray()[2];
                var v3 = obj.AsArray()[3];

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var z = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var w = v3.IsNumber() ? (float)v3.AsNumber() : 0;
                return(new Vector4(x, y, z, w));
            }

            if (obj.IsObject())
            {
                var ob = obj.AsObject();

                var v0 = ob.Get("x");
                var v1 = ob.Get("y");
                var v2 = ob.Get("z");
                var v3 = ob.Get("w");

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                var z = v2.IsNumber() ? (float)v2.AsNumber() : 0;
                var w = v3.IsNumber() ? (float)v3.AsNumber() : 0;

                return(new Vector4(x, y, z, w));
            }

            return(null);
        }
Esempio n. 13
0
        /// <summary>
        /// https://tc39.es/ecma262/#sec-tonumeric
        /// </summary>
        public static JsValue ToNumeric(JsValue value)
        {
            if (value.IsNumber() || value.IsBigInt())
            {
                return(value);
            }

            var primValue = ToPrimitive(value, Types.Number);

            if (primValue.IsBigInt())
            {
                return(primValue);
            }

            return(ToNumber(primValue));
        }
        public void ShouldBeANumber()
        {
            var value = new JsValue(2);

            Assert.Equal(false, value.IsBoolean());
            Assert.Equal(false, value.IsArray());
            Assert.Equal(false, value.IsDate());
            Assert.Equal(false, value.IsNull());
            Assert.Equal(true, value.IsNumber());
            Assert.Equal(2, value.AsNumber());
            Assert.Equal(false, value.IsObject());
            Assert.Equal(true, value.IsPrimitive());
            Assert.Equal(false, value.IsRegExp());
            Assert.Equal(false, value.IsString());
            Assert.Equal(false, value.IsUndefined());
        }
Esempio n. 15
0
        private static bool EqualUnlikely(JsValue x, JsValue y)
        {
            if (x._type == InternalTypes.Null && y._type == InternalTypes.Undefined)
            {
                return(true);
            }

            if (x._type == InternalTypes.Undefined && y._type == InternalTypes.Null)
            {
                return(true);
            }

            if (x.IsNumber() && y.IsString())
            {
                return(Equal(x, TypeConverter.ToNumber(y)));
            }

            if (x.IsString() && y.IsNumber())
            {
                return(Equal(TypeConverter.ToNumber(x), y));
            }

            if (x.IsBoolean())
            {
                return(Equal(TypeConverter.ToNumber(x), y));
            }

            if (y.IsBoolean())
            {
                return(Equal(x, TypeConverter.ToNumber(y)));
            }

            const InternalTypes stringOrNumber = InternalTypes.String | InternalTypes.Integer | InternalTypes.Number;

            if (y.IsObject() && (x._type & stringOrNumber) != 0)
            {
                return(Equal(x, TypeConverter.ToPrimitive(y)));
            }

            if (x.IsObject() && ((y._type & stringOrNumber) != 0))
            {
                return(Equal(TypeConverter.ToPrimitive(x), y));
            }

            return(false);
        }
Esempio n. 16
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static bool ToBoolean(JsValue o)
        {
            if (o.IsObject())
            {
                return true;
            }

            if (o == Undefined.Instance || o == Null.Instance)
            {
                return false;
            }
            
            if (o.IsBoolean())
            {
                return o.AsBoolean();
            }

            if (o.IsNumber())
            {
                var n = o.AsNumber();
                if (n.Equals(0) || double.IsNaN(n))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

            if (o.IsString())
            {
                var s = o.AsString();
                if (String.IsNullOrEmpty(s))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

            return true;
        }
Esempio n. 17
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static bool ToBoolean(JsValue o)
        {
            if (o.IsObject())
            {
                return(true);
            }

            if (o == Undefined.Instance || o == Null.Instance)
            {
                return(false);
            }

            if (o.IsBoolean())
            {
                return(o.AsBoolean());
            }

            if (o.IsNumber())
            {
                var n = o.AsNumber();
                if (n.Equals(0) || double.IsNaN(n))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }

            if (o.IsString())
            {
                var s = o.AsString();
                if (String.IsNullOrEmpty(s))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }

            return(true);
        }
Esempio n. 18
0
 public static KeyCode AsKeyCode(JsValue value)
 {
     if (value == null)
     {
         Logger.Warn("invalid keycode: " + value);
         return(KeyCode.None);
     }
     else if (value.IsNumber())
     {
         return((KeyCode)TypeConverter.ToInt32(value));
     }
     else if (value.IsString())
     {
         return(AsKeyCode(TypeConverter.ToString(value)));
     }
     Logger.Warn("invalid keycode: " + value);
     return(KeyCode.None);
 }
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToString(JsValue o)
        {
            if (o == null)
            {
                return(null);
            }
            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o.IsString())
            {
                return(o.AsString());
            }

            if (o == Undefined.Instance)
            {
                return(Undefined.Text);
            }

            if (o == Null.Instance)
            {
                return(Null.Text);
            }

            if (o.IsBoolean())
            {
                return(o.AsBoolean() ? "true" : "false");
            }

            if (o.IsNumber())
            {
                return(NumberPrototype.ToNumberString(o.AsNumber()));
            }

            return(ToString(ToPrimitive(o, Types.String)));
        }
Esempio n. 20
0
        public virtual string PutDocument(string key, JsValue document, JsValue metadata, JsValue etagJs, Engine engine)
        {
            if (document.IsObject() == false)
            {
                throw new InvalidOperationException(
                          $"Created document must be a valid object which is not null or empty. Document key: '{key}'.");
            }

            long?etag = null;

            if (etagJs.IsNumber())
            {
                etag = (long)etagJs.AsNumber();
            }
            else if (etagJs.IsNull() == false && etagJs.IsUndefined() == false && etagJs.ToString() != "None")
            {
                throw new InvalidOperationException($"Invalid ETag value for document '{key}'");
            }

            var data = ToBlittable(document.AsObject());

            if (metadata.IsObject())
            {
                data["@metadata"] = ToBlittable(metadata.AsObject());
            }

            if (DebugMode)
            {
                DebugActions.PutDocument.Add(new DynamicJsonValue
                {
                    ["Key"]  = key,
                    ["Etag"] = etag,
                    ["Data"] = data,
                });
            }

            var dataReader = _context.ReadObject(data, key, BlittableJsonDocumentBuilder.UsageMode.ToDisk);
            var put        = _database.DocumentsStorage.Put(_context, key, etag, dataReader);

            return(put.Key);
        }
Esempio n. 21
0
        public object UncastJsValue(JsValue value)
        {
            if (value.IsBoolean())
            {
                return(value.AsBoolean());
            }
            if (value.IsNumber())
            {
                return(value.AsNumber());
            }
            if (value.IsObject())
            {
                return(value.AsObject());
            }
            if (value.IsString())
            {
                return(value.AsString());
            }

            return(null);
        }
Esempio n. 22
0
        public static Vector2?FromJsValue(JsValue obj)
        {
            if (obj == null || obj.IsNull() || obj.IsUndefined())
            {
                return(null);
            }

            if (obj.IsNumber())
            {
                var num = (float)obj.AsNumber();
                return(new Vector2(num, num));
            }

            if (obj.IsArray())
            {
                var v0 = obj.AsArray()[0];
                var v1 = obj.AsArray()[1];

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;
                return(new Vector2(x, y));
            }

            if (obj.IsObject())
            {
                var ob = obj.AsObject();

                var v0 = ob.Get("x");
                var v1 = ob.Get("y");

                var x = v0.IsNumber() ? (float)v0.AsNumber() : 0;
                var y = v1.IsNumber() ? (float)v1.AsNumber() : 0;

                return(new Vector2(x, y));
            }

            return(null);
        }
Esempio n. 23
0
        private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && (thisObject.TryCast<NumberInstance>() == null))
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var m = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(m))
            {
                return "NaN";
            }

            if (m.Equals(0))
            {
                return "0";
            }

            if (m < 0)
            {
                return "-" + ToLocaleString(-m, arguments);
            }

            if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
            {
                return "Infinity";
            }

            if (double.IsNegativeInfinity(m) || m <= -double.MaxValue)
            {
                return "-Infinity";
            }

            return m.ToString("n", Engine.Options.GetCulture());
        }
Esempio n. 24
0
        private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && (thisObject.TryCast <NumberInstance>() == null))
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var m = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(m))
            {
                return("NaN");
            }

            if (m.Equals(0))
            {
                return("0");
            }

            if (m < 0)
            {
                return("-" + ToNumberString(-m));
            }

            if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
            {
                return("Infinity");
            }

            if (double.IsNegativeInfinity(m) || m <= -double.MaxValue)
            {
                return("-Infinity");
            }

            return(m.ToString("n", Engine.Options.GetCulture()));
        }
        private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast <NumberInstance>(), null))
            {
                ExceptionHelper.ThrowTypeError(Engine);
            }

            var m = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(m))
            {
                return("NaN");
            }

            if (m == 0)
            {
                return(JsString.NumberZeroString);
            }

            if (m < 0)
            {
                return("-" + ToLocaleString(-m, arguments));
            }

            if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
            {
                return("Infinity");
            }

            if (double.IsNegativeInfinity(m) || m <= -double.MaxValue)
            {
                return("-Infinity");
            }

            return(m.ToString("n", Engine.Options._Culture));
        }
Esempio n. 26
0
        private object ToBlittableValue(JsValue v, string propertyKey, bool recursiveCall)
        {
            if (v.IsBoolean())
            {
                return(v.AsBoolean());
            }

            if (v.IsString())
            {
                const string RavenDataByteArrayToBase64 = "raven-data:byte[];base64,";
                var          valueAsObject = v.ToObject();
                var          value         = valueAsObject?.ToString();
                if (value != null && value.StartsWith(RavenDataByteArrayToBase64))
                {
                    value = value.Remove(0, RavenDataByteArrayToBase64.Length);
                    var byteArray = Convert.FromBase64String(value);
                    return(Encoding.UTF8.GetString(byteArray));
                }
                return(value);
            }

            if (v.IsNumber())
            {
                var num = v.AsNumber();

                KeyValuePair <object, JsValue> property;
                if (_propertiesByValue.TryGetValue(propertyKey, out property))
                {
                    var originalValue = property.Key;
                    if (originalValue is float || originalValue is int)
                    {
                        // If the current value is exactly as the original value, we can return the original value before we made the JS conversion,
                        // which will convert a Int64 to jsFloat.
                        var jsValue = property.Value;
                        if (jsValue.IsNumber() && Math.Abs(num - jsValue.AsNumber()) < double.Epsilon)
                        {
                            return(originalValue);
                        }

                        //We might have change the type of num from Integer to long in the script by design
                        //Making sure the number isn't a real float before returning it as integer
                        if (originalValue is int && (Math.Abs(num - Math.Floor(num)) <= double.Epsilon || Math.Abs(num - Math.Ceiling(num)) <= double.Epsilon))
                        {
                            return((long)num);
                        }
                        return(num); //float
                    }
                }

                // If we don't have the type, assume that if the number ending with ".0" it actually an integer.
                var integer = Math.Truncate(num);
                if (Math.Abs(num - integer) < double.Epsilon)
                {
                    return((long)integer);
                }
                return(num);
            }
            if (v.IsNull() || v.IsUndefined())
            {
                return(null);
            }
            if (v.IsArray())
            {
                var jsArray = v.AsArray();
                var array   = new DynamicJsonArray();

                foreach (var property in jsArray.GetOwnProperties())
                {
                    if (InheritedProperties.Contains(property.Key))
                    {
                        continue;
                    }

                    var jsInstance = property.Value.Value;
                    if (!jsInstance.HasValue)
                    {
                        continue;
                    }

                    var ravenJToken = ToBlittableValue(jsInstance.Value, propertyKey + "[" + property.Key + "]", recursiveCall);
                    if (ravenJToken == null)
                    {
                        continue;
                    }

                    array.Add(ravenJToken);
                }

                return(array);
            }
            if (v.IsDate())
            {
                return(v.AsDate().ToDateTime());
            }
            if (v.IsObject())
            {
                return(ToBlittable(v.AsObject(), propertyKey, recursiveCall));
            }
            if (v.IsRegExp())
            {
                return(null);
            }

            throw new NotSupportedException(v.Type.ToString());
        }
Esempio n. 27
0
        private static object GetValue(JsValue jsValue)
        {
            if (jsValue.IsNull())
            {
                return(null);
            }
            if (jsValue.IsString())
            {
                return(jsValue.AsString());
            }
            if (jsValue.IsBoolean())
            {
                return(jsValue.AsBoolean());
            }
            if (jsValue.IsNumber())
            {
                return(jsValue.AsNumber());
            }
            if (jsValue.IsDate())
            {
                return(jsValue.AsDate());
            }
            if (jsValue is ObjectWrapper ow)
            {
                var target = ow.Target;
                switch (target)
                {
                case LazyStringValue lsv:
                    return(lsv);

                case LazyCompressedStringValue lcsv:
                    return(lcsv);

                case LazyNumberValue lnv:
                    return(lnv);    //should be already blittable supported type.
                }
                ThrowInvalidObject(jsValue);
            }
            else if (jsValue.IsArray())
            {
                var arr   = jsValue.AsArray();
                var array = new object[arr.GetLength()];
                var i     = 0;
                foreach ((var key, var val) in arr.GetOwnProperties())
                {
                    if (key == "length")
                    {
                        continue;
                    }

                    array[i++] = GetValue(val.Value);
                }

                return(array);
            }
            else if (jsValue.IsObject())
            {
                return(jsValue.AsObject());
            }
            if (jsValue.IsUndefined())
            {
                return(null);
            }

            ThrowInvalidObject(jsValue);
            return(null);
        }
Esempio n. 28
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.3
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static double ToNumber(JsValue o)
        {
            // check number first as this is what is usually expected
            if (o.IsNumber())
            {
                return o.AsNumber();
            } 
            
            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o == Undefined.Instance)
            {
                return double.NaN;
            }

            if (o == Null.Instance)
            {
                return 0;
            }

            if (o.IsBoolean())
            {
                return o.AsBoolean() ? 1 : 0;
            }

            if (o.IsString())
            {
                var s = o.AsString().Trim();

                if (String.IsNullOrEmpty(s))
                {
                    return 0;
                }

                if ("+Infinity".Equals(s) || "Infinity".Equals(s))
                {
                    return double.PositiveInfinity;
                }

                if ("-Infinity".Equals(s))
                {
                    return double.NegativeInfinity;
                }

                // todo: use a common implementation with JavascriptParser
                try
                {
                    if (!s.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        var start = s[0];
                        if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
                        {
                            return double.NaN;
                        }

                        double n = Double.Parse(s,
                            NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
                            NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
                            NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
                        if (s.StartsWith("-") && n.Equals(0))
                        {
                            return -0.0;
                        }

                        return n;
                    }

                    int i = int.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                 
                    return i;
                }
                catch (OverflowException)
                {
                    return s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
                }
                catch
                {
                    return double.NaN;
                }
            }

            return ToNumber(ToPrimitive(o, Types.Number));
        }
Esempio n. 29
0
        private LocalVariable GetLocalVariableJS(string key, JsValue value)
        {
            var result = new LocalVariable()
            {
                Name = key, TypeName = value.Type.ToString()
            };

            if (value.IsArray())
            {
                var trueValue = value.AsArray();
                if (trueValue.GetLength() > 0)
                {
                    var props = trueValue.GetOwnProperties();
                    foreach (var item in props)
                    {
                        var ch = GetLocalVariableJS(item.Key, item.Value.Value);
                        result.Children.Add(ch);
                    }
                }
                //result.Value=trueValue.
            }
            else if (value.IsBoolean())
            {
                var trueValue = value.AsBoolean();
                result.Value = trueValue.ToString();
            }
            else if (value.IsDate())
            {
                var trueValue = value.AsDate();
                result.Value = trueValue.ToDateTime().ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if (value.IsNumber())
            {
                var trueValue = value.AsNumber();
                result.Value = trueValue.ToString();
            }
            else if (value.IsString())
            {
                var trueValue = value.AsString();
                result.Value = trueValue;
            }
            else if (value.IsObject())
            {
                var trueValue = value.AsObject();
                //判断对象是否原生JS
                if (trueValue.GetType().Name == "ObjectInstance")
                {
                    var props = trueValue.GetOwnProperties();
                    foreach (var item in props)
                    {
                        var ch = GetLocalVariableJS(item.Key, item.Value.Value);
                        result.Children.Add(ch);
                    }
                }
                else
                {
                    var csharpValue = value.ToObject();
                    if (csharpValue != null)
                    {
                        //只处理DapperRow
                        result = GetLocalVariableCSharp(key, csharpValue);
                        //csharpValue.
                    }
                }
            }
            return(result);
        }
Esempio n. 30
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToString(JsValue o)
        {
            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o.IsString())
            {
                return o.AsString();
            }

            if (o == Undefined.Instance)
            {
                return Undefined.Text;
            }

            if (o == Null.Instance)
            {
                return Null.Text;
            }
            
            if (o.IsBoolean())
            {
                return o.AsBoolean() ? "true" : "false";
            }

            if (o.IsNumber())
            {
                return NumberPrototype.ToNumberString(o.AsNumber());
            }

            return ToString(ToPrimitive(o, Types.String));
        }
Esempio n. 31
0
        public static ObjectInstance ToObject(Engine engine, JsValue value)
        {
            if (value.IsObject())
            {
                return value.AsObject();
            }

            if (value == Undefined.Instance)
            {
                throw new JavaScriptException(engine.TypeError);
            }

            if (value == Null.Instance)
            {
                throw new JavaScriptException(engine.TypeError);
            }

            if (value.IsBoolean())
            {
                return engine.Boolean.Construct(value.AsBoolean());
            }

            if (value.IsNumber())
            {
                return engine.Number.Construct(value.AsNumber());
            }

            if (value.IsString())
            {
                return engine.String.Construct(value.AsString());
            }

            throw new JavaScriptException(engine.TypeError);
        }
Esempio n. 32
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.3
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static double ToNumber(JsValue o)
        {
            // check number first as this is what is usually expected
            if (o.IsNumber())
            {
                return(o.AsNumber());
            }

            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o == Undefined.Instance)
            {
                return(double.NaN);
            }

            if (o == Null.Instance)
            {
                return(0);
            }

            if (o.IsBoolean())
            {
                return(o.AsBoolean() ? 1 : 0);
            }

            if (o.IsString())
            {
                var s = StringPrototype.TrimEx(o.AsString());

                if (String.IsNullOrEmpty(s))
                {
                    return(0);
                }

                if ("+Infinity".Equals(s) || "Infinity".Equals(s))
                {
                    return(double.PositiveInfinity);
                }

                if ("-Infinity".Equals(s))
                {
                    return(double.NegativeInfinity);
                }

                // todo: use a common implementation with JavascriptParser
                try
                {
                    if (!s.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        var start = s[0];
                        if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
                        {
                            return(double.NaN);
                        }

                        double n = Double.Parse(s,
                                                NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
                                                NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
                                                NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
                        if (s.StartsWith("-") && n.Equals(0))
                        {
                            return(-0.0);
                        }

                        return(n);
                    }

                    int i = int.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);

                    return(i);
                }
                catch (OverflowException)
                {
                    return(s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity);
                }
                catch
                {
                    return(double.NaN);
                }
            }

            return(ToNumber(ToPrimitive(o, Types.Number)));
        }
Esempio n. 33
0
        private RavenJToken ToRavenJToken(JsValue v, string propertyKey, bool recursiveCall)
        {
            if (v.IsBoolean())
            {
                return(new RavenJValue(v.AsBoolean()));
            }
            if (v.IsString())
            {
                const string RavenDataByteArrayToBase64 = "raven-data:byte[];base64,";
                var          valueAsObject = v.ToObject();
                var          value         = valueAsObject != null?valueAsObject.ToString() : null;

                if (value != null && value.StartsWith(RavenDataByteArrayToBase64))
                {
                    value = value.Remove(0, RavenDataByteArrayToBase64.Length);
                    var byteArray = Convert.FromBase64String(value);
                    return(new RavenJValue(byteArray));
                }
                return(new RavenJValue(value));
            }
            if (v.IsNumber())
            {
                var num = v.AsNumber();

                KeyValuePair <RavenJValue, JsValue> property;
                if (propertiesByValue.TryGetValue(propertyKey, out property))
                {
                    var originalValue = property.Key;
                    if (originalValue.Type == JTokenType.Float ||
                        originalValue.Type == JTokenType.Integer)
                    {
                        // If the current value is exactly as the original value, we can return the original value before we made the JS conversion,
                        // which will convert a Int64 to jsFloat.
                        var originalJsValue = property.Value;
                        if (originalJsValue.IsNumber() && Math.Abs(num - originalJsValue.AsNumber()) < double.Epsilon)
                        {
                            return(originalValue);
                        }

                        if (originalValue.Type == JTokenType.Integer)
                        {
                            return(new RavenJValue((long)num));
                        }
                        return(new RavenJValue(num));//float
                    }
                }

                // If we don't have the type, assume that if the number ending with ".0" it actually an integer.
                var integer = Math.Truncate(num);
                if (Math.Abs(num - integer) < double.Epsilon)
                {
                    return(new RavenJValue((long)integer));
                }
                return(new RavenJValue(num));
            }
            if (v.IsNull())
            {
                return(RavenJValue.Null);
            }
            if (v.IsUndefined())
            {
                return(RavenJValue.Null);
            }
            if (v.IsArray())
            {
                var jsArray = v.AsArray();
                var rja     = new RavenJArray();

                foreach (var property in jsArray.Properties)
                {
                    if (property.Key == "length")
                    {
                        continue;
                    }

                    var jsInstance = property.Value.Value;
                    if (!jsInstance.HasValue)
                    {
                        continue;
                    }

                    var ravenJToken = ToRavenJToken(jsInstance.Value, propertyKey + "[" + property.Key + "]", recursiveCall);
                    if (ravenJToken == null)
                    {
                        continue;
                    }

                    rja.Add(ravenJToken);
                }

                return(rja);
            }
            if (v.IsObject())
            {
                return(ToRavenJObject(v, propertyKey, recursiveCall));
            }
            if (v.IsRegExp())
            {
                return(null);
            }

            throw new NotSupportedException(v.Type.ToString());
        }
Esempio n. 34
0
        public JsValue Serialize(JsValue value, JsValue replacer, JsValue space)
        {
            _stack = new Stack<object>();

            // for JSON.stringify(), any function passed as the first argument will return undefined
            // if the replacer is not defined. The function is not called either.
            if (value.Is<ICallable>() && replacer == Undefined.Instance) 
            {
                return Undefined.Instance;
            }

            if (replacer.IsObject())
            {
                if (replacer.Is<ICallable>())
                {
                    _replacerFunction = replacer;
                }
                else
                {
                    var replacerObj = replacer.AsObject();
                    if (replacerObj.Class == "Array")
                    {
                        _propertyList = new List<string>();
                    }

                    foreach (var property in replacerObj.GetOwnProperties().Select(x => x.Value))
                    {
                        JsValue v = _engine.GetValue(property);
                        string item = null;
                        if (v.IsString())
                        {
                            item = v.AsString();
                        }
                        else if (v.IsNumber())
                        {
                            item = TypeConverter.ToString(v);
                        }
                        else if (v.IsObject())
                        {
                            var propertyObj = v.AsObject();
                            if (propertyObj.Class == "String" || propertyObj.Class == "Number")
                            {
                                item = TypeConverter.ToString(v);
                            }
                        }

                        if (item != null && !_propertyList.Contains(item))
                        {
                            _propertyList.Add(item);
                        }

                    }
                }
            }

            if (space.IsObject())
            {
                var spaceObj = space.AsObject();
                if (spaceObj.Class == "Number")
                {
                    space = TypeConverter.ToNumber(spaceObj);
                }
                else if (spaceObj.Class == "String")
                {
                    space = TypeConverter.ToString(spaceObj);
                }
            }

            // defining the gap
            if (space.IsNumber())
            {
                if (space.AsNumber() > 0) {
                    _gap = new System.String(' ', (int)System.Math.Min(10, space.AsNumber()));
                }
                else 
                {
                    _gap = string.Empty;
                }
            }
            else if (space.IsString())
            {
                var stringSpace = space.AsString();
                _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
            }
            else
            {
                _gap = string.Empty;
            }

            var wrapper = _engine.Object.Construct(Arguments.Empty);
            wrapper.DefineOwnProperty("", new PropertyDescriptor(value, true, true, true), false);

            return Str("", wrapper);
        }
Esempio n. 35
0
        private JsValue ToNumberString(JsValue thisObject, JsValue[] arguments)
        {
            if (!thisObject.IsNumber() && (thisObject.TryCast<NumberInstance>() == null))
            {
                throw new JavaScriptException(Engine.TypeError);
            }

            var radix = arguments.At(0) == JsValue.Undefined ? 10 : (int) TypeConverter.ToInteger(arguments.At(0));

            if (radix < 2 || radix > 36)
            {
                throw new JavaScriptException(Engine.RangeError, "radix must be between 2 and 36");
            }

            var x = TypeConverter.ToNumber(thisObject);

            if (double.IsNaN(x))
            {
                return "NaN";
            }

            if (x.Equals(0))
            {
                return "0";
            }

            if (double.IsPositiveInfinity(x) || x >= double.MaxValue)
            {
                return "Infinity";
            }

            if (x < 0)
            {
                return "-" + ToNumberString(-x, arguments);
            }

            if (radix == 10)
            {
                return ToNumberString(x);    
            }

            var integer = (long) x;
            var fraction = x -  integer;

            string result = ToBase(integer, radix);
            if (!fraction.Equals(0))
            {
                result += "." + ToFractionBase(fraction, radix);
            }

            return result;
        }
Esempio n. 36
0
        public static JToken Map(JsValue value)
        {
            if (value == null || value.IsNull())
            {
                return(JValue.CreateNull());
            }

            if (value.IsUndefined())
            {
                return(JValue.CreateUndefined());
            }

            if (value.IsString())
            {
                return(new JValue(value.AsString()));
            }

            if (value.IsBoolean())
            {
                return(new JValue(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(new JValue(value.AsNumber()));
            }

            if (value.IsDate())
            {
                return(new JValue(value.AsDate().ToDateTime()));
            }

            if (value.IsRegExp())
            {
                return(JValue.CreateString(value.AsRegExp().Value?.ToString()));
            }

            if (value.IsArray())
            {
                var arr = value.AsArray();

                var target = new JArray();

                for (var i = 0; i < arr.GetLength(); i++)
                {
                    target.Add(Map(arr.Get(i.ToString())));
                }

                return(target);
            }

            if (value.IsObject())
            {
                var obj = value.AsObject();

                var target = new JObject();

                foreach (var kvp in obj.GetOwnProperties())
                {
                    target[kvp.Key] = Map(kvp.Value.Value);
                }

                return(target);
            }

            throw new ArgumentException("Invalid json type.", nameof(value));
        }
Esempio n. 37
0
        public JsValue Serialize(JsValue value, JsValue replacer, JsValue space)
        {
            _stack = new Stack <object>();

            // for JSON.stringify(), any function passed as the first argument will return undefined
            // if the replacer is not defined. The function is not called either.
            if (value.Is <ICallable>() && replacer == Undefined.Instance)
            {
                return(Undefined.Instance);
            }

            if (replacer.IsObject())
            {
                if (replacer.Is <ICallable>())
                {
                    _replacerFunction = replacer;
                }
                else
                {
                    var replacerObj = replacer.AsObject();
                    if (replacerObj.Class == "Array")
                    {
                        _propertyList = new List <string>();
                    }

                    foreach (var property in replacerObj.GetOwnProperties().Select(x => x.Value))
                    {
                        JsValue v    = _engine.GetValue(property);
                        string  item = null;
                        if (v.IsString())
                        {
                            item = v.AsString();
                        }
                        else if (v.IsNumber())
                        {
                            item = TypeConverter.ToString(v);
                        }
                        else if (v.IsObject())
                        {
                            var propertyObj = v.AsObject();
                            if (propertyObj.Class == "String" || propertyObj.Class == "Number")
                            {
                                item = TypeConverter.ToString(v);
                            }
                        }

                        if (item != null && !_propertyList.Contains(item))
                        {
                            _propertyList.Add(item);
                        }
                    }
                }
            }

            if (space.IsObject())
            {
                var spaceObj = space.AsObject();
                if (spaceObj.Class == "Number")
                {
                    space = TypeConverter.ToNumber(spaceObj);
                }
                else if (spaceObj.Class == "String")
                {
                    space = TypeConverter.ToString(spaceObj);
                }
            }

            // defining the gap
            if (space.IsNumber())
            {
                if (space.AsNumber() > 0)
                {
                    _gap = new System.String(' ', (int)System.Math.Min(10, space.AsNumber()));
                }
                else
                {
                    _gap = string.Empty;
                }
            }
            else if (space.IsString())
            {
                var stringSpace = space.AsString();
                _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
            }
            else
            {
                _gap = string.Empty;
            }

            var wrapper = _engine.Object.Construct(Arguments.Empty);

            wrapper.DefineOwnProperty("", new PropertyDescriptor(value, true, true, true), false);

            return(Str("", wrapper));
        }