diff --git a/src/Realm.js b/src/Realm.js index 22cf7ee..95b5337 100644 --- a/src/Realm.js +++ b/src/Realm.js @@ -222,6 +222,22 @@ class Realm { } + lookupWellKnownByName(v) { + switch ( v ) { + case '%Object%': return this.Object; + case '%ObjectPrototype%': return this.ObjectPrototype; + case '%Function%': return this.Function; + case '%FunctionPrototype%': return this.FunctionPrototype; + case '%Math%': return this.Math; + case '%Number%': return this.Number; + case '%NumberPrototype%': return this.NumberPrototype; + case '%Array%': return this.Array; + case '%ArrayPrototype%': return this.ArrayPrototype; + case '%RegExp%': return this.RegExp; + case '%RegExpPrototype%': return this.RegExpPrototype; + } + } + valueFromNative(native) { return Value.fromNative(native, this); } @@ -262,6 +278,42 @@ class Realm { //this.importCache.set(native, result); return result; } + + dehydrate(value) { + let state = { + refrences: {}, + }; + + let val = this._dehydrate(value, state); + return {root: val, refrences: state.refrences}; + + } + + _dehydrate(value, state) { + if ( value instanceof PrimitiveValue ) return {'$v': value.native}; + if ( value === Value.null ) return {'$t': 'null'}; + if ( value === Value.undef ) return {'$t': 'undefined'}; + if ( value.wellKnownName ) return {'$s': value.wellKnownName}; + if ( !(value.serial in state.refrences) ) { + let ref = { + '$t': value.isCallable ? 'function' : 'object', + 'prop': {} + }; + state.refrences[value.serial] = ref; + ref.proto = this._dehydrate(value.getPrototype(this) || Value.null, state); + for ( let k in value.properties ) { + if ( !Object.prototype.hasOwnProperty.call(value.properties, k) ) continue; + let prop = value.properties[k]; + ref.prop[k] = { + v: this._dehydrate(prop.value, state), + e: prop.enumerable && undefined, + w: prop.writable && undefined, + c: prop.configurable && undefined + }; + } + } + return {'$ref': value.serial}; + } } Realm.prototype.makeForForeignObject = Realm.prototype.import; diff --git a/src/stdlib/Esper.js b/src/stdlib/Esper.js index 4ab57c7..32a5480 100644 --- a/src/stdlib/Esper.js +++ b/src/stdlib/Esper.js @@ -30,6 +30,12 @@ class EsperObject extends EasyObjectValue { return scope.object; } + static *pickle(thiz, args, scope, extra) { + let d = scope.realm.dehydrate(args[0]); + let dj = JSON.stringify(d, null, ' '); + return Value.fromNative(dj); + } + }