<--------------- currentCursor.element
*
*
<--------------- currentCursor.candidate -> cursor.element
* <- currentCursor.candidate.firstChild -> cursor.candidate
* Foo
*
*
* <-- becomes currentCursor.candidate
*/
// where to rehydrate from if we are in rehydration mode
cursor.candidate = element.firstChild;
// where to continue when we pop
currentCursor.candidate = element.nextSibling;
}
}
this.cursorStack.push(cursor);
}
clearMismatch(candidate) {
let current = candidate;
let currentCursor = this.currentCursor;
if (currentCursor !== null) {
let openBlockDepth = currentCursor.openBlockDepth;
if (openBlockDepth >= currentCursor.startingBlockDepth) {
while (current && !(isComment(current) && getCloseBlockDepth(current) === openBlockDepth)) {
current = this.remove(current);
}
} else {
while (current !== null) {
current = this.remove(current);
}
}
// current cursor parentNode should be openCandidate if element
// or openCandidate.parentNode if comment
currentCursor.nextSibling = current;
// disable rehydration until we popElement or closeBlock for openBlockDepth
currentCursor.candidate = null;
}
}
__openBlock() {
let { currentCursor } = this;
if (currentCursor === null) return;
let blockDepth = this.blockDepth;
this.blockDepth++;
let { candidate } = currentCursor;
if (candidate === null) return;
if (isComment(candidate) && getOpenBlockDepth(candidate) === blockDepth) {
currentCursor.candidate = this.remove(candidate);
currentCursor.openBlockDepth = blockDepth;
} else {
this.clearMismatch(candidate);
}
}
__closeBlock() {
let { currentCursor } = this;
if (currentCursor === null) return;
// openBlock is the last rehydrated open block
let openBlockDepth = currentCursor.openBlockDepth;
// this currently is the expected next open block depth
this.blockDepth--;
let { candidate } = currentCursor;
// rehydrating
if (candidate !== null) {
if (isComment(candidate) && getCloseBlockDepth(candidate) === openBlockDepth) {
currentCursor.candidate = this.remove(candidate);
currentCursor.openBlockDepth--;
} else {
this.clearMismatch(candidate);
}
// if the openBlockDepth matches the blockDepth we just closed to
// then restore rehydration
}
if (currentCursor.openBlockDepth === this.blockDepth) {
currentCursor.candidate = this.remove(currentCursor.nextSibling);
currentCursor.openBlockDepth--;
}
}
__appendNode(node) {
let { candidate } = this;
// This code path is only used when inserting precisely one node. It needs more
// comparison logic, but we can probably lean on the cases where this code path
// is actually used.
if (candidate) {
return candidate;
} else {
return super.__appendNode(node);
}
}
__appendHTML(html) {
let candidateBounds = this.markerBounds();
if (candidateBounds) {
let first = candidateBounds.firstNode();
let last = candidateBounds.lastNode();
let newBounds = bounds(this.element, first.nextSibling, last.previousSibling);
let possibleEmptyMarker = this.remove(first);
this.remove(last);
if (possibleEmptyMarker !== null && isEmpty$1(possibleEmptyMarker)) {
this.candidate = this.remove(possibleEmptyMarker);
if (this.candidate !== null) {
this.clearMismatch(this.candidate);
}
}
return newBounds;
} else {
return super.__appendHTML(html);
}
}
remove(node) {
let element = node.parentNode;
let next = node.nextSibling;
element.removeChild(node);
return next;
}
markerBounds() {
let _candidate = this.candidate;
if (_candidate && isMarker(_candidate)) {
let first = _candidate;
let last = first.nextSibling;
while (last && !isMarker(last)) {
last = last.nextSibling;
}
return bounds(this.element, first, last);
} else {
return null;
}
}
__appendText(string) {
let { candidate } = this;
if (candidate) {
if (isTextNode(candidate)) {
if (candidate.nodeValue !== string) {
candidate.nodeValue = string;
}
this.candidate = candidate.nextSibling;
return candidate;
} else if (candidate && (isSeparator(candidate) || isEmpty$1(candidate))) {
this.candidate = candidate.nextSibling;
this.remove(candidate);
return this.__appendText(string);
} else if (isEmpty$1(candidate)) {
let next = this.remove(candidate);
this.candidate = next;
let text = this.dom.createTextNode(string);
this.dom.insertBefore(this.element, text, next);
return text;
} else {
this.clearMismatch(candidate);
return super.__appendText(string);
}
} else {
return super.__appendText(string);
}
}
__appendComment(string) {
let _candidate = this.candidate;
if (_candidate && isComment(_candidate)) {
if (_candidate.nodeValue !== string) {
_candidate.nodeValue = string;
}
this.candidate = _candidate.nextSibling;
return _candidate;
} else if (_candidate) {
this.clearMismatch(_candidate);
}
return super.__appendComment(string);
}
__openElement(tag) {
let _candidate = this.candidate;
if (_candidate && isElement(_candidate) && isSameNodeType(_candidate, tag)) {
this.unmatchedAttributes = [].slice.call(_candidate.attributes);
return _candidate;
} else if (_candidate) {
if (isElement(_candidate) && _candidate.tagName === 'TBODY') {
this.pushElement(_candidate, null);
this.currentCursor.injectedOmittedNode = true;
return this.__openElement(tag);
}
this.clearMismatch(_candidate);
}
return super.__openElement(tag);
}
__setAttribute(name, value, namespace) {
let unmatched = this.unmatchedAttributes;
if (unmatched) {
let attr = findByName(unmatched, name);
if (attr) {
if (attr.value !== value) {
attr.value = value;
}
unmatched.splice(unmatched.indexOf(attr), 1);
return;
}
}
return super.__setAttribute(name, value, namespace);
}
__setProperty(name, value) {
let unmatched = this.unmatchedAttributes;
if (unmatched) {
let attr = findByName(unmatched, name);
if (attr) {
if (attr.value !== value) {
attr.value = value;
}
unmatched.splice(unmatched.indexOf(attr), 1);
return;
}
}
return super.__setProperty(name, value);
}
__flushElement(parent, constructing) {
let { unmatchedAttributes: unmatched } = this;
if (unmatched) {
for (let i = 0; i < unmatched.length; i++) {
this.constructing.removeAttribute(unmatched[i].name);
}
this.unmatchedAttributes = null;
} else {
super.__flushElement(parent, constructing);
}
}
willCloseElement() {
let { candidate, currentCursor } = this;
if (candidate !== null) {
this.clearMismatch(candidate);
}
if (currentCursor && currentCursor.injectedOmittedNode) {
this.popElement();
}
super.willCloseElement();
}
getMarker(element, guid) {
let marker = element.querySelector(`script[glmr="${guid}"]`);
if (marker) {
return marker;
}
throw new Error('Cannot find serialized cursor for `in-element`');
}
__pushRemoteElement(element, cursorId, nextSibling = null) {
let marker = this.getMarker(element, cursorId);
if (marker.parentNode === element) {
let currentCursor = this.currentCursor;
let candidate = currentCursor.candidate;
this.pushElement(element, nextSibling);
currentCursor.candidate = candidate;
this.candidate = this.remove(marker);
let tracker = new RemoteBlockTracker(element);
this.pushBlockTracker(tracker, true);
}
}
didAppendBounds(bounds$$1) {
super.didAppendBounds(bounds$$1);
if (this.candidate) {
let last = bounds$$1.lastNode();
this.candidate = last && last.nextSibling;
}
return bounds$$1;
}
}
function isTextNode(node) {
return node.nodeType === 3;
}
function isComment(node) {
return node.nodeType === 8;
}
function getOpenBlockDepth(node) {
let boundsDepth = node.nodeValue.match(/^%\+b:(\d+)%$/);
if (boundsDepth && boundsDepth[1]) {
return Number(boundsDepth[1]);
} else {
return null;
}
}
function getCloseBlockDepth(node) {
let boundsDepth = node.nodeValue.match(/^%\-b:(\d+)%$/);
if (boundsDepth && boundsDepth[1]) {
return Number(boundsDepth[1]);
} else {
return null;
}
}
function isElement(node) {
return node.nodeType === 1;
}
function isMarker(node) {
return node.nodeType === 8 && node.nodeValue === '%glmr%';
}
function isSeparator(node) {
return node.nodeType === 8 && node.nodeValue === '%|%';
}
function isEmpty$1(node) {
return node.nodeType === 8 && node.nodeValue === '% %';
}
function isSameNodeType(candidate, tag) {
if (candidate.namespaceURI === SVG_NAMESPACE$1) {
return candidate.tagName === tag;
}
return candidate.tagName === tag.toUpperCase();
}
function findByName(array, name) {
for (let i = 0; i < array.length; i++) {
let attr = array[i];
if (attr.name === name) return attr;
}
return undefined;
}
function rehydrationBuilder(env, cursor) {
return RehydrateBuilder.forInitialRender(env, cursor);
}
exports.renderMain = render;
exports.NULL_REFERENCE = NULL_REFERENCE;
exports.UNDEFINED_REFERENCE = UNDEFINED_REFERENCE;
exports.PrimitiveReference = PrimitiveReference;
exports.ConditionalReference = ConditionalReference;
exports.setDebuggerCallback = setDebuggerCallback;
exports.resetDebuggerCallback = resetDebuggerCallback;
exports.getDynamicVar = getDynamicVar;
exports.LowLevelVM = VM;
exports.UpdatingVM = UpdatingVM;
exports.RenderResult = RenderResult;
exports.SimpleDynamicAttribute = SimpleDynamicAttribute;
exports.DynamicAttribute = DynamicAttribute;
exports.EMPTY_ARGS = EMPTY_ARGS;
exports.Scope = Scope;
exports.Environment = Environment;
exports.DefaultEnvironment = DefaultEnvironment;
exports.DEFAULT_CAPABILITIES = DEFAULT_CAPABILITIES;
exports.MINIMAL_CAPABILITIES = MINIMAL_CAPABILITIES;
exports.CurriedComponentDefinition = CurriedComponentDefinition;
exports.isCurriedComponentDefinition = isCurriedComponentDefinition;
exports.curry = curry;
exports.DOMChanges = helper$1;
exports.SVG_NAMESPACE = SVG_NAMESPACE$1;
exports.IDOMChanges = DOMChanges;
exports.DOMTreeConstruction = DOMTreeConstruction;
exports.isWhitespace = isWhitespace;
exports.insertHTMLBefore = insertHTMLBefore;
exports.normalizeProperty = normalizeProperty;
exports.NewElementBuilder = NewElementBuilder;
exports.clientBuilder = clientBuilder;
exports.rehydrationBuilder = rehydrationBuilder;
exports.RehydrateBuilder = RehydrateBuilder;
exports.ConcreteBounds = ConcreteBounds;
exports.Cursor = Cursor;
exports.capabilityFlagsFrom = capabilityFlagsFrom;
exports.hasCapability = hasCapability;
});
enifed('@glimmer/util', ['exports'], function (exports) {
'use strict';
function unwrap(val) {
if (val === null || val === undefined) throw new Error(`Expected value to be present`);
return val;
}
function expect(val, message) {
if (val === null || val === undefined) throw new Error(message);
return val;
}
function unreachable(message = 'unreachable') {
return new Error(message);
}
// import Logger from './logger';
// let alreadyWarned = false;
function debugAssert(test, msg) {
// if (!alreadyWarned) {
// alreadyWarned = true;
// Logger.warn("Don't leave debug assertions on in public builds");
// }
if (!test) {
throw new Error(msg || 'assertion failure');
}
}
const { keys: objKeys } = Object;
function assign(obj) {
for (let i = 1; i < arguments.length; i++) {
let assignment = arguments[i];
if (assignment === null || typeof assignment !== 'object') continue;
let keys = objKeys(assignment);
for (let j = 0; j < keys.length; j++) {
let key = keys[j];
obj[key] = assignment[key];
}
}
return obj;
}
function fillNulls(count) {
let arr = new Array(count);
for (let i = 0; i < count; i++) {
arr[i] = null;
}
return arr;
}
let GUID = 0;
function initializeGuid(object) {
return object._guid = ++GUID;
}
function ensureGuid(object) {
return object._guid || initializeGuid(object);
}
const SERIALIZATION_FIRST_NODE_STRING = '%+b:0%';
function isSerializationFirstNode(node) {
return node.nodeValue === SERIALIZATION_FIRST_NODE_STRING;
}
function dict() {
return Object.create(null);
}
class DictSet {
constructor() {
this.dict = dict();
}
add(obj) {
if (typeof obj === 'string') this.dict[obj] = obj;else this.dict[ensureGuid(obj)] = obj;
return this;
}
delete(obj) {
if (typeof obj === 'string') delete this.dict[obj];else if (obj._guid) delete this.dict[obj._guid];
}
}
class Stack {
constructor() {
this.stack = [];
this.current = null;
}
get size() {
return this.stack.length;
}
push(item) {
this.current = item;
this.stack.push(item);
}
pop() {
let item = this.stack.pop();
let len = this.stack.length;
this.current = len === 0 ? null : this.stack[len - 1];
return item === undefined ? null : item;
}
isEmpty() {
return this.stack.length === 0;
}
}
class ListNode {
constructor(value) {
this.next = null;
this.prev = null;
this.value = value;
}
}
class LinkedList {
constructor() {
this.clear();
}
head() {
return this._head;
}
tail() {
return this._tail;
}
clear() {
this._head = this._tail = null;
}
toArray() {
let out = [];
this.forEachNode(n => out.push(n));
return out;
}
nextNode(node) {
return node.next;
}
forEachNode(callback) {
let node = this._head;
while (node !== null) {
callback(node);
node = node.next;
}
}
insertBefore(node, reference = null) {
if (reference === null) return this.append(node);
if (reference.prev) reference.prev.next = node;else this._head = node;
node.prev = reference.prev;
node.next = reference;
reference.prev = node;
return node;
}
append(node) {
let tail = this._tail;
if (tail) {
tail.next = node;
node.prev = tail;
node.next = null;
} else {
this._head = node;
}
return this._tail = node;
}
remove(node) {
if (node.prev) node.prev.next = node.next;else this._head = node.next;
if (node.next) node.next.prev = node.prev;else this._tail = node.prev;
return node;
}
}
class ListSlice {
constructor(head, tail) {
this._head = head;
this._tail = tail;
}
forEachNode(callback) {
let node = this._head;
while (node !== null) {
callback(node);
node = this.nextNode(node);
}
}
head() {
return this._head;
}
tail() {
return this._tail;
}
toArray() {
let out = [];
this.forEachNode(n => out.push(n));
return out;
}
nextNode(node) {
if (node === this._tail) return null;
return node.next;
}
}
const EMPTY_SLICE = new ListSlice(null, null);
const EMPTY_ARRAY = Object.freeze([]);
exports.assert = debugAssert;
exports.assign = assign;
exports.fillNulls = fillNulls;
exports.ensureGuid = ensureGuid;
exports.initializeGuid = initializeGuid;
exports.isSerializationFirstNode = isSerializationFirstNode;
exports.SERIALIZATION_FIRST_NODE_STRING = SERIALIZATION_FIRST_NODE_STRING;
exports.Stack = Stack;
exports.DictSet = DictSet;
exports.dict = dict;
exports.EMPTY_SLICE = EMPTY_SLICE;
exports.LinkedList = LinkedList;
exports.ListNode = ListNode;
exports.ListSlice = ListSlice;
exports.EMPTY_ARRAY = EMPTY_ARRAY;
exports.unwrap = unwrap;
exports.expect = expect;
exports.unreachable = unreachable;
});
enifed("@glimmer/vm", ["exports"], function (exports) {
"use strict";
/**
* Registers
*
* For the most part, these follows MIPS naming conventions, however the
* register numbers are different.
*/
var Register;
(function (Register) {
// $0 or $pc (program counter): pointer into `program` for the next insturction; -1 means exit
Register[Register["pc"] = 0] = "pc";
// $1 or $ra (return address): pointer into `program` for the return
Register[Register["ra"] = 1] = "ra";
// $2 or $fp (frame pointer): pointer into the `evalStack` for the base of the stack
Register[Register["fp"] = 2] = "fp";
// $3 or $sp (stack pointer): pointer into the `evalStack` for the top of the stack
Register[Register["sp"] = 3] = "sp";
// $4-$5 or $s0-$s1 (saved): callee saved general-purpose registers
Register[Register["s0"] = 4] = "s0";
Register[Register["s1"] = 5] = "s1";
// $6-$7 or $t0-$t1 (temporaries): caller saved general-purpose registers
Register[Register["t0"] = 6] = "t0";
Register[Register["t1"] = 7] = "t1";
// $8 or $v0 (return value)
Register[Register["v0"] = 8] = "v0";
})(Register || (exports.Register = Register = {}));
exports.Register = Register;
});
enifed("@glimmer/wire-format", ["exports"], function (exports) {
"use strict";
var Opcodes;
(function (Opcodes) {
// Statements
Opcodes[Opcodes["Text"] = 0] = "Text";
Opcodes[Opcodes["Append"] = 1] = "Append";
Opcodes[Opcodes["Comment"] = 2] = "Comment";
Opcodes[Opcodes["Modifier"] = 3] = "Modifier";
Opcodes[Opcodes["Block"] = 4] = "Block";
Opcodes[Opcodes["Component"] = 5] = "Component";
Opcodes[Opcodes["DynamicComponent"] = 6] = "DynamicComponent";
Opcodes[Opcodes["OpenElement"] = 7] = "OpenElement";
Opcodes[Opcodes["OpenSplattedElement"] = 8] = "OpenSplattedElement";
Opcodes[Opcodes["FlushElement"] = 9] = "FlushElement";
Opcodes[Opcodes["CloseElement"] = 10] = "CloseElement";
Opcodes[Opcodes["StaticAttr"] = 11] = "StaticAttr";
Opcodes[Opcodes["DynamicAttr"] = 12] = "DynamicAttr";
Opcodes[Opcodes["AttrSplat"] = 13] = "AttrSplat";
Opcodes[Opcodes["Yield"] = 14] = "Yield";
Opcodes[Opcodes["Partial"] = 15] = "Partial";
Opcodes[Opcodes["DynamicArg"] = 16] = "DynamicArg";
Opcodes[Opcodes["StaticArg"] = 17] = "StaticArg";
Opcodes[Opcodes["TrustingAttr"] = 18] = "TrustingAttr";
Opcodes[Opcodes["Debugger"] = 19] = "Debugger";
Opcodes[Opcodes["ClientSideStatement"] = 20] = "ClientSideStatement";
// Expressions
Opcodes[Opcodes["Unknown"] = 21] = "Unknown";
Opcodes[Opcodes["Get"] = 22] = "Get";
Opcodes[Opcodes["MaybeLocal"] = 23] = "MaybeLocal";
Opcodes[Opcodes["HasBlock"] = 24] = "HasBlock";
Opcodes[Opcodes["HasBlockParams"] = 25] = "HasBlockParams";
Opcodes[Opcodes["Undefined"] = 26] = "Undefined";
Opcodes[Opcodes["Helper"] = 27] = "Helper";
Opcodes[Opcodes["Concat"] = 28] = "Concat";
Opcodes[Opcodes["ClientSideExpression"] = 29] = "ClientSideExpression";
})(Opcodes || (exports.Ops = Opcodes = {}));
function is(variant) {
return function (value) {
return Array.isArray(value) && value[0] === variant;
};
}
// Statements
const isFlushElement = is(Opcodes.FlushElement);
const isAttrSplat = is(Opcodes.AttrSplat);
function isAttribute(val) {
return val[0] === Opcodes.StaticAttr || val[0] === Opcodes.DynamicAttr || val[0] === Opcodes.TrustingAttr;
}
function isArgument(val) {
return val[0] === Opcodes.StaticArg || val[0] === Opcodes.DynamicArg;
}
// Expressions
const isGet = is(Opcodes.Get);
const isMaybeLocal = is(Opcodes.MaybeLocal);
exports.is = is;
exports.isFlushElement = isFlushElement;
exports.isAttrSplat = isAttrSplat;
exports.isAttribute = isAttribute;
exports.isArgument = isArgument;
exports.isGet = isGet;
exports.isMaybeLocal = isMaybeLocal;
exports.Ops = Opcodes;
});
enifed('backburner', ['exports'], function (exports) {
'use strict';
const SET_TIMEOUT = setTimeout;
const NOOP = () => {};
function buildPlatform(flush) {
let next;
let clearNext = NOOP;
if (typeof MutationObserver === 'function') {
let iterations = 0;
let observer = new MutationObserver(flush);
let node = document.createTextNode('');
observer.observe(node, { characterData: true });
next = () => {
iterations = ++iterations % 2;
node.data = '' + iterations;
return iterations;
};
} else if (typeof Promise === 'function') {
const autorunPromise = Promise.resolve();
next = () => autorunPromise.then(flush);
} else {
next = () => SET_TIMEOUT(flush, 0);
}
return {
setTimeout(fn, ms) {
return setTimeout(fn, ms);
},
clearTimeout(timerId) {
return clearTimeout(timerId);
},
now() {
return Date.now();
},
next,
clearNext
};
}
const NUMBER = /\d+/;
const TIMERS_OFFSET = 6;
function isCoercableNumber(suspect) {
let type = typeof suspect;
return type === 'number' && suspect === suspect || type === 'string' && NUMBER.test(suspect);
}
function getOnError(options) {
return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod];
}
function findItem(target, method, collection) {
let index = -1;
for (let i = 0, l = collection.length; i < l; i += 4) {
if (collection[i] === target && collection[i + 1] === method) {
index = i;
break;
}
}
return index;
}
function findTimerItem(target, method, collection) {
let index = -1;
for (let i = 2, l = collection.length; i < l; i += 6) {
if (collection[i] === target && collection[i + 1] === method) {
index = i - 2;
break;
}
}
return index;
}
function getQueueItems(items, queueItemLength, queueItemPositionOffset = 0) {
let queueItems = [];
for (let i = 0; i < items.length; i += queueItemLength) {
let maybeError = items[i + 3 /* stack */ + queueItemPositionOffset];
let queueItem = {
target: items[i + 0 /* target */ + queueItemPositionOffset],
method: items[i + 1 /* method */ + queueItemPositionOffset],
args: items[i + 2 /* args */ + queueItemPositionOffset],
stack: maybeError !== undefined && 'stack' in maybeError ? maybeError.stack : ''
};
queueItems.push(queueItem);
}
return queueItems;
}
function binarySearch(time, timers) {
let start = 0;
let end = timers.length - TIMERS_OFFSET;
let middle;
let l;
while (start < end) {
// since timers is an array of pairs 'l' will always
// be an integer
l = (end - start) / TIMERS_OFFSET;
// compensate for the index in case even number
// of pairs inside timers
middle = start + l - l % TIMERS_OFFSET;
if (time >= timers[middle]) {
start = middle + TIMERS_OFFSET;
} else {
end = middle;
}
}
return time >= timers[start] ? start + TIMERS_OFFSET : start;
}
const QUEUE_ITEM_LENGTH = 4;
class Queue {
constructor(name, options = {}, globalOptions = {}) {
this._queueBeingFlushed = [];
this.targetQueues = new Map();
this.index = 0;
this._queue = [];
this.name = name;
this.options = options;
this.globalOptions = globalOptions;
}
stackFor(index) {
if (index < this._queue.length) {
let entry = this._queue[index * 3 + QUEUE_ITEM_LENGTH];
if (entry) {
return entry.stack;
} else {
return null;
}
}
}
flush(sync) {
let { before, after } = this.options;
let target;
let method;
let args;
let errorRecordedForStack;
this.targetQueues.clear();
if (this._queueBeingFlushed.length === 0) {
this._queueBeingFlushed = this._queue;
this._queue = [];
}
if (before !== undefined) {
before();
}
let invoke;
let queueItems = this._queueBeingFlushed;
if (queueItems.length > 0) {
let onError = getOnError(this.globalOptions);
invoke = onError ? this.invokeWithOnError : this.invoke;
for (let i = this.index; i < queueItems.length; i += QUEUE_ITEM_LENGTH) {
this.index += QUEUE_ITEM_LENGTH;
method = queueItems[i + 1];
// method could have been nullified / canceled during flush
if (method !== null) {
//
// ** Attention intrepid developer **
//
// To find out the stack of this task when it was scheduled onto
// the run loop, add the following to your app.js:
//
// Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production.
//
// Once that is in place, when you are at a breakpoint and navigate
// here in the stack explorer, you can look at `errorRecordedForStack.stack`,
// which will be the captured stack when this job was scheduled.
//
// One possible long-term solution is the following Chrome issue:
// https://bugs.chromium.org/p/chromium/issues/detail?id=332624
//
target = queueItems[i];
args = queueItems[i + 2];
errorRecordedForStack = queueItems[i + 3]; // Debugging assistance
invoke(target, method, args, onError, errorRecordedForStack);
}
if (this.index !== this._queueBeingFlushed.length && this.globalOptions.mustYield && this.globalOptions.mustYield()) {
return 1 /* Pause */;
}
}
}
if (after !== undefined) {
after();
}
this._queueBeingFlushed.length = 0;
this.index = 0;
if (sync !== false && this._queue.length > 0) {
// check if new items have been added
this.flush(true);
}
}
hasWork() {
return this._queueBeingFlushed.length > 0 || this._queue.length > 0;
}
cancel({ target, method }) {
let queue = this._queue;
let targetQueueMap = this.targetQueues.get(target);
if (targetQueueMap !== undefined) {
targetQueueMap.delete(method);
}
let index = findItem(target, method, queue);
if (index > -1) {
queue.splice(index, QUEUE_ITEM_LENGTH);
return true;
}
// if not found in current queue
// could be in the queue that is being flushed
queue = this._queueBeingFlushed;
index = findItem(target, method, queue);
if (index > -1) {
queue[index + 1] = null;
return true;
}
return false;
}
push(target, method, args, stack) {
this._queue.push(target, method, args, stack);
return {
queue: this,
target,
method
};
}
pushUnique(target, method, args, stack) {
let localQueueMap = this.targetQueues.get(target);
if (localQueueMap === undefined) {
localQueueMap = new Map();
this.targetQueues.set(target, localQueueMap);
}
let index = localQueueMap.get(method);
if (index === undefined) {
let queueIndex = this._queue.push(target, method, args, stack) - QUEUE_ITEM_LENGTH;
localQueueMap.set(method, queueIndex);
} else {
let queue = this._queue;
queue[index + 2] = args; // replace args
queue[index + 3] = stack; // replace stack
}
return {
queue: this,
target,
method
};
}
_getDebugInfo(debugEnabled) {
if (debugEnabled) {
let debugInfo = getQueueItems(this._queue, QUEUE_ITEM_LENGTH);
return debugInfo;
}
return undefined;
}
invoke(target, method, args /*, onError, errorRecordedForStack */) {
if (args === undefined) {
method.call(target);
} else {
method.apply(target, args);
}
}
invokeWithOnError(target, method, args, onError, errorRecordedForStack) {
try {
if (args === undefined) {
method.call(target);
} else {
method.apply(target, args);
}
} catch (error) {
onError(error, errorRecordedForStack);
}
}
}
class DeferredActionQueues {
constructor(queueNames = [], options) {
this.queues = {};
this.queueNameIndex = 0;
this.queueNames = queueNames;
queueNames.reduce(function (queues, queueName) {
queues[queueName] = new Queue(queueName, options[queueName], options);
return queues;
}, this.queues);
}
/**
* @method schedule
* @param {String} queueName
* @param {Any} target
* @param {Any} method
* @param {Any} args
* @param {Boolean} onceFlag
* @param {Any} stack
* @return queue
*/
schedule(queueName, target, method, args, onceFlag, stack) {
let queues = this.queues;
let queue = queues[queueName];
if (queue === undefined) {
throw new Error(`You attempted to schedule an action in a queue (${queueName}) that doesn\'t exist`);
}
if (method === undefined || method === null) {
throw new Error(`You attempted to schedule an action in a queue (${queueName}) for a method that doesn\'t exist`);
}
this.queueNameIndex = 0;
if (onceFlag) {
return queue.pushUnique(target, method, args, stack);
} else {
return queue.push(target, method, args, stack);
}
}
/**
* DeferredActionQueues.flush() calls Queue.flush()
*
* @method flush
* @param {Boolean} fromAutorun
*/
flush(fromAutorun = false) {
let queue;
let queueName;
let numberOfQueues = this.queueNames.length;
while (this.queueNameIndex < numberOfQueues) {
queueName = this.queueNames[this.queueNameIndex];
queue = this.queues[queueName];
if (queue.hasWork() === false) {
this.queueNameIndex++;
if (fromAutorun && this.queueNameIndex < numberOfQueues) {
return 1 /* Pause */;
}
} else {
if (queue.flush(false /* async */) === 1 /* Pause */) {
return 1 /* Pause */;
}
}
}
}
/**
* Returns debug information for the current queues.
*
* @method _getDebugInfo
* @param {Boolean} debugEnabled
* @returns {IDebugInfo | undefined}
*/
_getDebugInfo(debugEnabled) {
if (debugEnabled) {
let debugInfo = {};
let queue;
let queueName;
let numberOfQueues = this.queueNames.length;
let i = 0;
while (i < numberOfQueues) {
queueName = this.queueNames[i];
queue = this.queues[queueName];
debugInfo[queueName] = queue._getDebugInfo(debugEnabled);
i++;
}
return debugInfo;
}
return;
}
}
function iteratorDrain(fn) {
let iterator = fn();
let result = iterator.next();
while (result.done === false) {
result.value();
result = iterator.next();
}
}
const noop = function () {};
const DISABLE_SCHEDULE = Object.freeze([]);
function parseArgs() {
let length = arguments.length;
let args;
let method;
let target;
if (length === 0) {} else if (length === 1) {
target = null;
method = arguments[0];
} else {
let argsIndex = 2;
let methodOrTarget = arguments[0];
let methodOrArgs = arguments[1];
let type = typeof methodOrArgs;
if (type === 'function') {
target = methodOrTarget;
method = methodOrArgs;
} else if (methodOrTarget !== null && type === 'string' && methodOrArgs in methodOrTarget) {
target = methodOrTarget;
method = target[methodOrArgs];
} else if (typeof methodOrTarget === 'function') {
argsIndex = 1;
target = null;
method = methodOrTarget;
}
if (length > argsIndex) {
let len = length - argsIndex;
args = new Array(len);
for (let i = 0; i < len; i++) {
args[i] = arguments[i + argsIndex];
}
}
}
return [target, method, args];
}
function parseTimerArgs() {
let [target, method, args] = parseArgs(...arguments);
let wait = 0;
let length = args !== undefined ? args.length : 0;
if (length > 0) {
let last = args[length - 1];
if (isCoercableNumber(last)) {
wait = parseInt(args.pop(), 10);
}
}
return [target, method, args, wait];
}
function parseDebounceArgs() {
let target;
let method;
let isImmediate;
let args;
let wait;
if (arguments.length === 2) {
method = arguments[0];
wait = arguments[1];
target = null;
} else {
[target, method, args] = parseArgs(...arguments);
if (args === undefined) {
wait = 0;
} else {
wait = args.pop();
if (!isCoercableNumber(wait)) {
isImmediate = wait === true;
wait = args.pop();
}
}
}
wait = parseInt(wait, 10);
return [target, method, args, wait, isImmediate];
}
let UUID = 0;
let beginCount = 0;
let endCount = 0;
let beginEventCount = 0;
let endEventCount = 0;
let runCount = 0;
let joinCount = 0;
let deferCount = 0;
let scheduleCount = 0;
let scheduleIterableCount = 0;
let deferOnceCount = 0;
let scheduleOnceCount = 0;
let setTimeoutCount = 0;
let laterCount = 0;
let throttleCount = 0;
let debounceCount = 0;
let cancelTimersCount = 0;
let cancelCount = 0;
let autorunsCreatedCount = 0;
let autorunsCompletedCount = 0;
let deferredActionQueuesCreatedCount = 0;
let nestedDeferredActionQueuesCreated = 0;
class Backburner {
constructor(queueNames, options) {
this.DEBUG = false;
this.currentInstance = null;
this.instanceStack = [];
this._eventCallbacks = {
end: [],
begin: []
};
this._timerTimeoutId = null;
this._timers = [];
this._autorun = null;
this._autorunStack = null;
this.queueNames = queueNames;
this.options = options || {};
if (typeof this.options.defaultQueue === 'string') {
this._defaultQueue = this.options.defaultQueue;
} else {
this._defaultQueue = this.queueNames[0];
}
this._onBegin = this.options.onBegin || noop;
this._onEnd = this.options.onEnd || noop;
this._boundRunExpiredTimers = this._runExpiredTimers.bind(this);
this._boundAutorunEnd = () => {
autorunsCompletedCount++;
// if the autorun was already flushed, do nothing
if (this._autorun === null) {
return;
}
this._autorun = null;
this._autorunStack = null;
this._end(true /* fromAutorun */);
};
let builder = this.options._buildPlatform || buildPlatform;
this._platform = builder(this._boundAutorunEnd);
}
get counters() {
return {
begin: beginCount,
end: endCount,
events: {
begin: beginEventCount,
end: endEventCount
},
autoruns: {
created: autorunsCreatedCount,
completed: autorunsCompletedCount
},
run: runCount,
join: joinCount,
defer: deferCount,
schedule: scheduleCount,
scheduleIterable: scheduleIterableCount,
deferOnce: deferOnceCount,
scheduleOnce: scheduleOnceCount,
setTimeout: setTimeoutCount,
later: laterCount,
throttle: throttleCount,
debounce: debounceCount,
cancelTimers: cancelTimersCount,
cancel: cancelCount,
loops: {
total: deferredActionQueuesCreatedCount,
nested: nestedDeferredActionQueuesCreated
}
};
}
get defaultQueue() {
return this._defaultQueue;
}
/*
@method begin
@return instantiated class DeferredActionQueues
*/
begin() {
beginCount++;
let options = this.options;
let previousInstance = this.currentInstance;
let current;
if (this._autorun !== null) {
current = previousInstance;
this._cancelAutorun();
} else {
if (previousInstance !== null) {
nestedDeferredActionQueuesCreated++;
this.instanceStack.push(previousInstance);
}
deferredActionQueuesCreatedCount++;
current = this.currentInstance = new DeferredActionQueues(this.queueNames, options);
beginEventCount++;
this._trigger('begin', current, previousInstance);
}
this._onBegin(current, previousInstance);
return current;
}
end() {
endCount++;
this._end(false);
}
on(eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError(`Callback must be a function`);
}
let callbacks = this._eventCallbacks[eventName];
if (callbacks !== undefined) {
callbacks.push(callback);
} else {
throw new TypeError(`Cannot on() event ${eventName} because it does not exist`);
}
}
off(eventName, callback) {
let callbacks = this._eventCallbacks[eventName];
if (!eventName || callbacks === undefined) {
throw new TypeError(`Cannot off() event ${eventName} because it does not exist`);
}
let callbackFound = false;
if (callback) {
for (let i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
callbackFound = true;
callbacks.splice(i, 1);
i--;
}
}
}
if (!callbackFound) {
throw new TypeError(`Cannot off() callback that does not exist`);
}
}
run() {
runCount++;
let [target, method, args] = parseArgs(...arguments);
return this._run(target, method, args);
}
join() {
joinCount++;
let [target, method, args] = parseArgs(...arguments);
return this._join(target, method, args);
}
/**
* @deprecated please use schedule instead.
*/
defer(queueName, target, method, ...args) {
deferCount++;
return this.schedule(queueName, target, method, ...args);
}
schedule(queueName, ..._args) {
scheduleCount++;
let [target, method, args] = parseArgs(..._args);
let stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, target, method, args, false, stack);
}
/*
Defer the passed iterable of functions to run inside the specified queue.
@method scheduleIterable
@param {String} queueName
@param {Iterable} an iterable of functions to execute
@return method result
*/
scheduleIterable(queueName, iterable) {
scheduleIterableCount++;
let stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, null, iteratorDrain, [iterable], false, stack);
}
/**
* @deprecated please use scheduleOnce instead.
*/
deferOnce(queueName, target, method, ...args) {
deferOnceCount++;
return this.scheduleOnce(queueName, target, method, ...args);
}
scheduleOnce(queueName, ..._args) {
scheduleOnceCount++;
let [target, method, args] = parseArgs(..._args);
let stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, target, method, args, true, stack);
}
setTimeout() {
setTimeoutCount++;
return this.later(...arguments);
}
later() {
laterCount++;
let [target, method, args, wait] = parseTimerArgs(...arguments);
return this._later(target, method, args, wait);
}
throttle() {
throttleCount++;
let [target, method, args, wait, isImmediate = true] = parseDebounceArgs(...arguments);
let index = findTimerItem(target, method, this._timers);
let timerId;
if (index === -1) {
timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait);
if (isImmediate) {
this._join(target, method, args);
}
} else {
timerId = this._timers[index + 1];
let argIndex = index + 4;
if (this._timers[argIndex] !== DISABLE_SCHEDULE) {
this._timers[argIndex] = args;
}
}
return timerId;
}
debounce() {
debounceCount++;
let [target, method, args, wait, isImmediate = false] = parseDebounceArgs(...arguments);
let _timers = this._timers;
let index = findTimerItem(target, method, _timers);
let timerId;
if (index === -1) {
timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait);
if (isImmediate) {
this._join(target, method, args);
}
} else {
let executeAt = this._platform.now() + wait;
let argIndex = index + 4;
if (_timers[argIndex] === DISABLE_SCHEDULE) {
args = DISABLE_SCHEDULE;
}
timerId = _timers[index + 1];
let i = binarySearch(executeAt, _timers);
if (index + TIMERS_OFFSET === i) {
_timers[index] = executeAt;
_timers[argIndex] = args;
} else {
let stack = this._timers[index + 5];
this._timers.splice(i, 0, executeAt, timerId, target, method, args, stack);
this._timers.splice(index, TIMERS_OFFSET);
}
if (index === 0) {
this._reinstallTimerTimeout();
}
}
return timerId;
}
cancelTimers() {
cancelTimersCount++;
this._clearTimerTimeout();
this._timers = [];
this._cancelAutorun();
}
hasTimers() {
return this._timers.length > 0 || this._autorun !== null;
}
cancel(timer) {
cancelCount++;
if (timer === null || timer === undefined) {
return false;
}
let timerType = typeof timer;
if (timerType === 'number') {
// we're cancelling a setTimeout or throttle or debounce
return this._cancelLaterTimer(timer);
} else if (timerType === 'object' && timer.queue && timer.method) {
// we're cancelling a deferOnce
return timer.queue.cancel(timer);
}
return false;
}
ensureInstance() {
this._ensureInstance();
}
/**
* Returns debug information related to the current instance of Backburner
*
* @method getDebugInfo
* @returns {Object | undefined} Will return and Object containing debug information if
* the DEBUG flag is set to true on the current instance of Backburner, else undefined.
*/
getDebugInfo() {
if (this.DEBUG) {
return {
autorun: this._autorunStack,
counters: this.counters,
timers: getQueueItems(this._timers, TIMERS_OFFSET, 2),
instanceStack: [this.currentInstance, ...this.instanceStack].map(deferredActionQueue => deferredActionQueue && deferredActionQueue._getDebugInfo(this.DEBUG))
};
}
return undefined;
}
_end(fromAutorun) {
let currentInstance = this.currentInstance;
let nextInstance = null;
if (currentInstance === null) {
throw new Error(`end called without begin`);
}
// Prevent double-finally bug in Safari 6.0.2 and iOS 6
// This bug appears to be resolved in Safari 6.0.5 and iOS 7
let finallyAlreadyCalled = false;
let result;
try {
result = currentInstance.flush(fromAutorun);
} finally {
if (!finallyAlreadyCalled) {
finallyAlreadyCalled = true;
if (result === 1 /* Pause */) {
this._scheduleAutorun();
} else {
this.currentInstance = null;
if (this.instanceStack.length > 0) {
nextInstance = this.instanceStack.pop();
this.currentInstance = nextInstance;
}
this._trigger('end', currentInstance, nextInstance);
this._onEnd(currentInstance, nextInstance);
}
}
}
}
_join(target, method, args) {
if (this.currentInstance === null) {
return this._run(target, method, args);
}
if (target === undefined && args === undefined) {
return method();
} else {
return method.apply(target, args);
}
}
_run(target, method, args) {
let onError = getOnError(this.options);
this.begin();
if (onError) {
try {
return method.apply(target, args);
} catch (error) {
onError(error);
} finally {
this.end();
}
} else {
try {
return method.apply(target, args);
} finally {
this.end();
}
}
}
_cancelAutorun() {
if (this._autorun !== null) {
this._platform.clearNext(this._autorun);
this._autorun = null;
this._autorunStack = null;
}
}
_later(target, method, args, wait) {
let stack = this.DEBUG ? new Error() : undefined;
let executeAt = this._platform.now() + wait;
let id = UUID++;
if (this._timers.length === 0) {
this._timers.push(executeAt, id, target, method, args, stack);
this._installTimerTimeout();
} else {
// find position to insert
let i = binarySearch(executeAt, this._timers);
this._timers.splice(i, 0, executeAt, id, target, method, args, stack);
// always reinstall since it could be out of sync
this._reinstallTimerTimeout();
}
return id;
}
_cancelLaterTimer(timer) {
for (let i = 1; i < this._timers.length; i += TIMERS_OFFSET) {
if (this._timers[i] === timer) {
this._timers.splice(i - 1, TIMERS_OFFSET);
if (i === 1) {
this._reinstallTimerTimeout();
}
return true;
}
}
return false;
}
/**
Trigger an event. Supports up to two arguments. Designed around
triggering transition events from one run loop instance to the
next, which requires an argument for the instance and then
an argument for the next instance.
@private
@method _trigger
@param {String} eventName
@param {any} arg1
@param {any} arg2
*/
_trigger(eventName, arg1, arg2) {
let callbacks = this._eventCallbacks[eventName];
if (callbacks !== undefined) {
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](arg1, arg2);
}
}
}
_runExpiredTimers() {
this._timerTimeoutId = null;
if (this._timers.length > 0) {
this.begin();
this._scheduleExpiredTimers();
this.end();
}
}
_scheduleExpiredTimers() {
let timers = this._timers;
let i = 0;
let l = timers.length;
let defaultQueue = this._defaultQueue;
let n = this._platform.now();
for (; i < l; i += TIMERS_OFFSET) {
let executeAt = timers[i];
if (executeAt > n) {
break;
}
let args = timers[i + 4];
if (args !== DISABLE_SCHEDULE) {
let target = timers[i + 2];
let method = timers[i + 3];
let stack = timers[i + 5];
this.currentInstance.schedule(defaultQueue, target, method, args, false, stack);
}
}
timers.splice(0, i);
this._installTimerTimeout();
}
_reinstallTimerTimeout() {
this._clearTimerTimeout();
this._installTimerTimeout();
}
_clearTimerTimeout() {
if (this._timerTimeoutId === null) {
return;
}
this._platform.clearTimeout(this._timerTimeoutId);
this._timerTimeoutId = null;
}
_installTimerTimeout() {
if (this._timers.length === 0) {
return;
}
let minExpiresAt = this._timers[0];
let n = this._platform.now();
let wait = Math.max(0, minExpiresAt - n);
this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait);
}
_ensureInstance() {
let currentInstance = this.currentInstance;
if (currentInstance === null) {
this._autorunStack = this.DEBUG ? new Error() : undefined;
currentInstance = this.begin();
this._scheduleAutorun();
}
return currentInstance;
}
_scheduleAutorun() {
autorunsCreatedCount++;
const next = this._platform.next;
this._autorun = next();
}
}
Backburner.Queue = Queue;
exports.default = Backburner;
exports.buildPlatform = buildPlatform;
});
enifed("dag-map", ["exports"], function (exports) {
"use strict";
/**
* A topologically ordered map of key/value pairs with a simple API for adding constraints.
*
* Edges can forward reference keys that have not been added yet (the forward reference will
* map the key to undefined).
*/
var DAG = function () {
function DAG() {
this._vertices = new Vertices();
}
/**
* Adds a key/value pair with dependencies on other key/value pairs.
*
* @public
* @param key The key of the vertex to be added.
* @param value The value of that vertex.
* @param before A key or array of keys of the vertices that must
* be visited before this vertex.
* @param after An string or array of strings with the keys of the
* vertices that must be after this vertex is visited.
*/
DAG.prototype.add = function (key, value, before, after) {
if (!key) throw new Error('argument `key` is required');
var vertices = this._vertices;
var v = vertices.add(key);
v.val = value;
if (before) {
if (typeof before === "string") {
vertices.addEdge(v, vertices.add(before));
} else {
for (var i = 0; i < before.length; i++) {
vertices.addEdge(v, vertices.add(before[i]));
}
}
}
if (after) {
if (typeof after === "string") {
vertices.addEdge(vertices.add(after), v);
} else {
for (var i = 0; i < after.length; i++) {
vertices.addEdge(vertices.add(after[i]), v);
}
}
}
};
/**
* @deprecated please use add.
*/
DAG.prototype.addEdges = function (key, value, before, after) {
this.add(key, value, before, after);
};
/**
* Visits key/value pairs in topological order.
*
* @public
* @param callback The function to be invoked with each key/value.
*/
DAG.prototype.each = function (callback) {
this._vertices.walk(callback);
};
/**
* @deprecated please use each.
*/
DAG.prototype.topsort = function (callback) {
this.each(callback);
};
return DAG;
}();
exports.default = DAG;
/** @private */
var Vertices = function () {
function Vertices() {
this.length = 0;
this.stack = new IntStack();
this.path = new IntStack();
this.result = new IntStack();
}
Vertices.prototype.add = function (key) {
if (!key) throw new Error("missing key");
var l = this.length | 0;
var vertex;
for (var i = 0; i < l; i++) {
vertex = this[i];
if (vertex.key === key) return vertex;
}
this.length = l + 1;
return this[l] = {
idx: l,
key: key,
val: undefined,
out: false,
flag: false,
length: 0
};
};
Vertices.prototype.addEdge = function (v, w) {
this.check(v, w.key);
var l = w.length | 0;
for (var i = 0; i < l; i++) {
if (w[i] === v.idx) return;
}
w.length = l + 1;
w[l] = v.idx;
v.out = true;
};
Vertices.prototype.walk = function (cb) {
this.reset();
for (var i = 0; i < this.length; i++) {
var vertex = this[i];
if (vertex.out) continue;
this.visit(vertex, "");
}
this.each(this.result, cb);
};
Vertices.prototype.check = function (v, w) {
if (v.key === w) {
throw new Error("cycle detected: " + w + " <- " + w);
}
// quick check
if (v.length === 0) return;
// shallow check
for (var i = 0; i < v.length; i++) {
var key = this[v[i]].key;
if (key === w) {
throw new Error("cycle detected: " + w + " <- " + v.key + " <- " + w);
}
}
// deep check
this.reset();
this.visit(v, w);
if (this.path.length > 0) {
var msg_1 = "cycle detected: " + w;
this.each(this.path, function (key) {
msg_1 += " <- " + key;
});
throw new Error(msg_1);
}
};
Vertices.prototype.reset = function () {
this.stack.length = 0;
this.path.length = 0;
this.result.length = 0;
for (var i = 0, l = this.length; i < l; i++) {
this[i].flag = false;
}
};
Vertices.prototype.visit = function (start, search) {
var _a = this,
stack = _a.stack,
path = _a.path,
result = _a.result;
stack.push(start.idx);
while (stack.length) {
var index = stack.pop() | 0;
if (index >= 0) {
// enter
var vertex = this[index];
if (vertex.flag) continue;
vertex.flag = true;
path.push(index);
if (search === vertex.key) break;
// push exit
stack.push(~index);
this.pushIncoming(vertex);
} else {
// exit
path.pop();
result.push(~index);
}
}
};
Vertices.prototype.pushIncoming = function (incomming) {
var stack = this.stack;
for (var i = incomming.length - 1; i >= 0; i--) {
var index = incomming[i];
if (!this[index].flag) {
stack.push(index);
}
}
};
Vertices.prototype.each = function (indices, cb) {
for (var i = 0, l = indices.length; i < l; i++) {
var vertex = this[indices[i]];
cb(vertex.key, vertex.val);
}
};
return Vertices;
}();
/** @private */
var IntStack = function () {
function IntStack() {
this.length = 0;
}
IntStack.prototype.push = function (n) {
this[this.length++] = n | 0;
};
IntStack.prototype.pop = function () {
return this[--this.length] | 0;
};
return IntStack;
}();
});
enifed('ember-babel', ['exports'], function (exports) {
'use strict';
exports.classCallCheck = classCallCheck;
exports.inherits = inherits;
exports.taggedTemplateLiteralLoose = taggedTemplateLiteralLoose;
exports.createClass = createClass;
const create = Object.create;
const setPrototypeOf = Object.setPrototypeOf;
const defineProperty = Object.defineProperty;
function classCallCheck(instance, Constructor) {
if (false /* DEBUG */) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
}
}
function inherits(subClass, superClass) {
if (false /* DEBUG */) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);
}
}
subClass.prototype = create(superClass === null ? null : superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass !== null) setPrototypeOf(subClass, superClass);
}
function taggedTemplateLiteralLoose(strings, raw) {
strings.raw = raw;
return strings;
}
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor) descriptor.writable = true;
defineProperty(target, descriptor.key, descriptor);
}
}
function createClass(Constructor, protoProps, staticProps) {
if (protoProps !== undefined) defineProperties(Constructor.prototype, protoProps);
if (staticProps !== undefined) defineProperties(Constructor, staticProps);
return Constructor;
}
const possibleConstructorReturn = exports.possibleConstructorReturn = function (self, call) {
if (false /* DEBUG */) {
if (!self) {
throw new ReferenceError(`this hasn't been initialized - super() hasn't been called`);
}
}
return call !== null && typeof call === 'object' || typeof call === 'function' ? call : self;
};
});
enifed('ember/index', ['exports', 'require', '@ember/-internals/environment', 'node-module', '@ember/-internals/utils', '@ember/-internals/container', '@ember/instrumentation', '@ember/-internals/meta', '@ember/-internals/metal', '@ember/canary-features', '@ember/debug', 'backburner', '@ember/-internals/console', '@ember/controller', '@ember/controller/lib/controller_mixin', '@ember/string', '@ember/service', '@ember/object/computed', '@ember/-internals/runtime', '@ember/-internals/glimmer', 'ember/version', '@ember/-internals/views', '@ember/-internals/routing', '@ember/-internals/extension-support', '@ember/error', '@ember/runloop', '@ember/-internals/error-handling', '@ember/-internals/owner', '@ember/application', '@ember/application/globals-resolver', '@ember/application/instance', '@ember/engine', '@ember/engine/instance', '@ember/map', '@ember/map/with-default', '@ember/map/lib/ordered-set', '@ember/polyfills', '@ember/deprecated-features'], function (exports, _require2, _environment, _nodeModule, _utils, _container, _instrumentation, _meta, _metal, _canaryFeatures, _debug, _backburner, _console, _controller, _controller_mixin, _string, _service, _computed, _runtime, _glimmer, _version, _views, _routing, _extensionSupport, _error, _runloop, _errorHandling, _owner, _application, _globalsResolver, _instance, _engine, _instance2, _map, _withDefault, _orderedSet, _polyfills, _deprecatedFeatures) {
'use strict';
// ****@ember/-internals/environment****
// eslint-disable-next-line import/no-unresolved
const Ember = typeof _environment.context.imports.Ember === 'object' && _environment.context.imports.Ember || {};
Ember.isNamespace = true;
Ember.toString = function () {
return 'Ember';
};
Object.defineProperty(Ember, 'ENV', {
get: _environment.getENV,
enumerable: false
});
Object.defineProperty(Ember, 'lookup', {
get: _environment.getLookup,
set: _environment.setLookup,
enumerable: false
});
if (_deprecatedFeatures.EMBER_EXTEND_PROTOTYPES) {
Object.defineProperty(Ember, 'EXTEND_PROTOTYPES', {
enumerable: false,
get() {
false && !false && (0, _debug.deprecate)('Accessing Ember.EXTEND_PROTOTYPES is deprecated, please migrate to Ember.ENV.EXTEND_PROTOTYPES', false, {
id: 'ember-env.old-extend-prototypes',
until: '4.0.0'
});
return _environment.ENV.EXTEND_PROTOTYPES;
}
});
}
// ****@ember/application****
Ember.getOwner = _owner.getOwner;
Ember.setOwner = _owner.setOwner;
Ember.Application = _application.default;
Ember.DefaultResolver = Ember.Resolver = _globalsResolver.default;
Ember.ApplicationInstance = _instance.default;
// ****@ember/engine****
Ember.Engine = _engine.default;
Ember.EngineInstance = _instance2.default;
// ****@ember/map****
Ember.OrderedSet = _orderedSet.default;
Ember.__OrderedSet__ = _orderedSet.__OrderedSet__;
Ember.Map = _map.default;
Ember.MapWithDefault = _withDefault.default;
// ****@ember/polyfills****
Ember.assign = _polyfills.assign;
Ember.merge = _polyfills.merge;
// ****@ember/-internals/utils****
Ember.generateGuid = _utils.generateGuid;
Ember.GUID_KEY = _utils.GUID_KEY;
Ember.guidFor = _utils.guidFor;
Ember.inspect = _utils.inspect;
Ember.makeArray = _utils.makeArray;
Ember.canInvoke = _utils.canInvoke;
Ember.tryInvoke = _utils.tryInvoke;
Ember.wrap = _utils.wrap;
Ember.uuid = _utils.uuid;
Ember.NAME_KEY = _utils.NAME_KEY;
Ember._Cache = _utils.Cache;
// ****@ember/-internals/container****
Ember.Container = _container.Container;
Ember.Registry = _container.Registry;
// ****@ember/debug****
Ember.assert = _debug.assert;
Ember.warn = _debug.warn;
Ember.debug = _debug.debug;
Ember.deprecate = _debug.deprecate;
Ember.deprecateFunc = _debug.deprecateFunc;
Ember.runInDebug = _debug.runInDebug;
// ****@ember/error****
Ember.Error = _error.default;
/**
@public
@class Ember.Debug
*/
Ember.Debug = {
registerDeprecationHandler: _debug.registerDeprecationHandler,
registerWarnHandler: _debug.registerWarnHandler
};
// ****@ember/instrumentation****
Ember.instrument = _instrumentation.instrument;
Ember.subscribe = _instrumentation.subscribe;
Ember.Instrumentation = {
instrument: _instrumentation.instrument,
subscribe: _instrumentation.subscribe,
unsubscribe: _instrumentation.unsubscribe,
reset: _instrumentation.reset
};
// ****@ember/runloop****
// Using _globalsRun here so that mutating the function (adding
// `next`, `later`, etc to it) is only available in globals builds
Ember.run = _runloop._globalsRun;
Ember.run.backburner = _runloop.backburner;
Ember.run.begin = _runloop.begin;
Ember.run.bind = _runloop.bind;
Ember.run.cancel = _runloop.cancel;
Ember.run.debounce = _runloop.debounce;
Ember.run.end = _runloop.end;
Ember.run.hasScheduledTimers = _runloop.hasScheduledTimers;
Ember.run.join = _runloop.join;
Ember.run.later = _runloop.later;
Ember.run.next = _runloop.next;
Ember.run.once = _runloop.once;
Ember.run.schedule = _runloop.schedule;
Ember.run.scheduleOnce = _runloop.scheduleOnce;
Ember.run.throttle = _runloop.throttle;
Ember.run.cancelTimers = _runloop.cancelTimers;
Object.defineProperty(Ember.run, 'currentRunLoop', {
get: _runloop.getCurrentRunLoop,
enumerable: false
});
// ****@ember/-internals/metal****
// Using _globalsComputed here so that mutating the function is only available
// in globals builds
const computed = _metal._globalsComputed;
Ember.computed = computed;
computed.alias = _metal.alias;
Ember.ComputedProperty = _metal.ComputedProperty;
Ember.cacheFor = _metal.getCachedValueFor;
Ember.meta = _meta.meta;
Ember.get = _metal.get;
Ember.getWithDefault = _metal.getWithDefault;
Ember._getPath = _metal._getPath;
Ember.set = _metal.set;
Ember.trySet = _metal.trySet;
Ember.FEATURES = (0, _polyfills.assign)({ isEnabled: _canaryFeatures.isEnabled }, _canaryFeatures.FEATURES);
Ember._Cache = _utils.Cache;
Ember.on = _metal.on;
Ember.addListener = _metal.addListener;
Ember.removeListener = _metal.removeListener;
Ember.sendEvent = _metal.sendEvent;
Ember.hasListeners = _metal.hasListeners;
Ember.isNone = _metal.isNone;
Ember.isEmpty = _metal.isEmpty;
Ember.isBlank = _metal.isBlank;
Ember.isPresent = _metal.isPresent;
Ember.notifyPropertyChange = _metal.notifyPropertyChange;
Ember.overrideChains = _metal.overrideChains;
Ember.beginPropertyChanges = _metal.beginPropertyChanges;
Ember.endPropertyChanges = _metal.endPropertyChanges;
Ember.changeProperties = _metal.changeProperties;
Ember.platform = {
defineProperty: true,
hasPropertyAccessors: true
};
Ember.defineProperty = _metal.defineProperty;
Ember.watchKey = _metal.watchKey;
Ember.unwatchKey = _metal.unwatchKey;
Ember.removeChainWatcher = _metal.removeChainWatcher;
Ember._ChainNode = _metal.ChainNode;
Ember.finishChains = _metal.finishChains;
Ember.watchPath = _metal.watchPath;
Ember.unwatchPath = _metal.unwatchPath;
Ember.watch = _metal.watch;
Ember.isWatching = _metal.isWatching;
Ember.unwatch = _metal.unwatch;
Ember.destroy = _meta.deleteMeta;
Ember.libraries = _metal.libraries;
Ember.getProperties = _metal.getProperties;
Ember.setProperties = _metal.setProperties;
Ember.expandProperties = _metal.expandProperties;
Ember.addObserver = _metal.addObserver;
Ember.removeObserver = _metal.removeObserver;
Ember.aliasMethod = _metal.aliasMethod;
Ember.observer = _metal.observer;
Ember.mixin = _metal.mixin;
Ember.Mixin = _metal.Mixin;
/**
A function may be assigned to `Ember.onerror` to be called when Ember
internals encounter an error. This is useful for specialized error handling
and reporting code.
```javascript
import $ from 'jquery';
Ember.onerror = function(error) {
$.ajax('/report-error', 'POST', {
stack: error.stack,
otherInformation: 'whatever app state you want to provide'
});
};
```
Internally, `Ember.onerror` is used as Backburner's error handler.
@event onerror
@for Ember
@param {Exception} error the error object
@public
*/
Object.defineProperty(Ember, 'onerror', {
get: _errorHandling.getOnerror,
set: _errorHandling.setOnerror,
enumerable: false
});
Object.defineProperty(Ember, 'testing', {
get: _debug.isTesting,
set: _debug.setTesting,
enumerable: false
});
Ember._Backburner = _backburner.default;
// ****@ember/-internals/console****
if (_deprecatedFeatures.LOGGER) {
Ember.Logger = _console.default;
}
// ****@ember/-internals/runtime****
Ember.A = _runtime.A;
Ember.String = {
loc: _string.loc,
w: _string.w,
dasherize: _string.dasherize,
decamelize: _string.decamelize,
camelize: _string.camelize,
classify: _string.classify,
underscore: _string.underscore,
capitalize: _string.capitalize
};
Ember.Object = _runtime.Object;
Ember._RegistryProxyMixin = _runtime.RegistryProxyMixin;
Ember._ContainerProxyMixin = _runtime.ContainerProxyMixin;
Ember.compare = _runtime.compare;
Ember.copy = _runtime.copy;
Ember.isEqual = _runtime.isEqual;
/**
@module ember
*/
/**
Namespace for injection helper methods.
@class inject
@namespace Ember
@static
@public
*/
Ember.inject = function inject() {
false && !false && (0, _debug.assert)(`Injected properties must be created through helpers, see '${Object.keys(inject).map(k => `'inject.${k}'`).join(' or ')}'`);
};
Ember.inject.service = _service.inject;
Ember.inject.controller = _controller.inject;
Ember.Array = _runtime.Array;
Ember.Comparable = _runtime.Comparable;
Ember.Enumerable = _runtime.Enumerable;
Ember.ArrayProxy = _runtime.ArrayProxy;
Ember.ObjectProxy = _runtime.ObjectProxy;
Ember.ActionHandler = _runtime.ActionHandler;
Ember.CoreObject = _runtime.CoreObject;
Ember.NativeArray = _runtime.NativeArray;
Ember.Copyable = _runtime.Copyable;
Ember.MutableEnumerable = _runtime.MutableEnumerable;
Ember.MutableArray = _runtime.MutableArray;
Ember.TargetActionSupport = _runtime.TargetActionSupport;
Ember.Evented = _runtime.Evented;
Ember.PromiseProxyMixin = _runtime.PromiseProxyMixin;
Ember.Observable = _runtime.Observable;
Ember.typeOf = _runtime.typeOf;
Ember.isArray = _runtime.isArray;
Ember.Object = _runtime.Object;
Ember.onLoad = _application.onLoad;
Ember.runLoadHooks = _application.runLoadHooks;
Ember.Controller = _controller.default;
Ember.ControllerMixin = _controller_mixin.default;
Ember.Service = _service.default;
Ember._ProxyMixin = _runtime._ProxyMixin;
Ember.RSVP = _runtime.RSVP;
Ember.Namespace = _runtime.Namespace;
computed.empty = _computed.empty;
computed.notEmpty = _computed.notEmpty;
computed.none = _computed.none;
computed.not = _computed.not;
computed.bool = _computed.bool;
computed.match = _computed.match;
computed.equal = _computed.equal;
computed.gt = _computed.gt;
computed.gte = _computed.gte;
computed.lt = _computed.lt;
computed.lte = _computed.lte;
computed.oneWay = _computed.oneWay;
computed.reads = _computed.oneWay;
computed.readOnly = _computed.readOnly;
computed.deprecatingAlias = _computed.deprecatingAlias;
computed.and = _computed.and;
computed.or = _computed.or;
computed.sum = _computed.sum;
computed.min = _computed.min;
computed.max = _computed.max;
computed.map = _computed.map;
computed.sort = _computed.sort;
computed.setDiff = _computed.setDiff;
computed.mapBy = _computed.mapBy;
computed.filter = _computed.filter;
computed.filterBy = _computed.filterBy;
computed.uniq = _computed.uniq;
computed.uniqBy = _computed.uniqBy;
computed.union = _computed.union;
computed.intersect = _computed.intersect;
computed.collect = _computed.collect;
/**
Defines the hash of localized strings for the current language. Used by
the `String.loc` helper. To localize, add string values to this
hash.
@property STRINGS
@for Ember
@type Object
@private
*/
Object.defineProperty(Ember, 'STRINGS', {
configurable: false,
get: _string._getStrings,
set: _string._setStrings
});
/**
Whether searching on the global for new Namespace instances is enabled.
This is only exported here as to not break any addons. Given the new
visit API, you will have issues if you treat this as a indicator of
booted.
Internally this is only exposing a flag in Namespace.
@property BOOTED
@for Ember
@type Boolean
@private
*/
Object.defineProperty(Ember, 'BOOTED', {
configurable: false,
enumerable: false,
get: _metal.isNamespaceSearchDisabled,
set: _metal.setNamespaceSearchDisabled
});
// ****@ember/-internals/glimmer****
Ember.Component = _glimmer.Component;
_glimmer.Helper.helper = _glimmer.helper;
Ember.Helper = _glimmer.Helper;
Ember.Checkbox = _glimmer.Checkbox;
Ember.TextField = _glimmer.TextField;
Ember.TextArea = _glimmer.TextArea;
Ember.LinkComponent = _glimmer.LinkComponent;
Ember._setComponentManager = _glimmer.setComponentManager;
Ember._componentManagerCapabilities = _glimmer.capabilities;
Ember._setModifierManager = _glimmer.setModifierManager;
Ember._modifierManagerCapabilties = _glimmer.modifierCapabilties;
Ember.Handlebars = {
template: _glimmer.template,
Utils: {
escapeExpression: _glimmer.escapeExpression
}
};
Ember.HTMLBars = {
template: _glimmer.template
};
if (_environment.ENV.EXTEND_PROTOTYPES.String) {
String.prototype.htmlSafe = function () {
return (0, _glimmer.htmlSafe)(this);
};
}
Ember.String.htmlSafe = _glimmer.htmlSafe;
Ember.String.isHTMLSafe = _glimmer.isHTMLSafe;
/**
Global hash of shared templates. This will automatically be populated
by the build tools so that you can store your Handlebars templates in
separate files that get loaded into JavaScript at buildtime.
@property TEMPLATES
@for Ember
@type Object
@private
*/
Object.defineProperty(Ember, 'TEMPLATES', {
get: _glimmer.getTemplates,
set: _glimmer.setTemplates,
configurable: false,
enumerable: false
});
/**
The semantic version
@property VERSION
@type String
@public
*/
Ember.VERSION = _version.default;
// ****@ember/-internals/views****
if (!_views.jQueryDisabled) {
Ember.$ = _views.jQuery;
}
Ember.ViewUtils = {
isSimpleClick: _views.isSimpleClick,
getViewElement: _views.getViewElement,
getViewBounds: _views.getViewBounds,
getViewClientRects: _views.getViewClientRects,
getViewBoundingClientRect: _views.getViewBoundingClientRect,
getRootViews: _views.getRootViews,
getChildViews: _views.getChildViews,
isSerializationFirstNode: _glimmer.isSerializationFirstNode
};
Ember.TextSupport = _views.TextSupport;
Ember.ComponentLookup = _views.ComponentLookup;
Ember.EventDispatcher = _views.EventDispatcher;
// ****@ember/-internals/routing****
Ember.Location = _routing.Location;
Ember.AutoLocation = _routing.AutoLocation;
Ember.HashLocation = _routing.HashLocation;
Ember.HistoryLocation = _routing.HistoryLocation;
Ember.NoneLocation = _routing.NoneLocation;
Ember.controllerFor = _routing.controllerFor;
Ember.generateControllerFactory = _routing.generateControllerFactory;
Ember.generateController = _routing.generateController;
Ember.RouterDSL = _routing.RouterDSL;
Ember.Router = _routing.Router;
Ember.Route = _routing.Route;
(0, _application.runLoadHooks)('Ember.Application', _application.default);
Ember.DataAdapter = _extensionSupport.DataAdapter;
Ember.ContainerDebugAdapter = _extensionSupport.ContainerDebugAdapter;
if ((0, _require2.has)('ember-template-compiler')) {
(0, _require2.default)('ember-template-compiler');
}
// do this to ensure that Ember.Test is defined properly on the global
// if it is present.
if ((0, _require2.has)('ember-testing')) {
let testing = (0, _require2.default)('ember-testing');
Ember.Test = testing.Test;
Ember.Test.Adapter = testing.Adapter;
Ember.Test.QUnitAdapter = testing.QUnitAdapter;
Ember.setupForTesting = testing.setupForTesting;
}
(0, _application.runLoadHooks)('Ember');
exports.default = Ember;
if (_nodeModule.IS_NODE) {
_nodeModule.module.exports = Ember;
} else {
_environment.context.exports.Ember = _environment.context.exports.Em = Ember;
}
/**
@module jquery
@public
*/
/**
@class jquery
@public
@static
*/
/**
Alias for jQuery
@for jquery
@method $
@static
@public
*/
});
enifed("ember/version", ["exports"], function (exports) {
"use strict";
exports.default = "3.7.0";
});
/*global enifed, module */
enifed('node-module', ['exports'], function(_exports) {
var IS_NODE = typeof module === 'object' && typeof module.require === 'function';
if (IS_NODE) {
_exports.require = module.require;
_exports.module = module;
_exports.IS_NODE = IS_NODE;
} else {
_exports.require = null;
_exports.module = null;
_exports.IS_NODE = IS_NODE;
}
});
enifed("route-recognizer", ["exports"], function (exports) {
"use strict";
var createObject = Object.create;
function createMap() {
var map = createObject(null);
map["__"] = undefined;
delete map["__"];
return map;
}
var Target = function Target(path, matcher, delegate) {
this.path = path;
this.matcher = matcher;
this.delegate = delegate;
};
Target.prototype.to = function to(target, callback) {
var delegate = this.delegate;
if (delegate && delegate.willAddRoute) {
target = delegate.willAddRoute(this.matcher.target, target);
}
this.matcher.add(this.path, target);
if (callback) {
if (callback.length === 0) {
throw new Error("You must have an argument in the function passed to `to`");
}
this.matcher.addChild(this.path, target, callback, this.delegate);
}
};
var Matcher = function Matcher(target) {
this.routes = createMap();
this.children = createMap();
this.target = target;
};
Matcher.prototype.add = function add(path, target) {
this.routes[path] = target;
};
Matcher.prototype.addChild = function addChild(path, target, callback, delegate) {
var matcher = new Matcher(target);
this.children[path] = matcher;
var match = generateMatch(path, matcher, delegate);
if (delegate && delegate.contextEntered) {
delegate.contextEntered(target, match);
}
callback(match);
};
function generateMatch(startingPath, matcher, delegate) {
function match(path, callback) {
var fullPath = startingPath + path;
if (callback) {
callback(generateMatch(fullPath, matcher, delegate));
} else {
return new Target(fullPath, matcher, delegate);
}
}
return match;
}
function addRoute(routeArray, path, handler) {
var len = 0;
for (var i = 0; i < routeArray.length; i++) {
len += routeArray[i].path.length;
}
path = path.substr(len);
var route = { path: path, handler: handler };
routeArray.push(route);
}
function eachRoute(baseRoute, matcher, callback, binding) {
var routes = matcher.routes;
var paths = Object.keys(routes);
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
var routeArray = baseRoute.slice();
addRoute(routeArray, path, routes[path]);
var nested = matcher.children[path];
if (nested) {
eachRoute(routeArray, nested, callback, binding);
} else {
callback.call(binding, routeArray);
}
}
}
var map = function (callback, addRouteCallback) {
var matcher = new Matcher();
callback(generateMatch("", matcher, this.delegate));
eachRoute([], matcher, function (routes) {
if (addRouteCallback) {
addRouteCallback(this, routes);
} else {
this.add(routes);
}
}, this);
};
// Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
// values that are not reserved (i.e., unicode characters, emoji, etc). The reserved
// chars are "/" and "%".
// Safe to call multiple times on the same path.
// Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
function normalizePath(path) {
return path.split("/").map(normalizeSegment).join("/");
}
// We want to ensure the characters "%" and "/" remain in percent-encoded
// form when normalizing paths, so replace them with their encoded form after
// decoding the rest of the path
var SEGMENT_RESERVED_CHARS = /%|\//g;
function normalizeSegment(segment) {
if (segment.length < 3 || segment.indexOf("%") === -1) {
return segment;
}
return decodeURIComponent(segment).replace(SEGMENT_RESERVED_CHARS, encodeURIComponent);
}
// We do not want to encode these characters when generating dynamic path segments
// See https://tools.ietf.org/html/rfc3986#section-3.3
// sub-delims: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
// others allowed by RFC 3986: ":", "@"
//
// First encode the entire path segment, then decode any of the encoded special chars.
//
// The chars "!", "'", "(", ")", "*" do not get changed by `encodeURIComponent`,
// so the possible encoded chars are:
// ['%24', '%26', '%2B', '%2C', '%3B', '%3D', '%3A', '%40'].
var PATH_SEGMENT_ENCODINGS = /%(?:2(?:4|6|B|C)|3(?:B|D|A)|40)/g;
function encodePathSegment(str) {
return encodeURIComponent(str).replace(PATH_SEGMENT_ENCODINGS, decodeURIComponent);
}
var escapeRegex = /(\/|\.|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g;
var isArray = Array.isArray;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function getParam(params, key) {
if (typeof params !== "object" || params === null) {
throw new Error("You must pass an object as the second argument to `generate`.");
}
if (!hasOwnProperty.call(params, key)) {
throw new Error("You must provide param `" + key + "` to `generate`.");
}
var value = params[key];
var str = typeof value === "string" ? value : "" + value;
if (str.length === 0) {
throw new Error("You must provide a param `" + key + "`.");
}
return str;
}
var eachChar = [];
eachChar[0 /* Static */] = function (segment, currentState) {
var state = currentState;
var value = segment.value;
for (var i = 0; i < value.length; i++) {
var ch = value.charCodeAt(i);
state = state.put(ch, false, false);
}
return state;
};
eachChar[1 /* Dynamic */] = function (_, currentState) {
return currentState.put(47 /* SLASH */, true, true);
};
eachChar[2 /* Star */] = function (_, currentState) {
return currentState.put(-1 /* ANY */, false, true);
};
eachChar[4 /* Epsilon */] = function (_, currentState) {
return currentState;
};
var regex = [];
regex[0 /* Static */] = function (segment) {
return segment.value.replace(escapeRegex, "\\$1");
};
regex[1 /* Dynamic */] = function () {
return "([^/]+)";
};
regex[2 /* Star */] = function () {
return "(.+)";
};
regex[4 /* Epsilon */] = function () {
return "";
};
var generate = [];
generate[0 /* Static */] = function (segment) {
return segment.value;
};
generate[1 /* Dynamic */] = function (segment, params) {
var value = getParam(params, segment.value);
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
return encodePathSegment(value);
} else {
return value;
}
};
generate[2 /* Star */] = function (segment, params) {
return getParam(params, segment.value);
};
generate[4 /* Epsilon */] = function () {
return "";
};
var EmptyObject = Object.freeze({});
var EmptyArray = Object.freeze([]);
// The `names` will be populated with the paramter name for each dynamic/star
// segment. `shouldDecodes` will be populated with a boolean for each dyanamic/star
// segment, indicating whether it should be decoded during recognition.
function parse(segments, route, types) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.length > 0 && route.charCodeAt(0) === 47 /* SLASH */) {
route = route.substr(1);
}
var parts = route.split("/");
var names = undefined;
var shouldDecodes = undefined;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
var flags = 0;
var type = 0;
if (part === "") {
type = 4 /* Epsilon */;
} else if (part.charCodeAt(0) === 58 /* COLON */) {
type = 1 /* Dynamic */;
} else if (part.charCodeAt(0) === 42 /* STAR */) {
type = 2 /* Star */;
} else {
type = 0 /* Static */;
}
flags = 2 << type;
if (flags & 12 /* Named */) {
part = part.slice(1);
names = names || [];
names.push(part);
shouldDecodes = shouldDecodes || [];
shouldDecodes.push((flags & 4 /* Decoded */) !== 0);
}
if (flags & 14 /* Counted */) {
types[type]++;
}
segments.push({
type: type,
value: normalizeSegment(part)
});
}
return {
names: names || EmptyArray,
shouldDecodes: shouldDecodes || EmptyArray
};
}
function isEqualCharSpec(spec, char, negate) {
return spec.char === char && spec.negate === negate;
}
// A State has a character specification and (`charSpec`) and a list of possible
// subsequent states (`nextStates`).
//
// If a State is an accepting state, it will also have several additional
// properties:
//
// * `regex`: A regular expression that is used to extract parameters from paths
// that reached this accepting state.
// * `handlers`: Information on how to convert the list of captures into calls
// to registered handlers with the specified parameters
// * `types`: How many static, dynamic or star segments in this route. Used to
// decide which route to use if multiple registered routes match a path.
//
// Currently, State is implemented naively by looping over `nextStates` and
// comparing a character specification against a character. A more efficient
// implementation would use a hash of keys pointing at one or more next states.
var State = function State(states, id, char, negate, repeat) {
this.states = states;
this.id = id;
this.char = char;
this.negate = negate;
this.nextStates = repeat ? id : null;
this.pattern = "";
this._regex = undefined;
this.handlers = undefined;
this.types = undefined;
};
State.prototype.regex = function regex$1() {
if (!this._regex) {
this._regex = new RegExp(this.pattern);
}
return this._regex;
};
State.prototype.get = function get(char, negate) {
var this$1 = this;
var nextStates = this.nextStates;
if (nextStates === null) {
return;
}
if (isArray(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1.states[nextStates[i]];
if (isEqualCharSpec(child, char, negate)) {
return child;
}
}
} else {
var child$1 = this.states[nextStates];
if (isEqualCharSpec(child$1, char, negate)) {
return child$1;
}
}
};
State.prototype.put = function put(char, negate, repeat) {
var state;
// If the character specification already exists in a child of the current
// state, just return that state.
if (state = this.get(char, negate)) {
return state;
}
// Make a new state for the character spec
var states = this.states;
state = new State(states, states.length, char, negate, repeat);
states[states.length] = state;
// Insert the new state as a child of the current state
if (this.nextStates == null) {
this.nextStates = state.id;
} else if (isArray(this.nextStates)) {
this.nextStates.push(state.id);
} else {
this.nextStates = [this.nextStates, state.id];
}
// Return the new state
return state;
};
// Find a list of child states matching the next character
State.prototype.match = function match(ch) {
var this$1 = this;
var nextStates = this.nextStates;
if (!nextStates) {
return [];
}
var returned = [];
if (isArray(nextStates)) {
for (var i = 0; i < nextStates.length; i++) {
var child = this$1.states[nextStates[i]];
if (isMatch(child, ch)) {
returned.push(child);
}
}
} else {
var child$1 = this.states[nextStates];
if (isMatch(child$1, ch)) {
returned.push(child$1);
}
}
return returned;
};
function isMatch(spec, char) {
return spec.negate ? spec.char !== char && spec.char !== -1 /* ANY */ : spec.char === char || spec.char === -1 /* ANY */;
}
// This is a somewhat naive strategy, but should work in a lot of cases
// A better strategy would properly resolve /posts/:id/new and /posts/edit/:id.
//
// This strategy generally prefers more static and less dynamic matching.
// Specifically, it
//
// * prefers fewer stars to more, then
// * prefers using stars for less of the match to more, then
// * prefers fewer dynamic segments to more, then
// * prefers more static segments to more
function sortSolutions(states) {
return states.sort(function (a, b) {
var ref = a.types || [0, 0, 0];
var astatics = ref[0];
var adynamics = ref[1];
var astars = ref[2];
var ref$1 = b.types || [0, 0, 0];
var bstatics = ref$1[0];
var bdynamics = ref$1[1];
var bstars = ref$1[2];
if (astars !== bstars) {
return astars - bstars;
}
if (astars) {
if (astatics !== bstatics) {
return bstatics - astatics;
}
if (adynamics !== bdynamics) {
return bdynamics - adynamics;
}
}
if (adynamics !== bdynamics) {
return adynamics - bdynamics;
}
if (astatics !== bstatics) {
return bstatics - astatics;
}
return 0;
});
}
function recognizeChar(states, ch) {
var nextStates = [];
for (var i = 0, l = states.length; i < l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
var RecognizeResults = function RecognizeResults(queryParams) {
this.length = 0;
this.queryParams = queryParams || {};
};
RecognizeResults.prototype.splice = Array.prototype.splice;
RecognizeResults.prototype.slice = Array.prototype.slice;
RecognizeResults.prototype.push = Array.prototype.push;
function findHandler(state, originalPath, queryParams) {
var handlers = state.handlers;
var regex = state.regex();
if (!regex || !handlers) {
throw new Error("state not initialized");
}
var captures = originalPath.match(regex);
var currentCapture = 1;
var result = new RecognizeResults(queryParams);
result.length = handlers.length;
for (var i = 0; i < handlers.length; i++) {
var handler = handlers[i];
var names = handler.names;
var shouldDecodes = handler.shouldDecodes;
var params = EmptyObject;
var isDynamic = false;
if (names !== EmptyArray && shouldDecodes !== EmptyArray) {
for (var j = 0; j < names.length; j++) {
isDynamic = true;
var name = names[j];
var capture = captures && captures[currentCapture++];
if (params === EmptyObject) {
params = {};
}
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS && shouldDecodes[j]) {
params[name] = capture && decodeURIComponent(capture);
} else {
params[name] = capture;
}
}
}
result[i] = {
handler: handler.handler,
params: params,
isDynamic: isDynamic
};
}
return result;
}
function decodeQueryParamPart(part) {
// http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
part = part.replace(/\+/gm, "%20");
var result;
try {
result = decodeURIComponent(part);
} catch (error) {
result = "";
}
return result;
}
var RouteRecognizer = function RouteRecognizer() {
this.names = createMap();
var states = [];
var state = new State(states, 0, -1 /* ANY */, true, false);
states[0] = state;
this.states = states;
this.rootState = state;
};
RouteRecognizer.prototype.add = function add(routes, options) {
var currentState = this.rootState;
var pattern = "^";
var types = [0, 0, 0];
var handlers = new Array(routes.length);
var allSegments = [];
var isEmpty = true;
var j = 0;
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = parse(allSegments, route.path, types);
var names = ref.names;
var shouldDecodes = ref.shouldDecodes;
// preserve j so it points to the start of newly added segments
for (; j < allSegments.length; j++) {
var segment = allSegments[j];
if (segment.type === 4 /* Epsilon */) {
continue;
}
isEmpty = false;
// Add a "/" for the new segment
currentState = currentState.put(47 /* SLASH */, false, false);
pattern += "/";
// Add a representation of the segment to the NFA and regex
currentState = eachChar[segment.type](segment, currentState);
pattern += regex[segment.type](segment);
}
handlers[i] = {
handler: route.handler,
names: names,
shouldDecodes: shouldDecodes
};
}
if (isEmpty) {
currentState = currentState.put(47 /* SLASH */, false, false);
pattern += "/";
}
currentState.handlers = handlers;
currentState.pattern = pattern + "$";
currentState.types = types;
var name;
if (typeof options === "object" && options !== null && options.as) {
name = options.as;
}
if (name) {
// if (this.names[name]) {
// throw new Error("You may not add a duplicate route named `" + name + "`.");
// }
this.names[name] = {
segments: allSegments,
handlers: handlers
};
}
};
RouteRecognizer.prototype.handlersFor = function handlersFor(name) {
var route = this.names[name];
if (!route) {
throw new Error("There is no route named " + name);
}
var result = new Array(route.handlers.length);
for (var i = 0; i < route.handlers.length; i++) {
var handler = route.handlers[i];
result[i] = handler;
}
return result;
};
RouteRecognizer.prototype.hasRoute = function hasRoute(name) {
return !!this.names[name];
};
RouteRecognizer.prototype.generate = function generate$1(name, params) {
var route = this.names[name];
var output = "";
if (!route) {
throw new Error("There is no route named " + name);
}
var segments = route.segments;
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (segment.type === 4 /* Epsilon */) {
continue;
}
output += "/";
output += generate[segment.type](segment, params);
}
if (output.charAt(0) !== "/") {
output = "/" + output;
}
if (params && params.queryParams) {
output += this.generateQueryString(params.queryParams);
}
return output;
};
RouteRecognizer.prototype.generateQueryString = function generateQueryString(params) {
var pairs = [];
var keys = Object.keys(params);
keys.sort();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = params[key];
if (value == null) {
continue;
}
var pair = encodeURIComponent(key);
if (isArray(value)) {
for (var j = 0; j < value.length; j++) {
var arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
} else {
pair += "=" + encodeURIComponent(value);
pairs.push(pair);
}
}
if (pairs.length === 0) {
return "";
}
return "?" + pairs.join("&");
};
RouteRecognizer.prototype.parseQueryString = function parseQueryString(queryString) {
var pairs = queryString.split("&");
var queryParams = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("="),
key = decodeQueryParamPart(pair[0]),
keyLength = key.length,
isArray = false,
value = void 0;
if (pair.length === 1) {
value = "true";
} else {
// Handle arrays
if (keyLength > 2 && key.slice(keyLength - 2) === "[]") {
isArray = true;
key = key.slice(0, keyLength - 2);
if (!queryParams[key]) {
queryParams[key] = [];
}
}
value = pair[1] ? decodeQueryParamPart(pair[1]) : "";
}
if (isArray) {
queryParams[key].push(value);
} else {
queryParams[key] = value;
}
}
return queryParams;
};
RouteRecognizer.prototype.recognize = function recognize(path) {
var results;
var states = [this.rootState];
var queryParams = {};
var isSlashDropped = false;
var hashStart = path.indexOf("#");
if (hashStart !== -1) {
path = path.substr(0, hashStart);
}
var queryStart = path.indexOf("?");
if (queryStart !== -1) {
var queryString = path.substr(queryStart + 1, path.length);
path = path.substr(0, queryStart);
queryParams = this.parseQueryString(queryString);
}
if (path.charAt(0) !== "/") {
path = "/" + path;
}
var originalPath = path;
if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
path = normalizePath(path);
} else {
path = decodeURI(path);
originalPath = decodeURI(originalPath);
}
var pathLen = path.length;
if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
path = path.substr(0, pathLen - 1);
originalPath = originalPath.substr(0, originalPath.length - 1);
isSlashDropped = true;
}
for (var i = 0; i < path.length; i++) {
states = recognizeChar(states, path.charCodeAt(i));
if (!states.length) {
break;
}
}
var solutions = [];
for (var i$1 = 0; i$1 < states.length; i$1++) {
if (states[i$1].handlers) {
solutions.push(states[i$1]);
}
}
states = sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
// if a trailing slash was dropped and a star segment is the last segment
// specified, put the trailing slash back
if (isSlashDropped && state.pattern && state.pattern.slice(-5) === "(.+)$") {
originalPath = originalPath + "/";
}
results = findHandler(state, originalPath, queryParams);
}
return results;
};
RouteRecognizer.VERSION = "0.3.4";
// Set to false to opt-out of encoding and decoding path segments.
// See https://github.com/tildeio/route-recognizer/pull/55
RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS = true;
RouteRecognizer.Normalizer = {
normalizeSegment: normalizeSegment, normalizePath: normalizePath, encodePathSegment: encodePathSegment
};
RouteRecognizer.prototype.map = map;
exports.default = RouteRecognizer;
});
enifed('router_js', ['exports', 'rsvp', 'route-recognizer'], function (exports, _rsvp, _routeRecognizer) {
'use strict';
exports.InternalRouteInfo = exports.TransitionError = exports.TransitionState = exports.QUERY_PARAMS_SYMBOL = exports.PARAMS_SYMBOL = exports.STATE_SYMBOL = exports.logAbort = exports.InternalTransition = undefined;
const TransitionAbortedError = function () {
TransitionAbortedError.prototype = Object.create(Error.prototype);
TransitionAbortedError.prototype.constructor = TransitionAbortedError;
function TransitionAbortedError(message) {
let error = Error.call(this, message);
this.name = 'TransitionAborted';
this.message = message || 'TransitionAborted';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, TransitionAbortedError);
} else {
this.stack = error.stack;
}
}
return TransitionAbortedError;
}();
const slice = Array.prototype.slice;
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
Determines if an object is Promise by checking if it is "thenable".
**/
function isPromise(p) {
return p !== null && typeof p === 'object' && typeof p.then === 'function';
}
function merge(hash, other) {
for (let prop in other) {
if (hasOwnProperty.call(other, prop)) {
hash[prop] = other[prop];
}
}
}
/**
@private
Extracts query params from the end of an array
**/
function extractQueryParams(array) {
let len = array && array.length,
head,
queryParams;
if (len && len > 0) {
let obj = array[len - 1];
if (isQueryParams(obj)) {
queryParams = obj.queryParams;
head = slice.call(array, 0, len - 1);
return [head, queryParams];
}
}
return [array, null];
}
function isQueryParams(obj) {
return obj && hasOwnProperty.call(obj, 'queryParams');
}
/**
@private
Coerces query param properties and array elements into strings.
**/
function coerceQueryParamsToString(queryParams) {
for (let key in queryParams) {
let val = queryParams[key];
if (typeof val === 'number') {
queryParams[key] = '' + val;
} else if (Array.isArray(val)) {
for (let i = 0, l = val.length; i < l; i++) {
val[i] = '' + val[i];
}
}
}
}
/**
@private
*/
function log(router, ...args) {
if (!router.log) {
return;
}
if (arguments.length === 2) {
let [sequence, msg] = args;
router.log('Transition #' + sequence + ': ' + msg);
} else {
let [msg] = args;
router.log(msg);
}
}
function isParam(object) {
return typeof object === 'string' || object instanceof String || typeof object === 'number' || object instanceof Number;
}
function forEach(array, callback) {
for (let i = 0, l = array.length; i < l && callback(array[i]) !== false; i++) {
// empty intentionally
}
}
function getChangelist(oldObject, newObject) {
let key;
let results = {
all: {},
changed: {},
removed: {}
};
merge(results.all, newObject);
let didChange = false;
coerceQueryParamsToString(oldObject);
coerceQueryParamsToString(newObject);
// Calculate removals
for (key in oldObject) {
if (hasOwnProperty.call(oldObject, key)) {
if (!hasOwnProperty.call(newObject, key)) {
didChange = true;
results.removed[key] = oldObject[key];
}
}
}
// Calculate changes
for (key in newObject) {
if (hasOwnProperty.call(newObject, key)) {
let oldElement = oldObject[key];
let newElement = newObject[key];
if (isArray(oldElement) && isArray(newElement)) {
if (oldElement.length !== newElement.length) {
results.changed[key] = newObject[key];
didChange = true;
} else {
for (let i = 0, l = oldElement.length; i < l; i++) {
if (oldElement[i] !== newElement[i]) {
results.changed[key] = newObject[key];
didChange = true;
}
}
}
} else if (oldObject[key] !== newObject[key]) {
results.changed[key] = newObject[key];
didChange = true;
}
}
}
return didChange ? results : undefined;
}
function isArray(obj) {
return Array.isArray(obj);
}
function promiseLabel(label) {
return 'Router: ' + label;
}
const STATE_SYMBOL = `__STATE__-2619860001345920-3322w3`;
const PARAMS_SYMBOL = `__PARAMS__-261986232992830203-23323`;
const QUERY_PARAMS_SYMBOL = `__QPS__-2619863929824844-32323`;
/**
A Transition is a thennable (a promise-like object) that represents
an attempt to transition to another route. It can be aborted, either
explicitly via `abort` or by attempting another transition while a
previous one is still underway. An aborted transition can also
be `retry()`d later.
@class Transition
@constructor
@param {Object} router
@param {Object} intent
@param {Object} state
@param {Object} error
@private
*/
class Transition {
constructor(router, intent, state, error = undefined, previousTransition = undefined) {
this.from = null;
this.to = undefined;
this.isAborted = false;
this.isActive = true;
this.urlMethod = 'update';
this.resolveIndex = 0;
this.queryParamsOnly = false;
this.isTransition = true;
this.isCausedByAbortingTransition = false;
this.isCausedByInitialTransition = false;
this.isCausedByAbortingReplaceTransition = false;
this._visibleQueryParams = {};
this[STATE_SYMBOL] = state || router.state;
this.intent = intent;
this.router = router;
this.data = intent && intent.data || {};
this.resolvedModels = {};
this[QUERY_PARAMS_SYMBOL] = {};
this.promise = undefined;
this.error = undefined;
this[PARAMS_SYMBOL] = {};
this.routeInfos = [];
this.targetName = undefined;
this.pivotHandler = undefined;
this.sequence = -1;
if (error) {
this.promise = _rsvp.Promise.reject(error);
this.error = error;
return;
}
// if you're doing multiple redirects, need the new transition to know if it
// is actually part of the first transition or not. Any further redirects
// in the initial transition also need to know if they are part of the
// initial transition
this.isCausedByAbortingTransition = !!previousTransition;
this.isCausedByInitialTransition = !!previousTransition && (previousTransition.isCausedByInitialTransition || previousTransition.sequence === 0);
// Every transition in the chain is a replace
this.isCausedByAbortingReplaceTransition = !!previousTransition && previousTransition.urlMethod === 'replace' && (!previousTransition.isCausedByAbortingTransition || previousTransition.isCausedByAbortingReplaceTransition);
if (state) {
this[PARAMS_SYMBOL] = state.params;
this[QUERY_PARAMS_SYMBOL] = state.queryParams;
this.routeInfos = state.routeInfos;
let len = state.routeInfos.length;
if (len) {
this.targetName = state.routeInfos[len - 1].name;
}
for (let i = 0; i < len; ++i) {
let handlerInfo = state.routeInfos[i];
// TODO: this all seems hacky
if (!handlerInfo.isResolved) {
break;
}
this.pivotHandler = handlerInfo.route;
}
this.sequence = router.currentSequence++;
this.promise = state.resolve(() => {
if (this.isAborted) {
return _rsvp.Promise.reject(false, promiseLabel('Transition aborted - reject'));
}
return _rsvp.Promise.resolve(true);
}, this).catch(result => {
return _rsvp.Promise.reject(this.router.transitionDidError(result, this));
}, promiseLabel('Handle Abort'));
} else {
this.promise = _rsvp.Promise.resolve(this[STATE_SYMBOL]);
this[PARAMS_SYMBOL] = {};
}
}
/**
The Transition's internal promise. Calling `.then` on this property
is that same as calling `.then` on the Transition object itself, but
this property is exposed for when you want to pass around a
Transition's promise, but not the Transition object itself, since
Transition object can be externally `abort`ed, while the promise
cannot.
@property promise
@type {Object}
@public
*/
/**
Custom state can be stored on a Transition's `data` object.
This can be useful for decorating a Transition within an earlier
hook and shared with a later hook. Properties set on `data` will
be copied to new transitions generated by calling `retry` on this
transition.
@property data
@type {Object}
@public
*/
/**
A standard promise hook that resolves if the transition
succeeds and rejects if it fails/redirects/aborts.
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thennable,
but not the Transition itself.
@method then
@param {Function} onFulfilled
@param {Function} onRejected
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
then(onFulfilled, onRejected, label) {
return this.promise.then(onFulfilled, onRejected, label);
}
/**
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thennable,
but not the Transition itself.
@method catch
@param {Function} onRejection
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
catch(onRejection, label) {
return this.promise.catch(onRejection, label);
}
/**
Forwards to the internal `promise` property which you can
use in situations where you want to pass around a thennable,
but not the Transition itself.
@method finally
@param {Function} callback
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
@public
*/
finally(callback, label) {
return this.promise.finally(callback, label);
}
/**
Aborts the Transition. Note you can also implicitly abort a transition
by initiating another transition while a previous one is underway.
@method abort
@return {Transition} this transition
@public
*/
abort() {
this.rollback();
let transition = new Transition(this.router, undefined, undefined, undefined);
transition.to = this.from;
transition.from = this.from;
transition.isAborted = true;
this.router.routeWillChange(transition);
this.router.routeDidChange(transition);
return this;
}
rollback() {
if (!this.isAborted) {
log(this.router, this.sequence, this.targetName + ': transition was aborted');
if (this.intent !== undefined && this.intent !== null) {
this.intent.preTransitionState = this.router.state;
}
this.isAborted = true;
this.isActive = false;
this.router.activeTransition = undefined;
}
}
redirect(newTransition) {
this.rollback();
this.router.routeWillChange(newTransition);
}
/**
Retries a previously-aborted transition (making sure to abort the
transition if it's still active). Returns a new transition that
represents the new attempt to transition.
@method retry
@return {Transition} new transition
@public
*/
retry() {
// TODO: add tests for merged state retry()s
this.abort();
let newTransition = this.router.transitionByIntent(this.intent, false);
// inheriting a `null` urlMethod is not valid
// the urlMethod is only set to `null` when
// the transition is initiated *after* the url
// has been updated (i.e. `router.handleURL`)
//
// in that scenario, the url method cannot be
// inherited for a new transition because then
// the url would not update even though it should
if (this.urlMethod !== null) {
newTransition.method(this.urlMethod);
}
return newTransition;
}
/**
Sets the URL-changing method to be employed at the end of a
successful transition. By default, a new Transition will just
use `updateURL`, but passing 'replace' to this method will
cause the URL to update using 'replaceWith' instead. Omitting
a parameter will disable the URL change, allowing for transitions
that don't update the URL at completion (this is also used for
handleURL, since the URL has already changed before the
transition took place).
@method method
@param {String} method the type of URL-changing method to use
at the end of a transition. Accepted values are 'replace',
falsy values, or any other non-falsy value (which is
interpreted as an updateURL transition).
@return {Transition} this transition
@public
*/
method(method) {
this.urlMethod = method;
return this;
}
// Alias 'trigger' as 'send'
send(ignoreFailure, _name, err, transition, handler) {
this.trigger(ignoreFailure, _name, err, transition, handler);
}
/**
Fires an event on the current list of resolved/resolving
handlers within this transition. Useful for firing events
on route hierarchies that haven't fully been entered yet.
Note: This method is also aliased as `send`
@method trigger
@param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error
@param {String} name the name of the event to fire
@public
*/
trigger(ignoreFailure, name, ...args) {
this.router.triggerEvent(this[STATE_SYMBOL].routeInfos.slice(0, this.resolveIndex + 1), ignoreFailure, name, args);
}
/**
Transitions are aborted and their promises rejected
when redirects occur; this method returns a promise
that will follow any redirects that occur and fulfill
with the value fulfilled by any redirecting transitions
that occur.
@method followRedirects
@return {Promise} a promise that fulfills with the same
value that the final redirecting transition fulfills with
@public
*/
followRedirects() {
let router = this.router;
return this.promise.catch(function (reason) {
if (router.activeTransition) {
return router.activeTransition.followRedirects();
}
return _rsvp.Promise.reject(reason);
});
}
toString() {
return 'Transition (sequence ' + this.sequence + ')';
}
/**
@private
*/
log(message) {
log(this.router, this.sequence, message);
}
}
/**
@private
Logs and returns an instance of TransitionAborted.
*/
function logAbort(transition) {
log(transition.router, transition.sequence, 'detected abort.');
return new TransitionAbortedError();
}
function isTransition(obj) {
return typeof obj === 'object' && obj instanceof Transition && obj.isTransition;
}
function prepareResult(obj) {
if (isTransition(obj)) {
return null;
}
return obj;
}
let ROUTE_INFOS = new WeakMap();
function toReadOnlyRouteInfo(routeInfos, queryParams = {}, includeAttributes = false) {
return routeInfos.map((info, i) => {
let { name, params, paramNames, context, route } = info;
if (ROUTE_INFOS.has(info) && includeAttributes) {
let routeInfo = ROUTE_INFOS.get(info);
routeInfo = attachMetadata(route, routeInfo);
let routeInfoWithAttribute = createRouteInfoWithAttributes(routeInfo, context);
ROUTE_INFOS.set(info, routeInfoWithAttribute);
return routeInfoWithAttribute;
}
let routeInfo = {
find(predicate, thisArg) {
let publicInfo;
let arr = [];
if (predicate.length === 3) {
arr = routeInfos.map(info => ROUTE_INFOS.get(info));
}
for (let i = 0; routeInfos.length > i; i++) {
publicInfo = ROUTE_INFOS.get(routeInfos[i]);
if (predicate.call(thisArg, publicInfo, i, arr)) {
return publicInfo;
}
}
return undefined;
},
get name() {
return name;
},
get paramNames() {
return paramNames;
},
get metadata() {
return buildRouteInfoMetadata(route);
},
get parent() {
let parent = routeInfos[i - 1];
if (parent === undefined) {
return null;
}
return ROUTE_INFOS.get(parent);
},
get child() {
let child = routeInfos[i + 1];
if (child === undefined) {
return null;
}
return ROUTE_INFOS.get(child);
},
get localName() {
let parts = this.name.split('.');
return parts[parts.length - 1];
},
get params() {
return params;
},
get queryParams() {
return queryParams;
}
};
if (includeAttributes) {
routeInfo = createRouteInfoWithAttributes(routeInfo, context);
}
ROUTE_INFOS.set(info, routeInfo);
return routeInfo;
});
}
function createRouteInfoWithAttributes(routeInfo, context) {
let attributes = {
get attributes() {
return context;
}
};
if (Object.isFrozen(routeInfo) || routeInfo.hasOwnProperty('attributes')) {
return Object.freeze(Object.assign({}, routeInfo, attributes));
}
return Object.assign(routeInfo, attributes);
}
function buildRouteInfoMetadata(route) {
if (route !== undefined && route !== null && route.buildRouteInfoMetadata !== undefined) {
return route.buildRouteInfoMetadata();
}
return null;
}
function attachMetadata(route, routeInfo) {
let metadata = {
get metadata() {
return buildRouteInfoMetadata(route);
}
};
if (Object.isFrozen(routeInfo) || routeInfo.hasOwnProperty('metadata')) {
return Object.freeze(Object.assign({}, routeInfo, metadata));
}
return Object.assign(routeInfo, metadata);
}
class InternalRouteInfo {
constructor(router, name, paramNames, route) {
this._routePromise = undefined;
this._route = null;
this.params = {};
this.isResolved = false;
this.name = name;
this.paramNames = paramNames;
this.router = router;
if (route) {
this._processRoute(route);
}
}
getModel(_transition) {
return _rsvp.Promise.resolve(this.context);
}
serialize(_context) {
return this.params || {};
}
resolve(shouldContinue, transition) {
return _rsvp.Promise.resolve(this.routePromise).then(route => this.checkForAbort(shouldContinue, route)).then(() => this.runBeforeModelHook(transition)).then(() => this.checkForAbort(shouldContinue, null)).then(() => this.getModel(transition)).then(resolvedModel => this.checkForAbort(shouldContinue, resolvedModel)).then(resolvedModel => this.runAfterModelHook(transition, resolvedModel)).then(resolvedModel => this.becomeResolved(transition, resolvedModel));
}
becomeResolved(transition, resolvedContext) {
let params = this.serialize(resolvedContext);
if (transition) {
this.stashResolvedModel(transition, resolvedContext);
transition[PARAMS_SYMBOL] = transition[PARAMS_SYMBOL] || {};
transition[PARAMS_SYMBOL][this.name] = params;
}
let context;
let contextsMatch = resolvedContext === this.context;
if ('context' in this || !contextsMatch) {
context = resolvedContext;
}
let cached = ROUTE_INFOS.get(this);
let resolved = new ResolvedRouteInfo(this.router, this.name, this.paramNames, params, this.route, context);
if (cached !== undefined) {
ROUTE_INFOS.set(resolved, cached);
}
return resolved;
}
shouldSupercede(routeInfo) {
// Prefer this newer routeInfo over `other` if:
// 1) The other one doesn't exist
// 2) The names don't match
// 3) This route has a context that doesn't match
// the other one (or the other one doesn't have one).
// 4) This route has parameters that don't match the other.
if (!routeInfo) {
return true;
}
let contextsMatch = routeInfo.context === this.context;
return routeInfo.name !== this.name || 'context' in this && !contextsMatch || this.hasOwnProperty('params') && !paramsMatch(this.params, routeInfo.params);
}
get route() {
// _route could be set to either a route object or undefined, so we
// compare against null to know when it's been set
if (this._route !== null) {
return this._route;
}
return this.fetchRoute();
}
set route(route) {
this._route = route;
}
get routePromise() {
if (this._routePromise) {
return this._routePromise;
}
this.fetchRoute();
return this._routePromise;
}
set routePromise(routePromise) {
this._routePromise = routePromise;
}
log(transition, message) {
if (transition.log) {
transition.log(this.name + ': ' + message);
}
}
updateRoute(route) {
return this.route = route;
}
runBeforeModelHook(transition) {
if (transition.trigger) {
transition.trigger(true, 'willResolveModel', transition, this.route);
}
let result;
if (this.route) {
if (this.route.beforeModel !== undefined) {
result = this.route.beforeModel(transition);
}
}
if (isTransition(result)) {
result = null;
}
return _rsvp.Promise.resolve(result);
}
runAfterModelHook(transition, resolvedModel) {
// Stash the resolved model on the payload.
// This makes it possible for users to swap out
// the resolved model in afterModel.
let name = this.name;
this.stashResolvedModel(transition, resolvedModel);
let result;
if (this.route !== undefined) {
if (this.route.afterModel !== undefined) {
result = this.route.afterModel(resolvedModel, transition);
}
}
result = prepareResult(result);
return _rsvp.Promise.resolve(result).then(() => {
// Ignore the fulfilled value returned from afterModel.
// Return the value stashed in resolvedModels, which
// might have been swapped out in afterModel.
return transition.resolvedModels[name];
});
}
checkForAbort(shouldContinue, value) {
return _rsvp.Promise.resolve(shouldContinue()).then(function () {
// We don't care about shouldContinue's resolve value;
// pass along the original value passed to this fn.
return value;
}, null);
}
stashResolvedModel(transition, resolvedModel) {
transition.resolvedModels = transition.resolvedModels || {};
transition.resolvedModels[this.name] = resolvedModel;
}
fetchRoute() {
let route = this.router.getRoute(this.name);
return this._processRoute(route);
}
_processRoute(route) {
// Setup a routePromise so that we can wait for asynchronously loaded routes
this.routePromise = _rsvp.Promise.resolve(route);
// Wait until the 'route' property has been updated when chaining to a route
// that is a promise
if (isPromise(route)) {
this.routePromise = this.routePromise.then(r => {
return this.updateRoute(r);
});
// set to undefined to avoid recursive loop in the route getter
return this.route = undefined;
} else if (route) {
return this.updateRoute(route);
}
return undefined;
}
}
class ResolvedRouteInfo extends InternalRouteInfo {
constructor(router, name, paramNames, params, route, context) {
super(router, name, paramNames, route);
this.params = params;
this.isResolved = true;
this.context = context;
}
resolve(_shouldContinue, transition) {
// A ResolvedRouteInfo just resolved with itself.
if (transition && transition.resolvedModels) {
transition.resolvedModels[this.name] = this.context;
}
return _rsvp.Promise.resolve(this);
}
}
class UnresolvedRouteInfoByParam extends InternalRouteInfo {
constructor(router, name, paramNames, params, route) {
super(router, name, paramNames, route);
this.params = {};
this.params = params;
}
getModel(transition) {
let fullParams = this.params;
if (transition && transition[QUERY_PARAMS_SYMBOL]) {
fullParams = {};
merge(fullParams, this.params);
fullParams.queryParams = transition[QUERY_PARAMS_SYMBOL];
}
let route = this.route;
let result = undefined;
if (route.deserialize) {
result = route.deserialize(fullParams, transition);
} else if (route.model) {
result = route.model(fullParams, transition);
}
if (result && isTransition(result)) {
result = undefined;
}
return _rsvp.Promise.resolve(result);
}
}
class UnresolvedRouteInfoByObject extends InternalRouteInfo {
constructor(router, name, paramNames, context) {
super(router, name, paramNames);
this.context = context;
this.serializer = this.router.getSerializer(name);
}
getModel(transition) {
if (this.router.log !== undefined) {
this.router.log(this.name + ': resolving provided model');
}
return super.getModel(transition);
}
/**
@private
Serializes a route using its custom `serialize` method or
by a default that looks up the expected property name from
the dynamic segment.
@param {Object} model the model to be serialized for this route
*/
serialize(model) {
let { paramNames, context } = this;
if (!model) {
model = context;
}
let object = {};
if (isParam(model)) {
object[paramNames[0]] = model;
return object;
}
// Use custom serialize if it exists.
if (this.serializer) {
// invoke this.serializer unbound (getSerializer returns a stateless function)
return this.serializer.call(null, model, paramNames);
} else if (this.route !== undefined) {
if (this.route.serialize) {
return this.route.serialize(model, paramNames);
}
}
if (paramNames.length !== 1) {
return;
}
let name = paramNames[0];
if (/_id$/.test(name)) {
object[name] = model.id;
} else {
object[name] = model;
}
return object;
}
}
function paramsMatch(a, b) {
if (!a !== !b) {
// Only one is null.
return false;
}
if (!a) {
// Both must be null.
return true;
}
// Note: this assumes that both params have the same
// number of keys, but since we're comparing the
// same routes, they should.
for (let k in a) {
if (a.hasOwnProperty(k) && a[k] !== b[k]) {
return false;
}
}
return true;
}
class TransitionIntent {
constructor(router, data = {}) {
this.router = router;
this.data = data;
}
}
class TransitionState {
constructor() {
this.routeInfos = [];
this.queryParams = {};
this.params = {};
}
promiseLabel(label) {
let targetName = '';
forEach(this.routeInfos, function (routeInfo) {
if (targetName !== '') {
targetName += '.';
}
targetName += routeInfo.name;
return true;
});
return promiseLabel("'" + targetName + "': " + label);
}
resolve(shouldContinue, transition) {
// First, calculate params for this state. This is useful
// information to provide to the various route hooks.
let params = this.params;
forEach(this.routeInfos, routeInfo => {
params[routeInfo.name] = routeInfo.params || {};
return true;
});
transition.resolveIndex = 0;
let currentState = this;
let wasAborted = false;
// The prelude RSVP.resolve() asyncs us into the promise land.
return _rsvp.Promise.resolve(null, this.promiseLabel('Start transition')).then(resolveOneRouteInfo, null, this.promiseLabel('Resolve route')).catch(handleError, this.promiseLabel('Handle error'));
function innerShouldContinue() {
return _rsvp.Promise.resolve(shouldContinue(), currentState.promiseLabel('Check if should continue')).catch(function (reason) {
// We distinguish between errors that occurred
// during resolution (e.g. before"Model/model/afterModel),
// and aborts due to a rejecting promise from shouldContinue().
wasAborted = true;
return _rsvp.Promise.reject(reason);
}, currentState.promiseLabel('Handle abort'));
}
function handleError(error) {
// This is the only possible
// reject value of TransitionState#resolve
let routeInfos = currentState.routeInfos;
let errorHandlerIndex = transition.resolveIndex >= routeInfos.length ? routeInfos.length - 1 : transition.resolveIndex;
return _rsvp.Promise.reject(new TransitionError(error, currentState.routeInfos[errorHandlerIndex].route, wasAborted, currentState));
}
function proceed(resolvedRouteInfo) {
let wasAlreadyResolved = currentState.routeInfos[transition.resolveIndex].isResolved;
// Swap the previously unresolved routeInfo with
// the resolved routeInfo
currentState.routeInfos[transition.resolveIndex++] = resolvedRouteInfo;
if (!wasAlreadyResolved) {
// Call the redirect hook. The reason we call it here
// vs. afterModel is so that redirects into child
// routes don't re-run the model hooks for this
// already-resolved route.
let { route } = resolvedRouteInfo;
if (route !== undefined) {
if (route.redirect) {
route.redirect(resolvedRouteInfo.context, transition);
}
}
}
// Proceed after ensuring that the redirect hook
// didn't abort this transition by transitioning elsewhere.
return innerShouldContinue().then(resolveOneRouteInfo, null, currentState.promiseLabel('Resolve route'));
}
function resolveOneRouteInfo() {
if (transition.resolveIndex === currentState.routeInfos.length) {
// This is is the only possible
// fulfill value of TransitionState#resolve
return currentState;
}
let routeInfo = currentState.routeInfos[transition.resolveIndex];
return routeInfo.resolve(innerShouldContinue, transition).then(proceed, null, currentState.promiseLabel('Proceed'));
}
}
}
class TransitionError {
constructor(error, route, wasAborted, state) {
this.error = error;
this.route = route;
this.wasAborted = wasAborted;
this.state = state;
}
}
class NamedTransitionIntent extends TransitionIntent {
constructor(router, name, pivotHandler, contexts = [], queryParams = {}, data) {
super(router, data);
this.preTransitionState = undefined;
this.name = name;
this.pivotHandler = pivotHandler;
this.contexts = contexts;
this.queryParams = queryParams;
}
applyToState(oldState, isIntermediate) {
// TODO: WTF fix me
let partitionedArgs = extractQueryParams([this.name].concat(this.contexts)),
pureArgs = partitionedArgs[0],
handlers = this.router.recognizer.handlersFor(pureArgs[0]);
let targetRouteName = handlers[handlers.length - 1].handler;
return this.applyToHandlers(oldState, handlers, targetRouteName, isIntermediate, false);
}
applyToHandlers(oldState, parsedHandlers, targetRouteName, isIntermediate, checkingIfActive) {
let i, len;
let newState = new TransitionState();
let objects = this.contexts.slice(0);
let invalidateIndex = parsedHandlers.length;
// Pivot handlers are provided for refresh transitions
if (this.pivotHandler) {
for (i = 0, len = parsedHandlers.length; i < len; ++i) {
if (parsedHandlers[i].handler === this.pivotHandler.routeName) {
invalidateIndex = i;
break;
}
}
}
for (i = parsedHandlers.length - 1; i >= 0; --i) {
let result = parsedHandlers[i];
let name = result.handler;
let oldHandlerInfo = oldState.routeInfos[i];
let newHandlerInfo = null;
if (result.names.length > 0) {
if (i >= invalidateIndex) {
newHandlerInfo = this.createParamHandlerInfo(name, result.names, objects, oldHandlerInfo);
} else {
newHandlerInfo = this.getHandlerInfoForDynamicSegment(name, result.names, objects, oldHandlerInfo, targetRouteName, i);
}
} else {
// This route has no dynamic segment.
// Therefore treat as a param-based handlerInfo
// with empty params. This will cause the `model`
// hook to be called with empty params, which is desirable.
newHandlerInfo = this.createParamHandlerInfo(name, result.names, objects, oldHandlerInfo);
}
if (checkingIfActive) {
// If we're performing an isActive check, we want to
// serialize URL params with the provided context, but
// ignore mismatches between old and new context.
newHandlerInfo = newHandlerInfo.becomeResolved(null, newHandlerInfo.context);
let oldContext = oldHandlerInfo && oldHandlerInfo.context;
if (result.names.length > 0 && oldHandlerInfo.context !== undefined && newHandlerInfo.context === oldContext) {
// If contexts match in isActive test, assume params also match.
// This allows for flexibility in not requiring that every last
// handler provide a `serialize` method
newHandlerInfo.params = oldHandlerInfo && oldHandlerInfo.params;
}
newHandlerInfo.context = oldContext;
}
let handlerToUse = oldHandlerInfo;
if (i >= invalidateIndex || newHandlerInfo.shouldSupercede(oldHandlerInfo)) {
invalidateIndex = Math.min(i, invalidateIndex);
handlerToUse = newHandlerInfo;
}
if (isIntermediate && !checkingIfActive) {
handlerToUse = handlerToUse.becomeResolved(null, handlerToUse.context);
}
newState.routeInfos.unshift(handlerToUse);
}
if (objects.length > 0) {
throw new Error('More context objects were passed than there are dynamic segments for the route: ' + targetRouteName);
}
if (!isIntermediate) {
this.invalidateChildren(newState.routeInfos, invalidateIndex);
}
merge(newState.queryParams, this.queryParams || {});
return newState;
}
invalidateChildren(handlerInfos, invalidateIndex) {
for (let i = invalidateIndex, l = handlerInfos.length; i < l; ++i) {
let handlerInfo = handlerInfos[i];
if (handlerInfo.isResolved) {
let { name, params, route, paramNames } = handlerInfos[i];
handlerInfos[i] = new UnresolvedRouteInfoByParam(this.router, name, paramNames, params, route);
}
}
}
getHandlerInfoForDynamicSegment(name, names, objects, oldHandlerInfo, _targetRouteName, i) {
let objectToUse;
if (objects.length > 0) {
// Use the objects provided for this transition.
objectToUse = objects[objects.length - 1];
if (isParam(objectToUse)) {
return this.createParamHandlerInfo(name, names, objects, oldHandlerInfo);
} else {
objects.pop();
}
} else if (oldHandlerInfo && oldHandlerInfo.name === name) {
// Reuse the matching oldHandlerInfo
return oldHandlerInfo;
} else {
if (this.preTransitionState) {
let preTransitionHandlerInfo = this.preTransitionState.routeInfos[i];
objectToUse = preTransitionHandlerInfo && preTransitionHandlerInfo.context;
} else {
// Ideally we should throw this error to provide maximal
// information to the user that not enough context objects
// were provided, but this proves too cumbersome in Ember
// in cases where inner template helpers are evaluated
// before parent helpers un-render, in which cases this
// error somewhat prematurely fires.
//throw new Error("Not enough context objects were provided to complete a transition to " + targetRouteName + ". Specifically, the " + name + " route needs an object that can be serialized into its dynamic URL segments [" + names.join(', ') + "]");
return oldHandlerInfo;
}
}
return new UnresolvedRouteInfoByObject(this.router, name, names, objectToUse);
}
createParamHandlerInfo(name, names, objects, oldHandlerInfo) {
let params = {};
// Soak up all the provided string/numbers
let numNames = names.length;
while (numNames--) {
// Only use old params if the names match with the new handler
let oldParams = oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params || {};
let peek = objects[objects.length - 1];
let paramName = names[numNames];
if (isParam(peek)) {
params[paramName] = '' + objects.pop();
} else {
// If we're here, this means only some of the params
// were string/number params, so try and use a param
// value from a previous handler.
if (oldParams.hasOwnProperty(paramName)) {
params[paramName] = oldParams[paramName];
} else {
throw new Error("You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments for route " + name);
}
}
}
return new UnresolvedRouteInfoByParam(this.router, name, names, params);
}
}
const UnrecognizedURLError = function () {
UnrecognizedURLError.prototype = Object.create(Error.prototype);
UnrecognizedURLError.prototype.constructor = UnrecognizedURLError;
function UnrecognizedURLError(message) {
let error = Error.call(this, message);
this.name = 'UnrecognizedURLError';
this.message = message || 'UnrecognizedURL';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, UnrecognizedURLError);
} else {
this.stack = error.stack;
}
}
return UnrecognizedURLError;
}();
class URLTransitionIntent extends TransitionIntent {
constructor(router, url, data) {
super(router, data);
this.url = url;
this.preTransitionState = undefined;
}
applyToState(oldState) {
let newState = new TransitionState();
let results = this.router.recognizer.recognize(this.url),
i,
len;
if (!results) {
throw new UnrecognizedURLError(this.url);
}
let statesDiffer = false;
let _url = this.url;
// Checks if a handler is accessible by URL. If it is not, an error is thrown.
// For the case where the handler is loaded asynchronously, the error will be
// thrown once it is loaded.
function checkHandlerAccessibility(handler) {
if (handler && handler.inaccessibleByURL) {
throw new UnrecognizedURLError(_url);
}
return handler;
}
for (i = 0, len = results.length; i < len; ++i) {
let result = results[i];
let name = result.handler;
let paramNames = [];
if (this.router.recognizer.hasRoute(name)) {
paramNames = this.router.recognizer.handlersFor(name)[i].names;
}
let newRouteInfo = new UnresolvedRouteInfoByParam(this.router, name, paramNames, result.params);
let route = newRouteInfo.route;
if (route) {
checkHandlerAccessibility(route);
} else {
// If the hanlder is being loaded asynchronously, check if we can
// access it after it has resolved
newRouteInfo.routePromise = newRouteInfo.routePromise.then(checkHandlerAccessibility);
}
let oldRouteInfo = oldState.routeInfos[i];
if (statesDiffer || newRouteInfo.shouldSupercede(oldRouteInfo)) {
statesDiffer = true;
newState.routeInfos[i] = newRouteInfo;
} else {
newState.routeInfos[i] = oldRouteInfo;
}
}
merge(newState.queryParams, results.queryParams);
return newState;
}
}
class Router {
constructor(logger) {
this._lastQueryParams = {};
this.state = undefined;
this.oldState = undefined;
this.activeTransition = undefined;
this.currentRouteInfos = undefined;
this._changedQueryParams = undefined;
this.currentSequence = 0;
this.log = logger;
this.recognizer = new _routeRecognizer.default();
this.reset();
}
/**
The main entry point into the router. The API is essentially
the same as the `map` method in `route-recognizer`.
This method extracts the String handler at the last `.to()`
call and uses it as the name of the whole route.
@param {Function} callback
*/
map(callback) {
this.recognizer.map(callback, function (recognizer, routes) {
for (let i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) {
let route = routes[i];
let handler = route.handler;
recognizer.add(routes, { as: handler });
proceed = route.path === '/' || route.path === '' || handler.slice(-6) === '.index';
}
});
}
hasRoute(route) {
return this.recognizer.hasRoute(route);
}
queryParamsTransition(changelist, wasTransitioning, oldState, newState) {
this.fireQueryParamDidChange(newState, changelist);
if (!wasTransitioning && this.activeTransition) {
// One of the routes in queryParamsDidChange
// caused a transition. Just return that transition.
return this.activeTransition;
} else {
// Running queryParamsDidChange didn't change anything.
// Just update query params and be on our way.
// We have to return a noop transition that will
// perform a URL update at the end. This gives
// the user the ability to set the url update
// method (default is replaceState).
let newTransition = new Transition(this, undefined, undefined);
newTransition.queryParamsOnly = true;
oldState.queryParams = this.finalizeQueryParamChange(newState.routeInfos, newState.queryParams, newTransition);
newTransition[QUERY_PARAMS_SYMBOL] = newState.queryParams;
this.toReadOnlyInfos(newTransition, newState);
this.routeWillChange(newTransition);
newTransition.promise = newTransition.promise.then(result => {
this._updateURL(newTransition, oldState);
this.didTransition(this.currentRouteInfos);
this.toInfos(newTransition, newState.routeInfos, true);
this.routeDidChange(newTransition);
return result;
}, null, promiseLabel('Transition complete'));
return newTransition;
}
}
transitionByIntent(intent, isIntermediate) {
try {
return this.getTransitionByIntent(intent, isIntermediate);
} catch (e) {
return new Transition(this, intent, undefined, e, undefined);
}
}
recognize(url) {
let intent = new URLTransitionIntent(this, url);
let newState = this.generateNewState(intent);
if (newState === null) {
return newState;
}
let readonlyInfos = toReadOnlyRouteInfo(newState.routeInfos, newState.queryParams);
return readonlyInfos[readonlyInfos.length - 1];
}
recognizeAndLoad(url) {
let intent = new URLTransitionIntent(this, url);
let newState = this.generateNewState(intent);
if (newState === null) {
return _rsvp.Promise.reject(`URL ${url} was not recognized`);
}
let newTransition = new Transition(this, intent, newState, undefined);
return newTransition.then(() => {
let routeInfosWithAttributes = toReadOnlyRouteInfo(newState.routeInfos, newTransition[QUERY_PARAMS_SYMBOL], true);
return routeInfosWithAttributes[routeInfosWithAttributes.length - 1];
});
}
generateNewState(intent) {
try {
return intent.applyToState(this.state, false);
} catch (e) {
return null;
}
}
getTransitionByIntent(intent, isIntermediate) {
let wasTransitioning = !!this.activeTransition;
let oldState = wasTransitioning ? this.activeTransition[STATE_SYMBOL] : this.state;
let newTransition;
let newState = intent.applyToState(oldState, isIntermediate);
let queryParamChangelist = getChangelist(oldState.queryParams, newState.queryParams);
if (routeInfosEqual(newState.routeInfos, oldState.routeInfos)) {
// This is a no-op transition. See if query params changed.
if (queryParamChangelist) {
let newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState);
newTransition.queryParamsOnly = true;
return newTransition;
}
// No-op. No need to create a new transition.
return this.activeTransition || new Transition(this, undefined, undefined);
}
if (isIntermediate) {
this.setupContexts(newState);
let transition = this.activeTransition;
if (transition !== undefined && !transition.isCausedByAbortingTransition) {
transition = new Transition(this, undefined, undefined);
transition.from = transition.from;
}
this.toInfos(transition, newState.routeInfos);
this.routeWillChange(transition);
return this.activeTransition;
}
// Create a new transition to the destination route.
newTransition = new Transition(this, intent, newState, undefined, this.activeTransition);
// transition is to same route with same params, only query params differ.
// not caught above probably because refresh() has been used
if (routeInfosSameExceptQueryParams(newState.routeInfos, oldState.routeInfos)) {
newTransition.queryParamsOnly = true;
}
this.toReadOnlyInfos(newTransition, newState);
// Abort and usurp any previously active transition.
if (this.activeTransition) {
this.activeTransition.redirect(newTransition);
}
this.activeTransition = newTransition;
// Transition promises by default resolve with resolved state.
// For our purposes, swap out the promise to resolve
// after the transition has been finalized.
newTransition.promise = newTransition.promise.then(result => {
return this.finalizeTransition(newTransition, result);
}, null, promiseLabel('Settle transition promise when transition is finalized'));
if (!wasTransitioning) {
this.notifyExistingHandlers(newState, newTransition);
}
this.fireQueryParamDidChange(newState, queryParamChangelist);
return newTransition;
}
/**
@private
Begins and returns a Transition based on the provided
arguments. Accepts arguments in the form of both URL
transitions and named transitions.
@param {Router} router
@param {Array[Object]} args arguments passed to transitionTo,
replaceWith, or handleURL
*/
doTransition(name, modelsArray = [], isIntermediate = false) {
let lastArg = modelsArray[modelsArray.length - 1];
let queryParams = {};
if (lastArg !== undefined && lastArg.hasOwnProperty('queryParams')) {
queryParams = modelsArray.pop().queryParams;
}
let intent;
if (name === undefined) {
log(this, 'Updating query params');
// A query param update is really just a transition
// into the route you're already on.
let { routeInfos } = this.state;
intent = new NamedTransitionIntent(this, routeInfos[routeInfos.length - 1].name, undefined, [], queryParams);
} else if (name.charAt(0) === '/') {
log(this, 'Attempting URL transition to ' + name);
intent = new URLTransitionIntent(this, name);
} else {
log(this, 'Attempting transition to ' + name);
intent = new NamedTransitionIntent(this, name, undefined, modelsArray, queryParams);
}
return this.transitionByIntent(intent, isIntermediate);
}
/**
@private
Updates the URL (if necessary) and calls `setupContexts`
to update the router's array of `currentRouteInfos`.
*/
finalizeTransition(transition, newState) {
try {
log(transition.router, transition.sequence, 'Resolved all models on destination route; finalizing transition.');
let routeInfos = newState.routeInfos;
// Run all the necessary enter/setup/exit hooks
this.setupContexts(newState, transition);
// Check if a redirect occurred in enter/setup
if (transition.isAborted) {
// TODO: cleaner way? distinguish b/w targetRouteInfos?
this.state.routeInfos = this.currentRouteInfos;
return _rsvp.Promise.reject(logAbort(transition));
}
this._updateURL(transition, newState);
transition.isActive = false;
this.activeTransition = undefined;
this.triggerEvent(this.currentRouteInfos, true, 'didTransition', []);
this.didTransition(this.currentRouteInfos);
this.toInfos(transition, newState.routeInfos, true);
this.routeDidChange(transition);
log(this, transition.sequence, 'TRANSITION COMPLETE.');
// Resolve with the final route.
return routeInfos[routeInfos.length - 1].route;
} catch (e) {
if (!(e instanceof TransitionAbortedError)) {
let infos = transition[STATE_SYMBOL].routeInfos;
transition.trigger(true, 'error', e, transition, infos[infos.length - 1].route);
transition.abort();
}
throw e;
}
}
/**
@private
Takes an Array of `RouteInfo`s, figures out which ones are
exiting, entering, or changing contexts, and calls the
proper route hooks.
For example, consider the following tree of routes. Each route is
followed by the URL segment it handles.
```
|~index ("/")
| |~posts ("/posts")
| | |-showPost ("/:id")
| | |-newPost ("/new")
| | |-editPost ("/edit")
| |~about ("/about/:id")
```
Consider the following transitions:
1. A URL transition to `/posts/1`.
1. Triggers the `*model` callbacks on the
`index`, `posts`, and `showPost` routes
2. Triggers the `enter` callback on the same
3. Triggers the `setup` callback on the same
2. A direct transition to `newPost`
1. Triggers the `exit` callback on `showPost`
2. Triggers the `enter` callback on `newPost`
3. Triggers the `setup` callback on `newPost`
3. A direct transition to `about` with a specified
context object
1. Triggers the `exit` callback on `newPost`
and `posts`
2. Triggers the `serialize` callback on `about`
3. Triggers the `enter` callback on `about`
4. Triggers the `setup` callback on `about`
@param {Router} transition
@param {TransitionState} newState
*/
setupContexts(newState, transition) {
let partition = this.partitionRoutes(this.state, newState);
let i, l, route;
for (i = 0, l = partition.exited.length; i < l; i++) {
route = partition.exited[i].route;
delete route.context;
if (route !== undefined) {
if (route._internalReset !== undefined) {
route._internalReset(true, transition);
}
if (route.exit !== undefined) {
route.exit(transition);
}
}
}
let oldState = this.oldState = this.state;
this.state = newState;
let currentRouteInfos = this.currentRouteInfos = partition.unchanged.slice();
try {
for (i = 0, l = partition.reset.length; i < l; i++) {
route = partition.reset[i].route;
if (route !== undefined) {
if (route._internalReset !== undefined) {
route._internalReset(false, transition);
}
}
}
for (i = 0, l = partition.updatedContext.length; i < l; i++) {
this.routeEnteredOrUpdated(currentRouteInfos, partition.updatedContext[i], false, transition);
}
for (i = 0, l = partition.entered.length; i < l; i++) {
this.routeEnteredOrUpdated(currentRouteInfos, partition.entered[i], true, transition);
}
} catch (e) {
this.state = oldState;
this.currentRouteInfos = oldState.routeInfos;
throw e;
}
this.state.queryParams = this.finalizeQueryParamChange(currentRouteInfos, newState.queryParams, transition);
}
/**
@private
Fires queryParamsDidChange event
*/
fireQueryParamDidChange(newState, queryParamChangelist) {
// If queryParams changed trigger event
if (queryParamChangelist) {
// This is a little hacky but we need some way of storing
// changed query params given that no activeTransition
// is guaranteed to have occurred.
this._changedQueryParams = queryParamChangelist.all;
this.triggerEvent(newState.routeInfos, true, 'queryParamsDidChange', [queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]);
this._changedQueryParams = undefined;
}
}
/**
@private
Helper method used by setupContexts. Handles errors or redirects
that may happen in enter/setup.
*/
routeEnteredOrUpdated(currentRouteInfos, routeInfo, enter, transition) {
let route = routeInfo.route,
context = routeInfo.context;
function _routeEnteredOrUpdated(route) {
if (enter) {
if (route.enter !== undefined) {
route.enter(transition);
}
}
if (transition && transition.isAborted) {
throw new TransitionAbortedError();
}
route.context = context;
if (route.contextDidChange !== undefined) {
route.contextDidChange();
}
if (route.setup !== undefined) {
route.setup(context, transition);
}
if (transition && transition.isAborted) {
throw new TransitionAbortedError();
}
currentRouteInfos.push(routeInfo);
return route;
}
// If the route doesn't exist, it means we haven't resolved the route promise yet
if (route === undefined) {
routeInfo.routePromise = routeInfo.routePromise.then(_routeEnteredOrUpdated);
} else {
_routeEnteredOrUpdated(route);
}
return true;
}
/**
@private
This function is called when transitioning from one URL to
another to determine which routes are no longer active,
which routes are newly active, and which routes remain
active but have their context changed.
Take a list of old routes and new routes and partition
them into four buckets:
* unchanged: the route was active in both the old and
new URL, and its context remains the same
* updated context: the route was active in both the
old and new URL, but its context changed. The route's
`setup` method, if any, will be called with the new
context.
* exited: the route was active in the old URL, but is
no longer active.
* entered: the route was not active in the old URL, but
is now active.
The PartitionedRoutes structure has four fields:
* `updatedContext`: a list of `RouteInfo` objects that
represent routes that remain active but have a changed
context
* `entered`: a list of `RouteInfo` objects that represent
routes that are newly active
* `exited`: a list of `RouteInfo` objects that are no
longer active.
* `unchanged`: a list of `RouteInfo` objects that remain active.
@param {Array[InternalRouteInfo]} oldRoutes a list of the route
information for the previous URL (or `[]` if this is the
first handled transition)
@param {Array[InternalRouteInfo]} newRoutes a list of the route
information for the new URL
@return {Partition}
*/
partitionRoutes(oldState, newState) {
let oldRouteInfos = oldState.routeInfos;
let newRouteInfos = newState.routeInfos;
let routes = {
updatedContext: [],
exited: [],
entered: [],
unchanged: [],
reset: []
};
let routeChanged,
contextChanged = false,
i,
l;
for (i = 0, l = newRouteInfos.length; i < l; i++) {
let oldRouteInfo = oldRouteInfos[i],
newRouteInfo = newRouteInfos[i];
if (!oldRouteInfo || oldRouteInfo.route !== newRouteInfo.route) {
routeChanged = true;
}
if (routeChanged) {
routes.entered.push(newRouteInfo);
if (oldRouteInfo) {
routes.exited.unshift(oldRouteInfo);
}
} else if (contextChanged || oldRouteInfo.context !== newRouteInfo.context) {
contextChanged = true;
routes.updatedContext.push(newRouteInfo);
} else {
routes.unchanged.push(oldRouteInfo);
}
}
for (i = newRouteInfos.length, l = oldRouteInfos.length; i < l; i++) {
routes.exited.unshift(oldRouteInfos[i]);
}
routes.reset = routes.updatedContext.slice();
routes.reset.reverse();
return routes;
}
_updateURL(transition, state) {
let urlMethod = transition.urlMethod;
if (!urlMethod) {
return;
}
let { routeInfos } = state;
let { name: routeName } = routeInfos[routeInfos.length - 1];
let params = {};
for (let i = routeInfos.length - 1; i >= 0; --i) {
let routeInfo = routeInfos[i];
merge(params, routeInfo.params);
if (routeInfo.route.inaccessibleByURL) {
urlMethod = null;
}
}
if (urlMethod) {
params.queryParams = transition._visibleQueryParams || state.queryParams;
let url = this.recognizer.generate(routeName, params);
// transitions during the initial transition must always use replaceURL.
// When the app boots, you are at a url, e.g. /foo. If some route
// redirects to bar as part of the initial transition, you don't want to
// add a history entry for /foo. If you do, pressing back will immediately
// hit the redirect again and take you back to /bar, thus killing the back
// button
let initial = transition.isCausedByInitialTransition;
// say you are at / and you click a link to route /foo. In /foo's
// route, the transition is aborted using replacewith('/bar').
// Because the current url is still /, the history entry for / is
// removed from the history. Clicking back will take you to the page
// you were on before /, which is often not even the app, thus killing
// the back button. That's why updateURL is always correct for an
// aborting transition that's not the initial transition
let replaceAndNotAborting = urlMethod === 'replace' && !transition.isCausedByAbortingTransition;
// because calling refresh causes an aborted transition, this needs to be
// special cased - if the initial transition is a replace transition, the
// urlMethod should be honored here.
let isQueryParamsRefreshTransition = transition.queryParamsOnly && urlMethod === 'replace';
// say you are at / and you a `replaceWith(/foo)` is called. Then, that
// transition is aborted with `replaceWith(/bar)`. At the end, we should
// end up with /bar replacing /. We are replacing the replace. We only
// will replace the initial route if all subsequent aborts are also
// replaces. However, there is some ambiguity around the correct behavior
// here.
let replacingReplace = urlMethod === 'replace' && transition.isCausedByAbortingReplaceTransition;
if (initial || replaceAndNotAborting || isQueryParamsRefreshTransition || replacingReplace) {
this.replaceURL(url);
} else {
this.updateURL(url);
}
}
}
finalizeQueryParamChange(resolvedHandlers, newQueryParams, transition) {
// We fire a finalizeQueryParamChange event which
// gives the new route hierarchy a chance to tell
// us which query params it's consuming and what
// their final values are. If a query param is
// no longer consumed in the final route hierarchy,
// its serialized segment will be removed
// from the URL.
for (let k in newQueryParams) {
if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) {
delete newQueryParams[k];
}
}
let finalQueryParamsArray = [];
this.triggerEvent(resolvedHandlers, true, 'finalizeQueryParamChange', [newQueryParams, finalQueryParamsArray, transition]);
if (transition) {
transition._visibleQueryParams = {};
}
let finalQueryParams = {};
for (let i = 0, len = finalQueryParamsArray.length; i < len; ++i) {
let qp = finalQueryParamsArray[i];
finalQueryParams[qp.key] = qp.value;
if (transition && qp.visible !== false) {
transition._visibleQueryParams[qp.key] = qp.value;
}
}
return finalQueryParams;
}
toReadOnlyInfos(newTransition, newState) {
let oldRouteInfos = this.state.routeInfos;
this.fromInfos(newTransition, oldRouteInfos);
this.toInfos(newTransition, newState.routeInfos);
this._lastQueryParams = newState.queryParams;
}
fromInfos(newTransition, oldRouteInfos) {
if (newTransition !== undefined && oldRouteInfos.length > 0) {
let fromInfos = toReadOnlyRouteInfo(oldRouteInfos, Object.assign({}, this._lastQueryParams), true);
newTransition.from = fromInfos[fromInfos.length - 1] || null;
}
}
toInfos(newTransition, newRouteInfos, includeAttributes = false) {
if (newTransition !== undefined && newRouteInfos.length > 0) {
let toInfos = toReadOnlyRouteInfo(newRouteInfos, Object.assign({}, newTransition[QUERY_PARAMS_SYMBOL]), includeAttributes);
newTransition.to = toInfos[toInfos.length - 1] || null;
}
}
notifyExistingHandlers(newState, newTransition) {
let oldRouteInfos = this.state.routeInfos,
i,
oldRouteInfoLen,
oldHandler,
newRouteInfo;
oldRouteInfoLen = oldRouteInfos.length;
for (i = 0; i < oldRouteInfoLen; i++) {
oldHandler = oldRouteInfos[i];
newRouteInfo = newState.routeInfos[i];
if (!newRouteInfo || oldHandler.name !== newRouteInfo.name) {
break;
}
if (!newRouteInfo.isResolved) {}
}
this.triggerEvent(oldRouteInfos, true, 'willTransition', [newTransition]);
this.routeWillChange(newTransition);
this.willTransition(oldRouteInfos, newState.routeInfos, newTransition);
}
/**
Clears the current and target route routes and triggers exit
on each of them starting at the leaf and traversing up through
its ancestors.
*/
reset() {
if (this.state) {
forEach(this.state.routeInfos.slice().reverse(), function (routeInfo) {
let route = routeInfo.route;
if (route !== undefined) {
if (route.exit !== undefined) {
route.exit();
}
}
return true;
});
}
this.oldState = undefined;
this.state = new TransitionState();
this.currentRouteInfos = undefined;
}
/**
let handler = routeInfo.handler;
The entry point for handling a change to the URL (usually
via the back and forward button).
Returns an Array of handlers and the parameters associated
with those parameters.
@param {String} url a URL to process
@return {Array} an Array of `[handler, parameter]` tuples
*/
handleURL(url) {
// Perform a URL-based transition, but don't change
// the URL afterward, since it already happened.
if (url.charAt(0) !== '/') {
url = '/' + url;
}
return this.doTransition(url).method(null);
}
/**
Transition into the specified named route.
If necessary, trigger the exit callback on any routes
that are no longer represented by the target route.
@param {String} name the name of the route
*/
transitionTo(name, ...contexts) {
if (typeof name === 'object') {
contexts.push(name);
return this.doTransition(undefined, contexts, false);
}
return this.doTransition(name, contexts);
}
intermediateTransitionTo(name, ...args) {
return this.doTransition(name, args, true);
}
refresh(pivotRoute) {
let previousTransition = this.activeTransition;
let state = previousTransition ? previousTransition[STATE_SYMBOL] : this.state;
let routeInfos = state.routeInfos;
if (pivotRoute === undefined) {
pivotRoute = routeInfos[0].route;
}
log(this, 'Starting a refresh transition');
let name = routeInfos[routeInfos.length - 1].name;
let intent = new NamedTransitionIntent(this, name, pivotRoute, [], this._changedQueryParams || state.queryParams);
let newTransition = this.transitionByIntent(intent, false);
// if the previous transition is a replace transition, that needs to be preserved
if (previousTransition && previousTransition.urlMethod === 'replace') {
newTransition.method(previousTransition.urlMethod);
}
return newTransition;
}
/**
Identical to `transitionTo` except that the current URL will be replaced
if possible.
This method is intended primarily for use with `replaceState`.
@param {String} name the name of the route
*/
replaceWith(name) {
return this.doTransition(name).method('replace');
}
/**
Take a named route and context objects and generate a
URL.
@param {String} name the name of the route to generate
a URL for
@param {...Object} objects a list of objects to serialize
@return {String} a URL
*/
generate(routeName, ...args) {
let partitionedArgs = extractQueryParams(args),
suppliedParams = partitionedArgs[0],
queryParams = partitionedArgs[1];
// Construct a TransitionIntent with the provided params
// and apply it to the present state of the router.
let intent = new NamedTransitionIntent(this, routeName, undefined, suppliedParams);
let state = intent.applyToState(this.state, false);
let params = {};
for (let i = 0, len = state.routeInfos.length; i < len; ++i) {
let routeInfo = state.routeInfos[i];
let routeParams = routeInfo.serialize();
merge(params, routeParams);
}
params.queryParams = queryParams;
return this.recognizer.generate(routeName, params);
}
applyIntent(routeName, contexts) {
let intent = new NamedTransitionIntent(this, routeName, undefined, contexts);
let state = this.activeTransition && this.activeTransition[STATE_SYMBOL] || this.state;
return intent.applyToState(state, false);
}
isActiveIntent(routeName, contexts, queryParams, _state) {
let state = _state || this.state,
targetRouteInfos = state.routeInfos,
routeInfo,
len;
if (!targetRouteInfos.length) {
return false;
}
let targetHandler = targetRouteInfos[targetRouteInfos.length - 1].name;
let recogHandlers = this.recognizer.handlersFor(targetHandler);
let index = 0;
for (len = recogHandlers.length; index < len; ++index) {
routeInfo = targetRouteInfos[index];
if (routeInfo.name === routeName) {
break;
}
}
if (index === recogHandlers.length) {
// The provided route name isn't even in the route hierarchy.
return false;
}
let testState = new TransitionState();
testState.routeInfos = targetRouteInfos.slice(0, index + 1);
recogHandlers = recogHandlers.slice(0, index + 1);
let intent = new NamedTransitionIntent(this, targetHandler, undefined, contexts);
let newState = intent.applyToHandlers(testState, recogHandlers, targetHandler, true, true);
let routesEqual = routeInfosEqual(newState.routeInfos, testState.routeInfos);
if (!queryParams || !routesEqual) {
return routesEqual;
}
// Get a hash of QPs that will still be active on new route
let activeQPsOnNewHandler = {};
merge(activeQPsOnNewHandler, queryParams);
let activeQueryParams = state.queryParams;
for (let key in activeQueryParams) {
if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) {
activeQPsOnNewHandler[key] = activeQueryParams[key];
}
}
return routesEqual && !getChangelist(activeQPsOnNewHandler, queryParams);
}
isActive(routeName, ...args) {
let partitionedArgs = extractQueryParams(args);
return this.isActiveIntent(routeName, partitionedArgs[0], partitionedArgs[1]);
}
trigger(name, ...args) {
this.triggerEvent(this.currentRouteInfos, false, name, args);
}
}
function routeInfosEqual(routeInfos, otherRouteInfos) {
if (routeInfos.length !== otherRouteInfos.length) {
return false;
}
for (let i = 0, len = routeInfos.length; i < len; ++i) {
if (routeInfos[i] !== otherRouteInfos[i]) {
return false;
}
}
return true;
}
function routeInfosSameExceptQueryParams(routeInfos, otherRouteInfos) {
if (routeInfos.length !== otherRouteInfos.length) {
return false;
}
for (let i = 0, len = routeInfos.length; i < len; ++i) {
if (routeInfos[i].name !== otherRouteInfos[i].name) {
return false;
}
if (!paramsEqual(routeInfos[i].params, otherRouteInfos[i].params)) {
return false;
}
}
return true;
}
function paramsEqual(params, otherParams) {
if (!params && !otherParams) {
return true;
} else if (!params && !!otherParams || !!params && !otherParams) {
// one is falsy but other is not;
return false;
}
let keys = Object.keys(params);
let otherKeys = Object.keys(otherParams);
if (keys.length !== otherKeys.length) {
return false;
}
for (let i = 0, len = keys.length; i < len; ++i) {
let key = keys[i];
if (params[key] !== otherParams[key]) {
return false;
}
}
return true;
}
exports.default = Router;
exports.InternalTransition = Transition;
exports.logAbort = logAbort;
exports.STATE_SYMBOL = STATE_SYMBOL;
exports.PARAMS_SYMBOL = PARAMS_SYMBOL;
exports.QUERY_PARAMS_SYMBOL = QUERY_PARAMS_SYMBOL;
exports.TransitionState = TransitionState;
exports.TransitionError = TransitionError;
exports.InternalRouteInfo = InternalRouteInfo;
});
enifed('rsvp', ['exports', 'node-module'], function (exports, _nodeModule) {
'use strict';
exports.filter = exports.async = exports.map = exports.reject = exports.resolve = exports.off = exports.on = exports.configure = exports.denodeify = exports.defer = exports.rethrow = exports.hashSettled = exports.hash = exports.race = exports.allSettled = exports.all = exports.EventTarget = exports.Promise = exports.cast = exports.asap = undefined;
function callbacksFor(object) {
let callbacks = object._promiseCallbacks;
if (!callbacks) {
callbacks = object._promiseCallbacks = {};
}
return callbacks;
}
/**
@class EventTarget
@for rsvp
@public
*/
var EventTarget = {
/**
`EventTarget.mixin` extends an object with EventTarget methods. For
Example:
```javascript
import EventTarget from 'rsvp';
let object = {};
EventTarget.mixin(object);
object.on('finished', function(event) {
// handle event
});
object.trigger('finished', { detail: value });
```
`EventTarget.mixin` also works with prototypes:
```javascript
import EventTarget from 'rsvp';
let Person = function() {};
EventTarget.mixin(Person.prototype);
let yehuda = new Person();
let tom = new Person();
yehuda.on('poke', function(event) {
console.log('Yehuda says OW');
});
tom.on('poke', function(event) {
console.log('Tom says OW');
});
yehuda.trigger('poke');
tom.trigger('poke');
```
@method mixin
@for rsvp
@private
@param {Object} object object to extend with EventTarget methods
*/
mixin(object) {
object.on = this.on;
object.off = this.off;
object.trigger = this.trigger;
object._promiseCallbacks = undefined;
return object;
},
/**
Registers a callback to be executed when `eventName` is triggered
```javascript
object.on('event', function(eventInfo){
// handle the event
});
object.trigger('event');
```
@method on
@for EventTarget
@private
@param {String} eventName name of the event to listen for
@param {Function} callback function to be called when the event is triggered.
*/
on(eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function');
}
let allCallbacks = callbacksFor(this);
let callbacks = allCallbacks[eventName];
if (!callbacks) {
callbacks = allCallbacks[eventName] = [];
}
if (callbacks.indexOf(callback) === -1) {
callbacks.push(callback);
}
},
/**
You can use `off` to stop firing a particular callback for an event:
```javascript
function doStuff() { // do stuff! }
object.on('stuff', doStuff);
object.trigger('stuff'); // doStuff will be called
// Unregister ONLY the doStuff callback
object.off('stuff', doStuff);
object.trigger('stuff'); // doStuff will NOT be called
```
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:
```javascript
let callback1 = function(){};
let callback2 = function(){};
object.on('stuff', callback1);
object.on('stuff', callback2);
object.trigger('stuff'); // callback1 and callback2 will be executed.
object.off('stuff');
object.trigger('stuff'); // callback1 and callback2 will not be executed!
```
@method off
@for rsvp
@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(eventName, callback) {
let allCallbacks = callbacksFor(this);
if (!callback) {
allCallbacks[eventName] = [];
return;
}
let callbacks = allCallbacks[eventName];
let index = callbacks.indexOf(callback);
if (index !== -1) {
callbacks.splice(index, 1);
}
},
/**
Use `trigger` to fire custom events. For example:
```javascript
object.on('foo', function(){
console.log('foo event happened!');
});
object.trigger('foo');
// 'foo event happened!' logged to the console
```
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
@private
@param {String} eventName name of the event to be triggered
@param {*} options optional value to be passed to any event handlers for
the given `eventName`
*/
trigger(eventName, options, label) {
let allCallbacks = callbacksFor(this);
let callbacks = allCallbacks[eventName];
if (callbacks) {
// Don't cache the callbacks.length since it may grow
let callback;
for (let i = 0; i < callbacks.length; i++) {
callback = callbacks[i];
callback(options, label);
}
}
}
};
const config = {
instrument: false
};
EventTarget['mixin'](config);
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
const queue = [];
function scheduleFlush() {
setTimeout(() => {
for (let i = 0; i < queue.length; i++) {
let entry = queue[i];
let payload = entry.payload;
payload.guid = payload.key + payload.id;
payload.childGuid = payload.key + payload.childId;
if (payload.error) {
payload.stack = payload.error.stack;
}
config['trigger'](entry.name, entry.payload);
}
queue.length = 0;
}, 50);
}
function instrument(eventName, promise, child) {
if (1 === queue.push({
name: eventName,
payload: {
key: promise._guidKey,
id: promise._id,
eventName: eventName,
detail: promise._result,
childId: child && child._id,
label: promise._label,
timeStamp: Date.now(),
error: config["instrument-with-stack"] ? new Error(promise._label) : null
} })) {
scheduleFlush();
}
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
import Promise from 'rsvp';
let promise = new 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
import Promise from 'rsvp';
let promise = RSVP.Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@for Promise
@static
@param {*} object 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`
*/
function resolve$$1(object, label) {
/*jshint validthis:true */
let Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
let promise = new Constructor(noop, label);
resolve$1(promise, object);
return promise;
}
function withOwnPromise() {
return new TypeError('A promises callback cannot return that same promise.');
}
function objectOrFunction(x) {
let type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function noop() {}
const PENDING = void 0;
const FULFILLED = 1;
const REJECTED = 2;
const TRY_CATCH_ERROR = { error: null };
function getThen(promise) {
try {
return promise.then;
} catch (error) {
TRY_CATCH_ERROR.error = error;
return TRY_CATCH_ERROR;
}
}
let tryCatchCallback;
function tryCatcher() {
try {
let target = tryCatchCallback;
tryCatchCallback = null;
return target.apply(this, arguments);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function tryCatch(fn) {
tryCatchCallback = fn;
return tryCatcher;
}
function handleForeignThenable(promise, thenable, then$$1) {
config.async(promise => {
let sealed = false;
let result = tryCatch(then$$1).call(thenable, value => {
if (sealed) {
return;
}
sealed = true;
if (thenable === value) {
fulfill(promise, value);
} else {
resolve$1(promise, value);
}
}, reason => {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && result === TRY_CATCH_ERROR) {
sealed = true;
let error = TRY_CATCH_ERROR.error;
TRY_CATCH_ERROR.error = null;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
thenable._onError = null;
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, value => {
if (thenable === value) {
fulfill(promise, value);
} else {
resolve$1(promise, value);
}
}, reason => reject(promise, reason));
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
let isOwnThenable = maybeThenable.constructor === promise.constructor && then$$1 === then && promise.constructor.resolve === resolve$$1;
if (isOwnThenable) {
handleOwnThenable(promise, maybeThenable);
} else if (then$$1 === TRY_CATCH_ERROR) {
let error = TRY_CATCH_ERROR.error;
TRY_CATCH_ERROR.error = null;
reject(promise, error);
} else if (typeof then$$1 === 'function') {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
function resolve$1(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onError) {
promise._onError(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length === 0) {
if (config.instrument) {
instrument('fulfilled', promise);
}
} else {
config.async(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
config.async(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
let subscribers = parent._subscribers;
let length = subscribers.length;
parent._onError = null;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
config.async(publish, parent);
}
}
function publish(promise) {
let subscribers = promise._subscribers;
let settled = promise._state;
if (config.instrument) {
instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);
}
if (subscribers.length === 0) {
return;
}
let child,
callback,
result = promise._result;
for (let i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, result);
} else {
callback(result);
}
}
promise._subscribers.length = 0;
}
function invokeCallback(state, promise, callback, result) {
let hasCallback = typeof callback === 'function';
let value;
if (hasCallback) {
value = tryCatch(callback)(result);
} else {
value = result;
}
if (promise._state !== PENDING) {
// noop
} else if (value === promise) {
reject(promise, withOwnPromise());
} else if (value === TRY_CATCH_ERROR) {
let error = TRY_CATCH_ERROR.error;
TRY_CATCH_ERROR.error = null; // release
reject(promise, error);
} else if (hasCallback) {
resolve$1(promise, value);
} else if (state === FULFILLED) {
fulfill(promise, value);
} else if (state === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
let resolved = false;
try {
resolver(value => {
if (resolved) {
return;
}
resolved = true;
resolve$1(promise, value);
}, reason => {
if (resolved) {
return;
}
resolved = true;
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
function then(onFulfillment, onRejection, label) {
let parent = this;
let state = parent._state;
if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
config.instrument && instrument('chained', parent, parent);
return parent;
}
parent._onError = null;
let child = new parent.constructor(noop, label);
let result = parent._result;
config.instrument && instrument('chained', parent, child);
if (state === PENDING) {
subscribe(parent, child, onFulfillment, onRejection);
} else {
let callback = state === FULFILLED ? onFulfillment : onRejection;
config.async(() => invokeCallback(state, child, callback, result));
}
return child;
}
class Enumerator {
constructor(Constructor, input, abortOnReject, label) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop, label);
this._abortOnReject = abortOnReject;
this._isUsingOwnPromise = Constructor === Promise;
this._isUsingOwnResolve = Constructor.resolve === resolve$$1;
this._init(...arguments);
}
_init(Constructor, input) {
let len = input.length || 0;
this.length = len;
this._remaining = len;
this._result = new Array(len);
this._enumerate(input);
}
_enumerate(input) {
let length = this.length;
let promise = this.promise;
for (let i = 0; promise._state === PENDING && i < length; i++) {
this._eachEntry(input[i], i, true);
}
this._checkFullfillment();
}
_checkFullfillment() {
if (this._remaining === 0) {
let result = this._result;
fulfill(this.promise, result);
this._result = null;
}
}
_settleMaybeThenable(entry, i, firstPass) {
let c = this._instanceConstructor;
if (this._isUsingOwnResolve) {
let then$$1 = getThen(entry);
if (then$$1 === then && entry._state !== PENDING) {
entry._onError = null;
this._settledAt(entry._state, i, entry._result, firstPass);
} else if (typeof then$$1 !== 'function') {
this._settledAt(FULFILLED, i, entry, firstPass);
} else if (this._isUsingOwnPromise) {
let promise = new c(noop);
handleMaybeThenable(promise, entry, then$$1);
this._willSettleAt(promise, i, firstPass);
} else {
this._willSettleAt(new c(resolve => resolve(entry)), i, firstPass);
}
} else {
this._willSettleAt(c.resolve(entry), i, firstPass);
}
}
_eachEntry(entry, i, firstPass) {
if (entry !== null && typeof entry === 'object') {
this._settleMaybeThenable(entry, i, firstPass);
} else {
this._setResultAt(FULFILLED, i, entry, firstPass);
}
}
_settledAt(state, i, value, firstPass) {
let promise = this.promise;
if (promise._state === PENDING) {
if (this._abortOnReject && state === REJECTED) {
reject(promise, value);
} else {
this._setResultAt(state, i, value, firstPass);
this._checkFullfillment();
}
}
}
_setResultAt(state, i, value, firstPass) {
this._remaining--;
this._result[i] = value;
}
_willSettleAt(promise, i, firstPass) {
subscribe(promise, undefined, value => this._settledAt(FULFILLED, i, value, firstPass), reason => this._settledAt(REJECTED, i, reason, firstPass));
}
}
function setSettledResult(state, i, value) {
this._remaining--;
if (state === FULFILLED) {
this._result[i] = {
state: 'fulfilled',
value: value
};
} else {
this._result[i] = {
state: 'rejected',
reason: value
};
}
}
/**
`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.
Example:
```javascript
import Promise, { resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
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
import Promise, { resolve, reject } from 'rsvp';
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for Promise
@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
*/
function all(entries, label) {
if (!Array.isArray(entries)) {
return this.reject(new TypeError("Promise.all must be called with an array"), label);
}
return new Enumerator(this, entries, true /* abort on reject */, label).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
import Promise from 'rsvp';
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`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
import Promise from 'rsvp';
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
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
import Promise from 'rsvp';
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@for Promise
@static
@param {Array} entries 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.
*/
function race(entries, label) {
/*jshint validthis:true */
let Constructor = this;
let promise = new Constructor(noop, label);
if (!Array.isArray(entries)) {
reject(promise, new TypeError('Promise.race must be called with an array'));
return promise;
}
for (let i = 0; promise._state === PENDING && i < entries.length; i++) {
subscribe(Constructor.resolve(entries[i]), undefined, value => resolve$1(promise, value), reason => reject(promise, reason));
}
return promise;
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
import Promise from 'rsvp';
let promise = new 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
import Promise from 'rsvp';
let promise = 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
@for Promise
@static
@param {*} 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`.
*/
function reject$1(reason, label) {
/*jshint validthis:true */
let Constructor = this;
let promise = new Constructor(noop, label);
reject(promise, reason);
return promise;
}
const guidKey = 'rsvp_' + Date.now() + '-';
let counter = 0;
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. 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.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@public
@param {function} resolver
@param {String} label optional string for labeling the promise.
Useful for tooling.
@constructor
*/
class Promise {
constructor(resolver, label) {
this._id = counter++;
this._label = label;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
config.instrument && instrument('created', this);
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
_onError(reason) {
config.after(() => {
if (this._onError) {
config.trigger('error', reason, this._label);
}
});
}
/**
`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(onRejection, label) {
return this.then(undefined, 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 findOtherAuthor();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuthor();
}).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(callback, label) {
let promise = this;
let constructor = promise.constructor;
if (typeof callback === 'function') {
return promise.then(value => constructor.resolve(callback()).then(() => value), reason => constructor.resolve(callback()).then(() => {
throw reason;
}));
}
return promise.then(callback, callback);
}
}
Promise.cast = resolve$$1; // deprecated
Promise.all = all;
Promise.race = race;
Promise.resolve = resolve$$1;
Promise.reject = reject$1;
Promise.prototype._guidKey = guidKey;
/**
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
});
```
Chaining
--------
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
let 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
let 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} onFulfillment
@param {Function} onRejection
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
Promise.prototype.then = then;
function makeObject(_, argumentNames) {
let obj = {};
let length = _.length;
let args = new Array(length);
for (let x = 0; x < length; x++) {
args[x] = _[x];
}
for (let i = 0; i < argumentNames.length; i++) {
let name = argumentNames[i];
obj[name] = args[i + 1];
}
return obj;
}
function arrayResult(_) {
let length = _.length;
let args = new Array(length - 1);
for (let i = 1; i < length; i++) {
args[i - 1] = _[i];
}
return args;
}
function wrapThenable(then, promise) {
return {
then(onFulFillment, onRejection) {
return then.call(promise, onFulFillment, onRejection);
}
};
}
/**
`denodeify` takes a 'node-style' function and returns a function that
will return an `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
let fs = require('fs');
fs.readFile('myfile.txt', function(err, data){
if (err) return handleError(err);
handleData(data);
});
```
into:
```javascript
let fs = require('fs');
let readFile = 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
let request = 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
let request = 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
let request = denodeify(require('request'), ['res', 'body']);
request('http://example.com').then(function(result) {
// result.res
// result.body
});
```
Sometimes you need to retain the `this`:
```javascript
let app = require('express')();
let render = 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
let request = 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
let 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
let fs = require('fs');
let readFile = denodeify(fs.readFile);
let writeFile = 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
@public
@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} [options] 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 a `Promise`
*/
function denodeify(nodeFunc, options) {
let fn = function () {
let l = arguments.length;
let args = new Array(l + 1);
let promiseInput = false;
for (let i = 0; i < l; ++i) {
let arg = arguments[i];
if (!promiseInput) {
// TODO: clean this up
promiseInput = needsPromiseInput(arg);
if (promiseInput === TRY_CATCH_ERROR) {
let error = TRY_CATCH_ERROR.error;
TRY_CATCH_ERROR.error = null;
let p = new Promise(noop);
reject(p, error);
return p;
} else if (promiseInput && promiseInput !== true) {
arg = wrapThenable(promiseInput, arg);
}
}
args[i] = arg;
}
let promise = new Promise(noop);
args[l] = function (err, val) {
if (err) {
reject(promise, err);
} else if (options === undefined) {
resolve$1(promise, val);
} else if (options === true) {
resolve$1(promise, arrayResult(arguments));
} else if (Array.isArray(options)) {
resolve$1(promise, makeObject(arguments, options));
} else {
resolve$1(promise, val);
}
};
if (promiseInput) {
return handlePromiseInput(promise, args, nodeFunc, this);
} else {
return handleValueInput(promise, args, nodeFunc, this);
}
};
fn.__proto__ = nodeFunc;
return fn;
}
function handleValueInput(promise, args, nodeFunc, self) {
let result = tryCatch(nodeFunc).apply(self, args);
if (result === TRY_CATCH_ERROR) {
let error = TRY_CATCH_ERROR.error;
TRY_CATCH_ERROR.error = null;
reject(promise, error);
}
return promise;
}
function handlePromiseInput(promise, args, nodeFunc, self) {
return Promise.all(args).then(args => handleValueInput(promise, args, nodeFunc, self));
}
function needsPromiseInput(arg) {
if (arg !== null && typeof arg === 'object') {
if (arg.constructor === Promise) {
return true;
} else {
return getThen(arg);
}
} else {
return false;
}
}
/**
This is a convenient alias for `Promise.all`.
@method all
@public
@static
@for rsvp
@param {Array} array Array of promises.
@param {String} label An optional label. This is useful
for tooling.
*/
function all$1(array, label) {
return Promise.all(array, label);
}
/**
@module rsvp
@public
**/
class AllSettled extends Enumerator {
constructor(Constructor, entries, label) {
super(Constructor, entries, false /* don't abort on reject */, label);
}
}
AllSettled.prototype._setResultAt = setSettledResult;
/**
`RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing
a fail-fast method, it waits until all the promises have returned and
shows you all the results. This is useful if you want to handle multiple
promises' failure states together as a set.
Returns a promise that is fulfilled when all the given promises have been
settled. The return promise is fulfilled with an array of the states of
the promises passed into the `promises` array argument.
Each state object will either indicate fulfillment or rejection, and
provide the corresponding value or reason. The states will take one of
the following formats:
```javascript
{ state: 'fulfilled', value: value }
or
{ state: 'rejected', reason: reason }
```
Example:
```javascript
let promise1 = RSVP.Promise.resolve(1);
let promise2 = RSVP.Promise.reject(new Error('2'));
let promise3 = RSVP.Promise.reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
RSVP.allSettled(promises).then(function(array){
// array == [
// { state: 'fulfilled', value: 1 },
// { state: 'rejected', reason: Error },
// { state: 'rejected', reason: Error }
// ]
// Note that for the second item, reason.message will be '2', and for the
// third item, reason.message will be '3'.
}, function(error) {
// Not run. (This block would only be called if allSettled had failed,
// for instance if passed an incorrect argument type.)
});
```
@method allSettled
@public
@static
@for rsvp
@param {Array} entries
@param {String} label - optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled with an array of the settled
states of the constituent promises.
*/
function allSettled(entries, label) {
if (!Array.isArray(entries)) {
return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label);
}
return new AllSettled(Promise, entries, label).promise;
}
/**
This is a convenient alias for `Promise.race`.
@method race
@public
@static
@for rsvp
@param {Array} array Array of promises.
@param {String} label An optional label. This is useful
for tooling.
*/
function race$1(array, label) {
return Promise.race(array, label);
}
class PromiseHash extends Enumerator {
constructor(Constructor, object, abortOnReject = true, label) {
super(Constructor, object, abortOnReject, label);
}
_init(Constructor, object) {
this._result = {};
this._enumerate(object);
}
_enumerate(input) {
let keys = Object.keys(input);
let length = keys.length;
let promise = this.promise;
this._remaining = length;
let key, val;
for (let i = 0; promise._state === PENDING && i < length; i++) {
key = keys[i];
val = input[key];
this._eachEntry(val, key, true);
}
this._checkFullfillment();
}
}
/**
`hash` is similar to `all`, but takes an object instead of an array
for its `promises` argument.
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The returned promise
is fulfilled with a hash that has the same key names as the `promises` object
argument. If any of the values in the object are not promises, they will
simply be copied over to the fulfilled object.
Example:
```javascript
let promises = {
myPromise: resolve(1),
yourPromise: resolve(2),
theirPromise: resolve(3),
notAPromise: 4
};
hash(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: 1,
// yourPromise: 2,
// theirPromise: 3,
// notAPromise: 4
// }
});
```
If any of the `promises` given to `hash` are rejected, the first promise
that is rejected will be given as the reason to the rejection handler.
Example:
```javascript
let promises = {
myPromise: resolve(1),
rejectedPromise: reject(new Error('rejectedPromise')),
anotherRejectedPromise: reject(new Error('anotherRejectedPromise')),
};
hash(promises).then(function(hash){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === 'rejectedPromise'
});
```
An important note: `hash` is intended for plain JavaScript objects that
are just a set of keys and values. `hash` will NOT preserve prototype
chains.
Example:
```javascript
import { hash, resolve } from 'rsvp';
function MyConstructor(){
this.example = resolve('Example');
}
MyConstructor.prototype = {
protoProperty: resolve('Proto Property')
};
let myObject = new MyConstructor();
hash(myObject).then(function(hash){
// protoProperty will not be present, instead you will just have an
// object that looks like:
// {
// example: 'Example'
// }
//
// hash.hasOwnProperty('protoProperty'); // false
// 'undefined' === typeof hash.protoProperty
});
```
@method hash
@public
@static
@for rsvp
@param {Object} object
@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.
*/
function hash(object, label) {
return Promise.resolve(object, label).then(function (object) {
if (object === null || typeof object !== 'object') {
throw new TypeError("Promise.hash must be called with an object");
}
return new PromiseHash(Promise, object, label).promise;
});
}
class HashSettled extends PromiseHash {
constructor(Constructor, object, label) {
super(Constructor, object, false, label);
}
}
HashSettled.prototype._setResultAt = setSettledResult;
/**
`hashSettled` is similar to `allSettled`, but takes an object
instead of an array for its `promises` argument.
Unlike `all` or `hash`, which implement a fail-fast method,
but like `allSettled`, `hashSettled` waits until all the
constituent promises have returned and then shows you all the results
with their states and values/reasons. This is useful if you want to
handle multiple promises' failure states together as a set.
Returns a promise that is fulfilled when all the given promises have been
settled, or rejected if the passed parameters are invalid.
The returned promise is fulfilled with a hash that has the same key names as
the `promises` object argument. If any of the values in the object are not
promises, they will be copied over to the fulfilled object and marked with state
'fulfilled'.
Example:
```javascript
import { hashSettled, resolve } from 'rsvp';
let promises = {
myPromise: resolve(1),
yourPromise: resolve(2),
theirPromise: resolve(3),
notAPromise: 4
};
hashSettled(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: { state: 'fulfilled', value: 1 },
// yourPromise: { state: 'fulfilled', value: 2 },
// theirPromise: { state: 'fulfilled', value: 3 },
// notAPromise: { state: 'fulfilled', value: 4 }
// }
});
```
If any of the `promises` given to `hash` are rejected, the state will
be set to 'rejected' and the reason for rejection provided.
Example:
```javascript
import { hashSettled, reject, resolve } from 'rsvp';
let promises = {
myPromise: resolve(1),
rejectedPromise: reject(new Error('rejection')),
anotherRejectedPromise: reject(new Error('more rejection')),
};
hashSettled(promises).then(function(hash){
// hash here is an object that looks like:
// {
// myPromise: { state: 'fulfilled', value: 1 },
// rejectedPromise: { state: 'rejected', reason: Error },
// anotherRejectedPromise: { state: 'rejected', reason: Error },
// }
// Note that for rejectedPromise, reason.message == 'rejection',
// and for anotherRejectedPromise, reason.message == 'more rejection'.
});
```
An important note: `hashSettled` is intended for plain JavaScript objects that
are just a set of keys and values. `hashSettled` will NOT preserve prototype
chains.
Example:
```javascript
import Promise, { hashSettled, resolve } from 'rsvp';
function MyConstructor(){
this.example = resolve('Example');
}
MyConstructor.prototype = {
protoProperty: Promise.resolve('Proto Property')
};
let myObject = new MyConstructor();
hashSettled(myObject).then(function(hash){
// protoProperty will not be present, instead you will just have an
// object that looks like:
// {
// example: { state: 'fulfilled', value: 'Example' }
// }
//
// hash.hasOwnProperty('protoProperty'); // false
// 'undefined' === typeof hash.protoProperty
});
```
@method hashSettled
@public
@for rsvp
@param {Object} object
@param {String} label optional string that describes the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when when all properties of `promises`
have been settled.
@static
*/
function hashSettled(object, label) {
return Promise.resolve(object, label).then(function (object) {
if (object === null || typeof object !== 'object') {
throw new TypeError("hashSettled must be called with an object");
}
return new HashSettled(Promise, object, false, label).promise;
});
}
/**
`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, `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
import { rethrow } from 'rsvp';
function throws(){
throw new Error('Whoops!');
}
let promise = new Promise(function(resolve, reject){
throws();
});
promise.catch(rethrow).then(function(){
// Code here doesn't run because the promise became rejected due to an
// error!
}, function (err){
// handle the error here
});
```
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.
@method rethrow
@public
@static
@for rsvp
@param {Error} reason reason the promise became rejected.
@throws Error
@static
*/
function rethrow(reason) {
setTimeout(() => {
throw reason;
});
throw reason;
}
/**
`defer` returns an object similar to jQuery's `$.Deferred`.
`defer` should be used when porting over code reliant on `$.Deferred`'s
interface. New code should use the `Promise` constructor instead.
The object returned from `defer` is a plain object with three properties:
* promise - an `Promise`.
* reject - a function that causes the `promise` property on this object to
become rejected
* resolve - a function that causes the `promise` property on this object to
become fulfilled.
Example:
```javascript
let deferred = defer();
deferred.resolve("Success!");
deferred.promise.then(function(value){
// value here is "Success!"
});
```
@method defer
@public
@static
@for rsvp
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Object}
*/
function defer(label) {
let deferred = { resolve: undefined, reject: undefined };
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
}, label);
return deferred;
}
class MapEnumerator extends Enumerator {
constructor(Constructor, entries, mapFn, label) {
super(Constructor, entries, true, label, mapFn);
}
_init(Constructor, input, bool, label, mapFn) {
let len = input.length || 0;
this.length = len;
this._remaining = len;
this._result = new Array(len);
this._mapFn = mapFn;
this._enumerate(input);
}
_setResultAt(state, i, value, firstPass) {
if (firstPass) {
let val = tryCatch(this._mapFn)(value, i);
if (val === TRY_CATCH_ERROR) {
this._settledAt(REJECTED, i, val.error, false);
} else {
this._eachEntry(val, i, false);
}
} else {
this._remaining--;
this._result[i] = value;
}
}
}
/**
`map` is similar to JavaScript's native `map` method. `mapFn` is eagerly called
meaning that as soon as any promise resolves its value will be passed to `mapFn`.
`map` returns a promise that will become fulfilled with the result of running
`mapFn` on the values the promises become fulfilled with.
For example:
```javascript
import { map, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
let mapFn = function(item){
return item + 1;
};
map(promises, mapFn).then(function(result){
// result is [ 2, 3, 4 ]
});
```
If any of the `promises` given to `map` are rejected, the first promise
that is rejected will be given as an argument to the returned promise's
rejection handler. For example:
```javascript
import { map, reject, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = reject(new Error('2'));
let promise3 = reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
let mapFn = function(item){
return item + 1;
};
map(promises, mapFn).then(function(array){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === '2'
});
```
`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
import { map } from 'rsvp';
let mapFn = function(blogPost){
// getComments does some ajax and returns an Promise that is fulfilled
// with some comments data
return getComments(blogPost.comments_url);
};
// getBlogPosts does some ajax and returns an Promise that is fulfilled
// with some blog post data
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
@public
@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.
*/
function map(promises, mapFn, label) {
if (typeof mapFn !== 'function') {
return Promise.reject(new TypeError("map expects a function as a second argument"), label);
}
return Promise.resolve(promises, label).then(function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError("map must be called with an array");
}
return new MapEnumerator(Promise, promises, mapFn, label).promise;
});
}
/**
This is a convenient alias for `Promise.resolve`.
@method resolve
@public
@static
@for rsvp
@param {*} 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`
*/
function resolve$2(value, label) {
return Promise.resolve(value, label);
}
/**
This is a convenient alias for `Promise.reject`.
@method reject
@public
@static
@for rsvp
@param {*} 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`.
*/
function reject$2(reason, label) {
return Promise.reject(reason, label);
}
const EMPTY_OBJECT = {};
class FilterEnumerator extends MapEnumerator {
_checkFullfillment() {
if (this._remaining === 0 && this._result !== null) {
let result = this._result.filter(val => val !== EMPTY_OBJECT);
fulfill(this.promise, result);
this._result = null;
}
}
_setResultAt(state, i, value, firstPass) {
if (firstPass) {
this._result[i] = value;
let val = tryCatch(this._mapFn)(value, i);
if (val === TRY_CATCH_ERROR) {
this._settledAt(REJECTED, i, val.error, false);
} else {
this._eachEntry(val, i, false);
}
} else {
this._remaining--;
if (!value) {
this._result[i] = EMPTY_OBJECT;
}
}
}
}
/**
`filter` is similar to JavaScript's native `filter` method.
`filterFn` is eagerly called meaning that as soon as any promise
resolves its value will be passed to `filterFn`. `filter` returns
a promise that will become fulfilled with the result of running
`filterFn` on the values the promises become fulfilled with.
For example:
```javascript
import { filter, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [promise1, promise2, promise3];
let filterFn = function(item){
return item > 1;
};
filter(promises, filterFn).then(function(result){
// result is [ 2, 3 ]
});
```
If any of the `promises` given to `filter` are rejected, the first promise
that is rejected will be given as an argument to the returned promise's
rejection handler. For example:
```javascript
import { filter, reject, resolve } from 'rsvp';
let promise1 = resolve(1);
let promise2 = reject(new Error('2'));
let promise3 = reject(new Error('3'));
let promises = [ promise1, promise2, promise3 ];
let filterFn = function(item){
return item > 1;
};
filter(promises, filterFn).then(function(array){
// Code here never runs because there are rejected promises!
}, function(reason) {
// reason.message === '2'
});
```
`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:
```javascript
import { filter, resolve } from 'rsvp';
let alice = { name: 'alice' };
let bob = { name: 'bob' };
let users = [ alice, bob ];
let promises = users.map(function(user){
return resolve(user);
});
let 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;
});
};
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;
});
```
@method filter
@public
@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}
*/
function filter(promises, filterFn, label) {
if (typeof filterFn !== 'function') {
return Promise.reject(new TypeError("filter expects function as a second argument"), label);
}
return Promise.resolve(promises, label).then(function (promises) {
if (!Array.isArray(promises)) {
throw new TypeError("filter must be called with an array");
}
return new FilterEnumerator(Promise, promises, filterFn, label).promise;
});
}
let len = 0;
let vertxNext;
function asap(callback, arg) {
queue$1[len] = callback;
queue$1[len + 1] = arg;
len += 2;
if (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.
scheduleFlush$1();
}
}
const browserWindow = typeof window !== 'undefined' ? window : undefined;
const browserGlobal = browserWindow || {};
const BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
const isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
const isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
let nextTick = process.nextTick;
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// setImmediate should be used instead instead
let version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);
if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {
nextTick = setImmediate;
}
return () => nextTick(flush);
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
let iterations = 0;
let observer = new BrowserMutationObserver(flush);
let node = document.createTextNode('');
observer.observe(node, { characterData: true });
return () => node.data = iterations = ++iterations % 2;
}
// web worker
function useMessageChannel() {
let channel = new MessageChannel();
channel.port1.onmessage = flush;
return () => channel.port2.postMessage(0);
}
function useSetTimeout() {
return () => setTimeout(flush, 1);
}
const queue$1 = new Array(1000);
function flush() {
for (let i = 0; i < len; i += 2) {
let callback = queue$1[i];
let arg = queue$1[i + 1];
callback(arg);
queue$1[i] = undefined;
queue$1[i + 1] = undefined;
}
len = 0;
}
function attemptVertex() {
try {
const vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
let scheduleFlush$1;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush$1 = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush$1 = useMutationObserver();
} else if (isWorker) {
scheduleFlush$1 = useMessageChannel();
} else if (browserWindow === undefined && typeof _nodeModule.require === 'function') {
scheduleFlush$1 = attemptVertex();
} else {
scheduleFlush$1 = useSetTimeout();
}
// defaults
config.async = asap;
config.after = cb => setTimeout(cb, 0);
const cast = resolve$2;
const async = (callback, arg) => config.async(callback, arg);
function on() {
config.on(...arguments);
}
function off() {
config.off(...arguments);
}
// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {
let callbacks = window['__PROMISE_INSTRUMENTATION__'];
configure('instrument', true);
for (let eventName in callbacks) {
if (callbacks.hasOwnProperty(eventName)) {
on(eventName, callbacks[eventName]);
}
}
}
// the default export here is for backwards compat:
// https://github.com/tildeio/rsvp.js/issues/434
var rsvp = {
asap,
cast,
Promise,
EventTarget,
all: all$1,
allSettled,
race: race$1,
hash,
hashSettled,
rethrow,
defer,
denodeify,
configure,
on,
off,
resolve: resolve$2,
reject: reject$2,
map,
async,
filter
};
exports.default = rsvp;
exports.asap = asap;
exports.cast = cast;
exports.Promise = Promise;
exports.EventTarget = EventTarget;
exports.all = all$1;
exports.allSettled = allSettled;
exports.race = race$1;
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$2;
exports.reject = reject$2;
exports.map = map;
exports.async = async;
exports.filter = filter;
});
requireModule('ember')
}());
//# sourceMappingURL=ember.prod.map