/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1147); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind, nativeCreate = Object.create; // Naked function reference for surrogate-prototype-swapping. var Ctor = function(){}; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (true) { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.8.3'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var optimizeCb = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. var cb = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value)) return _.matcher(value); return _.property(value); }; _.iteratee = function(value, context) { return cb(value, context, Infinity); }; // An internal function for creating assigner functions. var createAssigner = function(keysFunc, undefinedOnly) { return function(obj) { var length = arguments.length; if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; }; // An internal function for creating a new object that inherits from another. var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; }; var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; // Helper for collection methods to determine whether a collection // should be iterated as an array or as an object // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; var getLength = property('length'); var isArrayLike = function(collection) { var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Create a reducing function iterating left or right. function createReduce(dir) { // Optimized iterator function as using arguments.length // in the main function will deoptimize the, see #1991. function iterator(obj, iteratee, memo, keys, index, length) { for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; } return function(obj, iteratee, memo, context) { iteratee = optimizeCb(iteratee, context, 4); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; // Determine the initial value if none is provided. if (arguments.length < 3) { memo = obj[keys ? keys[index] : index]; index += dir; } return iterator(obj, iteratee, memo, keys, index, length); }; } // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = createReduce(1); // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = createReduce(-1); // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var key; if (isArrayLike(obj)) { key = _.findIndex(obj, predicate, context); } else { key = _.findKey(obj, predicate, context); } if (key !== void 0 && key !== -1) return obj[key]; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; predicate = cb(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given item (using `===`). // Aliased as `includes` and `include`. _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { if (!isArrayLike(obj)) obj = _.values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return _.indexOf(obj, item, fromIndex) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { var func = isFunc ? method : value[method]; return func == null ? func : func.apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var set = isArrayLike(obj) ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = cb(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = cb(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = cb(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; return _.initial(array, array.length - n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return _.rest(array, Math.max(0, array.length - n)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, startIndex) { var output = [], idx = 0; for (var i = startIndex || 0, length = getLength(input); i < length; i++) { var value = input[i]; if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { //flatten current level of array or arguments object if (!shallow) value = flatten(value, shallow, strict); var j = 0, len = value.length; output.length += len; while (j < len) { output[idx++] = value[j++]; } } else if (!strict) { output[idx++] = value; } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!_.contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!_.contains(result, value)) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(arguments, true, true, 1); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { return _.unzip(arguments); }; // Complement of _.zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices _.unzip = function(array) { var length = array && _.max(array, getLength).length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Generator function to create the findIndex and findLastIndex functions function createPredicateIndexFinder(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; } // Returns the first index on an array-like that passes a predicate test _.findIndex = createPredicateIndexFinder(1); _.findLastIndex = createPredicateIndexFinder(-1); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Generator function to create the indexOf and lastIndexOf functions function createIndexFinder(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), _.isNaN); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; } // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Determines whether to execute a function as a constructor // or a normal function with the provided arguments var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (_.isObject(result)) return result; return self; }; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); var args = slice.call(arguments, 2); var bound = function() { return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = _.partial(_.delay, _, 1); // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed on and after the Nth call. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed up to (but not including) the Nth call. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; function collectNonEnumProps(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { keys.push(prop); } } } // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve all the property names of an object. _.allKeys = function(obj) { if (!_.isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Returns the results of applying the iteratee to each element of the object // In contrast to _.map it returns an object _.mapObject = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = _.keys(obj), length = keys.length, results = {}, currentKey; for (var index = 0; index < length; index++) { currentKey = keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = createAssigner(_.allKeys); // Assigns a given object with all the own properties in the passed-in object(s) // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) _.extendOwn = _.assign = createAssigner(_.keys); // Returns the first key on an object that passes a predicate test _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = _.keys(obj), key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (predicate(obj[key], key, obj)) return key; } }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(object, oiteratee, context) { var result = {}, obj = object, iteratee, keys; if (obj == null) return result; if (_.isFunction(oiteratee)) { keys = _.allKeys(obj); iteratee = optimizeCb(oiteratee, context); } else { keys = flatten(arguments, false, false, 1); iteratee = function(value, key, obj) { return key in obj; }; obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(flatten(arguments, false, false, 1), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = createAssigner(_.allKeys, true); // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. _.create = function(prototype, props) { var result = baseCreate(prototype); if (props) _.extendOwn(result, props); return result; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Returns whether an object has a given set of `key:value` pairs. _.isMatch = function(object, attrs) { var keys = _.keys(attrs), length = keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } var areArrays = className === '[object Array]'; if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // Deep compare objects. var keys = _.keys(a), key; length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (_.keys(b).length !== length) return false; while (length--) { // Deep compare each member key = keys[length]; if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), and in Safari 8 (#1929). if (typeof /./ != 'function' && typeof Int8Array != 'object') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; // Predicate-generating functions. Often useful outside of Underscore. _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = property; // Generates a function for a given object that returns a given property. _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. _.matcher = _.matches = function(attrs) { attrs = _.extendOwn({}, attrs); return function(obj) { return _.isMatch(obj, attrs); }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property, fallback) { var value = object == null ? void 0 : object[property]; if (value === void 0) { value = fallback; } return _.isFunction(value) ? value.call(object) : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(instance, obj) { return instance._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxy for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return '' + this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return _; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } }.call(this)); /***/ }), /***/ 1: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var TRANSFORM_SOURCE_ERROR_PREFIX = 'binary.unprocessable.image.transform.source.'; var TRANSFORM_SOURCE_TOO_LARGE = 'binary.unprocessable.image.transform.source.too_large'; // From https://phabricator.babeljs.io/T3083#65595 function ExtendableError() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } Error.apply(this, args); } ExtendableError.prototype = Object.create(Error.prototype); if (Object.setPrototypeOf) { Object.setPrototypeOf(ExtendableError, Error); } else { ExtendableError.__proto__ = Error; } var ScrivitoError = function (_ExtendableError) { _inherits(ScrivitoError, _ExtendableError); function ScrivitoError(message) { var captureStackTrace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; _classCallCheck(this, ScrivitoError); // message should be set before capturing stacktrace // since it is featured in the stacktrace in some environments. var _this = _possibleConstructorReturn(this, (ScrivitoError.__proto__ || Object.getPrototypeOf(ScrivitoError)).call(this)); _this.message = message; _this._captureStackTrace = captureStackTrace; if (captureStackTrace) { if (Error.captureStackTrace) { Error.captureStackTrace(_this, _this.constructor); } else { var stack = void 0; try { throw new Error(); } catch (error) { stack = error.stack; } Object.defineProperty(_this, 'stack', { value: stack }); } } return _this; } _createClass(ScrivitoError, [{ key: 'name', get: function get() { return this.constructor.name; } // For test purpose only. }, { key: 'captureStackTrace', get: function get() { return !!this._captureStackTrace; } }]); return ScrivitoError; }(ExtendableError); var ClientError = function (_ScrivitoError) { _inherits(ClientError, _ScrivitoError); function ClientError(message, httpCode, backendCode) { _classCallCheck(this, ClientError); var _this2 = _possibleConstructorReturn(this, (ClientError.__proto__ || Object.getPrototypeOf(ClientError)).call(this, message)); _this2.httpCode = httpCode; _this2.backendCode = backendCode; return _this2; } _createClass(ClientError, null, [{ key: 'for', value: function _for(message, httpCode, backendCode) { if (backendCode === TRANSFORM_SOURCE_TOO_LARGE) { return new TransformationSourceTooLargeError(message, httpCode, backendCode); } if (backendCode && backendCode.indexOf(TRANSFORM_SOURCE_ERROR_PREFIX) !== -1) { return new TransformationSourceInvalidError(message, httpCode, backendCode); } return new ClientError(message, httpCode, backendCode); } }]); return ClientError; }(ScrivitoError); var AccessDeniedError = function (_ClientError) { _inherits(AccessDeniedError, _ClientError); function AccessDeniedError(message, httpCode, backendCode) { _classCallCheck(this, AccessDeniedError); return _possibleConstructorReturn(this, (AccessDeniedError.__proto__ || Object.getPrototypeOf(AccessDeniedError)).call(this, message, httpCode, backendCode)); } return AccessDeniedError; }(ClientError); var ArgumentError = function (_ScrivitoError2) { _inherits(ArgumentError, _ScrivitoError2); function ArgumentError(message) { _classCallCheck(this, ArgumentError); return _possibleConstructorReturn(this, (ArgumentError.__proto__ || Object.getPrototypeOf(ArgumentError)).call(this, message)); } return ArgumentError; }(ScrivitoError); var CommunicationError = function (_ScrivitoError3) { _inherits(CommunicationError, _ScrivitoError3); function CommunicationError(message, httpCode) { _classCallCheck(this, CommunicationError); var _this5 = _possibleConstructorReturn(this, (CommunicationError.__proto__ || Object.getPrototypeOf(CommunicationError)).call(this, message)); _this5.httpCode = httpCode; return _this5; } return CommunicationError; }(ScrivitoError); var BackendError = function (_CommunicationError) { _inherits(BackendError, _CommunicationError); function BackendError(message, httpCode) { _classCallCheck(this, BackendError); return _possibleConstructorReturn(this, (BackendError.__proto__ || Object.getPrototypeOf(BackendError)).call(this, message, httpCode)); } return BackendError; }(CommunicationError); var InternalError = function (_ScrivitoError4) { _inherits(InternalError, _ScrivitoError4); function InternalError(message) { _classCallCheck(this, InternalError); return _possibleConstructorReturn(this, (InternalError.__proto__ || Object.getPrototypeOf(InternalError)).call(this, message)); } return InternalError; }(ScrivitoError); var NetworkError = function (_CommunicationError2) { _inherits(NetworkError, _CommunicationError2); function NetworkError(response) { _classCallCheck(this, NetworkError); var status = response.status; var _this8 = _possibleConstructorReturn(this, (NetworkError.__proto__ || Object.getPrototypeOf(NetworkError)).call(this, status === 0 ? response.statusText : response.responseText, status)); _this8.response = response; return _this8; } return NetworkError; }(CommunicationError); var RateLimitExceededError = function (_CommunicationError3) { _inherits(RateLimitExceededError, _CommunicationError3); function RateLimitExceededError(message, httpCode) { _classCallCheck(this, RateLimitExceededError); return _possibleConstructorReturn(this, (RateLimitExceededError.__proto__ || Object.getPrototypeOf(RateLimitExceededError)).call(this, message, httpCode)); } return RateLimitExceededError; }(CommunicationError); // public API var ResourceNotFoundError = function (_ScrivitoError5) { _inherits(ResourceNotFoundError, _ScrivitoError5); function ResourceNotFoundError(message) { _classCallCheck(this, ResourceNotFoundError); return _possibleConstructorReturn(this, (ResourceNotFoundError.__proto__ || Object.getPrototypeOf(ResourceNotFoundError)).call(this, message)); } return ResourceNotFoundError; }(ScrivitoError); var UnauthorizedError = function (_ClientError2) { _inherits(UnauthorizedError, _ClientError2); function UnauthorizedError(message, httpCode, backendCode, details) { _classCallCheck(this, UnauthorizedError); var _this11 = _possibleConstructorReturn(this, (UnauthorizedError.__proto__ || Object.getPrototypeOf(UnauthorizedError)).call(this, message, httpCode, backendCode)); _this11.details = details || {}; return _this11; } return UnauthorizedError; }(ClientError); var TransformationSourceTooLargeError = function (_ClientError3) { _inherits(TransformationSourceTooLargeError, _ClientError3); function TransformationSourceTooLargeError(message, httpCode, backendCode) { _classCallCheck(this, TransformationSourceTooLargeError); return _possibleConstructorReturn(this, (TransformationSourceTooLargeError.__proto__ || Object.getPrototypeOf(TransformationSourceTooLargeError)).call(this, message, httpCode, backendCode)); } return TransformationSourceTooLargeError; }(ClientError); var TransformationSourceInvalidError = function (_ClientError4) { _inherits(TransformationSourceInvalidError, _ClientError4); function TransformationSourceInvalidError(message, httpCode, backendCode) { _classCallCheck(this, TransformationSourceInvalidError); return _possibleConstructorReturn(this, (TransformationSourceInvalidError.__proto__ || Object.getPrototypeOf(TransformationSourceInvalidError)).call(this, message, httpCode, backendCode)); } return TransformationSourceInvalidError; }(ClientError); var TranslationError = function (_InternalError) { _inherits(TranslationError, _InternalError); function TranslationError(message) { _classCallCheck(this, TranslationError); return _possibleConstructorReturn(this, (TranslationError.__proto__ || Object.getPrototypeOf(TranslationError)).call(this, message)); } return TranslationError; }(InternalError); var NavigateToEmptyBinaryError = function (_InternalError2) { _inherits(NavigateToEmptyBinaryError, _InternalError2); function NavigateToEmptyBinaryError(message) { _classCallCheck(this, NavigateToEmptyBinaryError); return _possibleConstructorReturn(this, (NavigateToEmptyBinaryError.__proto__ || Object.getPrototypeOf(NavigateToEmptyBinaryError)).call(this, message)); } return NavigateToEmptyBinaryError; }(InternalError); var InterpolationError = function (_TranslationError) { _inherits(InterpolationError, _TranslationError); function InterpolationError(message) { _classCallCheck(this, InterpolationError); return _possibleConstructorReturn(this, (InterpolationError.__proto__ || Object.getPrototypeOf(InterpolationError)).call(this, message)); } return InterpolationError; }(TranslationError); exports.AccessDeniedError = AccessDeniedError; exports.ArgumentError = ArgumentError; exports.BackendError = BackendError; exports.ClientError = ClientError; exports.InternalError = InternalError; exports.InterpolationError = InterpolationError; exports.NavigateToEmptyBinaryError = NavigateToEmptyBinaryError; exports.NetworkError = NetworkError; exports.RateLimitExceededError = RateLimitExceededError; exports.ResourceNotFoundError = ResourceNotFoundError; exports.ScrivitoError = ScrivitoError; exports.TransformationSourceInvalidError = TransformationSourceInvalidError; exports.TransformationSourceTooLargeError = TransformationSourceTooLargeError; exports.TranslationError = TranslationError; exports.UnauthorizedError = UnauthorizedError; /***/ }), /***/ 10: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // The iframe context is the `scrivito` object, available top-level in the application iframe and // used as the public API for the client. Following indirection is used in the specs in order to // not pollute the global `window` object with the public API properties. var iframeContext = void 0; function getWindowContext() { return iframeContext || window.Scrivito; } // For test purpose only. function setWindowContext(newIframeContext) { iframeContext = newIframeContext; } exports.getWindowContext = getWindowContext; exports.setWindowContext = setWindowContext; /***/ }), /***/ 106: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _controller_content_proxy = __webpack_require__(53); var _controller_content_proxy2 = _interopRequireDefault(_controller_content_proxy); var _apply_placeholder_to_element = __webpack_require__(52); var _apply_placeholder_to_element2 = _interopRequireDefault(_apply_placeholder_to_element); __webpack_require__(107); var _medium_editor = __webpack_require__(191); var _medium_editor2 = _interopRequireDefault(_medium_editor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var HtmlEditor = function () { _createClass(HtmlEditor, null, [{ key: 'canEdit', value: function canEdit(_ref) { var type = _ref.type; return type === 'html'; } }]); function HtmlEditor(_ref2) { var controller = _ref2.controller; _classCallCheck(this, HtmlEditor); this.controller = controller; } _createClass(HtmlEditor, [{ key: 'editorWillBeActivated', value: function editorWillBeActivated() { this.controller.setDomMode('Replace'); } }, { key: 'editorDomWasMounted', value: function editorDomWasMounted(domNode) { (0, _apply_placeholder_to_element2.default)(domNode); $(domNode).html(this.controller.content); var editorProxy = new _controller_content_proxy2.default(domNode, this.controller); (0, _medium_editor2.default)(editorProxy); } }]); return HtmlEditor; }(); exports.default = HtmlEditor; /***/ }), /***/ 107: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _mediumEditor = __webpack_require__(201); var _mediumEditor2 = _interopRequireDefault(_mediumEditor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } window.MediumEditor = _mediumEditor2.default; /***/ }), /***/ 108: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _controller_content_proxy = __webpack_require__(53); var _controller_content_proxy2 = _interopRequireDefault(_controller_content_proxy); var _apply_placeholder_to_element = __webpack_require__(52); var _apply_placeholder_to_element2 = _interopRequireDefault(_apply_placeholder_to_element); var _string_editor = __webpack_require__(192); var _string_editor2 = _interopRequireDefault(_string_editor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var StringEditor = function () { _createClass(StringEditor, null, [{ key: 'canEdit', value: function canEdit(_ref) { var type = _ref.type; return type === 'string'; } }]); function StringEditor(_ref2) { var attributeInfo = _ref2.attributeInfo, controller = _ref2.controller; _classCallCheck(this, StringEditor); this.attributeInfo = attributeInfo; this.controller = controller; } _createClass(StringEditor, [{ key: 'editorWillBeActivated', value: function editorWillBeActivated() { this.controller.setDomMode('Replace'); } }, { key: 'editorDomWasMounted', value: function editorDomWasMounted(domNode) { (0, _apply_placeholder_to_element2.default)(domNode); $(domNode).text(this.controller.content); var editorProxy = new _controller_content_proxy2.default(domNode, this.controller); (0, _string_editor2.default)(editorProxy); } }]); return StringEditor; }(); exports.default = StringEditor; /***/ }), /***/ 109: /***/ (function(module, exports, __webpack_require__) { "use strict"; if (!window.scrivito) { window.scrivito = {}; } __webpack_require__(121); var clientContext = __webpack_require__(211); clientContext.keys().forEach(clientContext); __webpack_require__(111); var appContext = __webpack_require__(210); appContext.keys().forEach(appContext); __webpack_require__(183); __webpack_require__(185); __webpack_require__(67); __webpack_require__(65); var reactContext = __webpack_require__(212); reactContext.keys().forEach(reactContext); __webpack_require__(184); /***/ }), /***/ 111: /***/ (function(module, exports, __webpack_require__) { "use strict"; //= require_self //= require_tree ./app_support (function () { scrivito.AppSupport = {}; })(); /***/ }), /***/ 112: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _current_page = __webpack_require__(9); var _provide_ui_config = __webpack_require__(36); var _errors = __webpack_require__(1); var _window_context = __webpack_require__(10); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var UI_CONFIG_KEYS = ['title', 'description', 'thumbnail']; /* The AppAdapter is provided to the UI by the App. * The UI uses it as a communication channel to the App. * It is the counterpart of the UiAdapter. * * Communication should use only built-in datatypes, * i.e. communicate using `string` and `array`, not `BasicObj`. */ var AppAdapter = { titleForClass: function titleForClass(className) { return (0, _provide_ui_config.getUiConfigPropertyFor)(className, 'title'); }, titleForObj: function titleForObj(objId) { return invokeCallbackFromUiConfigWithObjId('titleForContent', objId); }, descriptionForObj: function descriptionForObj(objId) { return invokeCallbackFromUiConfigWithObjId('descriptionForContent', objId); }, titleForWidget: function titleForWidget(objId, widgetId) { var obj = (0, _window_context.getWindowContext)().Obj.getIncludingDeleted(objId); var widget = obj.widget(widgetId); return invokeCallbackFromUiConfigWithObj('titleForContent', widget); }, thumbnailForObj: function thumbnailForObj(objId) { return invokeCallbackFromUiConfigWithObjId('thumbnailForContent', objId); }, getClasses: function getClasses() { var realm = (0, _window_context.getWindowContext)(); var classDatas = []; _underscore2.default.each(realm.allObjClasses(), function (modelClass, name) { return classDatas.push(buildClassData('Obj', name, modelClass)); }); _underscore2.default.each(realm.allWidgetClasses(), function (modelClass, name) { return classDatas.push(buildClassData('Widget', name, modelClass)); }); return classDatas; }, navigateTo: function navigateTo(objId) { (0, _current_page.navigateTo)(function () { return (0, _window_context.getWindowContext)().Obj.get(objId); }); } }; function buildClassData(type, name, modelClass) { var schema = scrivito.Schema.forClass(modelClass); var classData = { name: name, type: type, attributes: buildAttributeData(schema, _underscore2.default.keys(schema.attributes)), validContainerClasses: schema.validContainerClasses }; addValuesFromUiConfig(classData, name); addAttributeValuesFromUiConfig(classData, name); return classData; } function buildAttributeData(schema, names) { return names.map(function (name) { var _schema$attributeDefi = schema.attributeDefinition(name), _schema$attributeDefi2 = _slicedToArray(_schema$attributeDefi, 2), type = _schema$attributeDefi2[0], options = _schema$attributeDefi2[1]; var attributeDefinition = { name: name, type: type }; if (options) { if (options.only) { attributeDefinition.only = options.only; } if (options.validValues) { attributeDefinition.validValues = options.validValues; } } return attributeDefinition; }); } function addValuesFromUiConfig(classData, className) { UI_CONFIG_KEYS.forEach(function (uiConfigKey) { var uiConfigValue = (0, _provide_ui_config.getUiConfigPropertyFor)(className, uiConfigKey); if (uiConfigValue) { classData[uiConfigKey] = uiConfigValue; } }); } function addAttributeValuesFromUiConfig(classData, className) { var attributes = (0, _provide_ui_config.getUiConfigPropertyFor)(className, 'attributes'); if (!attributes) { return; } Object.keys(attributes).forEach(function (name) { var attributeDefinition = _underscore2.default.findWhere(classData.attributes, { name: name }); if (attributeDefinition) { var _attributes$name = attributes[name], title = _attributes$name.title, description = _attributes$name.description; _underscore2.default.extend(attributeDefinition, { title: title, description: description }); } }); } function invokeCallbackFromUiConfigWithObjId(callbackName, objId) { var obj = (0, _window_context.getWindowContext)().Obj.getIncludingDeleted(objId); return invokeCallbackFromUiConfigWithObj(callbackName, obj); } function invokeCallbackFromUiConfigWithObj(callbackName, obj) { var callback = (0, _provide_ui_config.getUiConfigPropertyFor)(obj.objClass, callbackName); if (callback) { assertIsFunction(callback, callbackName); return callback(obj); } } function assertIsFunction(callback, name) { if (typeof callback !== 'function') { throw new _errors.ArgumentError(name + ' in the Scrivito.provideUiConfig definition must be a function'); } } scrivito.AppAdapter = AppAdapter; })(); /***/ }), /***/ 113: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _current_page = __webpack_require__(9); (function () { function pushWith(target) { var state = { scrivitoObjId: target.id }; var url = scrivito.Routing.generate(target); var history = scrivito.BrowserLocation.window().history; if (history.state && history.state.scrivitoObjId === target.id) { // noop; return; } history.pushState(state, '', url); } function replaceWith(target) { var state = { scrivitoObjId: target.id }; var url = scrivito.Routing.generate(target); scrivito.BrowserLocation.window().history.replaceState(state, '', url); } function handlePopEvents() { scrivito.BrowserLocation.window().onpopstate = onpopstate; } function recognizeCurrentLocation() { var location = scrivito.BrowserLocation.window().location.toString(); (0, _current_page.replaceCurrentPage)(function () { return scrivito.Routing.recognize(location); }); } function init() { recognizeCurrentLocation(); handlePopEvents(); } function onpopstate(event) { var objId = event.state && event.state.scrivitoObjId; if (objId) { (0, _current_page.replaceCurrentPage)(function () { return scrivito.BasicObj.get(objId); }); } else { recognizeCurrentLocation(); } } // Do not use the function name "window", // otherwise you will no longer be able to access the global window function myWindow() { return window; } scrivito.BrowserLocation = {}; scrivito.BrowserLocation.init = init; scrivito.BrowserLocation.pushWith = pushWith; scrivito.BrowserLocation.replaceWith = replaceWith; scrivito.BrowserLocation.window = myWindow; })(); /***/ }), /***/ 114: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { function changeLocation(newLocation) { if (scrivito.uiAdapter) { // change the location of the parent, to avoid CSP errors. scrivito.uiAdapter.navigateToExternalUrl(newLocation); } else { scrivito.setWindowLocation(newLocation); } } function setWindowLocation(newLocation) { window.location = newLocation; } function openLocation(newLocation, target) { window.open(newLocation, target); } // For test purpose only. scrivito.setWindowLocation = setWindowLocation; scrivito.changeLocation = changeLocation; scrivito.openLocation = openLocation; })(); /***/ }), /***/ 1147: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _install_rails_api_fallback = __webpack_require__(213); var _install_rails_api_fallback2 = _interopRequireDefault(_install_rails_api_fallback); var _initialize_sdk = __webpack_require__(214); var _initialize_sdk2 = _interopRequireDefault(_initialize_sdk); var _connect_to_ui = __webpack_require__(79); var _connect_to_ui2 = _interopRequireDefault(_connect_to_ui); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ui = (0, _connect_to_ui2.default)(); /* * This is the webpack entry file used by Rails application that also use the JS SDK */ if (ui) { ui.installRailsApi(); } else { (0, _install_rails_api_fallback2.default)(); } (0, _initialize_sdk2.default)(ui); /***/ }), /***/ 115: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var registry = []; function register(editor) { registry.push(editor); } function editorClassFor(attrDef) { return _underscore2.default.find(registry, function (editor) { return editor.canEdit(attrDef); }); } function clear() { registry = []; } scrivito.editorRegistry = { editorClassFor: editorClassFor, clear: clear }; scrivito.registerEditor = register; })(); /***/ }), /***/ 116: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { function isEditingMode() { if (scrivito.uiAdapter) { return scrivito.uiAdapter.isEditingMode(); } return false; } scrivito.isEditingMode = isEditingMode; })(); /***/ }), /***/ 117: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _errors = __webpack_require__(1); (function () { var hashPrefix = '!'; var isPathRoutingMode = void 0; var basePath = void 0; var isInitialized = false; function init(_ref) { var routingMethod = _ref.routingMethod, routingBasePath = _ref.routingBasePath; isInitialized = true; isPathRoutingMode = routingMethod === 'path'; basePath = routingBasePath || ''; } // For test purpose only. function reset() { isInitialized = false; isPathRoutingMode = undefined; basePath = undefined; } function assertIsInitialized(methodName) { if (!isInitialized) { throw new _errors.InternalError(methodName + ' can\'t be called before init.'); } } function generate(obj) { assertIsInitialized('generate'); var path = scrivito.RoutingPath.generate(obj); if (isPathRoutingMode) { var _scrivito$parseUrl = scrivito.parseUrl(window.location), origin = _scrivito$parseUrl.origin; var normalizedPath = ('/' + basePath + '/' + path).replace(/\/+/g, '/'); return '' + origin + normalizedPath; } return '#' + hashPrefix + path; } function recognize(url) { assertIsInitialized('recognize'); var path = void 0; if (isPathRoutingMode) { path = extractPath(url); } else { path = extractPathFromHash(url); } return scrivito.RoutingPath.recognize(path); } function extractPath(url) { var _scrivito$parseUrl2 = scrivito.parseUrl(url), pathname = _scrivito$parseUrl2.pathname; if (pathname.substring(0, basePath.length) !== basePath) { return ''; } return pathname.substring(basePath.length); } function extractPathFromHash(url) { var _scrivito$parseUrl3 = scrivito.parseUrl(url), hash = _scrivito$parseUrl3.hash; if (hash.substring(0, hashPrefix.length) === hashPrefix) { return hash.substring(hashPrefix.length); } return ''; } scrivito.Routing = {}; scrivito.Routing.init = init; scrivito.Routing.reset = reset; scrivito.Routing.generate = generate; scrivito.Routing.recognize = recognize; })(); /***/ }), /***/ 118: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _window_registry = __webpack_require__(20); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var homepageCallback = void 0; var RoutingPath = { init: function init(initHomepageCallback) { homepageCallback = initHomepageCallback; }, generate: function generate(obj) { assertObjIsBasicObj(obj); if (isHomepage(obj)) { return '/'; } if (obj.permalink) { return '/' + obj.permalink; } var slug = generateSlug(obj); if (slug) { return '/' + slug + '-' + obj.id; } return '/' + obj.id; }, recognize: function recognize(path) { assertPathIsString(path); if (_underscore2.default.include(['/', ''], path)) { return scrivito.unwrapAppClassValues(homepageCallback()); } // remove leading / var pathWithoutLeadingSlash = removeLeadingChars(path, '/'); try { return scrivito.BasicObj.getByPermalink(pathWithoutLeadingSlash); } catch (error) { if (!(error instanceof _errors.ResourceNotFoundError)) { throw error; } } return scrivito.BasicObj.get(removeSlug(pathWithoutLeadingSlash)); }, // For test purpose only. get homepageCallback() { return homepageCallback; }, // For test purpose only. resetHomepageCallback: function resetHomepageCallback() { homepageCallback = undefined; } }; function removeLeadingChars(input, leadingChars) { if (input.substring(0, leadingChars.length) === leadingChars) { return input.substring(leadingChars.length); } return input; } function isHomepage(obj) { if (!homepageCallback) { return false; } var homepage = scrivito.loadableWithDefault(null, homepageCallback); if (!homepage) { return false; } return homepage.id === obj.id; } function assertObjIsBasicObj(obj) { if (!(obj instanceof scrivito.BasicObj)) { throw new _errors.ArgumentError('Parameter obj needs to be a scrivito.BasicObj.'); } } function assertPathIsString(input) { if (!_underscore2.default.isString(input)) { throw new _errors.ArgumentError('Parameter path needs to be a String.'); } } function generateSlug(basicObj) { var registry = (0, _window_registry.getWindowRegistry)(); var appObj = scrivito.wrapInAppClass(registry, basicObj); return appObj.slug(); } function removeSlug(input) { return _underscore2.default.last(input.split('-')); } scrivito.RoutingPath = RoutingPath; })(); /***/ }), /***/ 119: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { function scrollWindowToTop() { window.scrollTo(0, 0); } // For test purpose only. scrivito.scrollWindowToTop = scrollWindowToTop; })(); /***/ }), /***/ 12: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _loadable_data = __webpack_require__(3); var _loadable_data2 = _interopRequireDefault(_loadable_data); var _underscore = __webpack_require__(0); var _errors = __webpack_require__(1); var _future_binary = __webpack_require__(21); var _future_binary2 = _interopRequireDefault(_future_binary); var _metadata_collection = __webpack_require__(57); var _metadata_collection2 = _interopRequireDefault(_metadata_collection); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // this is a small, 1x1 pixel, fully transparent GIF image var FALLBACK_URL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; var FALLBACK_BINARY_DATA = { public_access: { get: { url: FALLBACK_URL } }, private_access: { get: { url: FALLBACK_URL } } }; // public API var Binary = function () { function Binary(id, isPublic, definition) { var _this = this; _classCallCheck(this, Binary); this._id = id; this._isPublic = isPublic; this._definition = definition; this._loadableData = new _loadable_data2.default({ state: modelState(id, definition), loader: function loader() { return _this._loadUrlData(); } }); } // public API _createClass(Binary, [{ key: 'copy', // public API value: function copy() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; options.idToCopy = this._id; return new _future_binary2.default(options); } // public API }, { key: 'isPrivate', value: function isPrivate() { return !this._isPublic; } // public API }, { key: 'transform', value: function transform(definition) { return new Binary(this._id, this._isPublic, (0, _underscore.extend)({}, this._definition, definition)); } // public API }, { key: 'isTransformed', // public API value: function isTransformed() { return !!this._definition; } }, { key: 'isExplicitlyTransformed', value: function isExplicitlyTransformed() { return this.isTransformed() && !(0, _underscore.isEmpty)(this._definition); } }, { key: 'isRaw', value: function isRaw() { return !this.isTransformed(); } // public API }, { key: 'equals', // For test purpose only. value: function equals(binary) { return binary instanceof Binary && binary.id === this.id && binary.isPrivate() === this.isPrivate() && (0, _underscore.isEqual)(binary.definition, this.definition); } // For test purpose only. }, { key: '_loadUrlData', value: function _loadUrlData() { var path = 'blobs/' + encodeURIComponent(this._id); var params = void 0; if (this._definition) { path = path + '/transform'; params = { transformation: this._definition }; } return scrivito.CmsRestApi.get(path, params); } }, { key: '_assertNotTransformed', value: function _assertNotTransformed(fieldName) { if (this.isTransformed()) { throw new _errors.ScrivitoError('"' + fieldName + '" is not available for transformed images.' + ' Use "Scrivito.Binary#raw" to access the untransformed version of the image.'); } } }, { key: 'id', get: function get() { return this._id; } }, { key: 'original', get: function get() { return new Binary(this._id, this._isPublic, {}); } // public API }, { key: 'raw', get: function get() { return new Binary(this._id, this._isPublic); } }, { key: 'url', get: function get() { return this._urlData[this._accessType].get.url; } // public API }, { key: 'filename', get: function get() { var url = this.url; if (url.match(/^data:/)) { return ''; } return scrivito.parseUrl(url).pathname.split('/').pop(); } // public API }, { key: 'metadata', get: function get() { this._assertNotTransformed('Metadata'); return new _metadata_collection2.default(this._id); } // public API }, { key: 'contentType', get: function get() { this._assertNotTransformed('Content type'); return this.metadata.get('contentType'); } // public API }, { key: 'contentLength', get: function get() { this._assertNotTransformed('Content length'); return this.metadata.get('contentLength'); } }, { key: 'extname', get: function get() { if (this.raw.filename.indexOf('.') > -1) { var ext = /[^.\\]*$/.exec(this.raw.filename)[0]; return ext.toLowerCase(); } } }, { key: 'definition', get: function get() { return this._definition || null; } }, { key: '_accessType', get: function get() { if (this.isPrivate()) { return 'private_access'; } return 'public_access'; } }, { key: '_urlData', get: function get() { return this._loadableData.get() || FALLBACK_BINARY_DATA; } }], [{ key: 'upload', value: function upload(source) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options.source = source; return new _future_binary2.default(options); } }, { key: 'store', value: function store(binaryId, definition, cmsRestApiResponse) { var loadableData = new _loadable_data2.default({ state: modelState(binaryId, definition) }); loadableData.set(cmsRestApiResponse); var raw = new Binary(binaryId); if (definition) { return raw.transform(definition); } return raw; } }, { key: 'storeMetadata', value: function storeMetadata(binaryId, cmsRestApiResponse) { return _metadata_collection2.default.store(binaryId, cmsRestApiResponse); } }]); return Binary; }(); function modelState(binaryId, definition) { var subStateKey = scrivito.computeCacheKey([binaryId, definition]); return scrivito.cmsState.subState('binary').subState(subStateKey); } exports.default = Binary; /***/ }), /***/ 120: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _window_context = __webpack_require__(10); var _errors = __webpack_require__(1); var _binary = __webpack_require__(12); var _binary2 = _interopRequireDefault(_binary); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function basicUrlFor(target) { assertValidTarget(target); if (target instanceof scrivito.BasicLink) { return urlForLink(target); } if (target instanceof _binary2.default) { return urlForBinary(target); } if (isBinaryObj(target)) { return urlForBinaryObj(target); } return scrivito.Routing.generate(target); } function urlFor(target) { var basicTarget = scrivito.unwrapAppClassValues(target); return basicUrlFor(basicTarget); } function assertValidTarget(target) { if (!target) { throw new _errors.ArgumentError('Missing target.'); } if (target instanceof scrivito.BasicLink) { return; } if (target instanceof scrivito.BasicObj) { return; } if (target instanceof _binary2.default) { return; } throw new _errors.ArgumentError('Target is invalid. Valid targets are instances of Obj or Link.'); } function urlForBinary(binary) { return binary.url; } function urlForBinaryObj(obj) { var blob = obj.get('blob', ['binary']); if (blob) { return urlForBinary(blob); } return '#__empty_blob'; } function urlForLink(link) { if (link.isExternal()) { return link.url; } return basicUrlFor(link.obj); } function context() { return (0, _window_context.getWindowContext)(); } function isBinaryObj(obj) { var klass = context().getClass(obj.objClass); if (!klass) { return false; } var schema = scrivito.Schema.forClass(klass); return schema.isBinary(); } scrivito.basicUrlFor = basicUrlFor; scrivito.urlFor = urlFor; })(); /***/ }), /***/ 121: /***/ (function(module, exports, __webpack_require__) { "use strict"; //= require_self //= require_tree ./client (function () { scrivito.client = {}; })(); /***/ }), /***/ 122: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var isDisabled = false; function ajax(type, path) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var isWriteRequest = _underscore2.default.contains(['PUT', 'POST', 'DELETE'], type); var skipWriteMonitor = options && options.skip_write_monitor; if (isWriteRequest) { options.timeout = 15000; // miliseconds if (!skipWriteMonitor) { scrivito.WriteMonitor.startWrite(); } } var ajaxPromise = performRequest(type, path, options); if (isWriteRequest && !skipWriteMonitor) { scrivito.WriteMonitor.endWriteWhenDone(ajaxPromise); } return ajaxPromise; } function ajaxWithErrorDialog(type, path, options) { return scrivito.ajax(type, path, options).catch(function (error) { displayAjaxError(error); throw error; }); } function displayAjaxError(error) { var message = void 0; var messageForEditor = void 0; if (_underscore2.default.isObject(error)) { message = scrivito.t('ajax_error', error.message); messageForEditor = error.message_for_editor; } else if (_underscore2.default.contains(['abort', 'parsererror', 'timeout'], error)) { message = scrivito.t('ajax_error.communication'); } else { message = scrivito.t('ajax_error', error); } if (scrivito.isDevelopmentMode) { scrivito.AlertDialog.open(message); } else { scrivito.logError(message); scrivito.ErrorDialog.open(messageForEditor || scrivito.t('ajax_error.message_for_editor'), [error.timestamp, message]); } } // For test purpose only function disableAjax() { isDisabled = true; } // For test purpose only function enableAjax() { isDisabled = false; } function performRequest(type, path) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (isDisabled) { return scrivito.Promise.reject('scrivito.ajax is disabled due to scrivito.disableAjax()!'); } var baseUrl = window.location.protocol + '//' + window.location.host + '/__scrivito/'; if (options.data) { options.data = JSON.stringify(options.data); } var ajaxRequest = $.ajax(baseUrl + path, _underscore2.default.extend({ type: type, dataType: 'json', contentType: 'application/json; charset=utf-8', cache: false }, options)); return new scrivito.Promise(function (resolve, reject) { ajaxRequest.then(resolve); ajaxRequest.fail(function (xhr, _textStatus, xhrError) { try { return reject(JSON.parse(xhr.responseText)); } catch (_error) { return reject(xhrError); } }); }); } scrivito.ajax = ajax; scrivito.ajaxWithErrorDialog = ajaxWithErrorDialog; scrivito.displayAjaxError = displayAjaxError; scrivito.disableAjax = disableAjax; scrivito.enableAjax = enableAjax; })(); /***/ }), /***/ 123: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _load = __webpack_require__(6); var _load2 = _interopRequireDefault(_load); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function provideAsyncInstanceMethods(klass, methods) { return provideAsyncMethods(klass.prototype, methods); } function provideAsyncMethods(klass, methods) { _underscore2.default.each(methods, function (asyncName, syncName) { klass[asyncName] = asyncMethodFor(syncName); }); } function asyncMethodFor(syncName) { return function asyncMethod() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return scrivito.PublicPromise.resolve((0, _load2.default)(function () { return _this[syncName].apply(_this, args); })); }; } function asyncMethodStub() { throw new _errors.InternalError('this method is supposed to be overwritten by calling provideAsyncMethods'); } // export scrivito.provideAsyncMethods = provideAsyncMethods; scrivito.provideAsyncClassMethods = provideAsyncMethods; scrivito.provideAsyncInstanceMethods = provideAsyncInstanceMethods; scrivito.asyncMethodStub = asyncMethodStub; })(); /***/ }), /***/ 124: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _pretty_print = __webpack_require__(15); var _pretty_print2 = _interopRequireDefault(_pretty_print); var _attribute_inflection = __webpack_require__(7); var _binary = __webpack_require__(12); var _binary2 = _interopRequireDefault(_binary); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { scrivito.AttributeSerializer = { serialize: function serialize(attributes) { var serializedAttributes = {}; _underscore2.default.each(attributes, function (_ref, name) { var _ref2 = _slicedToArray(_ref, 2), value = _ref2[0], attrInfo = _ref2[1]; var serializedName = convertCamelCasedAttributeName(name); if (scrivito.Attribute.isSystemAttribute(serializedName)) { serializedAttributes[serializedName] = value; } else { var _attrInfo = _slicedToArray(attrInfo, 2), attrType = _attrInfo[0], attrOptions = _attrInfo[1]; serializedAttributes[serializedName] = [serializeAttributeType(attrType, name), valueOrNull(serializeAttributeValue(attrType, attrOptions, value, name))]; } }); return serializedAttributes; } }; function convertCamelCasedAttributeName(name) { if (!(0, _attribute_inflection.isCamelCase)(name)) { throw new _errors.ArgumentError('Attribute names have to be in camel case.'); } return (0, _attribute_inflection.underscore)(name); } function serializeAttributeType(type, name) { switch (type) { case 'enum': return 'string'; case 'float': case 'integer': return 'number'; case 'multienum': return 'stringlist'; case 'binary': case 'date': case 'html': case 'link': case 'linklist': case 'reference': case 'referencelist': case 'string': case 'stringlist': case 'widgetlist': return type; default: throw new _errors.ArgumentError('Attribute "' + name + '" is of unsupported type "' + type + '".'); } } function serializeAttributeValue(type, options, value, name) { if (value === null) { return value; } switch (type) { case 'binary': return serializeBinaryAttributeValue(value, name); case 'date': return serializeDateAttributeValue(value, name); case 'enum': return serializeEnumAttributeValue(options, value, name); case 'float': return serializeFloatAttributeValue(value, name); case 'html': return serializeHtmlAttributeValue(value, name); case 'integer': return serializeIntegerAttributeValue(value, name); case 'link': return serializeLinkAttributeValue(value, name); case 'linklist': return serializeLinklistAttributeValue(value, name); case 'multienum': return serializeMultienumAttributeValue(options, value, name); case 'reference': return serializeReferenceAttributeValue(value, name); case 'referencelist': return serializeReferencelistAttributeValue(value, name); case 'string': return serializeStringAttributeValue(value, name); case 'stringlist': return serializeStringlistAttributeValue(value, name); case 'widgetlist': return serializeWidgetlistAttributeValue(value, name); default: throw new _errors.InternalError('serializeAttributeValue is not implemented for "' + type + '".'); } } function valueOrNull(value) { if ((_underscore2.default.isString(value) || _underscore2.default.isArray(value)) && _underscore2.default.isEmpty(value)) { return null; } return value; } function throwInvalidAttributeValue(value, name, expected) { throw new _errors.ArgumentError('Unexpected value ' + (0, _pretty_print2.default)(value) + ' for' + (' attribute "' + name + '". Expected: ' + expected)); } function serializeBinaryAttributeValue(value, name) { if (value instanceof _binary2.default) { return { id: value.id }; } throwInvalidAttributeValue(value, name, 'A Binary.'); } function serializeDateAttributeValue(value, name) { if (_underscore2.default.isDate(value)) { return scrivito.types.formatDateToString(value); } if (scrivito.types.isValidDateString(value)) { return value; } throwInvalidAttributeValue(value, name, 'A Date.'); } function serializeEnumAttributeValue(_ref3, value, name) { var validValues = _ref3.validValues; if (_underscore2.default.contains(validValues, value)) { return value; } var e = 'Valid attribute values are contained in its "validValues" array [' + validValues + '].'; throwInvalidAttributeValue(value, name, e); } function serializeFloatAttributeValue(value, name) { if (scrivito.types.isValidFloat(value)) { return value; } var invalidValue = value; if (_underscore2.default.isNumber(value)) { invalidValue = String(value); } throwInvalidAttributeValue(invalidValue, name, 'A Number, that is #isFinite().'); } function serializeHtmlAttributeValue(value, name) { if (_underscore2.default.isString(value)) { return value; } throwInvalidAttributeValue(value, name, 'A String.'); } function serializeIntegerAttributeValue(value, name) { if (scrivito.types.isValidInteger(value)) { return value; } throwInvalidAttributeValue(value, name, 'A Number, that is #isSafeInteger().'); } function serializeLinkAttributeValue(value, name) { if (validLinkObject(value)) { return convertLinkToCmsApi(value); } throwInvalidAttributeValue(value, name, 'A Link instance.'); } function serializeLinklistAttributeValue(value, name) { if (_underscore2.default.isArray(value) && _underscore2.default.every(value, validLinkObject)) { return _underscore2.default.map(value, convertLinkToCmsApi); } throwInvalidAttributeValue(value, name, 'An array of Link instances.'); } function validLinkObject(value) { if (value instanceof scrivito.BasicLink) { return true; } // check if value is backend compatible if (!_underscore2.default.isObject(value)) { return false; } var invalidKeys = _underscore2.default.without(_underscore2.default.keys(value), 'fragment', 'obj_id', 'query', 'target', 'title', 'url'); return _underscore2.default.isEmpty(invalidKeys); } function convertLinkToCmsApi(value) { var backendLink = { fragment: value.fragment, query: value.query, target: value.target, title: value.title, url: value.url }; backendLink.obj_id = value.objId || value.obj_id; return _underscore2.default.mapObject(backendLink, function (v) { return v || null; }); } function serializeMultienumAttributeValue(_ref4, value, name) { var validValues = _ref4.validValues; var errorMessage = 'An array with values from ' + (0, _pretty_print2.default)(validValues) + '.'; if (!_underscore2.default.isArray(value) || !_underscore2.default.every(value, _underscore2.default.isString)) { throwInvalidAttributeValue(value, name, errorMessage); } var forbiddenValues = _underscore2.default.difference(value, validValues); if (forbiddenValues.length) { var e = errorMessage + ' Forbidden values: ' + (0, _pretty_print2.default)(forbiddenValues) + '.'; throwInvalidAttributeValue(value, name, e); } return value; } function serializeReferenceAttributeValue(value, name) { if (isValidReference(value)) { return serializeSingleReferenceValue(value); } throwInvalidAttributeValue(value, name, 'A BasicObj or a String ID.'); } function serializeReferencelistAttributeValue(value, name) { if (isValidReferencelistValue(value)) { return _underscore2.default.map(value, serializeSingleReferenceValue); } throwInvalidAttributeValue(value, name, 'An array with BasicObjs or String IDs.'); } function serializeSingleReferenceValue(value) { if (value instanceof scrivito.BasicObj) { return value.id; } return value; } function isValidReference(value) { return _underscore2.default.isString(value) || value instanceof scrivito.BasicObj; } function isValidReferencelistValue(value) { return _underscore2.default.isArray(value) && _underscore2.default.every(value, function (v) { return isValidReference(v); }); } function serializeStringAttributeValue(value, name) { if (isValidString(value)) { return value.toString(); } throwInvalidAttributeValue(value, name, 'A String.'); } function serializeStringlistAttributeValue(value, name) { if (_underscore2.default.isArray(value) && _underscore2.default.every(value, function (v) { return isValidString(v); })) { return _underscore2.default.invoke(value, 'toString'); } throwInvalidAttributeValue(value, name, 'An array of strings.'); } function isValidString(value) { return _underscore2.default.isString(value) || _underscore2.default.isNumber(value); } function serializeWidgetlistAttributeValue(value, name) { if (_underscore2.default.isArray(value) && _underscore2.default.every(value, function (v) { return v instanceof scrivito.BasicWidget; })) { return _underscore2.default.pluck(value, 'id'); } throwInvalidAttributeValue(value, name, 'An array of scrivito.BasicWidget instances.'); } })(); /***/ }), /***/ 125: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.BatchRetrieval = function () { function BatchRetrieval(mget) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, batchSize = _ref.batchSize; _classCallCheck(this, BatchRetrieval); this._mget = mget; this._batchSize = batchSize || 100; this._deferreds = {}; } _createClass(BatchRetrieval, [{ key: 'retrieve', value: function retrieve(id) { var _this = this; if (_underscore2.default.isEmpty(this._deferreds)) { scrivito.nextTick(function () { return _this._performRetrieval(); }); } if (!this._deferreds[id]) { var deferred = new scrivito.Deferred(); this._deferreds[id] = deferred; } return this._deferreds[id].promise; } }, { key: '_performRetrieval', value: function _performRetrieval() { var _this2 = this; var ids = _underscore2.default.keys(this._deferreds).slice(0, this._batchSize); if (ids.length === 0) { return; } var currentRequestDeferreds = {}; _underscore2.default.each(ids, function (id) { currentRequestDeferreds[id] = _this2._deferreds[id]; delete _this2._deferreds[id]; }); this._mget(ids).then(function (results) { _underscore2.default.each(ids, function (id, index) { var deferred = currentRequestDeferreds[id]; var result = results[index]; if (index < results.length) { deferred.resolve(result); } else { _this2.retrieve(id).then(deferred.resolve, deferred.reject); } }); }, function (error) { _underscore2.default.each(currentRequestDeferreds, function (deferred) { return deferred.reject(error); }); }); this._performRetrieval(); } // For test purpose only. }, { key: 'reset', value: function reset() { this._deferreds = {}; } }]); return BatchRetrieval; }(); })(); /***/ }), /***/ 126: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { var bufferedUpdates = []; var isUpdateScheduled = function isUpdateScheduled() { return bufferedUpdates.length; }; function add(callback) { if (!isUpdateScheduled()) { scrivito.nextTick(function () { scrivito.globalState.withBatchedUpdates(function () { return performUpdate(bufferedUpdates); }); }); } bufferedUpdates.push(callback); } function performUpdate(callbacks) { bufferedUpdates = []; try { callbacks.forEach(function (callback) { return callback(); }); } finally { if (isUpdateScheduled()) { performUpdate(bufferedUpdates); } } } scrivito.batchedStateUpdater = { add: add }; })(); /***/ }), /***/ 127: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { scrivito.BinaryUtils = { isBlob: function isBlob(obj) { return !!obj && _underscore2.default.isNumber(obj.size) && _underscore2.default.isString(obj.type); }, isFile: function isFile(obj) { return this.isBlob(obj) && _underscore2.default.isString(obj.name); } }; })(); /***/ }), /***/ 128: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _auth_failure_counter = __webpack_require__(43); var _auth_failure_counter2 = _interopRequireDefault(_auth_failure_counter); var _public_authentication = __webpack_require__(71); var _public_authentication2 = _interopRequireDefault(_public_authentication); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var MIN_REQUEST_TIME = 5; var DEFAULT_REQUEST_TIMEOUT = 15000; var backendEndpoint = void 0; var tenant = void 0; var initDeferred = void 0; var authHeaderValueProvider = void 0; var forceVerification = void 0; scrivito.CmsRestApi = { init: function init(endpoint, initTenant, authorizationProvider) { if (initTenant) { backendEndpoint = endpoint; tenant = initTenant; if (initDeferred) { initDeferred.resolve(); } } authHeaderValueProvider = authorizationProvider || authHeaderValueProvider || _public_authentication2.default; }, // For test purpose only. reset: function reset() { backendEndpoint = undefined; tenant = undefined; initDeferred = undefined; authHeaderValueProvider = undefined; forceVerification = undefined; }, get: function get(path, requestParams) { return fetch('GET', path, requestParams); }, put: function put(path, requestParams) { return fetch('PUT', path, requestParams); }, post: function post(path, requestParams) { return fetch('POST', path, requestParams); }, delete: function _delete(path, requestParams) { return fetch('DELETE', path, requestParams); }, requestBuiltInUserSession: function requestBuiltInUserSession(sessionId) { return ensureInitialized().then(function () { var method = 'PUT'; var path = 'sessions/' + sessionId; var promise = retryRequest(method, function (timeout) { return requestAjaxDeferred(ajax({ method: method, path: path, timeout: timeout })); }); promise.then(_auth_failure_counter2.default.reset); return promise; }); }, // For test purpose only. enableForceVerification: function enableForceVerification() { forceVerification = true; }, // For test purpose only. currentPublicAuthorizationState: function currentPublicAuthorizationState() { if (authHeaderValueProvider) { if (authHeaderValueProvider.currentState) { return '[API] ' + authHeaderValueProvider.currentState(); } return '[API]: authorization provider without currentState()'; } return '[API]: no authorization provider'; }, get endpoint() { return backendEndpoint; }, // For test purpose only. get tenant() { return tenant; } }; var Timer = function () { function Timer() { var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_REQUEST_TIMEOUT; _classCallCheck(this, Timer); this.timesOutAt = Date.now() + timeout; } _createClass(Timer, [{ key: 'timedOut', value: function timedOut() { return this.remainingTime() < MIN_REQUEST_TIME; } }, { key: 'remainingTime', value: function remainingTime() { return Math.max(this.timesOutAt - Date.now(), 0); } }, { key: 'cover', value: function cover(time) { return time <= this.timesOutAt - MIN_REQUEST_TIME; } }]); return Timer; }(); function ensureInitialized() { if (tenant) { return scrivito.Promise.resolve(); } if (!initDeferred) { initDeferred = new scrivito.Deferred(); } return initDeferred.promise; } function fetch(method, path, requestParams) { return ensureInitialized().then(function () { return request(method, path, requestParams).then(function (result) { if (result && result.task && _underscore2.default.size(result) === 1) { return handleTask(result.task); } return result; }); }); } function request(method, path, requestParams) { return retryRequest(method, function (timeout) { return authHeaderValueProvider.perform(function (authorization) { return requestAjaxDeferred(ajax({ method: method, path: path, requestParams: requestParams, timeout: timeout, authorization: authorization })); }); }); } function requestAjaxDeferred(ajaxDeferred) { return scrivito.Promise.resolve(ajaxDeferred).catch(handleAjaxError); } function retryRequest(method, actualRequest) { var timer = new Timer(); return retryOnceOnError(timer, method, function () { return retryOnRateLimit(timer, function () { return actualRequest(timer.remainingTime()); }); }); } function retryOnceOnError(timer, method, requestCallback) { if (method === 'POST') { return requestCallback(); } return requestCallback().catch(function (error) { if (!timer.timedOut()) { if (error instanceof _errors.BackendError) { return requestCallback(); } if (error instanceof _errors.NetworkError) { return requestCallback(); } } throw error; }); } function retryOnRateLimit(timer, requestCallback) { var retry = function retry(retryCount) { return requestCallback().catch(function (e) { if (e instanceof _errors.NetworkError && e.httpCode === 429) { var error = e.response; var timeout = calculateTimeout(error.getResponseHeader('Retry-After'), retryCount); if (timer.cover(Date.now() + timeout)) { return scrivito.Promise.resolve(scrivito.waitMs(timeout)).then(function () { return retry(retryCount + 1); }); } throw new _errors.RateLimitExceededError('rate limit exceeded', 429); } throw e; }); }; return retry(0); } function calculateTimeout(retryAfter, retryCount) { var calculatedTimeout = Math.pow(2, retryCount) * 0.5 * 1000; return Math.max(calculatedTimeout, retryAfter * 1000); } function handleAjaxError(error) { if (error.status === undefined || !_underscore2.default.isNumber(error.status)) { throw error; } var errorBody = void 0; try { errorBody = JSON.parse(error.responseText); } catch (e) { throw new _errors.NetworkError(error); } if (errorBody.code === 'auth_missing' && errorBody.details) { var returnTo = _auth_failure_counter2.default.augmentedRedirectUrl(scrivito.location()); var redirectTo = errorBody.details.visit.replace('retry=RETRY', 'retry=' + _auth_failure_counter2.default.currentFailureCount()).replace(/\$RETURN_TO/, encodeURIComponent(returnTo)); return scrivito.redirect_to(redirectTo); } var specificOutput = errorBody.error; if (error.status === 401) { throw new _errors.UnauthorizedError(specificOutput, error.status, errorBody.code, errorBody.details); } if (error.status === 403) { throw new _errors.AccessDeniedError(specificOutput, error.status, errorBody.code); } if (error.status === 429) { throw new _errors.NetworkError(error); } if (specificOutput) { if (error.status === 500) { throw new _errors.BackendError(specificOutput, error.status); } if (error.status.toString()[0] === '4' && errorBody.error) { throw _errors.ClientError.for(specificOutput, error.status, errorBody.code); } } throw new _errors.NetworkError(error); } function prepareAjaxParams(method, path) { var requestParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var ajaxParams = { path: path, verb: method, params: requestParams }; return ajaxParams; } function ajax(_ref) { var method = _ref.method, path = _ref.path, requestParams = _ref.requestParams, timeout = _ref.timeout, authorization = _ref.authorization; var url = 'https://' + backendEndpoint + '/tenants/' + tenant + '/perform'; var params = prepareAjaxParams(method, path, requestParams); return scrivito.fetch(method, url, { params: params, timeout: timeout, authorization: authorization, forceVerification: forceVerification }); } function handleTask(task) { switch (task.status) { case 'success': return task.result; case 'error': throw _errors.ClientError.for(task.message, 412, task.code); case 'open': return scrivito.wait(2).then(function () { return request('GET', 'tasks/' + task.id).then(function (result) { return handleTask(result); }); }); default: throw new _errors.ScrivitoError('Invalid task response (unknown status)'); } } })(); /***/ }), /***/ 129: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { scrivito.computeCacheKey = function (data) { var normalizedData = normalizeData(data); return JSON.stringify(normalizedData); }; function normalizeData(data) { if (_underscore2.default.isArray(data)) { return _underscore2.default.map(data, normalizeData); } if (_underscore2.default.isObject(data)) { return _underscore2.default.chain(data).mapObject(normalizeData).pairs().sortBy(_underscore2.default.first); } return data; } })(); /***/ }), /***/ 130: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _speakingurl = __webpack_require__(77); var _speakingurl2 = _interopRequireDefault(_speakingurl); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function convertToSlug(input) { return (0, _speakingurl2.default)(input); } scrivito.convertToSlug = convertToSlug; })(); /***/ }), /***/ 131: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { var PUBLISHED_WORKSPACE_ID = 'published'; scrivito.currentWorkspaceId = function () { if (scrivito.uiAdapter) { return scrivito.uiAdapter.currentWorkspaceId(); } return PUBLISHED_WORKSPACE_ID; }; })(); /***/ }), /***/ 132: /***/ (function(module, exports, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.Deferred = function Deferred() { var _this = this; _classCallCheck(this, Deferred); this.promise = new scrivito.Promise(function (resolveFn, rejectFn) { _this.resolve = resolveFn; _this.reject = rejectFn; }); }; })(); /***/ }), /***/ 133: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errorStackParser = __webpack_require__(193); var _errorStackParser2 = _interopRequireDefault(_errorStackParser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } (function () { var consoleErrorIsDisabled = false; function logError() { if (window && window.console && !consoleErrorIsDisabled) { var _window$console; (_window$console = window.console).error.apply(_window$console, arguments); } } function disableConsoleError() { consoleErrorIsDisabled = true; } function printError(error) { if (error instanceof Error) { var stackTrace = _errorStackParser2.default.parse(error); scrivito.logError([error.message].concat(_toConsumableArray(_underscore2.default.pluck(stackTrace, 'source'))).join('\n')); } else { scrivito.logError(error); } } scrivito.logError = logError; scrivito.disableConsoleError = disableConsoleError; scrivito.printError = printError; })(); /***/ }), /***/ 134: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _loadable_data = __webpack_require__(3); var _loadable_data2 = _interopRequireDefault(_loadable_data); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _pretty_print = __webpack_require__(15); var _pretty_print2 = _interopRequireDefault(_pretty_print); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var VALID_OPTIONS = ['limit', 'includeObjs']; var FacetQuery = function () { function FacetQuery(attribute, options, searchQuery) { var _this = this; _classCallCheck(this, FacetQuery); assertValidOptions(options); this._requestParams = buildRequestParams(attribute, options, searchQuery); this._loadableData = new _loadable_data2.default({ state: modelStateFor(this._requestParams), loader: function loader() { return _this._loadData(); }, invalidation: invalidation, throwNotLoaded: true }); } _createClass(FacetQuery, [{ key: 'result', value: function result() { var firstFacetResult = _underscore2.default.first(this._loadableData.get().facets); return _underscore2.default.map(firstFacetResult, function (rawFacetValue) { var name = rawFacetValue.value; var count = rawFacetValue.total; var includedObjs = _underscore2.default.pluck(rawFacetValue.results, 'id'); return new scrivito.BasicObjFacetValue(name, count, includedObjs); }); } }, { key: '_loadData', value: function _loadData() { var workspaceId = scrivito.currentWorkspaceId(); return scrivito.CmsRestApi.get('workspaces/' + workspaceId + '/objs/search', this._requestParams); } }], [{ key: 'store', value: function store(attribute, options, searchQuery, cmsRestApiResponse) { assertValidOptions(options); var requestParams = buildRequestParams(attribute, options, searchQuery); var loadableData = new _loadable_data2.default({ state: modelStateFor(requestParams), invalidation: invalidation, throwNotLoaded: true }); loadableData.set(cmsRestApiResponse); } }]); return FacetQuery; }(); function invalidation() { return scrivito.ObjReplication.getWorkspaceVersion(); } function modelStateFor(requestParams) { var subStateKey = scrivito.computeCacheKey(requestParams); return scrivito.cmsState.subState('facetQuery').subState(subStateKey); } function assertValidOptions(options) { var invalidOptions = _underscore2.default.without.apply(_underscore2.default, [_underscore2.default.keys(options)].concat(VALID_OPTIONS)); if (invalidOptions.length) { throw new _errors.ArgumentError('Invalid options: ' + ((0, _pretty_print2.default)(invalidOptions) + '. Valid options: ' + VALID_OPTIONS)); } } function buildRequestParams(attribute, options, searchQuery) { var requestParams = { facets: [{ attribute: attribute, limit: options.limit || 10, include_objs: options.includeObjs || 0 }], size: 0 }; if (searchQuery && searchQuery.length) { requestParams.query = searchQuery; } return requestParams; } scrivito.FacetQuery = FacetQuery; })(); /***/ }), /***/ 135: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { var isDisabled = false; var connectionCounter = 0; // For test purpose only scrivito.isFetchingActive = function () { return connectionCounter > 0; }; // For test purpose only scrivito.disableFetching = function () { isDisabled = true; }; scrivito.fetch = function (method, url, _ref) { var params = _ref.params, timeout = _ref.timeout, authorization = _ref.authorization, forceVerification = _ref.forceVerification; if (isDisabled) { return new scrivito.Deferred().promise; } connectionCounter += 1; return new scrivito.Promise(function (resolve, reject) { var request = createRequestObj(method, url, timeout, resolve, reject); if (authorization) { request.setRequestHeader('Authorization', authorization); } if (forceVerification) { request.setRequestHeader('Scrivito-Force-Verification', 'true'); } request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); request.send(JSON.stringify(params)); }); }; function createRequestObj(method, url, timeout, resolve, reject) { var request = new XMLHttpRequest(); request.open(method === 'POST' ? 'POST' : 'PUT', url); request.timeout = timeout; request.withCredentials = true; request.onload = function () { return onAjaxLoad(request, resolve, reject); }; request.onerror = function (error) { return onAjaxError(error, reject); }; return request; } function onAjaxLoad(request, resolve, reject) { connectionCounter -= 1; if (request.status >= 200 && request.status < 300) { try { return resolve(JSON.parse(request.responseText)); } catch (error) { if (error instanceof SyntaxError) { return resolve(request.responseText); } throw error; } } return reject(request); } function onAjaxError(error, reject) { connectionCounter -= 1; reject(new Error('Network Error: ' + error)); } })(); /***/ }), /***/ 136: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function findWidgetPlacement(objData, widgetId) { var placement = findWidgetPlacementIn(objData, widgetId); if (placement) { return placement; } var widgetPool = objData._widget_pool; _underscore2.default.find(widgetPool, function (parentWidgetData, parentWidgetId) { placement = findWidgetPlacementIn(parentWidgetData, widgetId); if (placement) { placement.parentWidgetId = parentWidgetId; return true; } }); return placement; } function findWidgetPlacementIn(objOrWidgetData, widgetId) { var placement = void 0; _underscore2.default.find(objOrWidgetData, function (attributeDict, attributeName) { if (scrivito.Attribute.isSystemAttribute(attributeName)) { return; } var _attributeDict = _slicedToArray(attributeDict, 2), attributeType = _attributeDict[0], attributeValue = _attributeDict[1]; if (attributeValue && attributeType === 'widgetlist') { var index = attributeValue.indexOf(widgetId); if (index !== -1) { placement = { attributeName: attributeName, index: index }; return true; } } }); return placement; } scrivito.findWidgetPlacement = findWidgetPlacement; })(); /***/ }), /***/ 137: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { // if the UI is present, these modules are "connected" to the UI, // i.e. the local client module is replaced with // the matching module from the client inside the UI. var modulesToConnect = ['BinaryRequest', 'CmsRestApi', 'ObjReplication']; function connectModulesToUi(ui) { var uiModules = ui.clientModulesForExport(); modulesToConnect.forEach(function (moduleName) { scrivito[moduleName] = uiModules[moduleName]; }); } function modulesForExport() { var modules = {}; modulesToConnect.forEach(function (moduleName) { modules[moduleName] = scrivito[moduleName]; }); return modules; } var appStateCounter = 0; function createAppState() { var id = (appStateCounter++).toString(); return scrivito.globalState.subState('apps').subState(id); } function setupState(ui) { if (ui) { scrivito.globalState = ui.globalState(); scrivito.appState = ui.createAppState(); } else { scrivito.globalState = new scrivito.StateTree(); scrivito.appState = createAppState(); } // the state of the CMS content, shared between UI and Apps scrivito.cmsState = scrivito.globalState.subState('cms'); } function init() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, ui = _ref.ui, realmContext = _ref.realmContext; if (realmContext) { scrivito.Realm.init(realmContext); } if (ui) { connectModulesToUi(ui); } setupState(ui); } // export scrivito.client.init = init; scrivito.client.createAppState = createAppState; scrivito.client.modulesForExport = modulesForExport; })(); /***/ }), /***/ 138: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } (function () { _underscore2.default.extend(scrivito, { iterable: { collectValuesFromIterator: function collectValuesFromIterator(iterator) { var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var _iterator$next = iterator.next(), value = _iterator$next.value, done = _iterator$next.done; if (done) { return result; } return this.collectValuesFromIterator(iterator, [].concat(_toConsumableArray(result), [value])); }, firstValueFromIterator: function firstValueFromIterator(iterator) { var _iterator$next2 = iterator.next(), value = _iterator$next2.value; return value || null; } } }); })(); /***/ }), /***/ 139: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _loadable_data = __webpack_require__(3); var _loadable_data2 = _interopRequireDefault(_loadable_data); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function loadAllUntil(iterator, size) { var objs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var run = _loadable_data2.default.run(function () { return iterator.next(); }); if (!run.success) { return { done: false, objs: objs }; } var _run$result = run.result, obj = _run$result.value, done = _run$result.done; if (done || size === 0) { return { done: done, objs: objs }; } return loadAllUntil(iterator, size - 1, objs.concat([obj])); } scrivito.loadAllUntil = loadAllUntil; })(); /***/ }), /***/ 14: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _pretty_print = __webpack_require__(15); var _pretty_print2 = _interopRequireDefault(_pretty_print); var _attribute_content_class = __webpack_require__(45); var _attribute_content_class2 = _interopRequireDefault(_attribute_content_class); var _valid_rails_page_classes = __webpack_require__(94); var _use_rails_engine = __webpack_require__(27); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ALLOWED_CREATE_OBJ_ATTRIBUTES = ['_path', 'blob']; var ObjClass = function (_AttributeContentClas) { _inherits(ObjClass, _AttributeContentClas); function ObjClass() { _classCallCheck(this, ObjClass); return _possibleConstructorReturn(this, (ObjClass.__proto__ || Object.getPrototypeOf(ObjClass)).apply(this, arguments)); } _createClass(ObjClass, [{ key: 'createObjWithDefaults', value: function createObjWithDefaults(attributes) { var unexpectedAttrs = _underscore2.default.without.apply(_underscore2.default, [_underscore2.default.keys(attributes)].concat(ALLOWED_CREATE_OBJ_ATTRIBUTES)); attributes._obj_class = this.name; if (!_underscore2.default.isEmpty(unexpectedAttrs)) { throw new _errors.InternalError('Unexpected attributes ' + (0, _pretty_print2.default)(unexpectedAttrs) + '.' + (' Available attributes: ' + (0, _pretty_print2.default)(ALLOWED_CREATE_OBJ_ATTRIBUTES))); } if (this._classData.usesServerCallbacks) { return scrivito.withServerDefaults.createObjFromLegacyAttributes(attributes); } var obj = scrivito.BasicObj.create(buildPublicAttributesFrom(attributes)); return obj.finishSaving().then(function () { return obj; }); } }, { key: 'isBinary', value: function isBinary() { var blob = this.attribute('blob'); return !!(blob && blob.type === 'binary'); } }, { key: 'hasChildOrder', value: function hasChildOrder() { var childOrder = this.attribute('childOrder'); return !!(childOrder && childOrder.type === 'referencelist'); } }], [{ key: 'type', value: function type() { return 'Obj'; } }, { key: 'validPageClasses', value: function validPageClasses(path) { if ((0, _use_rails_engine.useRailsEngine)()) { var objClassNames = (0, _valid_rails_page_classes.validRailsPageClasses)(path); return objClassNames.reduce(function (arr, objClassName) { var objClass = ObjClass.find(objClassName); if (objClass) { arr.push(objClass); } return arr; }, []); } return ObjClass.all().filter(function (objClass) { return !objClass.isHiddenFromEditors() && !objClass.isBinary(); }); } }]); return ObjClass; }(_attribute_content_class2.default); function buildPublicAttributesFrom(_ref) { var _objClass = _ref._obj_class, _path = _ref._path, blob = _ref.blob; var publicAttrs = { _objClass: [_objClass] }; if (_path) { publicAttrs._path = [_path]; } if (blob) { publicAttrs.blob = [blob, 'binary']; } return publicAttrs; } exports.default = ObjClass; /***/ }), /***/ 140: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _loadable_data = __webpack_require__(3); var _loadable_data2 = _interopRequireDefault(_loadable_data); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function loadableWithDefault(theDefault, loadableFunction) { var run = _loadable_data2.default.run(loadableFunction); return run.success ? run.result : theDefault; } // export scrivito.loadableWithDefault = loadableWithDefault; // legacy, keeping this for now to avoid conflicts. scrivito.loadWithDefault = loadableWithDefault; })(); /***/ }), /***/ 141: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _loadable_data = __webpack_require__(3); var _loadable_data2 = _interopRequireDefault(_loadable_data); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function mapAndLoadParallel(list, iteratee) { var results = []; _underscore2.default.each(list, function (item) { var run = _loadable_data2.default.run(function () { return iteratee(item); }); if (run.success) { results.push(run.result); } }); if (results.length < list.length) { _loadable_data2.default.throwNotLoaded(); } return results; } scrivito.mapAndLoadParallel = mapAndLoadParallel; })(); /***/ }), /***/ 142: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _errors = __webpack_require__(1); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { /** * A `NotLoadedError` is thrown when data is accessed in a synchronous fashion but is not yet * available locally. For example {@link scrivito.BasicObj.get} throws a `NotLoadedError` * whenever a CMS object is accessed that is not yet cached in the browser. */ var NotLoadedError = function (_ScrivitoError) { _inherits(NotLoadedError, _ScrivitoError); function NotLoadedError(captureStackTrace) { _classCallCheck(this, NotLoadedError); return _possibleConstructorReturn(this, (NotLoadedError.__proto__ || Object.getPrototypeOf(NotLoadedError)).call(this, 'Data is not yet loaded.', captureStackTrace)); } // this getter has an extravagant name, in order to avoid name clashes _createClass(NotLoadedError, [{ key: 'scrivitoPrivateIsNotLoadedError', get: function get() { return true; } }]); return NotLoadedError; }(_errors.ScrivitoError); function isNotLoadedError(error) { // using duck-typing instead of "instanceof", so that these errors // can be recognized across javascript (iframe) boundaries. return error && error.scrivitoPrivateIsNotLoadedError; } // export scrivito.NotLoadedError = NotLoadedError; scrivito.isNotLoadedError = isNotLoadedError; })(); /***/ }), /***/ 143: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { function AppClassFactory(definition, parent) { var schema = new scrivito.Schema(definition, parent); return function (_parent) { _inherits(_class, _parent); function _class() { _classCallCheck(this, _class); return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments)); } _createClass(_class, null, [{ key: "_scrivitoPrivateSchema", get: function get() { return schema; } }]); return _class; }(parent); } scrivito.AppClassFactory = AppClassFactory; })(); /***/ }), /***/ 144: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _obj_class = __webpack_require__(14); var _obj_class2 = _interopRequireDefault(_obj_class); var _widget_class = __webpack_require__(17); var _widget_class2 = _interopRequireDefault(_widget_class); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.Attribute = function () { _createClass(Attribute, null, [{ key: 'isSystemAttribute', value: function isSystemAttribute(name) { return name[0] === '_'; } }]); function Attribute(attributeData) { _classCallCheck(this, Attribute); this.name = attributeData.name; this.type = attributeData.type; this._validValues = attributeData.validValues; this._attributeData = attributeData; } // public _createClass(Attribute, [{ key: 'title', value: function title() { return this._attributeData.title; } }, { key: 'description', value: function description() { return this._attributeData.description; } }, { key: 'typeInfo', value: function typeInfo() { if (this.type === 'enum' || this.type === 'multienum') { return [this.type, { validValues: this._validValues }]; } return [this.type, {}]; } }, { key: 'validValues', value: function validValues() { this._assertValidTypes(['enum', 'multienum'], 'Only enum and multienum attributes can have valid values'); return this._validValues || []; } }, { key: 'validClasses', value: function validClasses() { this._assertValidTypes(['reference', 'referencelist'], 'Only reference and referencelist attributes can have valid classes'); var objClassNames = this._attributeData.validClasses; if (objClassNames) { return _underscore2.default.map(objClassNames, function (name) { return _obj_class2.default.find(name); }); } } }, { key: 'only', value: function only() { this._assertValidTypes(['widgetlist'], 'Only widgetlist attributes have only()'); var widgetClassName = this._attributeData.only; if (widgetClassName) { var widgetClass = _widget_class2.default.find(widgetClassName); return widgetClass ? [widgetClass] : []; } } // private }, { key: '_assertValidTypes', value: function _assertValidTypes(validTypes, errorMessage) { if (!_underscore2.default.include(validTypes, this.type)) { $.error(errorMessage); } } }]); return Attribute; }(); })(); /***/ }), /***/ 145: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { function AttributeContentFactory(appModelAccessor) { var AttributeContent = function () { function AttributeContent() { _classCallCheck(this, AttributeContent); } _createClass(AttributeContent, [{ key: 'finishSaving', /** * Resolves when all previous updates have been persisted. * If an update fails the promise is rejected. * * @returns {Promise} */ value: function finishSaving() { return this._scrivitoPrivateContent.finishSaving(); } // public API }, { key: 'get', value: function get(attributeName) { return appModelAccessor.read(this, attributeName); } // public API }, { key: 'update', value: function update(attributes) { appModelAccessor.update(this, attributes); } }, { key: 'id', // public API get: function get() { return this._scrivitoPrivateContent.id; } // public API }, { key: 'objClass', get: function get() { return this._scrivitoPrivateContent.objClass; } }]); return AttributeContent; }(); return AttributeContent; } function prepareAttributes(attributes, schema, appClassName) { return _underscore2.default.mapObject(attributes, function (value, name) { if (scrivito.Attribute.isSystemAttribute(name)) { return [value]; } var typeInfo = schema.attributes[name]; if (!typeInfo) { throw new _errors.ArgumentError('Attribute "' + name + '" is not defined for CMS object ' + ('class "' + appClassName + '".')); } var unwrappedValue = scrivito.unwrapAppClassValues(value); return [unwrappedValue, typeInfo]; }); } scrivito.AttributeContentFactory = AttributeContentFactory; scrivito.AttributeContentFactory.prepareAttributes = prepareAttributes; })(); /***/ }), /***/ 146: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _binary = __webpack_require__(12); var _binary2 = _interopRequireDefault(_binary); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { scrivito.AttributeDeserializer = { deserialize: function deserialize(model, rawValue, type, options) { var _rawValue = _slicedToArray(rawValue, 2), typeFromBackend = _rawValue[0], valueFromBackend = _rawValue[1]; switch (type) { case 'binary': return deserializeBinaryValue(typeFromBackend, valueFromBackend); case 'date': return deserializeDateValue(typeFromBackend, valueFromBackend); case 'float': return deserializeFloatValue(typeFromBackend, valueFromBackend); case 'enum': return deserializeEnumValue(typeFromBackend, valueFromBackend, options); case 'html': return deserializeHtmlValue(typeFromBackend, valueFromBackend); case 'integer': return deserializeIntegerValue(typeFromBackend, valueFromBackend); case 'link': return deserializeLinkValue(typeFromBackend, valueFromBackend); case 'linklist': return deserializeLinklistValue(typeFromBackend, valueFromBackend); case 'multienum': return deserializeMultienumValue(typeFromBackend, valueFromBackend, options); case 'reference': return deserializeReferenceValue(typeFromBackend, valueFromBackend); case 'referencelist': return deserializeReferencelistValue(typeFromBackend, valueFromBackend); case 'string': return deserializeStringValue(typeFromBackend, valueFromBackend); case 'stringlist': return deserializeStringlistValue(typeFromBackend, valueFromBackend); case 'widgetlist': return deserializeWidgetlistValue(typeFromBackend, valueFromBackend, model); } } }; function deserializeBinaryValue(typeFromBackend, valueFromBackend) { if (typeFromBackend === 'binary' && valueFromBackend) { var binaryId = valueFromBackend.id; var isPublic = scrivito.currentWorkspaceId() === 'published'; return new _binary2.default(binaryId, isPublic).transform({}); } return null; } function deserializeDateValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'date') { return null; } return scrivito.types.deserializeAsDate(valueFromBackend); } function deserializeHtmlValue(typeFromBackend, valueFromBackend) { if (_underscore2.default.contains(['html', 'string'], typeFromBackend) && _underscore2.default.isString(valueFromBackend)) { return valueFromBackend; } return ''; } function deserializeEnumValue(typeFromBackend, valueFromBackend, _ref) { var validValues = _ref.validValues; if (typeFromBackend === 'string' && _underscore2.default.contains(validValues, valueFromBackend)) { return valueFromBackend; } return null; } function deserializeMultienumValue(typeFromBackend, valueFromBackend, _ref2) { var validValues = _ref2.validValues; if (typeFromBackend !== 'stringlist' || !Array.isArray(valueFromBackend)) { return []; } return _underscore2.default.intersection(valueFromBackend, validValues); } function deserializeFloatValue(typeFromBackend, valueFromBackend) { switch (typeFromBackend) { case 'string': if (valueFromBackend.match(/^-?\d+(\.\d+)?$/)) { return convertToFloat(valueFromBackend); } return null; case 'number': return convertToFloat(valueFromBackend); default: return null; } } function convertToFloat(valueFromBackend) { var floatValue = parseFloat(valueFromBackend); if (scrivito.types.isValidFloat(floatValue)) { return floatValue; } return null; } function deserializeIntegerValue(typeFromBackend, valueFromBackend) { switch (typeFromBackend) { case 'string': case 'number': return scrivito.types.deserializeAsInteger(valueFromBackend); default: return null; } } function deserializeLinkValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'link' || !_underscore2.default.isObject(valueFromBackend)) { return null; } return convertToLink(valueFromBackend); } function deserializeLinklistValue(_typeFromBackend, valueFromBackend) { if (!_underscore2.default.isArray(valueFromBackend)) { return []; } return _underscore2.default.map(valueFromBackend, convertToLink); } function convertToLink(valueFromBackend) { var linkParams = _underscore2.default.pick(valueFromBackend, 'title', 'query', 'fragment', 'target', 'url'); linkParams.objId = valueFromBackend.obj_id; return scrivito.BasicLink.build(linkParams); } function convertReferenceToBasicObj(valueFromBackend) { try { return scrivito.BasicObj.get(valueFromBackend); } catch (e) { if (e instanceof _errors.ResourceNotFoundError) { return null; } throw e; } } function deserializeReferenceValue(typeFromBackend, valueFromBackend) { if (typeFromBackend === 'reference' && valueFromBackend) { return convertReferenceToBasicObj(valueFromBackend); } return null; } function deserializeReferencelistValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'referencelist') { return []; } if (!valueFromBackend) { return []; } var objs = scrivito.mapAndLoadParallel(valueFromBackend, convertReferenceToBasicObj); return _underscore2.default.compact(objs); } function deserializeStringValue(typeFromBackend, valueFromBackend) { if (_underscore2.default.contains(['html', 'string'], typeFromBackend) && _underscore2.default.isString(valueFromBackend)) { return valueFromBackend; } return ''; } function deserializeStringlistValue(typeFromBackend, valueFromBackend) { if (typeFromBackend !== 'stringlist' || !Array.isArray(valueFromBackend)) { return []; } return valueFromBackend; } function deserializeWidgetlistValue(typeFromBackend, valueFromBackend, model) { if (typeFromBackend !== 'widgetlist') { return []; } return _underscore2.default.map(valueFromBackend, function (widgetId) { return model.widget(widgetId); }); } })(); /***/ }), /***/ 147: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _attribute_inflection = __webpack_require__(7); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.BasicAttributeContent = function () { function BasicAttributeContent() { _classCallCheck(this, BasicAttributeContent); } _createClass(BasicAttributeContent, [{ key: 'get', value: function get(attributeName, typeInfo) { if (!(0, _attribute_inflection.isCamelCase)(attributeName)) { throw new _errors.ArgumentError('Attribute names have to be in camel case.'); } var internalAttributeName = (0, _attribute_inflection.underscore)(attributeName); if (scrivito.Attribute.isSystemAttribute(internalAttributeName)) { if (_underscore2.default.has(this._systemAttributes, internalAttributeName)) { return this[this._systemAttributes[internalAttributeName]]; } return; } var _scrivito$typeInfo$no = scrivito.typeInfo.normalize(typeInfo), _scrivito$typeInfo$no2 = _slicedToArray(_scrivito$typeInfo$no, 2), type = _scrivito$typeInfo$no2[0], options = _scrivito$typeInfo$no2[1]; var rawValue = this._current[internalAttributeName]; if (!rawValue || !_underscore2.default.isArray(rawValue)) { rawValue = []; } return scrivito.AttributeDeserializer.deserialize(this, rawValue, type, options); } }, { key: 'field', value: function field(attributeName, typeInfo) { return new scrivito.BasicField({ container: this, attributeName: attributeName, typeInfo: scrivito.typeInfo.normalize(typeInfo) }); } }, { key: 'widget', value: function widget(_id) { throw new TypeError('Override in subclass.'); } }, { key: 'serializeAttributes', value: function serializeAttributes() { var _this = this; var serializedAttrs = {}; _underscore2.default.each(this._current, function (value, name) { if (_underscore2.default.isArray(value) && _underscore2.default.first(value) === 'widgetlist') { var publicAttrName = (0, _attribute_inflection.camelCase)(name); var serializedAttributes = _underscore2.default.invoke(_this.get(publicAttrName, ['widgetlist']), 'serializeAttributes'); serializedAttrs[name] = ['widgetlist', serializedAttributes]; return; } serializedAttrs[name] = value; }); return serializedAttrs; } }, { key: '_persistWidgets', value: function _persistWidgets(obj, attributes) { _underscore2.default.each(attributes, function (_ref) { var _ref2 = _slicedToArray(_ref, 2), widgets = _ref2[0], typeInfo = _ref2[1]; if (typeInfo && typeInfo[0] === 'widgetlist') { _underscore2.default.each(widgets, function (widget) { if (!widget.isPersisted()) { widget.persistInObj(obj); } }); } }); } }, { key: '_objClass', get: function get() { throw new TypeError('Override in subclass.'); } }, { key: '_current', get: function get() { throw new TypeError('Override in subclass.'); } }]); return BasicAttributeContent; }(); })(); /***/ }), /***/ 148: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var BasicField = function () { function BasicField(_ref) { var container = _ref.container, attributeName = _ref.attributeName, typeInfo = _ref.typeInfo; _classCallCheck(this, BasicField); this._container = container; this._attributeName = attributeName; this._typeInfo = typeInfo; } _createClass(BasicField, [{ key: 'get', value: function get() { return this._container.get(this.name(), this._typeInfo); } }, { key: 'update', value: function update(newValue) { this._container.update(_defineProperty({}, this.name(), [newValue, this._typeInfo])); } }, { key: 'container', value: function container() { return this._container; } }, { key: 'name', value: function name() { return this._attributeName; } }, { key: 'type', value: function type() { return this._typeInfo[0]; } }, { key: 'typeOptions', value: function typeOptions() { return this._typeInfo[1] || {}; } }, { key: 'equals', value: function equals(other) { if (!(other instanceof scrivito.BasicField)) { return false; } return this.container().equals(other.container()) && this.name() === other.name(); } }, { key: 'validValues', value: function validValues() { this._assertValidTypes(['enum', 'multienum'], 'Only enum and multienum attributes can have valid values'); return this.typeOptions().validValues || []; } }, { key: 'toString', value: function toString() { var _dataForId2 = this._dataForId(), name = _dataForId2.name, objId = _dataForId2.objId, widgetId = _dataForId2.widgetId; var stringRepresentation = ''; } else { stringRepresentation += '>'; } return stringRepresentation; } }, { key: 'id', value: function id() { var _dataForId3 = this._dataForId(), name = _dataForId3.name, objId = _dataForId3.objId, widgetId = _dataForId3.widgetId; var id = name + '|' + objId; if (widgetId) { id += '|' + widgetId; } return id; } }, { key: '_assertValidTypes', value: function _assertValidTypes(validTypes, errorMessage) { if (!(0, _underscore.include)(validTypes, this.type())) { $.error(errorMessage); } } }, { key: '_dataForId', value: function _dataForId() { var jsonHash = { name: this.name() }; var container = this.container(); if (container instanceof scrivito.BasicObj) { jsonHash.objId = container.id; } else { jsonHash.objId = container.obj.id; jsonHash.widgetId = container.id; } return jsonHash; } }]); return BasicField; }(); scrivito.BasicField = BasicField; })(); /***/ }), /***/ 149: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _pretty_print = __webpack_require__(15); var _pretty_print2 = _interopRequireDefault(_pretty_print); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var allowedAttributes = ['fragment', 'obj', 'query', 'target', 'title', 'url']; scrivito.BasicLink = function () { _createClass(BasicLink, null, [{ key: 'build', value: function build(attributes) { var objId = attributes.objId; delete attributes.objId; var link = new this(attributes); if (objId) { link._objId = objId; } return link; } }]); function BasicLink(attributes) { _classCallCheck(this, BasicLink); assertValidPublicAttributes(attributes); this._fragment = attributes.fragment || null; this._query = attributes.query || null; this._target = attributes.target || null; this._title = attributes.title || null; this._url = attributes.url || null; this._objId = null; if (attributes.obj) { this._objId = attributes.obj.id; } } // public API _createClass(BasicLink, [{ key: 'fetchObj', value: function fetchObj() { if (this.isExternal()) { return scrivito.PublicPromise.reject(new _errors.ScrivitoError('The link is external and does not reference an object.')); } return scrivito.BasicObj.fetch(this.objId); } // public API }, { key: 'isExternal', value: function isExternal() { return !!this.url; } // public API }, { key: 'isInternal', value: function isInternal() { return !this.isExternal(); } // public API }, { key: 'copy', value: function copy(attributes) { assertValidPublicAttributes(attributes); var newAttributes = this.buildAttributes(); if (_underscore2.default.has(attributes, 'obj')) { delete newAttributes.objId; } _underscore2.default.extend(newAttributes, attributes); return this.constructor.build(newAttributes); } }, { key: 'buildAttributes', value: function buildAttributes() { return _underscore2.default.pick(this, 'title', 'query', 'fragment', 'target', 'url', 'objId'); } }, { key: 'title', get: function get() { return this._title; } // public API }, { key: 'query', get: function get() { return this._query; } // public API }, { key: 'fragment', get: function get() { return this._fragment; } // public API }, { key: 'target', get: function get() { return this._target; } // public API }, { key: 'url', get: function get() { return this._url; } }, { key: 'objId', get: function get() { return this._objId; } // public API }, { key: 'obj', get: function get() { if (this.objId) { return scrivito.BasicObj.get(this.objId); } return null; } }]); return BasicLink; }(); function assertValidPublicAttributes(attributes) { var unknownAttrs = _underscore2.default.without.apply(_underscore2.default, [_underscore2.default.keys(attributes)].concat(allowedAttributes)); if (!_underscore2.default.isEmpty(unknownAttrs)) { throw new _errors.ArgumentError('Unexpected attributes ' + (0, _pretty_print2.default)(unknownAttrs) + '.' + (' Available attributes: ' + (0, _pretty_print2.default)(allowedAttributes))); } } })(); /***/ }), /***/ 15: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = prettyPrint; function prettyPrint(object) { return JSON.stringify(object); } /***/ }), /***/ 150: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); var _future_binary = __webpack_require__(21); var _future_binary2 = _interopRequireDefault(_future_binary); var _random = __webpack_require__(33); var _obj_class = __webpack_require__(14); var _obj_class2 = _interopRequireDefault(_obj_class); var _attribute_inflection = __webpack_require__(7); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { var SYSTEM_ATTRIBUTES = { _id: 'id', _obj_class: 'objClass', _path: 'path', _permalink: 'permalink', _last_changed: 'lastChanged' }; scrivito.BasicObj = function (_scrivito$BasicAttrib) { _inherits(BasicObj, _scrivito$BasicAttrib); _createClass(BasicObj, null, [{ key: 'fetch', value: function fetch(_id) { scrivito.asyncMethodStub(); } }, { key: 'fetchIncludingDeleted', value: function fetchIncludingDeleted(_id) { scrivito.asyncMethodStub(); } }, { key: 'get', value: function get(idOrList) { var _this2 = this; if (_underscore2.default.isArray(idOrList)) { return scrivito.mapAndLoadParallel(idOrList, function (id) { return _this2.get(id); }); } var obj = this.getIncludingDeleted(idOrList); if (obj.isDeleted()) { throwObjNotFound(idOrList); } return obj; } }, { key: 'getIncludingDeleted', value: function getIncludingDeleted(idOrList) { var _this3 = this; if (_underscore2.default.isArray(idOrList)) { return scrivito.mapAndLoadParallel(idOrList, function (id) { return _this3.getIncludingDeleted(id); }); } var objData = scrivito.ObjDataStore.get(idOrList); var obj = new scrivito.BasicObj(objData); if (obj.isFinallyDeleted()) { throwObjNotFound(idOrList); } return obj; } }, { key: 'create', value: function create(attributes) { var normalizedAttributes = scrivito.typeInfo.normalizeAttrs(attributes); assertObjClassExists(normalizedAttributes._objClass); if (!normalizedAttributes._id) { normalizedAttributes._id = [this.generateId()]; } var serializedAttributes = { _id: normalizedAttributes._id, _obj_class: normalizedAttributes._objClass }; return this.createWithSerializedAttributes(scrivito.typeInfo.unwrapAttributes(serializedAttributes), _underscore2.default.omit(attributes, '_objClass', '_id')); } }, { key: 'addChildWithSerializedAttributes', value: function addChildWithSerializedAttributes(parentPath, serializedAttributes) { var objId = scrivito.BasicObj.generateId(); return this.createWithSerializedAttributes(_underscore2.default.extend({}, serializedAttributes, { _id: objId, _path: parentPath + '/' + objId })); } }, { key: 'createWithSerializedAttributes', value: function createWithSerializedAttributes(serializedAttributes, attributeDict) { if (!attributeDict) { return this.createWithSerializedAttributes.apply(this, _toConsumableArray(extractAttributeDict(serializedAttributes))); } var objData = scrivito.ObjDataStore.createObjData(serializedAttributes._id); objData.update(serializedAttributes); var obj = new scrivito.BasicObj(objData); obj.update(attributeDict); return obj; } }, { key: 'generateId', value: function generateId() { return (0, _random.randomId)(); } }, { key: 'all', value: function all() { return new scrivito.BasicObjSearchIterable().batchSize(1000); } }, { key: 'root', value: function root() { return scrivito.BasicObj.getByPath('/'); } }, { key: 'where', value: function where(attribute, operator, value) { var boost = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; return new scrivito.BasicObjSearchIterable().and(attribute, operator, value, boost); } }, { key: 'getByPath', value: function getByPath(path) { var iterator = this.where('_path', 'equals', path).iterator(); var obj = scrivito.iterable.firstValueFromIterator(iterator); if (obj) { return obj; } throw new _errors.ResourceNotFoundError('Obj with path "' + path + '" not found.'); } }, { key: 'getByPermalink', value: function getByPermalink(permalink) { var iterator = this.where('_permalink', 'equals', permalink).iterator(); var obj = scrivito.iterable.firstValueFromIterator(iterator); if (obj) { return obj; } throw new _errors.ResourceNotFoundError('Obj with permalink "' + permalink + '" not found.'); } }]); function BasicObj(objData) { _classCallCheck(this, BasicObj); var _this = _possibleConstructorReturn(this, (BasicObj.__proto__ || Object.getPrototypeOf(BasicObj)).call(this)); _this.objData = objData; return _this; } _createClass(BasicObj, [{ key: 'getParent', value: function getParent() { if (!this._hasParentPath()) { return null; } try { return scrivito.BasicObj.getByPath(this.parentPath); } catch (error) { if (error instanceof _errors.ResourceNotFoundError) { return null; } throw error; } } }, { key: 'hasConflicts', value: function hasConflicts() { return !!this._current._conflicts; } }, { key: 'isModified', value: function isModified() { return !!this.modification; } }, { key: 'isNew', value: function isNew() { return this.modification === 'new'; } }, { key: 'isEdited', value: function isEdited() { return this.modification === 'edited'; } }, { key: 'isDeleted', value: function isDeleted() { return this.modification === 'deleted'; } }, { key: 'isFinallyDeleted', value: function isFinallyDeleted() { return !!this._current._deleted; } }, { key: 'isBinary', value: function isBinary() { if (!this._objClass) { return false; } var blobAttribute = this._objClass.attribute('blob'); if (blobAttribute) { return blobAttribute.type === 'binary'; } return false; } }, { key: 'fetchParent', value: function fetchParent() { scrivito.asyncMethodStub(); } }, { key: 'hasChildren', value: function hasChildren() { return !!this.children.length; } }, { key: 'orderedChildren', value: function orderedChildren() { var children = this.children; var childOrder = this.get('childOrder', 'referencelist'); if (_underscore2.default.isArray(childOrder)) { return _underscore2.default.sortBy(children, function (child) { var childOrderIds = _underscore2.default.pluck(childOrder, 'id'); var childIndex = childOrderIds.indexOf(child.id); if (childIndex === -1) { return childOrder.length; } return childIndex; }); } return children; } }, { key: 'update', value: function update(attributes) { var _this4 = this; var normalizedAttributes = scrivito.typeInfo.normalizeAttrs(attributes); scrivito.globalState.withBatchedUpdates(function () { _this4._persistWidgets(_this4, normalizedAttributes); var patch = scrivito.AttributeSerializer.serialize(normalizedAttributes); _this4.objData.update(patch); }); this._linkResolution.start(); } }, { key: 'destroy', value: function destroy() { this.update({ _modification: ['deleted'] }); } }, { key: 'insertWidget', value: function insertWidget(widget, _ref) { var before = _ref.before, after = _ref.after; var id = (before || after).id; var _widgetPlacementFor2 = this._widgetPlacementFor(id), attributeValue = _widgetPlacementFor2.attributeValue, attributeName = _widgetPlacementFor2.attributeName, container = _widgetPlacementFor2.container, index = _widgetPlacementFor2.index; var newIndex = before ? index : index + 1; var newAttributeValue = [].concat(_toConsumableArray(attributeValue.slice(0, newIndex)), [widget], _toConsumableArray(attributeValue.slice(newIndex))); container.update(_defineProperty({}, attributeName, [newAttributeValue, 'widgetlist'])); } }, { key: 'removeWidget', value: function removeWidget(widget) { var field = this.fieldContainingWidget(widget); field.update(_underscore2.default.reject(field.get(), function (curWidget) { return curWidget.equals(widget); })); } }, { key: 'copyAsync', value: function copyAsync() { var copyOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; assertValidCopyOptions(copyOptions); return this._copyAttributes().then(function (copiedAttributes) { var serializedAttributes = _underscore2.default.extend(copiedAttributes, copyOptions); var obj = scrivito.BasicObj.createWithSerializedAttributes(serializedAttributes); return obj.finishSaving().then(function () { return obj; }); }); } }, { key: 'moveToAsync', value: function moveToAsync(parentPath) { this.update({ _path: [parentPath + '/' + this.id] }); return this.finishSaving(); } }, { key: 'markResolvedAsync', value: function markResolvedAsync() { this.update({ _conflicts: [null] }); return this.finishSaving(); } }, { key: 'finishSaving', value: function finishSaving() { var _this5 = this; var finish = this._linkResolution.finishResolving().then(function () { return _this5.objData.finishSaving(); }); return new scrivito.PublicPromise(finish); } }, { key: 'equals', value: function equals(otherObj) { if (!(otherObj instanceof scrivito.BasicObj)) { return false; } return this.id === otherObj.id; } }, { key: 'widget', value: function widget(id) { if (this.widgetData(id)) { return scrivito.BasicWidget.build(id, this); } return null; } }, { key: 'widgets', value: function widgets() { var _this6 = this; return _underscore2.default.map(_underscore2.default.keys(this._widgetPool), function (id) { return _this6.widget(id); }); } }, { key: 'widgetData', value: function widgetData(id) { return this._widgetPool[id]; } }, { key: 'fieldContainingWidget', value: function fieldContainingWidget(widget) { var _widgetPlacementFor3 = this._widgetPlacementFor(widget.id), container = _widgetPlacementFor3.container, attributeName = _widgetPlacementFor3.attributeName; return container.field(attributeName, 'widgetlist'); } }, { key: 'generateWidgetId', value: function generateWidgetId() { for (var i = 0; i < 10; i++) { var id = (0, _random.randomHex)(); if (!this.widget(id)) { return id; } } $.error('Could not generate a new unused widget id.'); } }, { key: 'serializeAttributes', value: function serializeAttributes() { var serializedAttributes = _get(BasicObj.prototype.__proto__ || Object.getPrototypeOf(BasicObj.prototype), 'serializeAttributes', this).call(this); delete serializedAttributes._conflicts; delete serializedAttributes._modification; delete serializedAttributes._last_changed; return serializedAttributes; } }, { key: 'slug', value: function slug() { var title = this.get('title', 'string'); return scrivito.convertToSlug(title); } }, { key: '_hasParentPath', value: function _hasParentPath() { return this.path && this.path !== '/'; } }, { key: '_copyAttributes', value: function _copyAttributes() { var objId = scrivito.BasicObj.generateId(); var serializedAttributes = this.serializeAttributes(); var uploadPromises = []; _underscore2.default.each(serializedAttributes, function (typeAndValue, name) { if (name[0] === '_') { delete serializedAttributes[name]; return; } var _typeAndValue = _slicedToArray(typeAndValue, 2), type = _typeAndValue[0], value = _typeAndValue[1]; if (type === 'binary' && value) { var futureBinary = new _future_binary2.default({ idToCopy: value.id }); var promise = futureBinary.into(objId).then(function (binary) { return { name: name, binary: binary }; }); uploadPromises.push(promise); } }); serializedAttributes._id = objId; serializedAttributes._obj_class = this.objClass; if (this.path) { serializedAttributes._path = this.parentPath + '/' + objId; } return scrivito.PublicPromise.all(uploadPromises).then(function (binaries) { _underscore2.default.each(binaries, function (_ref2) { var name = _ref2.name, binary = _ref2.binary; serializedAttributes[name] = ['binary', { id: binary.id }]; }); return serializedAttributes; }); } }, { key: '_widgetPlacementFor', value: function _widgetPlacementFor(widgetId) { var placement = scrivito.findWidgetPlacement(this._current, widgetId); var container = placement.parentWidgetId ? this.widget(placement.parentWidgetId) : this; var attributeName = (0, _attribute_inflection.camelCase)(placement.attributeName); var attributeValue = container.get(attributeName, 'widgetlist'); return _underscore2.default.extend(placement, { container: container, attributeName: attributeName, attributeValue: attributeValue }); } }, { key: 'id', get: function get() { return this._current._id; } }, { key: 'objId', get: function get() { return this.id; } }, { key: 'objClass', get: function get() { return this._current._obj_class; } }, { key: 'lastChanged', get: function get() { if (this._current._last_changed) { return scrivito.types.parseStringToDate(this._current._last_changed); } return null; } }, { key: 'version', get: function get() { return this._current._version; } }, { key: 'path', get: function get() { return this._current._path || null; } }, { key: 'permalink', get: function get() { return this._current._permalink || null; } }, { key: 'parentPath', get: function get() { if (this._hasParentPath()) { return computeParentPath(this.path); } return null; } }, { key: 'parent', get: function get() { return this.getParent(); } }, { key: 'modification', get: function get() { if (this._current._deleted) { return 'deleted'; } return this._current._modification || null; } }, { key: 'children', get: function get() { if (this.path) { var iterable = scrivito.BasicObj.all().and('_parentPath', 'equals', this.path); return scrivito.iterable.collectValuesFromIterator(iterable.iterator()); } return []; } }, { key: 'backlinks', get: function get() { var iterator = scrivito.BasicObj.where('*', 'linksTo', this).iterator(); return scrivito.iterable.collectValuesFromIterator(iterator); } }, { key: 'ancestors', get: function get() { if (this._hasParentPath()) { return collectPathComponents(this.parentPath).map(function (ancestorPath) { try { return scrivito.BasicObj.getByPath(ancestorPath); } catch (err) { if (err instanceof _errors.ResourceNotFoundError) { return null; } throw err; } }); } return []; } }, { key: '_widgetPool', get: function get() { return this._current._widget_pool || {}; } }, { key: '_systemAttributes', get: function get() { return SYSTEM_ATTRIBUTES; } }, { key: '_current', get: function get() { return this.objData.current; } }, { key: '_objClass', get: function get() { return _obj_class2.default.find(this.objClass); } }, { key: '_linkResolution', get: function get() { return scrivito.uiAdapter.linkResolutionFor(this.objData); } }]); return BasicObj; }(scrivito.BasicAttributeContent); scrivito.provideAsyncClassMethods(scrivito.BasicObj, { get: 'fetch', getByPermalink: 'fetchByPermalink', getIncludingDeleted: 'fetchIncludingDeleted' }); scrivito.provideAsyncInstanceMethods(scrivito.BasicObj, { getParent: 'fetchParent' }); function assertObjClassExists(attrInfoAndValue) { if (!attrInfoAndValue) { throw new _errors.ArgumentError('Please provide an obj class as the "_objClass" property.'); } } function extractAttributeDict(attributes) { var serializedAttributes = {}; var attributeDict = {}; _underscore2.default.each(attributes, function (serializedValue, name) { if (_underscore2.default.isArray(serializedValue) && _underscore2.default.first(serializedValue) === 'widgetlist') { var widgets = _underscore2.default.map(_underscore2.default.last(serializedValue), function (serializedWidgetAttributes) { return scrivito.BasicWidget.newWithSerializedAttributes(serializedWidgetAttributes); }); var attrName = (0, _attribute_inflection.camelCase)(name); attributeDict[attrName] = [widgets, ['widgetlist']]; } else { serializedAttributes[name] = serializedValue; } }); if (!serializedAttributes._id) { serializedAttributes._id = scrivito.BasicObj.generateId(); } return [serializedAttributes, attributeDict]; } function collectPathComponents(path) { var results = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (path === '/') { return ['/'].concat(_toConsumableArray(results)); } return collectPathComponents(computeParentPath(path), [path].concat(_toConsumableArray(results))); } function computeParentPath(path) { var pathComponents = path.split('/'); pathComponents.pop(); if (pathComponents.length === 1) { return '/'; } return pathComponents.join('/'); } function assertValidCopyOptions(copyOptions) { var validCopyOptions = ['_path']; if (_underscore2.default.difference(_underscore2.default.keys(copyOptions), validCopyOptions).length) { throw new _errors.ArgumentError('Currently only "_path" copy option is supported.'); } } function throwObjNotFound(id) { throw new _errors.ResourceNotFoundError('Obj with id "' + id + '" not found.'); } })(); /***/ }), /***/ 151: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var BasicObjFacetValue = function () { function BasicObjFacetValue(name, count, includedObjs) { _classCallCheck(this, BasicObjFacetValue); this._name = name; this._count = count; this._includedObjs = includedObjs; } _createClass(BasicObjFacetValue, [{ key: "includedObjs", value: function includedObjs() { return scrivito.BasicObj.get(this._includedObjs); } }, { key: "name", get: function get() { return this._name; } }, { key: "count", get: function get() { return this._count; } }]); return BasicObjFacetValue; }(); scrivito.BasicObjFacetValue = BasicObjFacetValue; })(); /***/ }), /***/ 152: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _attribute_inflection = __webpack_require__(7); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var OPERATORS = ['contains', 'containsPrefix', 'equals', 'startsWith', 'isGreaterThan', 'isLessThan', 'linksTo', 'refersTo']; var NEGATEABLE_OPERATORS = ['equals', 'startsWith', 'isGreaterThan', 'isLessThan']; var BOOSTABLE_PARAMETERS = ['contains', 'containsPrefix']; var DEFAULT_BATCH_SIZE = 100; scrivito.BasicObjSearchIterable = function () { function BasicObjSearchIterable() { _classCallCheck(this, BasicObjSearchIterable); this._query = []; this._batchSize = DEFAULT_BATCH_SIZE; } _createClass(BasicObjSearchIterable, [{ key: 'and', value: function and(attributeOrSearch, operator, value) { var boost = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; if (attributeOrSearch instanceof scrivito.BasicObjSearchIterable) { this._query = [].concat(_toConsumableArray(this._query), _toConsumableArray(attributeOrSearch._query)); } else { var subQuery = buildSubQuery(attributeOrSearch, operator, value); if (boost) { assertBoostableOperator(operator); subQuery.boost = underscoreBoostAttributes(boost); } this._query.push(subQuery); } return this; } }, { key: 'andNot', value: function andNot(attribute, operator, value) { var subQuery = buildSubQuery(attribute, operator, value); assertNegetableOperator(operator); subQuery.negate = true; this._query.push(subQuery); return this; } // public API }, { key: 'offset', value: function offset(_offset) { this._offset = _offset; return this; } // public API }, { key: 'order', value: function order(attribute) { var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'asc'; this._sortBy = underscoreAttribute(attribute); this._sortDirection = direction; return this; } // public API }, { key: 'batchSize', value: function batchSize(_batchSize) { this._batchSize = _batchSize; return this; } }, { key: 'includeDeleted', value: function includeDeleted() { this._includeDeleted = true; return this; } }, { key: 'iterator', value: function iterator() { var queryIterator = scrivito.ObjQueryStore.get(this._params, this._batchSize); return { next: function next() { var _queryIterator$next = queryIterator.next(), done = _queryIterator$next.done, value = _queryIterator$next.value; if (done) { return { done: done }; } return { done: done, value: new scrivito.BasicObj(value) }; } }; } // For test purpose only. }, { key: 'getBatchSize', // For test purpose only. value: function getBatchSize() { return this._batchSize; } }, { key: 'facet', value: function facet(attribute) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var facetQuery = new scrivito.FacetQuery(underscoreAttribute(attribute), options, this._query); return facetQuery.result(); } }, { key: 'store', value: function store(objIds) { scrivito.ObjQueryStore.store(this._params, objIds); } }, { key: 'params', get: function get() { return this._params; } }, { key: '_params', get: function get() { var params = _underscore2.default.omit({ query: this._query, offset: this._offset, sort_by: this._sortBy, sort_order: this._sortDirection }, _underscore2.default.isUndefined); if (this._includeDeleted) { params.options = { include_deleted: true }; } return params; } }]); return BasicObjSearchIterable; }(); function buildSubQuery(camelcasedAttribute, publicOperator, unserializedValue) { var attribute = convertAttribute(camelcasedAttribute); var operator = convertOperator(publicOperator); var value = convertValue(unserializedValue); return { field: attribute, operator: operator, value: value }; } function assertBoostableOperator(operator) { if (!_underscore2.default.contains(BOOSTABLE_PARAMETERS, operator)) { throw new _errors.ArgumentError('Boosting operator "' + operator + '" is invalid.'); } } function assertNegetableOperator(operator) { if (!_underscore2.default.contains(NEGATEABLE_OPERATORS, operator)) { throw new _errors.ArgumentError('Negating operator "' + operator + '" is invalid.'); } } function convertValue(value) { if (_underscore2.default.isArray(value)) { return _underscore2.default.map(value, convertSingleValue); } return convertSingleValue(value); } function convertSingleValue(value) { if (_underscore2.default.isDate(value)) { return scrivito.types.formatDateToString(value); } if (value instanceof scrivito.BasicObj) { return value.id; } return value; } function convertOperator(operator) { if (!_underscore2.default.contains(OPERATORS, operator)) { throw new _errors.ArgumentError('Operator "' + operator + '" is invalid.'); } return (0, _attribute_inflection.underscore)(operator); } function convertAttribute(attribute) { if (_underscore2.default.isArray(attribute)) { return _underscore2.default.map(attribute, underscoreAttribute); } return underscoreAttribute(attribute); } function underscoreBoostAttributes(boost) { var boostWithUnderscoreAttributes = {}; _underscore2.default.each(boost, function (value, attributeName) { var underscoredAttributeName = underscoreAttribute(attributeName); boostWithUnderscoreAttributes[underscoredAttributeName] = value; }); return boostWithUnderscoreAttributes; } function underscoreAttribute(attributeName) { if (!(0, _attribute_inflection.isCamelCase)(attributeName)) { throw new _errors.ArgumentError('Attribute name "' + attributeName + '" is not camel case.'); } return (0, _attribute_inflection.underscore)(attributeName); } })(); /***/ }), /***/ 153: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _attribute_inflection = __webpack_require__(7); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { var SYSTEM_ATTRIBUTES = { _id: 'id', _obj_class: 'objClass' }; scrivito.BasicWidget = function (_scrivito$BasicAttrib) { _inherits(BasicWidget, _scrivito$BasicAttrib); _createClass(BasicWidget, null, [{ key: 'build', value: function build(id, obj) { var instance = Object.create(scrivito.BasicWidget.prototype); instance._obj = obj; instance._id = id; return instance; } }, { key: 'newWithSerializedAttributes', value: function newWithSerializedAttributes(attributes) { var unserializedAttributes = {}; var serializedAttributes = {}; _underscore2.default.each(attributes, function (value, name) { if (name === '_obj_class') { unserializedAttributes._objClass = [value]; return; } if (_underscore2.default.isArray(value) && _underscore2.default.first(value) === 'widgetlist') { var newWidgets = _underscore2.default.map(_underscore2.default.last(value), function (serializedWidget) { return scrivito.BasicWidget.newWithSerializedAttributes(serializedWidget); }); var attrName = (0, _attribute_inflection.camelCase)(name); unserializedAttributes[attrName] = [newWidgets, ['widgetlist']]; return; } serializedAttributes[name] = value; }); var widget = new scrivito.BasicWidget(unserializedAttributes); widget.preserializedAttributes = serializedAttributes; return widget; } }]); function BasicWidget(attributes) { _classCallCheck(this, BasicWidget); var _this = _possibleConstructorReturn(this, (BasicWidget.__proto__ || Object.getPrototypeOf(BasicWidget)).call(this)); _this._attributesToBeSaved = scrivito.typeInfo.normalizeAttrs(attributes); assertWidgetClassExists(attributes._objClass); return _this; } _createClass(BasicWidget, [{ key: 'widget', value: function widget(id) { return this.obj.widget(id); } }, { key: 'update', value: function update(attributes) { var _this2 = this; var normalizedAttributes = scrivito.typeInfo.normalizeAttrs(attributes); scrivito.globalState.withBatchedUpdates(function () { _this2._persistWidgets(_this2.obj, normalizedAttributes); var patch = scrivito.AttributeSerializer.serialize(normalizedAttributes); _this2._updateSelf(patch); }); } }, { key: 'insertBefore', value: function insertBefore(widget) { widget.obj.insertWidget(this, { before: widget }); } }, { key: 'insertAfter', value: function insertAfter(widget) { widget.obj.insertWidget(this, { after: widget }); } }, { key: 'remove', value: function remove() { this.obj.removeWidget(this); } }, { key: 'copy', value: function copy() { var serializedAttributes = this.serializeAttributes(); return scrivito.BasicWidget.newWithSerializedAttributes(serializedAttributes); } }, { key: 'persistInObj', value: function persistInObj(obj) { this._persistWidgets(obj, this._attributesToBeSaved); var patch = scrivito.AttributeSerializer.serialize(this._attributesToBeSaved); _underscore2.default.extend(patch, this.preserializedAttributes || {}); this._obj = obj; this._id = obj.generateWidgetId(); this._updateSelf(patch); } }, { key: 'isPersisted', value: function isPersisted() { return !!this._obj; } }, { key: 'finishSaving', value: function finishSaving() { return this.obj.finishSaving(); } }, { key: 'equals', value: function equals(otherWidget) { if (!(otherWidget instanceof scrivito.BasicWidget)) { return false; } return this.id === otherWidget.id && this.obj.id === otherWidget.obj.id; } }, { key: 'containingField', value: function containingField() { return this.obj.fieldContainingWidget(this); } }, { key: '_throwUnpersistedError', value: function _throwUnpersistedError() { throw new _errors.ScrivitoError('Can not access a new widget before it has been saved.'); } }, { key: '_updateSelf', value: function _updateSelf(patch) { var widgetPoolPatch = { _widgetPool: [_defineProperty({}, this.id, patch)] }; this.obj.update(widgetPoolPatch); } }, { key: 'id', get: function get() { if (this.isPersisted()) { return this._id; } this._throwUnpersistedError(); } }, { key: 'objClass', get: function get() { return this._current._obj_class; } }, { key: 'obj', get: function get() { if (this.isPersisted()) { return this._obj; } this._throwUnpersistedError(); } }, { key: 'objId', get: function get() { return this.obj.id; } }, { key: 'attributesToBeSaved', get: function get() { return this._attributesToBeSaved; } }, { key: '_current', get: function get() { if (this.isPersisted()) { return this.obj.widgetData(this.id); } throw new _errors.ScrivitoError('Can not access an unpersisted widget.'); } }, { key: '_systemAttributes', get: function get() { return SYSTEM_ATTRIBUTES; } }]); return BasicWidget; }(scrivito.BasicAttributeContent); function assertWidgetClassExists(attrInfoAndValue) { if (!attrInfoAndValue) { throw new _errors.ArgumentError('Please provide a widget class as the "_objClass" property.'); } } })(); /***/ }), /***/ 154: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { function LinkFactory(registry) { // public API var Link = function (_scrivito$BasicLink) { _inherits(Link, _scrivito$BasicLink); // public API function Link(attributes) { _classCallCheck(this, Link); return _possibleConstructorReturn(this, (Link.__proto__ || Object.getPrototypeOf(Link)).call(this, attributes)); } // public API _createClass(Link, [{ key: "fetchObj", value: function fetchObj(id) { return _get(Link.prototype.__proto__ || Object.getPrototypeOf(Link.prototype), "fetchObj", this).call(this, id).then(function (basicObj) { return scrivito.wrapInAppClass(registry, basicObj); }); } }, { key: "obj", get: function get() { return scrivito.wrapInAppClass(registry, _get(Link.prototype.__proto__ || Object.getPrototypeOf(Link.prototype), "obj", this)); } }, { key: "_scrivitoPrivateContent", get: function get() { return scrivito.BasicLink.build(this.buildAttributes()); } }]); return Link; }(scrivito.BasicLink); return Link; } scrivito.LinkFactory = LinkFactory; })(); /***/ }), /***/ 155: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _errors = __webpack_require__(1); var _app_model_accessor = __webpack_require__(30); var _app_model_accessor2 = _interopRequireDefault(_app_model_accessor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { function ObjFactory(registry) { var appModelAccessor = new _app_model_accessor2.default(registry); function buildObjSearchIterable(objClassName) { var iterable = new registry.ObjSearchIterable(); if (objClassName) { iterable.and('_objClass', 'equals', objClassName); } return iterable; } function wrap(response) { return scrivito.wrapInAppClass(registry, response); } // public API var Obj = function (_scrivito$AttributeCo) { _inherits(Obj, _scrivito$AttributeCo); function Obj() { _classCallCheck(this, Obj); return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).apply(this, arguments)); } _createClass(Obj, [{ key: 'orderedChildren', value: function orderedChildren() { return wrap(this._scrivitoPrivateContent.orderedChildren()); } // public API }, { key: 'slug', // public API value: function slug() { return this._scrivitoPrivateContent.slug(); } // public API }, { key: 'isBinary', value: function isBinary() { var schema = scrivito.Schema.forInstance(this); if (!schema) { return false; } return schema.isBinary(); } // public API }, { key: 'destroy', value: function destroy() { this._scrivitoPrivateContent.destroy(); } // public API }, { key: 'widget', value: function widget(id) { return wrap(this._scrivitoPrivateContent.widget(id)); } // public API }, { key: 'widgets', value: function widgets() { return wrap(this._scrivitoPrivateContent.widgets()); } }, { key: 'lastChanged', // public API get: function get() { return this._scrivitoPrivateContent.lastChanged; } // public API }, { key: 'path', get: function get() { return this._scrivitoPrivateContent.path; } // public API }, { key: 'parent', get: function get() { return wrap(this._scrivitoPrivateContent.parent); } // public API }, { key: 'ancestors', get: function get() { return wrap(this._scrivitoPrivateContent.ancestors); } // public API }, { key: 'backlinks', get: function get() { return wrap(this._scrivitoPrivateContent.backlinks); } // public API }, { key: 'children', get: function get() { return wrap(this._scrivitoPrivateContent.children); } }, { key: 'permalink', get: function get() { return this._scrivitoPrivateContent.permalink; } }], [{ key: 'get', // public API value: function get(id) { return appModelAccessor.getObj(this, id); } // public API }, { key: 'getIncludingDeleted', value: function getIncludingDeleted(id) { return appModelAccessor.getObjIncludingDeleted(this, id); } // public API }, { key: 'getByPath', value: function getByPath(path) { return wrap(scrivito.BasicObj.getByPath(path)); } // public API }, { key: 'getByPermalink', value: function getByPermalink(permalink) { return wrap(scrivito.BasicObj.getByPermalink(permalink)); } // public API }, { key: 'all', value: function all() { var objClassName = registry.objClassNameFor(this); return buildObjSearchIterable(objClassName).batchSize(1000); } // public API }, { key: 'root', value: function root() { return wrap(scrivito.BasicObj.root()); } // public API }, { key: 'where', value: function where(attribute, operator, value) { var boost = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var objClassName = registry.objClassNameFor(this); return buildObjSearchIterable(objClassName).and(attribute, operator, value, boost); } // public API }, { key: 'create', value: function create(attributes) { var schema = scrivito.Schema.forClass(this); var appClassName = registry.objClassNameFor(this); if (!appClassName) { throw new _errors.ArgumentError('Creating CMS objects is not supported for the class Obj or abstract classes.'); } if (attributes.constructor !== Object) { throw new _errors.ArgumentError('The provided attributes are invalid. They have ' + 'to be an Object with valid Scrivito attribute values.'); } if (attributes._objClass) { throw new _errors.ArgumentError('Invalid attribute "_objClass". ' + ('"' + attributes._objClass + '.create" will automatically set the CMS object class ') + 'correctly.'); } attributes._objClass = appClassName; var attributesWithTypeInfo = scrivito.AttributeContentFactory.prepareAttributes(attributes, schema, appClassName); return wrap(scrivito.BasicObj.create(attributesWithTypeInfo)); } }]); return Obj; }(scrivito.AttributeContentFactory(appModelAccessor)); return Obj; } scrivito.ObjFactory = ObjFactory; })(); /***/ }), /***/ 156: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _obj_facet_value = __webpack_require__(37); var _obj_facet_value2 = _interopRequireDefault(_obj_facet_value); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { function ObjSearchIterableFactory(registry) { // public API var ObjSearchIterable = function (_scrivito$BasicObjSea) { _inherits(ObjSearchIterable, _scrivito$BasicObjSea); function ObjSearchIterable() { _classCallCheck(this, ObjSearchIterable); return _possibleConstructorReturn(this, (ObjSearchIterable.__proto__ || Object.getPrototypeOf(ObjSearchIterable)).apply(this, arguments)); } _createClass(ObjSearchIterable, [{ key: 'iterator', // public API value: function iterator() { var basicIterator = _get(ObjSearchIterable.prototype.__proto__ || Object.getPrototypeOf(ObjSearchIterable.prototype), 'iterator', this).call(this); return { next: function next() { var _basicIterator$next = basicIterator.next(), done = _basicIterator$next.done, value = _basicIterator$next.value; if (done) { return { done: done }; } return { done: done, value: scrivito.wrapInAppClass(registry, value) }; } }; } // public API }, { key: 'and', value: function and(attribute, operator, value) { var boost = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var unwrappedValue = scrivito.unwrapAppClassValues(value); return _get(ObjSearchIterable.prototype.__proto__ || Object.getPrototypeOf(ObjSearchIterable.prototype), 'and', this).call(this, attribute, operator, unwrappedValue, boost); } // public API }, { key: 'andNot', value: function andNot(attribute, operator, value) { var unwrappedValue = scrivito.unwrapAppClassValues(value); return _get(ObjSearchIterable.prototype.__proto__ || Object.getPrototypeOf(ObjSearchIterable.prototype), 'andNot', this).call(this, attribute, operator, unwrappedValue); } // public API }, { key: 'facet', value: function facet(attribute) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var result = _get(ObjSearchIterable.prototype.__proto__ || Object.getPrototypeOf(ObjSearchIterable.prototype), 'facet', this).call(this, attribute, options); return _underscore2.default.map(result, function (facetValue) { return new _obj_facet_value2.default(registry, facetValue); }); } }]); return ObjSearchIterable; }(scrivito.BasicObjSearchIterable); // check if the environment supports ES6 iterables // (either native or through some kind of polyfill) // if yes, make BasicObjSearchIterable an ES6 iterable. if (typeof window.Symbol === 'function') { var iteratorSymbol = window.Symbol.iterator; if (iteratorSymbol) { var proto = ObjSearchIterable.prototype; proto[iteratorSymbol] = proto.iterator; } } return ObjSearchIterable; } scrivito.ObjSearchIterableFactory = ObjSearchIterableFactory; })(); /***/ }), /***/ 157: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _errors = __webpack_require__(1); var _app_model_accessor = __webpack_require__(30); var _app_model_accessor2 = _interopRequireDefault(_app_model_accessor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } (function () { function WidgetFactory(registry) { var appModelAccessor = new _app_model_accessor2.default(registry); // public API var Widget = function (_scrivito$AttributeCo) { _inherits(Widget, _scrivito$AttributeCo); // public API function Widget(attributes) { _classCallCheck(this, Widget); var _this = _possibleConstructorReturn(this, (Widget.__proto__ || Object.getPrototypeOf(Widget)).call(this)); var schema = scrivito.Schema.forInstance(_this); var appClassName = registry.objClassNameFor(_this.constructor); if (!appClassName) { throw new _errors.ArgumentError('Creating widgets is not supported for the class Widget or abstract classes.'); } if (attributes.constructor !== Object) { throw new _errors.ArgumentError('The provided attributes are invalid. They have ' + 'to be an Object with valid Scrivito attribute values.'); } if (attributes._objClass) { throw new _errors.ArgumentError('Invalid attribute "_objClass". ' + ('"new ' + attributes._objClass + '" will automatically set the CMS object class correctly.')); } attributes._objClass = appClassName; var attributesWithTypeInfo = scrivito.AttributeContentFactory.prepareAttributes(attributes, schema, appClassName); _this._scrivitoPrivateContent = new scrivito.BasicWidget(attributesWithTypeInfo); return _this; } // public API _createClass(Widget, [{ key: 'copy', // public API value: function copy() { var appClass = registry.widgetClassFor(this.objClass); var basicWidget = this._scrivitoPrivateContent.copy(); return scrivito.buildAppClassInstance(basicWidget, appClass); } }, { key: 'obj', get: function get() { var basicObj = this._scrivitoPrivateContent.obj; return scrivito.wrapInAppClass(registry, basicObj); } }]); return Widget; }(scrivito.AttributeContentFactory(appModelAccessor)); return Widget; } scrivito.WidgetFactory = WidgetFactory; })(); /***/ }), /***/ 158: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var capturedDelayedFunctions = []; var captureEnabled = void 0; _underscore2.default.extend(scrivito, { nextTick: function nextTick(delayedFunction) { if (captureEnabled) { capturedDelayedFunctions.push(delayedFunction); } else { setTimeout(delayedFunction, 0); } }, // For test purpose only. simulateNextTicks: function simulateNextTicks() { if (!captureEnabled) { return; } var exceptions = []; while (capturedDelayedFunctions.length) { var currentFunctions = _underscore2.default.shuffle(capturedDelayedFunctions); capturedDelayedFunctions = []; _underscore2.default.each(currentFunctions, function (delayedFunction) { try { delayedFunction(); } catch (e) { exceptions.push(e); } }); } if (exceptions.length > 0) { throw exceptions[0]; } }, // For test purpose only. enableNextTickCapture: function enableNextTickCapture() { captureEnabled = true; }, // For test purpose only. disableNextTickCapture: function disableNextTickCapture() { captureEnabled = false; } }); })(); /***/ }), /***/ 159: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _loadable_data = __webpack_require__(3); var _loadable_data2 = _interopRequireDefault(_loadable_data); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.ObjData = function () { function ObjData(id, state) { var _this = this; _classCallCheck(this, ObjData); this._loadableData = new _loadable_data2.default({ state: state, loader: function loader(push) { return scrivito.ObjRetrieval.retrieveObj(_this._id).then(function (data) { push(function () { return _this._replication().notifyBackendState(data); }); return data; }); }, throwNotLoaded: true }); this._id = id; } _createClass(ObjData, [{ key: 'set', value: function set(newState) { this._loadableData.set(newState); } }, { key: 'setError', value: function setError(error) { this._loadableData.setError(error); } }, { key: 'ensureAvailable', value: function ensureAvailable() { this._loadableData.get(); } }, { key: 'isAvailable', value: function isAvailable() { return this._loadableData.isAvailable(); } }, { key: 'update', value: function update(objPatch) { var newState = scrivito.ObjPatch.apply(this.current, objPatch); this._loadableData.set(newState); this._replication().notifyLocalState(newState); } }, { key: 'finishSaving', value: function finishSaving() { return this._replication().finishSaving(); } }, { key: '_replication', value: function _replication() { return scrivito.ObjReplication.get(this._id); } }, { key: 'current', get: function get() { return this._loadableData.get(); } }]); return ObjData; }(); })(); /***/ }), /***/ 160: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _load = __webpack_require__(6); var _load2 = _interopRequireDefault(_load); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { scrivito.ObjDataStore = { preload: function preload(id) { var _this = this; (0, _load2.default)(function () { return _this.get(id); }); }, createObjData: function createObjData(id) { var objData = objDataFor(id); objData.set(null); scrivito.ObjReplication.get(id).notifyBackendState(null); return objData; }, store: function store(primitiveObj) { var id = primitiveObj._id; if (!objDataFor(id).isAvailable()) { this.set(id, primitiveObj); } scrivito.ObjReplication.get(id).notifyBackendState(primitiveObj); }, set: function set(id, primitiveObj) { objDataFor(id).set(primitiveObj); }, // test method only! setError: function setError(id, error) { objDataFor(id).setError(error); }, get: function get(id) { objDataFor(id).ensureAvailable(); return objDataFor(id); }, clearCache: function clearCache() { cacheStore().clear(); } }; function cacheStore() { return scrivito.cmsState.subState('objData'); } function objDataFor(id) { return new scrivito.ObjData(id, cacheStore().subState(id)); } })(); /***/ }), /***/ 161: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var ObjPatch = { apply: function apply(primitiveObj, patch) { if (!primitiveObj) { return patch; } if (!patch) { return null; } var updatedPrimitiveObj = {}; eachKeyFrom(primitiveObj, patch, function (attribute, objValue, patchValue) { if (attribute === '_widget_pool') { updatedPrimitiveObj._widget_pool = buildUpdatedWidgetPool(objValue, patchValue); } else if (patch.hasOwnProperty(attribute)) { if (patchValue) { updatedPrimitiveObj[attribute] = patchValue; } } else { updatedPrimitiveObj[attribute] = primitiveObj[attribute]; } }); return updatedPrimitiveObj; }, diff: function diff(primitiveObjA, primitiveObjB) { if (!primitiveObjA) { return primitiveObjB; } if (!primitiveObjB) { return null; } var patch = {}; eachKeyFrom(primitiveObjA, primitiveObjB, function (attribute, valueInA, valueInB) { if (attribute === '_widget_pool') { var widgetPoolPatch = buildWidgetPoolPatch(valueInA, valueInB); if (!_underscore2.default.isEmpty(widgetPoolPatch)) { patch._widget_pool = widgetPoolPatch; } } else { var patchValue = buildPatchEntry(valueInA, valueInB, function () { if (!_underscore2.default.isEqual(valueInA, valueInB)) { return valueInB; } }); if (patchValue !== undefined) { patch[attribute] = patchValue; } } }); return patch; } }; function eachKeyFrom(objectA, objectB, handler) { _underscore2.default.union(_underscore2.default.keys(objectA), _underscore2.default.keys(objectB)).forEach(function (key) { return handler(key, workspaceAwareObject(objectA[key]), workspaceAwareObject(objectB[key])); }); } function workspaceAwareObject(object) { if (_underscore2.default.isArray(object)) { var _object = _slicedToArray(object, 2), type = _object[0], value = _object[1]; // Ignore binary URLs, since they are different across workspaces. // However, a binary ID identifies a binary unambiguously. if (type === 'binary' && value) { return [type, _underscore2.default.omit(value, 'url')]; } return object; } return object; } function buildUpdatedWidgetPool(widgetPool, widgetPoolPatch) { if (!widgetPoolPatch || _underscore2.default.isEmpty(widgetPoolPatch)) { return widgetPool; } var updatedWidgetPool = {}; eachKeyFrom(widgetPool || {}, widgetPoolPatch || {}, function (id, widget, widgetPatch) { if (widgetPoolPatch.hasOwnProperty(id)) { if (widgetPatch && !widget) { updatedWidgetPool[id] = widgetPatch; } else if (widgetPatch) { updatedWidgetPool[id] = ObjPatch.apply(widget, widgetPatch); } } else { updatedWidgetPool[id] = widget; } }); return updatedWidgetPool; } function buildPatchEntry(valueA, valueB, fnHandleBoth) { if (!valueA && valueB) { return valueB; } if (valueA && !valueB) { return null; } if (valueA && valueB) { return fnHandleBoth(); } } function buildWidgetPoolPatch(widgetPoolA, widgetPoolB) { if (widgetPoolA === widgetPoolB) { return {}; } var patch = {}; eachKeyFrom(widgetPoolA, widgetPoolB, function (widgetId, widgetA, widgetB) { var widgetValue = buildPatchEntry(widgetA, widgetB, function () { var widgetPatch = ObjPatch.diff(widgetA, widgetB); if (!_underscore2.default.isEmpty(widgetPatch)) { return widgetPatch; } }); if (widgetValue !== undefined) { patch[widgetId] = widgetValue; } }); return patch; } scrivito.ObjPatch = ObjPatch; })(); /***/ }), /***/ 162: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.ObjQuery = function () { _createClass(ObjQuery, null, [{ key: "store", value: function store(params, objIds) { scrivito.ObjQueryBatch.store(params, objIds); } }]); function ObjQuery(params) { _classCallCheck(this, ObjQuery); this._params = params; } _createClass(ObjQuery, [{ key: "iterator", value: function iterator(batchSize) { var priorObjIds = {}; var currentBatch = scrivito.ObjQueryBatch.firstBatchFor(this._params, batchSize); var currentIndex = 0; function next() { var currentObjIds = currentBatch.objIds(); if (currentIndex < currentObjIds.length) { var objId = currentObjIds[currentIndex]; currentIndex++; if (priorObjIds[objId]) { return next(); } priorObjIds[objId] = true; return { value: objId, done: false }; } var nextBatch = currentBatch.nextBatch(); if (nextBatch) { currentBatch = nextBatch; currentIndex = 0; return next(); } return { done: true }; } return { next: next }; } }]); return ObjQuery; }(); })(); /***/ }), /***/ 163: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _load2 = __webpack_require__(6); var _load3 = _interopRequireDefault(_load2); var _loadable_data = __webpack_require__(3); var _loadable_data2 = _interopRequireDefault(_loadable_data); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.ObjQueryBatch = function () { _createClass(ObjQueryBatch, null, [{ key: 'store', value: function store(params, objIds) { var state = stateContainer(params, 0); var invalidation = invalidationFn(undefined); var loadableData = new _loadable_data2.default({ state: state, invalidation: invalidation }); loadableData.set({ results: objIds }); } }, { key: 'firstBatchFor', value: function firstBatchFor(params, batchSize) { return new ObjQueryBatch(params, batchSize); } // the constructor should only be called internally, // i.e. by ObjQueryBatch itself }]); function ObjQueryBatch(params, batchSize) { var previousBatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; _classCallCheck(this, ObjQueryBatch); this._params = params; this._batchSize = batchSize; if (previousBatch) { this._index = previousBatch.index + 1; this._continuation = previousBatch.continuationForNextBatch(); this._previousBatch = previousBatch; } else { // First batch this._index = 0; } } // throws NotLoadedError if not available _createClass(ObjQueryBatch, [{ key: 'objIds', value: function objIds() { return this._response().results; } // returns the next batch or undefined if this is the last batch // throws NotLoadedError if not available }, { key: 'nextBatch', value: function nextBatch() { if (this.continuationForNextBatch()) { return new ObjQueryBatch(this._params, this._batchSize, this); } } }, { key: 'continuationForNextBatch', value: function continuationForNextBatch() { return this._response().continuation; } }, { key: '_response', value: function _response() { return this._data().get(); } }, { key: '_data', value: function _data() { var _this = this; return new _loadable_data2.default({ state: stateContainer(this._params, this._index), loader: function loader() { return _this._load(); }, invalidation: invalidationFn(this._continuation), throwNotLoaded: true }); } }, { key: '_load', value: function _load() { var _this2 = this; return this._fetchContinuation().then(function (continuation) { var batchSpecificParams = { size: _this2._batchSize, continuation: continuation }; var requestParams = _underscore2.default.extend({}, _this2._params, batchSpecificParams); return scrivito.ObjQueryRetrieval.retrieve(requestParams).then(function (response) { preloadObjData(response.results); return response; }); }); } }, { key: '_fetchContinuation', value: function _fetchContinuation() { var _this3 = this; if (this._previousBatch) { return (0, _load3.default)(function () { return _this3._previousBatch.continuationForNextBatch(); }); } return scrivito.Promise.resolve(); } }, { key: 'index', get: function get() { return this._index; } }]); return ObjQueryBatch; }(); function preloadObjData(ids) { _underscore2.default.each(ids, function (id) { return scrivito.ObjDataStore.preload(id); }); } function stateContainer(params, index) { var paramsWithIndex = _underscore2.default.extend({}, params, { index: index }); var key = scrivito.ObjQueryStore.computeCacheKey(paramsWithIndex); return scrivito.ObjQueryStore.stateContainer().subState(key); } function invalidationFn(continuation) { return function () { return continuation + '|' + scrivito.ObjReplication.getWorkspaceVersion(); }; } })(); /***/ }), /***/ 164: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _errors = __webpack_require__(1); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var ObjQueryIterator = function () { function ObjQueryIterator(query, batchSize) { _classCallCheck(this, ObjQueryIterator); this._iterator = query.iterator(batchSize); } _createClass(ObjQueryIterator, [{ key: 'next', value: function next() { var id = this._fetchNextId(); if (!id) { return { done: true }; } try { var objData = scrivito.ObjDataStore.get(id); this._nextId = null; if (isFinallyDeleted(objData)) { return this.next(); } return { value: objData, done: false }; } catch (error) { if (error instanceof _errors.ResourceNotFoundError) { this._nextId = null; return this.next(); } throw error; } } }, { key: '_fetchNextId', value: function _fetchNextId() { if (!this._nextId) { var _iterator$next = this._iterator.next(), value = _iterator$next.value; this._nextId = value; } return this._nextId; } }]); return ObjQueryIterator; }(); function isFinallyDeleted(objData) { return !!objData.current._deleted; } scrivito.ObjQueryIterator = ObjQueryIterator; })(); /***/ }), /***/ 165: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { scrivito.ObjQueryRetrieval = { retrieve: function retrieve(params) { var workspaceId = scrivito.currentWorkspaceId(); var consistentParams = _underscore2.default.extend({ consistent: true }, params); return scrivito.CmsRestApi.get('workspaces/' + workspaceId + '/objs/search', consistentParams).then(function (response) { response.results = _underscore2.default.pluck(response.results, 'id'); return _underscore2.default.pick(response, 'results', 'continuation'); }); } }; })(); /***/ }), /***/ 166: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { scrivito.ObjQueryStore = { store: function store(params, objIds) { scrivito.ObjQuery.store(params, objIds); }, computeCacheKey: function computeCacheKey(obj) { return scrivito.computeCacheKey(obj); }, get: function get(params, batchSize) { var objQuery = new scrivito.ObjQuery(params); return new scrivito.ObjQueryIterator(objQuery, batchSize); }, stateContainer: function stateContainer() { return scrivito.cmsState.subState('objQuery'); }, clearCache: function clearCache() { this.stateContainer().clear(); } }; })(); /***/ }), /***/ 167: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var replicationCache = {}; var disabled = void 0; var writeCallbacks = {}; var subscriptionToken = 0; var workspaceVersion = 0; scrivito.ObjReplication = function () { _createClass(ObjReplication, null, [{ key: 'get', value: function get(id) { if (!replicationCache[id]) { replicationCache[id] = new scrivito.ObjReplication(id); } return replicationCache[id]; } }, { key: 'subscribeWrites', value: function subscribeWrites(callback) { subscriptionToken += 1; writeCallbacks[subscriptionToken] = callback; return subscriptionToken; } }, { key: 'unsubscribeWrites', value: function unsubscribeWrites(token) { delete writeCallbacks[token]; } // a version counter that increases whenever an Obj in the Workspace is changed. }, { key: 'getWorkspaceVersion', value: function getWorkspaceVersion() { return workspaceVersion; } }]); function ObjReplication(id) { var _this = this; _classCallCheck(this, ObjReplication); this._id = id; this._replicationActive = false; this._scheduledReplication = false; this._currentRequestDeferred = null; this._nextRequestDeferred = null; this._performThrottledReplication = scrivito.throttle(function () { return _this._performReplication(); }, 1000); } _createClass(ObjReplication, [{ key: 'notifyLocalState', value: function notifyLocalState(localState) { if (disabled) { return; } if (this._backendState === undefined) { throw new _errors.InternalError('Can not set local state before backend state.'); } if (this._backendState && this._backendState._deleted) { throw new _errors.InternalError('Can not update a fully deleted obj.'); } this._localState = localState; this._startReplication(); } }, { key: 'notifyBackendState', value: function notifyBackendState(newBackendState) { if (this._backendState === undefined) { this._updateBackendState(newBackendState); this._updateLocalState(newBackendState); return; } var newestKnownBackendState = this._bufferedBackendState || this._backendState; if (compareStates(newBackendState, newestKnownBackendState) > 0) { if (this._replicationActive) { this._bufferedBackendState = newBackendState; } else { if (newBackendState._deleted) { this._updateLocalState(null); } else { var patch = diff(this._backendState, newBackendState); this._updateLocalState(apply(this.localState, patch)); } this._updateBackendState(newBackendState); } } } }, { key: 'finishSaving', value: function finishSaving() { var finishSavingPromise = void 0; if (this._nextRequestDeferred) { finishSavingPromise = this._nextRequestDeferred.promise; } else if (this._currentRequestDeferred) { finishSavingPromise = this._currentRequestDeferred.promise; } else { return scrivito.Promise.resolve(); } return finishSavingPromise.catch(function () { return scrivito.Promise.reject(); }); } }, { key: '_startReplication', value: function _startReplication() { var _this2 = this; if (!_underscore2.default.isEmpty(diff(this._backendState, this._localState))) { if (!this._replicationActive) { if (!this._scheduledReplication) { this._scheduledReplication = true; this._initDeferredForRequest(); writeStarted(this._currentRequestDeferred.promise); scrivito.nextTick(function () { return _this2._performThrottledReplication(); }); } } else { if (!this._nextRequestDeferred) { this._nextRequestDeferred = new scrivito.Deferred(); } } } else { if (this._nextRequestDeferred) { this._nextRequestDeferred.resolve(); this._nextRequestDeferred = null; } } } }, { key: '_performReplication', value: function _performReplication() { var _this3 = this; var localState = this._localState; var patch = diff(this._backendState, this._localState); this._scheduledReplication = false; this._replicationActive = true; this._replicatePatchToBackend(patch).then(function (backendState) { _this3._handleBackendUpdate(localState, backendState); _this3._currentRequestDeferred.resolve(_this3._id); _this3._currentRequestDeferred = null; _this3._replicationActive = false; _this3._startReplication(); }, function (error) { _this3._currentRequestDeferred.reject(error); _this3._currentRequestDeferred = null; _this3._replicationActive = false; }); } }, { key: '_replicatePatchToBackend', value: function _replicatePatchToBackend(patch) { if (patch._modification === 'deleted') { return this._deleteObj(); } if (_underscore2.default.isEmpty(patch)) { return scrivito.Promise.resolve(this._backendState); } var workspaceId = scrivito.currentWorkspaceId(); var path = 'workspaces/' + workspaceId + '/objs/' + this._id; return scrivito.CmsRestApi.put(path, { obj: patch }); } }, { key: '_deleteObj', value: function _deleteObj() { var workspaceId = scrivito.currentWorkspaceId(); var path = 'workspaces/' + workspaceId + '/objs/' + this._id; return scrivito.CmsRestApi.delete(path, { include_deleted: true }); } }, { key: '_initDeferredForRequest', value: function _initDeferredForRequest() { if (this._nextRequestDeferred) { var currentDeferred = this._nextRequestDeferred; this._nextRequestDeferred = null; this._currentRequestDeferred = currentDeferred; } else { this._currentRequestDeferred = new scrivito.Deferred(); } } }, { key: '_handleBackendUpdate', value: function _handleBackendUpdate(replicatedState, backendState) { var bufferedLocalChanges = diff(replicatedState, this._localState); this._updateBackendState(newerState(backendState, this._bufferedBackendState)); this._bufferedBackendState = undefined; this._updateLocalState(apply(this._backendState, bufferedLocalChanges)); } }, { key: '_updateLocalState', value: function _updateLocalState(localState) { this._localState = localState; scrivito.ObjDataStore.set(this._id, this._localState); } }, { key: '_updateBackendState', value: function _updateBackendState(newBackendState) { if (this._backendState !== undefined) { workspaceVersion++; } this._backendState = newBackendState; } // For test purpose only. }, { key: 'isNotStoredInBackend', // For test purpose only. value: function isNotStoredInBackend() { return this._backendState === null; } // For test purpose only. }, { key: 'isRequestInFlight', value: function isRequestInFlight() { return this._replicationActive; } // For test purpose only. }, { key: 'backendState', get: function get() { return this._backendState; } // For test purpose only. }, { key: 'localState', get: function get() { return this._localState; } }], [{ key: 'disableReplication', value: function disableReplication() { disabled = true; } // For test purpose only. }, { key: 'enableReplication', value: function enableReplication() { disabled = false; } // For test purpose only. }, { key: 'clearWriteCallbacks', value: function clearWriteCallbacks() { writeCallbacks = {}; } // For test purpose only. }, { key: 'clearCache', value: function clearCache() { replicationCache = {}; } }]); return ObjReplication; }(); function diff(stateA, stateB) { return scrivito.ObjPatch.diff(stateA, stateB); } function apply(stateA, patch) { return scrivito.ObjPatch.apply(stateA, patch); } function newerState(stateA, stateB) { if (compareStates(stateA, stateB) > 0) { return stateA; } return stateB; } function compareStates(stateA, stateB) { if (!stateA) { return -1; } if (!stateB) { return 1; } return strCompare(stateA._version, stateB._version); } function strCompare(str1, str2) { if (str1 > str2) { return 1; } if (str2 > str1) { return -1; } return 0; } function writeStarted(promise) { _underscore2.default.each(writeCallbacks, function (callback) { callback(promise); }); } })(); /***/ }), /***/ 168: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _errors = __webpack_require__(1); (function () { function mget(ids) { var workspaceId = scrivito.currentWorkspaceId(); return scrivito.CmsRestApi.get('workspaces/' + workspaceId + '/objs/mget', { ids: ids, include_deleted: true }).then(function (response) { return response.results; }); } // Why batchSize: 17? // Retrieval of up to 100 Objs is a common use-case (see ObjSearchIterable) // With a batchSize of 17, this leads to 6 concurrent requests, // which is the concurrent request limit in many browsers for HTTP/1. // This ensures maximum parallel loading. var batchRetrieval = new scrivito.BatchRetrieval(mget, { batchSize: 17 }); scrivito.ObjRetrieval = { retrieveObj: function retrieveObj(id) { return batchRetrieval.retrieve(id).then(function (value) { if (value) { return value; } throw new _errors.ResourceNotFoundError('Obj with id "' + id + '" not found.'); }); }, // For test purpose only. reset: function reset() { batchRetrieval.reset(); } }; })(); /***/ }), /***/ 169: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _jsuri = __webpack_require__(196); var _jsuri2 = _interopRequireDefault(_jsuri); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function parseUrl(url) { var uri = new _jsuri2.default(url); return { origin: uri.origin(), pathname: uri.path(), hash: uri.anchor() }; } scrivito.parseUrl = parseUrl; })(); /***/ }), /***/ 17: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _attribute_content_class = __webpack_require__(45); var _attribute_content_class2 = _interopRequireDefault(_attribute_content_class); var _content_class_registry = __webpack_require__(44); var _content_class_registry2 = _interopRequireDefault(_content_class_registry); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var WidgetClass = function (_AttributeContentClas) { _inherits(WidgetClass, _AttributeContentClas); _createClass(WidgetClass, null, [{ key: 'type', value: function type() { return 'Widget'; } }, { key: 'validClassNamesForField', value: function validClassNamesForField(field) { return this.validClassesForField(field).map(function (widgetClass) { return widgetClass.name; }); } }, { key: 'validClassesForField', value: function validClassesForField(field) { var container = field.container(); var containerClass = findContentClassForBasicModel(container); if (containerClass && containerClass.usesServerCallbacks()) { var names = scrivito.validClassesForWidgetlistField(field); return names.reduce(function (acc, name) { var widgetClass = _content_class_registry2.default.findByType('Widget', name); if (widgetClass) { acc.push(widgetClass); } return acc; }, []); } var attribute = containerClass && containerClass.attribute(field.name()); var only = attribute && attribute.only(); var widgetClasses = only || _content_class_registry2.default.allForType('Widget'); return widgetClasses.filter(validWidgetClassForObjClass(container.objClass)); } }]); function WidgetClass(classData) { _classCallCheck(this, WidgetClass); var _this = _possibleConstructorReturn(this, (WidgetClass.__proto__ || Object.getPrototypeOf(WidgetClass)).call(this, classData)); _this.embeds = classData.embeds; _this._embeddingAttribute = classData.embeddingAttribute; return _this; } _createClass(WidgetClass, [{ key: 'newWidgetWithDefaults', value: function newWidgetWithDefaults() { if (this._classData.usesServerCallbacks) { return scrivito.withServerDefaults.newWidget(this.name); } return scrivito.Promise.resolve(new scrivito.BasicWidget({ _objClass: [this.name] })); } // public }, { key: 'embeddingAttribute', value: function embeddingAttribute() { if (this.embeds) { return this.attribute(this._embeddingAttribute); } } }, { key: 'isValidContainerClass', value: function isValidContainerClass(modelClassName) { if (!this._classData.validContainerClasses) { return true; } return _underscore2.default.contains(this._classData.validContainerClasses, modelClassName); } }, { key: 'hasJsDetailsView', value: function hasJsDetailsView() { return this.localizedAttributes().length > 0; } }]); return WidgetClass; }(_attribute_content_class2.default); function validWidgetClassForObjClass(objClassName) { return function (widgetClass) { return !widgetClass.isHiddenFromEditors() && widgetClass.isValidContainerClass(objClassName); }; } function findContentClassForBasicModel(basicModel) { var type = basicModel instanceof scrivito.BasicWidget ? 'Widget' : 'Obj'; return _content_class_registry2.default.findByType(type, basicModel.objClass); } exports.default = WidgetClass; /***/ }), /***/ 170: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _bluebird = __webpack_require__(190); var _bluebird2 = _interopRequireDefault(_bluebird); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { _bluebird2.default.noConflict(); _bluebird2.default.config({ warnings: false, longStackTraces: false }); _underscore2.default.extend(scrivito, { Promise: _bluebird2.default, promise: { enableDebugMode: function enableDebugMode() { _bluebird2.default.config({ warnings: true, longStackTraces: true }); }, wrapInJqueryDeferred: function wrapInJqueryDeferred(promise) { var d = $.Deferred(); promise.then(function (data) { return d.resolve(data); }, function (error) { d.reject(error); }); return d; }, always: function always(promise, callback) { promise.then(callback, callback); return promise; }, capturePromises: function capturePromises() { _bluebird2.default.setScheduler(function (promiseCallback) { scrivito.nextTick(promiseCallback); }); } } }); })(); /***/ }), /***/ 171: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { scrivito.PublicPromise = function () { _createClass(Promise, null, [{ key: "all", value: function all(promises) { return new scrivito.PublicPromise(scrivito.Promise.all(promises)); } }, { key: "race", value: function race(promises) { return new scrivito.PublicPromise(scrivito.Promise.race(promises)); } }, { key: "resolve", value: function resolve(valueOrThenable) { return new scrivito.PublicPromise(scrivito.Promise.resolve(valueOrThenable)); } }, { key: "reject", value: function reject(valueOrThenable) { return new scrivito.PublicPromise(scrivito.Promise.reject(valueOrThenable)); } }]); function Promise(promise) { _classCallCheck(this, Promise); this._internalPromise = promise; } _createClass(Promise, [{ key: "then", value: function then(resolve, reject) { return new scrivito.PublicPromise(this._internalPromise.then(resolve, reject)); } }, { key: "catch", value: function _catch(reject) { return new scrivito.PublicPromise(this._internalPromise.catch(reject)); } }]); return Promise; }(); })(); /***/ }), /***/ 172: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _errors = __webpack_require__(1); var _app_model_accessor = __webpack_require__(30); var _app_model_accessor2 = _interopRequireDefault(_app_model_accessor); var _app_class_validations = __webpack_require__(69); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var Realm = function () { _createClass(Realm, null, [{ key: 'init', value: function init(context) { var realm = new Realm(); context.Obj = realm.Obj; context.Widget = realm.Widget; context.Link = realm.Link; context.ObjSearchIterable = realm.ObjSearchIterable; context.appModelAccessor = realm.appModelAccessor; context.createObjClass = function () { return realm.createObjClass.apply(realm, arguments); }; context.createWidgetClass = function () { return realm.createWidgetClass.apply(realm, arguments); }; context.getClass = function () { return realm.getClass.apply(realm, arguments); }; context.registerClass = function () { return realm.registerClass.apply(realm, arguments); }; context.allObjClasses = function () { return realm.allObjClasses(); }; context.allWidgetClasses = function () { return realm.allWidgetClasses(); }; context._privateRealm = realm; } }]); function Realm() { _classCallCheck(this, Realm); this._registry = new scrivito.Registry(); this._registry.defaultClassForObjs = scrivito.ObjFactory(this._registry); this._registry.defaultClassForWidgets = scrivito.WidgetFactory(this._registry); this._registry.defaultClassForLinks = scrivito.LinkFactory(this._registry); this._registry.ObjSearchIterable = scrivito.ObjSearchIterableFactory(this._registry); this.appModelAccessor = new _app_model_accessor2.default(this._registry); } _createClass(Realm, [{ key: 'createObjClass', // public API value: function createObjClass(definition) { (0, _app_class_validations.assertValidObjClassDefinition)(definition, this.Obj); return this._createAppClass(definition, this.Obj); } // public API }, { key: 'createWidgetClass', value: function createWidgetClass(definition) { (0, _app_class_validations.assertValidWidgetClassDefinition)(definition, this.Widget); var onlyInside = definition.onlyInside; if (onlyInside) { delete definition.onlyInside; definition.validContainerClasses = [onlyInside]; } return this._createAppClass(definition, this.Widget); } // public API }, { key: 'getClass', value: function getClass(name) { return this._registry.getClass(name); } // public API }, { key: 'registerClass', value: function registerClass(name, appClass) { if (!appClass || !(0, _app_class_validations.isValidAppClass)(appClass, this.Obj, this.Widget)) { throw new _errors.ArgumentError('registerClass has to be called with a CMS Obj or Widget class.'); } this._registry.register(name, appClass); } }, { key: 'allObjClasses', value: function allObjClasses() { return this._registry.allObjClasses(); } }, { key: 'allWidgetClasses', value: function allWidgetClasses() { return this._registry.allWidgetClasses(); } }, { key: '_createAppClass', value: function _createAppClass(definition, defaultBaseClass) { var baseClass = definition.extend || defaultBaseClass; var appClass = scrivito.AppClassFactory(definition, baseClass); var name = definition.name; if (name) { this._registry.register(name, appClass); } return appClass; } }, { key: 'Obj', get: function get() { return this._registry.defaultClassForObjs; } }, { key: 'Widget', get: function get() { return this._registry.defaultClassForWidgets; } }, { key: 'Link', get: function get() { return this._registry.defaultClassForLinks; } }, { key: 'ObjSearchIterable', get: function get() { return this._registry.ObjSearchIterable; } }]); return Realm; }(); scrivito.Realm = Realm; })(); /***/ }), /***/ 173: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var Registry = function () { function Registry() { _classCallCheck(this, Registry); this._mapping = {}; } _createClass(Registry, [{ key: 'register', value: function register(name, klass) { this._mapping[name] = klass; } }, { key: 'getClass', value: function getClass(name) { return this._mapping[name]; } }, { key: 'allObjClasses', value: function allObjClasses() { return this._allForBaseClass(this.defaultClassForObjs); } }, { key: 'allWidgetClasses', value: function allWidgetClasses() { return this._allForBaseClass(this.defaultClassForWidgets); } }, { key: 'objClassFor', value: function objClassFor(name) { return this._appClassFor(name, this.defaultClassForObjs); } }, { key: 'widgetClassFor', value: function widgetClassFor(name) { return this._appClassFor(name, this.defaultClassForWidgets); } }, { key: 'objClassNameFor', value: function objClassNameFor(modelClass) { return _underscore2.default.findKey(this._mapping, function (klass) { return klass === modelClass; }); } }, { key: '_appClassFor', value: function _appClassFor(name, baseClass) { var appClass = this.getClass(name); if (appClass && baseClass.isPrototypeOf(appClass)) { return appClass; } return baseClass; } }, { key: '_allForBaseClass', value: function _allForBaseClass(baseClass) { return _underscore2.default.pick(this._mapping, function (modelClass) { return baseClass.isPrototypeOf(modelClass); }); } }]); return Registry; }(); scrivito.Registry = Registry; })(); /***/ }), /***/ 174: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var Schema = function () { _createClass(Schema, null, [{ key: 'forInstance', value: function forInstance(model) { return this.forClass(model.constructor); } }, { key: 'forClass', value: function forClass(klass) { return klass._scrivitoPrivateSchema; } }, { key: 'basicFieldFor', value: function basicFieldFor(model, attributeName) { var schema = Schema.forInstance(model); if (!schema) { return; } var typeInfo = schema.attributeDefinition(attributeName); if (!typeInfo) { return; } return model._scrivitoPrivateContent.field(attributeName, typeInfo); } }]); function Schema(definition, parent) { _classCallCheck(this, Schema); definition.attributes = definition.attributes || {}; if (parent._scrivitoPrivateSchema) { definition.attributes = _underscore2.default.extend({}, parent._scrivitoPrivateSchema.attributes, definition.attributes); } this.definition = definition; } _createClass(Schema, [{ key: 'attributeDefinition', value: function attributeDefinition(name) { var attrDefinition = this.attributes[name]; if (attrDefinition) { return scrivito.typeInfo.normalize(attrDefinition); } } }, { key: 'isBinary', value: function isBinary() { var _ref = this.attributeDefinition('blob') || [], _ref2 = _slicedToArray(_ref, 1), type = _ref2[0]; return type === 'binary'; } }, { key: 'attributes', get: function get() { return this.definition.attributes; } }, { key: 'name', get: function get() { return this.definition.name; } }, { key: 'validContainerClasses', get: function get() { return this.definition.validContainerClasses; } }]); return Schema; }(); scrivito.Schema = Schema; })(); /***/ }), /***/ 175: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _speakingurl = __webpack_require__(77); var _speakingurl2 = _interopRequireDefault(_speakingurl); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function slug(input) { return (0, _speakingurl2.default)(input); } scrivito.slug = slug; })(); /***/ }), /***/ 176: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var treeIdCounter = 0; // use native assign where available, since it's faster var assign = Object.assign || _underscore2.default.extend; // abstract interface for managing state var AbstractStateStore = function () { function AbstractStateStore() { _classCallCheck(this, AbstractStateStore); } _createClass(AbstractStateStore, [{ key: 'get', // return current state value: function get() { throw (0, _errors.InternalError)('implement in subclass'); } // change state }, { key: 'set', value: function set(_newState) { throw (0, _errors.InternalError)('implement in subclass'); } // get a string that uniquely identifies this state }, { key: 'id', value: function id() { throw (0, _errors.InternalError)('implement in subclass'); } // reset the state back to undefined }, { key: 'clear', value: function clear() { this.set(undefined); } }, { key: 'subState', value: function subState(key) { return new StateTreeNode(this, key); } }, { key: 'setSubState', value: function setSubState(key, newState) { var priorState = this.get(); if (priorState === undefined) { this.set(_defineProperty({}, key, newState)); } else { var type = typeof priorState === 'undefined' ? 'undefined' : _typeof(priorState); if (type !== 'object') { throw new _errors.InternalError('Tried to set substate of a ' + type); } var duplicate = assign({}, priorState); duplicate[key] = newState; this.set(duplicate); } } }, { key: 'getSubState', value: function getSubState(key) { var state = this.get(); if (state !== undefined) { return state[key]; } } }]); return AbstractStateStore; }(); // a state tree, which can be used to store state. // this is the root of the tree, which keeps the state of the entire tree. var StateTree = function (_AbstractStateStore) { _inherits(StateTree, _AbstractStateStore); function StateTree() { _classCallCheck(this, StateTree); var _this = _possibleConstructorReturn(this, (StateTree.__proto__ || Object.getPrototypeOf(StateTree)).call(this)); _this._id = (treeIdCounter++).toString(); _this.clearListeners(); _this._batchUpdates = false; _this._version = 0; return _this; } _createClass(StateTree, [{ key: 'get', value: function get() { return this._state; } }, { key: 'set', value: function set(newState) { this._state = newState; this._version++; if (!this._batchUpdates) { this._notifyListeners(); } } }, { key: 'currentVersion', value: function currentVersion() { return this._version; } }, { key: 'id', value: function id() { return this._id; } }, { key: 'subscribe', value: function subscribe(listener) { var _this2 = this; if (!listener) { throw new _errors.InternalError('subscribe needs an argument'); } var active = true; var guardedListener = function guardedListener() { if (active) { listener(); } }; this._ensureCanMutateListeners(); this._listeners.push(guardedListener); return function () { active = false; var index = _this2._listeners.indexOf(guardedListener); _this2._ensureCanMutateListeners(); _this2._listeners.splice(index, 1); }; } }, { key: 'withBatchedUpdates', value: function withBatchedUpdates(fn) { var stateBefore = this._state; var batchBefore = this._batchUpdates; try { this._batchUpdates = true; fn(); } finally { this._batchUpdates = batchBefore; if (!this._batchUpdates && stateBefore !== this._state) { this._notifyListeners(); } } } // For test purpose only. }, { key: 'listenerCount', value: function listenerCount() { return this._listeners.length; } // public for test purpose only. }, { key: 'clearListeners', value: function clearListeners() { this._listeners = []; } }, { key: '_notifyListeners', value: function _notifyListeners() { this._listenersToNotify = this._listeners; this._listenersToNotify.forEach(function (listener) { return listener(); }); } }, { key: '_ensureCanMutateListeners', value: function _ensureCanMutateListeners() { if (this._listenersToNotify === this._listeners) { // make shallow copy to avoid messing up a running notification loop this._listeners = this._listeners.slice(); } } }]); return StateTree; }(AbstractStateStore); // a node of a state tree. // does not actually keep state, but provides // access scoped to a subtree of a StateTree. var StateTreeNode = function (_AbstractStateStore2) { _inherits(StateTreeNode, _AbstractStateStore2); function StateTreeNode(parentState, key) { _classCallCheck(this, StateTreeNode); if (!_underscore2.default.isString(key)) { throw new _errors.InternalError(key + ' is not a string'); } var _this3 = _possibleConstructorReturn(this, (StateTreeNode.__proto__ || Object.getPrototypeOf(StateTreeNode)).call(this)); _this3._parentState = parentState; _this3._key = key; return _this3; } _createClass(StateTreeNode, [{ key: 'get', value: function get() { return this._parentState.getSubState(this._key); } }, { key: 'set', value: function set(newState) { this._parentState.setSubState(this._key, newState); } }, { key: 'id', value: function id() { // first convert backslash to double-backslash // then convert slash to backslash-slash var escapedKey = this._key.replace(/\\/g, '\\\\').replace(/\//g, '\\/'); return this._parentState.id() + '/' + escapedKey; } }]); return StateTreeNode; }(AbstractStateStore); // export class scrivito.StateTree = StateTree; })(); /***/ }), /***/ 177: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var TestHelper = { setup: function setup() { scrivito.client.init(); }, storeObjSearch: function storeObjSearch(_ref) { var query = _ref.query, objIds = _ref.objIds; query.store(objIds); }, storeObjFacetSearch: function storeObjFacetSearch(_ref2) { var query = _ref2.query, attribute = _ref2.attribute, facets = _ref2.facets, _ref2$options = _ref2.options, options = _ref2$options === undefined ? {} : _ref2$options; scrivito.FacetQuery.store(attribute, options, query.params.query, { total: 0, results: [], facets: [buildFacetApiResult(facets)] }); }, storeObjChildren: function storeObjChildren(_ref3) { var parentPath = _ref3.parentPath, objIds = _ref3.objIds; var query = scrivito.BasicObj.where('_parentPath', 'equals', parentPath); scrivito.TestHelper.storeObjSearch({ query: query, objIds: objIds }); } }; function buildFacetApiResult(facets) { return _underscore2.default.map(facets, function (_ref4) { var name = _ref4.name, count = _ref4.count, _ref4$includedObjIds = _ref4.includedObjIds, includedObjIds = _ref4$includedObjIds === undefined ? [] : _ref4$includedObjIds; var results = _underscore2.default.map(includedObjIds, function (id) { return { id: id }; }); return { value: name, total: count, results: results }; }); } scrivito.TestHelper = TestHelper; })(); /***/ }), /***/ 178: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var shouldBypassThrottle = false; function throttle(fn, ms, options) { return shouldBypassThrottle ? fn : _underscore2.default.throttle(fn, ms, options); } function bypassThrottle() { shouldBypassThrottle = true; } scrivito.throttle = throttle; scrivito.bypassThrottle = bypassThrottle; })(); /***/ }), /***/ 179: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { scrivito.typeInfo = { normalize: function normalize(typeInfo) { if (_underscore2.default.isString(typeInfo)) { return [typeInfo]; } if (_underscore2.default.isArray(typeInfo)) { return typeInfo; } throw new _errors.InternalError('Type Info needs to be a string or an array containing a string and optionally a hash'); }, normalizeAttrs: function normalizeAttrs(attributes) { var _this = this; return _underscore2.default.mapObject(attributes, function (_ref, name) { var _ref2 = _slicedToArray(_ref, 2), value = _ref2[0], typeInfo = _ref2[1]; if (scrivito.Attribute.isSystemAttribute(name)) { return [value]; } return [value, _this.normalize(typeInfo)]; }); }, unwrapAttributes: function unwrapAttributes(attributes) { return _underscore2.default.mapObject(attributes, function (_ref3) { var _ref4 = _slicedToArray(_ref3, 1), value = _ref4[0]; return value; }); } }; })(); /***/ }), /***/ 180: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); var _errors = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { var INTEGER_RANGE_START = -9007199254740991; var INTEGER_RANGE_END = 9007199254740991; var BACKEND_FORMAT_REGEXP = /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/; scrivito.types = { deserializeAsInteger: function deserializeAsInteger(value) { if (_underscore2.default.isString(value)) { if (value.match(/^-?\d+$/)) { return convertToInteger(value); } return null; } return convertToInteger(value); }, isValidInteger: function isValidInteger(value) { return isInteger(value) && INTEGER_RANGE_START <= value && value <= INTEGER_RANGE_END; }, isValidFloat: function isValidFloat(value) { return _underscore2.default.isNumber(value) && _underscore2.default.isFinite(value); }, deserializeAsDate: function deserializeAsDate(value) { if (!_underscore2.default.isString(value)) { return null; } if (!scrivito.types.isValidDateString(value)) { throw new _errors.InternalError('The value is not a valid ISO date time: "' + value + '"'); } return scrivito.types.parseStringToDate(value); }, parseStringToDate: function parseStringToDate(dateString) { if (!dateString) { return; } var _dateString$match = dateString.match(BACKEND_FORMAT_REGEXP), _dateString$match2 = _slicedToArray(_dateString$match, 7), _match = _dateString$match2[0], year = _dateString$match2[1], month = _dateString$match2[2], day = _dateString$match2[3], hours = _dateString$match2[4], minutes = _dateString$match2[5], seconds = _dateString$match2[6]; return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)); }, formatDateToString: function formatDateToString(date) { var yearMonth = '' + date.getUTCFullYear() + pad(date.getUTCMonth() + 1); var dateHours = '' + pad(date.getUTCDate()) + pad(date.getUTCHours()); var minutesSeconds = '' + pad(date.getUTCMinutes()) + pad(date.getUTCSeconds()); return '' + yearMonth + dateHours + minutesSeconds; }, isValidDateString: function isValidDateString(dateString) { return _underscore2.default.isString(dateString) && dateString.match(/^\d{14}$/); } }; function pad(number) { return number < 10 ? '0' + number : number; } function isInteger(value) { return _underscore2.default.isNumber(value) && _underscore2.default.isFinite(value) && Math.floor(value) === value; } function convertToInteger(valueFromBackend) { var intValue = parseInt(valueFromBackend, 10); if (intValue === 0) { return 0; // otherwise -0 could be returned. } else if (scrivito.types.isValidInteger(intValue)) { return intValue; } return null; } })(); /***/ }), /***/ 181: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _underscore = __webpack_require__(0); var _underscore2 = _interopRequireDefault(_underscore); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (function () { function wrapInAppClass(registry, internalValue) { if (_underscore2.default.isArray(internalValue)) { return _underscore2.default.map(internalValue, function (value) { return wrapInAppClass(registry, value); }); } if (internalValue instanceof scrivito.BasicObj) { return buildAppClassInstance(internalValue, registry.objClassFor(internalValue.objClass)); } if (internalValue instanceof scrivito.BasicWidget) { return buildAppClassInstance(internalValue, registry.widgetClassFor(internalValue.objClass)); } if (internalValue instanceof scrivito.BasicLink) { return registry.defaultClassForLinks.build(internalValue.buildAttributes()); } return internalValue; } function buildAppClassInstance(internalValue, appClass) { var externalValue = Object.create(appClass.prototype); externalValue._scrivitoPrivateContent = internalValue; return externalValue; } function unwrapAppClassValues(values) { if (_underscore2.default.isArray(values)) { return _underscore2.default.map(values, unwrapSingleValue); } return unwrapSingleValue(values); } function unwrapSingleValue(value) { if (value && value._scrivitoPrivateContent) { return value._scrivitoPrivateContent; } return value; } scrivito.wrapInAppClass = wrapInAppClass; scrivito.unwrapAppClassValues = unwrapAppClassValues; scrivito.buildAppClassInstance = buildAppClassInstance; })(); /***/ }), /***/ 182: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ReferenceEditor = function () { _createClass(ReferenceEditor, null, [{ key: 'canEdit', value: function canEdit(_ref) { var type = _ref.type; return type === 'reference'; } }]); function ReferenceEditor(_ref2) { var controller = _ref2.controller; _classCallCheck(this, ReferenceEditor); this._controller = controller; } _createClass(ReferenceEditor, [{ key: 'onClick', value: function onClick() { var _this = this; scrivito.content_browser.open({ selection: this._currentSelection(), selection_mode: 'single' }).then(function (ids) { return _this._saveContentBrowserSelection(ids); }); } }, { key: '_currentSelection', value: function _currentSelection() { return this._controller.content ? [this._controller.content.id] : []; } }, { key: '_saveContentBrowserSelection', value: function _saveContentBrowserSelection(ids) { this._controller.content = ids[0] || null; } }]); return ReferenceEditor; }(); exports.default = ReferenceEditor; /***/ }), /***/ 183: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _html_editor = __webpack_require__(106); var _html_editor2 = _interopRequireDefault(_html_editor); var _reference_editor = __webpack_require__(182); var _reference_editor2 = _interopRequireDefault(_reference_editor); var _string_editor = __webpack_require__(108); var _string_editor2 = _interopRequireDefault(_string_editor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } scrivito.registerEditor(_html_editor2.default); scrivito.registerEditor(_reference_editor2.default); scrivito.registerEditor(_string_editor2.default); /***/ }), /***/ 184: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _current_page = __webpack_require__(9); var _provide_ui_config = __webpack_require__(36); var _configure = __webpack_require__(54); var _configure2 = _interopRequireDefault(_configure); var _load = __webpack_require__(6); var _load2 = _interopRequireDefault(_load); var _binary = __webpack_require__(12); var _binary2 = _interopRequireDefault(_binary); var _future_binary = __webpack_require__(21); var _future_binary2 = _interopRequireDefault(_future_binary); var _obj_facet_value = __webpack_require__(37); var _obj_facet_value2 = _interopRequireDefault(_obj_facet_value); var _errors = __webpack_require__(1); var _errors2 = __webpack_require__(63); var _provide_component = __webpack_require__(68); var _child_list = __webpack_require__(60); var _child_list2 = _interopRequireDefault(_child_list); var _content = __webpack_require__(38); var _content2 = _interopRequireDefault(_content); var _current_page2 = __webpack_require__(62); var _current_page3 = _interopRequireDefault(_current_page2); var _image = __webpack_require__(64); var _image2 = _interopRequireDefault(_image); var _link = __webpack_require__(40); var _link2 = _interopRequireDefault(_link); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Scrivito = {}; Scrivito.configure = _configure2.default; Scrivito.createComponent = _provide_component.createComponent; Scrivito.currentPage = _current_page.currentPage; Scrivito.load = _load2.default; Scrivito.navigateTo = _current_page.navigateTo; Scrivito.provideComponent = _provide_component.provideComponent; Scrivito.provideUiConfig = _provide_ui_config.provideUiConfig; Scrivito.Binary = _binary2.default; Scrivito.FutureBinary = _future_binary2.default; Scrivito.ObjFacetValue = _obj_facet_value2.default; Scrivito.ArgumentError = _errors.ArgumentError; Scrivito.ResourceNotFoundError = _errors.ResourceNotFoundError; Scrivito.ScrivitoError = _errors.ScrivitoError; Scrivito.TransformationSourceInvalidError = _errors.TransformationSourceInvalidError; Scrivito.TransformationSourceTooLargeError = _errors.TransformationSourceTooLargeError; Scrivito.React = {}; Scrivito.React.ChildList = _child_list2.default; Scrivito.React.Content = _content2.default; Scrivito.React.CurrentPage = _current_page3.default; Scrivito.React.Image = _image2.default; Scrivito.React.InternalErrorPage = _errors2.InternalErrorPage; Scrivito.React.Link = _link2.default; Scrivito.React.NotFoundErrorPage = _errors2.NotFoundErrorPage; window.Scrivito = Scrivito; /***/ }), /***/ 185: /***/ (function(module, exports, __webpack_require__) { "use strict"; //= require_self //= require ./react/prop_types //= require ./react/create_react_class //= require_tree ./react (function () { scrivito.React = {}; })(); /***/ }), /***/ 186: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _window_registry = __webpack_require__(20); (function () { var registry = {}; var componentRegistry = { provideComponentClass: function provideComponentClass(appClass, componentClass) { registry[registryKeyFor(appClass)] = componentClass; }, getComponentClass: function getComponentClass(appClass) { return registry[registryKeyFor(appClass)]; }, // For test purpose only. clear: function clear() { registry = {}; } }; function registryKeyFor(appClass) { return (0, _window_registry.getWindowRegistry)().objClassNameFor(appClass); } scrivito.componentRegistry = componentRegistry; })(); /***/ }), /***/ 187: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function () { var EditorEvent = function () { function EditorEvent(internalEvent) { _classCallCheck(this, EditorEvent); this._internalEvent = internalEvent; } _createClass(EditorEvent, [{ key: "preventDefault", value: function preventDefault() { this._internalEvent.preventDefault(); } }, { key: "stopPropagation", value: function stopPropagation() { this._internalEvent.stopPropagation(); } }]); return EditorEvent; }(); scrivito.EditorEvent = EditorEvent; })(); /***/ }), /***/ 188: /***/ (function(module, exports, __webpack_require__) { "use strict"; var _window_context = __webpack_require__(10); var _errors = __webpack_require__(1); (function () { var REG_EXP = /\bobjid:([a-f0-9]{16})\b([^"']*)/g; var knownLinks = {}; var InternalLinks = { transformHTML: function transformHTML(htmlString) { return htmlString.replace(REG_EXP, function (_match, objId) { var getObj = function getObj() { return (0, _window_context.getWindowContext)().Obj.get(objId); }; try { var url = scrivito.loadWithDefault(undefined, function () { return scrivito.urlFor(getObj()); }); if (url) { knownLinks[url] = getObj(); return url; } url = '#__LOADING_OBJ_WITH_ID_' + objId; knownLinks[url] = getObj; return url; } catch (error) { if (error instanceof _errors.ResourceNotFoundError) { return '#__MISSING_OBJ_WITH_ID_' + objId; } throw error; } }); }, findTarget: function findTarget(currentNode, outermostNode) { if (currentNode === outermostNode) { return null; } if (currentNode.nodeName === 'A') { var target = knownLinks[currentNode.pathname] || knownLinks[currentNode.hash]; if (target) { return target; } } return this.findTarget(currentNode.parentNode, outermostNode); }, // For test purpose only. reset: function reset() { knownLinks = {}; } }; scrivito.InternalLinks = InternalLinks; })(); /***/ }), /***/ 189: /***/ (function(module, exports, __webpack_require__) { "use strict"; (function () { var currentFocus = void 0; var currentToken = 0; var handlers = {}; var WidgetFocus = { subscribe: function subscribe(_ref) { var onFocus = _ref.onFocus, onBlur = _ref.onBlur; var token = currentToken; handlers[token] = { onFocus: onFocus, onBlur: onBlur }; currentToken += 1; return token; }, unsubscribe: function unsubscribe(token) { delete handlers[token]; }, notifyFocus: function notifyFocus(token) { currentFocus = token; handlers[currentFocus].onFocus(); }, notifyBlur: function notifyBlur(token) { // Performance optimization: Only re-render the widget, which lost the focus. if (token === currentFocus) { handlers[token].onBlur(); } }, // For test purpose only. get handlers() { return handlers; }, // For test purpose only. reset: function reset() { currentFocus = undefined; currentToken = 0; handlers = {}; } }; scrivito.WidgetFocus = WidgetFocus; })(); /***/ }), /***/ 190: /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2015 Petka Antonov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * bluebird build version 3.4.7 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if(true)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = Async; module.exports.firstLineError = firstLineError; },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { if (!calledBind) { calledBind = true; Promise.prototype._propagateFrom = debug.propagateFromFunction(); Promise.prototype._boundValue = debug.boundValueFunction(); } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( bindingResolved, bindingRejected, undefined, ret, context); ret._setOnCancel(maybePromise); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { return Promise.resolve(value).bind(thisArg); }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise":22}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; if (false) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var args = [].slice.call(arguments, 1);; if (false) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util":36}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; Promise.prototype["break"] = Promise.prototype.cancel = function() { if (!debug.cancellation()) return this._warn("cancellation is disabled"); var promise = this; var child = promise; while (promise._isCancellable()) { if (!promise._cancelBy(child)) { if (child._isFollowing()) { child._followee().cancel(); } else { child._cancelBranched(); } break; } var parent = promise._cancellationParent; if (parent == null || !parent._isCancellable()) { if (promise._isFollowing()) { promise._followee().cancel(); } else { promise._cancelBranched(); } break; } else { if (promise._isFollowing()) promise._followee().cancel(); promise._setWillBeCancelled(); child = promise; promise = parent; } } }; Promise.prototype._branchHasCancelled = function() { this._branchesRemainingToCancel--; }; Promise.prototype._enoughBranchesHaveCancelled = function() { return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; }; Promise.prototype._cancelBy = function(canceller) { if (canceller === this) { this._branchesRemainingToCancel = 0; this._invokeOnCancel(); return true; } else { this._branchHasCancelled(); if (this._enoughBranchesHaveCancelled()) { this._invokeOnCancel(); return true; } } return false; }; Promise.prototype._cancelBranched = function() { if (this._enoughBranchesHaveCancelled()) { this._cancel(); } }; Promise.prototype._cancel = function() { if (!this._isCancellable()) return; this._setCancelled(); async.invoke(this._cancelPromises, this, undefined); }; Promise.prototype._cancelPromises = function() { if (this._length() > 0) this._settlePromises(); }; Promise.prototype._unsetOnCancel = function() { this._onCancelField = undefined; }; Promise.prototype._isCancellable = function() { return this.isPending() && !this._isCancelled(); }; Promise.prototype.isCancellable = function() { return this.isPending() && !this.isCancelled(); }; Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { if (util.isArray(onCancelCallback)) { for (var i = 0; i < onCancelCallback.length; ++i) { this._doInvokeOnCancel(onCancelCallback[i], internalOnly); } } else if (onCancelCallback !== undefined) { if (typeof onCancelCallback === "function") { if (!internalOnly) { var e = tryCatch(onCancelCallback).call(this._boundValue()); if (e === errorObj) { this._attachExtraTrace(e.e); async.throwLater(e.e); } } } else { onCancelCallback._resultCancelled(this); } } }; Promise.prototype._invokeOnCancel = function() { var onCancelCallback = this._onCancel(); this._unsetOnCancel(); async.invoke(this._doInvokeOnCancel, this, onCancelCallback); }; Promise.prototype._invokeInternalOnCancel = function() { if (this._isCancellable()) { this._doInvokeOnCancel(this._onCancel(), true); this._unsetOnCancel(); } }; Promise.prototype._resultCancelled = function() { this.cancel(); }; }; },{"./util":36}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util"); var getKeys = _dereq_("./es5").keys; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function catchFilter(instances, cb, promise) { return function(e) { var boundTo = promise._boundValue(); predicateLoop: for (var i = 0; i < instances.length; ++i) { var item = instances[i]; if (item === Error || (item != null && item.prototype instanceof Error)) { if (e instanceof item) { return tryCatch(cb).call(boundTo, e); } } else if (typeof item === "function") { var matchesPredicate = tryCatch(item).call(boundTo, e); if (matchesPredicate === errorObj) { return matchesPredicate; } else if (matchesPredicate) { return tryCatch(cb).call(boundTo, e); } } else if (util.isObject(e)) { var keys = getKeys(item); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; if (item[key] != e[key]) { continue predicateLoop; } } return tryCatch(cb).call(boundTo, e); } } return NEXT_FILTER; }; } return catchFilter; }; },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var longStackTraces = false; var contextStack = []; Promise.prototype._promiseCreated = function() {}; Promise.prototype._pushContext = function() {}; Promise.prototype._popContext = function() {return null;}; Promise._peekContext = Promise.prototype._peekContext = function() {}; function Context() { this._trace = new Context.CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (this._trace !== undefined) { this._trace._promiseCreated = null; contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (this._trace !== undefined) { var trace = contextStack.pop(); var ret = trace._promiseCreated; trace._promiseCreated = null; return ret; } return null; }; function createContext() { if (longStackTraces) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Context.CapturedTrace = null; Context.create = createContext; Context.deactivateLongStackTraces = function() {}; Context.activateLongStackTraces = function() { var Promise_pushContext = Promise.prototype._pushContext; var Promise_popContext = Promise.prototype._popContext; var Promise_PeekContext = Promise._peekContext; var Promise_peekContext = Promise.prototype._peekContext; var Promise_promiseCreated = Promise.prototype._promiseCreated; Context.deactivateLongStackTraces = function() { Promise.prototype._pushContext = Promise_pushContext; Promise.prototype._popContext = Promise_popContext; Promise._peekContext = Promise_PeekContext; Promise.prototype._peekContext = Promise_peekContext; Promise.prototype._promiseCreated = Promise_promiseCreated; longStackTraces = false; }; longStackTraces = true; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; Promise._peekContext = Promise.prototype._peekContext = peekContext; Promise.prototype._promiseCreated = function() { var ctx = this._peekContext(); if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; }; }; return Context; }; },{}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, Context) { var getDomain = Promise._getDomain; var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var printWarning; var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development")); var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | 524288); }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._setReturnedNonUndefined = function() { this._bitField = this._bitField | 268435456; }; Promise.prototype._returnedNonUndefined = function() { return (this._bitField & 268435456) !== 0; }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._settledValue(); this._setUnhandledRejectionIsNotified(); fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 262144; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~262144); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 1048576; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~1048576); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { return warn(message, shouldUseOwnTrace, promise || this); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : util.domainBind(domain, fn)) : undefined; }; var disableLongStackTraces = function() {}; Promise.longStackTraces = function () { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (!config.longStackTraces && longStackTracesIsSupported()) { var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; config.longStackTraces = true; disableLongStackTraces = function() { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Context.deactivateLongStackTraces(); async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Context.activateLongStackTraces(); async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; var fireDomEvent = (function() { try { if (typeof CustomEvent === "function") { var event = new CustomEvent("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new CustomEvent(name.toLowerCase(), { detail: event, cancelable: true }); return !util.global.dispatchEvent(domEvent); }; } else if (typeof Event === "function") { var event = new Event("CustomEvent"); util.global.dispatchEvent(event); return function(name, event) { var domEvent = new Event(name.toLowerCase(), { cancelable: true }); domEvent.detail = event; return !util.global.dispatchEvent(domEvent); }; } else { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { var domEvent = document.createEvent("CustomEvent"); domEvent.initCustomEvent(name.toLowerCase(), false, true, event); return !util.global.dispatchEvent(domEvent); }; } } catch (e) {} return function() { return false; }; })(); var fireGlobalEvent = (function() { if (util.isNode) { return function() { return process.emit.apply(process, arguments); }; } else { if (!util.global) { return function() { return false; }; } return function(name) { var methodName = "on" + name.toLowerCase(); var method = util.global[methodName]; if (!method) return false; method.apply(util.global, [].slice.call(arguments, 1)); return true; }; } })(); function generatePromiseLifecycleEventObject(name, promise) { return {promise: promise}; } var eventToObjectGenerator = { promiseCreated: generatePromiseLifecycleEventObject, promiseFulfilled: generatePromiseLifecycleEventObject, promiseRejected: generatePromiseLifecycleEventObject, promiseResolved: generatePromiseLifecycleEventObject, promiseCancelled: generatePromiseLifecycleEventObject, promiseChained: function(name, promise, child) { return {promise: promise, child: child}; }, warning: function(name, warning) { return {warning: warning}; }, unhandledRejection: function (name, reason, promise) { return {reason: reason, promise: promise}; }, rejectionHandled: generatePromiseLifecycleEventObject }; var activeFireEvent = function (name) { var globalEventFired = false; try { globalEventFired = fireGlobalEvent.apply(null, arguments); } catch (e) { async.throwLater(e); globalEventFired = true; } var domEventFired = false; try { domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments)); } catch (e) { async.throwLater(e); domEventFired = true; } return domEventFired || globalEventFired; }; Promise.config = function(opts) { opts = Object(opts); if ("longStackTraces" in opts) { if (opts.longStackTraces) { Promise.longStackTraces(); } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { disableLongStackTraces(); } } if ("warnings" in opts) { var warningsOption = opts.warnings; config.warnings = !!warningsOption; wForgottenReturn = config.warnings; if (util.isObject(warningsOption)) { if ("wForgottenReturn" in warningsOption) { wForgottenReturn = !!warningsOption.wForgottenReturn; } } } if ("cancellation" in opts && opts.cancellation && !config.cancellation) { if (async.haveItemsQueued()) { throw new Error( "cannot enable cancellation after promises are in use"); } Promise.prototype._clearCancellationData = cancellationClearCancellationData; Promise.prototype._propagateFrom = cancellationPropagateFrom; Promise.prototype._onCancel = cancellationOnCancel; Promise.prototype._setOnCancel = cancellationSetOnCancel; Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; Promise.prototype._execute = cancellationExecute; propagateFromFunction = cancellationPropagateFrom; config.cancellation = true; } if ("monitoring" in opts) { if (opts.monitoring && !config.monitoring) { config.monitoring = true; Promise.prototype._fireEvent = activeFireEvent; } else if (!opts.monitoring && config.monitoring) { config.monitoring = false; Promise.prototype._fireEvent = defaultFireEvent; } } return Promise; }; function defaultFireEvent() { return false; } Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._execute = function(executor, resolve, reject) { try { executor(resolve, reject); } catch (e) { return e; } }; Promise.prototype._onCancel = function () {}; Promise.prototype._setOnCancel = function (handler) { ; }; Promise.prototype._attachCancellationCallback = function(onCancel) { ; }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; ; }; function cancellationExecute(executor, resolve, reject) { var promise = this; try { executor(resolve, reject, function(onCancel) { if (typeof onCancel !== "function") { throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); } promise._attachCancellationCallback(onCancel); }); } catch (e) { return e; } } function cancellationAttachCancellationCallback(onCancel) { if (!this._isCancellable()) return this; var previousOnCancel = this._onCancel(); if (previousOnCancel !== undefined) { if (util.isArray(previousOnCancel)) { previousOnCancel.push(onCancel); } else { this._setOnCancel([previousOnCancel, onCancel]); } } else { this._setOnCancel(onCancel); } } function cancellationOnCancel() { return this._onCancelField; } function cancellationSetOnCancel(onCancel) { this._onCancelField = onCancel; } function cancellationClearCancellationData() { this._cancellationParent = undefined; this._onCancelField = undefined; } function cancellationPropagateFrom(parent, flags) { if ((flags & 1) !== 0) { this._cancellationParent = parent; var branchesRemainingToCancel = parent._branchesRemainingToCancel; if (branchesRemainingToCancel === undefined) { branchesRemainingToCancel = 0; } parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; } if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } function bindingPropagateFrom(parent, flags) { if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } var propagateFromFunction = bindingPropagateFrom; function boundValueFunction() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; } function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } function longStackTracesAttachExtraTrace(error, ignoreSelf) { if (canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } } function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) { if (parent !== undefined && parent._returnedNonUndefined()) return; if ((promise._bitField & 65535) === 0) return; if (name) name = name + " "; var handlerLine = ""; var creatorLine = ""; if (promiseCreated._trace) { var traceLines = promiseCreated._trace.stack.split("\n"); var stack = cleanStack(traceLines); for (var i = stack.length - 1; i >= 0; --i) { var line = stack[i]; if (!nodeFramePattern.test(line)) { var lineMatches = line.match(parseLinePattern); if (lineMatches) { handlerLine = "at " + lineMatches[1] + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; } break; } } if (stack.length > 0) { var firstUserLine = stack[0]; for (var i = 0; i < traceLines.length; ++i) { if (traceLines[i] === firstUserLine) { if (i > 0) { creatorLine = "\n" + traceLines[i - 1]; } break; } } } } var msg = "a promise was created in a " + name + "handler " + handlerLine + "but was not returned from it, " + "see http://goo.gl/rRqMUw" + creatorLine; promise._warn(msg, true, promiseCreated); } } function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; if (replacement) message += " Use " + replacement + " instead."; return warn(message); } function warn(message, shouldUseOwnTrace, promise) { if (!config.warnings) return; var warning = new Warning(message); var ctx; if (shouldUseOwnTrace) { promise._attachExtraTrace(warning); } else if (config.longStackTraces && (ctx = Promise._peekContext())) { ctx.attachExtraTrace(warning); } else { var parsed = parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } if (!activeFireEvent("warning", warning)) { formatAndLogError(warning, "", true); } } function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0 && error.name != "SyntaxError") { stack = stack.slice(i); } return stack; } function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: error.name == "SyntaxError" ? stack : cleanStack(stack) }; } function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof printWarning === "function") { printWarning(message, isSoft); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } } function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } if (name === "unhandledRejection") { if (!activeFireEvent(name, reason, promise) && !localEventFired) { formatAndLogError(reason, "Unhandled rejection "); } } else { activeFireEvent(name, promise); } } function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } function longStackTracesIsSupported() { return typeof captureStackTrace === "function"; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; } function CapturedTrace(parent) { this._parent = parent; this._promisesCreated = 0; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); Context.CapturedTrace = CapturedTrace; CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit -= 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit -= 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { printWarning = function(message, isSoft) { var color = isSoft ? "\u001b[33m" : "\u001b[31m"; console.warn(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { printWarning = function(message, isSoft) { console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); }; } } var config = { warnings: warnings, longStackTraces: false, cancellation: false, monitoring: false }; if (longStackTraces) Promise.longStackTraces(); return { longStackTraces: function() { return config.longStackTraces; }, warnings: function() { return config.warnings; }, cancellation: function() { return config.cancellation; }, monitoring: function() { return config.monitoring; }, propagateFromFunction: function() { return propagateFromFunction; }, boundValueFunction: function() { return boundValueFunction; }, checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, CapturedTrace: CapturedTrace, fireDomEvent: fireDomEvent, fireGlobalEvent: fireGlobalEvent }; }; },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function returner() { return this.value; } function thrower() { throw this.reason; } Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { return this._then( thrower, undefined, undefined, {reason: reason}, undefined); }; Promise.prototype.catchThrow = function (reason) { if (arguments.length <= 1) { return this._then( undefined, thrower, undefined, {reason: reason}, undefined); } else { var _reason = arguments[1]; var handler = function() {throw _reason;}; return this.caught(reason, handler); } }; Promise.prototype.catchReturn = function (value) { if (arguments.length <= 1) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( undefined, returner, undefined, {value: value}, undefined); } else { var _value = arguments[1]; if (_value instanceof Promise) _value.suppressUnhandledRejections(); var handler = function() {return _value;}; return this.caught(value, handler); } }; }; },{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return PromiseReduce(this, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseReduce(promises, fn, INTERNAL, 0) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; },{}],12:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); es5.defineProperty(Error, "__BluebirdErrorTypes__", { value: errorTypes, writable: false, enumerable: false, configurable: false }); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, tryConvertToPromise) { var util = _dereq_("./util"); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; function PassThroughHandlerContext(promise, type, handler) { this.promise = promise; this.type = type; this.handler = handler; this.called = false; this.cancelPromise = null; } PassThroughHandlerContext.prototype.isFinallyHandler = function() { return this.type === 0; }; function FinallyHandlerCancelReaction(finallyHandler) { this.finallyHandler = finallyHandler; } FinallyHandlerCancelReaction.prototype._resultCancelled = function() { checkCancel(this.finallyHandler); }; function checkCancel(ctx, reason) { if (ctx.cancelPromise != null) { if (arguments.length > 1) { ctx.cancelPromise._reject(reason); } else { ctx.cancelPromise._cancel(); } ctx.cancelPromise = null; return true; } return false; } function succeed() { return finallyHandler.call(this, this.promise._target()._settledValue()); } function fail(reason) { if (checkCancel(this, reason)) return; errorObj.e = reason; return errorObj; } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; if (!this.called) { this.called = true; var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); if (ret !== undefined) { promise._setReturnedNonUndefined(); var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { if (this.cancelPromise != null) { if (maybePromise._isCancelled()) { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); errorObj.e = reason; return errorObj; } else if (maybePromise.isPending()) { maybePromise._attachCancellationCallback( new FinallyHandlerCancelReaction(this)); } } return maybePromise._then( succeed, fail, undefined, this, undefined); } } } if (promise.isRejected()) { checkCancel(this); errorObj.e = reasonOrValue; return errorObj; } else { checkCancel(this); return reasonOrValue; } } Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThrough(handler, 0, finallyHandler, finallyHandler); }; Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; return PassThroughHandlerContext; }; },{"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = _dereq_("./errors"); var TypeError = errors.TypeError; var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { if (debug.cancellation()) { var internal = new Promise(INTERNAL); var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); this._promise = internal.lastly(function() { return _finallyPromise; }); internal._captureStackTrace(); internal._setOnCancel(this); } else { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); } this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; this._cancellationPhase = false; } util.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this._promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; if (debug.cancellation() && this._finallyPromise !== null) { this._finallyPromise._fulfill(); this._finallyPromise = null; } }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } this._cancellationPhase = true; this._yieldedPromise = null; this._continue(result); }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._rejectCallback(result.e, false); } } var value = result.value; if (result.done === true) { this._cleanup(); if (this._cancellationPhase) { return promise.cancel(); } else { return promise._resolveCallback(value); } } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { Promise._async.invoke( this._promiseFulfilled, this, maybePromise._value() ); } else if (((bitField & 16777216) !== 0)) { Promise._async.invoke( this._promiseRejected, this, maybePromise._reason() ); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; var reject; if (false) { if (canEvaluate) { var thenCallback = function(i) { return new Function("value", "holder", " \n\ 'use strict'; \n\ holder.pIndex = value; \n\ holder.checkFulfillment(this); \n\ ".replace(/Index/g, i)); }; var promiseSetter = function(i) { return new Function("promise", "holder", " \n\ 'use strict'; \n\ holder.pIndex = promise; \n\ ".replace(/Index/g, i)); }; var generateHolderClass = function(total) { var props = new Array(total); for (var i = 0; i < props.length; ++i) { props[i] = "this.p" + (i+1); } var assignment = props.join(" = ") + " = null;"; var cancellationCode= "var promise;\n" + props.map(function(prop) { return " \n\ promise = " + prop + "; \n\ if (promise instanceof Promise) { \n\ promise.cancel(); \n\ } \n\ "; }).join("\n"); var passedArguments = props.join(", "); var name = "Holder$" + total; var code = "return function(tryCatch, errorObj, Promise, async) { \n\ 'use strict'; \n\ function [TheName](fn) { \n\ [TheProperties] \n\ this.fn = fn; \n\ this.asyncNeeded = true; \n\ this.now = 0; \n\ } \n\ \n\ [TheName].prototype._callFunction = function(promise) { \n\ promise._pushContext(); \n\ var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ promise._popContext(); \n\ if (ret === errorObj) { \n\ promise._rejectCallback(ret.e, false); \n\ } else { \n\ promise._resolveCallback(ret); \n\ } \n\ }; \n\ \n\ [TheName].prototype.checkFulfillment = function(promise) { \n\ var now = ++this.now; \n\ if (now === [TheTotal]) { \n\ if (this.asyncNeeded) { \n\ async.invoke(this._callFunction, this, promise); \n\ } else { \n\ this._callFunction(promise); \n\ } \n\ \n\ } \n\ }; \n\ \n\ [TheName].prototype._resultCancelled = function() { \n\ [CancellationCode] \n\ }; \n\ \n\ return [TheName]; \n\ }(tryCatch, errorObj, Promise, async); \n\ "; code = code.replace(/\[TheName\]/g, name) .replace(/\[TheTotal\]/g, total) .replace(/\[ThePassedArguments\]/g, passedArguments) .replace(/\[TheProperties\]/g, assignment) .replace(/\[CancellationCode\]/g, cancellationCode); return new Function("tryCatch", "errorObj", "Promise", "async", code) (tryCatch, errorObj, Promise, async); }; var holderClasses = []; var thenCallbacks = []; var promiseSetters = []; for (var i = 0; i < 8; ++i) { holderClasses.push(generateHolderClass(i + 1)); thenCallbacks.push(thenCallback(i + 1)); promiseSetters.push(promiseSetter(i + 1)); } reject = function (reason) { this._reject(reason); }; }} Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (false) { if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var HolderClass = holderClasses[last - 1]; var holder = new HolderClass(fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); promiseSetters[i](maybePromise, holder); holder.asyncNeeded = false; } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); } else { ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } if (!ret._isFateSealed()) { if (holder.asyncNeeded) { var domain = getDomain(); if (domain !== null) { holder.fn = util.domainBind(domain, holder.fn); } } ret._setAsyncGuaranteed(); ret._setOnCancel(holder); } return ret; } } } var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : util.domainBind(domain, fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = []; async.invoke(this._asyncInit, this, undefined); } util.inherits(MappingPromiseArray, PromiseArray); MappingPromiseArray.prototype._asyncInit = function() { this._init$(undefined, -2); }; MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (index < 0) { index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return false; } if (preservedValues !== null) preservedValues[index] = value; var promise = this._promise; var callback = this._callback; var receiver = promise._boundValue(); promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise ); if (ret === errorObj) { this._reject(ret.e); return true; } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; values[index] = maybePromise; maybePromise._proxy(this, (index + 1) * -1); return false; } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); } else if (((bitField & 16777216) !== 0)) { this._reject(maybePromise._reason()); return true; } else { this._cancel(); return true; } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } return true; } return false; }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var limit = 0; if (options !== undefined) { if (typeof options === "object" && options !== null) { if (typeof options.concurrency !== "number") { return Promise.reject( new TypeError("'concurrency' must be a number but it is " + util.classString(options.concurrency))); } limit = options.concurrency; } else { return Promise.reject(new TypeError( "options argument must be an object but it is " + util.classString(options))); } } limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } Promise.prototype.map = function (fn, options) { return map(this, fn, options, null); }; Promise.map = function (promises, fn, options, _filter) { return map(promises, fn, options, _filter); }; }; },{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value; if (arguments.length > 1) { debug.deprecated("calling Promise.try with more than 1 argument"); var arg = arguments[1]; var ctx = arguments[2]; value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); } else { value = tryCatch(fn)(); } var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.try", ret); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; },{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise, multiArgs) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (!multiArgs) { promise._fulfill(value); } else { var args = [].slice.call(arguments, 1);; promise._fulfill(args); } promise = null; }; } module.exports = nodebackForPromise; },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util"); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; },{"./util":36}],22:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = _dereq_("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = _dereq_("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var nodebackForPromise = _dereq_("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } if (self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } } function Promise(executor) { this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; if (executor !== INTERNAL) { check(this, executor); this._resolveFromExecutor(executor); } this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("expecting an object but got " + "A catch statement predicate " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } return async.setScheduler(fn); }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && util.domainBind(domain, handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setWillBeCancelled = function() { this._bitField = this._bitField | 8388608; }; Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : util.domainBind(domain, reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : util.domainBind(domain, reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); Promise.Promise = Promise; Promise.version = "3.4.7"; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./call_get.js')(Promise); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./timers.js')(Promise, INTERNAL, debug); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./filter.js')(Promise, INTERNAL); _dereq_('./each.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { var util = _dereq_("./util"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); } promise._setOnCancel(this); this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } util.inherits(PromiseArray, Proxyable); PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); var bitField = values._bitField; ; this._values = values; if (((bitField & 50397184) === 0)) { this._promise._setAsyncGuaranteed(); return values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); } else if (((bitField & 33554432) !== 0)) { values = values._value(); } else if (((bitField & 16777216) !== 0)) { return this._reject(values._reason()); } else { return this._cancel(); } } values = util.asArray(values); if (values === null) { var err = apiRejection( "expecting an array or an iterable object but got " + util.classString(values)).reason(); this._promise._rejectCallback(err, false); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } this._iterate(values); }; PromiseArray.prototype._iterate = function(values) { var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var result = this._promise; var isResolved = false; var bitField = null; for (var i = 0; i < len; ++i) { var maybePromise = tryConvertToPromise(values[i], result); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); bitField = maybePromise._bitField; } else { bitField = null; } if (isResolved) { if (bitField !== null) { maybePromise.suppressUnhandledRejections(); } } else if (bitField !== null) { if (((bitField & 50397184) === 0)) { maybePromise._proxy(this, i); this._values[i] = maybePromise; } else if (((bitField & 33554432) !== 0)) { isResolved = this._promiseFulfilled(maybePromise._value(), i); } else if (((bitField & 16777216) !== 0)) { isResolved = this._promiseRejected(maybePromise._reason(), i); } else { isResolved = this._promiseCancelled(i); } } else { isResolved = this._promiseFulfilled(maybePromise, i); } } if (!isResolved) result._setAsyncGuaranteed(); }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype._cancel = function() { if (this._isResolved() || !this._promise._isCancellable()) return; this._values = null; this._promise._cancel(); }; PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; PromiseArray.prototype._promiseCancelled = function() { this._cancel(); return true; }; PromiseArray.prototype._promiseRejected = function (reason) { this._totalResolved++; this._reject(reason); return true; }; PromiseArray.prototype._resultCancelled = function() { if (this._isResolved()) return; var values = this._values; this._cancel(); if (values instanceof Promise) { values.cancel(); } else { for (var i = 0; i < values.length; ++i) { if (values[i] instanceof Promise) { values[i].cancel(); } } } }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util"); var nodebackForPromise = _dereq_("./nodeback"); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; if (false) { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var isObject = util.isObject; var es5 = _dereq_("./es5"); var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, -3); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; },{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : util.domainBind(domain, fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; if(_each === INTERNAL) { this._eachValues = Array(this._length); } else if (_each === 0) { this._eachValues = null; } else { this._eachValues = undefined; } this._promise._captureStackTrace(); this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && this._eachValues !== null && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { if (this._eachValues !== null) { this._eachValues.push(value); } return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; },{"./util":36}],29:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var NativePromise = util.getNativePromise(); if (util.isNode && typeof MutationObserver === "undefined") { var GlobalSetImmediate = global.setImmediate; var ProcessNextTick = process.nextTick; schedule = util.isRecentNode ? function(fn) { GlobalSetImmediate.call(global, fn); } : function(fn) { ProcessNextTick.call(process, fn); }; } else if (typeof NativePromise === "function" && typeof NativePromise.resolve === "function") { var nativePromise = NativePromise.resolve(); schedule = function(fn) { nativePromise.then(fn); }; } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && (window.navigator.standalone || window.cordova))) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; var toggleScheduled = false; var div2 = document.createElement("div"); var o2 = new MutationObserver(function() { div.classList.toggle("foo"); toggleScheduled = false; }); o2.observe(div2, opts); var scheduleToggle = function() { if (toggleScheduled) return; toggleScheduled = true; div2.classList.toggle("foo"); }; return function schedule(fn) { var o = new MutationObserver(function() { o.disconnect(); fn(); }); o.observe(div, opts); scheduleToggle(); }; })(); } else if (typeof setImmediate !== "undefined") { schedule = function (fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function (fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; },{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); } util.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; },{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util"); var RangeError = _dereq_("./errors").RangeError; var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; } else { this._bitField = 0; this._settledValueField = undefined; } } PromiseInspection.prototype._settledValue = function() { return this._settledValueField; }; var value = PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { return (this._bitField & 33554432) !== 0; }; var isRejected = PromiseInspection.prototype.isRejected = function () { return (this._bitField & 16777216) !== 0; }; var isPending = PromiseInspection.prototype.isPending = function () { return (this._bitField & 50397184) === 0; }; var isResolved = PromiseInspection.prototype.isResolved = function () { return (this._bitField & 50331648) !== 0; }; PromiseInspection.prototype.isCancelled = function() { return (this._bitField & 8454144) !== 0; }; Promise.prototype.__isCancelled = function() { return (this._bitField & 65536) === 65536; }; Promise.prototype._isCancelled = function() { return this._target().__isCancelled(); }; Promise.prototype.isCancelled = function() { return (this._target()._bitField & 8454144) !== 0; }; Promise.prototype.isPending = function() { return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { return isResolved.call(this._target()); }; Promise.prototype.value = function() { return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); target._unsetRejectionIsUnhandled(); return reason.call(target); }; Promise.prototype._value = function() { return this._settledValue(); }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue(); }; Promise.PromiseInspection = PromiseInspection; }; },{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) return obj; var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfill, ret._reject, undefined, ret, null ); return ret; } return doThenable(obj, then, context); } } return obj; } function doGetThen(obj) { return obj.then; } function getThen(obj) { try { return doGetThen(obj); } catch (e) { errorObj.e = e; return errorObj; } } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { try { return hasProp.call(obj, "_promise0"); } catch (e) { return false; } } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } function resolve(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } return ret; } return tryConvertToPromise; }; },{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, debug) { var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { this.handle = handle; } HandleWrapper.prototype._resultCancelled = function() { clearTimeout(this.handle); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; var handle; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); if (debug.cancellation() && value instanceof Promise) { ret._setOnCancel(value); } } else { ret = new Promise(INTERNAL); handle = setTimeout(function() { ret._fulfill(); }, +ms); if (debug.cancellation()) { ret._setOnCancel(new HandleWrapper(handle)); } ret._captureStackTrace(); } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; var afterTimeout = function (promise, message, parent) { var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); if (parent != null) { parent.cancel(); } }; function successClear(value) { clearTimeout(this.handle); return value; } function failureClear(reason) { clearTimeout(this.handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret.isPending()) { afterTimeout(ret, message, parent); } }, ms)); if (debug.cancellation()) { parent = this.then(); ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); ret._setOnCancel(handleWrapper); } else { ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); } return ret; }; }; },{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { var util = _dereq_("./util"); var TypeError = _dereq_("./errors").TypeError; var inherits = _dereq_("./util").inherits; var errorObj = util.errorObj; var tryCatch = util.tryCatch; var NULL = {}; function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = new Promise(INTERNAL); function iterator() { if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret; } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return NULL; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== NULL ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } function ResourceList(length) { this.length = length; this.promise = null; this[length-1] = null; } ResourceList.prototype._resultCancelled = function() { var len = this.length; for (var i = 0; i < len; ++i) { var item = this[i]; if (item instanceof Promise) { item.cancel(); } } }; Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var reflectedResources = new Array(resources.length); for (var i = 0; i < reflectedResources.length; ++i) { reflectedResources[i] = Promise.resolve(resources[i]).reflect(); } var resultPromise = Promise.all(reflectedResources) .then(function(inspections) { for (var i = 0; i < inspections.length; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { errorObj.e = inspection.error(); return errorObj; } else if (!inspection.isFulfilled()) { resultPromise.cancel(); return; } inspections[i] = inspection.value(); } promise._pushContext(); fn = tryCatch(fn); var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, "Promise.using", promise); return ret; }); var promise = resultPromise.lastly(function() { var inspection = new Promise.PromiseInspection(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; var tryCatchTarget; var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this !== undefined ? this : null; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return typeof value === "function" || typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; var l = 8; while (l--) new FakeConstructor(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function isError(obj) { return obj !== null && typeof obj === "object" && typeof obj.message === "string" && typeof obj.name === "string"; } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return isError(obj) && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var asArray = function(v) { if (es5.isArray(v)) { return v; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { var ArrayFrom = typeof Array.from === "function" ? function(v) { return Array.from(v); } : function(v) { var ret = []; var it = v[Symbol.iterator](); var itResult; while (!((itResult = it.next()).done)) { ret.push(itResult.value); } return ret; }; asArray = function(v) { if (es5.isArray(v)) { return v; } else if (v != null && typeof v[Symbol.iterator] === "function") { return ArrayFrom(v); } return null; }; } var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; var hasEnvVariables = typeof process !== "undefined" && "object" !== "undefined"; function env(key) { return hasEnvVariables ? __webpack_require__.i({"NODE_ENV":"production"})[key] : undefined; } function getNativePromise() { if (typeof Promise === "function") { try { var promise = new Promise(function(){}); if ({}.toString.call(promise) === "[object Promise]") { return Promise; } } catch (e) {} } } function domainBind(self, cb) { return self.bind(cb); } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, isError: isError, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: isNode, hasEnvVariables: hasEnvVariables, env: env, global: globalObject, getNativePromise: getNativePromise, domainBind: domainBind }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(28), __webpack_require__(25), __webpack_require__(208).setImmediate)) /***/ }), /***/ 191: /***/ (function(module, exports) { var ScrivitoAnchor, activate, customOptions, defaultOptions, editorOptions, medium_editor; ScrivitoAnchor = MediumEditor.extensions.anchor.extend({ name: 'scrivito_anchor', proxy: null, contentDefault: '', init: function() { var _ref; MediumEditor.extensions.anchor.prototype.init.apply(this, arguments); return this.targetCheckbox = (_ref = this.getEditorOption('anchor')) != null ? _ref.targetCheckbox : void 0; }, handleClick: function(event) { var linkElement, selectedParent, selectionRange; event.preventDefault(); event.stopPropagation(); if (!this.isDisplayed()) { selectionRange = MediumEditor.selection.getSelectionRange(this.document); selectedParent = MediumEditor.selection.getSelectedParentElement(selectionRange); linkElement = MediumEditor.util.getClosestTag(selectedParent, 'a'); this.showForm({ value: $(linkElement).attr('href') || null, target: $(linkElement).attr('target') || null }); } return false; }, getTemplate: function() { var targetCheckboxTemplate; targetCheckboxTemplate = ""; if (this.targetCheckbox) { targetCheckboxTemplate = "
\n \n
"; } return ("\n\n\n\n" + targetCheckboxTemplate).replace(/\n\s*/g, ""); }, attachFormEvents: function(form) { var input; MediumEditor.extensions.anchor.prototype.attachFormEvents.call(this, form); form = $(form); input = form.find('.medium-editor-toolbar-input'); return form.find('.medium-editor-toolbar-browse').on('click', (function(_this) { return function() { var cmsField, id, selection; selection = (id = _this.proxy.idFromPath(input.val())) ? [id] : []; cmsField = $(_this.base.origElements); scrivito.content_browser.open({ filter: cmsField.data('scrivitoEditorsFilter'), filter_context: cmsField.data('scrivitoEditorsFilterContext'), selection: selection, selection_mode: 'single' }).always(function() { return input.focus(); }).done(function(selection) { if (selection.length) { return input.val(_this.proxy.pathForId(selection[0])); } else { return input.val(''); } }); return false; }; })(this)); }, completeFormSave: function(opts) { this.base.restoreSelection(); if (opts.value) { this.execAction(this.action, opts); } else { this.execAction('unlink'); } return this.base.checkSelection(); } }); editorOptions = function() { return $.extend({}, defaultOptions(), customOptions()); }; defaultOptions = function() { return { anchorPreview: false, extensions: { scrivito_anchor: new ScrivitoAnchor, imageDragging: {} }, placeholder: false, toolbar: { buttons: ['bold', 'italic', 'scrivito_anchor', 'h2', 'h3', 'unorderedlist', 'orderedlist'], standardizeSelectionStart: true } }; }; customOptions = function() { var _ref, _ref1, _ref2, _ref3; if (typeof (typeof scrivito !== "undefined" && scrivito !== null ? (_ref = scrivito.editors) != null ? (_ref1 = _ref.medium_editor) != null ? _ref1.options : void 0 : void 0 : void 0) === 'function') { return scrivito.editors.medium_editor.options(); } else { return (typeof scrivito !== "undefined" && scrivito !== null ? (_ref2 = scrivito.editors) != null ? (_ref3 = _ref2.medium_editor) != null ? _ref3.options : void 0 : void 0 : void 0) || {}; } }; activate = function(proxy) { var cmsField, mediumEditor, scrivitoAnchorExtension; cmsField = proxy.jQueryElement(); mediumEditor = new MediumEditor(cmsField, editorOptions()).subscribe('editableInput', function() { return proxy.save(cmsField.html()); }); scrivitoAnchorExtension = mediumEditor.getExtensionByName('scrivito_anchor'); return scrivitoAnchorExtension != null ? scrivitoAnchorExtension.proxy = proxy : void 0; }; medium_editor = { can_edit: function(element) { return $(element).is('[data-scrivito-field-type=html]'); }, activate: function(element) { return activate(new scrivito.editors.DomContentProxy(element)); }, default_options: defaultOptions, options: function() { return {}; }, _activateWithProxy: function(proxy) { return activate(proxy); } }; module.exports = medium_editor._activateWithProxy; /***/ }), /***/ 192: /***/ (function(module, exports) { var DOUBLE_CLICK_MS, activate, cleanUp, cmsFieldAndPastedContent, finishEditing, getCurrentContent, isNewlineAllowed, onBlur, onFocus, onInput, onKey, prepareForEditing, save, string_editor; onKey = function(event, proxy) { var cmsField, key; cmsField = proxy.jQueryElement(); key = event.keyCode || event.which; switch (key) { case 13: if (!isNewlineAllowed(cmsField)) { event.preventDefault(); return cmsField.blur(); } break; case 27: event.stopPropagation(); return cmsField.blur(); } }; onInput = function(proxy) { return save(proxy); }; onFocus = function(proxy) { return prepareForEditing(proxy.jQueryElement()); }; onBlur = function(proxy) { save(proxy).done(function() { return proxy.trigger('scrivito_editors:blur'); }); return finishEditing(proxy); }; save = function(proxy) { var content; content = getCurrentContent(proxy.jQueryElement()); return proxy.save(content).done(function() { return proxy.trigger('scrivito_editors:save'); }); }; getCurrentContent = function(cmsField) { var clone, content; cleanUp(cmsField); clone = cmsFieldAndPastedContent(cmsField).clone(); clone.find('div:not(:has(br)),p:not(:first)').before('\n'); clone.find('br').replaceWith('\n'); content = clone.text(); clone.remove(); if (!isNewlineAllowed(cmsField)) { content = content.replace(/\n$/, ''); } return content; }; cleanUp = function(cmsField) { var pasted, siblings; siblings = cmsFieldAndPastedContent(cmsField); pasted = siblings.not(cmsField); if (pasted.length > 0) { pasted.remove(); return cmsField.text(siblings.text()); } }; cmsFieldAndPastedContent = function(cmsField) { var needsReset, siblings, siblingsBefore; siblingsBefore = cmsField.data('scrivito_editors_siblings_before_edit'); siblings = cmsField.siblings(); needsReset = !siblingsBefore || siblings.filter(siblingsBefore).length < siblingsBefore.length; if (needsReset) { return cmsField.data('scrivito_editors_siblings_before_edit', siblings); } else { return cmsField.siblings().addBack().not(siblingsBefore); } }; isNewlineAllowed = function(cmsField) { if (cmsField.data('scrivitoEditorsMultiline') === true) { return true; } if (cmsField.data('scrivitoEditorsMultiline') === false) { return false; } return cmsField.css('white-space').match(/pre/); }; prepareForEditing = function(cmsField) { var html, htmlNl2Br; if (isNewlineAllowed(cmsField) && !cmsField.data('scrivito_editors_prepared_for_editing')) { cmsField.data('scrivito_editors_prepared_for_editing', true); html = cmsField.html(); htmlNl2Br = html.replace(/\n/g, '
'); if (html !== htmlNl2Br) { return cmsField.html(htmlNl2Br); } } }; finishEditing = function(proxy) { var cmsField; cmsField = proxy.jQueryElement(); cmsField.data('scrivito_editors_prepared_for_editing', false); return cmsField.text(proxy.content()); }; DOUBLE_CLICK_MS = 300; activate = function(proxy) { var cmsField; cmsField = proxy.jQueryElement(); cmsField.attr('contenteditable', true).blur(function() { return onBlur(proxy); }).focus(function() { return onFocus(proxy); }).keypress(function(event) { return onKey(event, proxy); }).keyup(function(event) { return onKey(event, proxy); }); if (cmsField.attr('data-scrivito-editors-autosave') !== 'false') { cmsField.on('cut input keypress keyup paste', function() { return onInput(proxy); }); } prepareForEditing(cmsField); return cmsField.on('click', function(event) { cmsField.attr('contenteditable', true); cleanUp(cmsField); if (!(event.timeStamp - cmsField.data('scrivito_editors_last_click') < DOUBLE_CLICK_MS)) { event.preventDefault(); } return cmsField.data('scrivito_editors_last_click', event.timeStamp); }); }; string_editor = { can_edit: function(element) { return $(element).is('[data-scrivito-field-type=string]'); }, activate: function(element) { return activate(new scrivito.editors.DomContentProxy(element)); }, _activateWithProxy: function(proxy) { return activate(proxy); } }; module.exports = string_editor._activateWithProxy; /***/ }), /***/ 193: /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers. /* istanbul ignore next */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(207)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === 'object') { module.exports = factory(require('stackframe')); } else { root.ErrorStackParser = factory(root.StackFrame); } }(this, function ErrorStackParser(StackFrame) { 'use strict'; var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+\:\d+/; var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+\:\d+|\(native\))/m; var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code\])?$/; function _map(array, fn, thisArg) { if (typeof Array.prototype.map === 'function') { return array.map(fn, thisArg); } else { var output = new Array(array.length); for (var i = 0; i < array.length; i++) { output[i] = fn.call(thisArg, array[i]); } return output; } } function _filter(array, fn, thisArg) { if (typeof Array.prototype.filter === 'function') { return array.filter(fn, thisArg); } else { var output = []; for (var i = 0; i < array.length; i++) { if (fn.call(thisArg, array[i])) { output.push(array[i]); } } return output; } } function _indexOf(array, target) { if (typeof Array.prototype.indexOf === 'function') { return array.indexOf(target); } else { for (var i = 0; i < array.length; i++) { if (array[i] === target) { return i; } } return -1; } } return { /** * Given an Error object, extract the most information from it. * * @param {Error} error object * @return {Array} of StackFrames */ parse: function ErrorStackParser$$parse(error) { if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') { return this.parseOpera(error); } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) { return this.parseV8OrIE(error); } else if (error.stack) { return this.parseFFOrSafari(error); } else { throw new Error('Cannot parse given Error object'); } }, // Separate line and column numbers from a string of the form: (URI:Line:Column) extractLocation: function ErrorStackParser$$extractLocation(urlLike) { // Fail-fast but return locations like "(native)" if (urlLike.indexOf(':') === -1) { return [urlLike]; } var regExp = /(.+?)(?:\:(\d+))?(?:\:(\d+))?$/; var parts = regExp.exec(urlLike.replace(/[\(\)]/g, '')); return [parts[1], parts[2] || undefined, parts[3] || undefined]; }, parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) { var filtered = _filter(error.stack.split('\n'), function(line) { return !!line.match(CHROME_IE_STACK_REGEXP); }, this); return _map(filtered, function(line) { if (line.indexOf('(eval ') > -1) { // Throw away eval information until we implement stacktrace.js/stackframe#8 line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^\()]*)|(\)\,.*$)/g, ''); } var tokens = line.replace(/^\s+/, '').replace(/\(eval code/g, '(').split(/\s+/).slice(1); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.join(' ') || undefined; var fileName = _indexOf(['eval', ''], locationParts[0]) > -1 ? undefined : locationParts[0]; return new StackFrame(functionName, undefined, fileName, locationParts[1], locationParts[2], line); }, this); }, parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) { var filtered = _filter(error.stack.split('\n'), function(line) { return !line.match(SAFARI_NATIVE_CODE_REGEXP); }, this); return _map(filtered, function(line) { // Throw away eval information until we implement stacktrace.js/stackframe#8 if (line.indexOf(' > eval') > -1) { line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g, ':$1'); } if (line.indexOf('@') === -1 && line.indexOf(':') === -1) { // Safari eval frames only have function names and nothing else return new StackFrame(line); } else { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.join('@') || undefined; return new StackFrame(functionName, undefined, locationParts[0], locationParts[1], locationParts[2], line); } }, this); }, parseOpera: function ErrorStackParser$$parseOpera(e) { if (!e.stacktrace || (e.message.indexOf('\n') > -1 && e.message.split('\n').length > e.stacktrace.split('\n').length)) { return this.parseOpera9(e); } else if (!e.stack) { return this.parseOpera10(e); } else { return this.parseOpera11(e); } }, parseOpera9: function ErrorStackParser$$parseOpera9(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)/i; var lines = e.message.split('\n'); var result = []; for (var i = 2, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push(new StackFrame(undefined, undefined, match[2], match[1], undefined, lines[i])); } } return result; }, parseOpera10: function ErrorStackParser$$parseOpera10(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i; var lines = e.stacktrace.split('\n'); var result = []; for (var i = 0, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push( new StackFrame( match[3] || undefined, undefined, match[2], match[1], undefined, lines[i] ) ); } } return result; }, // Opera 10.65+ Error.stack very similar to FF/Safari parseOpera11: function ErrorStackParser$$parseOpera11(error) { var filtered = _filter(error.stack.split('\n'), function(line) { return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/); }, this); return _map(filtered, function(line) { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionCall = (tokens.shift() || ''); var functionName = functionCall .replace(//, '$2') .replace(/\([^\)]*\)/g, '') || undefined; var argsRaw; if (functionCall.match(/\(([^\)]*)\)/)) { argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1'); } var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ? undefined : argsRaw.split(','); return new StackFrame( functionName, args, locationParts[0], locationParts[1], locationParts[2], line); }, this); } }; })); /***/ }), /***/ 196: /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * jsUri * https://github.com/derek-watson/jsUri * * Copyright 2013, Derek Watson * Released under the MIT license. * * Includes parseUri regular expressions * http://blog.stevenlevithan.com/archives/parseuri * Copyright 2007, Steven Levithan * Released under the MIT license. */ /*globals define, module */ (function(global) { var re = { starts_with_slashes: /^\/+/, ends_with_slashes: /\/+$/, pluses: /\+/g, query_separator: /[&;]/, uri_parser: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*)(?::([^:@]*))?)?@)?(\[[0-9a-fA-F:.]+\]|[^:\/?#]*)(?::(\d+|(?=:)))?(:)?)((((?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ }; /** * Define forEach for older js environments * @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach#Compatibility */ if (!Array.prototype.forEach) { Array.prototype.forEach = function(callback, thisArg) { var T, k; if (this == null) { throw new TypeError(' this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } /** * unescape a query param value * @param {string} s encoded value * @return {string} decoded value */ function decode(s) { if (s) { s = s.toString().replace(re.pluses, '%20'); s = decodeURIComponent(s); } return s; } /** * Breaks a uri string down into its individual parts * @param {string} str uri * @return {object} parts */ function parseUri(str) { var parser = re.uri_parser; var parserKeys = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "isColonUri", "relative", "path", "directory", "file", "query", "anchor"]; var m = parser.exec(str || ''); var parts = {}; parserKeys.forEach(function(key, i) { parts[key] = m[i] || ''; }); return parts; } /** * Breaks a query string down into an array of key/value pairs * @param {string} str query * @return {array} array of arrays (key/value pairs) */ function parseQuery(str) { var i, ps, p, n, k, v, l; var pairs = []; if (typeof(str) === 'undefined' || str === null || str === '') { return pairs; } if (str.indexOf('?') === 0) { str = str.substring(1); } ps = str.toString().split(re.query_separator); for (i = 0, l = ps.length; i < l; i++) { p = ps[i]; n = p.indexOf('='); if (n !== 0) { k = decode(p.substring(0, n)); v = decode(p.substring(n + 1)); pairs.push(n === -1 ? [p, null] : [k, v]); } } return pairs; } /** * Creates a new Uri object * @constructor * @param {string} str */ function Uri(str) { this.uriParts = parseUri(str); this.queryPairs = parseQuery(this.uriParts.query); this.hasAuthorityPrefixUserPref = null; } /** * Define getter/setter methods */ ['protocol', 'userInfo', 'host', 'port', 'path', 'anchor'].forEach(function(key) { Uri.prototype[key] = function(val) { if (typeof val !== 'undefined') { this.uriParts[key] = val; } return this.uriParts[key]; }; }); /** * if there is no protocol, the leading // can be enabled or disabled * @param {Boolean} val * @return {Boolean} */ Uri.prototype.hasAuthorityPrefix = function(val) { if (typeof val !== 'undefined') { this.hasAuthorityPrefixUserPref = val; } if (this.hasAuthorityPrefixUserPref === null) { return (this.uriParts.source.indexOf('//') !== -1); } else { return this.hasAuthorityPrefixUserPref; } }; Uri.prototype.isColonUri = function (val) { if (typeof val !== 'undefined') { this.uriParts.isColonUri = !!val; } else { return !!this.uriParts.isColonUri; } }; /** * Serializes the internal state of the query pairs * @param {string} [val] set a new query string * @return {string} query string */ Uri.prototype.query = function(val) { var s = '', i, param, l; if (typeof val !== 'undefined') { this.queryPairs = parseQuery(val); } for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; if (s.length > 0) { s += '&'; } if (param[1] === null) { s += param[0]; } else { s += param[0]; s += '='; if (typeof param[1] !== 'undefined') { s += encodeURIComponent(param[1]); } } } return s.length > 0 ? '?' + s : s; }; /** * returns the first query param value found for the key * @param {string} key query key * @return {string} first value found for key */ Uri.prototype.getQueryParamValue = function (key) { var param, i, l; for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; if (key === param[0]) { return param[1]; } } }; /** * returns an array of query param values for the key * @param {string} key query key * @return {array} array of values */ Uri.prototype.getQueryParamValues = function (key) { var arr = [], i, param, l; for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; if (key === param[0]) { arr.push(param[1]); } } return arr; }; /** * removes query parameters * @param {string} key remove values for key * @param {val} [val] remove a specific value, otherwise removes all * @return {Uri} returns self for fluent chaining */ Uri.prototype.deleteQueryParam = function (key, val) { var arr = [], i, param, keyMatchesFilter, valMatchesFilter, l; for (i = 0, l = this.queryPairs.length; i < l; i++) { param = this.queryPairs[i]; keyMatchesFilter = decode(param[0]) === decode(key); valMatchesFilter = param[1] === val; if ((arguments.length === 1 && !keyMatchesFilter) || (arguments.length === 2 && (!keyMatchesFilter || !valMatchesFilter))) { arr.push(param); } } this.queryPairs = arr; return this; }; /** * adds a query parameter * @param {string} key add values for key * @param {string} val value to add * @param {integer} [index] specific index to add the value at * @return {Uri} returns self for fluent chaining */ Uri.prototype.addQueryParam = function (key, val, index) { if (arguments.length === 3 && index !== -1) { index = Math.min(index, this.queryPairs.length); this.queryPairs.splice(index, 0, [key, val]); } else if (arguments.length > 0) { this.queryPairs.push([key, val]); } return this; }; /** * test for the existence of a query parameter * @param {string} key add values for key * @param {string} val value to add * @param {integer} [index] specific index to add the value at * @return {Uri} returns self for fluent chaining */ Uri.prototype.hasQueryParam = function (key) { var i, len = this.queryPairs.length; for (i = 0; i < len; i++) { if (this.queryPairs[i][0] == key) return true; } return false; }; /** * replaces query param values * @param {string} key key to replace value for * @param {string} newVal new value * @param {string} [oldVal] replace only one specific value (otherwise replaces all) * @return {Uri} returns self for fluent chaining */ Uri.prototype.replaceQueryParam = function (key, newVal, oldVal) { var index = -1, len = this.queryPairs.length, i, param; if (arguments.length === 3) { for (i = 0; i < len; i++) { param = this.queryPairs[i]; if (decode(param[0]) === decode(key) && decodeURIComponent(param[1]) === decode(oldVal)) { index = i; break; } } if (index >= 0) { this.deleteQueryParam(key, decode(oldVal)).addQueryParam(key, newVal, index); } } else { for (i = 0; i < len; i++) { param = this.queryPairs[i]; if (decode(param[0]) === decode(key)) { index = i; break; } } this.deleteQueryParam(key); this.addQueryParam(key, newVal, index); } return this; }; /** * Define fluent setter methods (setProtocol, setHasAuthorityPrefix, etc) */ ['protocol', 'hasAuthorityPrefix', 'isColonUri', 'userInfo', 'host', 'port', 'path', 'query', 'anchor'].forEach(function(key) { var method = 'set' + key.charAt(0).toUpperCase() + key.slice(1); Uri.prototype[method] = function(val) { this[key](val); return this; }; }); /** * Scheme name, colon and doubleslash, as required * @return {string} http:// or possibly just // */ Uri.prototype.scheme = function() { var s = ''; if (this.protocol()) { s += this.protocol(); if (this.protocol().indexOf(':') !== this.protocol().length - 1) { s += ':'; } s += '//'; } else { if (this.hasAuthorityPrefix() && this.host()) { s += '//'; } } return s; }; /** * Same as Mozilla nsIURI.prePath * @return {string} scheme://user:password@host:port * @see https://developer.mozilla.org/en/nsIURI */ Uri.prototype.origin = function() { var s = this.scheme(); if (this.userInfo() && this.host()) { s += this.userInfo(); if (this.userInfo().indexOf('@') !== this.userInfo().length - 1) { s += '@'; } } if (this.host()) { s += this.host(); if (this.port() || (this.path() && this.path().substr(0, 1).match(/[0-9]/))) { s += ':' + this.port(); } } return s; }; /** * Adds a trailing slash to the path */ Uri.prototype.addTrailingSlash = function() { var path = this.path() || ''; if (path.substr(-1) !== '/') { this.path(path + '/'); } return this; }; /** * Serializes the internal state of the Uri object * @return {string} */ Uri.prototype.toString = function() { var path, s = this.origin(); if (this.isColonUri()) { if (this.path()) { s += ':'+this.path(); } } else if (this.path()) { path = this.path(); if (!(re.ends_with_slashes.test(s) || re.starts_with_slashes.test(path))) { s += '/'; } else { if (s) { s.replace(re.ends_with_slashes, '/'); } path = path.replace(re.starts_with_slashes, '/'); } s += path; } else { if (this.host() && (this.query().toString() || this.anchor())) { s += '/'; } } if (this.query().toString()) { s += this.query().toString(); } if (this.anchor()) { if (this.anchor().indexOf('#') !== 0) { s += '#'; } s += this.anchor(); } return s; }; /** * Clone a Uri object * @return {Uri} duplicate copy of the Uri */ Uri.prototype.clone = function() { return new Uri(this.toString()); }; /** * export via AMD or CommonJS, otherwise leak a global */ if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return Uri; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = Uri; } else { global.Uri = Uri; } }(this)); /***/ }), /***/ 20: /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getWindowRegistry = undefined; var _window_context = __webpack_require__(10); function getWindowRegistry() { return (0, _window_context.getWindowContext)()._privateRealm._registry; } exports.getWindowRegistry = getWindowRegistry; /***/ }), /***/ 201: /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {var __WEBPACK_AMD_DEFINE_RESULT__;/*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */ // Full polyfill for browsers with no classList support if (!("classList" in document.createElement("_"))) { (function (view) { "use strict"; if (!('Element' in view)) return; var classListProp = "classList" , protoProp = "prototype" , elemCtrProto = view.Element[protoProp] , objCtr = Object , strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); } , arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0 , len = this.length ; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function (type, message) { this.name = type; this.code = DOMException[type]; this.message = message; } , checkTokenAndGetIndex = function (classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR" , "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR" , "String contains an invalid character" ); } return arrIndexOf.call(classList, token); } , ClassList = function (elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class") || "") , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [] , i = 0 , len = classes.length ; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; } , classListProto = ClassList[protoProp] = [] , classListGetter = function () { return new ClassList(this); } ; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false ; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false , index ; do { token = tokens[i] + ""; index = checkTokenAndGetIndex(this, token); while (index !== -1) { this.splice(index, 1); updated = true; index = checkTokenAndGetIndex(this, token); } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, force) { token += ""; var result = this.contains(token) , method = result ? force !== true && "remove" : force !== false && "add" ; if (method) { this[method](token); } if (force === true || force === false) { return force; } else { return !result; } }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter , enumerable: true , configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(self)); } /* Blob.js * A Blob implementation. * 2014-07-24 * * By Eli Grey, http://eligrey.com * By Devin Samarin, https://github.com/dsamarin * License: X11/MIT * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md */ /*global self, unescape */ /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */ (function (view) { "use strict"; view.URL = view.URL || view.webkitURL; if (view.Blob && view.URL) { try { new Blob; return; } catch (e) {} } // Internally we use a BlobBuilder implementation to base Blob off of // in order to support older browsers that only have BlobBuilder var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) { var get_class = function(object) { return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1]; } , FakeBlobBuilder = function BlobBuilder() { this.data = []; } , FakeBlob = function Blob(data, type, encoding) { this.data = data; this.size = data.length; this.type = type; this.encoding = encoding; } , FBB_proto = FakeBlobBuilder.prototype , FB_proto = FakeBlob.prototype , FileReaderSync = view.FileReaderSync , FileException = function(type) { this.code = this[this.name = type]; } , file_ex_codes = ( "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR " + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR" ).split(" ") , file_ex_code = file_ex_codes.length , real_URL = view.URL || view.webkitURL || view , real_create_object_URL = real_URL.createObjectURL , real_revoke_object_URL = real_URL.revokeObjectURL , URL = real_URL , btoa = view.btoa , atob = view.atob , ArrayBuffer = view.ArrayBuffer , Uint8Array = view.Uint8Array , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/ ; FakeBlob.fake = FB_proto.fake = true; while (file_ex_code--) { FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1; } // Polyfill URL if (!real_URL.createObjectURL) { URL = view.URL = function(uri) { var uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a") , uri_origin ; uri_info.href = uri; if (!("origin" in uri_info)) { if (uri_info.protocol.toLowerCase() === "data:") { uri_info.origin = null; } else { uri_origin = uri.match(origin); uri_info.origin = uri_origin && uri_origin[1]; } } return uri_info; }; } URL.createObjectURL = function(blob) { var type = blob.type , data_URI_header ; if (type === null) { type = "application/octet-stream"; } if (blob instanceof FakeBlob) { data_URI_header = "data:" + type; if (blob.encoding === "base64") { return data_URI_header + ";base64," + blob.data; } else if (blob.encoding === "URI") { return data_URI_header + "," + decodeURIComponent(blob.data); } if (btoa) { return data_URI_header + ";base64," + btoa(blob.data); } else { return data_URI_header + "," + encodeURIComponent(blob.data); } } else if (real_create_object_URL) { return real_create_object_URL.call(real_URL, blob); } }; URL.revokeObjectURL = function(object_URL) { if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) { real_revoke_object_URL.call(real_URL, object_URL); } }; FBB_proto.append = function(data/*, endings*/) { var bb = this.data; // decode data to a binary string if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) { var str = "" , buf = new Uint8Array(data) , i = 0 , buf_len = buf.length ; for (; i < buf_len; i++) { str += String.fromCharCode(buf[i]); } bb.push(str); } else if (get_class(data) === "Blob" || get_class(data) === "File") { if (FileReaderSync) { var fr = new FileReaderSync; bb.push(fr.readAsBinaryString(data)); } else { // async FileReader won't work as BlobBuilder is sync throw new FileException("NOT_READABLE_ERR"); } } else if (data instanceof FakeBlob) { if (data.encoding === "base64" && atob) { bb.push(atob(data.data)); } else if (data.encoding === "URI") { bb.push(decodeURIComponent(data.data)); } else if (data.encoding === "raw") { bb.push(data.data); } } else { if (typeof data !== "string") { data += ""; // convert unsupported types to strings } // decode UTF-16 to binary string bb.push(unescape(encodeURIComponent(data))); } }; FBB_proto.getBlob = function(type) { if (!arguments.length) { type = null; } return new FakeBlob(this.data.join(""), type, "raw"); }; FBB_proto.toString = function() { return "[object BlobBuilder]"; }; FB_proto.slice = function(start, end, type) { var args = arguments.length; if (args < 3) { type = null; } return new FakeBlob( this.data.slice(start, args > 1 ? end : this.data.length) , type , this.encoding ); }; FB_proto.toString = function() { return "[object Blob]"; }; FB_proto.close = function() { this.size = 0; delete this.data; }; return FakeBlobBuilder; }(view)); view.Blob = function(blobParts, options) { var type = options ? (options.type || "") : ""; var builder = new BlobBuilder(); if (blobParts) { for (var i = 0, len = blobParts.length; i < len; i++) { if (Uint8Array && blobParts[i] instanceof Uint8Array) { builder.append(blobParts[i].buffer); } else { builder.append(blobParts[i]); } } } var blob = builder.getBlob(type); if (!blob.slice && blob.webkitSlice) { blob.slice = blob.webkitSlice; } return blob; }; var getPrototypeOf = Object.getPrototypeOf || function(object) { return object.__proto__; }; view.Blob.prototype = getPrototypeOf(new view.Blob()); }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this)); (function (root, factory) { 'use strict'; var isElectron = typeof module === 'object' && typeof process !== 'undefined' && process && process.versions && process.versions.electron; if (!isElectron && typeof module === 'object') { module.exports = factory; } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function () { return factory; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { root.MediumEditor = factory; } }(this, function () { 'use strict'; function MediumEditor(elements, options) { 'use strict'; return this.init(elements, options); } MediumEditor.extensions = {}; /*jshint unused: true */ (function (window) { 'use strict'; function copyInto(overwrite, dest) { var prop, sources = Array.prototype.slice.call(arguments, 2); dest = dest || {}; for (var i = 0; i < sources.length; i++) { var source = sources[i]; if (source) { for (prop in source) { if (source.hasOwnProperty(prop) && typeof source[prop] !== 'undefined' && (overwrite || dest.hasOwnProperty(prop) === false)) { dest[prop] = source[prop]; } } } } return dest; } // https://developer.mozilla.org/en-US/docs/Web/API/Node/contains // Some browsers (including phantom) don't return true for Node.contains(child) // if child is a text node. Detect these cases here and use a fallback // for calls to Util.isDescendant() var nodeContainsWorksWithTextNodes = false; try { var testParent = document.createElement('div'), testText = document.createTextNode(' '); testParent.appendChild(testText); nodeContainsWorksWithTextNodes = testParent.contains(testText); } catch (exc) {} var Util = { // http://stackoverflow.com/questions/17907445/how-to-detect-ie11#comment30165888_17907562 // by rg89 isIE: ((navigator.appName === 'Microsoft Internet Explorer') || ((navigator.appName === 'Netscape') && (new RegExp('Trident/.*rv:([0-9]{1,}[.0-9]{0,})').exec(navigator.userAgent) !== null))), isEdge: (/Edge\/\d+/).exec(navigator.userAgent) !== null, // if firefox isFF: (navigator.userAgent.toLowerCase().indexOf('firefox') > -1), // http://stackoverflow.com/a/11752084/569101 isMac: (window.navigator.platform.toUpperCase().indexOf('MAC') >= 0), // https://github.com/jashkenas/underscore // Lonely letter MUST USE the uppercase code keyCode: { BACKSPACE: 8, TAB: 9, ENTER: 13, ESCAPE: 27, SPACE: 32, DELETE: 46, K: 75, // K keycode, and not k M: 77, V: 86 }, /** * Returns true if it's metaKey on Mac, or ctrlKey on non-Mac. * See #591 */ isMetaCtrlKey: function (event) { if ((Util.isMac && event.metaKey) || (!Util.isMac && event.ctrlKey)) { return true; } return false; }, /** * Returns true if the key associated to the event is inside keys array * * @see : https://github.com/jquery/jquery/blob/0705be475092aede1eddae01319ec931fb9c65fc/src/event.js#L473-L484 * @see : http://stackoverflow.com/q/4471582/569101 */ isKey: function (event, keys) { var keyCode = Util.getKeyCode(event); // it's not an array let's just compare strings! if (false === Array.isArray(keys)) { return keyCode === keys; } if (-1 === keys.indexOf(keyCode)) { return false; } return true; }, getKeyCode: function (event) { var keyCode = event.which; // getting the key code from event if (null === keyCode) { keyCode = event.charCode !== null ? event.charCode : event.keyCode; } return keyCode; }, blockContainerElementNames: [ // elements our editor generates 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'li', 'ol', // all other known block elements 'address', 'article', 'aside', 'audio', 'canvas', 'dd', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'header', 'hgroup', 'main', 'nav', 'noscript', 'output', 'section', 'video', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td' ], emptyElementNames: ['br', 'col', 'colgroup', 'hr', 'img', 'input', 'source', 'wbr'], extend: function extend(/* dest, source1, source2, ...*/) { var args = [true].concat(Array.prototype.slice.call(arguments)); return copyInto.apply(this, args); }, defaults: function defaults(/*dest, source1, source2, ...*/) { var args = [false].concat(Array.prototype.slice.call(arguments)); return copyInto.apply(this, args); }, /* * Create a link around the provided text nodes which must be adjacent to each other and all be * descendants of the same closest block container. If the preconditions are not met, unexpected * behavior will result. */ createLink: function (document, textNodes, href, target) { var anchor = document.createElement('a'); Util.moveTextRangeIntoElement(textNodes[0], textNodes[textNodes.length - 1], anchor); anchor.setAttribute('href', href); if (target) { anchor.setAttribute('target', target); } return anchor; }, /* * Given the provided match in the format {start: 1, end: 2} where start and end are indices into the * textContent of the provided element argument, modify the DOM inside element to ensure that the text * identified by the provided match can be returned as text nodes that contain exactly that text, without * any additional text at the beginning or end of the returned array of adjacent text nodes. * * The only DOM manipulation performed by this function is splitting the text nodes, non-text nodes are * not affected in any way. */ findOrCreateMatchingTextNodes: function (document, element, match) { var treeWalker = document.createTreeWalker(element, NodeFilter.SHOW_ALL, null, false), matchedNodes = [], currentTextIndex = 0, startReached = false, currentNode = null, newNode = null; while ((currentNode = treeWalker.nextNode()) !== null) { if (currentNode.nodeType > 3) { continue; } else if (currentNode.nodeType === 3) { if (!startReached && match.start < (currentTextIndex + currentNode.nodeValue.length)) { startReached = true; newNode = Util.splitStartNodeIfNeeded(currentNode, match.start, currentTextIndex); } if (startReached) { Util.splitEndNodeIfNeeded(currentNode, newNode, match.end, currentTextIndex); } if (startReached && currentTextIndex === match.end) { break; // Found the node(s) corresponding to the link. Break out and move on to the next. } else if (startReached && currentTextIndex > (match.end + 1)) { throw new Error('PerformLinking overshot the target!'); // should never happen... } if (startReached) { matchedNodes.push(newNode || currentNode); } currentTextIndex += currentNode.nodeValue.length; if (newNode !== null) { currentTextIndex += newNode.nodeValue.length; // Skip the newNode as we'll already have pushed it to the matches treeWalker.nextNode(); } newNode = null; } else if (currentNode.tagName.toLowerCase() === 'img') { if (!startReached && (match.start <= currentTextIndex)) { startReached = true; } if (startReached) { matchedNodes.push(currentNode); } } } return matchedNodes; }, /* * Given the provided text node and text coordinates, split the text node if needed to make it align * precisely with the coordinates. * * This function is intended to be called from Util.findOrCreateMatchingTextNodes. */ splitStartNodeIfNeeded: function (currentNode, matchStartIndex, currentTextIndex) { if (matchStartIndex !== currentTextIndex) { return currentNode.splitText(matchStartIndex - currentTextIndex); } return null; }, /* * Given the provided text node and text coordinates, split the text node if needed to make it align * precisely with the coordinates. The newNode argument should from the result of Util.splitStartNodeIfNeeded, * if that function has been called on the same currentNode. * * This function is intended to be called from Util.findOrCreateMatchingTextNodes. */ splitEndNodeIfNeeded: function (currentNode, newNode, matchEndIndex, currentTextIndex) { var textIndexOfEndOfFarthestNode, endSplitPoint; textIndexOfEndOfFarthestNode = currentTextIndex + currentNode.nodeValue.length + (newNode ? newNode.nodeValue.length : 0) - 1; endSplitPoint = matchEndIndex - currentTextIndex - (newNode ? currentNode.nodeValue.length : 0); if (textIndexOfEndOfFarthestNode >= matchEndIndex && currentTextIndex !== textIndexOfEndOfFarthestNode && endSplitPoint !== 0) { (newNode || currentNode).splitText(endSplitPoint); } }, /* * Take an element, and break up all of its text content into unique pieces such that: * 1) All text content of the elements are in separate blocks. No piece of text content should span * across multiple blocks. This means no element return by this function should have * any blocks as children. * 2) The union of the textcontent of all of the elements returned here covers all * of the text within the element. * * * EXAMPLE: * In the event that we have something like: * *
*

