UNPKG

react-carousel-query

Version:

A infinite carousel component made with react that handles the pagination for you.

1,367 lines (1,227 loc) 77.8 kB
// Copyright (C) 2011-2012 Software Languages Lab, Vrije Universiteit Brussel // This code is dual-licensed under both the Apache License and the MPL // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is a shim for the ES-Harmony reflection module * * The Initial Developer of the Original Code is * Tom Van Cutsem, Vrije Universiteit Brussel. * Portions created by the Initial Developer are Copyright (C) 2011-2012 * the Initial Developer. All Rights Reserved. * * Contributor(s): * */ // ---------------------------------------------------------------------------- // This file is a polyfill for the upcoming ECMAScript Reflect API, // including support for Proxies. See the draft specification at: // http://wiki.ecmascript.org/doku.php?id=harmony:reflect_api // http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies // For an implementation of the Handler API, see handlers.js, which implements: // http://wiki.ecmascript.org/doku.php?id=harmony:virtual_object_api // This implementation supersedes the earlier polyfill at: // code.google.com/p/es-lab/source/browse/trunk/src/proxies/DirectProxies.js // This code was tested on tracemonkey / Firefox 12 // (and should run fine on older Firefox versions starting with FF4) // The code also works correctly on // v8 --harmony_proxies --harmony_weakmaps (v3.6.5.1) // Language Dependencies: // - ECMAScript 5/strict // - "old" (i.e. non-direct) Harmony Proxies // - Harmony WeakMaps // Patches: // - Object.{freeze,seal,preventExtensions} // - Object.{isFrozen,isSealed,isExtensible} // - Object.getPrototypeOf // - Object.keys // - Object.prototype.valueOf // - Object.prototype.isPrototypeOf // - Object.prototype.toString // - Object.prototype.hasOwnProperty // - Object.getOwnPropertyDescriptor // - Object.defineProperty // - Object.defineProperties // - Object.getOwnPropertyNames // - Object.getOwnPropertySymbols // - Object.getPrototypeOf // - Object.setPrototypeOf // - Object.assign // - Function.prototype.toString // - Date.prototype.toString // - Array.isArray // - Array.prototype.concat // - Proxy // Adds new globals: // - Reflect // Direct proxies can be created via Proxy(target, handler) // ---------------------------------------------------------------------------- (function(global){ // function-as-module pattern "use strict"; // === Direct Proxies: Invariant Enforcement === // Direct proxies build on non-direct proxies by automatically wrapping // all user-defined proxy handlers in a Validator handler that checks and // enforces ES5 invariants. // A direct proxy is a proxy for an existing object called the target object. // A Validator handler is a wrapper for a target proxy handler H. // The Validator forwards all operations to H, but additionally // performs a number of integrity checks on the results of some traps, // to make sure H does not violate the ES5 invariants w.r.t. non-configurable // properties and non-extensible, sealed or frozen objects. // For each property that H exposes as own, non-configurable // (e.g. by returning a descriptor from a call to getOwnPropertyDescriptor) // the Validator handler defines those properties on the target object. // When the proxy becomes non-extensible, also configurable own properties // are checked against the target. // We will call properties that are defined on the target object // "fixed properties". // We will name fixed non-configurable properties "sealed properties". // We will name fixed non-configurable non-writable properties "frozen // properties". // The Validator handler upholds the following invariants w.r.t. non-configurability: // - getOwnPropertyDescriptor cannot report sealed properties as non-existent // - getOwnPropertyDescriptor cannot report incompatible changes to the // attributes of a sealed property (e.g. reporting a non-configurable // property as configurable, or reporting a non-configurable, non-writable // property as writable) // - getPropertyDescriptor cannot report sealed properties as non-existent // - getPropertyDescriptor cannot report incompatible changes to the // attributes of a sealed property. It _can_ report incompatible changes // to the attributes of non-own, inherited properties. // - defineProperty cannot make incompatible changes to the attributes of // sealed properties // - deleteProperty cannot report a successful deletion of a sealed property // - hasOwn cannot report a sealed property as non-existent // - has cannot report a sealed property as non-existent // - get cannot report inconsistent values for frozen data // properties, and must report undefined for sealed accessors with an // undefined getter // - set cannot report a successful assignment for frozen data // properties or sealed accessors with an undefined setter. // - get{Own}PropertyNames lists all sealed properties of the target. // - keys lists all enumerable sealed properties of the target. // - enumerate lists all enumerable sealed properties of the target. // - if a property of a non-extensible proxy is reported as non-existent, // then it must forever be reported as non-existent. This applies to // own and inherited properties and is enforced in the // deleteProperty, get{Own}PropertyDescriptor, has{Own}, // get{Own}PropertyNames, keys and enumerate traps // Violation of any of these invariants by H will result in TypeError being // thrown. // Additionally, once Object.preventExtensions, Object.seal or Object.freeze // is invoked on the proxy, the set of own property names for the proxy is // fixed. Any property name that is not fixed is called a 'new' property. // The Validator upholds the following invariants regarding extensibility: // - getOwnPropertyDescriptor cannot report new properties as existent // (it must report them as non-existent by returning undefined) // - defineProperty cannot successfully add a new property (it must reject) // - getOwnPropertyNames cannot list new properties // - hasOwn cannot report true for new properties (it must report false) // - keys cannot list new properties // Invariants currently not enforced: // - getOwnPropertyNames lists only own property names // - keys lists only enumerable own property names // Both traps may list more property names than are actually defined on the // target. // Invariants with regard to inheritance are currently not enforced. // - a non-configurable potentially inherited property on a proxy with // non-mutable ancestry cannot be reported as non-existent // (An object with non-mutable ancestry is a non-extensible object whose // [[Prototype]] is either null or an object with non-mutable ancestry.) // Changes in Handler API compared to previous harmony:proxies, see: // http://wiki.ecmascript.org/doku.php?id=strawman:direct_proxies // http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies // ---------------------------------------------------------------------------- // ---- WeakMap polyfill ---- // TODO: find a proper WeakMap polyfill // define an empty WeakMap so that at least the Reflect module code // will work in the absence of WeakMaps. Proxy emulation depends on // actual WeakMaps, so will not work with this little shim. if (typeof WeakMap === "undefined") { global.WeakMap = function(){}; global.WeakMap.prototype = { get: function(k) { return undefined; }, set: function(k,v) { throw new Error("WeakMap not supported"); } }; } // ---- Normalization functions for property descriptors ---- function isStandardAttribute(name) { return /^(get|set|value|writable|enumerable|configurable)$/.test(name); } // Adapted from ES5 section 8.10.5 function toPropertyDescriptor(obj) { if (Object(obj) !== obj) { throw new TypeError("property descriptor should be an Object, given: "+ obj); } var desc = {}; if ('enumerable' in obj) { desc.enumerable = !!obj.enumerable; } if ('configurable' in obj) { desc.configurable = !!obj.configurable; } if ('value' in obj) { desc.value = obj.value; } if ('writable' in obj) { desc.writable = !!obj.writable; } if ('get' in obj) { var getter = obj.get; if (getter !== undefined && typeof getter !== "function") { throw new TypeError("property descriptor 'get' attribute must be "+ "callable or undefined, given: "+getter); } desc.get = getter; } if ('set' in obj) { var setter = obj.set; if (setter !== undefined && typeof setter !== "function") { throw new TypeError("property descriptor 'set' attribute must be "+ "callable or undefined, given: "+setter); } desc.set = setter; } if ('get' in desc || 'set' in desc) { if ('value' in desc || 'writable' in desc) { throw new TypeError("property descriptor cannot be both a data and an "+ "accessor descriptor: "+obj); } } return desc; } function isAccessorDescriptor(desc) { if (desc === undefined) return false; return ('get' in desc || 'set' in desc); } function isDataDescriptor(desc) { if (desc === undefined) return false; return ('value' in desc || 'writable' in desc); } function isGenericDescriptor(desc) { if (desc === undefined) return false; return !isAccessorDescriptor(desc) && !isDataDescriptor(desc); } function toCompletePropertyDescriptor(desc) { var internalDesc = toPropertyDescriptor(desc); if (isGenericDescriptor(internalDesc) || isDataDescriptor(internalDesc)) { if (!('value' in internalDesc)) { internalDesc.value = undefined; } if (!('writable' in internalDesc)) { internalDesc.writable = false; } } else { if (!('get' in internalDesc)) { internalDesc.get = undefined; } if (!('set' in internalDesc)) { internalDesc.set = undefined; } } if (!('enumerable' in internalDesc)) { internalDesc.enumerable = false; } if (!('configurable' in internalDesc)) { internalDesc.configurable = false; } return internalDesc; } function isEmptyDescriptor(desc) { return !('get' in desc) && !('set' in desc) && !('value' in desc) && !('writable' in desc) && !('enumerable' in desc) && !('configurable' in desc); } function isEquivalentDescriptor(desc1, desc2) { return sameValue(desc1.get, desc2.get) && sameValue(desc1.set, desc2.set) && sameValue(desc1.value, desc2.value) && sameValue(desc1.writable, desc2.writable) && sameValue(desc1.enumerable, desc2.enumerable) && sameValue(desc1.configurable, desc2.configurable); } // copied from http://wiki.ecmascript.org/doku.php?id=harmony:egal function sameValue(x, y) { if (x === y) { // 0 === -0, but they are not identical return x !== 0 || 1 / x === 1 / y; } // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is a NaN. // isNaN is broken: it converts its argument to number, so // isNaN("foo") => true return x !== x && y !== y; } /** * Returns a fresh property descriptor that is guaranteed * to be complete (i.e. contain all the standard attributes). * Additionally, any non-standard enumerable properties of * attributes are copied over to the fresh descriptor. * * If attributes is undefined, returns undefined. * * See also: http://wiki.ecmascript.org/doku.php?id=harmony:proxies_semantics */ function normalizeAndCompletePropertyDescriptor(attributes) { if (attributes === undefined) { return undefined; } var desc = toCompletePropertyDescriptor(attributes); // Note: no need to call FromPropertyDescriptor(desc), as we represent // "internal" property descriptors as proper Objects from the start for (var name in attributes) { if (!isStandardAttribute(name)) { Object.defineProperty(desc, name, { value: attributes[name], writable: true, enumerable: true, configurable: true }); } } return desc; } /** * Returns a fresh property descriptor whose standard * attributes are guaranteed to be data properties of the right type. * Additionally, any non-standard enumerable properties of * attributes are copied over to the fresh descriptor. * * If attributes is undefined, will throw a TypeError. * * See also: http://wiki.ecmascript.org/doku.php?id=harmony:proxies_semantics */ function normalizePropertyDescriptor(attributes) { var desc = toPropertyDescriptor(attributes); // Note: no need to call FromGenericPropertyDescriptor(desc), as we represent // "internal" property descriptors as proper Objects from the start for (var name in attributes) { if (!isStandardAttribute(name)) { Object.defineProperty(desc, name, { value: attributes[name], writable: true, enumerable: true, configurable: true }); } } return desc; } // store a reference to the real ES5 primitives before patching them later var prim_preventExtensions = Object.preventExtensions, prim_seal = Object.seal, prim_freeze = Object.freeze, prim_isExtensible = Object.isExtensible, prim_isSealed = Object.isSealed, prim_isFrozen = Object.isFrozen, prim_getPrototypeOf = Object.getPrototypeOf, prim_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, prim_defineProperty = Object.defineProperty, prim_defineProperties = Object.defineProperties, prim_keys = Object.keys, prim_getOwnPropertyNames = Object.getOwnPropertyNames, prim_getOwnPropertySymbols = Object.getOwnPropertySymbols, prim_assign = Object.assign, prim_isArray = Array.isArray, prim_concat = Array.prototype.concat, prim_isPrototypeOf = Object.prototype.isPrototypeOf, prim_hasOwnProperty = Object.prototype.hasOwnProperty; // these will point to the patched versions of the respective methods on // Object. They are used within this module as the "intrinsic" bindings // of these methods (i.e. the "original" bindings as defined in the spec) var Object_isFrozen, Object_isSealed, Object_isExtensible, Object_getPrototypeOf, Object_getOwnPropertyNames; /** * A property 'name' is fixed if it is an own property of the target. */ function isFixed(name, target) { return ({}).hasOwnProperty.call(target, name); } function isSealed(name, target) { var desc = Object.getOwnPropertyDescriptor(target, name); if (desc === undefined) { return false; } return desc.configurable === false; } function isSealedDesc(desc) { return desc !== undefined && desc.configurable === false; } /** * Performs all validation that Object.defineProperty performs, * without actually defining the property. Returns a boolean * indicating whether validation succeeded. * * Implementation transliterated from ES5.1 section 8.12.9 */ function isCompatibleDescriptor(extensible, current, desc) { if (current === undefined && extensible === false) { return false; } if (current === undefined && extensible === true) { return true; } if (isEmptyDescriptor(desc)) { return true; } if (isEquivalentDescriptor(current, desc)) { return true; } if (current.configurable === false) { if (desc.configurable === true) { return false; } if ('enumerable' in desc && desc.enumerable !== current.enumerable) { return false; } } if (isGenericDescriptor(desc)) { return true; } if (isDataDescriptor(current) !== isDataDescriptor(desc)) { if (current.configurable === false) { return false; } return true; } if (isDataDescriptor(current) && isDataDescriptor(desc)) { if (current.configurable === false) { if (current.writable === false && desc.writable === true) { return false; } if (current.writable === false) { if ('value' in desc && !sameValue(desc.value, current.value)) { return false; } } } return true; } if (isAccessorDescriptor(current) && isAccessorDescriptor(desc)) { if (current.configurable === false) { if ('set' in desc && !sameValue(desc.set, current.set)) { return false; } if ('get' in desc && !sameValue(desc.get, current.get)) { return false; } } } return true; } // ES6 7.3.11 SetIntegrityLevel // level is one of "sealed" or "frozen" function setIntegrityLevel(target, level) { var ownProps = Object_getOwnPropertyNames(target); var pendingException = undefined; if (level === "sealed") { var l = +ownProps.length; var k; for (var i = 0; i < l; i++) { k = String(ownProps[i]); try { Object.defineProperty(target, k, { configurable: false }); } catch (e) { if (pendingException === undefined) { pendingException = e; } } } } else { // level === "frozen" var l = +ownProps.length; var k; for (var i = 0; i < l; i++) { k = String(ownProps[i]); try { var currentDesc = Object.getOwnPropertyDescriptor(target, k); if (currentDesc !== undefined) { var desc; if (isAccessorDescriptor(currentDesc)) { desc = { configurable: false } } else { desc = { configurable: false, writable: false } } Object.defineProperty(target, k, desc); } } catch (e) { if (pendingException === undefined) { pendingException = e; } } } } if (pendingException !== undefined) { throw pendingException; } return Reflect.preventExtensions(target); } // ES6 7.3.12 TestIntegrityLevel // level is one of "sealed" or "frozen" function testIntegrityLevel(target, level) { var isExtensible = Object_isExtensible(target); if (isExtensible) return false; var ownProps = Object_getOwnPropertyNames(target); var pendingException = undefined; var configurable = false; var writable = false; var l = +ownProps.length; var k; var currentDesc; for (var i = 0; i < l; i++) { k = String(ownProps[i]); try { currentDesc = Object.getOwnPropertyDescriptor(target, k); configurable = configurable || currentDesc.configurable; if (isDataDescriptor(currentDesc)) { writable = writable || currentDesc.writable; } } catch (e) { if (pendingException === undefined) { pendingException = e; configurable = true; } } } if (pendingException !== undefined) { throw pendingException; } if (level === "frozen" && writable === true) { return false; } if (configurable === true) { return false; } return true; } // ---- The Validator handler wrapper around user handlers ---- /** * @param target the object wrapped by this proxy. * As long as the proxy is extensible, only non-configurable properties * are checked against the target. Once the proxy becomes non-extensible, * invariants w.r.t. non-extensibility are also enforced. * * @param handler the handler of the direct proxy. The object emulated by * this handler is validated against the target object of the direct proxy. * Any violations that the handler makes against the invariants * of the target will cause a TypeError to be thrown. * * Both target and handler must be proper Objects at initialization time. */ function Validator(target, handler) { // for non-revokable proxies, these are const references // for revokable proxies, on revocation: // - this.target is set to null // - this.handler is set to a handler that throws on all traps this.target = target; this.handler = handler; } Validator.prototype = { /** * If getTrap returns undefined, the caller should perform the * default forwarding behavior. * If getTrap returns normally otherwise, the return value * will be a callable trap function. When calling the trap function, * the caller is responsible for binding its |this| to |this.handler|. */ getTrap: function(trapName) { var trap = this.handler[trapName]; if (trap === undefined) { // the trap was not defined, // perform the default forwarding behavior return undefined; } if (typeof trap !== "function") { throw new TypeError(trapName + " trap is not callable: "+trap); } return trap; }, // === fundamental traps === /** * If name denotes a fixed property, check: * - whether targetHandler reports it as existent * - whether the returned descriptor is compatible with the fixed property * If the proxy is non-extensible, check: * - whether name is not a new property * Additionally, the returned descriptor is normalized and completed. */ getOwnPropertyDescriptor: function(name) { "use strict"; var trap = this.getTrap("getOwnPropertyDescriptor"); if (trap === undefined) { return Reflect.getOwnPropertyDescriptor(this.target, name); } name = String(name); var desc = trap.call(this.handler, this.target, name); desc = normalizeAndCompletePropertyDescriptor(desc); var targetDesc = Object.getOwnPropertyDescriptor(this.target, name); var extensible = Object.isExtensible(this.target); if (desc === undefined) { if (isSealedDesc(targetDesc)) { throw new TypeError("cannot report non-configurable property '"+name+ "' as non-existent"); } if (!extensible && targetDesc !== undefined) { // if handler is allowed to return undefined, we cannot guarantee // that it will not return a descriptor for this property later. // Once a property has been reported as non-existent on a non-extensible // object, it should forever be reported as non-existent throw new TypeError("cannot report existing own property '"+name+ "' as non-existent on a non-extensible object"); } return undefined; } // at this point, we know (desc !== undefined), i.e. // targetHandler reports 'name' as an existing property // Note: we could collapse the following two if-tests into a single // test. Separating out the cases to improve error reporting. if (!extensible) { if (targetDesc === undefined) { throw new TypeError("cannot report a new own property '"+ name + "' on a non-extensible object"); } } if (name !== undefined) { if (!isCompatibleDescriptor(extensible, targetDesc, desc)) { throw new TypeError("cannot report incompatible property descriptor "+ "for property '"+name+"'"); } } if (desc.configurable === false) { if (targetDesc === undefined || targetDesc.configurable === true) { // if the property is configurable or non-existent on the target, // but is reported as a non-configurable property, it may later be // reported as configurable or non-existent, which violates the // invariant that if the property might change or disappear, the // configurable attribute must be true. throw new TypeError( "cannot report a non-configurable descriptor " + "for configurable or non-existent property '" + name + "'"); } if ('writable' in desc && desc.writable === false) { if (targetDesc.writable === true) { // if the property is non-configurable, writable on the target, // but is reported as non-configurable, non-writable, it may later // be reported as non-configurable, writable again, which violates // the invariant that a non-configurable, non-writable property // may not change state. throw new TypeError( "cannot report non-configurable, writable property '" + name + "' as non-configurable, non-writable"); } } } return desc; }, /** * In the direct proxies design with refactored prototype climbing, * this trap is deprecated. For proxies-as-prototypes, instead * of calling this trap, the get, set, has or enumerate traps are * called instead. * * In this implementation, we "abuse" getPropertyDescriptor to * support trapping the get or set traps for proxies-as-prototypes. * We do this by returning a getter/setter pair that invokes * the corresponding traps. * * While this hack works for inherited property access, it has some * quirks: * * In Firefox, this trap is only called after a prior invocation * of the 'has' trap has returned true. Hence, expect the following * behavior: * <code> * var child = Object.create(Proxy(target, handler)); * child[name] // triggers handler.has(target, name) * // if that returns true, triggers handler.get(target, name, child) * </code> * * On v8, the 'in' operator, when applied to an object that inherits * from a proxy, will call getPropertyDescriptor and walk the proto-chain. * That calls the below getPropertyDescriptor trap on the proxy. The * result of the 'in'-operator is then determined by whether this trap * returns undefined or a property descriptor object. That is why * we first explicitly trigger the 'has' trap to determine whether * the property exists. * * This has the side-effect that when enumerating properties on * an object that inherits from a proxy in v8, only properties * for which 'has' returns true are returned: * * <code> * var child = Object.create(Proxy(target, handler)); * for (var prop in child) { * // only enumerates prop if (prop in child) returns true * } * </code> */ getPropertyDescriptor: function(name) { var handler = this; if (!handler.has(name)) return undefined; return { get: function() { return handler.get(this, name); }, set: function(val) { if (handler.set(this, name, val)) { return val; } else { throw new TypeError("failed assignment to "+name); } }, enumerable: true, configurable: true }; }, /** * If name denotes a fixed property, check for incompatible changes. * If the proxy is non-extensible, check that new properties are rejected. */ defineProperty: function(name, desc) { // TODO(tvcutsem): the current tracemonkey implementation of proxies // auto-completes 'desc', which is not correct. 'desc' should be // normalized, but not completed. Consider: // Object.defineProperty(proxy, 'foo', {enumerable:false}) // This trap will receive desc = // {value:undefined,writable:false,enumerable:false,configurable:false} // This will also set all other attributes to their default value, // which is unexpected and different from [[DefineOwnProperty]]. // Bug filed: https://bugzilla.mozilla.org/show_bug.cgi?id=601329 var trap = this.getTrap("defineProperty"); if (trap === undefined) { // default forwarding behavior return Reflect.defineProperty(this.target, name, desc); } name = String(name); var descObj = normalizePropertyDescriptor(desc); var success = trap.call(this.handler, this.target, name, descObj); success = !!success; // coerce to Boolean if (success === true) { var targetDesc = Object.getOwnPropertyDescriptor(this.target, name); var extensible = Object.isExtensible(this.target); // Note: we could collapse the following two if-tests into a single // test. Separating out the cases to improve error reporting. if (!extensible) { if (targetDesc === undefined) { throw new TypeError("cannot successfully add a new property '"+ name + "' to a non-extensible object"); } } if (targetDesc !== undefined) { if (!isCompatibleDescriptor(extensible, targetDesc, desc)) { throw new TypeError("cannot define incompatible property "+ "descriptor for property '"+name+"'"); } if (isDataDescriptor(targetDesc) && targetDesc.configurable === false && targetDesc.writable === true) { if (desc.configurable === false && desc.writable === false) { // if the property is non-configurable, writable on the target // but was successfully reported to be updated to // non-configurable, non-writable, it can later be reported // again as non-configurable, writable, which violates // the invariant that non-configurable, non-writable properties // cannot change state throw new TypeError( "cannot successfully define non-configurable, writable " + " property '" + name + "' as non-configurable, non-writable"); } } } if (desc.configurable === false && !isSealedDesc(targetDesc)) { // if the property is configurable or non-existent on the target, // but is successfully being redefined as a non-configurable property, // it may later be reported as configurable or non-existent, which violates // the invariant that if the property might change or disappear, the // configurable attribute must be true. throw new TypeError( "cannot successfully define a non-configurable " + "descriptor for configurable or non-existent property '" + name + "'"); } } return success; }, /** * On success, check whether the target object is indeed non-extensible. */ preventExtensions: function() { var trap = this.getTrap("preventExtensions"); if (trap === undefined) { // default forwarding behavior return Reflect.preventExtensions(this.target); } var success = trap.call(this.handler, this.target); success = !!success; // coerce to Boolean if (success) { if (Object_isExtensible(this.target)) { throw new TypeError("can't report extensible object as non-extensible: "+ this.target); } } return success; }, /** * If name denotes a sealed property, check whether handler rejects. */ delete: function(name) { "use strict"; var trap = this.getTrap("deleteProperty"); if (trap === undefined) { // default forwarding behavior return Reflect.deleteProperty(this.target, name); } name = String(name); var res = trap.call(this.handler, this.target, name); res = !!res; // coerce to Boolean var targetDesc; if (res === true) { targetDesc = Object.getOwnPropertyDescriptor(this.target, name); if (targetDesc !== undefined && targetDesc.configurable === false) { throw new TypeError("property '" + name + "' is non-configurable "+ "and can't be deleted"); } if (targetDesc !== undefined && !Object_isExtensible(this.target)) { // if the property still exists on a non-extensible target but // is reported as successfully deleted, it may later be reported // as present, which violates the invariant that an own property, // deleted from a non-extensible object cannot reappear. throw new TypeError( "cannot successfully delete existing property '" + name + "' on a non-extensible object"); } } return res; }, /** * The getOwnPropertyNames trap was replaced by the ownKeys trap, * which now also returns an array (of strings or symbols) and * which performs the same rigorous invariant checks as getOwnPropertyNames * * See issue #48 on how this trap can still get invoked by external libs * that don't use the patched Object.getOwnPropertyNames function. */ getOwnPropertyNames: function() { // Note: removed deprecation warning to avoid dependency on 'console' // (and on node, should anyway use util.deprecate). Deprecation warnings // can also be annoying when they are outside of the user's control, e.g. // when an external library calls unpatched Object.getOwnPropertyNames. // Since there is a clean fallback to `ownKeys`, the fact that the // deprecated method is still called is mostly harmless anyway. // See also issues #65 and #66. // console.warn("getOwnPropertyNames trap is deprecated. Use ownKeys instead"); return this.ownKeys(); }, /** * Checks whether the trap result does not contain any new properties * if the proxy is non-extensible. * * Any own non-configurable properties of the target that are not included * in the trap result give rise to a TypeError. As such, we check whether the * returned result contains at least all sealed properties of the target * object. * * Additionally, the trap result is normalized. * Instead of returning the trap result directly: * - create and return a fresh Array, * - of which each element is coerced to a String * * This trap is called a.o. by Reflect.ownKeys, Object.getOwnPropertyNames * and Object.keys (the latter filters out only the enumerable own properties). */ ownKeys: function() { var trap = this.getTrap("ownKeys"); if (trap === undefined) { // default forwarding behavior return Reflect.ownKeys(this.target); } var trapResult = trap.call(this.handler, this.target); // propNames is used as a set of strings var propNames = Object.create(null); var numProps = +trapResult.length; var result = new Array(numProps); for (var i = 0; i < numProps; i++) { var s = String(trapResult[i]); if (!Object.isExtensible(this.target) && !isFixed(s, this.target)) { // non-extensible proxies don't tolerate new own property names throw new TypeError("ownKeys trap cannot list a new "+ "property '"+s+"' on a non-extensible object"); } propNames[s] = true; result[i] = s; } var ownProps = Object_getOwnPropertyNames(this.target); var target = this.target; ownProps.forEach(function (ownProp) { if (!propNames[ownProp]) { if (isSealed(ownProp, target)) { throw new TypeError("ownKeys trap failed to include "+ "non-configurable property '"+ownProp+"'"); } if (!Object.isExtensible(target) && isFixed(ownProp, target)) { // if handler is allowed to report ownProp as non-existent, // we cannot guarantee that it will never later report it as // existent. Once a property has been reported as non-existent // on a non-extensible object, it should forever be reported as // non-existent throw new TypeError("ownKeys trap cannot report existing own property '"+ ownProp+"' as non-existent on a non-extensible object"); } } }); return result; }, /** * Checks whether the trap result is consistent with the state of the * wrapped target. */ isExtensible: function() { var trap = this.getTrap("isExtensible"); if (trap === undefined) { // default forwarding behavior return Reflect.isExtensible(this.target); } var result = trap.call(this.handler, this.target); result = !!result; // coerce to Boolean var state = Object_isExtensible(this.target); if (result !== state) { if (result) { throw new TypeError("cannot report non-extensible object as extensible: "+ this.target); } else { throw new TypeError("cannot report extensible object as non-extensible: "+ this.target); } } return state; }, /** * Check whether the trap result corresponds to the target's [[Prototype]] */ getPrototypeOf: function() { var trap = this.getTrap("getPrototypeOf"); if (trap === undefined) { // default forwarding behavior return Reflect.getPrototypeOf(this.target); } var allegedProto = trap.call(this.handler, this.target); if (!Object_isExtensible(this.target)) { var actualProto = Object_getPrototypeOf(this.target); if (!sameValue(allegedProto, actualProto)) { throw new TypeError("prototype value does not match: " + this.target); } } return allegedProto; }, /** * If target is non-extensible and setPrototypeOf trap returns true, * check whether the trap result corresponds to the target's [[Prototype]] */ setPrototypeOf: function(newProto) { var trap = this.getTrap("setPrototypeOf"); if (trap === undefined) { // default forwarding behavior return Reflect.setPrototypeOf(this.target, newProto); } var success = trap.call(this.handler, this.target, newProto); success = !!success; if (success && !Object_isExtensible(this.target)) { var actualProto = Object_getPrototypeOf(this.target); if (!sameValue(newProto, actualProto)) { throw new TypeError("prototype value does not match: " + this.target); } } return success; }, /** * In the direct proxies design with refactored prototype climbing, * this trap is deprecated. For proxies-as-prototypes, for-in will * call the enumerate() trap. If that trap is not defined, the * operation is forwarded to the target, no more fallback on this * fundamental trap. */ getPropertyNames: function() { throw new TypeError("getPropertyNames trap is deprecated"); }, // === derived traps === /** * If name denotes a fixed property, check whether the trap returns true. */ has: function(name) { var trap = this.getTrap("has"); if (trap === undefined) { // default forwarding behavior return Reflect.has(this.target, name); } name = String(name); var res = trap.call(this.handler, this.target, name); res = !!res; // coerce to Boolean if (res === false) { if (isSealed(name, this.target)) { throw new TypeError("cannot report existing non-configurable own "+ "property '"+ name + "' as a non-existent "+ "property"); } if (!Object.isExtensible(this.target) && isFixed(name, this.target)) { // if handler is allowed to return false, we cannot guarantee // that it will not return true for this property later. // Once a property has been reported as non-existent on a non-extensible // object, it should forever be reported as non-existent throw new TypeError("cannot report existing own property '"+name+ "' as non-existent on a non-extensible object"); } } // if res === true, we don't need to check for extensibility // even for a non-extensible proxy that has no own name property, // the property may have been inherited return res; }, /** * If name denotes a fixed non-configurable, non-writable data property, * check its return value against the previously asserted value of the * fixed property. */ get: function(receiver, name) { // experimental support for invoke() trap on platforms that // support __noSuchMethod__ /* if (name === '__noSuchMethod__') { var handler = this; return function(name, args) { return handler.invoke(receiver, name, args); } } */ var trap = this.getTrap("get"); if (trap === undefined) { // default forwarding behavior return Reflect.get(this.target, name, receiver); } name = String(name); var res = trap.call(this.handler, this.target, name, receiver); var fixedDesc = Object.getOwnPropertyDescriptor(this.target, name); // check consistency of the returned value if (fixedDesc !== undefined) { // getting an existing property if (isDataDescriptor(fixedDesc) && fixedDesc.configurable === false && fixedDesc.writable === false) { // own frozen data property if (!sameValue(res, fixedDesc.value)) { throw new TypeError("cannot report inconsistent value for "+ "non-writable, non-configurable property '"+ name+"'"); } } else { // it's an accessor property if (isAccessorDescriptor(fixedDesc) && fixedDesc.configurable === false && fixedDesc.get === undefined) { if (res !== undefined) { throw new TypeError("must report undefined for non-configurable "+ "accessor property '"+name+"' without getter"); } } } } return res; }, /** * If name denotes a fixed non-configurable, non-writable data property, * check that the trap rejects the assignment. */ set: function(receiver, name, val) { var trap = this.getTrap("set"); if (trap === undefined) { // default forwarding behavior return Reflect.set(this.target, name, val, receiver); } name = String(name); var res = trap.call(this.handler, this.target, name, val, receiver); res = !!res; // coerce to Boolean // if success is reported, check whether property is truly assignable if (res === true) { var fixedDesc = Object.getOwnPropertyDescriptor(this.target, name); if (fixedDesc !== undefined) { // setting an existing property if (isDataDescriptor(fixedDesc) && fixedDesc.configurable === false && fixedDesc.writable === false) { if (!sameValue(val, fixedDesc.value)) { throw new TypeError("cannot successfully assign to a "+ "non-writable, non-configurable property '"+ name+"'"); } } else { if (isAccessorDescriptor(fixedDesc) && fixedDesc.configurable === false && // non-configurable fixedDesc.set === undefined) { // accessor with undefined setter throw new TypeError("setting a property '"+name+"' that has "+ " only a getter"); } } } } return res; }, /** * Any own enumerable non-configurable properties of the target that are not * included in the trap result give rise to a TypeError. As such, we check * whether the returned result contains at least all sealed enumerable properties * of the target object. * * The trap should return an iterator. * * However, as implementations of pre-direct proxies still expect enumerate * to return an array of strings, we convert the iterator into an array. */ enumerate: function() { var trap = this.getTrap("enumerate"); if (trap === undefined) { // default forwarding behavior var trapResult = Reflect.enumerate(this.target); var result = []; var nxt = trapResult.next(); while (!nxt.done) { result.push(String(nxt.value)); nxt = trapResult.next(); } return result; } var trapResult = trap.call(this.handler, this.target); if (trapResult === null || trapResult === undefined || trapResult.next === undefined) { throw new TypeError("enumerate trap should return an iterator, got: "+ trapResult); } // propNames is used as a set of strings var propNames = Object.create(null); // var numProps = +trapResult.length; var result = []; // new Array(numProps); // trapResult is supposed to be an iterator // drain iterator to array as current implementations still expect // enumerate to return an array of strings var nxt = trapResult.next(); while (!nxt.done) { var s = String(nxt.value); if (propNames[s]) { throw new TypeError("enumerate trap cannot list a "+ "duplicate property '"+s+"'"); } propNames[s] = true; result.push(s); nxt = trapResult.next(); } /*for (var i = 0; i < numProps; i++) { var s = String(trapResult[i]); if (propNames[s]) { throw new TypeError("enumerate trap cannot list a "+ "duplicate property '"+s+"'"); } propNames[s] = true; result[i] = s; } */ var ownEnumerableProps = Object.keys(this.target); var target = this.target; ownEnumerableProps.forEach(function (ownEnumerableProp) { if (!propNames[ownEnumerableProp]) { if (isSealed(ownEnumerableProp, target)) { throw new TypeError("enumerate trap failed to include "+ "non-configurable enumerable property '"+ ownEnumerableProp+"'"); } if (!Object.isExtensible(target) && isFixed(ownEnumerableProp, target)) { // if handler is allowed not to report ownEnumerableProp as an own // property, we cannot guarantee that it will never report it as // an own property later. Once a property has been reported as // non-existent on a non-extensible object, it should forever be // reported as non-existent throw new TypeError("cannot report existing own property '"+ ownEnumerableProp+"' as non-existent on a "+ "non-extensible object"); } } }); return result; }, /** * The iterate trap is deprecated by the enumerate trap. */ iterate: Validator.prototype.enumerate, /** * Any own non-configurable properties of the target that are not included * in the trap result give rise to a TypeError. As such, we check whether the * returned result contains at least all sealed properties of the target * object. * * The trap result is normalized. * The trap result is not returned directly. Instead: * - create and return a fresh Array, * - of which each element is coerced to String, * - which does not contain duplicates * * FIXME: keys trap is deprecated */ /* keys: function() { var trap = this.getTrap("keys"); if (trap === undefined) { // default forwarding behavior return Reflect.keys(this.target); } var trapResult = trap.call(this.handler, this.target); // propNames is used as a set of strings var propNames = Object.create(null); var numProps = +trapResult.length; var result = new Array(numProps); for (var i = 0; i < numProps; i++) { var s = String(trapResult[i]); if (propNames[s]) { throw new TypeError("keys trap cannot list a "+ "duplicate property '"+s+"'"); } if (!Object.isExtensible(this.target) && !isFixed(s, this.target)) { // non-extensible proxies don't tolerate new own property names throw new TypeError("keys trap cannot list a new "+ "property '"+s+"' on a non-extensible object"); } propNames[s] = true; result[i] = s; } var ownEnumerableProps = Object.keys(this.target); var target = this.target; ownEnumerableProps.forEach(function (ownEnumerableProp) { if (!propNames[ownEnumerableProp]) { if (isSealed(ownEnumerableProp, target)) { throw new TypeError("keys trap failed to include "+ "non-configurable enumerable property '"+ ownEnumerableProp+"'"); } if (!Object.isExtensible(target) && isFixed(ownEnumerableProp, target)) { // if handler is allowed not to report ownEnumerableProp as an own // property, we cannot guarantee that it will never report it as // an own property later. Once a property has been reported as // non-existent on a non-extensible object, it should forever be // reported as non-existent throw new TypeError("cannot report existing own property '"+ ownEnumerableProp+"' as non-existent on a "+ "non-extensible object"); } } }); return result; }, */ /** * New trap that reifies [[Call]]. * If the target is a function, then a call to * proxy(...args) * Triggers this trap */ apply: function(target, thisBinding, args) { var trap = this.getTrap("apply"); if (trap === undefined) { return Reflect.apply(target,