diff --git a/dist/epub.js b/dist/epub.js index f04c47a..16f9534 100644 --- a/dist/epub.js +++ b/dist/epub.js @@ -1,1500 +1,706 @@ -if (typeof EPUBJS === 'undefined') { - (typeof window !== 'undefined' ? window : this).EPUBJS = {}; -} - -EPUBJS.VERSION = "0.3.0"; -EPUBJS.Render = {}; - -(function(root) { - "use strict"; - var ePub = function(_url) { - return new EPUBJS.Book(_url); - }; - - ePub.Render = { - register: function(name, renderer) { - ePub.Render[name] = renderer; - } - } - - // CommonJS - if (typeof exports === "object") { - root.RSVP = require("rsvp"); - module.exports = ePub; - // RequireJS - } else if (typeof define === "function" && define.amd) { - define(ePub); - // Global - } else { - root.ePub = ePub; - } - -})(this); - - -(function(global) { -/** - @class RSVP - @module RSVP - */ -var define, require; +/*! + * @overview RSVP - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE + * @version 3.0.13 + */ (function() { - var registry = {}, seen = {}; + "use strict"; - define = function(name, deps, callback) { - registry[name] = { deps: deps, callback: callback }; - }; - - require = function(name) { - - if (seen[name]) { return seen[name]; } - seen[name] = {}; - - if (!registry[name]) { - throw new Error("Could not find module " + name); - } - - var mod = registry[name], - deps = mod.deps, - callback = mod.callback, - reified = [], - exports; - - for (var i=0, l=deps.length; i 1; - }; + If you don't pass a `callback` argument to `off`, ALL callbacks for the + event will not be executed when the event fires. For example: - RSVP.filter(promises, filterFn).then(function(result){ - // result is [ 2, 3 ] - }); - ``` + ```javascript + var callback1 = function(){}; + var callback2 = function(){}; - If any of the `promises` given to `RSVP.filter` are rejected, the first promise - that is rejected will be given as an argument to the returned promise's - rejection handler. For example: + object.on('stuff', callback1); + object.on('stuff', callback2); - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error("2")); - var promise3 = RSVP.reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; + object.trigger('stuff'); // callback1 and callback2 will be executed. - var filterFn = function(item){ - return item > 1; - }; + object.off('stuff'); + object.trigger('stuff'); // callback1 and callback2 will not be executed! + ``` - RSVP.filter(promises, filterFn).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(reason) { - // reason.message === "2" - }); - ``` + @method off + @for RSVP.EventTarget + @private + @param {String} eventName event to stop listening to + @param {Function} callback optional argument. If given, only the function + given will be removed from the event's callback queue. If no `callback` + argument is given, all callbacks will be removed from the event's callback + queue. + */ + off: function(eventName, callback) { + var allCallbacks = $$rsvp$events$$callbacksFor(this), callbacks, index; - `RSVP.filter` will also wait for any promises returned from `filterFn`. - For instance, you may want to fetch a list of users then return a subset - of those users based on some asynchronous operation: + if (!callback) { + allCallbacks[eventName] = []; + return; + } - ```javascript + callbacks = allCallbacks[eventName]; - var alice = { name: 'alice' }; - var bob = { name: 'bob' }; - var users = [ alice, bob ]; + index = $$rsvp$events$$indexOf(callbacks, callback); - var promises = users.map(function(user){ - return RSVP.resolve(user); - }); + if (index !== -1) { callbacks.splice(index, 1); } + }, - var filterFn = function(user){ - // Here, Alice has permissions to create a blog post, but Bob does not. - return getPrivilegesForUser(user).then(function(privs){ - return privs.can_create_blog_post === true; + /** + Use `trigger` to fire custom events. For example: + + ```javascript + object.on('foo', function(){ + console.log('foo event happened!'); }); - }; - RSVP.filter(promises, filterFn).then(function(users){ - // true, because the server told us only Alice can create a blog post. - users.length === 1; - // false, because Alice is the only user present in `users` - users[0] === bob; - }); - ``` + object.trigger('foo'); + // 'foo event happened!' logged to the console + ``` - @method filter - @static - @for RSVP - @param {Array} promises - @param {Function} filterFn - function to be called on each resolved value to - filter the final results. - @param {String} label optional string describing the promise. Useful for - tooling. - @return {Promise} - */ - __exports__['default'] = function filter(promises, filterFn, label) { - return Promise.all(promises, label).then(function (values) { - if (!isFunction(filterFn)) { - throw new TypeError('You must pass a function as filter\'s second argument.'); - } - var length = values.length; - var filtered = new Array(length); - for (var i = 0; i < length; i++) { - filtered[i] = filterFn(values[i]); - } - return Promise.all(filtered, label).then(function (filtered$2) { - var results = new Array(length); - var newLength = 0; - for (var i$2 = 0; i$2 < length; i$2++) { - if (filtered$2[i$2]) { - results[newLength] = values[i$2]; - newLength++; - } - } - results.length = newLength; - return results; - }); + You can also pass a value as a second argument to `trigger` that will be + passed as an argument to all event listeners for the event: + + ```javascript + object.on('foo', function(value){ + console.log(value.name); }); + + object.trigger('foo', { name: 'bar' }); + // 'bar' logged to the console + ``` + + @method trigger + @for RSVP.EventTarget + @private + @param {String} eventName name of the event to be triggered + @param {Any} options optional value to be passed to any event handlers for + the given `eventName` + */ + trigger: function(eventName, options) { + var allCallbacks = $$rsvp$events$$callbacksFor(this), callbacks, callback; + + if (callbacks = allCallbacks[eventName]) { + // Don't cache the callbacks.length since it may grow + for (var i=0; i 1) { + throw new Error('Second argument not supported'); + } + if (typeof o !== 'object') { + throw new TypeError('Argument must be an object'); + } + $$utils$$F.prototype = o; + return new $$utils$$F(); + }); - @method hash - @static - @for RSVP - @param {Object} promises - @param {String} label optional string that describes the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all properties of `promises` - have been fulfilled, or rejected if any of them become rejected. - */ - __exports__['default'] = function hash(object, label) { - return new PromiseHash(Promise, object, label).promise; - }; -}); -define('rsvp/instrument', [ - './config', - './utils', - 'exports' -], function (__dependency1__, __dependency2__, __exports__) { - 'use strict'; - var config = __dependency1__.config; - var now = __dependency2__.now; - var queue = []; - __exports__['default'] = function instrument(eventName, promise, child) { - if (1 === queue.push({ - name: eventName, - payload: { - guid: promise._guidKey + promise._id, - eventName: eventName, - detail: promise._result, - childGuid: child && promise._guidKey + child._id, - label: promise._label, - timeStamp: now(), - stack: new Error(promise._label).stack - } - })) { - setTimeout(function () { - var entry; - for (var i = 0; i < queue.length; i++) { - entry = queue[i]; - config.trigger(entry.name, entry.payload); - } - queue.length = 0; + var $$instrument$$queue = []; + + var $$instrument$$default = function instrument(eventName, promise, child) { + if (1 === $$instrument$$queue.push({ + name: eventName, + payload: { + guid: promise._guidKey + promise._id, + eventName: eventName, + detail: promise._result, + childGuid: child && promise._guidKey + child._id, + label: promise._label, + timeStamp: $$utils$$now(), + stack: new Error(promise._label).stack + }})) { + + setTimeout(function() { + var entry; + for (var i = 0; i < $$instrument$$queue.length; i++) { + entry = $$instrument$$queue[i]; + $$rsvp$config$$config.trigger(entry.name, entry.payload); + } + $$instrument$$queue.length = 0; }, 50); + } + }; + + function $$$internal$$noop() {} + var $$$internal$$PENDING = void 0; + var $$$internal$$FULFILLED = 1; + var $$$internal$$REJECTED = 2; + var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); + + function $$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + $$$internal$$GET_THEN_ERROR.error = error; + return $$$internal$$GET_THEN_ERROR; + } + } + + function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function $$$internal$$handleForeignThenable(promise, thenable, then) { + $$rsvp$config$$config.async(function(promise) { + var sealed = false; + var error = $$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + $$$internal$$resolve(promise, value); + } else { + $$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + $$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + $$$internal$$reject(promise, error); } + }, promise); + } + + function $$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === $$$internal$$FULFILLED) { + $$$internal$$fulfill(promise, thenable._result); + } else if (promise._state === $$$internal$$REJECTED) { + $$$internal$$reject(promise, thenable._result); + } else { + $$$internal$$subscribe(thenable, undefined, function(value) { + if (thenable !== value) { + $$$internal$$resolve(promise, value); + } else { + $$$internal$$fulfill(promise, value); + } + }, function(reason) { + $$$internal$$reject(promise, reason); + }); + } + } + + function $$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + $$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = $$$internal$$getThen(maybeThenable); + + if (then === $$$internal$$GET_THEN_ERROR) { + $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + $$$internal$$fulfill(promise, maybeThenable); + } else if ($$utils$$isFunction(then)) { + $$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + $$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function $$$internal$$resolve(promise, value) { + if (promise === value) { + $$$internal$$fulfill(promise, value); + } else if ($$utils$$objectOrFunction(value)) { + $$$internal$$handleMaybeThenable(promise, value); + } else { + $$$internal$$fulfill(promise, value); + } + } + + function $$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + $$$internal$$publish(promise); + } + + function $$$internal$$fulfill(promise, value) { + if (promise._state !== $$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = $$$internal$$FULFILLED; + + if (promise._subscribers.length === 0) { + if ($$rsvp$config$$config.instrument) { + $$instrument$$default('fulfilled', promise); + } + } else { + $$rsvp$config$$config.async($$$internal$$publish, promise); + } + } + + function $$$internal$$reject(promise, reason) { + if (promise._state !== $$$internal$$PENDING) { return; } + promise._state = $$$internal$$REJECTED; + promise._result = reason; + + $$rsvp$config$$config.async($$$internal$$publishRejection, promise); + } + + function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + $$$internal$$FULFILLED] = onFulfillment; + subscribers[length + $$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + $$rsvp$config$$config.async($$$internal$$publish, parent); + } + } + + function $$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if ($$rsvp$config$$config.instrument) { + $$instrument$$default(settled === $$$internal$$FULFILLED ? 'fulfilled' : 'rejected', promise); + } + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + $$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function $$$internal$$ErrorObject() { + this.error = null; + } + + var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); + + function $$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + $$$internal$$TRY_CATCH_ERROR.error = e; + return $$$internal$$TRY_CATCH_ERROR; + } + } + + function $$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = $$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = $$$internal$$tryCatch(callback, detail); + + if (value === $$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + $$$internal$$reject(promise, new TypeError('A promises callback cannot return that same promise.')); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== $$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + $$$internal$$resolve(promise, value); + } else if (failed) { + $$$internal$$reject(promise, error); + } else if (settled === $$$internal$$FULFILLED) { + $$$internal$$fulfill(promise, value); + } else if (settled === $$$internal$$REJECTED) { + $$$internal$$reject(promise, value); + } + } + + function $$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + $$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + $$$internal$$reject(promise, reason); + }); + } catch(e) { + $$$internal$$reject(promise, e); + } + } + + function $$enumerator$$makeSettledResult(state, position, value) { + if (state === $$$internal$$FULFILLED) { + return { + state: 'fulfilled', + value: value + }; + } else { + return { + state: 'rejected', + reason: value + }; + } + } + + function $$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { + this._instanceConstructor = Constructor; + this.promise = new Constructor($$$internal$$noop, label); + this._abortOnReject = abortOnReject; + + if (this._validateInput(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._init(); + + if (this.length === 0) { + $$$internal$$fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + $$$internal$$fulfill(this.promise, this._result); + } + } + } else { + $$$internal$$reject(this.promise, this._validationError()); + } + } + + $$enumerator$$Enumerator.prototype._validateInput = function(input) { + return $$utils$$isArray(input); }; -}); -define('rsvp/map', [ - './promise', - './utils', - 'exports' -], function (__dependency1__, __dependency2__, __exports__) { - 'use strict'; - var Promise = __dependency1__['default']; - var isArray = __dependency2__.isArray; - var isFunction = __dependency2__.isFunction; - /** - `RSVP.map` is similar to JavaScript's native `map` method, except that it - waits for all promises to become fulfilled before running the `mapFn` on - each item in given to `promises`. `RSVP.map` returns a promise that will - become fulfilled with the result of running `mapFn` on the values the promises - become fulfilled with. - For example: + $$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; - ```javascript + $$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.resolve(2); - var promise3 = RSVP.resolve(3); - var promises = [ promise1, promise2, promise3 ]; + var $$enumerator$$default = $$enumerator$$Enumerator; - var mapFn = function(item){ - return item + 1; - }; + $$enumerator$$Enumerator.prototype._enumerate = function() { + var length = this.length; + var promise = this.promise; + var input = this._input; - RSVP.map(promises, mapFn).then(function(result){ - // result is [ 2, 3, 4 ] - }); - ``` + for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { + this._eachEntry(input[i], i); + } + }; - If any of the `promises` given to `RSVP.map` are rejected, the first promise - that is rejected will be given as an argument to the returned promise's - rejection handler. For example: + $$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + if ($$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { + entry._onerror = null; + this._settledAt(entry._state, i, entry._result); + } else { + this._willSettleAt(c.resolve(entry), i); + } + } else { + this._remaining--; + this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); + } + }; - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error("2")); - var promise3 = RSVP.reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; + $$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; - var mapFn = function(item){ - return item + 1; - }; + if (promise._state === $$$internal$$PENDING) { + this._remaining--; - RSVP.map(promises, mapFn).then(function(array){ - // Code here never runs because there are rejected promises! + if (this._abortOnReject && state === $$$internal$$REJECTED) { + $$$internal$$reject(promise, value); + } else { + this._result[i] = this._makeResult(state, i, value); + } + } + + if (this._remaining === 0) { + $$$internal$$fulfill(promise, this._result); + } + }; + + $$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { + return value; + }; + + $$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + $$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { - // reason.message === "2" + enumerator._settledAt($$$internal$$REJECTED, i, reason); }); - ``` - - `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, - say you want to get all comments from a set of blog posts, but you need - the blog posts first because they contain a url to those comments. - - ```javscript - - var mapFn = function(blogPost){ - // getComments does some ajax and returns an RSVP.Promise that is fulfilled - // with some comments data - return getComments(blogPost.comments_url); - }; - - // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled - // with some blog post data - RSVP.map(getBlogPosts(), mapFn).then(function(comments){ - // comments is the result of asking the server for the comments - // of all blog posts returned from getBlogPosts() - }); - ``` - - @method map - @static - @for RSVP - @param {Array} promises - @param {Function} mapFn function to be called on each fulfilled promise. - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled with the result of calling - `mapFn` on each fulfilled promise or value when they become fulfilled. - The promise will be rejected if any of the given `promises` become rejected. - @static - */ - __exports__['default'] = function map(promises, mapFn, label) { - return Promise.all(promises, label).then(function (values) { - if (!isFunction(mapFn)) { - throw new TypeError('You must pass a function as map\'s second argument.'); - } - var length = values.length; - var results = new Array(length); - for (var i = 0; i < length; i++) { - results[i] = mapFn(values[i]); - } - return Promise.all(results, label); - }); }; -}); -define('rsvp/node', [ - './promise', - './utils', - 'exports' -], function (__dependency1__, __dependency2__, __exports__) { - 'use strict'; - /* global arraySlice */ - var Promise = __dependency1__['default']; - var isArray = __dependency2__.isArray; - /** - `RSVP.denodeify` takes a "node-style" function and returns a function that - will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the - browser when you'd prefer to use promises over using callbacks. For example, - `denodeify` transforms the following: - ```javascript - var fs = require('fs'); - - fs.readFile('myfile.txt', function(err, data){ - if (err) return handleError(err); - handleData(data); - }); - ``` - - into: - - ```javascript - var fs = require('fs'); - var readFile = RSVP.denodeify(fs.readFile); - - readFile('myfile.txt').then(handleData, handleError); - ``` - - If the node function has multiple success parameters, then `denodeify` - just returns the first one: - - ```javascript - var request = RSVP.denodeify(require('request')); - - request('http://example.com').then(function(res) { - // ... - }); - ``` - - However, if you need all success parameters, setting `denodeify`'s - second parameter to `true` causes it to return all success parameters - as an array: - - ```javascript - var request = RSVP.denodeify(require('request'), true); - - request('http://example.com').then(function(result) { - // result[0] -> res - // result[1] -> body - }); - ``` - - Or if you pass it an array with names it returns the parameters as a hash: - - ```javascript - var request = RSVP.denodeify(require('request'), ['res', 'body']); - - request('http://example.com').then(function(result) { - // result.res - // result.body - }); - ``` - - Sometimes you need to retain the `this`: - - ```javascript - var app = require('express')(); - var render = RSVP.denodeify(app.render.bind(app)); - ``` - - The denodified function inherits from the original function. It works in all - environments, except IE 10 and below. Consequently all properties of the original - function are available to you. However, any properties you change on the - denodeified function won't be changed on the original function. Example: - - ```javascript - var request = RSVP.denodeify(require('request')), - cookieJar = request.jar(); // <- Inheritance is used here - - request('http://example.com', {jar: cookieJar}).then(function(res) { - // cookieJar.cookies holds now the cookies returned by example.com - }); - ``` - - Using `denodeify` makes it easier to compose asynchronous operations instead - of using callbacks. For example, instead of: - - ```javascript - var fs = require('fs'); - - fs.readFile('myfile.txt', function(err, data){ - if (err) { ... } // Handle error - fs.writeFile('myfile2.txt', data, function(err){ - if (err) { ... } // Handle error - console.log('done') - }); - }); - ``` - - you can chain the operations together using `then` from the returned promise: - - ```javascript - var fs = require('fs'); - var readFile = RSVP.denodeify(fs.readFile); - var writeFile = RSVP.denodeify(fs.writeFile); - - readFile('myfile.txt').then(function(data){ - return writeFile('myfile2.txt', data); - }).then(function(){ - console.log('done') - }).catch(function(error){ - // Handle error - }); - ``` - - @method denodeify - @static - @for RSVP - @param {Function} nodeFunc a "node-style" function that takes a callback as - its last argument. The callback expects an error to be passed as its first - argument (if an error occurred, otherwise null), and the value from the - operation as its second argument ("function(err, value){ }"). - @param {Boolean|Array} argumentNames An optional paramter that if set - to `true` causes the promise to fulfill with the callback's success arguments - as an array. This is useful if the node function has multiple success - paramters. If you set this paramter to an array with names, the promise will - fulfill with a hash with these names as keys and the success parameters as - values. - @return {Function} a function that wraps `nodeFunc` to return an - `RSVP.Promise` - @static - */ - __exports__['default'] = function denodeify(nodeFunc, argumentNames) { - var asArray = argumentNames === true; - var asHash = isArray(argumentNames); - function denodeifiedFunction() { - var length = arguments.length; - var nodeArgs = new Array(length); - for (var i = 0; i < length; i++) { - nodeArgs[i] = arguments[i]; - } - var thisArg; - if (!asArray && !asHash && argumentNames) { - if (typeof console === 'object') { - console.warn('Deprecation: RSVP.denodeify() doesn\'t allow setting the ' + '"this" binding anymore. Use yourFunction.bind(yourThis) instead.'); - } - thisArg = argumentNames; - } else { - thisArg = this; - } - return Promise.all(nodeArgs).then(function (nodeArgs$2) { - return new Promise(resolver); - // sweet.js has a bug, this resolver can't be defined in the constructor - // or the arraySlice macro doesn't work - function resolver(resolve, reject) { - function callback() { - var length$2 = arguments.length; - var args = new Array(length$2); - for (var i$2 = 0; i$2 < length$2; i$2++) { - args[i$2] = arguments[i$2]; - } - var error = args[0]; - var value = args[1]; - if (error) { - reject(error); - } else if (asArray) { - resolve(args.slice(1)); - } else if (asHash) { - var obj = {}; - var successArguments = args.slice(1); - var name; - var i$3; - for (i$3 = 0; i$3 < argumentNames.length; i$3++) { - name = argumentNames[i$3]; - obj[name] = successArguments[i$3]; - } - resolve(obj); - } else { - resolve(value); - } - } - nodeArgs$2.push(callback); - nodeFunc.apply(thisArg, nodeArgs$2); - } - }); - } - denodeifiedFunction.__proto__ = nodeFunc; - return denodeifiedFunction; + var $$promise$all$$default = function all(entries, label) { + return new $$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; -}); -define('rsvp/promise-hash', [ - './enumerator', - './-internal', - './utils', - 'exports' -], function (__dependency1__, __dependency2__, __dependency3__, __exports__) { - 'use strict'; - var Enumerator = __dependency1__['default']; - var PENDING = __dependency2__.PENDING; - var FULFILLED = __dependency2__.FULFILLED; - var o_create = __dependency3__.o_create; - function PromiseHash(Constructor, object, label) { - this._superConstructor(Constructor, object, true, label); + + var $$promise$race$$default = function race(entries, label) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor($$$internal$$noop, label); + + if (!$$utils$$isArray(entries)) { + $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + $$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + $$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { + $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + }; + + var $$promise$resolve$$default = function resolve(object, label) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor($$$internal$$noop, label); + $$$internal$$resolve(promise, object); + return promise; + }; + + var $$promise$reject$$default = function reject(reason, label) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor($$$internal$$noop, label); + $$$internal$$reject(promise, reason); + return promise; + }; + + var $$rsvp$promise$$guidKey = 'rsvp_' + $$utils$$now() + '-'; + var $$rsvp$promise$$counter = 0; + + function $$rsvp$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } - __exports__['default'] = PromiseHash; - PromiseHash.prototype = o_create(Enumerator.prototype); - PromiseHash.prototype._superConstructor = Enumerator; - PromiseHash.prototype._init = function () { - this._result = {}; - }; - PromiseHash.prototype._validateInput = function (input) { - return input && typeof input === 'object'; - }; - PromiseHash.prototype._validationError = function () { - return new Error('Promise.hash must be called with an object'); - }; - PromiseHash.prototype._enumerate = function () { - var promise = this.promise; - var input = this._input; - var results = []; - for (var key in input) { - if (promise._state === PENDING && input.hasOwnProperty(key)) { - results.push({ - position: key, - entry: input[key] - }); - } - } - var length = results.length; - this._remaining = length; - var result; - for (var i = 0; promise._state === PENDING && i < length; i++) { - result = results[i]; - this._eachEntry(result.entry, result.position); - } - }; -}); -define('rsvp/promise', [ - './config', - './events', - './instrument', - './utils', - './-internal', - './promise/cast', - './promise/all', - './promise/race', - './promise/resolve', - './promise/reject', - 'exports' -], function (__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __exports__) { - 'use strict'; - var config = __dependency1__.config; - var EventTarget = __dependency2__['default']; - var instrument = __dependency3__['default']; - var objectOrFunction = __dependency4__.objectOrFunction; - var isFunction = __dependency4__.isFunction; - var now = __dependency4__.now; - var noop = __dependency5__.noop; - var resolve = __dependency5__.resolve; - var reject = __dependency5__.reject; - var fulfill = __dependency5__.fulfill; - var subscribe = __dependency5__.subscribe; - var initializePromise = __dependency5__.initializePromise; - var invokeCallback = __dependency5__.invokeCallback; - var FULFILLED = __dependency5__.FULFILLED; - var cast = __dependency6__['default']; - var all = __dependency7__['default']; - var race = __dependency8__['default']; - var Resolve = __dependency9__['default']; - var Reject = __dependency10__['default']; - var guidKey = 'rsvp_' + now() + '-'; - var counter = 0; - function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + + function $$rsvp$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } - function needsNew() { - throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); - } - __exports__['default'] = Promise; + + var $$rsvp$promise$$default = $$rsvp$promise$$Promise; + /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which @@ -1565,7 +771,7 @@ define('rsvp/promise', [ if (this.status === 200) { resolve(this.response); } else { - reject(new Error("getJSON: `" + url + "` failed with status: [" + this.status + "]")); + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; @@ -1599,637 +805,836 @@ define('rsvp/promise', [ Useful for tooling. @constructor */ - function Promise(resolver, label) { - this._id = counter++; - this._label = label; - this._subscribers = []; - if (config.instrument) { - instrument('created', this); - } - if (noop !== resolver) { - if (!isFunction(resolver)) { - needsResolver(); - } - if (!(this instanceof Promise)) { - needsNew(); - } - initializePromise(this, resolver); - } - } - Promise.cast = cast; - Promise.all = all; - Promise.race = race; - Promise.resolve = Resolve; - Promise.reject = Reject; - Promise.prototype = { - constructor: Promise, - _id: undefined, - _guidKey: guidKey, - _label: undefined, - _state: undefined, - _result: undefined, - _subscribers: undefined, - _onerror: function (reason) { - config.trigger('error', reason); - }, - then: function (onFulfillment, onRejection, label) { - var parent = this; - parent._onerror = null; - var child = new this.constructor(noop, label); - var state = parent._state; - var result = parent._result; - if (config.instrument) { - instrument('chained', parent, child); - } - if (state === FULFILLED && onFulfillment) { - config.async(function () { - invokeCallback(state, child, onFulfillment, result); - }); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } - return child; - }, - 'catch': function (onRejection, label) { - return this.then(null, onRejection, label); - }, - 'finally': function (callback, label) { - var constructor = this.constructor; - return this.then(function (value) { - return constructor.resolve(callback()).then(function () { - return value; - }); - }, function (reason) { - return constructor.resolve(callback()).then(function () { - throw reason; - }); - }, label); - } - }; -}); -define('rsvp/promise/all', [ - '../enumerator', - 'exports' -], function (__dependency1__, __exports__) { - 'use strict'; - var Enumerator = __dependency1__['default']; - /** - `RSVP.Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. + function $$rsvp$promise$$Promise(resolver, label) { + this._id = $$rsvp$promise$$counter++; + this._label = label; + this._state = undefined; + this._result = undefined; + this._subscribers = []; - Example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.resolve(2); - var promise3 = RSVP.resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - RSVP.Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `RSVP.all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error("2")); - var promise3 = RSVP.reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - RSVP.Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static - */ - __exports__['default'] = function all(entries, label) { - return new Enumerator(this, entries, true, label).promise; - }; -}); -define('rsvp/promise/cast', [ - './resolve', - 'exports' -], function (__dependency1__, __exports__) { - 'use strict'; - var resolve = __dependency1__['default']; - /** - @deprecated - - `RSVP.Promise.cast` coerces its argument to a promise, or returns the - argument if it is already a promise which shares a constructor with the caster. - - Example: - - ```javascript - var promise = RSVP.Promise.resolve(1); - var casted = RSVP.Promise.cast(promise); - - console.log(promise === casted); // true - ``` - - In the case of a promise whose constructor does not match, it is assimilated. - The resulting promise will fulfill or reject based on the outcome of the - promise being casted. - - Example: - - ```javascript - var thennable = $.getJSON('/api/foo'); - var casted = RSVP.Promise.cast(thennable); - - console.log(thennable === casted); // false - console.log(casted instanceof RSVP.Promise) // true - - casted.then(function(data) { - // data is the value getJSON fulfills with - }); - ``` - - In the case of a non-promise, a promise which will fulfill with that value is - returned. - - Example: - - ```javascript - var value = 1; // could be a number, boolean, string, undefined... - var casted = RSVP.Promise.cast(value); - - console.log(value === casted); // false - console.log(casted instanceof RSVP.Promise) // true - - casted.then(function(val) { - val === value // => true - }); - ``` - - `RSVP.Promise.cast` is similar to `RSVP.Promise.resolve`, but `RSVP.Promise.cast` differs in the - following ways: - - * `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you - have something that could either be a promise or a value. RSVP.resolve - will have the same effect but will create a new promise wrapper if the - argument is a promise. - * `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to - promises of the exact class specified, so that the resulting object's `then` is - ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise). - - @method cast - @static - @param {Object} object to be casted - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise - */ - __exports__['default'] = resolve; -}); -define('rsvp/promise/race', [ - '../utils', - '../-internal', - 'exports' -], function (__dependency1__, __dependency2__, __exports__) { - 'use strict'; - var isArray = __dependency1__.isArray; - var isFunction = __dependency1__.isFunction; - var isMaybeThenable = __dependency1__.isMaybeThenable; - var noop = __dependency2__.noop; - var resolve = __dependency2__.resolve; - var reject = __dependency2__.reject; - var subscribe = __dependency2__.subscribe; - var PENDING = __dependency2__.PENDING; - /** - `RSVP.Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - var promise1 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve("promise 1"); - }, 200); - }); - - var promise2 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve("promise 2"); - }, 100); - }); - - RSVP.Promise.race([promise1, promise2]).then(function(result){ - // result === "promise 2" because it was resolved before promise1 - // was resolved. - }); - ``` - - `RSVP.Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - var promise1 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve("promise 1"); - }, 200); - }); - - var promise2 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error("promise 2")); - }, 100); - }); - - RSVP.Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === "promise 2" because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - RSVP.Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} promises array of promises to observe - @param {String} label optional string for describing the promise returned. - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. - */ - __exports__['default'] = function race(entries, label) { - /*jshint validthis:true */ - var Constructor = this, entry; - var promise = new Constructor(noop, label); - if (!isArray(entries)) { - reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - var length = entries.length; - function onFulfillment(value) { - resolve(promise, value); - } - function onRejection(reason) { - reject(promise, reason); - } - for (var i = 0; promise._state === PENDING && i < length; i++) { - subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - return promise; - }; -}); -define('rsvp/promise/reject', [ - '../-internal', - 'exports' -], function (__dependency1__, __exports__) { - 'use strict'; - var noop = __dependency1__.noop; - var _reject = __dependency1__.reject; - /** - `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: - - ```javascript - var promise = new RSVP.Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = RSVP.Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @static - @param {Any} reason value that the returned promise will be rejected with. - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. - */ - __exports__['default'] = function reject(reason, label) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop, label); - _reject(promise, reason); - return promise; - }; -}); -define('rsvp/promise/resolve', [ - '../-internal', - 'exports' -], function (__dependency1__, __exports__) { - 'use strict'; - var noop = __dependency1__.noop; - var _resolve = __dependency1__.resolve; - /** - `RSVP.Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - var promise = new RSVP.Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = RSVP.Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {Any} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - __exports__['default'] = function resolve(object, label) { - /*jshint validthis:true */ - var Constructor = this; - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - var promise = new Constructor(noop, label); - _resolve(promise, object); - return promise; - }; -}); -define('rsvp/race', [ - './promise', - 'exports' -], function (__dependency1__, __exports__) { - 'use strict'; - var Promise = __dependency1__['default']; - /** - This is a convenient alias for `RSVP.Promise.race`. - - @method race - @static - @for RSVP - @param {Array} array Array of promises. - @param {String} label An optional label. This is useful - for tooling. - */ - __exports__['default'] = function race(array, label) { - return Promise.race(array, label); - }; -}); -define('rsvp/reject', [ - './promise', - 'exports' -], function (__dependency1__, __exports__) { - 'use strict'; - var Promise = __dependency1__['default']; - /** - This is a convenient alias for `RSVP.Promise.reject`. - - @method reject - @static - @for RSVP - @param {Any} reason value that the returned promise will be rejected with. - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. - */ - __exports__['default'] = function reject(reason, label) { - return Promise.reject(reason, label); - }; -}); -define('rsvp/resolve', [ - './promise', - 'exports' -], function (__dependency1__, __exports__) { - 'use strict'; - var Promise = __dependency1__['default']; - /** - This is a convenient alias for `RSVP.Promise.resolve`. - - @method resolve - @static - @for RSVP - @param {Any} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - __exports__['default'] = function resolve(value, label) { - return Promise.resolve(value, label); - }; -}); -define('rsvp/rethrow', ['exports'], function (__exports__) { - 'use strict'; - /** - `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event - loop in order to aid debugging. - - Promises A+ specifies that any exceptions that occur with a promise must be - caught by the promises implementation and bubbled to the last handler. For - this reason, it is recommended that you always specify a second rejection - handler function to `then`. However, `RSVP.rethrow` will throw the exception - outside of the promise, so it bubbles up to your console if in the browser, - or domain/cause uncaught exception in Node. `rethrow` will also throw the - error again so the error can be handled by the promise per the spec. - - ```javascript - function throws(){ - throw new Error('Whoops!'); + if ($$rsvp$config$$config.instrument) { + $$instrument$$default('created', this); } - var promise = new RSVP.Promise(function(resolve, reject){ - throws(); - }); + if ($$$internal$$noop !== resolver) { + if (!$$utils$$isFunction(resolver)) { + $$rsvp$promise$$needsResolver(); + } - promise.catch(RSVP.rethrow).then(function(){ - // Code here doesn't run because the promise became rejected due to an - // error! - }, function (err){ - // handle the error here + if (!(this instanceof $$rsvp$promise$$Promise)) { + $$rsvp$promise$$needsNew(); + } + + $$$internal$$initializePromise(this, resolver); + } + } + + // deprecated + $$rsvp$promise$$Promise.cast = $$promise$resolve$$default; + + $$rsvp$promise$$Promise.all = $$promise$all$$default; + $$rsvp$promise$$Promise.race = $$promise$race$$default; + $$rsvp$promise$$Promise.resolve = $$promise$resolve$$default; + $$rsvp$promise$$Promise.reject = $$promise$reject$$default; + + $$rsvp$promise$$Promise.prototype = { + constructor: $$rsvp$promise$$Promise, + + _guidKey: $$rsvp$promise$$guidKey, + + _onerror: function (reason) { + $$rsvp$config$$config.trigger('error', reason); + }, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why }); ``` - The 'Whoops' error will be thrown on the next turn of the event loop - and you can watch for it in your console. You can also handle it using a - rejection handler given to `.then` or `.catch` on the returned promise. + Chaining + -------- - @method rethrow - @static - @for RSVP - @param {Error} reason reason the promise became rejected. - @throws Error - @static - */ - __exports__['default'] = function rethrow(reason) { - setTimeout(function () { - throw reason; - }); - throw reason; - }; -}); -define('rsvp/utils', ['exports'], function (__exports__) { - 'use strict'; - function objectOrFunction(x) { - return typeof x === 'function' || typeof x === 'object' && x !== null; - } - __exports__.objectOrFunction = objectOrFunction; - function isFunction(x) { - return typeof x === 'function'; - } - __exports__.isFunction = isFunction; - function isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - __exports__.isMaybeThenable = isMaybeThenable; - var _isArray; - if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - _isArray = Array.isArray; - } - var isArray = _isArray; - __exports__.isArray = isArray; - // Date.now is not available in browsers < IE9 - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility - var now = Date.now || function () { - return new Date().getTime(); - }; - __exports__.now = now; - var o_create = Object.create || function (object) { - var o = function () { - }; - o.prototype = object; - return o; - }; - __exports__.o_create = o_create; -}); -define('rsvp', [ - './rsvp/promise', - './rsvp/events', - './rsvp/node', - './rsvp/all', - './rsvp/all-settled', - './rsvp/race', - './rsvp/hash', - './rsvp/hash-settled', - './rsvp/rethrow', - './rsvp/defer', - './rsvp/config', - './rsvp/map', - './rsvp/resolve', - './rsvp/reject', - './rsvp/filter', - './rsvp/asap', - 'exports' -], function (__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __dependency16__, __exports__) { - 'use strict'; - var Promise = __dependency1__['default']; - var EventTarget = __dependency2__['default']; - var denodeify = __dependency3__['default']; - var all = __dependency4__['default']; - var allSettled = __dependency5__['default']; - var race = __dependency6__['default']; - var hash = __dependency7__['default']; - var hashSettled = __dependency8__['default']; - var rethrow = __dependency9__['default']; - var defer = __dependency10__['default']; - var config = __dependency11__.config; - var configure = __dependency11__.configure; - var map = __dependency12__['default']; - var resolve = __dependency13__['default']; - var reject = __dependency14__['default']; - var filter = __dependency15__['default']; - var asap = __dependency16__['default']; - config.async = asap; - // default async is asap; - function async(callback, arg) { - config.async(callback, arg); - } - function on() { - config.on.apply(config, arguments); - } - function off() { - config.off.apply(config, arguments); - } - // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` - if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') { - var callbacks = window.__PROMISE_INSTRUMENTATION__; - configure('instrument', true); - for (var eventName in callbacks) { - if (callbacks.hasOwnProperty(eventName)) { - on(eventName, callbacks[eventName]); - } + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection, label) { + var parent = this; + var state = parent._state; + + if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { + if ($$rsvp$config$$config.instrument) { + $$instrument$$default('chained', this, this); + } + return this; + } + + parent._onerror = null; + + var child = new this.constructor($$$internal$$noop, label); + var result = parent._result; + + if ($$rsvp$config$$config.instrument) { + $$instrument$$default('chained', parent, child); + } + + if (state) { + var callback = arguments[state - 1]; + $$rsvp$config$$config.async(function(){ + $$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + $$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection, label) { + return this.then(null, onRejection, label); + }, + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + Synchronous example: + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't affect the return value + } + ``` + + Asynchronous example: + + ```js + findAuthor().catch(function(reason){ + return findOtherAuther(); + }).finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'finally': function(callback, label) { + var constructor = this.constructor; + + return this.then(function(value) { + return constructor.resolve(callback()).then(function(){ + return value; + }); + }, function(reason) { + return constructor.resolve(callback()).then(function(){ + throw reason; + }); + }, label); + } + }; + + function $$rsvp$node$$Result() { + this.value = undefined; } - __exports__.Promise = Promise; - __exports__.EventTarget = EventTarget; - __exports__.all = all; - __exports__.allSettled = allSettled; - __exports__.race = race; - __exports__.hash = hash; - __exports__.hashSettled = hashSettled; - __exports__.rethrow = rethrow; - __exports__.defer = defer; - __exports__.denodeify = denodeify; - __exports__.configure = configure; - __exports__.on = on; - __exports__.off = off; - __exports__.resolve = resolve; - __exports__.reject = reject; - __exports__.async = async; - __exports__.map = map; - __exports__.filter = filter; -}); -global.RSVP = require('rsvp'); -}(self)); + + var $$rsvp$node$$ERROR = new $$rsvp$node$$Result(); + var $$rsvp$node$$GET_THEN_ERROR = new $$rsvp$node$$Result(); + + function $$rsvp$node$$getThen(obj) { + try { + return obj.then; + } catch(error) { + $$rsvp$node$$ERROR.value= error; + return $$rsvp$node$$ERROR; + } + } + + function $$rsvp$node$$tryApply(f, s, a) { + try { + f.apply(s, a); + } catch(error) { + $$rsvp$node$$ERROR.value = error; + return $$rsvp$node$$ERROR; + } + } + + function $$rsvp$node$$makeObject(_, argumentNames) { + var obj = {}; + var name; + var i; + var length = _.length; + var args = new Array(length); + + for (var x = 0; x < length; x++) { + args[x] = _[x]; + } + + for (i = 0; i < argumentNames.length; i++) { + name = argumentNames[i]; + obj[name] = args[i + 1]; + } + + return obj; + } + + function $$rsvp$node$$arrayResult(_) { + var length = _.length; + var args = new Array(length - 1); + + for (var i = 1; i < length; i++) { + args[i - 1] = _[i]; + } + + return args; + } + + function $$rsvp$node$$wrapThenable(then, promise) { + return { + then: function(onFulFillment, onRejection) { + return then.call(promise, onFulFillment, onRejection); + } + }; + } + + var $$rsvp$node$$default = function denodeify(nodeFunc, options) { + var fn = function() { + var self = this; + var l = arguments.length; + var args = new Array(l + 1); + var arg; + var promiseInput = false; + + for (var i = 0; i < l; ++i) { + arg = arguments[i]; + + if (!promiseInput) { + // TODO: clean this up + promiseInput = $$rsvp$node$$needsPromiseInput(arg); + if (promiseInput === $$rsvp$node$$GET_THEN_ERROR) { + var p = new $$rsvp$promise$$default($$$internal$$noop); + $$$internal$$reject(p, $$rsvp$node$$GET_THEN_ERROR.value); + return p; + } else if (promiseInput && promiseInput !== true) { + arg = $$rsvp$node$$wrapThenable(promiseInput, arg); + } + } + args[i] = arg; + } + + var promise = new $$rsvp$promise$$default($$$internal$$noop); + + args[l] = function(err, val) { + if (err) + $$$internal$$reject(promise, err); + else if (options === undefined) + $$$internal$$resolve(promise, val); + else if (options === true) + $$$internal$$resolve(promise, $$rsvp$node$$arrayResult(arguments)); + else if ($$utils$$isArray(options)) + $$$internal$$resolve(promise, $$rsvp$node$$makeObject(arguments, options)); + else + $$$internal$$resolve(promise, val); + }; + + if (promiseInput) { + return $$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self); + } else { + return $$rsvp$node$$handleValueInput(promise, args, nodeFunc, self); + } + }; + + fn.__proto__ = nodeFunc; + + return fn; + }; + + function $$rsvp$node$$handleValueInput(promise, args, nodeFunc, self) { + var result = $$rsvp$node$$tryApply(nodeFunc, self, args); + if (result === $$rsvp$node$$ERROR) { + $$$internal$$reject(promise, result.value); + } + return promise; + } + + function $$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self){ + return $$rsvp$promise$$default.all(args).then(function(args){ + var result = $$rsvp$node$$tryApply(nodeFunc, self, args); + if (result === $$rsvp$node$$ERROR) { + $$$internal$$reject(promise, result.value); + } + return promise; + }); + } + + function $$rsvp$node$$needsPromiseInput(arg) { + if (arg && typeof arg === 'object') { + if (arg.constructor === $$rsvp$promise$$default) { + return true; + } else { + return $$rsvp$node$$getThen(arg); + } + } else { + return false; + } + } + + var $$rsvp$all$$default = function all(array, label) { + return $$rsvp$promise$$default.all(array, label); + }; + + function $$rsvp$all$settled$$AllSettled(Constructor, entries, label) { + this._superConstructor(Constructor, entries, false /* don't abort on reject */, label); + } + + $$rsvp$all$settled$$AllSettled.prototype = $$utils$$o_create($$enumerator$$default.prototype); + $$rsvp$all$settled$$AllSettled.prototype._superConstructor = $$enumerator$$default; + $$rsvp$all$settled$$AllSettled.prototype._makeResult = $$enumerator$$makeSettledResult; + + $$rsvp$all$settled$$AllSettled.prototype._validationError = function() { + return new Error('allSettled must be called with an array'); + }; + + var $$rsvp$all$settled$$default = function allSettled(entries, label) { + return new $$rsvp$all$settled$$AllSettled($$rsvp$promise$$default, entries, label).promise; + }; + + var $$rsvp$race$$default = function race(array, label) { + return $$rsvp$promise$$default.race(array, label); + }; + + function $$promise$hash$$PromiseHash(Constructor, object, label) { + this._superConstructor(Constructor, object, true, label); + } + + var $$promise$hash$$default = $$promise$hash$$PromiseHash; + $$promise$hash$$PromiseHash.prototype = $$utils$$o_create($$enumerator$$default.prototype); + $$promise$hash$$PromiseHash.prototype._superConstructor = $$enumerator$$default; + + $$promise$hash$$PromiseHash.prototype._init = function() { + this._result = {}; + }; + + $$promise$hash$$PromiseHash.prototype._validateInput = function(input) { + return input && typeof input === 'object'; + }; + + $$promise$hash$$PromiseHash.prototype._validationError = function() { + return new Error('Promise.hash must be called with an object'); + }; + + $$promise$hash$$PromiseHash.prototype._enumerate = function() { + var promise = this.promise; + var input = this._input; + var results = []; + + for (var key in input) { + if (promise._state === $$$internal$$PENDING && input.hasOwnProperty(key)) { + results.push({ + position: key, + entry: input[key] + }); + } + } + + var length = results.length; + this._remaining = length; + var result; + + for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { + result = results[i]; + this._eachEntry(result.entry, result.position); + } + }; + + var $$rsvp$hash$$default = function hash(object, label) { + return new $$promise$hash$$default($$rsvp$promise$$default, object, label).promise; + }; + + function $$rsvp$hash$settled$$HashSettled(Constructor, object, label) { + this._superConstructor(Constructor, object, false, label); + } + + $$rsvp$hash$settled$$HashSettled.prototype = $$utils$$o_create($$promise$hash$$default.prototype); + $$rsvp$hash$settled$$HashSettled.prototype._superConstructor = $$enumerator$$default; + $$rsvp$hash$settled$$HashSettled.prototype._makeResult = $$enumerator$$makeSettledResult; + + $$rsvp$hash$settled$$HashSettled.prototype._validationError = function() { + return new Error('hashSettled must be called with an object'); + }; + + var $$rsvp$hash$settled$$default = function hashSettled(object, label) { + return new $$rsvp$hash$settled$$HashSettled($$rsvp$promise$$default, object, label).promise; + }; + + var $$rsvp$rethrow$$default = function rethrow(reason) { + setTimeout(function() { + throw reason; + }); + throw reason; + }; + + var $$rsvp$defer$$default = function defer(label) { + var deferred = { }; + + deferred.promise = new $$rsvp$promise$$default(function(resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }, label); + + return deferred; + }; + + var $$rsvp$map$$default = function map(promises, mapFn, label) { + return $$rsvp$promise$$default.all(promises, label).then(function(values) { + if (!$$utils$$isFunction(mapFn)) { + throw new TypeError("You must pass a function as map's second argument."); + } + + var length = values.length; + var results = new Array(length); + + for (var i = 0; i < length; i++) { + results[i] = mapFn(values[i]); + } + + return $$rsvp$promise$$default.all(results, label); + }); + }; + + var $$rsvp$resolve$$default = function resolve(value, label) { + return $$rsvp$promise$$default.resolve(value, label); + }; + + var $$rsvp$reject$$default = function reject(reason, label) { + return $$rsvp$promise$$default.reject(reason, label); + }; + + var $$rsvp$filter$$default = function filter(promises, filterFn, label) { + return $$rsvp$promise$$default.all(promises, label).then(function(values) { + if (!$$utils$$isFunction(filterFn)) { + throw new TypeError("You must pass a function as filter's second argument."); + } + + var length = values.length; + var filtered = new Array(length); + + for (var i = 0; i < length; i++) { + filtered[i] = filterFn(values[i]); + } + + return $$rsvp$promise$$default.all(filtered, label).then(function(filtered) { + var results = new Array(length); + var newLength = 0; + + for (var i = 0; i < length; i++) { + if (filtered[i]) { + results[newLength] = values[i]; + newLength++; + } + } + + results.length = newLength; + + return results; + }); + }); + }; + + var $$rsvp$asap$$len = 0; + + var $$rsvp$asap$$default = function asap(callback, arg) { + $$rsvp$asap$$queue[$$rsvp$asap$$len] = callback; + $$rsvp$asap$$queue[$$rsvp$asap$$len + 1] = arg; + $$rsvp$asap$$len += 2; + if ($$rsvp$asap$$len === 2) { + // If len is 1, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + $$rsvp$asap$$scheduleFlush(); + } + }; + + var $$rsvp$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; + var $$rsvp$asap$$BrowserMutationObserver = $$rsvp$asap$$browserGlobal.MutationObserver || $$rsvp$asap$$browserGlobal.WebKitMutationObserver; + + // test for web worker but not in IE10 + var $$rsvp$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function $$rsvp$asap$$useNextTick() { + return function() { + process.nextTick($$rsvp$asap$$flush); + }; + } + + function $$rsvp$asap$$useMutationObserver() { + var iterations = 0; + var observer = new $$rsvp$asap$$BrowserMutationObserver($$rsvp$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function $$rsvp$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = $$rsvp$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function $$rsvp$asap$$useSetTimeout() { + return function() { + setTimeout($$rsvp$asap$$flush, 1); + }; + } + + var $$rsvp$asap$$queue = new Array(1000); + + function $$rsvp$asap$$flush() { + for (var i = 0; i < $$rsvp$asap$$len; i+=2) { + var callback = $$rsvp$asap$$queue[i]; + var arg = $$rsvp$asap$$queue[i+1]; + + callback(arg); + + $$rsvp$asap$$queue[i] = undefined; + $$rsvp$asap$$queue[i+1] = undefined; + } + + $$rsvp$asap$$len = 0; + } + + var $$rsvp$asap$$scheduleFlush; + + // Decide what async method to use to triggering processing of queued callbacks: + if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { + $$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useNextTick(); + } else if ($$rsvp$asap$$BrowserMutationObserver) { + $$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useMutationObserver(); + } else if ($$rsvp$asap$$isWorker) { + $$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useMessageChannel(); + } else { + $$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useSetTimeout(); + } + + // default async is asap; + $$rsvp$config$$config.async = $$rsvp$asap$$default; + + var $$rsvp$$cast = $$rsvp$resolve$$default; + + function $$rsvp$$async(callback, arg) { + $$rsvp$config$$config.async(callback, arg); + } + + function $$rsvp$$on() { + $$rsvp$config$$config.on.apply($$rsvp$config$$config, arguments); + } + + function $$rsvp$$off() { + $$rsvp$config$$config.off.apply($$rsvp$config$$config, arguments); + } + + // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` + if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { + var $$rsvp$$callbacks = window['__PROMISE_INSTRUMENTATION__']; + $$rsvp$config$$configure('instrument', true); + for (var $$rsvp$$eventName in $$rsvp$$callbacks) { + if ($$rsvp$$callbacks.hasOwnProperty($$rsvp$$eventName)) { + $$rsvp$$on($$rsvp$$eventName, $$rsvp$$callbacks[$$rsvp$$eventName]); + } + } + } + + var rsvp$umd$$RSVP = { + 'race': $$rsvp$race$$default, + 'Promise': $$rsvp$promise$$default, + 'allSettled': $$rsvp$all$settled$$default, + 'hash': $$rsvp$hash$$default, + 'hashSettled': $$rsvp$hash$settled$$default, + 'denodeify': $$rsvp$node$$default, + 'on': $$rsvp$$on, + 'off': $$rsvp$$off, + 'map': $$rsvp$map$$default, + 'filter': $$rsvp$filter$$default, + 'resolve': $$rsvp$resolve$$default, + 'reject': $$rsvp$reject$$default, + 'all': $$rsvp$all$$default, + 'rethrow': $$rsvp$rethrow$$default, + 'defer': $$rsvp$defer$$default, + 'EventTarget': $$rsvp$events$$default, + 'configure': $$rsvp$config$$configure, + 'async': $$rsvp$$async + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define.amd) { + define(function() { return rsvp$umd$$RSVP; }); + } else if (typeof module !== 'undefined' && module.exports) { + module.exports = rsvp$umd$$RSVP; + } else if (typeof this !== 'undefined') { + this['RSVP'] = rsvp$umd$$RSVP; + } +}).call(this); +if (typeof EPUBJS === 'undefined') { + (typeof window !== 'undefined' ? window : this).EPUBJS = {}; +} + +EPUBJS.VERSION = "0.3.0"; + +(function(root) { + "use strict"; + var ePub = function(_url) { + return new EPUBJS.Book(_url); + }; + + // CommonJS + if (typeof exports === "object") { + root.RSVP = require("rsvp"); + module.exports = ePub; + // RequireJS + } else if (typeof define === "function" && define.amd) { + define(ePub); + // Global + } else { + root.ePub = ePub; + } + +})(this); + + EPUBJS.core = {}; EPUBJS.core.request = function(url, type, withCredentials, headers) { diff --git a/dist/epub.min.js b/dist/epub.min.js index 5b0c415..6e0e237 100644 --- a/dist/epub.min.js +++ b/dist/epub.min.js @@ -1,3 +1,3 @@ -"undefined"==typeof EPUBJS&&(("undefined"!=typeof window?window:this).EPUBJS={}),EPUBJS.VERSION="0.3.0",EPUBJS.Render={},function(t){"use strict";var e=function(t){return new EPUBJS.Book(t)};e.Render={register:function(t,i){e.Render[t]=i}},"object"==typeof exports?(t.RSVP=require("rsvp"),module.exports=e):"function"==typeof define&&define.amd?define(e):t.ePub=e}(this),function(t){var e,i;!function(){var t={},n={};e=function(e,i,n){t[e]={deps:i,callback:n}},i=function(e){function r(t){if("."!==t.charAt(0))return t;for(var i=t.split("/"),n=e.split("/").slice(0,-1),r=0,o=i.length;o>r;r++){var s=i[r];if(".."===s)n.pop();else{if("."===s)continue;n.push(s)}}return n.join("/")}if(n[e])return n[e];if(n[e]={},!t[e])throw new Error("Could not find module "+e);for(var o,s=t[e],a=s.deps,h=s.callback,u=[],c=0,l=a.length;l>c;c++)u.push("exports"===a[c]?o={}:i(r(a[c])));var p=h.apply(this,u);return n[e]=o||p},i.entries=t}(),e("rsvp/-internal",["./utils","./instrument","./config","exports"],function(t,e,i,n){"use strict";function r(){}function o(t){try{return t.then}catch(e){return x.error=e,x}}function s(t,e,i,n){try{t.call(e,i,n)}catch(r){return r}}function a(t,e,i){w.async(function(t){var n=!1,r=s(i,e,function(i){n||(n=!0,e!==i?c(t,i):p(t,i))},function(e){n||(n=!0,d(t,e))},"Settle: "+(t._label||" unknown promise"));!n&&r&&(n=!0,d(t,r))},t)}function h(t,e){t._onerror=null,e._state===U?p(t,e._result):t._state===J?d(t,e._result):f(e,void 0,function(i){e!==i?c(t,i):p(t,i)},function(e){d(t,e)})}function u(t,e){if(e instanceof t.constructor)h(t,e);else{var i=o(e);i===x?d(t,x.error):void 0===i?p(t,e):P(i)?a(t,e,i):p(t,e)}}function c(t,e){t===e?p(t,e):E(e)?u(t,e):p(t,e)}function l(t){t._onerror&&t._onerror(t._result),g(t)}function p(t,e){t._state===b&&(t._result=e,t._state=U,0===t._subscribers.length?w.instrument&&B("fulfilled",t):w.async(g,t))}function d(t,e){t._state===b&&(t._state=J,t._result=e,w.async(l,t))}function f(t,e,i,n){var r=t._subscribers,o=r.length;t._onerror=null,r[o]=e,r[o+U]=i,r[o+J]=n,0===o&&t._state&&w.async(g,t)}function g(t){var e=t._subscribers,i=t._state;if(w.instrument&&B(i===U?"fulfilled":"rejected",t),0!==e.length){for(var n,r,o=t._result,s=0;st;t+=2){var e=l[t],i=l[t+1];e(i),l[t]=void 0,l[t+1]=void 0}s=0}var s=0;t["default"]=function(t,e){l[s]=t,l[s+1]=e,s+=2,2===s&&a()};var a,h="undefined"!=typeof window?window:{},u=h.MutationObserver||h.WebKitMutationObserver,c="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,l=new Array(1e3);a="undefined"!=typeof process&&"[object process]"==={}.toString.call(process)?e():u?i():c?n():r()}),e("rsvp/config",["./events","exports"],function(t,e){"use strict";function i(t,e){return"onerror"===t?void r.on("error",e):2!==arguments.length?r[t]:void(r[t]=e)}var n=t["default"],r={instrument:!1};n.mixin(r),e.config=r,e.configure=i}),e("rsvp/defer",["./promise","exports"],function(t,e){"use strict";var i=t["default"];e["default"]=function(t){var e={};return e.promise=new i(function(t,i){e.resolve=t,e.reject=i},t),e}}),e("rsvp/enumerator",["./utils","./-internal","exports"],function(t,e,i){"use strict";function n(t,e,i){return t===l?{state:"fulfilled",value:i}:{state:"rejected",reason:i}}function r(t,e,i,n){this._instanceConstructor=t,this.promise=new t(a,n),this._abortOnReject=i,this._validateInput(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._init(),0===this.length?u(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&u(this.promise,this._result))):h(this.promise,this._validationError())}var o=t.isArray,s=t.isMaybeThenable,a=e.noop,h=e.reject,u=e.fulfill,c=e.subscribe,l=e.FULFILLED,p=e.REJECTED,d=e.PENDING,f=!0;i.ABORT_ON_REJECTION=f,i.makeSettledResult=n,r.prototype._validateInput=function(t){return o(t)},r.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},r.prototype._init=function(){this._result=new Array(this.length)},i["default"]=r,r.prototype._enumerate=function(){for(var t=this.length,e=this.promise,i=this._input,n=0;e._state===d&&t>n;n++)this._eachEntry(i[n],n)},r.prototype._eachEntry=function(t,e){var i=this._instanceConstructor;s(t)?t.constructor===i&&t._state!==d?(t._onerror=null,this._settledAt(t._state,e,t._result)):this._willSettleAt(i.resolve(t),e):(this._remaining--,this._result[e]=this._makeResult(l,e,t))},r.prototype._settledAt=function(t,e,i){var n=this.promise;n._state===d&&(this._remaining--,this._abortOnReject&&t===p?h(n,i):this._result[e]=this._makeResult(t,e,i)),0===this._remaining&&u(n,this._result)},r.prototype._makeResult=function(t,e,i){return i},r.prototype._willSettleAt=function(t,e){var i=this;c(t,void 0,function(t){i._settledAt(l,e,t)},function(t){i._settledAt(p,e,t)})}}),e("rsvp/events",["exports"],function(t){"use strict";function e(t,e){for(var i=0,n=t.length;n>i;i++)if(t[i]===e)return i;return-1}function i(t){var e=t._promiseCallbacks;return e||(e=t._promiseCallbacks={}),e}t["default"]={mixin:function(t){return t.on=this.on,t.off=this.off,t.trigger=this.trigger,t._promiseCallbacks=void 0,t},on:function(t,n){var r,o=i(this);r=o[t],r||(r=o[t]=[]),-1===e(r,n)&&r.push(n)},off:function(t,n){var r,o,s=i(this);return n?(r=s[t],o=e(r,n),void(-1!==o&&r.splice(o,1))):void(s[t]=[])},trigger:function(t,e){var n,r,o=i(this);if(n=o[t])for(var s=0;sa;a++)s[a]=e(t[a]);return n.all(s,i).then(function(e){for(var i=new Array(o),n=0,r=0;o>r;r++)e[r]&&(i[n]=t[r],n++);return i.length=n,i})})}}),e("rsvp/hash-settled",["./promise","./enumerator","./promise-hash","./utils","exports"],function(t,e,i,n,r){"use strict";function o(t,e,i){this._superConstructor(t,e,!1,i)}var s=t["default"],a=e.makeSettledResult,h=i["default"],u=e["default"],c=n.o_create;o.prototype=c(h.prototype),o.prototype._superConstructor=u,o.prototype._makeResult=a,o.prototype._validationError=function(){return new Error("hashSettled must be called with an object")},r["default"]=function(t,e){return new o(s,t,e).promise}}),e("rsvp/hash",["./promise","./promise-hash","./enumerator","exports"],function(t,e,i,n){"use strict";{var r=t["default"],o=e["default"];i.ABORT_ON_REJECTION}n["default"]=function(t,e){return new o(r,t,e).promise}}),e("rsvp/instrument",["./config","./utils","exports"],function(t,e,i){"use strict";var n=t.config,r=e.now,o=[];i["default"]=function(t,e,i){1===o.push({name:t,payload:{guid:e._guidKey+e._id,eventName:t,detail:e._result,childGuid:i&&e._guidKey+i._id,label:e._label,timeStamp:r(),stack:new Error(e._label).stack}})&&setTimeout(function(){for(var t,e=0;ea;a++)s[a]=e(t[a]);return n.all(s,i)})}}),e("rsvp/node",["./promise","./utils","exports"],function(t,e,i){"use strict";var n=t["default"],r=e.isArray;i["default"]=function(t,e){function i(){for(var i=arguments.length,r=new Array(i),a=0;i>a;a++)r[a]=arguments[a];var h;return o||s||!e?h=this:("object"==typeof console&&console.warn('Deprecation: RSVP.denodeify() doesn\'t allow setting the "this" binding anymore. Use yourFunction.bind(yourThis) instead.'),h=e),n.all(r).then(function(i){function r(n,r){function a(){for(var t=arguments.length,i=new Array(t),a=0;t>a;a++)i[a]=arguments[a];var h=i[0],u=i[1];if(h)r(h);else if(o)n(i.slice(1));else if(s){var c,l,p={},d=i.slice(1);for(l=0;la;a++)o=i[a],this._eachEntry(o.entry,o.position)}}),e("rsvp/promise",["./config","./events","./instrument","./utils","./-internal","./promise/cast","./promise/all","./promise/race","./promise/resolve","./promise/reject","exports"],function(t,e,i,n,r,o,s,a,h,u,c){"use strict";function l(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function p(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function d(t,e){this._id=R++,this._label=e,this._subscribers=[],f.instrument&&g("created",this),v!==t&&(y(t)||l(),this instanceof d||p(),E(this,t))}var f=t.config,g=(e["default"],i["default"]),y=(n.objectOrFunction,n.isFunction),m=n.now,v=r.noop,S=(r.resolve,r.reject,r.fulfill,r.subscribe),E=r.initializePromise,P=r.invokeCallback,B=r.FULFILLED,w=o["default"],b=s["default"],U=a["default"],J=h["default"],x=u["default"],C="rsvp_"+m()+"-",R=0;c["default"]=d,d.cast=w,d.all=b,d.race=U,d.resolve=J,d.reject=x,d.prototype={constructor:d,_id:void 0,_guidKey:C,_label:void 0,_state:void 0,_result:void 0,_subscribers:void 0,_onerror:function(t){f.trigger("error",t)},then:function(t,e,i){var n=this;n._onerror=null;var r=new this.constructor(v,i),o=n._state,s=n._result;return f.instrument&&g("chained",n,r),o===B&&t?f.async(function(){P(o,r,t,s)}):S(n,r,t,e),r},"catch":function(t,e){return this.then(null,t,e)},"finally":function(t,e){var i=this.constructor;return this.then(function(e){return i.resolve(t()).then(function(){return e})},function(e){return i.resolve(t()).then(function(){throw e})},e)}}}),e("rsvp/promise/all",["../enumerator","exports"],function(t,e){"use strict";var i=t["default"];e["default"]=function(t,e){return new i(this,t,!0,e).promise}}),e("rsvp/promise/cast",["./resolve","exports"],function(t,e){"use strict";var i=t["default"];e["default"]=i}),e("rsvp/promise/race",["../utils","../-internal","exports"],function(t,e,i){"use strict";var n=t.isArray,r=(t.isFunction,t.isMaybeThenable,e.noop),o=e.resolve,s=e.reject,a=e.subscribe,h=e.PENDING;i["default"]=function(t,e){function i(t){o(l,t)}function u(t){s(l,t)}var c=this,l=new c(r,e);if(!n(t))return s(l,new TypeError("You must pass an array to race.")),l;for(var p=t.length,d=0;l._state===h&&p>d;d++)a(c.resolve(t[d]),void 0,i,u);return l}}),e("rsvp/promise/reject",["../-internal","exports"],function(t,e){"use strict";var i=t.noop,n=t.reject;e["default"]=function(t,e){var r=this,o=new r(i,e);return n(o,t),o}}),e("rsvp/promise/resolve",["../-internal","exports"],function(t,e){"use strict";var i=t.noop,n=t.resolve;e["default"]=function(t,e){var r=this;if(t&&"object"==typeof t&&t.constructor===r)return t;var o=new r(i,e);return n(o,t),o}}),e("rsvp/race",["./promise","exports"],function(t,e){"use strict";var i=t["default"];e["default"]=function(t,e){return i.race(t,e)}}),e("rsvp/reject",["./promise","exports"],function(t,e){"use strict";var i=t["default"];e["default"]=function(t,e){return i.reject(t,e)}}),e("rsvp/resolve",["./promise","exports"],function(t,e){"use strict";var i=t["default"];e["default"]=function(t,e){return i.resolve(t,e)}}),e("rsvp/rethrow",["exports"],function(t){"use strict";t["default"]=function(t){throw setTimeout(function(){throw t}),t}}),e("rsvp/utils",["exports"],function(t){"use strict";function e(t){return"function"==typeof t||"object"==typeof t&&null!==t}function i(t){return"function"==typeof t}function n(t){return"object"==typeof t&&null!==t}t.objectOrFunction=e,t.isFunction=i,t.isMaybeThenable=n;var r;r=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var o=r;t.isArray=o;var s=Date.now||function(){return(new Date).getTime()};t.now=s;var a=Object.create||function(t){var e=function(){};return e.prototype=t,e};t.o_create=a}),e("rsvp",["./rsvp/promise","./rsvp/events","./rsvp/node","./rsvp/all","./rsvp/all-settled","./rsvp/race","./rsvp/hash","./rsvp/hash-settled","./rsvp/rethrow","./rsvp/defer","./rsvp/config","./rsvp/map","./rsvp/resolve","./rsvp/reject","./rsvp/filter","./rsvp/asap","exports"],function(t,e,i,n,r,o,s,a,h,u,c,l,p,d,f,g,y){"use strict";function m(t,e){_.async(t,e)}function v(){_.on.apply(_,arguments)}function S(){_.off.apply(_,arguments)}var E=t["default"],P=e["default"],B=i["default"],w=n["default"],b=r["default"],U=o["default"],J=s["default"],x=a["default"],C=h["default"],R=u["default"],_=c.config,T=c.configure,k=l["default"],N=p["default"],L=d["default"],F=f["default"],q=g["default"];if(_.async=q,"undefined"!=typeof window&&"object"==typeof window.__PROMISE_INSTRUMENTATION__){var O=window.__PROMISE_INSTRUMENTATION__;T("instrument",!0);for(var I in O)O.hasOwnProperty(I)&&v(I,O[I])}y.Promise=E,y.EventTarget=P,y.all=w,y.allSettled=b,y.race=U,y.hash=J,y.hashSettled=x,y.rethrow=C,y.defer=R,y.denodeify=B,y.configure=T,y.on=v,y.off=S,y.resolve=N,y.reject=L,y.async=m,y.map=k,y.filter=F}),t.RSVP=i("rsvp")}(self),EPUBJS.core={},EPUBJS.core.request=function(t,e,i,n){function r(){if(this.readyState===this.DONE)if(200===this.status||this.responseXML){var t;t="xml"==e?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"text/xml"):"json"==e?JSON.parse(this.response):"blob"==e?s?this.response:new Blob([this.response]):this.response,h.resolve(t)}else h.reject({status:this.status,message:this.response,stack:(new Error).stack})}var o,s=window.URL,a=s?"blob":"arraybuffer",h=new RSVP.defer,u=new XMLHttpRequest,c=XMLHttpRequest.prototype;"overrideMimeType"in c||Object.defineProperty(c,"overrideMimeType",{value:function(){}}),i&&(u.withCredentials=!0),u.open("GET",t,!0);for(o in n)u.setRequestHeader(o,n[o]);return u.onreadystatechange=r,"blob"==e&&(u.responseType=a),"json"==e&&u.setRequestHeader("Accept","application/json"),"xml"==e&&u.overrideMimeType("text/xml"),u.send(),h.promise},EPUBJS.core.uri=function(t){var e,i,n,r={protocol:"",host:"",path:"",origin:"",directory:"",base:"",filename:"",extension:"",fragment:"",href:t},o=t.indexOf("://"),s=t.indexOf("?"),a=t.indexOf("#");return-1!=a&&(r.fragment=t.slice(a+1),t=t.slice(0,a)),-1!=s&&(r.search=t.slice(s+1),t=t.slice(0,s),href=t),-1!=o?(r.protocol=t.slice(0,o),e=t.slice(o+3),n=e.indexOf("/"),-1===n?(r.host=r.path,r.path=""):(r.host=e.slice(0,n),r.path=e.slice(n)),r.origin=r.protocol+"://"+r.host,r.directory=EPUBJS.core.folder(r.path),r.base=r.origin+r.directory):(r.path=t,r.directory=EPUBJS.core.folder(t),r.base=r.directory),r.filename=t.replace(r.base,""),i=r.filename.lastIndexOf("."),-1!=i&&(r.extension=r.filename.slice(i+1)),r},EPUBJS.core.folder=function(t){var e=t.lastIndexOf("/");if(-1==e)var i="";return i=t.slice(0,e+1)},EPUBJS.core.queue=function(t){var e=[],i=t,n=function(t,i,n){return e.push({funcName:t,args:i,context:n}),e},r=function(){var t;e.length&&(t=e.shift(),i[t.funcName].apply(t.context||i,t.args))},o=function(){for(;e.length;)r()},s=function(){e=[]},a=function(){return e.length};return{enqueue:n,dequeue:r,flush:o,clear:s,length:a}},EPUBJS.core.isElement=function(t){return!(!t||1!=t.nodeType)},EPUBJS.core.uuid=function(){var t=(new Date).getTime(),e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:7&i|8).toString(16)});return e},EPUBJS.core.values=function(t){for(var e=-1,i=Object.keys(t),n=i.length,r=Array(n);++er;r++)if("undefined"!=typeof document.body.style[e[r]+i])return e[r]+i;return t},EPUBJS.core.defaults=function(t){for(var e=1,i=arguments.length;i>e;e++){var n=arguments[e];for(var r in n)void 0===t[r]&&(t[r]=n[r])}return t},EPUBJS.core.extend=function(t){var e=[].slice.call(arguments,1);return e.forEach(function(e){e&&Object.getOwnPropertyNames(e).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(e,i))})}),t},EPUBJS.core.insert=function(t,e,i){var n=EPUBJS.core.locationOf(t,e,i);return e.splice(n,0,t),n},EPUBJS.core.locationOf=function(t,e,i,n,r){var o,s=n||0,a=r||e.length,h=parseInt(s+(a-s)/2);return i||(i=function(t,e){return t>e?1:e>t?-1:(t=e)?0:void 0}),0>=a-s?h:(o=i(e[h],t),a-s===1?o>0?h:h+1:0===o?h:-1===o?EPUBJS.core.locationOf(t,e,i,h,a):EPUBJS.core.locationOf(t,e,i,s,h))},EPUBJS.core.indexOfSorted=function(t,e,i,n,r){var o,s=n||0,a=r||e.length,h=parseInt(s+(a-s)/2);return i||(i=function(t,e){return t>e?1:e>t?-1:(t=e)?0:void 0}),0>=a-s?-1:(o=i(e[h],t),a-s===1?0===o?h:-1:0===o?h:-1===o?EPUBJS.core.indexOfSorted(t,e,i,h,a):EPUBJS.core.indexOfSorted(t,e,i,s,h))},EPUBJS.core.requestAnimationFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,EPUBJS.core.bounds=function(t){var e=window.getComputedStyle(t),i=["width","paddingRight","paddingLeft","marginRight","marginLeft","borderRightWidth","borderLeftWidth"],n=["height","paddingTop","paddingBottom","marginTop","marginBottom","borderTopWidth","borderBottomWidth"],r=0,o=0;return i.forEach(function(t){r+=parseFloat(e[t])||0}),n.forEach(function(t){o+=parseFloat(e[t])||0}),{height:o,width:r}},EPUBJS.core.borders=function(t){var e=window.getComputedStyle(t),i=["paddingRight","paddingLeft","marginRight","marginLeft","borderRightWidth","borderLeftWidth"],n=["paddingTop","paddingBottom","marginTop","marginBottom","borderTopWidth","borderBottomWidth"],r=0,o=0;return i.forEach(function(t){r+=parseFloat(e[t])||0}),n.forEach(function(t){o+=parseFloat(e[t])||0}),{height:o,width:r}},EPUBJS.core.windowBounds=function(){var t=window.innerWidth,e=window.innerHeight;return{top:0,left:0,right:t,bottom:e,width:t,height:e}},EPUBJS.core.cleanStringForXpath=function(t){var e=t.match(/[^'"]+|['"]/g);return e=e.map(function(t){return"'"===t?'"\'"':'"'===t?"'\"'":"'"+t+"'"}),"concat('',"+e.join(",")+")"},EPUBJS.core.indexOfTextNode=function(t){for(var e,i=t.parentNode,n=i.childNodes,r=-1,o=0;o=0;s--){var a=r.snapshotItem(s),h=a.getAttribute("id")||!1,u=a.querySelector("content"),c=u.getAttribute("src"),l=a.querySelector("navLabel"),p=l.textContent?l.textContent:"",d=c.split("#"),f=(d[0],e(a));n.unshift({id:h,href:c,label:p,subitems:f,parent:i?i.getAttribute("id"):null})}return n}var i=t.querySelector("navMap");return i?e(i):[]},EPUBJS.EpubCFI=function(t){return t?this.parse(t):void 0},EPUBJS.EpubCFI.prototype.generateChapterComponent=function(t,e,i){var n=parseInt(e),r=t+1,o="/"+r+"/";return o+=2*(n+1),i&&(o+="["+i+"]"),o},EPUBJS.EpubCFI.prototype.generatePathComponent=function(t){var e=[];return t.forEach(function(t){var i="";i+=2*(t.index+1),t.id&&(i+="["+t.id+"]"),e.push(i)}),e.join("/")},EPUBJS.EpubCFI.prototype.generateCfiFromElement=function(t,e){var i=this.pathTo(t),n=this.generatePathComponent(i);return n.length?"epubcfi("+e+"!"+n+"/1:0)":"epubcfi("+e+"!/4/)"},EPUBJS.EpubCFI.prototype.pathTo=function(t){for(var e,i=[];t&&null!==t.parentNode&&9!=t.parentNode.nodeType;)e=t.parentNode.children,i.unshift({id:t.id,tagName:t.tagName,index:e?Array.prototype.indexOf.call(e,t):0}),t=t.parentNode;return i},EPUBJS.EpubCFI.prototype.getChapterComponent=function(t){var e=t.split("!");return e[0]},EPUBJS.EpubCFI.prototype.getPathComponent=function(t){var e=t.split("!"),i=e[1]?e[1].split(":"):"";return i[0]},EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent=function(t){var e=t.split(":");return e[1]||""},EPUBJS.EpubCFI.prototype.parse=function(t){var e,i,n,r,o,s,a,h,u,c={},l=function(t){var e,i,n,r;return e="element",i=parseInt(t)/2-1,n=t.match(/\[(.*)\]/),n&&n[1]&&(r=n[1]),{type:e,index:i,id:r||!1}};return"string"!=typeof t?{spinePos:-1}:(c.str=t,0===t.indexOf("epubcfi(")&&")"===t[t.length-1]&&(t=t.slice(8,t.length-1)),i=this.getChapterComponent(t),n=this.getPathComponent(t)||"",r=this.getCharecterOffsetComponent(t),i&&(e=i.split("/")[2]||"")?(c.spinePos=parseInt(e)/2-1||0,s=e.match(/\[(.*)\]/),c.spineId=s?s[1]:!1,-1!=n.indexOf(",")&&console.warn("CFI Ranges are not supported"),a=n.split("/"),h=a.pop(),c.steps=[],a.forEach(function(t){var e;t&&(e=l(t),c.steps.push(e))}),u=parseInt(h),isNaN(u)||c.steps.push(u%2===0?l(h):{type:"text",index:(u-1)/2}),o=r.match(/\[(.*)\]/),o&&o[1]?(c.characterOffset=parseInt(r.split("[")[0]),c.textLocationAssertion=o[1]):c.characterOffset=parseInt(r),c):{spinePos:-1})},EPUBJS.EpubCFI.prototype.addMarker=function(t,e,i){var n,r,o,s,a=e||document,h=i||this.createMarker(a);return"string"==typeof t&&(t=this.parse(t)),r=t.steps[t.steps.length-1],-1===t.spinePos?!1:(n=this.findParent(t,a))?(r&&"text"===r.type?(o=n.childNodes[r.index],t.characterOffset?(s=o.splitText(t.characterOffset),h.classList.add("EPUBJS-CFI-SPLIT"),n.insertBefore(h,s)):n.insertBefore(h,o)):n.insertBefore(h,n.firstChild),h):!1},EPUBJS.EpubCFI.prototype.createMarker=function(t){var e=t||document,i=e.createElement("span");return i.id="EPUBJS-CFI-MARKER:"+EPUBJS.core.uuid(),i.classList.add("EPUBJS-CFI-MARKER"),i},EPUBJS.EpubCFI.prototype.removeMarker=function(t,e){t.classList.contains("EPUBJS-CFI-SPLIT")?(nextSib=t.nextSibling,prevSib=t.previousSibling,nextSib&&prevSib&&3===nextSib.nodeType&&3===prevSib.nodeType&&(prevSib.textContent+=nextSib.textContent,t.parentNode.removeChild(nextSib)),t.parentNode.removeChild(t)):t.classList.contains("EPUBJS-CFI-MARKER")&&t.parentNode.removeChild(t)},EPUBJS.EpubCFI.prototype.findParent=function(t,e){var i,n,r,o=e||document,s=o.getElementsByTagName("html")[0],a=Array.prototype.slice.call(s.children);if("string"==typeof t&&(t=this.parse(t)),n=t.steps.slice(0),!n.length)return o.getElementsByTagName("body")[0];for(;n&&n.length>0;){if(i=n.shift(),"text"===i.type?(r=s.childNodes[i.index],s=r.parentNode||s):s=i.id?o.getElementById(i.id):a[i.index],"undefined"==typeof s)return console.error("No Element For",i,t.str),!1;a=Array.prototype.slice.call(s.children)}return s},EPUBJS.EpubCFI.prototype.compare=function(t,e){if("string"==typeof t&&(t=new EPUBJS.EpubCFI(t)),"string"==typeof e&&(e=new EPUBJS.EpubCFI(e)),t.spinePos>e.spinePos)return 1;if(t.spinePose.steps[i].index)return 1;if(t.steps[i].indexe.characterOffset?1:t.characterOffset=0?(o=r.length,t.characterOffset-1?(delete this.spineByHref[t.href],delete this.spineById[t.idref],this.spineItems.splice(e,1)):void 0},EPUBJS.replace={},EPUBJS.replace.links=function(t,e){for(var i=t.document.querySelectorAll("a[href]"),n=function(t){var i=t.getAttribute("href"),n=new EPUBJS.core.uri(i);n.protocol?t.setAttribute("target","_blank"):0===i.indexOf("#")||(t.onclick=function(){return e.display(i),!1})},r=0;r-1&&(this.observer=this.observe(this.document.body)),this.imageLoadListeners(),this.mediaQueryListeners(),this.resizeListenters()},EPUBJS.View.prototype.resizeListenters=function(){clearTimeout(this.expanding),this.expanding=setTimeout(this.expand.bind(this),350)},EPUBJS.View.prototype.mediaQueryListeners=function(){for(var t=this.document.styleSheets,e=function(t){t.matches&&!this._expanding&&this.expand()}.bind(this),i=0;i-1&&(id=t.substring(t.indexOf("#")),el=this.document.getElementById(id)))return el.getBoundingClientRect();return{left:0,top:0}}},EPUBJS.View.prototype.addCss=function(t){var e=document.createElement("link"),i=!1;return new RSVP.Promise(function(n){return this.document?(e.type="text/css",e.rel="stylesheet",e.href=t,e.onload=e.onreadystatechange=function(){i||this.readyState&&"complete"!=this.readyState||(i=!0,setTimeout(function(){n(!0)},1))},void this.document.head.appendChild(e)):void n(!1)}.bind(this))},EPUBJS.View.prototype.addStylesheetRules=function(t){var e,i=document.createElement("style");if(this.document){this.document.head.appendChild(i),e=i.sheet;for(var n=0,r=t.length;r>n;n++){var o=1,s=t[n],a=t[n][0],h="";"[object Array]"===Object.prototype.toString.call(s[1][0])&&(s=s[1],o=0);for(var u=s.length;u>o;o++){var c=s[o];h+=c[0]+":"+c[1]+(c[2]?" !important":"")+";\n"}e.insertRule(a+"{"+h+"}",e.cssRules.length)}}},RSVP.EventTarget.mixin(EPUBJS.View.prototype),EPUBJS.Layout=EPUBJS.Layout||{},EPUBJS.Layout.Reflowable=function(){},EPUBJS.Layout.Reflowable.prototype.calculate=function(t,e,i,n){var r,o,s,a=n||1,h=Math.floor(t),u=h%2===0?h:h-1,c=Math.floor(u/8),l=i>=0?i:c%2===0?c:c-1;r=a>1?Math.floor((u-l)/a):u,o=r*a,s=(r+l)*a,this.columnAxis=EPUBJS.core.prefixed("columnAxis"),this.columnGap=EPUBJS.core.prefixed("columnGap"),this.columnWidth=EPUBJS.core.prefixed("columnWidth"),this.columnFill=EPUBJS.core.prefixed("columnFill"),this.width=u,this.height=e,this.spread=o,this.delta=s,this.column=r,this.gap=l,this.divisor=a},EPUBJS.Layout.Reflowable.prototype.format=function(t){var e=t.document.documentElement,i=t.document.body;e.style.overflow="hidden",e.style.width=this.width+"px",i.style.height=this.height+"px",i.style[this.columnAxis]="horizontal",i.style[this.columnFill]="auto",i.style[this.columnGap]=this.gap+"px",i.style[this.columnWidth]=this.column+"px",t.iframe.style.marginRight=this.gap+"px"},EPUBJS.Layout.Reflowable.prototype.count=function(t){var e=t.root().scrollWidth,i=Math.ceil(e/this.spread);return{spreads:i,pages:i*this.divisor}},EPUBJS.Layout.Fixed=function(){},EPUBJS.Layout.Fixed.prototype.calculate=function(){},EPUBJS.Layout.Fixed.prototype.format=function(t){var e,i,n=t.document.documentElement,r=documentElement.querySelector("[name=viewport");r&&r.hasAttribute("content")&&(content=r.getAttribute("content"),contents=content.split(","),contents[0]&&(e=contents[0].replace("width=","")),contents[1]&&(i=contents[1].replace("height=",""))),t.resize(e,i),n.style.overflow="auto"},EPUBJS.Layout.Fixed.prototype.count=function(){return{spreads:1,pages:1}},EPUBJS.Layout.Scroll=function(){},EPUBJS.Layout.Scroll.prototype.calculate=function(t){this.spread=t,this.column=t,this.gap=0},EPUBJS.Layout.Scroll.prototype.format=function(t){var e=t.document.documentElement;e.style.width="auto",e.style.height="auto"},EPUBJS.Layout.Scroll.prototype.count=function(){return{spreads:1,pages:1}},EPUBJS.Rendition=function(t,e){this.settings=EPUBJS.core.extend(this.settings||{},{infinite:!0,hidden:!1,width:!1,height:null,layoutOveride:null,axis:"vertical"}),EPUBJS.core.extend(this.settings,e),this.viewSettings={},this.book=t,this.views=[],this.hooks={},this.hooks.display=new EPUBJS.Hook(this),this.hooks.content=new EPUBJS.Hook(this),this.hooks.layout=new EPUBJS.Hook(this),this.hooks.render=new EPUBJS.Hook(this),this.hooks.show=new EPUBJS.Hook(this),this.hooks.content.register(EPUBJS.replace.links.bind(this)),this.epubcfi=new EPUBJS.EpubCFI,this.q=new EPUBJS.Queue(this),this.q.enqueue(this.book.opened),this.q.enqueue(this.parseLayoutProperties)},EPUBJS.Rendition.prototype.initialize=function(t){{var e,i=t||{},n=i.height,r=i.width;i.hidden||!1}return i.height&&EPUBJS.core.isNumber(i.height)&&(n=i.height+"px"),i.width&&EPUBJS.core.isNumber(i.width)&&(r=i.width+"px"),e=document.createElement("div"),e.id="epubjs-container:"+EPUBJS.core.uuid(),e.classList.add("epub-container"),e.style.fontSize="0",e.style.wordSpacing="0",e.style.lineHeight="0",e.style.verticalAlign="top","horizontal"===this.settings.axis&&(e.style.whiteSpace="nowrap"),r&&(e.style.width=r),n&&(e.style.height=n),e.style.overflow=this.settings.overflow,e},EPUBJS.Rendition.wrap=function(t){var e=document.createElement("div");return e.style.visibility="hidden",e.style.overflow="hidden",e.style.width="0",e.style.height="0",e.appendChild(t),e},EPUBJS.Rendition.prototype.attachTo=function(t){return this.container=this.initialize({width:this.settings.width,height:this.settings.height}),EPUBJS.core.isElement(t)?this.element=t:"string"==typeof t&&(this.element=document.getElementById(t)),this.element?(this.settings.hidden?(this.wrapper=this.wrap(this.container),this.element.appendChild(this.wrapper)):this.element.appendChild(this.container),this.attachListeners(),this.stageSize(),this.applyLayoutMethod(),void this.trigger("attached")):void console.error("Not an Element")},EPUBJS.Rendition.prototype.attachListeners=function(){EPUBJS.core.isNumber(this.settings.width)&&EPUBJS.core.isNumber(this.settings.height)||window.addEventListener("resize",this.onResized.bind(this),!1)},EPUBJS.Rendition.prototype.bounds=function(){return this.container.getBoundingClientRect()},EPUBJS.Rendition.prototype.display=function(t){return this.q.enqueue(this._display,t)},EPUBJS.Rendition.prototype._display=function(t){var e,i,n,r,o=new RSVP.defer,s=o.promise;return this.epubcfi.isCfiString(t)?(n=this.epubcfi.parse(t),r=n.spinePos,e=this.book.spine.get(r)):e=this.book.spine.get(t),this.displaying=!0,this.hide(),e?(i=this.createView(e),this.q.enqueue(this.append,i),this.show(),this.hooks.display.trigger(i).then(function(){this.trigger("displayed",e),o.resolve(this)}.bind(this))):o.reject(new Error("No Section Found")),s},EPUBJS.Rendition.prototype.moveTo=function(){},EPUBJS.Rendition.prototype.render=function(t,e){return t.create(),t.onLayout=this.layout.format.bind(this.layout),this.resizeView(t),t.render(this.book.request).then(function(){return this.hooks.content.trigger(t,this)}.bind(this)).then(function(){return this.hooks.layout.trigger(t,this)}.bind(this)).then(function(){return t.display()}.bind(this)).then(function(){return this.hooks.render.trigger(t,this)}.bind(this)).then(function(){0!=e&&this.hidden===!1&&this.q.enqueue(function(t){t.show()},t),this.trigger("rendered",t.section)}.bind(this)).catch(function(t){this.trigger("loaderror",t)}.bind(this))},EPUBJS.Rendition.prototype.afterDisplayed=function(t){this.trigger("added",t.section)},EPUBJS.Rendition.prototype.append=function(t){return this.clear(),this.views.push(t),this.container.appendChild(t.element),t.onDisplayed=this.afterDisplayed.bind(this),this.render(t)},EPUBJS.Rendition.prototype.clear=function(){this.views.forEach(function(t){this._remove(t)}.bind(this)),this.views=[]},EPUBJS.Rendition.prototype.remove=function(t){var e=this.views.indexOf(t);e>-1&&this.views.splice(e,1),this._remove(t)},EPUBJS.Rendition.prototype._remove=function(t){t.off("resized"),t.displayed&&t.destroy(),this.container.removeChild(t.element),t=null},EPUBJS.Rendition.prototype.resizeView=function(t){"pre-paginated"===this.globalLayoutProperties.layout?t.lock("both",this.stage.width,this.stage.height):t.lock("width",this.stage.width,this.stage.height)},EPUBJS.Rendition.prototype.stageSize=function(t,e){var i,n=t||this.settings.width,r=e||this.settings.height;return n===!1&&(i=this.element.getBoundingClientRect(),i.width&&(n=i.width,this.container.style.width=i.width+"px")),r===!1&&(i=i||this.element.getBoundingClientRect(),i.height&&(r=i.height,this.container.style.height=i.height+"px")),n&&!EPUBJS.core.isNumber(n)&&(i=this.container.getBoundingClientRect(),n=i.width),r&&!EPUBJS.core.isNumber(r)&&(i=i||this.container.getBoundingClientRect(),r=i.height),this.containerStyles=window.getComputedStyle(this.container),this.containerPadding={left:parseFloat(this.containerStyles["padding-left"])||0,right:parseFloat(this.containerStyles["padding-right"])||0,top:parseFloat(this.containerStyles["padding-top"])||0,bottom:parseFloat(this.containerStyles["padding-bottom"])||0},this.stage={width:n-this.containerPadding.left-this.containerPadding.right,height:r-this.containerPadding.top-this.containerPadding.bottom},this.stage},EPUBJS.Rendition.prototype.applyLayoutMethod=function(){this.layout=new EPUBJS.Layout.Scroll,this.updateLayout(),this.map=new EPUBJS.Map(this.layout)},EPUBJS.Rendition.prototype.updateLayout=function(){this.layout.calculate(this.stage.width,this.stage.height)},EPUBJS.Rendition.prototype.resize=function(t,e){this.stageSize(t,e),this.updateLayout(),this.views.forEach(this.resizeView.bind(this)),this.trigger("resized",{width:this.stage.width,height:this.stage.height})},EPUBJS.Rendition.prototype.onResized=function(){this.resize()},EPUBJS.Rendition.prototype.createView=function(t){return new EPUBJS.View(t,this.viewSettings)},EPUBJS.Rendition.prototype.next=function(){return this.q.enqueue(function(){var t,e;return this.views.length?(t=this.views[0].section.next(),t?(e=this.createView(t),this.append(e)):void 0):void 0})},EPUBJS.Rendition.prototype.prev=function(){return this.q.enqueue(function(){var t,e;return this.views.length?(t=this.views[0].section.prev(),t?(e=this.createView(t),this.append(e)):void 0):void 0})},EPUBJS.Rendition.prototype.parseLayoutProperties=function(t){var e=t||this.book.package.metadata,i=this.layoutOveride&&this.layoutOveride.layout||e.layout||"reflowable",n=this.layoutOveride&&this.layoutOveride.spread||e.spread||"auto",r=this.layoutOveride&&this.layoutOveride.orientation||e.orientation||"auto";return this.globalLayoutProperties={layout:i,spread:n,orientation:r},this.globalLayoutProperties},EPUBJS.Rendition.prototype.current=function(){var t=this.visible();return t.length?t[t.length-1]:null},EPUBJS.Rendition.prototype.isVisible=function(t,e,i,n){var r=t.position(),o=n||this.container.getBoundingClientRect();return"horizontal"===this.settings.axis&&r.right>o.left-e&&!(r.left>=o.right+i)?!0:"vertical"===this.settings.axis&&r.bottom>o.top-e&&!(r.top>=o.bottom+i)?!0:!1},EPUBJS.Rendition.prototype.visible=function(){for(var t,e,i=this.bounds(),n=[],r=0;r=0;r--)if(t=this.views[r],e=t.bounds().top,ethis.settings.offsetDelta||this.scrollDeltaHorz>this.settings.offsetDelta)&&(this.q.enqueue(this.check),this.scrollDeltaVert=0,this.scrollDeltaHorz=0),this.scrollDeltaVert+=Math.abs(scrollTop-this.prevScrollTop),this.scrollDeltaHorz+=Math.abs(scrollLeft-this.prevScrollLeft),this.settings.height?(this.prevScrollTop=this.container.scrollTop,this.prevScrollLeft=this.container.scrollLeft):(this.prevScrollTop=window.scrollY,this.prevScrollLeft=window.scrollX),clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(function(){this.scrollDeltaVert=0,this.scrollDeltaHorz=0}.bind(this),150),this.scrolled=!1),this.tick.call(window,this.onScroll.bind(this))},EPUBJS.Continuous.prototype.scrollBy=function(t,e,i){i&&(this.ignore=!0),this.settings.height?(t&&(this.container.scrollLeft+=t),e&&(this.container.scrollTop+=e)):window.scrollBy(t,e),this.scrolled=!0},EPUBJS.Continuous.prototype.scrollTo=function(t,e,i){i&&(this.ignore=!0),this.settings.height?(this.container.scrollLeft=t,this.container.scrollTop=e):window.scrollTo(t,e),this.scrolled=!0},EPUBJS.Continuous.prototype.resizeView=function(t){"horizontal"===this.settings.axis?t.lock("height",this.stage.width,this.stage.height):t.lock("width",this.stage.width,this.stage.height)},EPUBJS.Continuous.prototype.currentLocation=function(){{var t,e,i=this.visible();this.container.getBoundingClientRect()}return 1===i.length?this.map.page(i[0]):i.length>1?(t=this.map.page(i[0]),e=this.map.page(i[i.length-1]),{start:t.start,end:e.end}):void 0},EPUBJS.Paginate=function(t,e){EPUBJS.Continuous.apply(this,arguments),this.settings=EPUBJS.core.extend(this.settings||{},{width:600,height:400,axis:"horizontal",forceSingle:!1,minSpreadWidth:800,gap:"auto",overflow:"hidden",infinite:!1}),EPUBJS.core.extend(this.settings,e),this.isForcedSingle=this.settings.forceSingle,this.viewSettings={axis:this.settings.axis},this.start()},EPUBJS.Paginate.prototype=Object.create(EPUBJS.Continuous.prototype),EPUBJS.Paginate.prototype.constructor=EPUBJS.Paginate,EPUBJS.Paginate.prototype.determineSpreads=function(t){return this.isForcedSingle||!t||this.bounds().width1?(t=a.left-s[0].position().left,i=t+this.layout.column,e=a.left+this.layout.spread-s[s.length-1].position().left,n=e+this.layout.column,r=this.map.page(s[0],t,i),o=this.map.page(s[s.length-1],e,n),{start:r.start,end:o.end}):void 0},EPUBJS.Paginate.prototype.resize=function(t,e){this.q.clear(),this.stageSize(t,e),this.updateLayout(),this.display(this.location.start),this.trigger("resized",{width:this.stage.width,height:this.stage.height})},EPUBJS.Paginate.prototype.onResized=function(){this.clear(),clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(function(){this.resize()}.bind(this),150)},EPUBJS.Paginate.prototype.adjustImages=function(t){return t.addStylesheetRules([["img",["max-width",this.layout.spread+"px"],["max-height",this.layout.height+"px"]]]),new RSVP.Promise(function(t){setTimeout(function(){t()},1)})},EPUBJS.Map=function(t){this.layout=t},EPUBJS.Map.prototype.section=function(t){var e=this.findRanges(t),i=this.rangeListToCfiList(t,e);return i},EPUBJS.Map.prototype.page=function(t,e,i){var n=t.document.body;return this.rangePairToCfiPair(t.section,{start:this.findStart(n,e,i),end:this.findEnd(n,e,i)})},EPUBJS.Map.prototype.walk=function(t,e){for(var i,n,r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode:function(t){return t.data.trim().length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}},!1);(i=r.nextNode())&&!(n=e(i)););return n},EPUBJS.Map.prototype.findRanges=function(t){for(var e,i,n=[],r=this.layout.count(t),o=this.layout.column,s=this.layout.gap,a=0;a=e&&i>=n?t:r>e?t:(s=t,void o.push(t))}))return this.findTextStartRange(r,e,i);return this.findTextStartRange(s,e,i)},EPUBJS.Map.prototype.findEnd=function(t,e,i){for(var n,r,o=[t],s=t;o.length;)if(n=o.shift(),r=this.walk(n,function(t){var e,n,r,a;return t.nodeType==Node.TEXT_NODE?(a=document.createRange(),a.selectNodeContents(t),r=a.getBoundingClientRect()):r=t.getBoundingClientRect(),e=r.left,n=r.right,e>i&&s?s:n>i?t:(s=t,void o.push(t))}))return this.findTextEndRange(r,e,i);return this.findTextEndRange(s,e,i)},EPUBJS.Map.prototype.findTextStartRange=function(t,e){for(var i,n,r,o=this.splitTextNodeIntoRanges(t),s=0;s=e)return n;i=n}return o[0]},EPUBJS.Map.prototype.findTextEndRange=function(t,e,i){for(var n,r,o,s=this.splitTextNodeIntoRanges(t),a=0;ai&&n)return n;if(o.right>i)return r;n=r}return s[s.length-1]},EPUBJS.Map.prototype.splitTextNodeIntoRanges=function(t,e){var i,n=[],r=t.textContent||"",o=r.trim(),s=t.ownerDocument,a=e||" ";if(pos=o.indexOf(a),-1===pos||t.nodeType!=Node.TEXT_NODE)return i=s.createRange(),i.selectNodeContents(t),[i];for(i=s.createRange(),i.setStart(t,0),i.setEnd(t,pos),n.push(i),i=!1;-1!=pos;)pos=o.indexOf(a,pos+1),pos>0&&(i&&(i.setEnd(t,pos),n.push(i)),i=s.createRange(),i.setStart(t,pos+1));return i&&(i.setEnd(t,o.length),n.push(i)),n},EPUBJS.Map.prototype.rangePairToCfiPair=function(t,e){var i=e.start,n=e.end;return i.collapse(!0),n.collapse(!0),startCfi=t.cfiFromRange(i),endCfi=t.cfiFromRange(n),{start:startCfi,end:endCfi}},EPUBJS.Map.prototype.rangeListToCfiList=function(t,e){for(var i,n=[],r=0;ri;i++)if(t[i]===e)return i;return-1}function e(t){var e=t._promiseCallbacks;return e||(e=t._promiseCallbacks={}),e}function i(t,e){return"onerror"===t?(Y.on("error",e),void 0):2!==arguments.length?Y[t]:(Y[t]=e,void 0)}function n(t){return"function"==typeof t||"object"==typeof t&&null!==t}function r(t){return"function"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(){}function h(){}function a(t){try{return t.then}catch(e){return oe.error=e,oe}}function u(t,e,i,n){try{t.call(e,i,n)}catch(r){return r}}function c(t,e,i){Y.async(function(t){var n=!1,r=u(i,e,function(i){n||(n=!0,e!==i?d(t,i):g(t,i))},function(e){n||(n=!0,y(t,e))},"Settle: "+(t._label||" unknown promise"));!n&&r&&(n=!0,y(t,r))},t)}function p(t,e){e._state===ne?g(t,e._result):t._state===re?y(t,e._result):m(e,void 0,function(i){e!==i?d(t,i):g(t,i)},function(e){y(t,e)})}function l(t,e){if(e.constructor===t.constructor)p(t,e);else{var i=a(e);i===oe?y(t,oe.error):void 0===i?g(t,e):r(i)?c(t,e,i):g(t,e)}}function d(t,e){t===e?g(t,e):n(e)?l(t,e):g(t,e)}function f(t){t._onerror&&t._onerror(t._result),S(t)}function g(t,e){t._state===ie&&(t._result=e,t._state=ne,0===t._subscribers.length?Y.instrument&&ee("fulfilled",t):Y.async(S,t))}function y(t,e){t._state===ie&&(t._state=re,t._result=e,Y.async(f,t))}function m(t,e,i,n){var r=t._subscribers,o=r.length;t._onerror=null,r[o]=e,r[o+ne]=i,r[o+re]=n,0===o&&t._state&&Y.async(S,t)}function S(t){var e=t._subscribers,i=t._state;if(Y.instrument&&ee(i===ne?"fulfilled":"rejected",t),0!==e.length){for(var n,r,o=t._result,s=0;sh;h++)s[h]=t[h];for(n=0;nn;n++)i[n-1]=t[n];return i}function N(t,e){return{then:function(i,n){return t.call(e,i,n)}}}function q(t,e,i,n){var r=_(i,n,e);return r===ge&&y(t,r.value),t}function L(t,e,i,n){return fe.all(e).then(function(e){var r=_(i,n,e);return r===ge&&y(t,r.value),t})}function F(t){return t&&"object"==typeof t?t.constructor===fe?!0:R(t):!1}function O(t,e,i){this._superConstructor(t,e,!1,i)}function I(t,e,i){this._superConstructor(t,e,!0,i)}function V(t,e,i){this._superConstructor(t,e,!1,i)}function A(){return function(){process.nextTick(z)}}function M(){var t=0,e=new qe(z),i=document.createTextNode("");return e.observe(i,{characterData:!0}),function(){i.data=t=++t%2}}function H(){var t=new MessageChannel;return t.port1.onmessage=z,function(){t.port2.postMessage(0)}}function j(){return function(){setTimeout(z,1)}}function z(){for(var t=0;Te>t;t+=2){var e=Fe[t],i=Fe[t+1];e(i),Fe[t]=void 0,Fe[t+1]=void 0}Te=0}function D(t,e){Y.async(t,e)}function W(){Y.on.apply(Y,arguments)}function X(){Y.off.apply(Y,arguments)}var Q={mixin:function(t){return t.on=this.on,t.off=this.off,t.trigger=this.trigger,t._promiseCallbacks=void 0,t},on:function(i,n){var r,o=e(this);r=o[i],r||(r=o[i]=[]),-1===t(r,n)&&r.push(n)},off:function(i,n){var r,o,s=e(this);return n?(r=s[i],o=t(r,n),-1!==o&&r.splice(o,1),void 0):(s[i]=[],void 0)},trigger:function(t,i){var n,r,o=e(this);if(n=o[t])for(var s=0;s1)throw new Error("Second argument not supported");if("object"!=typeof t)throw new TypeError("Argument must be an object");return s.prototype=t,new s},te=[],ee=function(t,e,i){1===te.push({name:t,payload:{guid:e._guidKey+e._id,eventName:t,detail:e._result,childGuid:i&&e._guidKey+i._id,label:e._label,timeStamp:Z(),stack:new Error(e._label).stack}})&&setTimeout(function(){for(var t,e=0;en;n++)this._eachEntry(i[n],n)},U.prototype._eachEntry=function(t,e){var i=this._instanceConstructor;o(t)?t.constructor===i&&t._state!==ie?(t._onerror=null,this._settledAt(t._state,e,t._result)):this._willSettleAt(i.resolve(t),e):(this._remaining--,this._result[e]=this._makeResult(ne,e,t))},U.prototype._settledAt=function(t,e,i){var n=this.promise;n._state===ie&&(this._remaining--,this._abortOnReject&&t===re?y(n,i):this._result[e]=this._makeResult(t,e,i)),0===this._remaining&&g(n,this._result)},U.prototype._makeResult=function(t,e,i){return i},U.prototype._willSettleAt=function(t,e){var i=this;m(t,void 0,function(t){i._settledAt(ne,e,t)},function(t){i._settledAt(re,e,t)})};var ae=function(t,e){return new he(this,t,!0,e).promise},ue=function(t,e){function i(t){d(o,t)}function n(t){y(o,t)}var r=this,o=new r(h,e);if(!G(t))return y(o,new TypeError("You must pass an array to race.")),o;for(var s=t.length,a=0;o._state===ie&&s>a;a++)m(r.resolve(t[a]),void 0,i,n);return o},ce=function(t,e){var i=this;if(t&&"object"==typeof t&&t.constructor===i)return t;var n=new i(h,e);return d(n,t),n},pe=function(t,e){var i=this,n=new i(h,e);return y(n,t),n},le="rsvp_"+Z()+"-",de=0,fe=x;x.cast=ce,x.all=ae,x.race=ue,x.resolve=ce,x.reject=pe,x.prototype={constructor:x,_guidKey:le,_onerror:function(t){Y.trigger("error",t)},then:function(t,e,i){var n=this,r=n._state;if(r===ne&&!t||r===re&&!e)return Y.instrument&&ee("chained",this,this),this;n._onerror=null;var o=new this.constructor(h,i),s=n._result;if(Y.instrument&&ee("chained",n,o),r){var a=arguments[r-1];Y.async(function(){P(r,o,a,s)})}else m(n,o,t,e);return o},"catch":function(t,e){return this.then(null,t,e)},"finally":function(t,e){var i=this.constructor;return this.then(function(e){return i.resolve(t()).then(function(){return e})},function(e){return i.resolve(t()).then(function(){throw e})},e)}};var ge=new C,ye=new C,me=function(t,e){var i=function(){for(var i,n=this,r=arguments.length,o=new Array(r+1),s=!1,a=0;r>a;++a){if(i=arguments[a],!s){if(s=F(i),s===ye){var u=new fe(h);return y(u,ye.value),u}s&&s!==!0&&(i=N(s,i))}o[a]=i}var c=new fe(h);return o[r]=function(t,i){t?y(c,t):void 0===e?d(c,i):e===!0?d(c,k(arguments)):G(e)?d(c,T(arguments,e)):d(c,i)},s?L(c,o,t,n):q(c,o,t,n)};return i.__proto__=t,i},Se=function(t,e){return fe.all(t,e)};O.prototype=$(he.prototype),O.prototype._superConstructor=he,O.prototype._makeResult=w,O.prototype._validationError=function(){return new Error("allSettled must be called with an array")};var ve=function(t,e){return new O(fe,t,e).promise},Ee=function(t,e){return fe.race(t,e)},Pe=I;I.prototype=$(he.prototype),I.prototype._superConstructor=he,I.prototype._init=function(){this._result={}},I.prototype._validateInput=function(t){return t&&"object"==typeof t},I.prototype._validationError=function(){return new Error("Promise.hash must be called with an object")},I.prototype._enumerate=function(){var t=this.promise,e=this._input,i=[];for(var n in e)t._state===ie&&e.hasOwnProperty(n)&&i.push({position:n,entry:e[n]});var r=i.length;this._remaining=r;for(var o,s=0;t._state===ie&&r>s;s++)o=i[s],this._eachEntry(o.entry,o.position)};var Be=function(t,e){return new Pe(fe,t,e).promise};V.prototype=$(Pe.prototype),V.prototype._superConstructor=he,V.prototype._makeResult=w,V.prototype._validationError=function(){return new Error("hashSettled must be called with an object")};var we,Ue=function(t,e){return new V(fe,t,e).promise},be=function(t){throw setTimeout(function(){throw t}),t},Je=function(t){var e={};return e.promise=new fe(function(t,i){e.resolve=t,e.reject=i},t),e},xe=function(t,e,i){return fe.all(t,i).then(function(t){if(!r(e))throw new TypeError("You must pass a function as map's second argument.");for(var n=t.length,o=new Array(n),s=0;n>s;s++)o[s]=e(t[s]);return fe.all(o,i)})},Ce=function(t,e){return fe.resolve(t,e)},Re=function(t,e){return fe.reject(t,e)},_e=function(t,e,i){return fe.all(t,i).then(function(t){if(!r(e))throw new TypeError("You must pass a function as filter's second argument.");for(var n=t.length,o=new Array(n),s=0;n>s;s++)o[s]=e(t[s]);return fe.all(o,i).then(function(e){for(var i=new Array(n),r=0,o=0;n>o;o++)e[o]&&(i[r]=t[o],r++);return i.length=r,i})})},Te=0,ke=function(t,e){Fe[Te]=t,Fe[Te+1]=e,Te+=2,2===Te&&we()},Ne="undefined"!=typeof window?window:{},qe=Ne.MutationObserver||Ne.WebKitMutationObserver,Le="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,Fe=new Array(1e3);we="undefined"!=typeof process&&"[object process]"==={}.toString.call(process)?A():qe?M():Le?H():j(),Y.async=ke;if("undefined"!=typeof window&&"object"==typeof window.__PROMISE_INSTRUMENTATION__){var Oe=window.__PROMISE_INSTRUMENTATION__;i("instrument",!0);for(var Ie in Oe)Oe.hasOwnProperty(Ie)&&W(Ie,Oe[Ie])}var Ve={race:Ee,Promise:fe,allSettled:ve,hash:Be,hashSettled:Ue,denodeify:me,on:W,off:X,map:xe,filter:_e,resolve:Ce,reject:Re,all:Se,rethrow:be,defer:Je,EventTarget:Q,configure:i,async:D};"function"==typeof define&&define.amd?define(function(){return Ve}):"undefined"!=typeof module&&module.exports?module.exports=Ve:"undefined"!=typeof this&&(this.RSVP=Ve)}).call(this),"undefined"==typeof EPUBJS&&(("undefined"!=typeof window?window:this).EPUBJS={}),EPUBJS.VERSION="0.3.0",function(t){"use strict";var e=function(t){return new EPUBJS.Book(t)};"object"==typeof exports?(t.RSVP=require("rsvp"),module.exports=e):"function"==typeof define&&define.amd?define(e):t.ePub=e}(this),EPUBJS.core={},EPUBJS.core.request=function(t,e,i,n){function r(){if(this.readyState===this.DONE)if(200===this.status||this.responseXML){var t;t="xml"==e?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"text/xml"):"json"==e?JSON.parse(this.response):"blob"==e?s?this.response:new Blob([this.response]):this.response,a.resolve(t)}else a.reject({status:this.status,message:this.response,stack:(new Error).stack})}var o,s=window.URL,h=s?"blob":"arraybuffer",a=new RSVP.defer,u=new XMLHttpRequest,c=XMLHttpRequest.prototype;"overrideMimeType"in c||Object.defineProperty(c,"overrideMimeType",{value:function(){}}),i&&(u.withCredentials=!0),u.open("GET",t,!0);for(o in n)u.setRequestHeader(o,n[o]);return u.onreadystatechange=r,"blob"==e&&(u.responseType=h),"json"==e&&u.setRequestHeader("Accept","application/json"),"xml"==e&&u.overrideMimeType("text/xml"),u.send(),a.promise},EPUBJS.core.uri=function(t){var e,i,n,r={protocol:"",host:"",path:"",origin:"",directory:"",base:"",filename:"",extension:"",fragment:"",href:t},o=t.indexOf("://"),s=t.indexOf("?"),h=t.indexOf("#");return-1!=h&&(r.fragment=t.slice(h+1),t=t.slice(0,h)),-1!=s&&(r.search=t.slice(s+1),t=t.slice(0,s),href=t),-1!=o?(r.protocol=t.slice(0,o),e=t.slice(o+3),n=e.indexOf("/"),-1===n?(r.host=r.path,r.path=""):(r.host=e.slice(0,n),r.path=e.slice(n)),r.origin=r.protocol+"://"+r.host,r.directory=EPUBJS.core.folder(r.path),r.base=r.origin+r.directory):(r.path=t,r.directory=EPUBJS.core.folder(t),r.base=r.directory),r.filename=t.replace(r.base,""),i=r.filename.lastIndexOf("."),-1!=i&&(r.extension=r.filename.slice(i+1)),r},EPUBJS.core.folder=function(t){var e=t.lastIndexOf("/");if(-1==e)var i="";return i=t.slice(0,e+1)},EPUBJS.core.queue=function(t){var e=[],i=t,n=function(t,i,n){return e.push({funcName:t,args:i,context:n}),e},r=function(){var t;e.length&&(t=e.shift(),i[t.funcName].apply(t.context||i,t.args))},o=function(){for(;e.length;)r()},s=function(){e=[]},h=function(){return e.length};return{enqueue:n,dequeue:r,flush:o,clear:s,length:h}},EPUBJS.core.isElement=function(t){return!(!t||1!=t.nodeType)},EPUBJS.core.uuid=function(){var t=(new Date).getTime(),e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:7&i|8).toString(16)});return e},EPUBJS.core.values=function(t){for(var e=-1,i=Object.keys(t),n=i.length,r=Array(n);++er;r++)if("undefined"!=typeof document.body.style[e[r]+i])return e[r]+i;return t},EPUBJS.core.defaults=function(t){for(var e=1,i=arguments.length;i>e;e++){var n=arguments[e];for(var r in n)void 0===t[r]&&(t[r]=n[r])}return t},EPUBJS.core.extend=function(t){var e=[].slice.call(arguments,1);return e.forEach(function(e){e&&Object.getOwnPropertyNames(e).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(e,i))})}),t},EPUBJS.core.insert=function(t,e,i){var n=EPUBJS.core.locationOf(t,e,i);return e.splice(n,0,t),n},EPUBJS.core.locationOf=function(t,e,i,n,r){var o,s=n||0,h=r||e.length,a=parseInt(s+(h-s)/2);return i||(i=function(t,e){return t>e?1:e>t?-1:(t=e)?0:void 0}),0>=h-s?a:(o=i(e[a],t),h-s===1?o>0?a:a+1:0===o?a:-1===o?EPUBJS.core.locationOf(t,e,i,a,h):EPUBJS.core.locationOf(t,e,i,s,a))},EPUBJS.core.indexOfSorted=function(t,e,i,n,r){var o,s=n||0,h=r||e.length,a=parseInt(s+(h-s)/2);return i||(i=function(t,e){return t>e?1:e>t?-1:(t=e)?0:void 0}),0>=h-s?-1:(o=i(e[a],t),h-s===1?0===o?a:-1:0===o?a:-1===o?EPUBJS.core.indexOfSorted(t,e,i,a,h):EPUBJS.core.indexOfSorted(t,e,i,s,a))},EPUBJS.core.requestAnimationFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,EPUBJS.core.bounds=function(t){var e=window.getComputedStyle(t),i=["width","paddingRight","paddingLeft","marginRight","marginLeft","borderRightWidth","borderLeftWidth"],n=["height","paddingTop","paddingBottom","marginTop","marginBottom","borderTopWidth","borderBottomWidth"],r=0,o=0;return i.forEach(function(t){r+=parseFloat(e[t])||0}),n.forEach(function(t){o+=parseFloat(e[t])||0}),{height:o,width:r}},EPUBJS.core.borders=function(t){var e=window.getComputedStyle(t),i=["paddingRight","paddingLeft","marginRight","marginLeft","borderRightWidth","borderLeftWidth"],n=["paddingTop","paddingBottom","marginTop","marginBottom","borderTopWidth","borderBottomWidth"],r=0,o=0;return i.forEach(function(t){r+=parseFloat(e[t])||0}),n.forEach(function(t){o+=parseFloat(e[t])||0}),{height:o,width:r}},EPUBJS.core.windowBounds=function(){var t=window.innerWidth,e=window.innerHeight;return{top:0,left:0,right:t,bottom:e,width:t,height:e}},EPUBJS.core.cleanStringForXpath=function(t){var e=t.match(/[^'"]+|['"]/g);return e=e.map(function(t){return"'"===t?'"\'"':'"'===t?"'\"'":"'"+t+"'"}),"concat('',"+e.join(",")+")"},EPUBJS.core.indexOfTextNode=function(t){for(var e,i=t.parentNode,n=i.childNodes,r=-1,o=0;o=0;s--){var h=r.snapshotItem(s),a=h.getAttribute("id")||!1,u=h.querySelector("content"),c=u.getAttribute("src"),p=h.querySelector("navLabel"),l=p.textContent?p.textContent:"",d=c.split("#"),f=(d[0],e(h));n.unshift({id:a,href:c,label:l,subitems:f,parent:i?i.getAttribute("id"):null})}return n}var i=t.querySelector("navMap");return i?e(i):[]},EPUBJS.EpubCFI=function(t){return t?this.parse(t):void 0},EPUBJS.EpubCFI.prototype.generateChapterComponent=function(t,e,i){var n=parseInt(e),r=t+1,o="/"+r+"/";return o+=2*(n+1),i&&(o+="["+i+"]"),o},EPUBJS.EpubCFI.prototype.generatePathComponent=function(t){var e=[];return t.forEach(function(t){var i="";i+=2*(t.index+1),t.id&&(i+="["+t.id+"]"),e.push(i)}),e.join("/")},EPUBJS.EpubCFI.prototype.generateCfiFromElement=function(t,e){var i=this.pathTo(t),n=this.generatePathComponent(i);return n.length?"epubcfi("+e+"!"+n+"/1:0)":"epubcfi("+e+"!/4/)"},EPUBJS.EpubCFI.prototype.pathTo=function(t){for(var e,i=[];t&&null!==t.parentNode&&9!=t.parentNode.nodeType;)e=t.parentNode.children,i.unshift({id:t.id,tagName:t.tagName,index:e?Array.prototype.indexOf.call(e,t):0}),t=t.parentNode;return i},EPUBJS.EpubCFI.prototype.getChapterComponent=function(t){var e=t.split("!");return e[0]},EPUBJS.EpubCFI.prototype.getPathComponent=function(t){var e=t.split("!"),i=e[1]?e[1].split(":"):"";return i[0]},EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent=function(t){var e=t.split(":");return e[1]||""},EPUBJS.EpubCFI.prototype.parse=function(t){var e,i,n,r,o,s,h,a,u,c={},p=function(t){var e,i,n,r;return e="element",i=parseInt(t)/2-1,n=t.match(/\[(.*)\]/),n&&n[1]&&(r=n[1]),{type:e,index:i,id:r||!1}};return"string"!=typeof t?{spinePos:-1}:(c.str=t,0===t.indexOf("epubcfi(")&&")"===t[t.length-1]&&(t=t.slice(8,t.length-1)),i=this.getChapterComponent(t),n=this.getPathComponent(t)||"",r=this.getCharecterOffsetComponent(t),i?(e=i.split("/")[2]||"")?(c.spinePos=parseInt(e)/2-1||0,s=e.match(/\[(.*)\]/),c.spineId=s?s[1]:!1,-1!=n.indexOf(",")&&console.warn("CFI Ranges are not supported"),h=n.split("/"),a=h.pop(),c.steps=[],h.forEach(function(t){var e;t&&(e=p(t),c.steps.push(e))}),u=parseInt(a),isNaN(u)||(u%2===0?c.steps.push(p(a)):c.steps.push({type:"text",index:(u-1)/2})),o=r.match(/\[(.*)\]/),o&&o[1]?(c.characterOffset=parseInt(r.split("[")[0]),c.textLocationAssertion=o[1]):c.characterOffset=parseInt(r),c):{spinePos:-1}:{spinePos:-1})},EPUBJS.EpubCFI.prototype.addMarker=function(t,e,i){var n,r,o,s,h=e||document,a=i||this.createMarker(h);return"string"==typeof t&&(t=this.parse(t)),r=t.steps[t.steps.length-1],-1===t.spinePos?!1:(n=this.findParent(t,h))?(r&&"text"===r.type?(o=n.childNodes[r.index],t.characterOffset?(s=o.splitText(t.characterOffset),a.classList.add("EPUBJS-CFI-SPLIT"),n.insertBefore(a,s)):n.insertBefore(a,o)):n.insertBefore(a,n.firstChild),a):!1},EPUBJS.EpubCFI.prototype.createMarker=function(t){var e=t||document,i=e.createElement("span");return i.id="EPUBJS-CFI-MARKER:"+EPUBJS.core.uuid(),i.classList.add("EPUBJS-CFI-MARKER"),i},EPUBJS.EpubCFI.prototype.removeMarker=function(t,e){t.classList.contains("EPUBJS-CFI-SPLIT")?(nextSib=t.nextSibling,prevSib=t.previousSibling,nextSib&&prevSib&&3===nextSib.nodeType&&3===prevSib.nodeType&&(prevSib.textContent+=nextSib.textContent,t.parentNode.removeChild(nextSib)),t.parentNode.removeChild(t)):t.classList.contains("EPUBJS-CFI-MARKER")&&t.parentNode.removeChild(t)},EPUBJS.EpubCFI.prototype.findParent=function(t,e){var i,n,r,o=e||document,s=o.getElementsByTagName("html")[0],h=Array.prototype.slice.call(s.children);if("string"==typeof t&&(t=this.parse(t)),n=t.steps.slice(0),!n.length)return o.getElementsByTagName("body")[0];for(;n&&n.length>0;){if(i=n.shift(),"text"===i.type?(r=s.childNodes[i.index],s=r.parentNode||s):s=i.id?o.getElementById(i.id):h[i.index],"undefined"==typeof s)return console.error("No Element For",i,t.str),!1;h=Array.prototype.slice.call(s.children)}return s},EPUBJS.EpubCFI.prototype.compare=function(t,e){if("string"==typeof t&&(t=new EPUBJS.EpubCFI(t)),"string"==typeof e&&(e=new EPUBJS.EpubCFI(e)),t.spinePos>e.spinePos)return 1;if(t.spinePose.steps[i].index)return 1;if(t.steps[i].indexe.characterOffset?1:t.characterOffset=0?(o=r.length,t.characterOffset-1?(delete this.spineByHref[t.href],delete this.spineById[t.idref],this.spineItems.splice(e,1)):void 0},EPUBJS.replace={},EPUBJS.replace.links=function(t,e){for(var i=t.document.querySelectorAll("a[href]"),n=function(t){var i=t.getAttribute("href"),n=new EPUBJS.core.uri(i);n.protocol?t.setAttribute("target","_blank"):0===i.indexOf("#")||(t.onclick=function(){return e.display(i),!1})},r=0;r-1&&(this.observer=this.observe(this.document.body)),this.imageLoadListeners(),this.mediaQueryListeners(),this.resizeListenters()},EPUBJS.View.prototype.resizeListenters=function(){clearTimeout(this.expanding),this.expanding=setTimeout(this.expand.bind(this),350)},EPUBJS.View.prototype.mediaQueryListeners=function(){for(var t=this.document.styleSheets,e=function(t){t.matches&&!this._expanding&&this.expand()}.bind(this),i=0;i-1&&(id=t.substring(t.indexOf("#")),el=this.document.getElementById(id)))return el.getBoundingClientRect();return{left:0,top:0}}},EPUBJS.View.prototype.addCss=function(t){var e=document.createElement("link"),i=!1;return new RSVP.Promise(function(n){return this.document?(e.type="text/css",e.rel="stylesheet",e.href=t,e.onload=e.onreadystatechange=function(){i||this.readyState&&"complete"!=this.readyState||(i=!0,setTimeout(function(){n(!0)},1))},this.document.head.appendChild(e),void 0):(n(!1),void 0)}.bind(this))},EPUBJS.View.prototype.addStylesheetRules=function(t){var e,i=document.createElement("style");if(this.document){this.document.head.appendChild(i),e=i.sheet;for(var n=0,r=t.length;r>n;n++){var o=1,s=t[n],h=t[n][0],a="";"[object Array]"===Object.prototype.toString.call(s[1][0])&&(s=s[1],o=0);for(var u=s.length;u>o;o++){var c=s[o];a+=c[0]+":"+c[1]+(c[2]?" !important":"")+";\n"}e.insertRule(h+"{"+a+"}",e.cssRules.length)}}},RSVP.EventTarget.mixin(EPUBJS.View.prototype),EPUBJS.Layout=EPUBJS.Layout||{},EPUBJS.Layout.Reflowable=function(){},EPUBJS.Layout.Reflowable.prototype.calculate=function(t,e,i,n){var r,o,s,h=n||1,a=Math.floor(t),u=a%2===0?a:a-1,c=Math.floor(u/8),p=i>=0?i:c%2===0?c:c-1;r=h>1?Math.floor((u-p)/h):u,o=r*h,s=(r+p)*h,this.columnAxis=EPUBJS.core.prefixed("columnAxis"),this.columnGap=EPUBJS.core.prefixed("columnGap"),this.columnWidth=EPUBJS.core.prefixed("columnWidth"),this.columnFill=EPUBJS.core.prefixed("columnFill"),this.width=u,this.height=e,this.spread=o,this.delta=s,this.column=r,this.gap=p,this.divisor=h},EPUBJS.Layout.Reflowable.prototype.format=function(t){var e=t.document.documentElement,i=t.document.body;e.style.overflow="hidden",e.style.width=this.width+"px",i.style.height=this.height+"px",i.style[this.columnAxis]="horizontal",i.style[this.columnFill]="auto",i.style[this.columnGap]=this.gap+"px",i.style[this.columnWidth]=this.column+"px",t.iframe.style.marginRight=this.gap+"px"},EPUBJS.Layout.Reflowable.prototype.count=function(t){var e=t.root().scrollWidth,i=Math.ceil(e/this.spread);return{spreads:i,pages:i*this.divisor}},EPUBJS.Layout.Fixed=function(){},EPUBJS.Layout.Fixed.prototype.calculate=function(){},EPUBJS.Layout.Fixed.prototype.format=function(t){var e,i,n=t.document.documentElement,r=documentElement.querySelector("[name=viewport");r&&r.hasAttribute("content")&&(content=r.getAttribute("content"),contents=content.split(","),contents[0]&&(e=contents[0].replace("width=","")),contents[1]&&(i=contents[1].replace("height=",""))),t.resize(e,i),n.style.overflow="auto"},EPUBJS.Layout.Fixed.prototype.count=function(){return{spreads:1,pages:1}},EPUBJS.Layout.Scroll=function(){},EPUBJS.Layout.Scroll.prototype.calculate=function(t){this.spread=t,this.column=t,this.gap=0},EPUBJS.Layout.Scroll.prototype.format=function(t){var e=t.document.documentElement;e.style.width="auto",e.style.height="auto"},EPUBJS.Layout.Scroll.prototype.count=function(){return{spreads:1,pages:1}},EPUBJS.Rendition=function(t,e){this.settings=EPUBJS.core.extend(this.settings||{},{infinite:!0,hidden:!1,width:!1,height:null,layoutOveride:null,axis:"vertical"}),EPUBJS.core.extend(this.settings,e),this.viewSettings={},this.book=t,this.views=[],this.hooks={},this.hooks.display=new EPUBJS.Hook(this),this.hooks.content=new EPUBJS.Hook(this),this.hooks.layout=new EPUBJS.Hook(this),this.hooks.render=new EPUBJS.Hook(this),this.hooks.show=new EPUBJS.Hook(this),this.hooks.content.register(EPUBJS.replace.links.bind(this)),this.epubcfi=new EPUBJS.EpubCFI,this.q=new EPUBJS.Queue(this),this.q.enqueue(this.book.opened),this.q.enqueue(this.parseLayoutProperties)},EPUBJS.Rendition.prototype.initialize=function(t){{var e,i=t||{},n=i.height,r=i.width;i.hidden||!1}return i.height&&EPUBJS.core.isNumber(i.height)&&(n=i.height+"px"),i.width&&EPUBJS.core.isNumber(i.width)&&(r=i.width+"px"),e=document.createElement("div"),e.id="epubjs-container:"+EPUBJS.core.uuid(),e.classList.add("epub-container"),e.style.fontSize="0",e.style.wordSpacing="0",e.style.lineHeight="0",e.style.verticalAlign="top","horizontal"===this.settings.axis&&(e.style.whiteSpace="nowrap"),r&&(e.style.width=r),n&&(e.style.height=n),e.style.overflow=this.settings.overflow,e},EPUBJS.Rendition.wrap=function(t){var e=document.createElement("div");return e.style.visibility="hidden",e.style.overflow="hidden",e.style.width="0",e.style.height="0",e.appendChild(t),e},EPUBJS.Rendition.prototype.attachTo=function(t){return this.container=this.initialize({width:this.settings.width,height:this.settings.height}),EPUBJS.core.isElement(t)?this.element=t:"string"==typeof t&&(this.element=document.getElementById(t)),this.element?(this.settings.hidden?(this.wrapper=this.wrap(this.container),this.element.appendChild(this.wrapper)):this.element.appendChild(this.container),this.attachListeners(),this.stageSize(),this.applyLayoutMethod(),this.trigger("attached"),void 0):(console.error("Not an Element"),void 0)},EPUBJS.Rendition.prototype.attachListeners=function(){EPUBJS.core.isNumber(this.settings.width)&&EPUBJS.core.isNumber(this.settings.height)||window.addEventListener("resize",this.onResized.bind(this),!1)},EPUBJS.Rendition.prototype.bounds=function(){return this.container.getBoundingClientRect()},EPUBJS.Rendition.prototype.display=function(t){return this.q.enqueue(this._display,t)},EPUBJS.Rendition.prototype._display=function(t){var e,i,n,r,o=new RSVP.defer,s=o.promise;return this.epubcfi.isCfiString(t)?(n=this.epubcfi.parse(t),r=n.spinePos,e=this.book.spine.get(r)):e=this.book.spine.get(t),this.displaying=!0,this.hide(),e?(i=this.createView(e),this.q.enqueue(this.append,i),this.show(),this.hooks.display.trigger(i).then(function(){this.trigger("displayed",e),o.resolve(this)}.bind(this))):o.reject(new Error("No Section Found")),s},EPUBJS.Rendition.prototype.moveTo=function(){},EPUBJS.Rendition.prototype.render=function(t,e){return t.create(),t.onLayout=this.layout.format.bind(this.layout),this.resizeView(t),t.render(this.book.request).then(function(){return this.hooks.content.trigger(t,this)}.bind(this)).then(function(){return this.hooks.layout.trigger(t,this)}.bind(this)).then(function(){return t.display()}.bind(this)).then(function(){return this.hooks.render.trigger(t,this)}.bind(this)).then(function(){0!=e&&this.hidden===!1&&this.q.enqueue(function(t){t.show()},t),this.trigger("rendered",t.section)}.bind(this)).catch(function(t){this.trigger("loaderror",t)}.bind(this))},EPUBJS.Rendition.prototype.afterDisplayed=function(t){this.trigger("added",t.section)},EPUBJS.Rendition.prototype.append=function(t){return this.clear(),this.views.push(t),this.container.appendChild(t.element),t.onDisplayed=this.afterDisplayed.bind(this),this.render(t)},EPUBJS.Rendition.prototype.clear=function(){this.views.forEach(function(t){this._remove(t)}.bind(this)),this.views=[]},EPUBJS.Rendition.prototype.remove=function(t){var e=this.views.indexOf(t);e>-1&&this.views.splice(e,1),this._remove(t)},EPUBJS.Rendition.prototype._remove=function(t){t.off("resized"),t.displayed&&t.destroy(),this.container.removeChild(t.element),t=null},EPUBJS.Rendition.prototype.resizeView=function(t){"pre-paginated"===this.globalLayoutProperties.layout?t.lock("both",this.stage.width,this.stage.height):t.lock("width",this.stage.width,this.stage.height)},EPUBJS.Rendition.prototype.stageSize=function(t,e){var i,n=t||this.settings.width,r=e||this.settings.height;return n===!1&&(i=this.element.getBoundingClientRect(),i.width&&(n=i.width,this.container.style.width=i.width+"px")),r===!1&&(i=i||this.element.getBoundingClientRect(),i.height&&(r=i.height,this.container.style.height=i.height+"px")),n&&!EPUBJS.core.isNumber(n)&&(i=this.container.getBoundingClientRect(),n=i.width),r&&!EPUBJS.core.isNumber(r)&&(i=i||this.container.getBoundingClientRect(),r=i.height),this.containerStyles=window.getComputedStyle(this.container),this.containerPadding={left:parseFloat(this.containerStyles["padding-left"])||0,right:parseFloat(this.containerStyles["padding-right"])||0,top:parseFloat(this.containerStyles["padding-top"])||0,bottom:parseFloat(this.containerStyles["padding-bottom"])||0},this.stage={width:n-this.containerPadding.left-this.containerPadding.right,height:r-this.containerPadding.top-this.containerPadding.bottom},this.stage},EPUBJS.Rendition.prototype.applyLayoutMethod=function(){this.layout=new EPUBJS.Layout.Scroll,this.updateLayout(),this.map=new EPUBJS.Map(this.layout)},EPUBJS.Rendition.prototype.updateLayout=function(){this.layout.calculate(this.stage.width,this.stage.height)},EPUBJS.Rendition.prototype.resize=function(t,e){this.stageSize(t,e),this.updateLayout(),this.views.forEach(this.resizeView.bind(this)),this.trigger("resized",{width:this.stage.width,height:this.stage.height})},EPUBJS.Rendition.prototype.onResized=function(){this.resize()},EPUBJS.Rendition.prototype.createView=function(t){return new EPUBJS.View(t,this.viewSettings)},EPUBJS.Rendition.prototype.next=function(){return this.q.enqueue(function(){var t,e;return this.views.length?(t=this.views[0].section.next(),t?(e=this.createView(t),this.append(e)):void 0):void 0})},EPUBJS.Rendition.prototype.prev=function(){return this.q.enqueue(function(){var t,e;return this.views.length?(t=this.views[0].section.prev(),t?(e=this.createView(t),this.append(e)):void 0):void 0})},EPUBJS.Rendition.prototype.parseLayoutProperties=function(t){var e=t||this.book.package.metadata,i=this.layoutOveride&&this.layoutOveride.layout||e.layout||"reflowable",n=this.layoutOveride&&this.layoutOveride.spread||e.spread||"auto",r=this.layoutOveride&&this.layoutOveride.orientation||e.orientation||"auto";return this.globalLayoutProperties={layout:i,spread:n,orientation:r},this.globalLayoutProperties},EPUBJS.Rendition.prototype.current=function(){var t=this.visible();return t.length?t[t.length-1]:null},EPUBJS.Rendition.prototype.isVisible=function(t,e,i,n){var r=t.position(),o=n||this.container.getBoundingClientRect();return"horizontal"===this.settings.axis&&r.right>o.left-e&&!(r.left>=o.right+i)?!0:"vertical"===this.settings.axis&&r.bottom>o.top-e&&!(r.top>=o.bottom+i)?!0:!1},EPUBJS.Rendition.prototype.visible=function(){for(var t,e,i=this.bounds(),n=[],r=0;r=0;r--)if(t=this.views[r],e=t.bounds().top,ethis.settings.offsetDelta||this.scrollDeltaHorz>this.settings.offsetDelta)&&(this.q.enqueue(this.check),this.scrollDeltaVert=0,this.scrollDeltaHorz=0),this.scrollDeltaVert+=Math.abs(scrollTop-this.prevScrollTop),this.scrollDeltaHorz+=Math.abs(scrollLeft-this.prevScrollLeft),this.settings.height?(this.prevScrollTop=this.container.scrollTop,this.prevScrollLeft=this.container.scrollLeft):(this.prevScrollTop=window.scrollY,this.prevScrollLeft=window.scrollX),clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(function(){this.scrollDeltaVert=0,this.scrollDeltaHorz=0}.bind(this),150),this.scrolled=!1),this.tick.call(window,this.onScroll.bind(this))},EPUBJS.Continuous.prototype.scrollBy=function(t,e,i){i&&(this.ignore=!0),this.settings.height?(t&&(this.container.scrollLeft+=t),e&&(this.container.scrollTop+=e)):window.scrollBy(t,e),this.scrolled=!0},EPUBJS.Continuous.prototype.scrollTo=function(t,e,i){i&&(this.ignore=!0),this.settings.height?(this.container.scrollLeft=t,this.container.scrollTop=e):window.scrollTo(t,e),this.scrolled=!0},EPUBJS.Continuous.prototype.resizeView=function(t){"horizontal"===this.settings.axis?t.lock("height",this.stage.width,this.stage.height):t.lock("width",this.stage.width,this.stage.height)},EPUBJS.Continuous.prototype.currentLocation=function(){{var t,e,i=this.visible();this.container.getBoundingClientRect()}return 1===i.length?this.map.page(i[0]):i.length>1?(t=this.map.page(i[0]),e=this.map.page(i[i.length-1]),{start:t.start,end:e.end}):void 0 +},EPUBJS.Paginate=function(t,e){EPUBJS.Continuous.apply(this,arguments),this.settings=EPUBJS.core.extend(this.settings||{},{width:600,height:400,axis:"horizontal",forceSingle:!1,minSpreadWidth:800,gap:"auto",overflow:"hidden",infinite:!1}),EPUBJS.core.extend(this.settings,e),this.isForcedSingle=this.settings.forceSingle,this.viewSettings={axis:this.settings.axis},this.start()},EPUBJS.Paginate.prototype=Object.create(EPUBJS.Continuous.prototype),EPUBJS.Paginate.prototype.constructor=EPUBJS.Paginate,EPUBJS.Paginate.prototype.determineSpreads=function(t){return this.isForcedSingle||!t||this.bounds().width1?(t=h.left-s[0].position().left,i=t+this.layout.column,e=h.left+this.layout.spread-s[s.length-1].position().left,n=e+this.layout.column,r=this.map.page(s[0],t,i),o=this.map.page(s[s.length-1],e,n),{start:r.start,end:o.end}):void 0},EPUBJS.Paginate.prototype.resize=function(t,e){this.q.clear(),this.stageSize(t,e),this.updateLayout(),this.display(this.location.start),this.trigger("resized",{width:this.stage.width,height:this.stage.height})},EPUBJS.Paginate.prototype.onResized=function(){this.clear(),clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(function(){this.resize()}.bind(this),150)},EPUBJS.Paginate.prototype.adjustImages=function(t){return t.addStylesheetRules([["img",["max-width",this.layout.spread+"px"],["max-height",this.layout.height+"px"]]]),new RSVP.Promise(function(t){setTimeout(function(){t()},1)})},EPUBJS.Map=function(t){this.layout=t},EPUBJS.Map.prototype.section=function(t){var e=this.findRanges(t),i=this.rangeListToCfiList(t,e);return i},EPUBJS.Map.prototype.page=function(t,e,i){var n=t.document.body;return this.rangePairToCfiPair(t.section,{start:this.findStart(n,e,i),end:this.findEnd(n,e,i)})},EPUBJS.Map.prototype.walk=function(t,e){for(var i,n,r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode:function(t){return t.data.trim().length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}},!1);(i=r.nextNode())&&!(n=e(i)););return n},EPUBJS.Map.prototype.findRanges=function(t){for(var e,i,n=[],r=this.layout.count(t),o=this.layout.column,s=this.layout.gap,h=0;h=e&&i>=n?t:r>e?t:(s=t,o.push(t),void 0)}))return this.findTextStartRange(r,e,i);return this.findTextStartRange(s,e,i)},EPUBJS.Map.prototype.findEnd=function(t,e,i){for(var n,r,o=[t],s=t;o.length;)if(n=o.shift(),r=this.walk(n,function(t){var e,n,r,h;return t.nodeType==Node.TEXT_NODE?(h=document.createRange(),h.selectNodeContents(t),r=h.getBoundingClientRect()):r=t.getBoundingClientRect(),e=r.left,n=r.right,e>i&&s?s:n>i?t:(s=t,o.push(t),void 0)}))return this.findTextEndRange(r,e,i);return this.findTextEndRange(s,e,i)},EPUBJS.Map.prototype.findTextStartRange=function(t,e){for(var i,n,r,o=this.splitTextNodeIntoRanges(t),s=0;s=e)return n;i=n}return o[0]},EPUBJS.Map.prototype.findTextEndRange=function(t,e,i){for(var n,r,o,s=this.splitTextNodeIntoRanges(t),h=0;hi&&n)return n;if(o.right>i)return r;n=r}return s[s.length-1]},EPUBJS.Map.prototype.splitTextNodeIntoRanges=function(t,e){var i,n=[],r=t.textContent||"",o=r.trim(),s=t.ownerDocument,h=e||" ";if(pos=o.indexOf(h),-1===pos||t.nodeType!=Node.TEXT_NODE)return i=s.createRange(),i.selectNodeContents(t),[i];for(i=s.createRange(),i.setStart(t,0),i.setEnd(t,pos),n.push(i),i=!1;-1!=pos;)pos=o.indexOf(h,pos+1),pos>0&&(i&&(i.setEnd(t,pos),n.push(i)),i=s.createRange(),i.setStart(t,pos+1));return i&&(i.setEnd(t,o.length),n.push(i)),n},EPUBJS.Map.prototype.rangePairToCfiPair=function(t,e){var i=e.start,n=e.end;return i.collapse(!0),n.collapse(!0),startCfi=t.cfiFromRange(i),endCfi=t.cfiFromRange(n),{start:startCfi,end:endCfi}},EPUBJS.Map.prototype.rangeListToCfiList=function(t,e){for(var i,n=[],r=0;r