Some Text

*
    *
  1. List Item 1
  2. *
  3. List Item 2
  4. *
*
* * This function would return these elements as an array: * [

Some Text

,
  • List Item 1
  • ,
  • List Item 2
  • ] * * Since the
    and
      elements contain blocks within them they are not returned. * Since the

      and

    1. 's don't contain block elements and cover all the text content of the *
      container, they are the elements returned. */ splitByBlockElements: function (element) { if (element.nodeType !== 3 && element.nodeType !== 1) { return []; } var toRet = [], blockElementQuery = MediumEditor.util.blockContainerElementNames.join(','); if (element.nodeType === 3 || element.querySelectorAll(blockElementQuery).length === 0) { return [element]; } for (var i = 0; i < element.childNodes.length; i++) { var child = element.childNodes[i]; if (child.nodeType === 3) { toRet.push(child); } else if (child.nodeType === 1) { var blockElements = child.querySelectorAll(blockElementQuery); if (blockElements.length === 0) { toRet.push(child); } else { toRet = toRet.concat(MediumEditor.util.splitByBlockElements(child)); } } } return toRet; }, // Find the next node in the DOM tree that represents any text that is being // displayed directly next to the targetNode (passed as an argument) // Text that appears directly next to the current node can be: // - A sibling text node // - A descendant of a sibling element // - A sibling text node of an ancestor // - A descendant of a sibling element of an ancestor findAdjacentTextNodeWithContent: function findAdjacentTextNodeWithContent(rootNode, targetNode, ownerDocument) { var pastTarget = false, nextNode, nodeIterator = ownerDocument.createNodeIterator(rootNode, NodeFilter.SHOW_TEXT, null, false); // Use a native NodeIterator to iterate over all the text nodes that are descendants // of the rootNode. Once past the targetNode, choose the first non-empty text node nextNode = nodeIterator.nextNode(); while (nextNode) { if (nextNode === targetNode) { pastTarget = true; } else if (pastTarget) { if (nextNode.nodeType === 3 && nextNode.nodeValue && nextNode.nodeValue.trim().length > 0) { break; } } nextNode = nodeIterator.nextNode(); } return nextNode; }, // Find an element's previous sibling within a medium-editor element // If one doesn't exist, find the closest ancestor's previous sibling findPreviousSibling: function (node) { if (!node || Util.isMediumEditorElement(node)) { return false; } var previousSibling = node.previousSibling; while (!previousSibling && !Util.isMediumEditorElement(node.parentNode)) { node = node.parentNode; previousSibling = node.previousSibling; } return previousSibling; }, isDescendant: function isDescendant(parent, child, checkEquality) { if (!parent || !child) { return false; } if (parent === child) { return !!checkEquality; } // If parent is not an element, it can't have any descendants if (parent.nodeType !== 1) { return false; } if (nodeContainsWorksWithTextNodes || child.nodeType !== 3) { return parent.contains(child); } var node = child.parentNode; while (node !== null) { if (node === parent) { return true; } node = node.parentNode; } return false; }, // https://github.com/jashkenas/underscore isElement: function isElement(obj) { return !!(obj && obj.nodeType === 1); }, // https://github.com/jashkenas/underscore throttle: function (func, wait) { var THROTTLE_INTERVAL = 50, context, args, result, timeout = null, previous = 0, later = function () { previous = Date.now(); timeout = null; result = func.apply(context, args); if (!timeout) { context = args = null; } }; if (!wait && wait !== 0) { wait = THROTTLE_INTERVAL; } return function () { var now = Date.now(), remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) { context = args = null; } } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }, traverseUp: function (current, testElementFunction) { if (!current) { return false; } do { if (current.nodeType === 1) { if (testElementFunction(current)) { return current; } // do not traverse upwards past the nearest containing editor if (Util.isMediumEditorElement(current)) { return false; } } current = current.parentNode; } while (current); return false; }, htmlEntities: function (str) { // converts special characters (like <) into their escaped/encoded values (like <). // This allows you to show to display the string without the browser reading it as HTML. return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); }, // http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div insertHTMLCommand: function (doc, html) { var selection, range, el, fragment, node, lastNode, toReplace, res = false, ecArgs = ['insertHTML', false, html]; /* Edge's implementation of insertHTML is just buggy right now: * - Doesn't allow leading white space at the beginning of an element * - Found a case when a tag was inserted when calling alignCenter inside a blockquote * * There are likely other bugs, these are just the ones we found so far. * For now, let's just use the same fallback we did for IE */ if (!MediumEditor.util.isEdge && doc.queryCommandSupported('insertHTML')) { try { return doc.execCommand.apply(doc, ecArgs); } catch (ignore) {} } selection = doc.getSelection(); if (selection.rangeCount) { range = selection.getRangeAt(0); toReplace = range.commonAncestorContainer; // https://github.com/yabwe/medium-editor/issues/748 // If the selection is an empty editor element, create a temporary text node inside of the editor // and select it so that we don't delete the editor element if (Util.isMediumEditorElement(toReplace) && !toReplace.firstChild) { range.selectNode(toReplace.appendChild(doc.createTextNode(''))); } else if ((toReplace.nodeType === 3 && range.startOffset === 0 && range.endOffset === toReplace.nodeValue.length) || (toReplace.nodeType !== 3 && toReplace.innerHTML === range.toString())) { // Ensure range covers maximum amount of nodes as possible // By moving up the DOM and selecting ancestors whose only child is the range while (!Util.isMediumEditorElement(toReplace) && toReplace.parentNode && toReplace.parentNode.childNodes.length === 1 && !Util.isMediumEditorElement(toReplace.parentNode)) { toReplace = toReplace.parentNode; } range.selectNode(toReplace); } range.deleteContents(); el = doc.createElement('div'); el.innerHTML = html; fragment = doc.createDocumentFragment(); while (el.firstChild) { node = el.firstChild; lastNode = fragment.appendChild(node); } range.insertNode(fragment); // Preserve the selection: if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); MediumEditor.selection.selectRange(doc, range); } res = true; } // https://github.com/yabwe/medium-editor/issues/992 // If we're monitoring calls to execCommand, notify listeners as if a real call had happened if (doc.execCommand.callListeners) { doc.execCommand.callListeners(ecArgs, res); } return res; }, execFormatBlock: function (doc, tagName) { // Get the top level block element that contains the selection var blockContainer = Util.getTopBlockContainer(MediumEditor.selection.getSelectionStart(doc)), childNodes; // Special handling for blockquote if (tagName === 'blockquote') { if (blockContainer) { childNodes = Array.prototype.slice.call(blockContainer.childNodes); // Check if the blockquote has a block element as a child (nested blocks) if (childNodes.some(function (childNode) { return Util.isBlockContainer(childNode); })) { // FF handles blockquote differently on formatBlock // allowing nesting, we need to use outdent // https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla return doc.execCommand('outdent', false, null); } } // When IE blockquote needs to be called as indent // http://stackoverflow.com/questions/1816223/rich-text-editor-with-blockquote-function/1821777#1821777 if (Util.isIE) { return doc.execCommand('indent', false, tagName); } } // If the blockContainer is already the element type being passed in // treat it as 'undo' formatting and just convert it to a

      if (blockContainer && tagName === blockContainer.nodeName.toLowerCase()) { tagName = 'p'; } // When IE we need to add <> to heading elements // http://stackoverflow.com/questions/10741831/execcommand-formatblock-headings-in-ie if (Util.isIE) { tagName = '<' + tagName + '>'; } // When FF, IE and Edge, we have to handle blockquote node seperately as 'formatblock' does not work. // https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Commands if (blockContainer && blockContainer.nodeName.toLowerCase() === 'blockquote') { // For IE, just use outdent if (Util.isIE && tagName === '

      ') { return doc.execCommand('outdent', false, tagName); } // For Firefox and Edge, make sure there's a nested block element before calling outdent if ((Util.isFF || Util.isEdge) && tagName === 'p') { childNodes = Array.prototype.slice.call(blockContainer.childNodes); // If there are some non-block elements we need to wrap everything in a

      before we outdent if (childNodes.some(function (childNode) { return !Util.isBlockContainer(childNode); })) { doc.execCommand('formatBlock', false, tagName); } return doc.execCommand('outdent', false, tagName); } } return doc.execCommand('formatBlock', false, tagName); }, /** * Set target to blank on the given el element * * TODO: not sure if this should be here * * When creating a link (using core -> createLink) the selection returned by Firefox will be the parent of the created link * instead of the created link itself (as it is for Chrome for example), so we retrieve all "a" children to grab the good one by * using `anchorUrl` to ensure that we are adding target="_blank" on the good one. * This isn't a bulletproof solution anyway .. */ setTargetBlank: function (el, anchorUrl) { var i, url = anchorUrl || false; if (el.nodeName.toLowerCase() === 'a') { el.target = '_blank'; } else { el = el.getElementsByTagName('a'); for (i = 0; i < el.length; i += 1) { if (false === url || url === el[i].attributes.href.value) { el[i].target = '_blank'; } } } }, /* * this function is called to explicitly remove the target='_blank' as FF holds on to _blank value even * after unchecking the checkbox on anchor form */ removeTargetBlank: function (el, anchorUrl) { var i; if (el.nodeName.toLowerCase() === 'a') { el.removeAttribute('target'); } else { el = el.getElementsByTagName('a'); for (i = 0; i < el.length; i += 1) { if (anchorUrl === el[i].attributes.href.value) { el[i].removeAttribute('target'); } } } }, /* * this function adds one or several classes on an a element. * if el parameter is not an a, it will look for a children of el. * if no a children are found, it will look for the a parent. */ addClassToAnchors: function (el, buttonClass) { var classes = buttonClass.split(' '), i, j; if (el.nodeName.toLowerCase() === 'a') { for (j = 0; j < classes.length; j += 1) { el.classList.add(classes[j]); } } else { var aChildren = el.getElementsByTagName('a'); if (aChildren.length === 0) { var parentAnchor = Util.getClosestTag(el, 'a'); el = parentAnchor ? [parentAnchor] : []; } else { el = aChildren; } for (i = 0; i < el.length; i += 1) { for (j = 0; j < classes.length; j += 1) { el[i].classList.add(classes[j]); } } } }, isListItem: function (node) { if (!node) { return false; } if (node.nodeName.toLowerCase() === 'li') { return true; } var parentNode = node.parentNode, tagName = parentNode.nodeName.toLowerCase(); while (tagName === 'li' || (!Util.isBlockContainer(parentNode) && tagName !== 'div')) { if (tagName === 'li') { return true; } parentNode = parentNode.parentNode; if (parentNode) { tagName = parentNode.nodeName.toLowerCase(); } else { return false; } } return false; }, cleanListDOM: function (ownerDocument, element) { if (element.nodeName.toLowerCase() !== 'li') { return; } var list = element.parentElement; if (list.parentElement.nodeName.toLowerCase() === 'p') { // yes we need to clean up Util.unwrap(list.parentElement, ownerDocument); // move cursor at the end of the text inside the list // for some unknown reason, the cursor is moved to end of the "visual" line MediumEditor.selection.moveCursor(ownerDocument, element.firstChild, element.firstChild.textContent.length); } }, /* splitDOMTree * * Given a root element some descendant element, split the root element * into its own element containing the descendant element and all elements * on the left or right side of the descendant ('right' is default) * * example: * *

      * / | \ * * / \ / \ / \ * 1 2 3 4 5 6 * * If I wanted to split this tree given the
      as the root and "4" as the leaf * the result would be (the prime ' marks indicates nodes that are created as clones): * * SPLITTING OFF 'RIGHT' TREE SPLITTING OFF 'LEFT' TREE * *
      '
      '
      * / \ / \ / \ | * ' * / \ | | / \ /\ /\ /\ * 1 2 3 4 5 6 1 2 3 4 5 6 * * The above example represents splitting off the 'right' or 'left' part of a tree, where * the
      ' would be returned as an element not appended to the DOM, and the
      * would remain in place where it was * */ splitOffDOMTree: function (rootNode, leafNode, splitLeft) { var splitOnNode = leafNode, createdNode = null, splitRight = !splitLeft; // loop until we hit the root while (splitOnNode !== rootNode) { var currParent = splitOnNode.parentNode, newParent = currParent.cloneNode(false), targetNode = (splitRight ? splitOnNode : currParent.firstChild), appendLast; // Create a new parent element which is a clone of the current parent if (createdNode) { if (splitRight) { // If we're splitting right, add previous created element before siblings newParent.appendChild(createdNode); } else { // If we're splitting left, add previous created element last appendLast = createdNode; } } createdNode = newParent; while (targetNode) { var sibling = targetNode.nextSibling; // Special handling for the 'splitNode' if (targetNode === splitOnNode) { if (!targetNode.hasChildNodes()) { targetNode.parentNode.removeChild(targetNode); } else { // For the node we're splitting on, if it has children, we need to clone it // and not just move it targetNode = targetNode.cloneNode(false); } // If the resulting split node has content, add it if (targetNode.textContent) { createdNode.appendChild(targetNode); } targetNode = (splitRight ? sibling : null); } else { // For general case, just remove the element and only // add it to the split tree if it contains something targetNode.parentNode.removeChild(targetNode); if (targetNode.hasChildNodes() || targetNode.textContent) { createdNode.appendChild(targetNode); } targetNode = sibling; } } // If we had an element we wanted to append at the end, do that now if (appendLast) { createdNode.appendChild(appendLast); } splitOnNode = currParent; } return createdNode; }, moveTextRangeIntoElement: function (startNode, endNode, newElement) { if (!startNode || !endNode) { return false; } var rootNode = Util.findCommonRoot(startNode, endNode); if (!rootNode) { return false; } if (endNode === startNode) { var temp = startNode.parentNode, sibling = startNode.nextSibling; temp.removeChild(startNode); newElement.appendChild(startNode); if (sibling) { temp.insertBefore(newElement, sibling); } else { temp.appendChild(newElement); } return newElement.hasChildNodes(); } // create rootChildren array which includes all the children // we care about var rootChildren = [], firstChild, lastChild, nextNode; for (var i = 0; i < rootNode.childNodes.length; i++) { nextNode = rootNode.childNodes[i]; if (!firstChild) { if (Util.isDescendant(nextNode, startNode, true)) { firstChild = nextNode; } } else { if (Util.isDescendant(nextNode, endNode, true)) { lastChild = nextNode; break; } else { rootChildren.push(nextNode); } } } var afterLast = lastChild.nextSibling, fragment = rootNode.ownerDocument.createDocumentFragment(); // build up fragment on startNode side of tree if (firstChild === startNode) { firstChild.parentNode.removeChild(firstChild); fragment.appendChild(firstChild); } else { fragment.appendChild(Util.splitOffDOMTree(firstChild, startNode)); } // add any elements between firstChild & lastChild rootChildren.forEach(function (element) { element.parentNode.removeChild(element); fragment.appendChild(element); }); // build up fragment on endNode side of the tree if (lastChild === endNode) { lastChild.parentNode.removeChild(lastChild); fragment.appendChild(lastChild); } else { fragment.appendChild(Util.splitOffDOMTree(lastChild, endNode, true)); } // Add fragment into passed in element newElement.appendChild(fragment); if (lastChild.parentNode === rootNode) { // If last child is in the root, insert newElement in front of it rootNode.insertBefore(newElement, lastChild); } else if (afterLast) { // If last child was removed, but it had a sibling, insert in front of it rootNode.insertBefore(newElement, afterLast); } else { // lastChild was removed and was the last actual element just append rootNode.appendChild(newElement); } return newElement.hasChildNodes(); }, /* based on http://stackoverflow.com/a/6183069 */ depthOfNode: function (inNode) { var theDepth = 0, node = inNode; while (node.parentNode !== null) { node = node.parentNode; theDepth++; } return theDepth; }, findCommonRoot: function (inNode1, inNode2) { var depth1 = Util.depthOfNode(inNode1), depth2 = Util.depthOfNode(inNode2), node1 = inNode1, node2 = inNode2; while (depth1 !== depth2) { if (depth1 > depth2) { node1 = node1.parentNode; depth1 -= 1; } else { node2 = node2.parentNode; depth2 -= 1; } } while (node1 !== node2) { node1 = node1.parentNode; node2 = node2.parentNode; } return node1; }, /* END - based on http://stackoverflow.com/a/6183069 */ isElementAtBeginningOfBlock: function (node) { var textVal, sibling; while (!Util.isBlockContainer(node) && !Util.isMediumEditorElement(node)) { sibling = node; while (sibling = sibling.previousSibling) { textVal = sibling.nodeType === 3 ? sibling.nodeValue : sibling.textContent; if (textVal.length > 0) { return false; } } node = node.parentNode; } return true; }, isMediumEditorElement: function (element) { return element && element.getAttribute && !!element.getAttribute('data-medium-editor-element'); }, getContainerEditorElement: function (element) { return Util.traverseUp(element, function (node) { return Util.isMediumEditorElement(node); }); }, isBlockContainer: function (element) { return element && element.nodeType !== 3 && Util.blockContainerElementNames.indexOf(element.nodeName.toLowerCase()) !== -1; }, /* Finds the closest ancestor which is a block container element * If element is within editor element but not within any other block element, * the editor element is returned */ getClosestBlockContainer: function (node) { return Util.traverseUp(node, function (node) { return Util.isBlockContainer(node) || Util.isMediumEditorElement(node); }); }, /* Finds highest level ancestor element which is a block container element * If element is within editor element but not within any other block element, * the editor element is returned */ getTopBlockContainer: function (element) { var topBlock = Util.isBlockContainer(element) ? element : false; Util.traverseUp(element, function (el) { if (Util.isBlockContainer(el)) { topBlock = el; } if (!topBlock && Util.isMediumEditorElement(el)) { topBlock = el; return true; } return false; }); return topBlock; }, getFirstSelectableLeafNode: function (element) { while (element && element.firstChild) { element = element.firstChild; } // We don't want to set the selection to an element that can't have children, this messes up Gecko. element = Util.traverseUp(element, function (el) { return Util.emptyElementNames.indexOf(el.nodeName.toLowerCase()) === -1; }); // Selecting at the beginning of a table doesn't work in PhantomJS. if (element.nodeName.toLowerCase() === 'table') { var firstCell = element.querySelector('th, td'); if (firstCell) { element = firstCell; } } return element; }, // TODO: remove getFirstTextNode AND _getFirstTextNode when jumping in 6.0.0 (no code references) getFirstTextNode: function (element) { Util.warn('getFirstTextNode is deprecated and will be removed in version 6.0.0'); return Util._getFirstTextNode(element); }, _getFirstTextNode: function (element) { if (element.nodeType === 3) { return element; } for (var i = 0; i < element.childNodes.length; i++) { var textNode = Util._getFirstTextNode(element.childNodes[i]); if (textNode !== null) { return textNode; } } return null; }, ensureUrlHasProtocol: function (url) { if (url.indexOf('://') === -1) { return 'http://' + url; } return url; }, warn: function () { if (window.console !== undefined && typeof window.console.warn === 'function') { window.console.warn.apply(window.console, arguments); } }, deprecated: function (oldName, newName, version) { // simple deprecation warning mechanism. var m = oldName + ' is deprecated, please use ' + newName + ' instead.'; if (version) { m += ' Will be removed in ' + version; } Util.warn(m); }, deprecatedMethod: function (oldName, newName, args, version) { // run the replacement and warn when someone calls a deprecated method Util.deprecated(oldName, newName, version); if (typeof this[newName] === 'function') { this[newName].apply(this, args); } }, cleanupAttrs: function (el, attrs) { attrs.forEach(function (attr) { el.removeAttribute(attr); }); }, cleanupTags: function (el, tags) { if (tags.indexOf(el.nodeName.toLowerCase()) !== -1) { el.parentNode.removeChild(el); } }, unwrapTags: function (el, tags) { if (tags.indexOf(el.nodeName.toLowerCase()) !== -1) { MediumEditor.util.unwrap(el, document); } }, // get the closest parent getClosestTag: function (el, tag) { return Util.traverseUp(el, function (element) { return element.nodeName.toLowerCase() === tag.toLowerCase(); }); }, unwrap: function (el, doc) { var fragment = doc.createDocumentFragment(), nodes = Array.prototype.slice.call(el.childNodes); // cast nodeList to array since appending child // to a different node will alter length of el.childNodes for (var i = 0; i < nodes.length; i++) { fragment.appendChild(nodes[i]); } if (fragment.childNodes.length) { el.parentNode.replaceChild(fragment, el); } else { el.parentNode.removeChild(el); } }, guid: function () { function _s4() { return Math .floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return _s4() + _s4() + '-' + _s4() + '-' + _s4() + '-' + _s4() + '-' + _s4() + _s4() + _s4(); } }; MediumEditor.util = Util; }(window)); (function () { 'use strict'; var Extension = function (options) { MediumEditor.util.extend(this, options); }; Extension.extend = function (protoProps) { // magic extender thinger. mostly borrowed from backbone/goog.inherits // place this function on some thing you want extend-able. // // example: // // function Thing(args){ // this.options = args; // } // // Thing.prototype = { foo: "bar" }; // Thing.extend = extenderify; // // var ThingTwo = Thing.extend({ foo: "baz" }); // // var thingOne = new Thing(); // foo === "bar" // var thingTwo = new ThingTwo(); // foo === "baz" // // which seems like some simply shallow copy nonsense // at first, but a lot more is going on there. // // passing a `constructor` to the extend props // will cause the instance to instantiate through that // instead of the parent's constructor. var parent = this, child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && protoProps.hasOwnProperty('constructor')) { child = protoProps.constructor; } else { child = function () { return parent.apply(this, arguments); }; } // das statics (.extend comes over, so your subclass can have subclasses too) MediumEditor.util.extend(child, parent); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function () { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); if (protoProps) { MediumEditor.util.extend(child.prototype, protoProps); } // todo: $super? return child; }; Extension.prototype = { /* init: [function] * * Called by MediumEditor during initialization. * The .base property will already have been set to * current instance of MediumEditor when this is called. * All helper methods will exist as well */ init: function () {}, /* base: [MediumEditor instance] * * If not overriden, this will be set to the current instance * of MediumEditor, before the init method is called */ base: undefined, /* name: [string] * * 'name' of the extension, used for retrieving the extension. * If not set, MediumEditor will set this to be the key * used when passing the extension into MediumEditor via the * 'extensions' option */ name: undefined, /* checkState: [function (node)] * * If implemented, this function will be called one or more times * the state of the editor & toolbar are updated. * When the state is updated, the editor does the following: * * 1) Find the parent node containing the current selection * 2) Call checkState on the extension, passing the node as an argument * 3) Get the parent node of the previous node * 4) Repeat steps #2 and #3 until we move outside the parent contenteditable */ checkState: undefined, /* destroy: [function ()] * * This method should remove any created html, custom event handlers * or any other cleanup tasks that should be performed. * If implemented, this function will be called when MediumEditor's * destroy method has been called. */ destroy: undefined, /* As alternatives to checkState, these functions provide a more structured * path to updating the state of an extension (usually a button) whenever * the state of the editor & toolbar are updated. */ /* queryCommandState: [function ()] * * If implemented, this function will be called once on each extension * when the state of the editor/toolbar is being updated. * * If this function returns a non-null value, the extension will * be ignored as the code climbs the dom tree. * * If this function returns true, and the setActive() function is defined * setActive() will be called */ queryCommandState: undefined, /* isActive: [function ()] * * If implemented, this function will be called when MediumEditor * has determined that this extension is 'active' for the current selection. * This may be called when the editor & toolbar are being updated, * but only if queryCommandState() or isAlreadyApplied() functions * are implemented, and when called, return true. */ isActive: undefined, /* isAlreadyApplied: [function (node)] * * If implemented, this function is similar to checkState() in * that it will be called repeatedly as MediumEditor moves up * the DOM to update the editor & toolbar after a state change. * * NOTE: This function will NOT be called if checkState() has * been implemented. This function will NOT be called if * queryCommandState() is implemented and returns a non-null * value when called */ isAlreadyApplied: undefined, /* setActive: [function ()] * * If implemented, this function is called when MediumEditor knows * that this extension is currently enabled. Currently, this * function is called when updating the editor & toolbar, and * only if queryCommandState() or isAlreadyApplied(node) return * true when called */ setActive: undefined, /* setInactive: [function ()] * * If implemented, this function is called when MediumEditor knows * that this extension is currently disabled. Curently, this * is called at the beginning of each state change for * the editor & toolbar. After calling this, MediumEditor * will attempt to update the extension, either via checkState() * or the combination of queryCommandState(), isAlreadyApplied(node), * isActive(), and setActive() */ setInactive: undefined, /* getInteractionElements: [function ()] * * If the extension renders any elements that the user can interact with, * this method should be implemented and return the root element or an array * containing all of the root elements. MediumEditor will call this function * during interaction to see if the user clicked on something outside of the editor. * The elements are used to check if the target element of a click or * other user event is a descendant of any extension elements. * This way, the editor can also count user interaction within editor elements as * interactions with the editor, and thus not trigger 'blur' */ getInteractionElements: undefined, /************************ Helpers ************************ * The following are helpers that are either set by MediumEditor * during initialization, or are helper methods which either * route calls to the MediumEditor instance or provide common * functionality for all extensions *********************************************************/ /* window: [Window] * * If not overriden, this will be set to the window object * to be used by MediumEditor and its extensions. This is * passed via the 'contentWindow' option to MediumEditor * and is the global 'window' object by default */ 'window': undefined, /* document: [Document] * * If not overriden, this will be set to the document object * to be used by MediumEditor and its extensions. This is * passed via the 'ownerDocument' optin to MediumEditor * and is the global 'document' object by default */ 'document': undefined, /* getEditorElements: [function ()] * * Helper function which returns an array containing * all the contenteditable elements for this instance * of MediumEditor */ getEditorElements: function () { return this.base.elements; }, /* getEditorId: [function ()] * * Helper function which returns a unique identifier * for this instance of MediumEditor */ getEditorId: function () { return this.base.id; }, /* getEditorOptions: [function (option)] * * Helper function which returns the value of an option * used to initialize this instance of MediumEditor */ getEditorOption: function (option) { return this.base.options[option]; } }; /* List of method names to add to the prototype of Extension * Each of these methods will be defined as helpers that * just call directly into the MediumEditor instance. * * example for 'on' method: * Extension.prototype.on = function () { * return this.base.on.apply(this.base, arguments); * } */ [ // general helpers 'execAction', // event handling 'on', 'off', 'subscribe', 'trigger' ].forEach(function (helper) { Extension.prototype[helper] = function () { return this.base[helper].apply(this.base, arguments); }; }); MediumEditor.Extension = Extension; })(); (function () { 'use strict'; function filterOnlyParentElements(node) { if (MediumEditor.util.isBlockContainer(node)) { return NodeFilter.FILTER_ACCEPT; } else { return NodeFilter.FILTER_SKIP; } } var Selection = { findMatchingSelectionParent: function (testElementFunction, contentWindow) { var selection = contentWindow.getSelection(), range, current; if (selection.rangeCount === 0) { return false; } range = selection.getRangeAt(0); current = range.commonAncestorContainer; return MediumEditor.util.traverseUp(current, testElementFunction); }, getSelectionElement: function (contentWindow) { return this.findMatchingSelectionParent(function (el) { return MediumEditor.util.isMediumEditorElement(el); }, contentWindow); }, // http://stackoverflow.com/questions/17678843/cant-restore-selection-after-html-modify-even-if-its-the-same-html // Tim Down exportSelection: function (root, doc) { if (!root) { return null; } var selectionState = null, selection = doc.getSelection(); if (selection.rangeCount > 0) { var range = selection.getRangeAt(0), preSelectionRange = range.cloneRange(), start; preSelectionRange.selectNodeContents(root); preSelectionRange.setEnd(range.startContainer, range.startOffset); start = preSelectionRange.toString().length; selectionState = { start: start, end: start + range.toString().length }; // Check to see if the selection starts with any images // if so we need to make sure the the beginning of the selection is // set correctly when importing selection if (this.doesRangeStartWithImages(range, doc)) { selectionState.startsWithImage = true; } // Check to see if the selection has any trailing images // if so, this this means we need to look for them when we import selection var trailingImageCount = this.getTrailingImageCount(root, selectionState, range.endContainer, range.endOffset); if (trailingImageCount) { selectionState.trailingImageCount = trailingImageCount; } // If start = 0 there may still be an empty paragraph before it, but we don't care. if (start !== 0) { var emptyBlocksIndex = this.getIndexRelativeToAdjacentEmptyBlocks(doc, root, range.startContainer, range.startOffset); if (emptyBlocksIndex !== -1) { selectionState.emptyBlocksIndex = emptyBlocksIndex; } } } return selectionState; }, // http://stackoverflow.com/questions/17678843/cant-restore-selection-after-html-modify-even-if-its-the-same-html // Tim Down // // {object} selectionState - the selection to import // {DOMElement} root - the root element the selection is being restored inside of // {Document} doc - the document to use for managing selection // {boolean} [favorLaterSelectionAnchor] - defaults to false. If true, import the cursor immediately // subsequent to an anchor tag if it would otherwise be placed right at the trailing edge inside the // anchor. This cursor positioning, even though visually equivalent to the user, can affect behavior // in MS IE. importSelection: function (selectionState, root, doc, favorLaterSelectionAnchor) { if (!selectionState || !root) { return; } var range = doc.createRange(); range.setStart(root, 0); range.collapse(true); var node = root, nodeStack = [], charIndex = 0, foundStart = false, foundEnd = false, trailingImageCount = 0, stop = false, nextCharIndex, allowRangeToStartAtEndOfNode = false, lastTextNode = null; // When importing selection, the start of the selection may lie at the end of an element // or at the beginning of an element. Since visually there is no difference between these 2 // we will try to move the selection to the beginning of an element since this is generally // what users will expect and it's a more predictable behavior. // // However, there are some specific cases when we don't want to do this: // 1) We're attempting to move the cursor outside of the end of an anchor [favorLaterSelectionAnchor = true] // 2) The selection starts with an image, which is special since an image doesn't have any 'content' // as far as selection and ranges are concerned // 3) The selection starts after a specified number of empty block elements (selectionState.emptyBlocksIndex) // // For these cases, we want the selection to start at a very specific location, so we should NOT // automatically move the cursor to the beginning of the first actual chunk of text if (favorLaterSelectionAnchor || selectionState.startsWithImage || typeof selectionState.emptyBlocksIndex !== 'undefined') { allowRangeToStartAtEndOfNode = true; } while (!stop && node) { // Only iterate over elements and text nodes if (node.nodeType > 3) { node = nodeStack.pop(); continue; } // If we hit a text node, we need to add the amount of characters to the overall count if (node.nodeType === 3 && !foundEnd) { nextCharIndex = charIndex + node.length; // Check if we're at or beyond the start of the selection we're importing if (!foundStart && selectionState.start >= charIndex && selectionState.start <= nextCharIndex) { // NOTE: We only want to allow a selection to start at the END of an element if // allowRangeToStartAtEndOfNode is true if (allowRangeToStartAtEndOfNode || selectionState.start < nextCharIndex) { range.setStart(node, selectionState.start - charIndex); foundStart = true; } // We're at the end of a text node where the selection could start but we shouldn't // make the selection start here because allowRangeToStartAtEndOfNode is false. // However, we should keep a reference to this node in case there aren't any more // text nodes after this, so that we have somewhere to import the selection to else { lastTextNode = node; } } // We've found the start of the selection, check if we're at or beyond the end of the selection we're importing if (foundStart && selectionState.end >= charIndex && selectionState.end <= nextCharIndex) { if (!selectionState.trailingImageCount) { range.setEnd(node, selectionState.end - charIndex); stop = true; } else { foundEnd = true; } } charIndex = nextCharIndex; } else { if (selectionState.trailingImageCount && foundEnd) { if (node.nodeName.toLowerCase() === 'img') { trailingImageCount++; } if (trailingImageCount === selectionState.trailingImageCount) { // Find which index the image is in its parent's children var endIndex = 0; while (node.parentNode.childNodes[endIndex] !== node) { endIndex++; } range.setEnd(node.parentNode, endIndex + 1); stop = true; } } if (!stop && node.nodeType === 1) { // this is an element // add all its children to the stack var i = node.childNodes.length - 1; while (i >= 0) { nodeStack.push(node.childNodes[i]); i -= 1; } } } if (!stop) { node = nodeStack.pop(); } } // If we've gone through the entire text but didn't find the beginning of a text node // to make the selection start at, we should fall back to starting the selection // at the END of the last text node we found if (!foundStart && lastTextNode) { range.setStart(lastTextNode, lastTextNode.length); range.setEnd(lastTextNode, lastTextNode.length); } if (typeof selectionState.emptyBlocksIndex !== 'undefined') { range = this.importSelectionMoveCursorPastBlocks(doc, root, selectionState.emptyBlocksIndex, range); } // If the selection is right at the ending edge of a link, put it outside the anchor tag instead of inside. if (favorLaterSelectionAnchor) { range = this.importSelectionMoveCursorPastAnchor(selectionState, range); } this.selectRange(doc, range); }, // Utility method called from importSelection only importSelectionMoveCursorPastAnchor: function (selectionState, range) { var nodeInsideAnchorTagFunction = function (node) { return node.nodeName.toLowerCase() === 'a'; }; if (selectionState.start === selectionState.end && range.startContainer.nodeType === 3 && range.startOffset === range.startContainer.nodeValue.length && MediumEditor.util.traverseUp(range.startContainer, nodeInsideAnchorTagFunction)) { var prevNode = range.startContainer, currentNode = range.startContainer.parentNode; while (currentNode !== null && currentNode.nodeName.toLowerCase() !== 'a') { if (currentNode.childNodes[currentNode.childNodes.length - 1] !== prevNode) { currentNode = null; } else { prevNode = currentNode; currentNode = currentNode.parentNode; } } if (currentNode !== null && currentNode.nodeName.toLowerCase() === 'a') { var currentNodeIndex = null; for (var i = 0; currentNodeIndex === null && i < currentNode.parentNode.childNodes.length; i++) { if (currentNode.parentNode.childNodes[i] === currentNode) { currentNodeIndex = i; } } range.setStart(currentNode.parentNode, currentNodeIndex + 1); range.collapse(true); } } return range; }, // Uses the emptyBlocksIndex calculated by getIndexRelativeToAdjacentEmptyBlocks // to move the cursor back to the start of the correct paragraph importSelectionMoveCursorPastBlocks: function (doc, root, index, range) { var treeWalker = doc.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, filterOnlyParentElements, false), startContainer = range.startContainer, startBlock, targetNode, currIndex = 0; index = index || 1; // If index is 0, we still want to move to the next block // Chrome counts newlines and spaces that separate block elements as actual elements. // If the selection is inside one of these text nodes, and it has a previous sibling // which is a block element, we want the treewalker to start at the previous sibling // and NOT at the parent of the textnode if (startContainer.nodeType === 3 && MediumEditor.util.isBlockContainer(startContainer.previousSibling)) { startBlock = startContainer.previousSibling; } else { startBlock = MediumEditor.util.getClosestBlockContainer(startContainer); } // Skip over empty blocks until we hit the block we want the selection to be in while (treeWalker.nextNode()) { if (!targetNode) { // Loop through all blocks until we hit the starting block element if (startBlock === treeWalker.currentNode) { targetNode = treeWalker.currentNode; } } else { targetNode = treeWalker.currentNode; currIndex++; // We hit the target index, bail if (currIndex === index) { break; } // If we find a non-empty block, ignore the emptyBlocksIndex and just put selection here if (targetNode.textContent.length > 0) { break; } } } if (!targetNode) { targetNode = startBlock; } // We're selecting a high-level block node, so make sure the cursor gets moved into the deepest // element at the beginning of the block range.setStart(MediumEditor.util.getFirstSelectableLeafNode(targetNode), 0); return range; }, // Returns -1 unless the cursor is at the beginning of a paragraph/block // If the paragraph/block is preceeded by empty paragraphs/block (with no text) // it will return the number of empty paragraphs before the cursor. // Otherwise, it will return 0, which indicates the cursor is at the beginning // of a paragraph/block, and not at the end of the paragraph/block before it getIndexRelativeToAdjacentEmptyBlocks: function (doc, root, cursorContainer, cursorOffset) { // If there is text in front of the cursor, that means there isn't only empty blocks before it if (cursorContainer.textContent.length > 0 && cursorOffset > 0) { return -1; } // Check if the block that contains the cursor has any other text in front of the cursor var node = cursorContainer; if (node.nodeType !== 3) { node = cursorContainer.childNodes[cursorOffset]; } if (node) { // The element isn't at the beginning of a block, so it has content before it if (!MediumEditor.util.isElementAtBeginningOfBlock(node)) { return -1; } var previousSibling = MediumEditor.util.findPreviousSibling(node); // If there is no previous sibling, this is the first text element in the editor if (!previousSibling) { return -1; } // If the previous sibling has text, then there are no empty blocks before this else if (previousSibling.nodeValue) { return -1; } } // Walk over block elements, counting number of empty blocks between last piece of text // and the block the cursor is in var closestBlock = MediumEditor.util.getClosestBlockContainer(cursorContainer), treeWalker = doc.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, filterOnlyParentElements, false), emptyBlocksCount = 0; while (treeWalker.nextNode()) { var blockIsEmpty = treeWalker.currentNode.textContent === ''; if (blockIsEmpty || emptyBlocksCount > 0) { emptyBlocksCount += 1; } if (treeWalker.currentNode === closestBlock) { return emptyBlocksCount; } if (!blockIsEmpty) { emptyBlocksCount = 0; } } return emptyBlocksCount; }, // Returns true if the selection range begins with an image tag // Returns false if the range starts with any non empty text nodes doesRangeStartWithImages: function (range, doc) { if (range.startOffset !== 0 || range.startContainer.nodeType !== 1) { return false; } if (range.startContainer.nodeName.toLowerCase() === 'img') { return true; } var img = range.startContainer.querySelector('img'); if (!img) { return false; } var treeWalker = doc.createTreeWalker(range.startContainer, NodeFilter.SHOW_ALL, null, false); while (treeWalker.nextNode()) { var next = treeWalker.currentNode; // If we hit the image, then there isn't any text before the image so // the image is at the beginning of the range if (next === img) { break; } // If we haven't hit the iamge, but found text that contains content // then the range doesn't start with an image if (next.nodeValue) { return false; } } return true; }, getTrailingImageCount: function (root, selectionState, endContainer, endOffset) { // If the endOffset of a range is 0, the endContainer doesn't contain images // If the endContainer is a text node, there are no trailing images if (endOffset === 0 || endContainer.nodeType !== 1) { return 0; } // If the endContainer isn't an image, and doesn't have an image descendants // there are no trailing images if (endContainer.nodeName.toLowerCase() !== 'img' && !endContainer.querySelector('img')) { return 0; } var lastNode = endContainer.childNodes[endOffset - 1]; while (lastNode.hasChildNodes()) { lastNode = lastNode.lastChild; } var node = root, nodeStack = [], charIndex = 0, foundStart = false, foundEnd = false, stop = false, nextCharIndex, trailingImages = 0; while (!stop && node) { // Only iterate over elements and text nodes if (node.nodeType > 3) { node = nodeStack.pop(); continue; } if (node.nodeType === 3 && !foundEnd) { trailingImages = 0; nextCharIndex = charIndex + node.length; if (!foundStart && selectionState.start >= charIndex && selectionState.start <= nextCharIndex) { foundStart = true; } if (foundStart && selectionState.end >= charIndex && selectionState.end <= nextCharIndex) { foundEnd = true; } charIndex = nextCharIndex; } else { if (node.nodeName.toLowerCase() === 'img') { trailingImages++; } if (node === lastNode) { stop = true; } else if (node.nodeType === 1) { // this is an element // add all its children to the stack var i = node.childNodes.length - 1; while (i >= 0) { nodeStack.push(node.childNodes[i]); i -= 1; } } } if (!stop) { node = nodeStack.pop(); } } return trailingImages; }, // determine if the current selection contains any 'content' // content being any non-white space text or an image selectionContainsContent: function (doc) { var sel = doc.getSelection(); // collapsed selection or selection withour range doesn't contain content if (!sel || sel.isCollapsed || !sel.rangeCount) { return false; } // if toString() contains any text, the selection contains some content if (sel.toString().trim() !== '') { return true; } // if selection contains only image(s), it will return empty for toString() // so check for an image manually var selectionNode = this.getSelectedParentElement(sel.getRangeAt(0)); if (selectionNode) { if (selectionNode.nodeName.toLowerCase() === 'img' || (selectionNode.nodeType === 1 && selectionNode.querySelector('img'))) { return true; } } return false; }, selectionInContentEditableFalse: function (contentWindow) { // determine if the current selection is exclusively inside // a contenteditable="false", though treat the case of an // explicit contenteditable="true" inside a "false" as false. var sawtrue, sawfalse = this.findMatchingSelectionParent(function (el) { var ce = el && el.getAttribute('contenteditable'); if (ce === 'true') { sawtrue = true; } return el.nodeName !== '#text' && ce === 'false'; }, contentWindow); return !sawtrue && sawfalse; }, // http://stackoverflow.com/questions/4176923/html-of-selected-text // by Tim Down getSelectionHtml: function getSelectionHtml(doc) { var i, html = '', sel = doc.getSelection(), len, container; if (sel.rangeCount) { container = doc.createElement('div'); for (i = 0, len = sel.rangeCount; i < len; i += 1) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } return html; }, /** * Find the caret position within an element irrespective of any inline tags it may contain. * * @param {DOMElement} An element containing the cursor to find offsets relative to. * @param {Range} A Range representing cursor position. Will window.getSelection if none is passed. * @return {Object} 'left' and 'right' attributes contain offsets from begining and end of Element */ getCaretOffsets: function getCaretOffsets(element, range) { var preCaretRange, postCaretRange; if (!range) { range = window.getSelection().getRangeAt(0); } preCaretRange = range.cloneRange(); postCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(element); preCaretRange.setEnd(range.endContainer, range.endOffset); postCaretRange.selectNodeContents(element); postCaretRange.setStart(range.endContainer, range.endOffset); return { left: preCaretRange.toString().length, right: postCaretRange.toString().length }; }, // http://stackoverflow.com/questions/15867542/range-object-get-selection-parent-node-chrome-vs-firefox rangeSelectsSingleNode: function (range) { var startNode = range.startContainer; return startNode === range.endContainer && startNode.hasChildNodes() && range.endOffset === range.startOffset + 1; }, getSelectedParentElement: function (range) { if (!range) { return null; } // Selection encompasses a single element if (this.rangeSelectsSingleNode(range) && range.startContainer.childNodes[range.startOffset].nodeType !== 3) { return range.startContainer.childNodes[range.startOffset]; } // Selection range starts inside a text node, so get its parent if (range.startContainer.nodeType === 3) { return range.startContainer.parentNode; } // Selection starts inside an element return range.startContainer; }, getSelectedElements: function (doc) { var selection = doc.getSelection(), range, toRet, currNode; if (!selection.rangeCount || selection.isCollapsed || !selection.getRangeAt(0).commonAncestorContainer) { return []; } range = selection.getRangeAt(0); if (range.commonAncestorContainer.nodeType === 3) { toRet = []; currNode = range.commonAncestorContainer; while (currNode.parentNode && currNode.parentNode.childNodes.length === 1) { toRet.push(currNode.parentNode); currNode = currNode.parentNode; } return toRet; } return [].filter.call(range.commonAncestorContainer.getElementsByTagName('*'), function (el) { return (typeof selection.containsNode === 'function') ? selection.containsNode(el, true) : true; }); }, selectNode: function (node, doc) { var range = doc.createRange(); range.selectNodeContents(node); this.selectRange(doc, range); }, select: function (doc, startNode, startOffset, endNode, endOffset) { var range = doc.createRange(); range.setStart(startNode, startOffset); if (endNode) { range.setEnd(endNode, endOffset); } else { range.collapse(true); } this.selectRange(doc, range); return range; }, /** * Clear the current highlighted selection and set the caret to the start or the end of that prior selection, defaults to end. * * @param {DomDocument} doc Current document * @param {boolean} moveCursorToStart A boolean representing whether or not to set the caret to the beginning of the prior selection. */ clearSelection: function (doc, moveCursorToStart) { if (moveCursorToStart) { doc.getSelection().collapseToStart(); } else { doc.getSelection().collapseToEnd(); } }, /** * Move cursor to the given node with the given offset. * * @param {DomDocument} doc Current document * @param {DomElement} node Element where to jump * @param {integer} offset Where in the element should we jump, 0 by default */ moveCursor: function (doc, node, offset) { this.select(doc, node, offset); }, getSelectionRange: function (ownerDocument) { var selection = ownerDocument.getSelection(); if (selection.rangeCount === 0) { return null; } return selection.getRangeAt(0); }, selectRange: function (ownerDocument, range) { var selection = ownerDocument.getSelection(); selection.removeAllRanges(); selection.addRange(range); }, // http://stackoverflow.com/questions/1197401/how-can-i-get-the-element-the-caret-is-in-with-javascript-when-using-contentedi // by You getSelectionStart: function (ownerDocument) { var node = ownerDocument.getSelection().anchorNode, startNode = (node && node.nodeType === 3 ? node.parentNode : node); return startNode; } }; MediumEditor.selection = Selection; }()); (function () { 'use strict'; function isElementDescendantOfExtension(extensions, element) { return extensions.some(function (extension) { if (typeof extension.getInteractionElements !== 'function') { return false; } var extensionElements = extension.getInteractionElements(); if (!extensionElements) { return false; } if (!Array.isArray(extensionElements)) { extensionElements = [extensionElements]; } return extensionElements.some(function (el) { return MediumEditor.util.isDescendant(el, element, true); }); }); } var Events = function (instance) { this.base = instance; this.options = this.base.options; this.events = []; this.disabledEvents = {}; this.customEvents = {}; this.listeners = {}; }; Events.prototype = { InputEventOnContenteditableSupported: !MediumEditor.util.isIE && !MediumEditor.util.isEdge, // Helpers for event handling attachDOMEvent: function (targets, event, listener, useCapture) { var win = this.base.options.contentWindow, doc = this.base.options.ownerDocument; targets = MediumEditor.util.isElement(targets) || [win, doc].indexOf(targets) > -1 ? [targets] : targets; Array.prototype.forEach.call(targets, function (target) { target.addEventListener(event, listener, useCapture); this.events.push([target, event, listener, useCapture]); }.bind(this)); }, detachDOMEvent: function (targets, event, listener, useCapture) { var index, e, win = this.base.options.contentWindow, doc = this.base.options.ownerDocument; if (targets !== null) { targets = MediumEditor.util.isElement(targets) || [win, doc].indexOf(targets) > -1 ? [targets] : targets; Array.prototype.forEach.call(targets, function (target) { index = this.indexOfListener(target, event, listener, useCapture); if (index !== -1) { e = this.events.splice(index, 1)[0]; e[0].removeEventListener(e[1], e[2], e[3]); } }.bind(this)); } }, indexOfListener: function (target, event, listener, useCapture) { var i, n, item; for (i = 0, n = this.events.length; i < n; i = i + 1) { item = this.events[i]; if (item[0] === target && item[1] === event && item[2] === listener && item[3] === useCapture) { return i; } } return -1; }, detachAllDOMEvents: function () { var e = this.events.pop(); while (e) { e[0].removeEventListener(e[1], e[2], e[3]); e = this.events.pop(); } }, detachAllEventsFromElement: function (element) { var filtered = this.events.filter(function (e) { return e && e[0].getAttribute && e[0].getAttribute('medium-editor-index') === element.getAttribute('medium-editor-index'); }); for (var i = 0, len = filtered.length; i < len; i++) { var e = filtered[i]; this.detachDOMEvent(e[0], e[1], e[2], e[3]); } }, // Attach all existing handlers to a new element attachAllEventsToElement: function (element) { if (this.listeners['editableInput']) { this.contentCache[element.getAttribute('medium-editor-index')] = element.innerHTML; } if (this.eventsCache) { this.eventsCache.forEach(function (e) { this.attachDOMEvent(element, e['name'], e['handler'].bind(this)); }, this); } }, enableCustomEvent: function (event) { if (this.disabledEvents[event] !== undefined) { delete this.disabledEvents[event]; } }, disableCustomEvent: function (event) { this.disabledEvents[event] = true; }, // custom events attachCustomEvent: function (event, listener) { this.setupListener(event); if (!this.customEvents[event]) { this.customEvents[event] = []; } this.customEvents[event].push(listener); }, detachCustomEvent: function (event, listener) { var index = this.indexOfCustomListener(event, listener); if (index !== -1) { this.customEvents[event].splice(index, 1); // TODO: If array is empty, should detach internal listeners via destroyListener() } }, indexOfCustomListener: function (event, listener) { if (!this.customEvents[event] || !this.customEvents[event].length) { return -1; } return this.customEvents[event].indexOf(listener); }, detachAllCustomEvents: function () { this.customEvents = {}; // TODO: Should detach internal listeners here via destroyListener() }, triggerCustomEvent: function (name, data, editable) { if (this.customEvents[name] && !this.disabledEvents[name]) { this.customEvents[name].forEach(function (listener) { listener(data, editable); }); } }, // Cleaning up destroy: function () { this.detachAllDOMEvents(); this.detachAllCustomEvents(); this.detachExecCommand(); if (this.base.elements) { this.base.elements.forEach(function (element) { element.removeAttribute('data-medium-focused'); }); } }, // Listening to calls to document.execCommand // Attach a listener to be notified when document.execCommand is called attachToExecCommand: function () { if (this.execCommandListener) { return; } // Store an instance of the listener so: // 1) We only attach to execCommand once // 2) We can remove the listener later this.execCommandListener = function (execInfo) { this.handleDocumentExecCommand(execInfo); }.bind(this); // Ensure that execCommand has been wrapped correctly this.wrapExecCommand(); // Add listener to list of execCommand listeners this.options.ownerDocument.execCommand.listeners.push(this.execCommandListener); }, // Remove our listener for calls to document.execCommand detachExecCommand: function () { var doc = this.options.ownerDocument; if (!this.execCommandListener || !doc.execCommand.listeners) { return; } // Find the index of this listener in the array of listeners so it can be removed var index = doc.execCommand.listeners.indexOf(this.execCommandListener); if (index !== -1) { doc.execCommand.listeners.splice(index, 1); } // If the list of listeners is now empty, put execCommand back to its original state if (!doc.execCommand.listeners.length) { this.unwrapExecCommand(); } }, // Wrap document.execCommand in a custom method so we can listen to calls to it wrapExecCommand: function () { var doc = this.options.ownerDocument; // Ensure all instance of MediumEditor only wrap execCommand once if (doc.execCommand.listeners) { return; } // Helper method to call all listeners to execCommand var callListeners = function (args, result) { if (doc.execCommand.listeners) { doc.execCommand.listeners.forEach(function (listener) { listener({ command: args[0], value: args[2], args: args, result: result }); }); } }, // Create a wrapper method for execCommand which will: // 1) Call document.execCommand with the correct arguments // 2) Loop through any listeners and notify them that execCommand was called // passing extra info on the call // 3) Return the result wrapper = function () { var result = doc.execCommand.orig.apply(this, arguments); if (!doc.execCommand.listeners) { return result; } var args = Array.prototype.slice.call(arguments); callListeners(args, result); return result; }; // Store a reference to the original execCommand wrapper.orig = doc.execCommand; // Attach an array for storing listeners wrapper.listeners = []; // Helper for notifying listeners wrapper.callListeners = callListeners; // Overwrite execCommand doc.execCommand = wrapper; }, // Revert document.execCommand back to its original self unwrapExecCommand: function () { var doc = this.options.ownerDocument; if (!doc.execCommand.orig) { return; } // Use the reference to the original execCommand to revert back doc.execCommand = doc.execCommand.orig; }, // Listening to browser events to emit events medium-editor cares about setupListener: function (name) { if (this.listeners[name]) { return; } switch (name) { case 'externalInteraction': // Detecting when user has interacted with elements outside of MediumEditor this.attachDOMEvent(this.options.ownerDocument.body, 'mousedown', this.handleBodyMousedown.bind(this), true); this.attachDOMEvent(this.options.ownerDocument.body, 'click', this.handleBodyClick.bind(this), true); this.attachDOMEvent(this.options.ownerDocument.body, 'focus', this.handleBodyFocus.bind(this), true); break; case 'blur': // Detecting when focus is lost this.setupListener('externalInteraction'); break; case 'focus': // Detecting when focus moves into some part of MediumEditor this.setupListener('externalInteraction'); break; case 'editableInput': // setup cache for knowing when the content has changed this.contentCache = {}; this.base.elements.forEach(function (element) { this.contentCache[element.getAttribute('medium-editor-index')] = element.innerHTML; }, this); // Attach to the 'oninput' event, handled correctly by most browsers if (this.InputEventOnContenteditableSupported) { this.attachToEachElement('input', this.handleInput); } // For browsers which don't support the input event on contenteditable (IE) // we'll attach to 'selectionchange' on the document and 'keypress' on the editables if (!this.InputEventOnContenteditableSupported) { this.setupListener('editableKeypress'); this.keypressUpdateInput = true; this.attachDOMEvent(document, 'selectionchange', this.handleDocumentSelectionChange.bind(this)); // Listen to calls to execCommand this.attachToExecCommand(); } break; case 'editableClick': // Detecting click in the contenteditables this.attachToEachElement('click', this.handleClick); break; case 'editableBlur': // Detecting blur in the contenteditables this.attachToEachElement('blur', this.handleBlur); break; case 'editableKeypress': // Detecting keypress in the contenteditables this.attachToEachElement('keypress', this.handleKeypress); break; case 'editableKeyup': // Detecting keyup in the contenteditables this.attachToEachElement('keyup', this.handleKeyup); break; case 'editableKeydown': // Detecting keydown on the contenteditables this.attachToEachElement('keydown', this.handleKeydown); break; case 'editableKeydownSpace': // Detecting keydown for SPACE on the contenteditables this.setupListener('editableKeydown'); break; case 'editableKeydownEnter': // Detecting keydown for ENTER on the contenteditables this.setupListener('editableKeydown'); break; case 'editableKeydownTab': // Detecting keydown for TAB on the contenteditable this.setupListener('editableKeydown'); break; case 'editableKeydownDelete': // Detecting keydown for DELETE/BACKSPACE on the contenteditables this.setupListener('editableKeydown'); break; case 'editableMouseover': // Detecting mouseover on the contenteditables this.attachToEachElement('mouseover', this.handleMouseover); break; case 'editableDrag': // Detecting dragover and dragleave on the contenteditables this.attachToEachElement('dragover', this.handleDragging); this.attachToEachElement('dragleave', this.handleDragging); break; case 'editableDrop': // Detecting drop on the contenteditables this.attachToEachElement('drop', this.handleDrop); break; // TODO: We need to have a custom 'paste' event separate from 'editablePaste' // Need to think about the way to introduce this without breaking folks case 'editablePaste': // Detecting paste on the contenteditables this.attachToEachElement('paste', this.handlePaste); break; } this.listeners[name] = true; }, attachToEachElement: function (name, handler) { // build our internal cache to know which element got already what handler attached if (!this.eventsCache) { this.eventsCache = []; } this.base.elements.forEach(function (element) { this.attachDOMEvent(element, name, handler.bind(this)); }, this); this.eventsCache.push({ 'name': name, 'handler': handler }); }, cleanupElement: function (element) { var index = element.getAttribute('medium-editor-index'); if (index) { this.detachAllEventsFromElement(element); if (this.contentCache) { delete this.contentCache[index]; } } }, focusElement: function (element) { element.focus(); this.updateFocus(element, { target: element, type: 'focus' }); }, updateFocus: function (target, eventObj) { var hadFocus = this.base.getFocusedElement(), toFocus; // For clicks, we need to know if the mousedown that caused the click happened inside the existing focused element // or one of the extension elements. If so, we don't want to focus another element if (hadFocus && eventObj.type === 'click' && this.lastMousedownTarget && (MediumEditor.util.isDescendant(hadFocus, this.lastMousedownTarget, true) || isElementDescendantOfExtension(this.base.extensions, this.lastMousedownTarget))) { toFocus = hadFocus; } if (!toFocus) { this.base.elements.some(function (element) { // If the target is part of an editor element, this is the element getting focus if (!toFocus && (MediumEditor.util.isDescendant(element, target, true))) { toFocus = element; } // bail if we found an element that's getting focus return !!toFocus; }, this); } // Check if the target is external (not part of the editor, toolbar, or any other extension) var externalEvent = !MediumEditor.util.isDescendant(hadFocus, target, true) && !isElementDescendantOfExtension(this.base.extensions, target); if (toFocus !== hadFocus) { // If element has focus, and focus is going outside of editor // Don't blur focused element if clicking on editor, toolbar, or anchorpreview if (hadFocus && externalEvent) { // Trigger blur on the editable that has lost focus hadFocus.removeAttribute('data-medium-focused'); this.triggerCustomEvent('blur', eventObj, hadFocus); } // If focus is going into an editor element if (toFocus) { // Trigger focus on the editable that now has focus toFocus.setAttribute('data-medium-focused', true); this.triggerCustomEvent('focus', eventObj, toFocus); } } if (externalEvent) { this.triggerCustomEvent('externalInteraction', eventObj); } }, updateInput: function (target, eventObj) { if (!this.contentCache) { return; } // An event triggered which signifies that the user may have changed someting // Look in our cache of input for the contenteditables to see if something changed var index = target.getAttribute('medium-editor-index'), html = target.innerHTML; if (html !== this.contentCache[index]) { // The content has changed since the last time we checked, fire the event this.triggerCustomEvent('editableInput', eventObj, target); } this.contentCache[index] = html; }, handleDocumentSelectionChange: function (event) { // When selectionchange fires, target and current target are set // to document, since this is where the event is handled // However, currentTarget will have an 'activeElement' property // which will point to whatever element has focus. if (event.currentTarget && event.currentTarget.activeElement) { var activeElement = event.currentTarget.activeElement, currentTarget; // We can look at the 'activeElement' to determine if the selectionchange has // happened within a contenteditable owned by this instance of MediumEditor this.base.elements.some(function (element) { if (MediumEditor.util.isDescendant(element, activeElement, true)) { currentTarget = element; return true; } return false; }, this); // We know selectionchange fired within one of our contenteditables if (currentTarget) { this.updateInput(currentTarget, { target: activeElement, currentTarget: currentTarget }); } } }, handleDocumentExecCommand: function () { // document.execCommand has been called // If one of our contenteditables currently has focus, we should // attempt to trigger the 'editableInput' event var target = this.base.getFocusedElement(); if (target) { this.updateInput(target, { target: target, currentTarget: target }); } }, handleBodyClick: function (event) { this.updateFocus(event.target, event); }, handleBodyFocus: function (event) { this.updateFocus(event.target, event); }, handleBodyMousedown: function (event) { this.lastMousedownTarget = event.target; }, handleInput: function (event) { this.updateInput(event.currentTarget, event); }, handleClick: function (event) { this.triggerCustomEvent('editableClick', event, event.currentTarget); }, handleBlur: function (event) { this.triggerCustomEvent('editableBlur', event, event.currentTarget); }, handleKeypress: function (event) { this.triggerCustomEvent('editableKeypress', event, event.currentTarget); // If we're doing manual detection of the editableInput event we need // to check for input changes during 'keypress' if (this.keypressUpdateInput) { var eventObj = { target: event.target, currentTarget: event.currentTarget }; // In IE, we need to let the rest of the event stack complete before we detect // changes to input, so using setTimeout here setTimeout(function () { this.updateInput(eventObj.currentTarget, eventObj); }.bind(this), 0); } }, handleKeyup: function (event) { this.triggerCustomEvent('editableKeyup', event, event.currentTarget); }, handleMouseover: function (event) { this.triggerCustomEvent('editableMouseover', event, event.currentTarget); }, handleDragging: function (event) { this.triggerCustomEvent('editableDrag', event, event.currentTarget); }, handleDrop: function (event) { this.triggerCustomEvent('editableDrop', event, event.currentTarget); }, handlePaste: function (event) { this.triggerCustomEvent('editablePaste', event, event.currentTarget); }, handleKeydown: function (event) { this.triggerCustomEvent('editableKeydown', event, event.currentTarget); if (MediumEditor.util.isKey(event, MediumEditor.util.keyCode.SPACE)) { return this.triggerCustomEvent('editableKeydownSpace', event, event.currentTarget); } if (MediumEditor.util.isKey(event, MediumEditor.util.keyCode.ENTER) || (event.ctrlKey && MediumEditor.util.isKey(event, MediumEditor.util.keyCode.M))) { return this.triggerCustomEvent('editableKeydownEnter', event, event.currentTarget); } if (MediumEditor.util.isKey(event, MediumEditor.util.keyCode.TAB)) { return this.triggerCustomEvent('editableKeydownTab', event, event.currentTarget); } if (MediumEditor.util.isKey(event, [MediumEditor.util.keyCode.DELETE, MediumEditor.util.keyCode.BACKSPACE])) { return this.triggerCustomEvent('editableKeydownDelete', event, event.currentTarget); } } }; MediumEditor.Events = Events; }()); (function () { 'use strict'; var Button = MediumEditor.Extension.extend({ /* Button Options */ /* action: [string] * The action argument to pass to MediumEditor.execAction() * when the button is clicked */ action: undefined, /* aria: [string] * The value to add as the aria-label attribute of the button * element displayed in the toolbar. * This is also used as the tooltip for the button */ aria: undefined, /* tagNames: [Array] * NOTE: This is not used if useQueryState is set to true. * * Array of element tag names that would indicate that this * button has already been applied. If this action has already * been applied, the button will be displayed as 'active' in the toolbar * * Example: * For 'bold', if the text is ever within a or * tag that indicates the text is already bold. So the array * of tagNames for bold would be: ['b', 'strong'] */ tagNames: undefined, /* style: [Object] * NOTE: This is not used if useQueryState is set to true. * * A pair of css property & value(s) that indicate that this * button has already been applied. If this action has already * been applied, the button will be displayed as 'active' in the toolbar * Properties of the object: * prop [String]: name of the css property * value [String]: value(s) of the css property * multiple values can be separated by a '|' * * Example: * For 'bold', if the text is ever within an element with a 'font-weight' * style property set to '700' or 'bold', that indicates the text * is already bold. So the style object for bold would be: * { prop: 'font-weight', value: '700|bold' } */ style: undefined, /* useQueryState: [boolean] * Enables/disables whether this button should use the built-in * document.queryCommandState() method to determine whether * the action has already been applied. If the action has already * been applied, the button will be displayed as 'active' in the toolbar * * Example: * For 'bold', if this is set to true, the code will call: * document.queryCommandState('bold') which will return true if the * browser thinks the text is already bold, and false otherwise */ useQueryState: undefined, /* contentDefault: [string] * Default innerHTML to put inside the button */ contentDefault: undefined, /* contentFA: [string] * The innerHTML to use for the content of the button * if the `buttonLabels` option for MediumEditor is set to 'fontawesome' */ contentFA: undefined, /* classList: [Array] * An array of classNames (strings) to be added to the button */ classList: undefined, /* attrs: [object] * A set of key-value pairs to add to the button as custom attributes */ attrs: undefined, // The button constructor can optionally accept the name of a built-in button // (ie 'bold', 'italic', etc.) // When the name of a button is passed, it will initialize itself with the // configuration for that button constructor: function (options) { if (Button.isBuiltInButton(options)) { MediumEditor.Extension.call(this, this.defaults[options]); } else { MediumEditor.Extension.call(this, options); } }, init: function () { MediumEditor.Extension.prototype.init.apply(this, arguments); this.button = this.createButton(); this.on(this.button, 'click', this.handleClick.bind(this)); }, /* getButton: [function ()] * * If implemented, this function will be called when * the toolbar is being created. The DOM Element returned * by this function will be appended to the toolbar along * with any other buttons. */ getButton: function () { return this.button; }, getAction: function () { return (typeof this.action === 'function') ? this.action(this.base.options) : this.action; }, getAria: function () { return (typeof this.aria === 'function') ? this.aria(this.base.options) : this.aria; }, getTagNames: function () { return (typeof this.tagNames === 'function') ? this.tagNames(this.base.options) : this.tagNames; }, createButton: function () { var button = this.document.createElement('button'), content = this.contentDefault, ariaLabel = this.getAria(), buttonLabels = this.getEditorOption('buttonLabels'); // Add class names button.classList.add('medium-editor-action'); button.classList.add('medium-editor-action-' + this.name); if (this.classList) { this.classList.forEach(function (className) { button.classList.add(className); }); } // Add attributes button.setAttribute('data-action', this.getAction()); if (ariaLabel) { button.setAttribute('title', ariaLabel); button.setAttribute('aria-label', ariaLabel); } if (this.attrs) { Object.keys(this.attrs).forEach(function (attr) { button.setAttribute(attr, this.attrs[attr]); }, this); } if (buttonLabels === 'fontawesome' && this.contentFA) { content = this.contentFA; } button.innerHTML = content; return button; }, handleClick: function (event) { event.preventDefault(); event.stopPropagation(); var action = this.getAction(); if (action) { this.execAction(action); } }, isActive: function () { return this.button.classList.contains(this.getEditorOption('activeButtonClass')); }, setInactive: function () { this.button.classList.remove(this.getEditorOption('activeButtonClass')); delete this.knownState; }, setActive: function () { this.button.classList.add(this.getEditorOption('activeButtonClass')); delete this.knownState; }, queryCommandState: function () { var queryState = null; if (this.useQueryState) { queryState = this.base.queryCommandState(this.getAction()); } return queryState; }, isAlreadyApplied: function (node) { var isMatch = false, tagNames = this.getTagNames(), styleVals, computedStyle; if (this.knownState === false || this.knownState === true) { return this.knownState; } if (tagNames && tagNames.length > 0) { isMatch = tagNames.indexOf(node.nodeName.toLowerCase()) !== -1; } if (!isMatch && this.style) { styleVals = this.style.value.split('|'); computedStyle = this.window.getComputedStyle(node, null).getPropertyValue(this.style.prop); styleVals.forEach(function (val) { if (!this.knownState) { isMatch = (computedStyle.indexOf(val) !== -1); // text-decoration is not inherited by default // so if the computed style for text-decoration doesn't match // don't write to knownState so we can fallback to other checks if (isMatch || this.style.prop !== 'text-decoration') { this.knownState = isMatch; } } }, this); } return isMatch; } }); Button.isBuiltInButton = function (name) { return (typeof name === 'string') && MediumEditor.extensions.button.prototype.defaults.hasOwnProperty(name); }; MediumEditor.extensions.button = Button; }()); (function () { 'use strict'; /* MediumEditor.extensions.button.defaults: [Object] * Set of default config options for all of the built-in MediumEditor buttons */ MediumEditor.extensions.button.prototype.defaults = { 'bold': { name: 'bold', action: 'bold', aria: 'bold', tagNames: ['b', 'strong'], style: { prop: 'font-weight', value: '700|bold' }, useQueryState: true, contentDefault: 'B', contentFA: '' }, 'italic': { name: 'italic', action: 'italic', aria: 'italic', tagNames: ['i', 'em'], style: { prop: 'font-style', value: 'italic' }, useQueryState: true, contentDefault: 'I', contentFA: '' }, 'underline': { name: 'underline', action: 'underline', aria: 'underline', tagNames: ['u'], style: { prop: 'text-decoration', value: 'underline' }, useQueryState: true, contentDefault: 'U', contentFA: '' }, 'strikethrough': { name: 'strikethrough', action: 'strikethrough', aria: 'strike through', tagNames: ['strike'], style: { prop: 'text-decoration', value: 'line-through' }, useQueryState: true, contentDefault: 'A', contentFA: '' }, 'superscript': { name: 'superscript', action: 'superscript', aria: 'superscript', tagNames: ['sup'], /* firefox doesn't behave the way we want it to, so we CAN'T use queryCommandState for superscript https://github.com/guardian/scribe/blob/master/BROWSERINCONSISTENCIES.md#documentquerycommandstate */ // useQueryState: true contentDefault: 'x1', contentFA: '' }, 'subscript': { name: 'subscript', action: 'subscript', aria: 'subscript', tagNames: ['sub'], /* firefox doesn't behave the way we want it to, so we CAN'T use queryCommandState for subscript https://github.com/guardian/scribe/blob/master/BROWSERINCONSISTENCIES.md#documentquerycommandstate */ // useQueryState: true contentDefault: 'x1', contentFA: '' }, 'image': { name: 'image', action: 'image', aria: 'image', tagNames: ['img'], contentDefault: 'image', contentFA: '' }, 'html': { name: 'html', action: 'html', aria: 'evaluate html', tagNames: ['iframe', 'object'], contentDefault: 'html', contentFA: '' }, 'orderedlist': { name: 'orderedlist', action: 'insertorderedlist', aria: 'ordered list', tagNames: ['ol'], useQueryState: true, contentDefault: '1.', contentFA: '' }, 'unorderedlist': { name: 'unorderedlist', action: 'insertunorderedlist', aria: 'unordered list', tagNames: ['ul'], useQueryState: true, contentDefault: '', contentFA: '' }, 'indent': { name: 'indent', action: 'indent', aria: 'indent', tagNames: [], contentDefault: '', contentFA: '' }, 'outdent': { name: 'outdent', action: 'outdent', aria: 'outdent', tagNames: [], contentDefault: '', contentFA: '' }, 'justifyCenter': { name: 'justifyCenter', action: 'justifyCenter', aria: 'center justify', tagNames: [], style: { prop: 'text-align', value: 'center' }, contentDefault: 'C', contentFA: '' }, 'justifyFull': { name: 'justifyFull', action: 'justifyFull', aria: 'full justify', tagNames: [], style: { prop: 'text-align', value: 'justify' }, contentDefault: 'J', contentFA: '' }, 'justifyLeft': { name: 'justifyLeft', action: 'justifyLeft', aria: 'left justify', tagNames: [], style: { prop: 'text-align', value: 'left' }, contentDefault: 'L', contentFA: '' }, 'justifyRight': { name: 'justifyRight', action: 'justifyRight', aria: 'right justify', tagNames: [], style: { prop: 'text-align', value: 'right' }, contentDefault: 'R', contentFA: '' }, // Known inline elements that are not removed, or not removed consistantly across browsers: // ,