diff --git a/UI/WebServerResources/js/vendor/angular-ui-router.js b/UI/WebServerResources/js/vendor/angular-ui-router.js index 0c60a51fd..384afc941 100644 --- a/UI/WebServerResources/js/vendor/angular-ui-router.js +++ b/UI/WebServerResources/js/vendor/angular-ui-router.js @@ -4,350 +4,368 @@ * This causes it to be incompatible with plugins that depend on @uirouter/core. * We recommend switching to the ui-router-core.js and ui-router-angularjs.js bundles instead. * For more information, see https://ui-router.github.io/blog/uirouter-for-angularjs-umd-bundles - * @version v1.0.15 + * @version v1.0.17 * @link https://ui-router.github.io * @license MIT License, http://www.opensource.org/licenses/MIT */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('angular')) : - typeof define === 'function' && define.amd ? define(['exports', 'angular'], factory) : - (factory((global['@uirouter/angularjs'] = {}),global.angular)); -}(this, (function (exports,ng_from_import) { 'use strict'; +(function(global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' + ? factory(exports, require('angular')) + : typeof define === 'function' && define.amd + ? define(['exports', 'angular'], factory) + : factory((global['@uirouter/angularjs'] = {}), global.angular); +})(this, function(exports, ng_from_import) { + 'use strict'; -var ng_from_global = angular; -var ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global; + var ng_from_global = angular; + var ng = ng_from_import && ng_from_import.module ? ng_from_import : ng_from_global; /** */ -/** - * Higher order functions - * - * These utility functions are exported, but are subject to change without notice. - * - * @module common_hof - */ /** */ -/** - * Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function. - * - * Given a function with N parameters, returns a new function that supports partial application. - * The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters, - * where M is less than N, it returns a new function that accepts the remaining parameters. It continues to - * accept more parameters until all N parameters have been supplied. - * - * - * This contrived example uses a partially applied function as an predicate, which returns true - * if an object is found in both arrays. - * @example - * ``` - * // returns true if an object is in both of the two arrays - * function inBoth(array1, array2, object) { - * return array1.indexOf(object) !== -1 && - * array2.indexOf(object) !== 1; - * } - * let obj1, obj2, obj3, obj4, obj5, obj6, obj7 - * let foos = [obj1, obj3] - * let bars = [obj3, obj4, obj5] - * - * // A curried "copy" of inBoth - * let curriedInBoth = curry(inBoth); - * // Partially apply both the array1 and array2 - * let inFoosAndBars = curriedInBoth(foos, bars); - * - * // Supply the final argument; since all arguments are - * // supplied, the original inBoth function is then called. - * let obj1InBoth = inFoosAndBars(obj1); // false - * - * // Use the inFoosAndBars as a predicate. - * // Filter, on each iteration, supplies the final argument - * let allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ]; - * let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ] - * - * ``` - * - * Stolen from: http://stackoverflow.com/questions/4394747/javascript-curry-function - * - * @param fn - * @returns {*|function(): (*|any)} - */ -function curry(fn) { + /** + * Higher order functions + * + * These utility functions are exported, but are subject to change without notice. + * + * @module common_hof + */ /** + * Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function. + * + * Given a function with N parameters, returns a new function that supports partial application. + * The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters, + * where M is less than N, it returns a new function that accepts the remaining parameters. It continues to + * accept more parameters until all N parameters have been supplied. + * + * + * This contrived example uses a partially applied function as an predicate, which returns true + * if an object is found in both arrays. + * @example + * ``` + * // returns true if an object is in both of the two arrays + * function inBoth(array1, array2, object) { + * return array1.indexOf(object) !== -1 && + * array2.indexOf(object) !== 1; + * } + * let obj1, obj2, obj3, obj4, obj5, obj6, obj7 + * let foos = [obj1, obj3] + * let bars = [obj3, obj4, obj5] + * + * // A curried "copy" of inBoth + * let curriedInBoth = curry(inBoth); + * // Partially apply both the array1 and array2 + * let inFoosAndBars = curriedInBoth(foos, bars); + * + * // Supply the final argument; since all arguments are + * // supplied, the original inBoth function is then called. + * let obj1InBoth = inFoosAndBars(obj1); // false + * + * // Use the inFoosAndBars as a predicate. + * // Filter, on each iteration, supplies the final argument + * let allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ]; + * let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ] + * + * ``` + * + * Stolen from: http://stackoverflow.com/questions/4394747/javascript-curry-function + * + * @param fn + * @returns {*|function(): (*|any)} + */ + function curry(fn) { var initial_args = [].slice.apply(arguments, [1]); var func_args_length = fn.length; function curried(args) { - if (args.length >= func_args_length) - return fn.apply(null, args); - return function () { - return curried(args.concat([].slice.apply(arguments))); - }; + if (args.length >= func_args_length) return fn.apply(null, args); + return function() { + return curried(args.concat([].slice.apply(arguments))); + }; } return curried(initial_args); -} -/** - * Given a varargs list of functions, returns a function that composes the argument functions, right-to-left - * given: f(x), g(x), h(x) - * let composed = compose(f,g,h) - * then, composed is: f(g(h(x))) - */ -function compose() { + } + /** + * Given a varargs list of functions, returns a function that composes the argument functions, right-to-left + * given: f(x), g(x), h(x) + * let composed = compose(f,g,h) + * then, composed is: f(g(h(x))) + */ + function compose() { var args = arguments; var start = args.length - 1; - return function () { - var i = start, result = args[start].apply(this, arguments); - while (i--) - result = args[i].call(this, result); - return result; + return function() { + var i = start, + result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; }; -} -/** - * Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right - * given: f(x), g(x), h(x) - * let piped = pipe(f,g,h); - * then, piped is: h(g(f(x))) - */ -function pipe() { + } + /** + * Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right + * given: f(x), g(x), h(x) + * let piped = pipe(f,g,h); + * then, piped is: h(g(f(x))) + */ + function pipe() { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { - funcs[_i] = arguments[_i]; + funcs[_i] = arguments[_i]; } return compose.apply(null, [].slice.call(arguments).reverse()); -} -/** - * Given a property name, returns a function that returns that property from an object - * let obj = { foo: 1, name: "blarg" }; - * let getName = prop("name"); - * getName(obj) === "blarg" - */ -var prop = function (name) { - return function (obj) { return obj && obj[name]; }; -}; -/** - * Given a property name and a value, returns a function that returns a boolean based on whether - * the passed object has a property that matches the value - * let obj = { foo: 1, name: "blarg" }; - * let getName = propEq("name", "blarg"); - * getName(obj) === true - */ -var propEq = curry(function (name, _val, obj) { return obj && obj[name] === _val; }); -/** - * Given a dotted property name, returns a function that returns a nested property from an object, or undefined - * let obj = { id: 1, nestedObj: { foo: 1, name: "blarg" }, }; - * let getName = prop("nestedObj.name"); - * getName(obj) === "blarg" - * let propNotFound = prop("this.property.doesnt.exist"); - * propNotFound(obj) === undefined - */ -var parse = function (name) { + } + /** + * Given a property name, returns a function that returns that property from an object + * let obj = { foo: 1, name: "blarg" }; + * let getName = prop("name"); + * getName(obj) === "blarg" + */ + var prop = function(name) { + return function(obj) { + return obj && obj[name]; + }; + }; + /** + * Given a property name and a value, returns a function that returns a boolean based on whether + * the passed object has a property that matches the value + * let obj = { foo: 1, name: "blarg" }; + * let getName = propEq("name", "blarg"); + * getName(obj) === true + */ + var propEq = curry(function(name, _val, obj) { + return obj && obj[name] === _val; + }); + /** + * Given a dotted property name, returns a function that returns a nested property from an object, or undefined + * let obj = { id: 1, nestedObj: { foo: 1, name: "blarg" }, }; + * let getName = prop("nestedObj.name"); + * getName(obj) === "blarg" + * let propNotFound = prop("this.property.doesnt.exist"); + * propNotFound(obj) === undefined + */ + var parse = function(name) { return pipe.apply(null, name.split('.').map(prop)); -}; -/** - * Given a function that returns a truthy or falsey value, returns a - * function that returns the opposite (falsey or truthy) value given the same inputs - */ -var not = function (fn) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return !fn.apply(null, args); + }; + /** + * Given a function that returns a truthy or falsey value, returns a + * function that returns the opposite (falsey or truthy) value given the same inputs + */ + var not = function(fn) { + return function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return !fn.apply(null, args); }; -}; -/** - * Given two functions that return truthy or falsey values, returns a function that returns truthy - * if both functions return truthy for the given arguments - */ -function and(fn1, fn2) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return fn1.apply(null, args) && fn2.apply(null, args); + }; + /** + * Given two functions that return truthy or falsey values, returns a function that returns truthy + * if both functions return truthy for the given arguments + */ + function and(fn1, fn2) { + return function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return fn1.apply(null, args) && fn2.apply(null, args); }; -} -/** - * Given two functions that return truthy or falsey values, returns a function that returns truthy - * if at least one of the functions returns truthy for the given arguments - */ -function or(fn1, fn2) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return fn1.apply(null, args) || fn2.apply(null, args); + } + /** + * Given two functions that return truthy or falsey values, returns a function that returns truthy + * if at least one of the functions returns truthy for the given arguments + */ + function or(fn1, fn2) { + return function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return fn1.apply(null, args) || fn2.apply(null, args); }; -} -/** - * Check if all the elements of an array match a predicate function - * - * @param fn1 a predicate function `fn1` - * @returns a function which takes an array and returns true if `fn1` is true for all elements of the array - */ -var all = function (fn1) { - return function (arr) { return arr.reduce(function (b, x) { return b && !!fn1(x); }, true); }; -}; -// tslint:disable-next-line:variable-name -var any = function (fn1) { - return function (arr) { return arr.reduce(function (b, x) { return b || !!fn1(x); }, false); }; -}; -/** Given a class, returns a Predicate function that returns true if the object is of that class */ -var is = function (ctor) { - return function (obj) { - return (obj != null && obj.constructor === ctor || obj instanceof ctor); + } + /** + * Check if all the elements of an array match a predicate function + * + * @param fn1 a predicate function `fn1` + * @returns a function which takes an array and returns true if `fn1` is true for all elements of the array + */ + var all = function(fn1) { + return function(arr) { + return arr.reduce(function(b, x) { + return b && !!fn1(x); + }, true); }; -}; -/** Given a value, returns a Predicate function that returns true if another value is === equal to the original value */ -var eq = function (value) { return function (other) { - return value === other; -}; }; -/** Given a value, returns a function which returns the value */ -var val = function (v) { return function () { return v; }; }; -function invoke(fnName, args) { - return function (obj) { - return obj[fnName].apply(obj, args); + }; + // tslint:disable-next-line:variable-name + var any = function(fn1) { + return function(arr) { + return arr.reduce(function(b, x) { + return b || !!fn1(x); + }, false); }; -} -/** - * Sorta like Pattern Matching (a functional programming conditional construct) - * - * See http://c2.com/cgi/wiki?PatternMatching - * - * This is a conditional construct which allows a series of predicates and output functions - * to be checked and then applied. Each predicate receives the input. If the predicate - * returns truthy, then its matching output function (mapping function) is provided with - * the input and, then the result is returned. - * - * Each combination (2-tuple) of predicate + output function should be placed in an array - * of size 2: [ predicate, mapFn ] - * - * These 2-tuples should be put in an outer array. - * - * @example - * ``` - * - * // Here's a 2-tuple where the first element is the isString predicate - * // and the second element is a function that returns a description of the input - * let firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ]; - * - * // Second tuple: predicate "isNumber", mapfn returns a description - * let secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ]; - * - * let third = [ (input) => input === null, (input) => `Oh, null...` ]; - * - * let fourth = [ (input) => input === undefined, (input) => `notdefined` ]; - * - * let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]); - * - * console.log(descriptionOf(undefined)); // 'notdefined' - * console.log(descriptionOf(55)); // '(55) That's a number!' - * console.log(descriptionOf("foo")); // 'Here's your string foo' - * ``` - * - * @param struct A 2D array. Each element of the array should be an array, a 2-tuple, - * with a Predicate and a mapping/output function - * @returns {function(any): *} - */ -function pattern(struct) { - return function (x) { - for (var i = 0; i < struct.length; i++) { - if (struct[i][0](x)) - return struct[i][1](x); - } + }; + /** Given a class, returns a Predicate function that returns true if the object is of that class */ + var is = function(ctor) { + return function(obj) { + return (obj != null && obj.constructor === ctor) || obj instanceof ctor; }; -} + }; + /** Given a value, returns a Predicate function that returns true if another value is === equal to the original value */ + var eq = function(value) { + return function(other) { + return value === other; + }; + }; + /** Given a value, returns a function which returns the value */ + var val = function(v) { + return function() { + return v; + }; + }; + function invoke(fnName, args) { + return function(obj) { + return obj[fnName].apply(obj, args); + }; + } + /** + * Sorta like Pattern Matching (a functional programming conditional construct) + * + * See http://c2.com/cgi/wiki?PatternMatching + * + * This is a conditional construct which allows a series of predicates and output functions + * to be checked and then applied. Each predicate receives the input. If the predicate + * returns truthy, then its matching output function (mapping function) is provided with + * the input and, then the result is returned. + * + * Each combination (2-tuple) of predicate + output function should be placed in an array + * of size 2: [ predicate, mapFn ] + * + * These 2-tuples should be put in an outer array. + * + * @example + * ``` + * + * // Here's a 2-tuple where the first element is the isString predicate + * // and the second element is a function that returns a description of the input + * let firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ]; + * + * // Second tuple: predicate "isNumber", mapfn returns a description + * let secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ]; + * + * let third = [ (input) => input === null, (input) => `Oh, null...` ]; + * + * let fourth = [ (input) => input === undefined, (input) => `notdefined` ]; + * + * let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]); + * + * console.log(descriptionOf(undefined)); // 'notdefined' + * console.log(descriptionOf(55)); // '(55) That's a number!' + * console.log(descriptionOf("foo")); // 'Here's your string foo' + * ``` + * + * @param struct A 2D array. Each element of the array should be an array, a 2-tuple, + * with a Predicate and a mapping/output function + * @returns {function(any): *} + */ + function pattern(struct) { + return function(x) { + for (var i = 0; i < struct.length; i++) { + if (struct[i][0](x)) return struct[i][1](x); + } + }; + } -/** - * @coreapi - * @module core - */ -/** - * Matches state names using glob-like pattern strings. - * - * Globs can be used in specific APIs including: - * - * - [[StateService.is]] - * - [[StateService.includes]] - * - The first argument to Hook Registration functions like [[TransitionService.onStart]] - * - [[HookMatchCriteria]] and [[HookMatchCriterion]] - * - * A `Glob` string is a pattern which matches state names. - * Nested state names are split into segments (separated by a dot) when processing. - * The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz'] - * - * Globs work according to the following rules: - * - * ### Exact match: - * - * The glob `'A.B'` matches the state named exactly `'A.B'`. - * - * | Glob |Matches states named|Does not match state named| - * |:------------|:--------------------|:---------------------| - * | `'A'` | `'A'` | `'B'` , `'A.C'` | - * | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` | - * | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`| - * - * ### Single star (`*`) - * - * A single star (`*`) is a wildcard that matches exactly one segment. - * - * | Glob |Matches states named |Does not match state named | - * |:------------|:---------------------|:--------------------------| - * | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` | - * | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` | - * | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`| - * - * ### Double star (`**`) - * - * A double star (`'**'`) is a wildcard that matches *zero or more segments* - * - * | Glob |Matches states named |Does not match state named | - * |:------------|:----------------------------------------------|:----------------------------------| - * | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) | - * | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` | - * | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` | - * | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` | - * - */ -var Glob = /** @class */ (function () { + /** + * @coreapi + * @module core + */ + /** + * Matches state names using glob-like pattern strings. + * + * Globs can be used in specific APIs including: + * + * - [[StateService.is]] + * - [[StateService.includes]] + * - The first argument to Hook Registration functions like [[TransitionService.onStart]] + * - [[HookMatchCriteria]] and [[HookMatchCriterion]] + * + * A `Glob` string is a pattern which matches state names. + * Nested state names are split into segments (separated by a dot) when processing. + * The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz'] + * + * Globs work according to the following rules: + * + * ### Exact match: + * + * The glob `'A.B'` matches the state named exactly `'A.B'`. + * + * | Glob |Matches states named|Does not match state named| + * |:------------|:--------------------|:---------------------| + * | `'A'` | `'A'` | `'B'` , `'A.C'` | + * | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` | + * | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`| + * + * ### Single star (`*`) + * + * A single star (`*`) is a wildcard that matches exactly one segment. + * + * | Glob |Matches states named |Does not match state named | + * |:------------|:---------------------|:--------------------------| + * | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` | + * | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` | + * | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`| + * + * ### Double star (`**`) + * + * A double star (`'**'`) is a wildcard that matches *zero or more segments* + * + * | Glob |Matches states named |Does not match state named | + * |:------------|:----------------------------------------------|:----------------------------------| + * | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) | + * | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` | + * | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` | + * | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` | + * + */ + var Glob = /** @class */ (function() { function Glob(text) { - this.text = text; - this.glob = text.split('.'); - var regexpString = this.text.split('.') - .map(function (seg) { - if (seg === '**') - return '(?:|(?:\\.[^.]*)*)'; - if (seg === '*') - return '\\.[^.]*'; - return '\\.' + seg; - }).join(''); - this.regexp = new RegExp('^' + regexpString + '$'); + this.text = text; + this.glob = text.split('.'); + var regexpString = this.text + .split('.') + .map(function(seg) { + if (seg === '**') return '(?:|(?:\\.[^.]*)*)'; + if (seg === '*') return '\\.[^.]*'; + return '\\.' + seg; + }) + .join(''); + this.regexp = new RegExp('^' + regexpString + '$'); } /** Returns true if the string has glob-like characters in it */ - Glob.is = function (text) { - return !!/[!,*]+/.exec(text); + Glob.is = function(text) { + return !!/[!,*]+/.exec(text); }; /** Returns a glob from the string, or null if the string isn't Glob-like */ - Glob.fromString = function (text) { - return Glob.is(text) ? new Glob(text) : null; + Glob.fromString = function(text) { + return Glob.is(text) ? new Glob(text) : null; }; - Glob.prototype.matches = function (name) { - return this.regexp.test('.' + name); + Glob.prototype.matches = function(name) { + return this.regexp.test('.' + name); }; return Glob; -}()); + })(); -/** - * Internal representation of a UI-Router state. - * - * Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]]. - * - * A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object. - * - * This class prototypally inherits from the corresponding [[StateDeclaration]]. - * Each of its own properties (i.e., `hasOwnProperty`) are built using builders from the [[StateBuilder]]. - */ -var StateObject = /** @class */ (function () { + /** + * Internal representation of a UI-Router state. + * + * Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]]. + * + * A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object. + * + * This class prototypally inherits from the corresponding [[StateDeclaration]]. + * Each of its own properties (i.e., `hasOwnProperty`) are built using builders from the [[StateBuilder]]. + */ + var StateObject = /** @class */ (function() { /** @deprecated use State.create() */ function StateObject(config) { - return StateObject.create(config || {}); + return StateObject.create(config || {}); } /** * Create a state object to put the private/internal implementation details onto. @@ -357,15 +375,17 @@ var StateObject = /** @class */ (function () { * @param stateDecl the user-supplied State Declaration * @returns {StateObject} an internal State object */ - StateObject.create = function (stateDecl) { - stateDecl = StateObject.isStateClass(stateDecl) ? new stateDecl() : stateDecl; - var state = inherit(inherit(stateDecl, StateObject.prototype)); - stateDecl.$$state = function () { return state; }; - state.self = stateDecl; - state.__stateObjectCache = { - nameGlob: Glob.fromString(state.name), - }; + StateObject.create = function(stateDecl) { + stateDecl = StateObject.isStateClass(stateDecl) ? new stateDecl() : stateDecl; + var state = inherit(inherit(stateDecl, StateObject.prototype)); + stateDecl.$$state = function() { return state; + }; + state.self = stateDecl; + state.__stateObjectCache = { + nameGlob: Glob.fromString(state.name), + }; + return state; }; /** * Returns true if the provided parameter is the same state. @@ -378,26 +398,25 @@ var StateObject = /** @class */ (function () { * into `$stateProvider.state()`, (c) the fully-qualified name of a state as a string. * @returns Returns `true` if `ref` matches the current `State` instance. */ - StateObject.prototype.is = function (ref) { - return this === ref || this.self === ref || this.fqn() === ref; + StateObject.prototype.is = function(ref) { + return this === ref || this.self === ref || this.fqn() === ref; }; /** * @deprecated this does not properly handle dot notation * @returns Returns a dot-separated name of the state. */ - StateObject.prototype.fqn = function () { - if (!this.parent || !(this.parent instanceof this.constructor)) - return this.name; - var name = this.parent.fqn(); - return name ? name + '.' + this.name : this.name; + StateObject.prototype.fqn = function() { + if (!this.parent || !(this.parent instanceof this.constructor)) return this.name; + var name = this.parent.fqn(); + return name ? name + '.' + this.name : this.name; }; /** * Returns the root node of this state's tree. * * @returns The root of this state's tree. */ - StateObject.prototype.root = function () { - return this.parent && this.parent.root() || this; + StateObject.prototype.root = function() { + return (this.parent && this.parent.root()) || this; }; /** * Gets the state's `Param` objects @@ -408,11 +427,12 @@ var StateObject = /** @class */ (function () { * * @param opts options */ - StateObject.prototype.parameters = function (opts) { - opts = defaults(opts, { inherit: true, matchingKeys: null }); - var inherited = opts.inherit && this.parent && this.parent.parameters() || []; - return inherited.concat(values(this.params)) - .filter(function (param) { return !opts.matchingKeys || opts.matchingKeys.hasOwnProperty(param.id); }); + StateObject.prototype.parameters = function(opts) { + opts = defaults(opts, { inherit: true, matchingKeys: null }); + var inherited = (opts.inherit && this.parent && this.parent.parameters()) || []; + return inherited.concat(values(this.params)).filter(function(param) { + return !opts.matchingKeys || opts.matchingKeys.hasOwnProperty(param.id); + }); }; /** * Returns a single [[Param]] that is owned by the state @@ -421,718 +441,806 @@ var StateObject = /** @class */ (function () { * @param id the name of the [[Param]] to return * @param opts options */ - StateObject.prototype.parameter = function (id, opts) { - if (opts === void 0) { opts = {}; } - return (this.url && this.url.parameter(id, opts) || - find(values(this.params), propEq('id', id)) || - opts.inherit && this.parent && this.parent.parameter(id)); + StateObject.prototype.parameter = function(id, opts) { + if (opts === void 0) { + opts = {}; + } + return ( + (this.url && this.url.parameter(id, opts)) || + find(values(this.params), propEq('id', id)) || + (opts.inherit && this.parent && this.parent.parameter(id)) + ); }; - StateObject.prototype.toString = function () { - return this.fqn(); + StateObject.prototype.toString = function() { + return this.fqn(); }; /** Predicate which returns true if the object is an class with @State() decorator */ - StateObject.isStateClass = function (stateDecl) { - return isFunction(stateDecl) && stateDecl['__uiRouterState'] === true; + StateObject.isStateClass = function(stateDecl) { + return isFunction(stateDecl) && stateDecl['__uiRouterState'] === true; }; /** Predicate which returns true if the object is an internal [[StateObject]] object */ - StateObject.isState = function (obj) { - return isObject(obj['__stateObjectCache']); + StateObject.isState = function(obj) { + return isObject(obj['__stateObjectCache']); }; return StateObject; -}()); + })(); -/** Predicates - * - * These predicates return true/false based on the input. - * Although these functions are exported, they are subject to change without notice. - * - * @module common_predicates - */ -/** */ -var toStr = Object.prototype.toString; -var tis = function (t) { return function (x) { return typeof (x) === t; }; }; -var isUndefined = tis('undefined'); -var isDefined = not(isUndefined); -var isNull = function (o) { return o === null; }; -var isNullOrUndefined = or(isNull, isUndefined); -var isFunction = tis('function'); -var isNumber = tis('number'); -var isString = tis('string'); -var isObject = function (x) { return x !== null && typeof x === 'object'; }; -var isArray = Array.isArray; -var isDate = (function (x) { return toStr.call(x) === '[object Date]'; }); -var isRegExp = (function (x) { return toStr.call(x) === '[object RegExp]'; }); -var isState = StateObject.isState; -/** - * Predicate which checks if a value is injectable - * - * A value is "injectable" if it is a function, or if it is an ng1 array-notation-style array - * where all the elements in the array are Strings, except the last one, which is a Function - */ -function isInjectable(val$$1) { + /** Predicates + * + * These predicates return true/false based on the input. + * Although these functions are exported, they are subject to change without notice. + * + * @module common_predicates + */ + var toStr = Object.prototype.toString; + var tis = function(t) { + return function(x) { + return typeof x === t; + }; + }; + var isUndefined = tis('undefined'); + var isDefined = not(isUndefined); + var isNull = function(o) { + return o === null; + }; + var isNullOrUndefined = or(isNull, isUndefined); + var isFunction = tis('function'); + var isNumber = tis('number'); + var isString = tis('string'); + var isObject = function(x) { + return x !== null && typeof x === 'object'; + }; + var isArray = Array.isArray; + var isDate = function(x) { + return toStr.call(x) === '[object Date]'; + }; + var isRegExp = function(x) { + return toStr.call(x) === '[object RegExp]'; + }; + var isState = StateObject.isState; + /** + * Predicate which checks if a value is injectable + * + * A value is "injectable" if it is a function, or if it is an ng1 array-notation-style array + * where all the elements in the array are Strings, except the last one, which is a Function + */ + function isInjectable(val$$1) { if (isArray(val$$1) && val$$1.length) { - var head = val$$1.slice(0, -1), tail = val$$1.slice(-1); - return !(head.filter(not(isString)).length || tail.filter(not(isFunction)).length); + var head = val$$1.slice(0, -1), + tail = val$$1.slice(-1); + return !(head.filter(not(isString)).length || tail.filter(not(isFunction)).length); } return isFunction(val$$1); -} -/** - * Predicate which checks if a value looks like a Promise - * - * It is probably a Promise if it's an object, and it has a `then` property which is a Function - */ -var isPromise = and(isObject, pipe(prop('then'), isFunction)); + } + /** + * Predicate which checks if a value looks like a Promise + * + * It is probably a Promise if it's an object, and it has a `then` property which is a Function + */ + var isPromise = and(isObject, pipe(prop('then'), isFunction)); -var notImplemented = function (fnname) { return function () { - throw new Error(fnname + "(): No coreservices implementation for UI-Router is loaded."); -}; }; -var services = { + var notImplemented = function(fnname) { + return function() { + throw new Error(fnname + '(): No coreservices implementation for UI-Router is loaded.'); + }; + }; + var services = { $q: undefined, $injector: undefined, -}; + }; -/** - * Random utility functions used in the UI-Router code - * - * These functions are exported, but are subject to change without notice. - * - * @preferred - * @module common - */ -/** for typedoc */ -var root = (typeof self === 'object' && self.self === self && self) || - (typeof global === 'object' && global.global === global && global) || undefined; -var angular$1 = root.angular || {}; -var fromJson = angular$1.fromJson || JSON.parse.bind(JSON); -var toJson = angular$1.toJson || JSON.stringify.bind(JSON); -var forEach = angular$1.forEach || _forEach; -var extend = Object.assign || _extend; -var equals = angular$1.equals || _equals; -function identity(x) { return x; } -function noop() { } -/** - * Builds proxy functions on the `to` object which pass through to the `from` object. - * - * For each key in `fnNames`, creates a proxy function on the `to` object. - * The proxy function calls the real function on the `from` object. - * - * - * #### Example: - * This example creates an new class instance whose functions are prebound to the new'd object. - * ```js - * class Foo { - * constructor(data) { - * // Binds all functions from Foo.prototype to 'this', - * // then copies them to 'this' - * bindFunctions(Foo.prototype, this, this); - * this.data = data; - * } - * - * log() { - * console.log(this.data); - * } - * } - * - * let myFoo = new Foo([1,2,3]); - * var logit = myFoo.log; - * logit(); // logs [1, 2, 3] from the myFoo 'this' instance - * ``` - * - * #### Example: - * This example creates a bound version of a service function, and copies it to another object - * ``` - * - * var SomeService = { - * this.data = [3, 4, 5]; - * this.log = function() { - * console.log(this.data); - * } - * } - * - * // Constructor fn - * function OtherThing() { - * // Binds all functions from SomeService to SomeService, - * // then copies them to 'this' - * bindFunctions(SomeService, this, SomeService); - * } - * - * let myOtherThing = new OtherThing(); - * myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this' - * ``` - * - * @param source A function that returns the source object which contains the original functions to be bound - * @param target A function that returns the target object which will receive the bound functions - * @param bind A function that returns the object which the functions will be bound to - * @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object) - * @param latebind If true, the binding of the function is delayed until the first time it's invoked - */ -function createProxyFunctions(source, target, bind, fnNames, latebind) { - if (latebind === void 0) { latebind = false; } - var bindFunction = function (fnName) { - return source()[fnName].bind(bind()); + /** + * Random utility functions used in the UI-Router code + * + * These functions are exported, but are subject to change without notice. + * + * @preferred + * @module common + */ + var root = + (typeof self === 'object' && self.self === self && self) || + (typeof global === 'object' && global.global === global && global) || + undefined; + var angular$1 = root.angular || {}; + var fromJson = angular$1.fromJson || JSON.parse.bind(JSON); + var toJson = angular$1.toJson || JSON.stringify.bind(JSON); + var forEach = angular$1.forEach || _forEach; + var extend = Object.assign || _extend; + var equals = angular$1.equals || _equals; + function identity(x) { + return x; + } + function noop() {} + /** + * Builds proxy functions on the `to` object which pass through to the `from` object. + * + * For each key in `fnNames`, creates a proxy function on the `to` object. + * The proxy function calls the real function on the `from` object. + * + * + * #### Example: + * This example creates an new class instance whose functions are prebound to the new'd object. + * ```js + * class Foo { + * constructor(data) { + * // Binds all functions from Foo.prototype to 'this', + * // then copies them to 'this' + * bindFunctions(Foo.prototype, this, this); + * this.data = data; + * } + * + * log() { + * console.log(this.data); + * } + * } + * + * let myFoo = new Foo([1,2,3]); + * var logit = myFoo.log; + * logit(); // logs [1, 2, 3] from the myFoo 'this' instance + * ``` + * + * #### Example: + * This example creates a bound version of a service function, and copies it to another object + * ``` + * + * var SomeService = { + * this.data = [3, 4, 5]; + * this.log = function() { + * console.log(this.data); + * } + * } + * + * // Constructor fn + * function OtherThing() { + * // Binds all functions from SomeService to SomeService, + * // then copies them to 'this' + * bindFunctions(SomeService, this, SomeService); + * } + * + * let myOtherThing = new OtherThing(); + * myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this' + * ``` + * + * @param source A function that returns the source object which contains the original functions to be bound + * @param target A function that returns the target object which will receive the bound functions + * @param bind A function that returns the object which the functions will be bound to + * @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object) + * @param latebind If true, the binding of the function is delayed until the first time it's invoked + */ + function createProxyFunctions(source, target, bind, fnNames, latebind) { + if (latebind === void 0) { + latebind = false; + } + var bindFunction = function(fnName) { + return source()[fnName].bind(bind()); }; - var makeLateRebindFn = function (fnName) { return function lateRebindFunction() { + var makeLateRebindFn = function(fnName) { + return function lateRebindFunction() { target[fnName] = bindFunction(fnName); return target[fnName].apply(null, arguments); - }; }; + }; + }; fnNames = fnNames || Object.keys(source()); - return fnNames.reduce(function (acc, name) { - acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name); - return acc; + return fnNames.reduce(function(acc, name) { + acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name); + return acc; }, target); -} -/** - * prototypal inheritance helper. - * Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it - */ -var inherit = function (parent, extra) { + } + /** + * prototypal inheritance helper. + * Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it + */ + var inherit = function(parent, extra) { return extend(Object.create(parent), extra); -}; -/** Given an array, returns true if the object is found in the array, (using indexOf) */ -var inArray = curry(_inArray); -function _inArray(array, obj) { + }; + /** Given an array, returns true if the object is found in the array, (using indexOf) */ + var inArray = curry(_inArray); + function _inArray(array, obj) { return array.indexOf(obj) !== -1; -} -/** - * Given an array, and an item, if the item is found in the array, it removes it (in-place). - * The same array is returned - */ -var removeFrom = curry(_removeFrom); -function _removeFrom(array, obj) { + } + /** + * Given an array, and an item, if the item is found in the array, it removes it (in-place). + * The same array is returned + */ + var removeFrom = curry(_removeFrom); + function _removeFrom(array, obj) { var idx = array.indexOf(obj); - if (idx >= 0) - array.splice(idx, 1); + if (idx >= 0) array.splice(idx, 1); return array; -} -/** pushes a values to an array and returns the value */ -var pushTo = curry(_pushTo); -function _pushTo(arr, val$$1) { - return (arr.push(val$$1), val$$1); -} -/** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */ -var deregAll = function (functions) { - return functions.slice().forEach(function (fn) { - typeof fn === 'function' && fn(); - removeFrom(functions, fn); + } + /** pushes a values to an array and returns the value */ + var pushTo = curry(_pushTo); + function _pushTo(arr, val$$1) { + return arr.push(val$$1), val$$1; + } + /** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */ + var deregAll = function(functions) { + return functions.slice().forEach(function(fn) { + typeof fn === 'function' && fn(); + removeFrom(functions, fn); }); -}; -/** - * Applies a set of defaults to an options object. The options object is filtered - * to only those properties of the objects in the defaultsList. - * Earlier objects in the defaultsList take precedence when applying defaults. - */ -function defaults(opts) { + }; + /** + * Applies a set of defaults to an options object. The options object is filtered + * to only those properties of the objects in the defaultsList. + * Earlier objects in the defaultsList take precedence when applying defaults. + */ + function defaults(opts) { var defaultsList = []; for (var _i = 1; _i < arguments.length; _i++) { - defaultsList[_i - 1] = arguments[_i]; + defaultsList[_i - 1] = arguments[_i]; } var _defaultsList = defaultsList.concat({}).reverse(); var defaultVals = extend.apply(null, _defaultsList); return extend({}, defaultVals, pick(opts || {}, Object.keys(defaultVals))); -} -/** Reduce function that merges each element of the list into a single object, using extend */ -var mergeR = function (memo, item) { return extend(memo, item); }; -/** - * Finds the common ancestor path between two states. - * - * @param {Object} first The first state. - * @param {Object} second The second state. - * @return {Array} Returns an array of state names in descending order, not including the root. - */ -function ancestors(first, second) { + } + /** Reduce function that merges each element of the list into a single object, using extend */ + var mergeR = function(memo, item) { + return extend(memo, item); + }; + /** + * Finds the common ancestor path between two states. + * + * @param {Object} first The first state. + * @param {Object} second The second state. + * @return {Array} Returns an array of state names in descending order, not including the root. + */ + function ancestors(first, second) { var path = []; + // tslint:disable-next-line:forin for (var n in first.path) { - if (first.path[n] !== second.path[n]) - break; - path.push(first.path[n]); + if (first.path[n] !== second.path[n]) break; + path.push(first.path[n]); } return path; -} -/** - * Return a copy of the object only containing the whitelisted properties. - * - * #### Example: - * ``` - * var foo = { a: 1, b: 2, c: 3 }; - * var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 } - * ``` - * @param obj the source object - * @param propNames an Array of strings, which are the whitelisted property names - */ -function pick(obj, propNames) { + } + /** + * Return a copy of the object only containing the whitelisted properties. + * + * #### Example: + * ``` + * var foo = { a: 1, b: 2, c: 3 }; + * var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 } + * ``` + * @param obj the source object + * @param propNames an Array of strings, which are the whitelisted property names + */ + function pick(obj, propNames) { var objCopy = {}; for (var _prop in obj) { - if (propNames.indexOf(_prop) !== -1) { - objCopy[_prop] = obj[_prop]; - } + if (propNames.indexOf(_prop) !== -1) { + objCopy[_prop] = obj[_prop]; + } } return objCopy; -} -/** - * Return a copy of the object omitting the blacklisted properties. - * - * @example - * ``` - * - * var foo = { a: 1, b: 2, c: 3 }; - * var ab = omit(foo, ['a', 'b']); // { c: 3 } - * ``` - * @param obj the source object - * @param propNames an Array of strings, which are the blacklisted property names - */ -function omit(obj, propNames) { + } + /** + * Return a copy of the object omitting the blacklisted properties. + * + * @example + * ``` + * + * var foo = { a: 1, b: 2, c: 3 }; + * var ab = omit(foo, ['a', 'b']); // { c: 3 } + * ``` + * @param obj the source object + * @param propNames an Array of strings, which are the blacklisted property names + */ + function omit(obj, propNames) { return Object.keys(obj) - .filter(not(inArray(propNames))) - .reduce(function (acc, key) { return (acc[key] = obj[key], acc); }, {}); -} -/** - * Maps an array, or object to a property (by name) - */ -function pluck(collection, propName) { + .filter(not(inArray(propNames))) + .reduce(function(acc, key) { + return (acc[key] = obj[key]), acc; + }, {}); + } + /** + * Maps an array, or object to a property (by name) + */ + function pluck(collection, propName) { return map(collection, prop(propName)); -} -/** Filters an Array or an Object's properties based on a predicate */ -function filter(collection, callback) { - var arr = isArray(collection), result = arr ? [] : {}; - var accept = arr ? function (x) { return result.push(x); } : function (x, key) { return result[key] = x; }; - forEach(collection, function (item, i) { - if (callback(item, i)) - accept(item, i); + } + /** Filters an Array or an Object's properties based on a predicate */ + function filter(collection, callback) { + var arr = isArray(collection), + result = arr ? [] : {}; + var accept = arr + ? function(x) { + return result.push(x); + } + : function(x, key) { + return (result[key] = x); + }; + forEach(collection, function(item, i) { + if (callback(item, i)) accept(item, i); }); return result; -} -/** Finds an object from an array, or a property of an object, that matches a predicate */ -function find(collection, callback) { + } + /** Finds an object from an array, or a property of an object, that matches a predicate */ + function find(collection, callback) { var result; - forEach(collection, function (item, i) { - if (result) - return; - if (callback(item, i)) - result = item; + forEach(collection, function(item, i) { + if (result) return; + if (callback(item, i)) result = item; }); return result; -} -/** Given an object, returns a new object, where each property is transformed by the callback function */ -var mapObj = map; -/** Maps an array or object properties using a callback function */ -function map(collection, callback, target) { + } + /** Given an object, returns a new object, where each property is transformed by the callback function */ + var mapObj = map; + /** Maps an array or object properties using a callback function */ + function map(collection, callback, target) { target = target || (isArray(collection) ? [] : {}); - forEach(collection, function (item, i) { return target[i] = callback(item, i); }); + forEach(collection, function(item, i) { + return (target[i] = callback(item, i)); + }); return target; -} -/** - * Given an object, return its enumerable property values - * - * @example - * ``` - * - * let foo = { a: 1, b: 2, c: 3 } - * let vals = values(foo); // [ 1, 2, 3 ] - * ``` - */ -var values = function (obj) { - return Object.keys(obj).map(function (key) { return obj[key]; }); -}; -/** - * Reduce function that returns true if all of the values are truthy. - * - * @example - * ``` - * - * let vals = [ 1, true, {}, "hello world"]; - * vals.reduce(allTrueR, true); // true - * - * vals.push(0); - * vals.reduce(allTrueR, true); // false - * ``` - */ -var allTrueR = function (memo, elem) { return memo && elem; }; -/** - * Reduce function that returns true if any of the values are truthy. - * - * * @example - * ``` - * - * let vals = [ 0, null, undefined ]; - * vals.reduce(anyTrueR, true); // false - * - * vals.push("hello world"); - * vals.reduce(anyTrueR, true); // true - * ``` - */ -var anyTrueR = function (memo, elem) { return memo || elem; }; -/** - * Reduce function which un-nests a single level of arrays - * @example - * ``` - * - * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; - * input.reduce(unnestR, []) // [ "a", "b", "c", "d", [ "double, "nested" ] ] - * ``` - */ -var unnestR = function (memo, elem) { return memo.concat(elem); }; -/** - * Reduce function which recursively un-nests all arrays - * - * @example - * ``` - * - * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; - * input.reduce(unnestR, []) // [ "a", "b", "c", "d", "double, "nested" ] - * ``` - */ -var flattenR = function (memo, elem) { + } + /** + * Given an object, return its enumerable property values + * + * @example + * ``` + * + * let foo = { a: 1, b: 2, c: 3 } + * let vals = values(foo); // [ 1, 2, 3 ] + * ``` + */ + var values = function(obj) { + return Object.keys(obj).map(function(key) { + return obj[key]; + }); + }; + /** + * Reduce function that returns true if all of the values are truthy. + * + * @example + * ``` + * + * let vals = [ 1, true, {}, "hello world"]; + * vals.reduce(allTrueR, true); // true + * + * vals.push(0); + * vals.reduce(allTrueR, true); // false + * ``` + */ + var allTrueR = function(memo, elem) { + return memo && elem; + }; + /** + * Reduce function that returns true if any of the values are truthy. + * + * * @example + * ``` + * + * let vals = [ 0, null, undefined ]; + * vals.reduce(anyTrueR, true); // false + * + * vals.push("hello world"); + * vals.reduce(anyTrueR, true); // true + * ``` + */ + var anyTrueR = function(memo, elem) { + return memo || elem; + }; + /** + * Reduce function which un-nests a single level of arrays + * @example + * ``` + * + * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; + * input.reduce(unnestR, []) // [ "a", "b", "c", "d", [ "double, "nested" ] ] + * ``` + */ + var unnestR = function(memo, elem) { + return memo.concat(elem); + }; + /** + * Reduce function which recursively un-nests all arrays + * + * @example + * ``` + * + * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; + * input.reduce(unnestR, []) // [ "a", "b", "c", "d", "double, "nested" ] + * ``` + */ + var flattenR = function(memo, elem) { return isArray(elem) ? memo.concat(elem.reduce(flattenR, [])) : pushR(memo, elem); -}; -/** - * Reduce function that pushes an object to an array, then returns the array. - * Mostly just for [[flattenR]] and [[uniqR]] - */ -function pushR(arr, obj) { + }; + /** + * Reduce function that pushes an object to an array, then returns the array. + * Mostly just for [[flattenR]] and [[uniqR]] + */ + function pushR(arr, obj) { arr.push(obj); return arr; -} -/** Reduce function that filters out duplicates */ -var uniqR = function (acc, token) { + } + /** Reduce function that filters out duplicates */ + var uniqR = function(acc, token) { return inArray(acc, token) ? acc : pushR(acc, token); -}; -/** - * Return a new array with a single level of arrays unnested. - * - * @example - * ``` - * - * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; - * unnest(input) // [ "a", "b", "c", "d", [ "double, "nested" ] ] - * ``` - */ -var unnest = function (arr) { return arr.reduce(unnestR, []); }; -/** - * Return a completely flattened version of an array. - * - * @example - * ``` - * - * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; - * flatten(input) // [ "a", "b", "c", "d", "double, "nested" ] - * ``` - */ -var flatten = function (arr) { return arr.reduce(flattenR, []); }; -/** - * Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass. - * @example - * ``` - * - * let isNumber = (obj) => typeof(obj) === 'number'; - * let allNumbers = [ 1, 2, 3, 4, 5 ]; - * allNumbers.filter(assertPredicate(isNumber)); //OK - * - * let oneString = [ 1, 2, 3, 4, "5" ]; - * oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers""); - * ``` - */ -var assertPredicate = assertFn; -/** - * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test. - * @example - * ``` - * - * var data = { foo: 1, bar: 2 }; - * - * let keys = [ 'foo', 'bar' ] - * let values = keys.map(assertMap(key => data[key], "Key not found")); - * // values is [1, 2] - * - * let keys = [ 'foo', 'bar', 'baz' ] - * let values = keys.map(assertMap(key => data[key], "Key not found")); - * // throws Error("Key not found") - * ``` - */ -var assertMap = assertFn; -function assertFn(predicateOrMap, errMsg) { - if (errMsg === void 0) { errMsg = 'assert failure'; } - return function (obj) { - var result = predicateOrMap(obj); - if (!result) { - throw new Error(isFunction(errMsg) ? errMsg(obj) : errMsg); - } - return result; + }; + /** + * Return a new array with a single level of arrays unnested. + * + * @example + * ``` + * + * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; + * unnest(input) // [ "a", "b", "c", "d", [ "double, "nested" ] ] + * ``` + */ + var unnest = function(arr) { + return arr.reduce(unnestR, []); + }; + /** + * Return a completely flattened version of an array. + * + * @example + * ``` + * + * let input = [ [ "a", "b" ], [ "c", "d" ], [ [ "double", "nested" ] ] ]; + * flatten(input) // [ "a", "b", "c", "d", "double, "nested" ] + * ``` + */ + var flatten = function(arr) { + return arr.reduce(flattenR, []); + }; + /** + * Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass. + * @example + * ``` + * + * let isNumber = (obj) => typeof(obj) === 'number'; + * let allNumbers = [ 1, 2, 3, 4, 5 ]; + * allNumbers.filter(assertPredicate(isNumber)); //OK + * + * let oneString = [ 1, 2, 3, 4, "5" ]; + * oneString.filter(assertPredicate(isNumber, "Not all numbers")); // throws Error(""Not all numbers""); + * ``` + */ + var assertPredicate = assertFn; + /** + * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test. + * @example + * ``` + * + * var data = { foo: 1, bar: 2 }; + * + * let keys = [ 'foo', 'bar' ] + * let values = keys.map(assertMap(key => data[key], "Key not found")); + * // values is [1, 2] + * + * let keys = [ 'foo', 'bar', 'baz' ] + * let values = keys.map(assertMap(key => data[key], "Key not found")); + * // throws Error("Key not found") + * ``` + */ + var assertMap = assertFn; + function assertFn(predicateOrMap, errMsg) { + if (errMsg === void 0) { + errMsg = 'assert failure'; + } + return function(obj) { + var result = predicateOrMap(obj); + if (!result) { + throw new Error(isFunction(errMsg) ? errMsg(obj) : errMsg); + } + return result; }; -} -/** - * Like _.pairs: Given an object, returns an array of key/value pairs - * - * @example - * ``` - * - * pairs({ foo: "FOO", bar: "BAR }) // [ [ "foo", "FOO" ], [ "bar": "BAR" ] ] - * ``` - */ -var pairs = function (obj) { - return Object.keys(obj).map(function (key) { return [key, obj[key]]; }); -}; -/** - * Given two or more parallel arrays, returns an array of tuples where - * each tuple is composed of [ a[i], b[i], ... z[i] ] - * - * @example - * ``` - * - * let foo = [ 0, 2, 4, 6 ]; - * let bar = [ 1, 3, 5, 7 ]; - * let baz = [ 10, 30, 50, 70 ]; - * arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ] - * arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ] - * ``` - */ -function arrayTuples() { + } + /** + * Like _.pairs: Given an object, returns an array of key/value pairs + * + * @example + * ``` + * + * pairs({ foo: "FOO", bar: "BAR }) // [ [ "foo", "FOO" ], [ "bar": "BAR" ] ] + * ``` + */ + var pairs = function(obj) { + return Object.keys(obj).map(function(key) { + return [key, obj[key]]; + }); + }; + /** + * Given two or more parallel arrays, returns an array of tuples where + * each tuple is composed of [ a[i], b[i], ... z[i] ] + * + * @example + * ``` + * + * let foo = [ 0, 2, 4, 6 ]; + * let bar = [ 1, 3, 5, 7 ]; + * let baz = [ 10, 30, 50, 70 ]; + * arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ] + * arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ] + * ``` + */ + function arrayTuples() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + args[_i] = arguments[_i]; } - if (args.length === 0) - return []; - var maxArrayLen = args.reduce(function (min, arr) { return Math.min(arr.length, min); }, 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER + if (args.length === 0) return []; + var maxArrayLen = args.reduce(function(min, arr) { + return Math.min(arr.length, min); + }, 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER var result = []; - var _loop_1 = function (i) { - // This is a hot function - // Unroll when there are 1-4 arguments - switch (args.length) { - case 1: - result.push([args[0][i]]); - break; - case 2: - result.push([args[0][i], args[1][i]]); - break; - case 3: - result.push([args[0][i], args[1][i], args[2][i]]); - break; - case 4: - result.push([args[0][i], args[1][i], args[2][i], args[3][i]]); - break; - default: - result.push(args.map(function (array) { return array[i]; })); - break; - } + var _loop_1 = function(i) { + // This is a hot function + // Unroll when there are 1-4 arguments + switch (args.length) { + case 1: + result.push([args[0][i]]); + break; + case 2: + result.push([args[0][i], args[1][i]]); + break; + case 3: + result.push([args[0][i], args[1][i], args[2][i]]); + break; + case 4: + result.push([args[0][i], args[1][i], args[2][i], args[3][i]]); + break; + default: + result.push( + args.map(function(array) { + return array[i]; + }), + ); + break; + } }; for (var i = 0; i < maxArrayLen; i++) { - _loop_1(i); + _loop_1(i); } return result; -} -/** - * Reduce function which builds an object from an array of [key, value] pairs. - * - * Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration. - * - * Each keyValueTuple should be an array with values [ key: string, value: any ] - * - * @example - * ``` - * - * var pairs = [ ["fookey", "fooval"], ["barkey", "barval"] ] - * - * var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {}) - * // pairsToObj == { fookey: "fooval", barkey: "barval" } - * - * // Or, more simply: - * var pairsToObj = pairs.reduce(applyPairs, {}) - * // pairsToObj == { fookey: "fooval", barkey: "barval" } - * ``` - */ -function applyPairs(memo, keyValTuple) { + } + /** + * Reduce function which builds an object from an array of [key, value] pairs. + * + * Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration. + * + * Each keyValueTuple should be an array with values [ key: string, value: any ] + * + * @example + * ``` + * + * var pairs = [ ["fookey", "fooval"], ["barkey", "barval"] ] + * + * var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {}) + * // pairsToObj == { fookey: "fooval", barkey: "barval" } + * + * // Or, more simply: + * var pairsToObj = pairs.reduce(applyPairs, {}) + * // pairsToObj == { fookey: "fooval", barkey: "barval" } + * ``` + */ + function applyPairs(memo, keyValTuple) { var key, value; - if (isArray(keyValTuple)) - key = keyValTuple[0], value = keyValTuple[1]; - if (!isString(key)) - throw new Error('invalid parameters to applyPairs'); + if (isArray(keyValTuple)) (key = keyValTuple[0]), (value = keyValTuple[1]); + if (!isString(key)) throw new Error('invalid parameters to applyPairs'); memo[key] = value; return memo; -} -/** Get the last element of an array */ -function tail(arr) { - return arr.length && arr[arr.length - 1] || undefined; -} -/** - * shallow copy from src to dest - */ -function copy(src, dest) { + } + /** Get the last element of an array */ + function tail(arr) { + return (arr.length && arr[arr.length - 1]) || undefined; + } + /** + * shallow copy from src to dest + */ + function copy(src, dest) { if (dest) - Object.keys(dest).forEach(function (key) { return delete dest[key]; }); - if (!dest) - dest = {}; + Object.keys(dest).forEach(function(key) { + return delete dest[key]; + }); + if (!dest) dest = {}; return extend(dest, src); -} -/** Naive forEach implementation works with Objects or Arrays */ -function _forEach(obj, cb, _this) { - if (isArray(obj)) - return obj.forEach(cb, _this); - Object.keys(obj).forEach(function (key) { return cb(obj[key], key); }); -} -function _extend(toObj) { + } + /** Naive forEach implementation works with Objects or Arrays */ + function _forEach(obj, cb, _this) { + if (isArray(obj)) return obj.forEach(cb, _this); + Object.keys(obj).forEach(function(key) { + return cb(obj[key], key); + }); + } + function _extend(toObj) { for (var i = 1; i < arguments.length; i++) { - var obj = arguments[i]; - if (!obj) - continue; - var keys = Object.keys(obj); - for (var j = 0; j < keys.length; j++) { - toObj[keys[j]] = obj[keys[j]]; - } + var obj = arguments[i]; + if (!obj) continue; + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; j++) { + toObj[keys[j]] = obj[keys[j]]; + } } return toObj; -} -function _equals(o1, o2) { - if (o1 === o2) - return true; - if (o1 === null || o2 === null) - return false; - if (o1 !== o1 && o2 !== o2) - return true; // NaN === NaN - var t1 = typeof o1, t2 = typeof o2; - if (t1 !== t2 || t1 !== 'object') - return false; + } + function _equals(o1, o2) { + if (o1 === o2) return true; + if (o1 === null || o2 === null) return false; + if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN + var t1 = typeof o1, + t2 = typeof o2; + if (t1 !== t2 || t1 !== 'object') return false; var tup = [o1, o2]; - if (all(isArray)(tup)) - return _arraysEq(o1, o2); - if (all(isDate)(tup)) - return o1.getTime() === o2.getTime(); - if (all(isRegExp)(tup)) - return o1.toString() === o2.toString(); - if (all(isFunction)(tup)) - return true; // meh + if (all(isArray)(tup)) return _arraysEq(o1, o2); + if (all(isDate)(tup)) return o1.getTime() === o2.getTime(); + if (all(isRegExp)(tup)) return o1.toString() === o2.toString(); + if (all(isFunction)(tup)) return true; // meh var predicates = [isFunction, isArray, isDate, isRegExp]; - if (predicates.map(any).reduce(function (b, fn) { return b || !!fn(tup); }, false)) - return false; + if ( + predicates.map(any).reduce(function(b, fn) { + return b || !!fn(tup); + }, false) + ) + return false; var keys = {}; + // tslint:disable-next-line:forin for (var key in o1) { - if (!_equals(o1[key], o2[key])) - return false; - keys[key] = true; + if (!_equals(o1[key], o2[key])) return false; + keys[key] = true; } for (var key in o2) { - if (!keys[key]) - return false; + if (!keys[key]) return false; } return true; -} -function _arraysEq(a1, a2) { - if (a1.length !== a2.length) - return false; - return arrayTuples(a1, a2).reduce(function (b, t) { return b && _equals(t[0], t[1]); }, true); -} -// issue #2676 -var silenceUncaughtInPromise = function (promise) { - return promise.catch(function (e) { return 0; }) && promise; -}; -var silentRejection = function (error) { + } + function _arraysEq(a1, a2) { + if (a1.length !== a2.length) return false; + return arrayTuples(a1, a2).reduce(function(b, t) { + return b && _equals(t[0], t[1]); + }, true); + } + // issue #2676 + var silenceUncaughtInPromise = function(promise) { + return ( + promise.catch(function(e) { + return 0; + }) && promise + ); + }; + var silentRejection = function(error) { return silenceUncaughtInPromise(services.$q.reject(error)); -}; + }; -/** @module common */ -var Queue = /** @class */ (function () { + /** @module common */ + var Queue = /** @class */ (function() { function Queue(_items, _limit) { - if (_items === void 0) { _items = []; } - if (_limit === void 0) { _limit = null; } - this._items = _items; - this._limit = _limit; - this._evictListeners = []; - this.onEvict = pushTo(this._evictListeners); + if (_items === void 0) { + _items = []; + } + if (_limit === void 0) { + _limit = null; + } + this._items = _items; + this._limit = _limit; + this._evictListeners = []; + this.onEvict = pushTo(this._evictListeners); } - Queue.prototype.enqueue = function (item) { - var items = this._items; - items.push(item); - if (this._limit && items.length > this._limit) - this.evict(); - return item; + Queue.prototype.enqueue = function(item) { + var items = this._items; + items.push(item); + if (this._limit && items.length > this._limit) this.evict(); + return item; }; - Queue.prototype.evict = function () { - var item = this._items.shift(); - this._evictListeners.forEach(function (fn) { return fn(item); }); - return item; + Queue.prototype.evict = function() { + var item = this._items.shift(); + this._evictListeners.forEach(function(fn) { + return fn(item); + }); + return item; }; - Queue.prototype.dequeue = function () { - if (this.size()) - return this._items.splice(0, 1)[0]; + Queue.prototype.dequeue = function() { + if (this.size()) return this._items.splice(0, 1)[0]; }; - Queue.prototype.clear = function () { - var current = this._items; - this._items = []; - return current; + Queue.prototype.clear = function() { + var current = this._items; + this._items = []; + return current; }; - Queue.prototype.size = function () { - return this._items.length; + Queue.prototype.size = function() { + return this._items.length; }; - Queue.prototype.remove = function (item) { - var idx = this._items.indexOf(item); - return idx > -1 && this._items.splice(idx, 1)[0]; + Queue.prototype.remove = function(item) { + var idx = this._items.indexOf(item); + return idx > -1 && this._items.splice(idx, 1)[0]; }; - Queue.prototype.peekTail = function () { - return this._items[this._items.length - 1]; + Queue.prototype.peekTail = function() { + return this._items[this._items.length - 1]; }; - Queue.prototype.peekHead = function () { - if (this.size()) - return this._items[0]; + Queue.prototype.peekHead = function() { + if (this.size()) return this._items[0]; }; return Queue; -}()); + })(); /** for typedoc */ -/** - * @coreapi - * @module transition - */ /** for typedoc */ - -(function (RejectType) { - RejectType[RejectType["SUPERSEDED"] = 2] = "SUPERSEDED"; - RejectType[RejectType["ABORTED"] = 3] = "ABORTED"; - RejectType[RejectType["INVALID"] = 4] = "INVALID"; - RejectType[RejectType["IGNORED"] = 5] = "IGNORED"; - RejectType[RejectType["ERROR"] = 6] = "ERROR"; -})(exports.RejectType || (exports.RejectType = {})); -/** @hidden */ -var id = 0; -var Rejection = /** @class */ (function () { + /** + * @coreapi + * @module transition + */ (function(RejectType) { + /** + * A new transition superseded this one. + * + * While this transition was running, a new transition started. + * This transition is cancelled because it was superseded by new transition. + */ + RejectType[(RejectType['SUPERSEDED'] = 2)] = 'SUPERSEDED'; + /** + * The transition was aborted + * + * The transition was aborted by a hook which returned `false` + */ + RejectType[(RejectType['ABORTED'] = 3)] = 'ABORTED'; + /** + * The transition was invalid + * + * The transition was never started because it was invalid + */ + RejectType[(RejectType['INVALID'] = 4)] = 'INVALID'; + /** + * The transition was ignored + * + * The transition was ignored because it would have no effect. + * + * Either: + * + * - The transition is targeting the current state and parameter values + * - The transition is targeting the same state and parameter values as the currently running transition. + */ + RejectType[(RejectType['IGNORED'] = 5)] = 'IGNORED'; + /** + * The transition errored. + * + * This generally means a hook threw an error or returned a rejected promise + */ + RejectType[(RejectType['ERROR'] = 6)] = 'ERROR'; + })(exports.RejectType || (exports.RejectType = {})); + /** @hidden */ + var id = 0; + var Rejection = /** @class */ (function() { function Rejection(type, message, detail) { - this.$id = id++; - this.type = type; - this.message = message; - this.detail = detail; + /** @hidden */ + this.$id = id++; + this.type = type; + this.message = message; + this.detail = detail; } /** Returns true if the obj is a rejected promise created from the `asPromise` factory */ - Rejection.isRejectionPromise = function (obj) { - return obj && (typeof obj.then === 'function') && is(Rejection)(obj._transitionRejection); + Rejection.isRejectionPromise = function(obj) { + return obj && typeof obj.then === 'function' && is(Rejection)(obj._transitionRejection); }; /** Returns a Rejection due to transition superseded */ - Rejection.superseded = function (detail, options) { - var message = 'The transition has been superseded by a different transition'; - var rejection = new Rejection(exports.RejectType.SUPERSEDED, message, detail); - if (options && options.redirected) { - rejection.redirected = true; - } - return rejection; + Rejection.superseded = function(detail, options) { + var message = 'The transition has been superseded by a different transition'; + var rejection = new Rejection(exports.RejectType.SUPERSEDED, message, detail); + if (options && options.redirected) { + rejection.redirected = true; + } + return rejection; }; /** Returns a Rejection due to redirected transition */ - Rejection.redirected = function (detail) { - return Rejection.superseded(detail, { redirected: true }); + Rejection.redirected = function(detail) { + return Rejection.superseded(detail, { redirected: true }); }; /** Returns a Rejection due to invalid transition */ - Rejection.invalid = function (detail) { - var message = 'This transition is invalid'; - return new Rejection(exports.RejectType.INVALID, message, detail); + Rejection.invalid = function(detail) { + var message = 'This transition is invalid'; + return new Rejection(exports.RejectType.INVALID, message, detail); }; /** Returns a Rejection due to ignored transition */ - Rejection.ignored = function (detail) { - var message = 'The transition was ignored'; - return new Rejection(exports.RejectType.IGNORED, message, detail); + Rejection.ignored = function(detail) { + var message = 'The transition was ignored'; + return new Rejection(exports.RejectType.IGNORED, message, detail); }; /** Returns a Rejection due to aborted transition */ - Rejection.aborted = function (detail) { - var message = 'The transition has been aborted'; - return new Rejection(exports.RejectType.ABORTED, message, detail); + Rejection.aborted = function(detail) { + var message = 'The transition has been aborted'; + return new Rejection(exports.RejectType.ABORTED, message, detail); }; /** Returns a Rejection due to aborted transition */ - Rejection.errored = function (detail) { - var message = 'The transition errored'; - return new Rejection(exports.RejectType.ERROR, message, detail); + Rejection.errored = function(detail) { + var message = 'The transition errored'; + return new Rejection(exports.RejectType.ERROR, message, detail); }; /** * Returns a Rejection @@ -1143,141 +1251,164 @@ var Rejection = /** @class */ (function () { * * @returns `detail` if it is already a `Rejection`, else returns an ERROR Rejection. */ - Rejection.normalize = function (detail) { - return is(Rejection)(detail) ? detail : Rejection.errored(detail); + Rejection.normalize = function(detail) { + return is(Rejection)(detail) ? detail : Rejection.errored(detail); }; - Rejection.prototype.toString = function () { - var detailString = function (d) { - return d && d.toString !== Object.prototype.toString ? d.toString() : stringify(d); - }; - var detail = detailString(this.detail); - var _a = this, $id = _a.$id, type = _a.type, message = _a.message; - return "Transition Rejection($id: " + $id + " type: " + type + ", message: " + message + ", detail: " + detail + ")"; + Rejection.prototype.toString = function() { + var detailString = function(d) { + return d && d.toString !== Object.prototype.toString ? d.toString() : stringify(d); + }; + var detail = detailString(this.detail); + var _a = this, + $id = _a.$id, + type = _a.type, + message = _a.message; + return ( + 'Transition Rejection($id: ' + $id + ' type: ' + type + ', message: ' + message + ', detail: ' + detail + ')' + ); }; - Rejection.prototype.toPromise = function () { - return extend(silentRejection(this), { _transitionRejection: this }); + Rejection.prototype.toPromise = function() { + return extend(silentRejection(this), { _transitionRejection: this }); }; return Rejection; -}()); + })(); -/** - * # Transition tracing (debug) - * - * Enable transition tracing to print transition information to the console, - * in order to help debug your application. - * Tracing logs detailed information about each Transition to your console. - * - * To enable tracing, import the [[Trace]] singleton and enable one or more categories. - * - * ### ES6 - * ```js - * import {trace} from "ui-router-ng2"; // or "angular-ui-router" - * trace.enable(1, 5); // TRANSITION and VIEWCONFIG - * ``` - * - * ### CJS - * ```js - * let trace = require("angular-ui-router").trace; // or "ui-router-ng2" - * trace.enable("TRANSITION", "VIEWCONFIG"); - * ``` - * - * ### Globals - * ```js - * let trace = window["angular-ui-router"].trace; // or "ui-router-ng2" - * trace.enable(); // Trace everything (very verbose) - * ``` - * - * ### Angular 1: - * ```js - * app.run($trace => $trace.enable()); - * ``` - * - * @coreapi - * @module trace - */ -/* tslint:disable:no-console */ -/** @hidden */ -function uiViewString(uiview) { - if (!uiview) - return 'ui-view (defunct)'; + /** + * # Transition tracing (debug) + * + * Enable transition tracing to print transition information to the console, + * in order to help debug your application. + * Tracing logs detailed information about each Transition to your console. + * + * To enable tracing, import the [[Trace]] singleton and enable one or more categories. + * + * ### ES6 + * ```js + * import {trace} from "@uirouter/core"; + * trace.enable(1, 5); // TRANSITION and VIEWCONFIG + * ``` + * + * ### CJS + * ```js + * let trace = require("@uirouter/core").trace; + * trace.enable("TRANSITION", "VIEWCONFIG"); + * ``` + * + * ### Globals + * ```js + * let trace = window["@uirouter/core"].trace; + * trace.enable(); // Trace everything (very verbose) + * ``` + * + * ### Angular 1: + * ```js + * app.run($trace => $trace.enable()); + * ``` + * + * @coreapi + * @module trace + */ + /** @hidden */ + function uiViewString(uiview) { + if (!uiview) return 'ui-view (defunct)'; var state = uiview.creationContext ? uiview.creationContext.name || '(root)' : '(none)'; - return "[ui-view#" + uiview.id + " " + uiview.$type + ":" + uiview.fqn + " (" + uiview.name + "@" + state + ")]"; -} -/** @hidden */ -var viewConfigString = function (viewConfig) { + return '[ui-view#' + uiview.id + ' ' + uiview.$type + ':' + uiview.fqn + ' (' + uiview.name + '@' + state + ')]'; + } + /** @hidden */ + var viewConfigString = function(viewConfig) { var view = viewConfig.viewDecl; var state = view.$context.name || '(root)'; - return "[View#" + viewConfig.$id + " from '" + state + "' state]: target ui-view: '" + view.$uiViewName + "@" + view.$uiViewContextAnchor + "'"; -}; -/** @hidden */ -function normalizedCat(input) { + return ( + '[View#' + + viewConfig.$id + + " from '" + + state + + "' state]: target ui-view: '" + + view.$uiViewName + + '@' + + view.$uiViewContextAnchor + + "'" + ); + }; + /** @hidden */ + function normalizedCat(input) { return isNumber(input) ? exports.Category[input] : exports.Category[exports.Category[input]]; -} -/** @hidden */ -var consoleLog = Function.prototype.bind.call(console.log, console); -/** @hidden */ -var consoletable = isFunction(console.table) ? console.table.bind(console) : consoleLog.bind(console); -/** - * Trace categories Enum - * - * Enable or disable a category using [[Trace.enable]] or [[Trace.disable]] - * - * `trace.enable(Category.TRANSITION)` - * - * These can also be provided using a matching string, or position ordinal - * - * `trace.enable("TRANSITION")` - * - * `trace.enable(1)` - */ + } + /** @hidden */ + var consoleLog = Function.prototype.bind.call(console.log, console); + /** @hidden */ + var consoletable = isFunction(console.table) ? console.table.bind(console) : consoleLog.bind(console); + /** + * Trace categories Enum + * + * Enable or disable a category using [[Trace.enable]] or [[Trace.disable]] + * + * `trace.enable(Category.TRANSITION)` + * + * These can also be provided using a matching string, or position ordinal + * + * `trace.enable("TRANSITION")` + * + * `trace.enable(1)` + */ -(function (Category) { - Category[Category["RESOLVE"] = 0] = "RESOLVE"; - Category[Category["TRANSITION"] = 1] = "TRANSITION"; - Category[Category["HOOK"] = 2] = "HOOK"; - Category[Category["UIVIEW"] = 3] = "UIVIEW"; - Category[Category["VIEWCONFIG"] = 4] = "VIEWCONFIG"; -})(exports.Category || (exports.Category = {})); -/** @hidden */ -var _tid = parse('$id'); -/** @hidden */ -var _rid = parse('router.$id'); -/** @hidden */ -var transLbl = function (trans) { return "Transition #" + _tid(trans) + "-" + _rid(trans); }; -/** - * Prints UI-Router Transition trace information to the console. - */ -var Trace = /** @class */ (function () { + (function(Category) { + Category[(Category['RESOLVE'] = 0)] = 'RESOLVE'; + Category[(Category['TRANSITION'] = 1)] = 'TRANSITION'; + Category[(Category['HOOK'] = 2)] = 'HOOK'; + Category[(Category['UIVIEW'] = 3)] = 'UIVIEW'; + Category[(Category['VIEWCONFIG'] = 4)] = 'VIEWCONFIG'; + })(exports.Category || (exports.Category = {})); + /** @hidden */ + var _tid = parse('$id'); + /** @hidden */ + var _rid = parse('router.$id'); + /** @hidden */ + var transLbl = function(trans) { + return 'Transition #' + _tid(trans) + '-' + _rid(trans); + }; + /** + * Prints UI-Router Transition trace information to the console. + */ + var Trace = /** @class */ (function() { /** @hidden */ function Trace() { - /** @hidden */ - this._enabled = {}; - this.approximateDigests = 0; + /** @hidden */ + this._enabled = {}; + this.approximateDigests = 0; } /** @hidden */ - Trace.prototype._set = function (enabled, categories) { - var _this = this; - if (!categories.length) { - categories = Object.keys(exports.Category) - .map(function (k) { return parseInt(k, 10); }) - .filter(function (k) { return !isNaN(k); }) - .map(function (key) { return exports.Category[key]; }); - } - categories.map(normalizedCat).forEach(function (category) { return _this._enabled[category] = enabled; }); + Trace.prototype._set = function(enabled, categories) { + var _this = this; + if (!categories.length) { + categories = Object.keys(exports.Category) + .map(function(k) { + return parseInt(k, 10); + }) + .filter(function(k) { + return !isNaN(k); + }) + .map(function(key) { + return exports.Category[key]; + }); + } + categories.map(normalizedCat).forEach(function(category) { + return (_this._enabled[category] = enabled); + }); }; - Trace.prototype.enable = function () { - var categories = []; - for (var _i = 0; _i < arguments.length; _i++) { - categories[_i] = arguments[_i]; - } - this._set(true, categories); + Trace.prototype.enable = function() { + var categories = []; + for (var _i = 0; _i < arguments.length; _i++) { + categories[_i] = arguments[_i]; + } + this._set(true, categories); }; - Trace.prototype.disable = function () { - var categories = []; - for (var _i = 0; _i < arguments.length; _i++) { - categories[_i] = arguments[_i]; - } - this._set(false, categories); + Trace.prototype.disable = function() { + var categories = []; + for (var _i = 0; _i < arguments.length; _i++) { + categories[_i] = arguments[_i]; + } + this._set(false, categories); }; /** * Retrieves the enabled stateus of a [[Category]] @@ -1288,164 +1419,164 @@ var Trace = /** @class */ (function () { * * @returns boolean true if the category is enabled */ - Trace.prototype.enabled = function (category) { - return !!this._enabled[normalizedCat(category)]; + Trace.prototype.enabled = function(category) { + return !!this._enabled[normalizedCat(category)]; }; /** @internalapi called by ui-router code */ - Trace.prototype.traceTransitionStart = function (trans) { - if (!this.enabled(exports.Category.TRANSITION)) - return; - console.log(transLbl(trans) + ": Started -> " + stringify(trans)); + Trace.prototype.traceTransitionStart = function(trans) { + if (!this.enabled(exports.Category.TRANSITION)) return; + console.log(transLbl(trans) + ': Started -> ' + stringify(trans)); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceTransitionIgnored = function (trans) { - if (!this.enabled(exports.Category.TRANSITION)) - return; - console.log(transLbl(trans) + ": Ignored <> " + stringify(trans)); + Trace.prototype.traceTransitionIgnored = function(trans) { + if (!this.enabled(exports.Category.TRANSITION)) return; + console.log(transLbl(trans) + ': Ignored <> ' + stringify(trans)); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceHookInvocation = function (step, trans, options) { - if (!this.enabled(exports.Category.HOOK)) - return; - var event = parse('traceData.hookType')(options) || 'internal', context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown', name = functionToString(step.registeredHook.callback); - console.log(transLbl(trans) + ": Hook -> " + event + " context: " + context + ", " + maxLength(200, name)); + Trace.prototype.traceHookInvocation = function(step, trans, options) { + if (!this.enabled(exports.Category.HOOK)) return; + var event = parse('traceData.hookType')(options) || 'internal', + context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown', + name = functionToString(step.registeredHook.callback); + console.log(transLbl(trans) + ': Hook -> ' + event + ' context: ' + context + ', ' + maxLength(200, name)); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceHookResult = function (hookResult, trans, transitionOptions) { - if (!this.enabled(exports.Category.HOOK)) - return; - console.log(transLbl(trans) + ": <- Hook returned: " + maxLength(200, stringify(hookResult))); + Trace.prototype.traceHookResult = function(hookResult, trans, transitionOptions) { + if (!this.enabled(exports.Category.HOOK)) return; + console.log(transLbl(trans) + ': <- Hook returned: ' + maxLength(200, stringify(hookResult))); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceResolvePath = function (path, when, trans) { - if (!this.enabled(exports.Category.RESOLVE)) - return; - console.log(transLbl(trans) + ": Resolving " + path + " (" + when + ")"); + Trace.prototype.traceResolvePath = function(path, when, trans) { + if (!this.enabled(exports.Category.RESOLVE)) return; + console.log(transLbl(trans) + ': Resolving ' + path + ' (' + when + ')'); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceResolvableResolved = function (resolvable, trans) { - if (!this.enabled(exports.Category.RESOLVE)) - return; - console.log(transLbl(trans) + ": <- Resolved " + resolvable + " to: " + maxLength(200, stringify(resolvable.data))); + Trace.prototype.traceResolvableResolved = function(resolvable, trans) { + if (!this.enabled(exports.Category.RESOLVE)) return; + console.log( + transLbl(trans) + + ': <- Resolved ' + + resolvable + + ' to: ' + + maxLength(200, stringify(resolvable.data)), + ); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceError = function (reason, trans) { - if (!this.enabled(exports.Category.TRANSITION)) - return; - console.log(transLbl(trans) + ": <- Rejected " + stringify(trans) + ", reason: " + reason); + Trace.prototype.traceError = function(reason, trans) { + if (!this.enabled(exports.Category.TRANSITION)) return; + console.log(transLbl(trans) + ': <- Rejected ' + stringify(trans) + ', reason: ' + reason); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceSuccess = function (finalState, trans) { - if (!this.enabled(exports.Category.TRANSITION)) - return; - console.log(transLbl(trans) + ": <- Success " + stringify(trans) + ", final state: " + finalState.name); + Trace.prototype.traceSuccess = function(finalState, trans) { + if (!this.enabled(exports.Category.TRANSITION)) return; + console.log(transLbl(trans) + ': <- Success ' + stringify(trans) + ', final state: ' + finalState.name); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceUIViewEvent = function (event, viewData, extra) { - if (extra === void 0) { extra = ''; } - if (!this.enabled(exports.Category.UIVIEW)) - return; - console.log("ui-view: " + padString(30, event) + " " + uiViewString(viewData) + extra); + Trace.prototype.traceUIViewEvent = function(event, viewData, extra) { + if (extra === void 0) { + extra = ''; + } + if (!this.enabled(exports.Category.UIVIEW)) return; + console.log('ui-view: ' + padString(30, event) + ' ' + uiViewString(viewData) + extra); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceUIViewConfigUpdated = function (viewData, context) { - if (!this.enabled(exports.Category.UIVIEW)) - return; - this.traceUIViewEvent('Updating', viewData, " with ViewConfig from context='" + context + "'"); + Trace.prototype.traceUIViewConfigUpdated = function(viewData, context) { + if (!this.enabled(exports.Category.UIVIEW)) return; + this.traceUIViewEvent('Updating', viewData, " with ViewConfig from context='" + context + "'"); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceUIViewFill = function (viewData, html) { - if (!this.enabled(exports.Category.UIVIEW)) - return; - this.traceUIViewEvent('Fill', viewData, " with: " + maxLength(200, html)); + Trace.prototype.traceUIViewFill = function(viewData, html) { + if (!this.enabled(exports.Category.UIVIEW)) return; + this.traceUIViewEvent('Fill', viewData, ' with: ' + maxLength(200, html)); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceViewSync = function (pairs) { - if (!this.enabled(exports.Category.VIEWCONFIG)) - return; - var uivheader = 'uiview component fqn'; - var cfgheader = 'view config state (view name)'; - var mapping = pairs.map(function (_a) { - var uiView = _a.uiView, viewConfig = _a.viewConfig; - var uiv = uiView && uiView.fqn; - var cfg = viewConfig && viewConfig.viewDecl.$context.name + ": (" + viewConfig.viewDecl.$name + ")"; - return _b = {}, _b[uivheader] = uiv, _b[cfgheader] = cfg, _b; - var _b; - }).sort(function (a, b) { return (a[uivheader] || '').localeCompare(b[uivheader] || ''); }); - consoletable(mapping); + Trace.prototype.traceViewSync = function(pairs) { + if (!this.enabled(exports.Category.VIEWCONFIG)) return; + var uivheader = 'uiview component fqn'; + var cfgheader = 'view config state (view name)'; + var mapping = pairs + .map(function(_a) { + var uiView = _a.uiView, + viewConfig = _a.viewConfig; + var uiv = uiView && uiView.fqn; + var cfg = viewConfig && viewConfig.viewDecl.$context.name + ': (' + viewConfig.viewDecl.$name + ')'; + return (_b = {}), (_b[uivheader] = uiv), (_b[cfgheader] = cfg), _b; + var _b; + }) + .sort(function(a, b) { + return (a[uivheader] || '').localeCompare(b[uivheader] || ''); + }); + consoletable(mapping); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceViewServiceEvent = function (event, viewConfig) { - if (!this.enabled(exports.Category.VIEWCONFIG)) - return; - console.log("VIEWCONFIG: " + event + " " + viewConfigString(viewConfig)); + Trace.prototype.traceViewServiceEvent = function(event, viewConfig) { + if (!this.enabled(exports.Category.VIEWCONFIG)) return; + console.log('VIEWCONFIG: ' + event + ' ' + viewConfigString(viewConfig)); }; /** @internalapi called by ui-router code */ - Trace.prototype.traceViewServiceUIViewEvent = function (event, viewData) { - if (!this.enabled(exports.Category.VIEWCONFIG)) - return; - console.log("VIEWCONFIG: " + event + " " + uiViewString(viewData)); + Trace.prototype.traceViewServiceUIViewEvent = function(event, viewData) { + if (!this.enabled(exports.Category.VIEWCONFIG)) return; + console.log('VIEWCONFIG: ' + event + ' ' + uiViewString(viewData)); }; return Trace; -}()); -/** - * The [[Trace]] singleton - * - * #### Example: - * ```js - * import {trace} from "angular-ui-router"; - * trace.enable(1, 5); - * ``` - */ -var trace = new Trace(); + })(); + /** + * The [[Trace]] singleton + * + * #### Example: + * ```js + * import {trace} from "@uirouter/core"; + * trace.enable(1, 5); + * ``` + */ + var trace = new Trace(); -(function (TransitionHookPhase) { - TransitionHookPhase[TransitionHookPhase["CREATE"] = 0] = "CREATE"; - TransitionHookPhase[TransitionHookPhase["BEFORE"] = 1] = "BEFORE"; - TransitionHookPhase[TransitionHookPhase["RUN"] = 2] = "RUN"; - TransitionHookPhase[TransitionHookPhase["SUCCESS"] = 3] = "SUCCESS"; - TransitionHookPhase[TransitionHookPhase["ERROR"] = 4] = "ERROR"; -})(exports.TransitionHookPhase || (exports.TransitionHookPhase = {})); + (function(TransitionHookPhase) { + TransitionHookPhase[(TransitionHookPhase['CREATE'] = 0)] = 'CREATE'; + TransitionHookPhase[(TransitionHookPhase['BEFORE'] = 1)] = 'BEFORE'; + TransitionHookPhase[(TransitionHookPhase['RUN'] = 2)] = 'RUN'; + TransitionHookPhase[(TransitionHookPhase['SUCCESS'] = 3)] = 'SUCCESS'; + TransitionHookPhase[(TransitionHookPhase['ERROR'] = 4)] = 'ERROR'; + })(exports.TransitionHookPhase || (exports.TransitionHookPhase = {})); -(function (TransitionHookScope) { - TransitionHookScope[TransitionHookScope["TRANSITION"] = 0] = "TRANSITION"; - TransitionHookScope[TransitionHookScope["STATE"] = 1] = "STATE"; -})(exports.TransitionHookScope || (exports.TransitionHookScope = {})); + (function(TransitionHookScope) { + TransitionHookScope[(TransitionHookScope['TRANSITION'] = 0)] = 'TRANSITION'; + TransitionHookScope[(TransitionHookScope['STATE'] = 1)] = 'STATE'; + })(exports.TransitionHookScope || (exports.TransitionHookScope = {})); /** for typedoc */ -/** - * @coreapi - * @module state - */ /** for typedoc */ -/** - * Encapsulate the target (destination) state/params/options of a [[Transition]]. - * - * This class is frequently used to redirect a transition to a new destination. - * - * See: - * - * - [[HookResult]] - * - [[TransitionHookFn]] - * - [[TransitionService.onStart]] - * - * To create a `TargetState`, use [[StateService.target]]. - * - * --- - * - * This class wraps: - * - * 1) an identifier for a state - * 2) a set of parameters - * 3) and transition options - * 4) the registered state object (the [[StateDeclaration]]) - * - * Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can - * either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string). - * The `TargetState` class normalizes those options. - * - * A `TargetState` may be valid (the state being targeted exists in the registry) - * or invalid (the state being targeted is not registered). - */ -var TargetState = /** @class */ (function () { + /** + * @coreapi + * @module state + */ /** + * Encapsulate the target (destination) state/params/options of a [[Transition]]. + * + * This class is frequently used to redirect a transition to a new destination. + * + * See: + * + * - [[HookResult]] + * - [[TransitionHookFn]] + * - [[TransitionService.onStart]] + * + * To create a `TargetState`, use [[StateService.target]]. + * + * --- + * + * This class wraps: + * + * 1) an identifier for a state + * 2) a set of parameters + * 3) and transition options + * 4) the registered state object (the [[StateDeclaration]]) + * + * Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can + * either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string). + * The `TargetState` class normalizes those options. + * + * A `TargetState` may be valid (the state being targeted exists in the registry) + * or invalid (the state being targeted is not registered). + */ + var TargetState = /** @class */ (function() { /** * The TargetState constructor * @@ -1461,59 +1592,57 @@ var TargetState = /** @class */ (function () { * @internalapi */ function TargetState(_stateRegistry, _identifier, _params, _options) { - this._stateRegistry = _stateRegistry; - this._identifier = _identifier; - this._identifier = _identifier; - this._params = extend({}, _params || {}); - this._options = extend({}, _options || {}); - this._definition = _stateRegistry.matcher.find(_identifier, this._options.relative); + this._stateRegistry = _stateRegistry; + this._identifier = _identifier; + this._identifier = _identifier; + this._params = extend({}, _params || {}); + this._options = extend({}, _options || {}); + this._definition = _stateRegistry.matcher.find(_identifier, this._options.relative); } /** The name of the state this object targets */ - TargetState.prototype.name = function () { - return this._definition && this._definition.name || this._identifier; + TargetState.prototype.name = function() { + return (this._definition && this._definition.name) || this._identifier; }; /** The identifier used when creating this TargetState */ - TargetState.prototype.identifier = function () { - return this._identifier; + TargetState.prototype.identifier = function() { + return this._identifier; }; /** The target parameter values */ - TargetState.prototype.params = function () { - return this._params; + TargetState.prototype.params = function() { + return this._params; }; /** The internal state object (if it was found) */ - TargetState.prototype.$state = function () { - return this._definition; + TargetState.prototype.$state = function() { + return this._definition; }; /** The internal state declaration (if it was found) */ - TargetState.prototype.state = function () { - return this._definition && this._definition.self; + TargetState.prototype.state = function() { + return this._definition && this._definition.self; }; /** The target options */ - TargetState.prototype.options = function () { - return this._options; + TargetState.prototype.options = function() { + return this._options; }; /** True if the target state was found */ - TargetState.prototype.exists = function () { - return !!(this._definition && this._definition.self); + TargetState.prototype.exists = function() { + return !!(this._definition && this._definition.self); }; /** True if the object is valid */ - TargetState.prototype.valid = function () { - return !this.error(); + TargetState.prototype.valid = function() { + return !this.error(); }; /** If the object is invalid, returns the reason why */ - TargetState.prototype.error = function () { - var base = this.options().relative; - if (!this._definition && !!base) { - var stateName = base.name ? base.name : base; - return "Could not resolve '" + this.name() + "' from state '" + stateName + "'"; - } - if (!this._definition) - return "No such state '" + this.name() + "'"; - if (!this._definition.self) - return "State '" + this.name() + "' has an invalid definition"; + TargetState.prototype.error = function() { + var base = this.options().relative; + if (!this._definition && !!base) { + var stateName = base.name ? base.name : base; + return "Could not resolve '" + this.name() + "' from state '" + stateName + "'"; + } + if (!this._definition) return "No such state '" + this.name() + "'"; + if (!this._definition.self) return "State '" + this.name() + "' has an invalid definition"; }; - TargetState.prototype.toString = function () { - return "'" + this.name() + "'" + stringify(this.params()); + TargetState.prototype.toString = function() { + return "'" + this.name() + "'" + stringify(this.params()); }; /** * Returns a copy of this TargetState which targets a different state. @@ -1521,8 +1650,8 @@ var TargetState = /** @class */ (function () { * * @param state The new state that should be targeted */ - TargetState.prototype.withState = function (state) { - return new TargetState(this._stateRegistry, state, this._params, this._options); + TargetState.prototype.withState = function(state) { + return new TargetState(this._stateRegistry, state, this._params, this._options); }; /** * Returns a copy of this TargetState, using the specified parameter values. @@ -1531,10 +1660,12 @@ var TargetState = /** @class */ (function () { * @param replace When false (default) the new parameter values will be merged with the current values. * When true the parameter values will be used instead of the current values. */ - TargetState.prototype.withParams = function (params, replace) { - if (replace === void 0) { replace = false; } - var newParams = replace ? params : extend({}, this._params, params); - return new TargetState(this._stateRegistry, this._identifier, newParams, this._options); + TargetState.prototype.withParams = function(params, replace) { + if (replace === void 0) { + replace = false; + } + var newParams = replace ? params : extend({}, this._params, params); + return new TargetState(this._stateRegistry, this._identifier, newParams, this._options); }; /** * Returns a copy of this TargetState, using the specified Transition Options. @@ -1543,42 +1674,43 @@ var TargetState = /** @class */ (function () { * @param replace When false (default) the new options will be merged with the current options. * When true the options will be used instead of the current options. */ - TargetState.prototype.withOptions = function (options, replace) { - if (replace === void 0) { replace = false; } - var newOpts = replace ? options : extend({}, this._options, options); - return new TargetState(this._stateRegistry, this._identifier, this._params, newOpts); + TargetState.prototype.withOptions = function(options, replace) { + if (replace === void 0) { + replace = false; + } + var newOpts = replace ? options : extend({}, this._options, options); + return new TargetState(this._stateRegistry, this._identifier, this._params, newOpts); }; /** Returns true if the object has a state property that might be a state or state name */ - TargetState.isDef = function (obj) { - return obj && obj.state && (isString(obj.state) || isString(obj.state.name)); + TargetState.isDef = function(obj) { + return obj && obj.state && (isString(obj.state) || isString(obj.state.name)); }; return TargetState; -}()); + })(); -/** - * @coreapi - * @module transition - */ -/** for typedoc */ -var defaultOptions = { + /** + * @coreapi + * @module transition + */ + var defaultOptions = { current: noop, transition: null, traceData: {}, bind: null, -}; -/** @hidden */ -var TransitionHook = /** @class */ (function () { + }; + /** @hidden */ + var TransitionHook = /** @class */ (function() { function TransitionHook(transition, stateContext, registeredHook, options) { - var _this = this; - this.transition = transition; - this.stateContext = stateContext; - this.registeredHook = registeredHook; - this.options = options; - this.isSuperseded = function () { - return _this.type.hookPhase === exports.TransitionHookPhase.RUN && !_this.options.transition.isActive(); - }; - this.options = defaults(options, defaultOptions); - this.type = registeredHook.eventType; + var _this = this; + this.transition = transition; + this.stateContext = stateContext; + this.registeredHook = registeredHook; + this.options = options; + this.isSuperseded = function() { + return _this.type.hookPhase === exports.TransitionHookPhase.RUN && !_this.options.transition.isActive(); + }; + this.options = defaults(options, defaultOptions); + this.type = registeredHook.eventType; } /** * Chains together an array of TransitionHooks. @@ -1598,12 +1730,14 @@ var TransitionHook = /** @class */ (function () { * @param waitFor if provided, the chain is `.then()`'ed off this promise * @returns a `Promise` for sequentially invoking the hooks (in order) */ - TransitionHook.chain = function (hooks, waitFor) { - // Chain the next hook off the previous - var createHookChainR = function (prev, nextHook) { - return prev.then(function () { return nextHook.invokeHook(); }); - }; - return hooks.reduce(createHookChainR, waitFor || services.$q.when()); + TransitionHook.chain = function(hooks, waitFor) { + // Chain the next hook off the previous + var createHookChainR = function(prev, nextHook) { + return prev.then(function() { + return nextHook.invokeHook(); + }); + }; + return hooks.reduce(createHookChainR, waitFor || services.$q.when()); }; /** * Invokes all the provided TransitionHooks, in order. @@ -1616,67 +1750,62 @@ var TransitionHook = /** @class */ (function () { * * @returns a promise for the async result, or the result of the callback */ - TransitionHook.invokeHooks = function (hooks, doneCallback) { - for (var idx = 0; idx < hooks.length; idx++) { - var hookResult = hooks[idx].invokeHook(); - if (isPromise(hookResult)) { - var remainingHooks = hooks.slice(idx + 1); - return TransitionHook.chain(remainingHooks, hookResult) - .then(doneCallback); - } + TransitionHook.invokeHooks = function(hooks, doneCallback) { + for (var idx = 0; idx < hooks.length; idx++) { + var hookResult = hooks[idx].invokeHook(); + if (isPromise(hookResult)) { + var remainingHooks = hooks.slice(idx + 1); + return TransitionHook.chain(remainingHooks, hookResult).then(doneCallback); } - return doneCallback(); + } + return doneCallback(); }; /** * Run all TransitionHooks, ignoring their return value. */ - TransitionHook.runAllHooks = function (hooks) { - hooks.forEach(function (hook) { return hook.invokeHook(); }); + TransitionHook.runAllHooks = function(hooks) { + hooks.forEach(function(hook) { + return hook.invokeHook(); + }); }; - TransitionHook.prototype.logError = function (err) { - this.transition.router.stateService.defaultErrorHandler()(err); + TransitionHook.prototype.logError = function(err) { + this.transition.router.stateService.defaultErrorHandler()(err); }; - TransitionHook.prototype.invokeHook = function () { - var _this = this; - var hook = this.registeredHook; - if (hook._deregistered) - return; - var notCurrent = this.getNotCurrentRejection(); - if (notCurrent) - return notCurrent; - var options = this.options; - trace.traceHookInvocation(this, this.transition, options); - var invokeCallback = function () { - return hook.callback.call(options.bind, _this.transition, _this.stateContext); - }; - var normalizeErr = function (err) { - return Rejection.normalize(err).toPromise(); - }; - var handleError = function (err) { - return hook.eventType.getErrorHandler(_this)(err); - }; - var handleResult = function (result) { - return hook.eventType.getResultHandler(_this)(result); - }; - try { - var result = invokeCallback(); - if (!this.type.synchronous && isPromise(result)) { - return result.catch(normalizeErr) - .then(handleResult, handleError); - } - else { - return handleResult(result); - } + TransitionHook.prototype.invokeHook = function() { + var _this = this; + var hook = this.registeredHook; + if (hook._deregistered) return; + var notCurrent = this.getNotCurrentRejection(); + if (notCurrent) return notCurrent; + var options = this.options; + trace.traceHookInvocation(this, this.transition, options); + var invokeCallback = function() { + return hook.callback.call(options.bind, _this.transition, _this.stateContext); + }; + var normalizeErr = function(err) { + return Rejection.normalize(err).toPromise(); + }; + var handleError = function(err) { + return hook.eventType.getErrorHandler(_this)(err); + }; + var handleResult = function(result) { + return hook.eventType.getResultHandler(_this)(result); + }; + try { + var result = invokeCallback(); + if (!this.type.synchronous && isPromise(result)) { + return result.catch(normalizeErr).then(handleResult, handleError); + } else { + return handleResult(result); } - catch (err) { - // If callback throws (synchronously) - return handleError(Rejection.normalize(err)); - } - finally { - if (hook.invokeLimit && ++hook.invokeCount >= hook.invokeLimit) { - hook.deregister(); - } + } catch (err) { + // If callback throws (synchronously) + return handleError(Rejection.normalize(err)); + } finally { + if (hook.invokeLimit && ++hook.invokeCount >= hook.invokeLimit) { + hook.deregister(); } + } }; /** * This method handles the return value of a Transition Hook. @@ -1687,136 +1816,153 @@ var TransitionHook = /** @class */ (function () { * This also handles "transition superseded" -- when a new transition * was started while the hook was still running */ - TransitionHook.prototype.handleHookResult = function (result) { - var _this = this; - var notCurrent = this.getNotCurrentRejection(); - if (notCurrent) - return notCurrent; - // Hook returned a promise - if (isPromise(result)) { - // Wait for the promise, then reprocess with the resulting value - return result.then(function (val$$1) { return _this.handleHookResult(val$$1); }); - } - trace.traceHookResult(result, this.transition, this.options); - // Hook returned false - if (result === false) { - // Abort this Transition - return Rejection.aborted('Hook aborted transition').toPromise(); - } - var isTargetState = is(TargetState); - // hook returned a TargetState - if (isTargetState(result)) { - // Halt the current Transition and redirect (a new Transition) to the TargetState. - return Rejection.redirected(result).toPromise(); - } + TransitionHook.prototype.handleHookResult = function(result) { + var _this = this; + var notCurrent = this.getNotCurrentRejection(); + if (notCurrent) return notCurrent; + // Hook returned a promise + if (isPromise(result)) { + // Wait for the promise, then reprocess with the resulting value + return result.then(function(val$$1) { + return _this.handleHookResult(val$$1); + }); + } + trace.traceHookResult(result, this.transition, this.options); + // Hook returned false + if (result === false) { + // Abort this Transition + return Rejection.aborted('Hook aborted transition').toPromise(); + } + var isTargetState = is(TargetState); + // hook returned a TargetState + if (isTargetState(result)) { + // Halt the current Transition and redirect (a new Transition) to the TargetState. + return Rejection.redirected(result).toPromise(); + } }; /** * Return a Rejection promise if the transition is no longer current due * to a stopped router (disposed), or a new transition has started and superseded this one. */ - TransitionHook.prototype.getNotCurrentRejection = function () { - var router = this.transition.router; - // The router is stopped - if (router._disposed) { - return Rejection.aborted("UIRouter instance #" + router.$id + " has been stopped (disposed)").toPromise(); - } - if (this.transition._aborted) { - return Rejection.aborted().toPromise(); - } - // This transition is no longer current. - // Another transition started while this hook was still running. - if (this.isSuperseded()) { - // Abort this transition - return Rejection.superseded(this.options.current()).toPromise(); - } + TransitionHook.prototype.getNotCurrentRejection = function() { + var router = this.transition.router; + // The router is stopped + if (router._disposed) { + return Rejection.aborted('UIRouter instance #' + router.$id + ' has been stopped (disposed)').toPromise(); + } + if (this.transition._aborted) { + return Rejection.aborted().toPromise(); + } + // This transition is no longer current. + // Another transition started while this hook was still running. + if (this.isSuperseded()) { + // Abort this transition + return Rejection.superseded(this.options.current()).toPromise(); + } }; - TransitionHook.prototype.toString = function () { - var _a = this, options = _a.options, registeredHook = _a.registeredHook; - var event = parse('traceData.hookType')(options) || 'internal', context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown', name = fnToString(registeredHook.callback); - return event + " context: " + context + ", " + maxLength(200, name); + TransitionHook.prototype.toString = function() { + var _a = this, + options = _a.options, + registeredHook = _a.registeredHook; + var event = parse('traceData.hookType')(options) || 'internal', + context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown', + name = fnToString(registeredHook.callback); + return event + ' context: ' + context + ', ' + maxLength(200, name); }; /** * These GetResultHandler(s) are used by [[invokeHook]] below * Each HookType chooses a GetResultHandler (See: [[TransitionService._defineCoreEvents]]) */ - TransitionHook.HANDLE_RESULT = function (hook) { return function (result) { + TransitionHook.HANDLE_RESULT = function(hook) { + return function(result) { return hook.handleHookResult(result); - }; }; + }; + }; /** * If the result is a promise rejection, log it. * Otherwise, ignore the result. */ - TransitionHook.LOG_REJECTED_RESULT = function (hook) { return function (result) { - isPromise(result) && result.catch(function (err) { + TransitionHook.LOG_REJECTED_RESULT = function(hook) { + return function(result) { + isPromise(result) && + result.catch(function(err) { return hook.logError(Rejection.normalize(err)); - }); + }); return undefined; - }; }; + }; + }; /** * These GetErrorHandler(s) are used by [[invokeHook]] below * Each HookType chooses a GetErrorHandler (See: [[TransitionService._defineCoreEvents]]) */ - TransitionHook.LOG_ERROR = function (hook) { return function (error) { + TransitionHook.LOG_ERROR = function(hook) { + return function(error) { return hook.logError(error); - }; }; - TransitionHook.REJECT_ERROR = function (hook) { return function (error) { + }; + }; + TransitionHook.REJECT_ERROR = function(hook) { + return function(error) { return silentRejection(error); - }; }; - TransitionHook.THROW_ERROR = function (hook) { return function (error) { + }; + }; + TransitionHook.THROW_ERROR = function(hook) { + return function(error) { throw error; - }; }; + }; + }; return TransitionHook; -}()); + })(); /** for typedoc */ -/** - * @coreapi - * @module transition - */ /** for typedoc */ -/** - * Determines if the given state matches the matchCriteria - * - * @hidden - * - * @param state a State Object to test against - * @param criterion - * - If a string, matchState uses the string as a glob-matcher against the state name - * - If an array (of strings), matchState uses each string in the array as a glob-matchers against the state name - * and returns a positive match if any of the globs match. - * - If a function, matchState calls the function with the state and returns true if the function's result is truthy. - * @returns {boolean} - */ -function matchState(state, criterion) { + /** + * @coreapi + * @module transition + */ /** + * Determines if the given state matches the matchCriteria + * + * @hidden + * + * @param state a State Object to test against + * @param criterion + * - If a string, matchState uses the string as a glob-matcher against the state name + * - If an array (of strings), matchState uses each string in the array as a glob-matchers against the state name + * and returns a positive match if any of the globs match. + * - If a function, matchState calls the function with the state and returns true if the function's result is truthy. + * @returns {boolean} + */ + function matchState(state, criterion) { var toMatch = isString(criterion) ? [criterion] : criterion; function matchGlobs(_state) { - var globStrings = toMatch; - for (var i = 0; i < globStrings.length; i++) { - var glob = new Glob(globStrings[i]); - if ((glob && glob.matches(_state.name)) || (!glob && globStrings[i] === _state.name)) { - return true; - } + var globStrings = toMatch; + for (var i = 0; i < globStrings.length; i++) { + var glob = new Glob(globStrings[i]); + if ((glob && glob.matches(_state.name)) || (!glob && globStrings[i] === _state.name)) { + return true; } - return false; + } + return false; } - var matchFn = (isFunction(toMatch) ? toMatch : matchGlobs); + var matchFn = isFunction(toMatch) ? toMatch : matchGlobs; return !!matchFn(state); -} -/** - * @internalapi - * The registration data for a registered transition hook - */ -var RegisteredHook = /** @class */ (function () { + } + /** + * @internalapi + * The registration data for a registered transition hook + */ + var RegisteredHook = /** @class */ (function() { function RegisteredHook(tranSvc, eventType, callback, matchCriteria, removeHookFromRegistry, options) { - if (options === void 0) { options = {}; } - this.tranSvc = tranSvc; - this.eventType = eventType; - this.callback = callback; - this.matchCriteria = matchCriteria; - this.removeHookFromRegistry = removeHookFromRegistry; - this.invokeCount = 0; - this._deregistered = false; - this.priority = options.priority || 0; - this.bind = options.bind || null; - this.invokeLimit = options.invokeLimit; + if (options === void 0) { + options = {}; + } + this.tranSvc = tranSvc; + this.eventType = eventType; + this.callback = callback; + this.matchCriteria = matchCriteria; + this.removeHookFromRegistry = removeHookFromRegistry; + this.invokeCount = 0; + this._deregistered = false; + this.priority = options.priority || 0; + this.bind = options.bind || null; + this.invokeLimit = options.invokeLimit; } /** * Gets the matching [[PathNode]]s @@ -1833,11 +1979,12 @@ var RegisteredHook = /** @class */ (function () { * with `entering: (state) => true` which only matches when a state is actually * being entered. */ - RegisteredHook.prototype._matchingNodes = function (nodes, criterion) { - if (criterion === true) - return nodes; - var matching = nodes.filter(function (node) { return matchState(node.state, criterion); }); - return matching.length ? matching : null; + RegisteredHook.prototype._matchingNodes = function(nodes, criterion) { + if (criterion === true) return nodes; + var matching = nodes.filter(function(node) { + return matchState(node.state, criterion); + }); + return matching.length ? matching : null; }; /** * Gets the default match criteria (all `true`) @@ -1853,8 +2000,10 @@ var RegisteredHook = /** @class */ (function () { * retained: true, * } */ - RegisteredHook.prototype._getDefaultMatchCriteria = function () { - return mapObj(this.tranSvc._pluginapi._getPathTypes(), function () { return true; }); + RegisteredHook.prototype._getDefaultMatchCriteria = function() { + return mapObj(this.tranSvc._pluginapi._getPathTypes(), function() { + return true; + }); }; /** * Gets matching nodes as [[IMatchingNodes]] @@ -1871,19 +2020,19 @@ var RegisteredHook = /** @class */ (function () { * }; * ``` */ - RegisteredHook.prototype._getMatchingNodes = function (treeChanges) { - var _this = this; - var criteria = extend(this._getDefaultMatchCriteria(), this.matchCriteria); - var paths = values(this.tranSvc._pluginapi._getPathTypes()); - return paths.reduce(function (mn, pathtype) { - // STATE scope criteria matches against every node in the path. - // TRANSITION scope criteria matches against only the last node in the path - var isStateHook = pathtype.scope === exports.TransitionHookScope.STATE; - var path = treeChanges[pathtype.name] || []; - var nodes = isStateHook ? path : [tail(path)]; - mn[pathtype.name] = _this._matchingNodes(nodes, criteria[pathtype.name]); - return mn; - }, {}); + RegisteredHook.prototype._getMatchingNodes = function(treeChanges) { + var _this = this; + var criteria = extend(this._getDefaultMatchCriteria(), this.matchCriteria); + var paths = values(this.tranSvc._pluginapi._getPathTypes()); + return paths.reduce(function(mn, pathtype) { + // STATE scope criteria matches against every node in the path. + // TRANSITION scope criteria matches against only the last node in the path + var isStateHook = pathtype.scope === exports.TransitionHookScope.STATE; + var path = treeChanges[pathtype.name] || []; + var nodes = isStateHook ? path : [tail(path)]; + mn[pathtype.name] = _this._matchingNodes(nodes, criteria[pathtype.name]); + return mn; + }, {}); }; /** * Determines if this hook's [[matchCriteria]] match the given [[TreeChanges]] @@ -1891,64 +2040,75 @@ var RegisteredHook = /** @class */ (function () { * @returns an IMatchingNodes object, or null. If an IMatchingNodes object is returned, its values * are the matching [[PathNode]]s for each [[HookMatchCriterion]] (to, from, exiting, retained, entering) */ - RegisteredHook.prototype.matches = function (treeChanges) { - var matches = this._getMatchingNodes(treeChanges); - // Check if all the criteria matched the TreeChanges object - var allMatched = values(matches).every(identity); - return allMatched ? matches : null; + RegisteredHook.prototype.matches = function(treeChanges) { + var matches = this._getMatchingNodes(treeChanges); + // Check if all the criteria matched the TreeChanges object + var allMatched = values(matches).every(identity); + return allMatched ? matches : null; }; - RegisteredHook.prototype.deregister = function () { - this.removeHookFromRegistry(this); - this._deregistered = true; + RegisteredHook.prototype.deregister = function() { + this.removeHookFromRegistry(this); + this._deregistered = true; }; return RegisteredHook; -}()); -/** @hidden Return a registration function of the requested type. */ -function makeEvent(registry, transitionService, eventType) { + })(); + /** @hidden Return a registration function of the requested type. */ + function makeEvent(registry, transitionService, eventType) { // Create the object which holds the registered transition hooks. - var _registeredHooks = registry._registeredHooks = (registry._registeredHooks || {}); - var hooks = _registeredHooks[eventType.name] = []; + var _registeredHooks = (registry._registeredHooks = registry._registeredHooks || {}); + var hooks = (_registeredHooks[eventType.name] = []); var removeHookFn = removeFrom(hooks); // Create hook registration function on the IHookRegistry for the event registry[eventType.name] = hookRegistrationFn; function hookRegistrationFn(matchObject, callback, options) { - if (options === void 0) { options = {}; } - var registeredHook = new RegisteredHook(transitionService, eventType, callback, matchObject, removeHookFn, options); - hooks.push(registeredHook); - return registeredHook.deregister.bind(registeredHook); + if (options === void 0) { + options = {}; + } + var registeredHook = new RegisteredHook( + transitionService, + eventType, + callback, + matchObject, + removeHookFn, + options, + ); + hooks.push(registeredHook); + return registeredHook.deregister.bind(registeredHook); } return hookRegistrationFn; -} + } /** for typedoc */ -/** - * @coreapi - * @module transition - */ /** for typedoc */ -/** - * This class returns applicable TransitionHooks for a specific Transition instance. - * - * Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g. - * myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is - * determined by the type of hook) - * - * The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition. - * - * The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder - * instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private - * in the Transition class, so we must also provide the Transition's _treeChanges) - * - */ -var HookBuilder = /** @class */ (function () { + /** + * @coreapi + * @module transition + */ /** + * This class returns applicable TransitionHooks for a specific Transition instance. + * + * Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g. + * myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is + * determined by the type of hook) + * + * The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition. + * + * The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder + * instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private + * in the Transition class, so we must also provide the Transition's _treeChanges) + * + */ + var HookBuilder = /** @class */ (function() { function HookBuilder(transition) { - this.transition = transition; + this.transition = transition; } - HookBuilder.prototype.buildHooksForPhase = function (phase) { - var _this = this; - var $transitions = this.transition.router.transitionService; - return $transitions._pluginapi._getEvents(phase) - .map(function (type) { return _this.buildHooks(type); }) - .reduce(unnestR, []) - .filter(identity); + HookBuilder.prototype.buildHooksForPhase = function(phase) { + var _this = this; + var $transitions = this.transition.router.transitionService; + return $transitions._pluginapi + ._getEvents(phase) + .map(function(type) { + return _this.buildHooks(type); + }) + .reduce(unnestR, []) + .filter(identity); }; /** * Returns an array of newly built TransitionHook objects. @@ -1959,37 +2119,42 @@ var HookBuilder = /** @class */ (function () { * * @param hookType the type of the hook registration function, e.g., 'onEnter', 'onFinish'. */ - HookBuilder.prototype.buildHooks = function (hookType) { - var transition = this.transition; - var treeChanges = transition.treeChanges(); - // Find all the matching registered hooks for a given hook type - var matchingHooks = this.getMatchingHooks(hookType, treeChanges); - if (!matchingHooks) - return []; - var baseHookOptions = { - transition: transition, - current: transition.options().current, - }; - var makeTransitionHooks = function (hook) { - // Fetch the Nodes that caused this hook to match. - var matches = hook.matches(treeChanges); - // Select the PathNode[] that will be used as TransitionHook context objects - var matchingNodes = matches[hookType.criteriaMatchPath.name]; - // Return an array of HookTuples - return matchingNodes.map(function (node) { - var _options = extend({ - bind: hook.bind, - traceData: { hookType: hookType.name, context: node }, - }, baseHookOptions); - var state = hookType.criteriaMatchPath.scope === exports.TransitionHookScope.STATE ? node.state.self : null; - var transitionHook = new TransitionHook(transition, state, hook, _options); - return { hook: hook, node: node, transitionHook: transitionHook }; - }); - }; - return matchingHooks.map(makeTransitionHooks) - .reduce(unnestR, []) - .sort(tupleSort(hookType.reverseSort)) - .map(function (tuple) { return tuple.transitionHook; }); + HookBuilder.prototype.buildHooks = function(hookType) { + var transition = this.transition; + var treeChanges = transition.treeChanges(); + // Find all the matching registered hooks for a given hook type + var matchingHooks = this.getMatchingHooks(hookType, treeChanges); + if (!matchingHooks) return []; + var baseHookOptions = { + transition: transition, + current: transition.options().current, + }; + var makeTransitionHooks = function(hook) { + // Fetch the Nodes that caused this hook to match. + var matches = hook.matches(treeChanges); + // Select the PathNode[] that will be used as TransitionHook context objects + var matchingNodes = matches[hookType.criteriaMatchPath.name]; + // Return an array of HookTuples + return matchingNodes.map(function(node) { + var _options = extend( + { + bind: hook.bind, + traceData: { hookType: hookType.name, context: node }, + }, + baseHookOptions, + ); + var state = hookType.criteriaMatchPath.scope === exports.TransitionHookScope.STATE ? node.state.self : null; + var transitionHook = new TransitionHook(transition, state, hook, _options); + return { hook: hook, node: node, transitionHook: transitionHook }; + }); + }; + return matchingHooks + .map(makeTransitionHooks) + .reduce(unnestR, []) + .sort(tupleSort(hookType.reverseSort)) + .map(function(tuple) { + return tuple.transitionHook; + }); }; /** * Finds all RegisteredHooks from: @@ -2002,97 +2167,112 @@ var HookBuilder = /** @class */ (function () { * * @returns an array of matched [[RegisteredHook]]s */ - HookBuilder.prototype.getMatchingHooks = function (hookType, treeChanges) { - var isCreate = hookType.hookPhase === exports.TransitionHookPhase.CREATE; - // Instance and Global hook registries - var $transitions = this.transition.router.transitionService; - var registries = isCreate ? [$transitions] : [this.transition, $transitions]; - return registries.map(function (reg) { return reg.getHooks(hookType.name); }) // Get named hooks from registries - .filter(assertPredicate(isArray, "broken event named: " + hookType.name)) // Sanity check - .reduce(unnestR, []) // Un-nest RegisteredHook[][] to RegisteredHook[] array - .filter(function (hook) { return hook.matches(treeChanges); }); // Only those satisfying matchCriteria + HookBuilder.prototype.getMatchingHooks = function(hookType, treeChanges) { + var isCreate = hookType.hookPhase === exports.TransitionHookPhase.CREATE; + // Instance and Global hook registries + var $transitions = this.transition.router.transitionService; + var registries = isCreate ? [$transitions] : [this.transition, $transitions]; + return registries + .map(function(reg) { + return reg.getHooks(hookType.name); + }) // Get named hooks from registries + .filter(assertPredicate(isArray, 'broken event named: ' + hookType.name)) // Sanity check + .reduce(unnestR, []) // Un-nest RegisteredHook[][] to RegisteredHook[] array + .filter(function(hook) { + return hook.matches(treeChanges); + }); // Only those satisfying matchCriteria }; return HookBuilder; -}()); -/** - * A factory for a sort function for HookTuples. - * - * The sort function first compares the PathNode depth (how deep in the state tree a node is), then compares - * the EventHook priority. - * - * @param reverseDepthSort a boolean, when true, reverses the sort order for the node depth - * @returns a tuple sort function - */ -function tupleSort(reverseDepthSort) { - if (reverseDepthSort === void 0) { reverseDepthSort = false; } + })(); + /** + * A factory for a sort function for HookTuples. + * + * The sort function first compares the PathNode depth (how deep in the state tree a node is), then compares + * the EventHook priority. + * + * @param reverseDepthSort a boolean, when true, reverses the sort order for the node depth + * @returns a tuple sort function + */ + function tupleSort(reverseDepthSort) { + if (reverseDepthSort === void 0) { + reverseDepthSort = false; + } return function nodeDepthThenPriority(l, r) { - var factor = reverseDepthSort ? -1 : 1; - var depthDelta = (l.node.state.path.length - r.node.state.path.length) * factor; - return depthDelta !== 0 ? depthDelta : r.hook.priority - l.hook.priority; + var factor = reverseDepthSort ? -1 : 1; + var depthDelta = (l.node.state.path.length - r.node.state.path.length) * factor; + return depthDelta !== 0 ? depthDelta : r.hook.priority - l.hook.priority; }; -} + } -/** - * @coreapi - * @module params - */ -/** */ -/** - * An internal class which implements [[ParamTypeDefinition]]. - * - * A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types. - * When a param type definition is registered, an instance of this class is created internally. - * - * This class has naive implementations for all the [[ParamTypeDefinition]] methods. - * - * Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values. - * - * #### Example: - * ```js - * var paramTypeDef = { - * decode: function(val) { return parseInt(val, 10); }, - * encode: function(val) { return val && val.toString(); }, - * equals: function(a, b) { return this.is(a) && a === b; }, - * is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; }, - * pattern: /\d+/ - * } - * - * var paramType = new ParamType(paramTypeDef); - * ``` - * @internalapi - */ -var ParamType = /** @class */ (function () { + /** + * @coreapi + * @module params + */ + /** + * An internal class which implements [[ParamTypeDefinition]]. + * + * A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types. + * When a param type definition is registered, an instance of this class is created internally. + * + * This class has naive implementations for all the [[ParamTypeDefinition]] methods. + * + * Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values. + * + * #### Example: + * ```js + * var paramTypeDef = { + * decode: function(val) { return parseInt(val, 10); }, + * encode: function(val) { return val && val.toString(); }, + * equals: function(a, b) { return this.is(a) && a === b; }, + * is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; }, + * pattern: /\d+/ + * } + * + * var paramType = new ParamType(paramTypeDef); + * ``` + * @internalapi + */ + var ParamType = /** @class */ (function() { /** * @param def A configuration object which contains the custom type definition. The object's * properties will override the default methods and/or pattern in `ParamType`'s public interface. * @returns a new ParamType object */ function ParamType(def) { - /** @inheritdoc */ - this.pattern = /.*/; - /** @inheritdoc */ - this.inherit = true; - extend(this, def); + /** @inheritdoc */ + this.pattern = /.*/; + /** @inheritdoc */ + this.inherit = true; + extend(this, def); } // consider these four methods to be "abstract methods" that should be overridden /** @inheritdoc */ - ParamType.prototype.is = function (val, key) { return true; }; - /** @inheritdoc */ - ParamType.prototype.encode = function (val, key) { return val; }; - /** @inheritdoc */ - ParamType.prototype.decode = function (val, key) { return val; }; - /** @inheritdoc */ - ParamType.prototype.equals = function (a, b) { return a == b; }; // tslint:disable-line:triple-equals - ParamType.prototype.$subPattern = function () { - var sub = this.pattern.toString(); - return sub.substr(1, sub.length - 2); + ParamType.prototype.is = function(val, key) { + return true; }; - ParamType.prototype.toString = function () { - return "{ParamType:" + this.name + "}"; + /** @inheritdoc */ + ParamType.prototype.encode = function(val, key) { + return val; + }; + /** @inheritdoc */ + ParamType.prototype.decode = function(val, key) { + return val; + }; + /** @inheritdoc */ + ParamType.prototype.equals = function(a, b) { + // tslint:disable-next-line:triple-equals + return a == b; + }; + ParamType.prototype.$subPattern = function() { + var sub = this.pattern.toString(); + return sub.substr(1, sub.length - 2); + }; + ParamType.prototype.toString = function() { + return '{ParamType:' + this.name + '}'; }; /** Given an encoded string, or a decoded object, returns a decoded object */ - ParamType.prototype.$normalize = function (val) { - return this.is(val) ? val : this.decode(val); + ParamType.prototype.$normalize = function(val) { + return this.is(val) ? val : this.decode(val); }; /** * Wraps an existing custom ParamType as an array of ParamType, depending on 'mode'. @@ -2104,170 +2284,187 @@ var ParamType = /** @class */ (function () { * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1 * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2] */ - ParamType.prototype.$asArray = function (mode, isSearch) { - if (!mode) - return this; - if (mode === 'auto' && !isSearch) - throw new Error("'auto' array mode is for query parameters only"); - return new ArrayType(this, mode); + ParamType.prototype.$asArray = function(mode, isSearch) { + if (!mode) return this; + if (mode === 'auto' && !isSearch) throw new Error("'auto' array mode is for query parameters only"); + return new ArrayType(this, mode); }; return ParamType; -}()); -/** - * Wraps up a `ParamType` object to handle array values. - * @internalapi - */ -function ArrayType(type, mode) { + })(); + /** + * Wraps up a `ParamType` object to handle array values. + * @internalapi + */ + function ArrayType(type, mode) { var _this = this; // Wrap non-array value as array function arrayWrap(val) { - return isArray(val) ? val : (isDefined(val) ? [val] : []); + return isArray(val) ? val : isDefined(val) ? [val] : []; } // Unwrap array value for "auto" mode. Return undefined for empty array. function arrayUnwrap(val) { - switch (val.length) { - case 0: return undefined; - case 1: return mode === 'auto' ? val[0] : val; - default: return val; - } + switch (val.length) { + case 0: + return undefined; + case 1: + return mode === 'auto' ? val[0] : val; + default: + return val; + } } // Wraps type (.is/.encode/.decode) functions to operate on each value of an array function arrayHandler(callback, allTruthyMode) { - return function handleArray(val) { - if (isArray(val) && val.length === 0) - return val; - var arr = arrayWrap(val); - var result = map(arr, callback); - return (allTruthyMode === true) ? filter(result, function (x) { return !x; }).length === 0 : arrayUnwrap(result); - }; + return function handleArray(val) { + if (isArray(val) && val.length === 0) return val; + var arr = arrayWrap(val); + var result = map(arr, callback); + return allTruthyMode === true + ? filter(result, function(x) { + return !x; + }).length === 0 + : arrayUnwrap(result); + }; } // Wraps type (.equals) functions to operate on each value of an array function arrayEqualsHandler(callback) { - return function handleArray(val1, val2) { - var left = arrayWrap(val1), right = arrayWrap(val2); - if (left.length !== right.length) - return false; - for (var i = 0; i < left.length; i++) { - if (!callback(left[i], right[i])) - return false; - } - return true; - }; + return function handleArray(val1, val2) { + var left = arrayWrap(val1), + right = arrayWrap(val2); + if (left.length !== right.length) return false; + for (var i = 0; i < left.length; i++) { + if (!callback(left[i], right[i])) return false; + } + return true; + }; } - ['encode', 'decode', 'equals', '$normalize'].forEach(function (name) { - var paramTypeFn = type[name].bind(type); - var wrapperFn = name === 'equals' ? arrayEqualsHandler : arrayHandler; - _this[name] = wrapperFn(paramTypeFn); + ['encode', 'decode', 'equals', '$normalize'].forEach(function(name) { + var paramTypeFn = type[name].bind(type); + var wrapperFn = name === 'equals' ? arrayEqualsHandler : arrayHandler; + _this[name] = wrapperFn(paramTypeFn); }); extend(this, { - dynamic: type.dynamic, - name: type.name, - pattern: type.pattern, - inherit: type.inherit, - is: arrayHandler(type.is.bind(type), true), - $arrayMode: mode, + dynamic: type.dynamic, + name: type.name, + pattern: type.pattern, + inherit: type.inherit, + is: arrayHandler(type.is.bind(type), true), + $arrayMode: mode, }); -} + } /** for typedoc */ -/** - * @coreapi - * @module params - */ /** for typedoc */ -/** @hidden */ -var hasOwn = Object.prototype.hasOwnProperty; -/** @hidden */ -var isShorthand = function (cfg) { + /** + * @coreapi + * @module params + */ /** @hidden */ + var hasOwn = Object.prototype.hasOwnProperty; + /** @hidden */ + var isShorthand = function(cfg) { return ['value', 'type', 'squash', 'array', 'dynamic'].filter(hasOwn.bind(cfg || {})).length === 0; -}; -/** @internalapi */ + }; + /** @internalapi */ -(function (DefType) { - DefType[DefType["PATH"] = 0] = "PATH"; - DefType[DefType["SEARCH"] = 1] = "SEARCH"; - DefType[DefType["CONFIG"] = 2] = "CONFIG"; -})(exports.DefType || (exports.DefType = {})); -/** @hidden */ -function unwrapShorthand(cfg) { - cfg = isShorthand(cfg) && { value: cfg } || cfg; + (function(DefType) { + DefType[(DefType['PATH'] = 0)] = 'PATH'; + DefType[(DefType['SEARCH'] = 1)] = 'SEARCH'; + DefType[(DefType['CONFIG'] = 2)] = 'CONFIG'; + })(exports.DefType || (exports.DefType = {})); + /** @hidden */ + function unwrapShorthand(cfg) { + cfg = (isShorthand(cfg) && { value: cfg }) || cfg; getStaticDefaultValue['__cacheable'] = true; function getStaticDefaultValue() { - return cfg.value; + return cfg.value; } return extend(cfg, { - $$fn: isInjectable(cfg.value) ? cfg.value : getStaticDefaultValue, + $$fn: isInjectable(cfg.value) ? cfg.value : getStaticDefaultValue, }); -} -/** @hidden */ -function getType(cfg, urlType, location, id, paramTypes) { + } + /** @hidden */ + function getType(cfg, urlType, location, id, paramTypes) { if (cfg.type && urlType && urlType.name !== 'string') - throw new Error("Param '" + id + "' has two type configurations."); - if (cfg.type && urlType && urlType.name === 'string' && paramTypes.type(cfg.type)) - return paramTypes.type(cfg.type); - if (urlType) - return urlType; + throw new Error("Param '" + id + "' has two type configurations."); + if (cfg.type && urlType && urlType.name === 'string' && paramTypes.type(cfg.type)) return paramTypes.type(cfg.type); + if (urlType) return urlType; if (!cfg.type) { - var type = location === exports.DefType.CONFIG ? 'any' : - location === exports.DefType.PATH ? 'path' : - location === exports.DefType.SEARCH ? 'query' : 'string'; - return paramTypes.type(type); + var type = + location === exports.DefType.CONFIG + ? 'any' + : location === exports.DefType.PATH + ? 'path' + : location === exports.DefType.SEARCH + ? 'query' + : 'string'; + return paramTypes.type(type); } return cfg.type instanceof ParamType ? cfg.type : paramTypes.type(cfg.type); -} -/** - * @internalapi - * returns false, true, or the squash value to indicate the "default parameter url squash policy". - */ -function getSquashPolicy(config, isOptional, defaultPolicy) { + } + /** + * @internalapi + * returns false, true, or the squash value to indicate the "default parameter url squash policy". + */ + function getSquashPolicy(config, isOptional, defaultPolicy) { var squash = config.squash; - if (!isOptional || squash === false) - return false; - if (!isDefined(squash) || squash == null) - return defaultPolicy; - if (squash === true || isString(squash)) - return squash; + if (!isOptional || squash === false) return false; + if (!isDefined(squash) || squash == null) return defaultPolicy; + if (squash === true || isString(squash)) return squash; throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); -} -/** @internalapi */ -function getReplace(config, arrayMode, isOptional, squash) { + } + /** @internalapi */ + function getReplace(config, arrayMode, isOptional, squash) { var defaultPolicy = [ - { from: '', to: (isOptional || arrayMode ? undefined : '') }, - { from: null, to: (isOptional || arrayMode ? undefined : '') }, + { from: '', to: isOptional || arrayMode ? undefined : '' }, + { from: null, to: isOptional || arrayMode ? undefined : '' }, ]; var replace = isArray(config.replace) ? config.replace : []; - if (isString(squash)) - replace.push({ from: squash, to: undefined }); + if (isString(squash)) replace.push({ from: squash, to: undefined }); var configuredKeys = map(replace, prop('from')); - return filter(defaultPolicy, function (item) { return configuredKeys.indexOf(item.from) === -1; }).concat(replace); -} -/** @internalapi */ -var Param = /** @class */ (function () { + return filter(defaultPolicy, function(item) { + return configuredKeys.indexOf(item.from) === -1; + }).concat(replace); + } + /** @internalapi */ + var Param = /** @class */ (function() { function Param(id, type, config, location, urlMatcherFactory) { - config = unwrapShorthand(config); - type = getType(config, type, location, id, urlMatcherFactory.paramTypes); - var arrayMode = getArrayMode(); - type = arrayMode ? type.$asArray(arrayMode, location === exports.DefType.SEARCH) : type; - var isOptional = config.value !== undefined || location === exports.DefType.SEARCH; - var dynamic = isDefined(config.dynamic) ? !!config.dynamic : !!type.dynamic; - var raw = isDefined(config.raw) ? !!config.raw : !!type.raw; - var squash = getSquashPolicy(config, isOptional, urlMatcherFactory.defaultSquashPolicy()); - var replace = getReplace(config, arrayMode, isOptional, squash); - var inherit$$1 = isDefined(config.inherit) ? !!config.inherit : !!type.inherit; - // array config: param name (param[]) overrides default settings. explicit config overrides param name. - function getArrayMode() { - var arrayDefaults = { array: (location === exports.DefType.SEARCH ? 'auto' : false) }; - var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {}; - return extend(arrayDefaults, arrayParamNomenclature, config).array; - } - extend(this, { id: id, type: type, location: location, isOptional: isOptional, dynamic: dynamic, raw: raw, squash: squash, replace: replace, inherit: inherit$$1, array: arrayMode, config: config }); + config = unwrapShorthand(config); + type = getType(config, type, location, id, urlMatcherFactory.paramTypes); + var arrayMode = getArrayMode(); + type = arrayMode ? type.$asArray(arrayMode, location === exports.DefType.SEARCH) : type; + var isOptional = config.value !== undefined || location === exports.DefType.SEARCH; + var dynamic = isDefined(config.dynamic) ? !!config.dynamic : !!type.dynamic; + var raw = isDefined(config.raw) ? !!config.raw : !!type.raw; + var squash = getSquashPolicy(config, isOptional, urlMatcherFactory.defaultSquashPolicy()); + var replace = getReplace(config, arrayMode, isOptional, squash); + var inherit$$1 = isDefined(config.inherit) ? !!config.inherit : !!type.inherit; + // array config: param name (param[]) overrides default settings. explicit config overrides param name. + function getArrayMode() { + var arrayDefaults = { array: location === exports.DefType.SEARCH ? 'auto' : false }; + var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {}; + return extend(arrayDefaults, arrayParamNomenclature, config).array; + } + extend(this, { + id: id, + type: type, + location: location, + isOptional: isOptional, + dynamic: dynamic, + raw: raw, + squash: squash, + replace: replace, + inherit: inherit$$1, + array: arrayMode, + config: config, + }); } - Param.values = function (params, values$$1) { - if (values$$1 === void 0) { values$$1 = {}; } - var paramValues = {}; - for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { - var param = params_1[_i]; - paramValues[param.id] = param.value(values$$1[param.id]); - } - return paramValues; + Param.values = function(params, values$$1) { + if (values$$1 === void 0) { + values$$1 = {}; + } + var paramValues = {}; + for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { + var param = params_1[_i]; + paramValues[param.id] = param.value(values$$1[param.id]); + } + return paramValues; }; /** * Finds [[Param]] objects which have different param values @@ -2280,10 +2477,16 @@ var Param = /** @class */ (function () { * * @returns any Param objects whose values were different between values1 and values2 */ - Param.changed = function (params, values1, values2) { - if (values1 === void 0) { values1 = {}; } - if (values2 === void 0) { values2 = {}; } - return params.filter(function (param) { return !param.type.equals(values1[param.id], values2[param.id]); }); + Param.changed = function(params, values1, values2) { + if (values1 === void 0) { + values1 = {}; + } + if (values2 === void 0) { + values2 = {}; + } + return params.filter(function(param) { + return !param.type.equals(values1[param.id], values2[param.id]); + }); }; /** * Checks if two param value objects are equal (for a set of [[Param]] objects) @@ -2294,121 +2497,140 @@ var Param = /** @class */ (function () { * * @returns true if the param values in values1 and values2 are equal */ - Param.equals = function (params, values1, values2) { - if (values1 === void 0) { values1 = {}; } - if (values2 === void 0) { values2 = {}; } - return Param.changed(params, values1, values2).length === 0; + Param.equals = function(params, values1, values2) { + if (values1 === void 0) { + values1 = {}; + } + if (values2 === void 0) { + values2 = {}; + } + return Param.changed(params, values1, values2).length === 0; }; /** Returns true if a the parameter values are valid, according to the Param definitions */ - Param.validates = function (params, values$$1) { - if (values$$1 === void 0) { values$$1 = {}; } - return params.map(function (param) { return param.validates(values$$1[param.id]); }).reduce(allTrueR, true); + Param.validates = function(params, values$$1) { + if (values$$1 === void 0) { + values$$1 = {}; + } + return params + .map(function(param) { + return param.validates(values$$1[param.id]); + }) + .reduce(allTrueR, true); }; - Param.prototype.isDefaultValue = function (value) { - return this.isOptional && this.type.equals(this.value(), value); + Param.prototype.isDefaultValue = function(value) { + return this.isOptional && this.type.equals(this.value(), value); }; /** * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the * default value, which may be the result of an injectable function. */ - Param.prototype.value = function (value) { - var _this = this; - /** - * [Internal] Get the default value of a parameter, which may be an injectable function. - */ - var getDefaultValue = function () { - if (_this._defaultValueCache) - return _this._defaultValueCache.defaultValue; - if (!services.$injector) - throw new Error('Injectable functions cannot be called at configuration time'); - var defaultValue = services.$injector.invoke(_this.config.$$fn); - if (defaultValue !== null && defaultValue !== undefined && !_this.type.is(defaultValue)) - throw new Error("Default value (" + defaultValue + ") for parameter '" + _this.id + "' is not an instance of ParamType (" + _this.type.name + ")"); - if (_this.config.$$fn['__cacheable']) { - _this._defaultValueCache = { defaultValue: defaultValue }; - } - return defaultValue; - }; - var replaceSpecialValues = function (val$$1) { - for (var _i = 0, _a = _this.replace; _i < _a.length; _i++) { - var tuple = _a[_i]; - if (tuple.from === val$$1) - return tuple.to; - } - return val$$1; - }; - value = replaceSpecialValues(value); - return isUndefined(value) ? getDefaultValue() : this.type.$normalize(value); + Param.prototype.value = function(value) { + var _this = this; + /** + * [Internal] Get the default value of a parameter, which may be an injectable function. + */ + var getDefaultValue = function() { + if (_this._defaultValueCache) return _this._defaultValueCache.defaultValue; + if (!services.$injector) throw new Error('Injectable functions cannot be called at configuration time'); + var defaultValue = services.$injector.invoke(_this.config.$$fn); + if (defaultValue !== null && defaultValue !== undefined && !_this.type.is(defaultValue)) + throw new Error( + 'Default value (' + + defaultValue + + ") for parameter '" + + _this.id + + "' is not an instance of ParamType (" + + _this.type.name + + ')', + ); + if (_this.config.$$fn['__cacheable']) { + _this._defaultValueCache = { defaultValue: defaultValue }; + } + return defaultValue; + }; + var replaceSpecialValues = function(val$$1) { + for (var _i = 0, _a = _this.replace; _i < _a.length; _i++) { + var tuple = _a[_i]; + if (tuple.from === val$$1) return tuple.to; + } + return val$$1; + }; + value = replaceSpecialValues(value); + return isUndefined(value) ? getDefaultValue() : this.type.$normalize(value); }; - Param.prototype.isSearch = function () { - return this.location === exports.DefType.SEARCH; + Param.prototype.isSearch = function() { + return this.location === exports.DefType.SEARCH; }; - Param.prototype.validates = function (value) { - // There was no parameter value, but the param is optional - if ((isUndefined(value) || value === null) && this.isOptional) - return true; - // The value was not of the correct ParamType, and could not be decoded to the correct ParamType - var normalized = this.type.$normalize(value); - if (!this.type.is(normalized)) - return false; - // The value was of the correct type, but when encoded, did not match the ParamType's regexp - var encoded = this.type.encode(normalized); - return !(isString(encoded) && !this.type.pattern.exec(encoded)); + Param.prototype.validates = function(value) { + // There was no parameter value, but the param is optional + if ((isUndefined(value) || value === null) && this.isOptional) return true; + // The value was not of the correct ParamType, and could not be decoded to the correct ParamType + var normalized = this.type.$normalize(value); + if (!this.type.is(normalized)) return false; + // The value was of the correct type, but when encoded, did not match the ParamType's regexp + var encoded = this.type.encode(normalized); + return !(isString(encoded) && !this.type.pattern.exec(encoded)); }; - Param.prototype.toString = function () { - return "{Param:" + this.id + " " + this.type + " squash: '" + this.squash + "' optional: " + this.isOptional + "}"; + Param.prototype.toString = function() { + return ( + '{Param:' + this.id + ' ' + this.type + " squash: '" + this.squash + "' optional: " + this.isOptional + '}' + ); }; return Param; -}()); + })(); /** for typedoc */ -/** @module path */ /** for typedoc */ -/** - * @internalapi - * - * A node in a [[TreeChanges]] path - * - * For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path. - * Each PathNode corresponds to a state being entered, exited, or retained. - * The stateful information includes parameter values and resolve data. - */ -var PathNode = /** @class */ (function () { + /** @module path */ /** + * @internalapi + * + * A node in a [[TreeChanges]] path + * + * For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path. + * Each PathNode corresponds to a state being entered, exited, or retained. + * The stateful information includes parameter values and resolve data. + */ + var PathNode = /** @class */ (function() { function PathNode(stateOrNode) { - if (stateOrNode instanceof PathNode) { - var node = stateOrNode; - this.state = node.state; - this.paramSchema = node.paramSchema.slice(); - this.paramValues = extend({}, node.paramValues); - this.resolvables = node.resolvables.slice(); - this.views = node.views && node.views.slice(); - } - else { - var state = stateOrNode; - this.state = state; - this.paramSchema = state.parameters({ inherit: false }); - this.paramValues = {}; - this.resolvables = state.resolvables.map(function (res) { return res.clone(); }); - } + if (stateOrNode instanceof PathNode) { + var node = stateOrNode; + this.state = node.state; + this.paramSchema = node.paramSchema.slice(); + this.paramValues = extend({}, node.paramValues); + this.resolvables = node.resolvables.slice(); + this.views = node.views && node.views.slice(); + } else { + var state = stateOrNode; + this.state = state; + this.paramSchema = state.parameters({ inherit: false }); + this.paramValues = {}; + this.resolvables = state.resolvables.map(function(res) { + return res.clone(); + }); + } } - PathNode.prototype.clone = function () { - return new PathNode(this); + PathNode.prototype.clone = function() { + return new PathNode(this); }; /** Sets [[paramValues]] for the node, from the values of an object hash */ - PathNode.prototype.applyRawParams = function (params) { - var getParamVal = function (paramDef) { return [paramDef.id, paramDef.value(params[paramDef.id])]; }; - this.paramValues = this.paramSchema.reduce(function (memo, pDef) { return applyPairs(memo, getParamVal(pDef)); }, {}); - return this; + PathNode.prototype.applyRawParams = function(params) { + var getParamVal = function(paramDef) { + return [paramDef.id, paramDef.value(params[paramDef.id])]; + }; + this.paramValues = this.paramSchema.reduce(function(memo, pDef) { + return applyPairs(memo, getParamVal(pDef)); + }, {}); + return this; }; /** Gets a specific [[Param]] metadata that belongs to the node */ - PathNode.prototype.parameter = function (name) { - return find(this.paramSchema, propEq('id', name)); + PathNode.prototype.parameter = function(name) { + return find(this.paramSchema, propEq('id', name)); }; /** * @returns true if the state and parameter values for another PathNode are * equal to the state and param values for this PathNode */ - PathNode.prototype.equals = function (node, paramsFn) { - var diff = this.diff(node, paramsFn); - return diff && diff.length === 0; + PathNode.prototype.equals = function(node, paramsFn) { + var diff = this.diff(node, paramsFn); + return diff && diff.length === 0; }; /** * Finds Params with different parameter values on another PathNode. @@ -2422,56 +2644,65 @@ var PathNode = /** @class */ (function () { * @param paramsFn A function that returns which parameters should be compared. * @returns The [[Param]]s which differ, or null if the two nodes are for different states */ - PathNode.prototype.diff = function (node, paramsFn) { - if (this.state !== node.state) - return false; - var params = paramsFn ? paramsFn(this) : this.paramSchema; - return Param.changed(params, this.paramValues, node.paramValues); + PathNode.prototype.diff = function(node, paramsFn) { + if (this.state !== node.state) return false; + var params = paramsFn ? paramsFn(this) : this.paramSchema; + return Param.changed(params, this.paramValues, node.paramValues); }; /** * Returns a clone of the PathNode * @deprecated use instance method `node.clone()` */ - PathNode.clone = function (node) { return node.clone(); }; - return PathNode; -}()); - -/** @module path */ /** for typedoc */ -/** - * This class contains functions which convert TargetStates, Nodes and paths from one type to another. - */ -var PathUtils = /** @class */ (function () { - function PathUtils() { - } - /** Given a PathNode[], create an TargetState */ - PathUtils.makeTargetState = function (registry, path) { - var state = tail(path).state; - return new TargetState(registry, state, path.map(prop('paramValues')).reduce(mergeR, {}), {}); + PathNode.clone = function(node) { + return node.clone(); }; - PathUtils.buildPath = function (targetState) { - var toParams = targetState.params(); - return targetState.$state().path.map(function (state) { return new PathNode(state).applyRawParams(toParams); }); + return PathNode; + })(); /** for typedoc */ + + /** @module path */ /** + * This class contains functions which convert TargetStates, Nodes and paths from one type to another. + */ + var PathUtils = /** @class */ (function() { + function PathUtils() {} + /** Given a PathNode[], create an TargetState */ + PathUtils.makeTargetState = function(registry, path) { + var state = tail(path).state; + return new TargetState(registry, state, path.map(prop('paramValues')).reduce(mergeR, {}), {}); + }; + PathUtils.buildPath = function(targetState) { + var toParams = targetState.params(); + return targetState.$state().path.map(function(state) { + return new PathNode(state).applyRawParams(toParams); + }); }; /** Given a fromPath: PathNode[] and a TargetState, builds a toPath: PathNode[] */ - PathUtils.buildToPath = function (fromPath, targetState) { - var toPath = PathUtils.buildPath(targetState); - if (targetState.options().inherit) { - return PathUtils.inheritParams(fromPath, toPath, Object.keys(targetState.params())); - } - return toPath; + PathUtils.buildToPath = function(fromPath, targetState) { + var toPath = PathUtils.buildPath(targetState); + if (targetState.options().inherit) { + return PathUtils.inheritParams(fromPath, toPath, Object.keys(targetState.params())); + } + return toPath; }; /** * Creates ViewConfig objects and adds to nodes. * * On each [[PathNode]], creates ViewConfig objects from the views: property of the node's state */ - PathUtils.applyViewConfigs = function ($view, path, states) { - // Only apply the viewConfigs to the nodes for the given states - path.filter(function (node) { return inArray(states, node.state); }).forEach(function (node) { - var viewDecls = values(node.state.views || {}); - var subPath = PathUtils.subPath(path, function (n) { return n === node; }); - var viewConfigs = viewDecls.map(function (view) { return $view.createViewConfig(subPath, view); }); - node.views = viewConfigs.reduce(unnestR, []); + PathUtils.applyViewConfigs = function($view, path, states) { + // Only apply the viewConfigs to the nodes for the given states + path + .filter(function(node) { + return inArray(states, node.state); + }) + .forEach(function(node) { + var viewDecls = values(node.state.views || {}); + var subPath = PathUtils.subPath(path, function(n) { + return n === node; + }); + var viewConfigs = viewDecls.map(function(view) { + return $view.createViewConfig(subPath, view); + }); + node.views = viewConfigs.reduce(unnestR, []); }); }; /** @@ -2485,61 +2716,75 @@ var PathUtils = /** @class */ (function () { * caller, for instance, $state.transitionTo(..., toParams). If a key was found in toParams, * it is not inherited from the fromPath. */ - PathUtils.inheritParams = function (fromPath, toPath, toKeys) { - if (toKeys === void 0) { toKeys = []; } - function nodeParamVals(path, state) { - var node = find(path, propEq('state', state)); - return extend({}, node && node.paramValues); - } - var noInherit = fromPath.map(function (node) { return node.paramSchema; }) - .reduce(unnestR, []) - .filter(function (param) { return !param.inherit; }) - .map(prop('id')); - /** - * Given an [[PathNode]] "toNode", return a new [[PathNode]] with param values inherited from the - * matching node in fromPath. Only inherit keys that aren't found in "toKeys" from the node in "fromPath"" - */ - function makeInheritedParamsNode(toNode) { - // All param values for the node (may include default key/vals, when key was not found in toParams) - var toParamVals = extend({}, toNode && toNode.paramValues); - // limited to only those keys found in toParams - var incomingParamVals = pick(toParamVals, toKeys); - toParamVals = omit(toParamVals, toKeys); - var fromParamVals = omit(nodeParamVals(fromPath, toNode.state) || {}, noInherit); - // extend toParamVals with any fromParamVals, then override any of those those with incomingParamVals - var ownParamVals = extend(toParamVals, fromParamVals, incomingParamVals); - return new PathNode(toNode.state).applyRawParams(ownParamVals); - } - // The param keys specified by the incoming toParams - return toPath.map(makeInheritedParamsNode); + PathUtils.inheritParams = function(fromPath, toPath, toKeys) { + if (toKeys === void 0) { + toKeys = []; + } + function nodeParamVals(path, state) { + var node = find(path, propEq('state', state)); + return extend({}, node && node.paramValues); + } + var noInherit = fromPath + .map(function(node) { + return node.paramSchema; + }) + .reduce(unnestR, []) + .filter(function(param) { + return !param.inherit; + }) + .map(prop('id')); + /** + * Given an [[PathNode]] "toNode", return a new [[PathNode]] with param values inherited from the + * matching node in fromPath. Only inherit keys that aren't found in "toKeys" from the node in "fromPath"" + */ + function makeInheritedParamsNode(toNode) { + // All param values for the node (may include default key/vals, when key was not found in toParams) + var toParamVals = extend({}, toNode && toNode.paramValues); + // limited to only those keys found in toParams + var incomingParamVals = pick(toParamVals, toKeys); + toParamVals = omit(toParamVals, toKeys); + var fromParamVals = omit(nodeParamVals(fromPath, toNode.state) || {}, noInherit); + // extend toParamVals with any fromParamVals, then override any of those those with incomingParamVals + var ownParamVals = extend(toParamVals, fromParamVals, incomingParamVals); + return new PathNode(toNode.state).applyRawParams(ownParamVals); + } + // The param keys specified by the incoming toParams + return toPath.map(makeInheritedParamsNode); }; /** * Computes the tree changes (entering, exiting) between a fromPath and toPath. */ - PathUtils.treeChanges = function (fromPath, toPath, reloadState) { - var max = Math.min(fromPath.length, toPath.length); - var keep = 0; - var nodesMatch = function (node1, node2) { - return node1.equals(node2, PathUtils.nonDynamicParams); - }; - while (keep < max && fromPath[keep].state !== reloadState && nodesMatch(fromPath[keep], toPath[keep])) { - keep++; - } - /** Given a retained node, return a new node which uses the to node's param values */ - function applyToParams(retainedNode, idx) { - var cloned = retainedNode.clone(); - cloned.paramValues = toPath[idx].paramValues; - return cloned; - } - var from, retained, exiting, entering, to; - from = fromPath; - retained = from.slice(0, keep); - exiting = from.slice(keep); - // Create a new retained path (with shallow copies of nodes) which have the params of the toPath mapped - var retainedWithToParams = retained.map(applyToParams); - entering = toPath.slice(keep); - to = (retainedWithToParams).concat(entering); - return { from: from, to: to, retained: retained, retainedWithToParams: retainedWithToParams, exiting: exiting, entering: entering }; + PathUtils.treeChanges = function(fromPath, toPath, reloadState) { + var max = Math.min(fromPath.length, toPath.length); + var keep = 0; + var nodesMatch = function(node1, node2) { + return node1.equals(node2, PathUtils.nonDynamicParams); + }; + while (keep < max && fromPath[keep].state !== reloadState && nodesMatch(fromPath[keep], toPath[keep])) { + keep++; + } + /** Given a retained node, return a new node which uses the to node's param values */ + function applyToParams(retainedNode, idx) { + var cloned = retainedNode.clone(); + cloned.paramValues = toPath[idx].paramValues; + return cloned; + } + var from, retained, exiting, entering, to; + from = fromPath; + retained = from.slice(0, keep); + exiting = from.slice(keep); + // Create a new retained path (with shallow copies of nodes) which have the params of the toPath mapped + var retainedWithToParams = retained.map(applyToParams); + entering = toPath.slice(keep); + to = retainedWithToParams.concat(entering); + return { + from: from, + to: to, + retained: retained, + retainedWithToParams: retainedWithToParams, + exiting: exiting, + entering: entering, + }; }; /** * Returns a new path which is: the subpath of the first path which matches the second path. @@ -2556,14 +2801,15 @@ var PathUtils = /** @class */ (function () { * * @returns an array of PathNodes from the first path which match the nodes in the second path */ - PathUtils.matching = function (pathA, pathB, paramsFn) { - var done = false; - var tuples = arrayTuples(pathA, pathB); - return tuples.reduce(function (matching, _a) { - var nodeA = _a[0], nodeB = _a[1]; - done = done || !nodeA.equals(nodeB, paramsFn); - return done ? matching : matching.concat(nodeA); - }, []); + PathUtils.matching = function(pathA, pathB, paramsFn) { + var done = false; + var tuples = arrayTuples(pathA, pathB); + return tuples.reduce(function(matching, _a) { + var nodeA = _a[0], + nodeB = _a[1]; + done = done || !nodeA.equals(nodeB, paramsFn); + return done ? matching : matching.concat(nodeA); + }, []); }; /** * Returns true if two paths are identical. @@ -2573,9 +2819,8 @@ var PathUtils = /** @class */ (function () { * @param paramsFn a function which returns the parameters to consider when comparing * @returns true if the the states and parameter values for both paths are identical */ - PathUtils.equals = function (pathA, pathB, paramsFn) { - return pathA.length === pathB.length && - PathUtils.matching(pathA, pathB, paramsFn).length === pathA.length; + PathUtils.equals = function(pathA, pathB, paramsFn) { + return pathA.length === pathB.length && PathUtils.matching(pathA, pathB, paramsFn).length === pathA.length; }; /** * Return a subpath of a path, which stops at the first matching node @@ -2587,75 +2832,73 @@ var PathUtils = /** @class */ (function () { * @param predicate a [[Predicate]] fn that matches [[PathNode]]s * @returns a subpath up to the matching node, or undefined if no match is found */ - PathUtils.subPath = function (path, predicate) { - var node = find(path, predicate); - var elementIdx = path.indexOf(node); - return elementIdx === -1 ? undefined : path.slice(0, elementIdx + 1); + PathUtils.subPath = function(path, predicate) { + var node = find(path, predicate); + var elementIdx = path.indexOf(node); + return elementIdx === -1 ? undefined : path.slice(0, elementIdx + 1); }; - PathUtils.nonDynamicParams = function (node) { - return node.state.parameters({ inherit: false }) - .filter(function (param) { return !param.dynamic; }); + PathUtils.nonDynamicParams = function(node) { + return node.state.parameters({ inherit: false }).filter(function(param) { + return !param.dynamic; + }); }; /** Gets the raw parameter values from a path */ - PathUtils.paramValues = function (path) { - return path.reduce(function (acc, node) { return extend(acc, node.paramValues); }, {}); + PathUtils.paramValues = function(path) { + return path.reduce(function(acc, node) { + return extend(acc, node.paramValues); + }, {}); }; return PathUtils; -}()); + })(); /** for typedoc */ -/** - * @coreapi - * @module resolve - */ /** for typedoc */ -// TODO: explicitly make this user configurable -var defaultResolvePolicy = { + /** + * @coreapi + * @module resolve + */ // TODO: explicitly make this user configurable + var defaultResolvePolicy = { when: 'LAZY', async: 'WAIT', -}; -/** - * The basic building block for the resolve system. - * - * Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise), - * and the unwrapped-when-complete (.data) result of the resolveFn. - * - * Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the - * resolveFn) and returns the resulting promise. - * - * Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first - * parameter to those fns. - */ -var Resolvable = /** @class */ (function () { + }; + /** + * The basic building block for the resolve system. + * + * Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise), + * and the unwrapped-when-complete (.data) result of the resolveFn. + * + * Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the + * resolveFn) and returns the resulting promise. + * + * Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first + * parameter to those fns. + */ + var Resolvable = /** @class */ (function() { function Resolvable(arg1, resolveFn, deps, policy, data) { - this.resolved = false; - this.promise = undefined; - if (arg1 instanceof Resolvable) { - extend(this, arg1); - } - else if (isFunction(resolveFn)) { - if (isNullOrUndefined(arg1)) - throw new Error('new Resolvable(): token argument is required'); - if (!isFunction(resolveFn)) - throw new Error('new Resolvable(): resolveFn argument must be a function'); - this.token = arg1; - this.policy = policy; - this.resolveFn = resolveFn; - this.deps = deps || []; - this.data = data; - this.resolved = data !== undefined; - this.promise = this.resolved ? services.$q.when(this.data) : undefined; - } - else if (isObject(arg1) && arg1.token && (arg1.hasOwnProperty('resolveFn') || arg1.hasOwnProperty('data'))) { - var literal = arg1; - return new Resolvable(literal.token, literal.resolveFn, literal.deps, literal.policy, literal.data); - } + this.resolved = false; + this.promise = undefined; + if (arg1 instanceof Resolvable) { + extend(this, arg1); + } else if (isFunction(resolveFn)) { + if (isNullOrUndefined(arg1)) throw new Error('new Resolvable(): token argument is required'); + if (!isFunction(resolveFn)) throw new Error('new Resolvable(): resolveFn argument must be a function'); + this.token = arg1; + this.policy = policy; + this.resolveFn = resolveFn; + this.deps = deps || []; + this.data = data; + this.resolved = data !== undefined; + this.promise = this.resolved ? services.$q.when(this.data) : undefined; + } else if (isObject(arg1) && arg1.token && (arg1.hasOwnProperty('resolveFn') || arg1.hasOwnProperty('data'))) { + var literal = arg1; + return new Resolvable(literal.token, literal.resolveFn, literal.deps, literal.policy, literal.data); + } } - Resolvable.prototype.getPolicy = function (state) { - var thisPolicy = this.policy || {}; - var statePolicy = state && state.resolvePolicy || {}; - return { - when: thisPolicy.when || statePolicy.when || defaultResolvePolicy.when, - async: thisPolicy.async || statePolicy.async || defaultResolvePolicy.async, - }; + Resolvable.prototype.getPolicy = function(state) { + var thisPolicy = this.policy || {}; + var statePolicy = (state && state.resolvePolicy) || {}; + return { + when: thisPolicy.when || statePolicy.when || defaultResolvePolicy.when, + async: thisPolicy.async || statePolicy.async || defaultResolvePolicy.async, + }; }; /** * Asynchronously resolve this Resolvable's data @@ -2664,49 +2907,57 @@ var Resolvable = /** @class */ (function () { * Wait for this Resolvable's dependencies, then invoke this Resolvable's function * and update the Resolvable's state */ - Resolvable.prototype.resolve = function (resolveContext, trans) { - var _this = this; - var $q = services.$q; - // Gets all dependencies from ResolveContext and wait for them to be resolved - var getResolvableDependencies = function () { - return $q.all(resolveContext.getDependencies(_this).map(function (resolvable) { - return resolvable.get(resolveContext, trans); - })); - }; - // Invokes the resolve function passing the resolved dependencies as arguments - var invokeResolveFn = function (resolvedDeps) { - return _this.resolveFn.apply(null, resolvedDeps); - }; - /** - * For RXWAIT policy: - * - * Given an observable returned from a resolve function: - * - enables .cache() mode (this allows multicast subscribers) - * - then calls toPromise() (this triggers subscribe() and thus fetches) - * - Waits for the promise, then return the cached observable (not the first emitted value). - */ - var waitForRx = function (observable$) { - var cached = observable$.cache(1); - return cached.take(1).toPromise().then(function () { return cached; }); - }; - // If the resolve policy is RXWAIT, wait for the observable to emit something. otherwise pass through. - var node = resolveContext.findNode(this); - var state = node && node.state; - var maybeWaitForRx = this.getPolicy(state).async === 'RXWAIT' ? waitForRx : identity; - // After the final value has been resolved, update the state of the Resolvable - var applyResolvedValue = function (resolvedValue) { - _this.data = resolvedValue; - _this.resolved = true; - _this.resolveFn = null; - trace.traceResolvableResolved(_this, trans); - return _this.data; - }; - // Sets the promise property first, then getsResolvableDependencies in the context of the promise chain. Always waits one tick. - return this.promise = $q.when() - .then(getResolvableDependencies) - .then(invokeResolveFn) - .then(maybeWaitForRx) - .then(applyResolvedValue); + Resolvable.prototype.resolve = function(resolveContext, trans) { + var _this = this; + var $q = services.$q; + // Gets all dependencies from ResolveContext and wait for them to be resolved + var getResolvableDependencies = function() { + return $q.all( + resolveContext.getDependencies(_this).map(function(resolvable) { + return resolvable.get(resolveContext, trans); + }), + ); + }; + // Invokes the resolve function passing the resolved dependencies as arguments + var invokeResolveFn = function(resolvedDeps) { + return _this.resolveFn.apply(null, resolvedDeps); + }; + /** + * For RXWAIT policy: + * + * Given an observable returned from a resolve function: + * - enables .cache() mode (this allows multicast subscribers) + * - then calls toPromise() (this triggers subscribe() and thus fetches) + * - Waits for the promise, then return the cached observable (not the first emitted value). + */ + var waitForRx = function(observable$) { + var cached = observable$.cache(1); + return cached + .take(1) + .toPromise() + .then(function() { + return cached; + }); + }; + // If the resolve policy is RXWAIT, wait for the observable to emit something. otherwise pass through. + var node = resolveContext.findNode(this); + var state = node && node.state; + var maybeWaitForRx = this.getPolicy(state).async === 'RXWAIT' ? waitForRx : identity; + // After the final value has been resolved, update the state of the Resolvable + var applyResolvedValue = function(resolvedValue) { + _this.data = resolvedValue; + _this.resolved = true; + _this.resolveFn = null; + trace.traceResolvableResolved(_this, trans); + return _this.data; + }; + // Sets the promise property first, then getsResolvableDependencies in the context of the promise chain. Always waits one tick. + return (this.promise = $q + .when() + .then(getResolvableDependencies) + .then(invokeResolveFn) + .then(maybeWaitForRx) + .then(applyResolvedValue)); }; /** * Gets a promise for this Resolvable's data. @@ -2714,58 +2965,73 @@ var Resolvable = /** @class */ (function () { * Fetches the data and returns a promise. * Returns the existing promise if it has already been fetched once. */ - Resolvable.prototype.get = function (resolveContext, trans) { - return this.promise || this.resolve(resolveContext, trans); + Resolvable.prototype.get = function(resolveContext, trans) { + return this.promise || this.resolve(resolveContext, trans); }; - Resolvable.prototype.toString = function () { - return "Resolvable(token: " + stringify(this.token) + ", requires: [" + this.deps.map(stringify) + "])"; + Resolvable.prototype.toString = function() { + return 'Resolvable(token: ' + stringify(this.token) + ', requires: [' + this.deps.map(stringify) + '])'; }; - Resolvable.prototype.clone = function () { - return new Resolvable(this); + Resolvable.prototype.clone = function() { + return new Resolvable(this); }; - Resolvable.fromData = function (token, data) { - return new Resolvable(token, function () { return data; }, null, null, data); + Resolvable.fromData = function(token, data) { + return new Resolvable( + token, + function() { + return data; + }, + null, + null, + data, + ); }; return Resolvable; -}()); + })(); -/** @internalapi */ -var resolvePolicies = { + /** @internalapi */ + var resolvePolicies = { when: { - LAZY: 'LAZY', - EAGER: 'EAGER', + LAZY: 'LAZY', + EAGER: 'EAGER', }, async: { - WAIT: 'WAIT', - NOWAIT: 'NOWAIT', - RXWAIT: 'RXWAIT', + WAIT: 'WAIT', + NOWAIT: 'NOWAIT', + RXWAIT: 'RXWAIT', }, -}; + }; -/** @module resolve */ -/** for typedoc */ -var whens = resolvePolicies.when; -var ALL_WHENS = [whens.EAGER, whens.LAZY]; -var EAGER_WHENS = [whens.EAGER]; -// tslint:disable-next-line:no-inferrable-types -var NATIVE_INJECTOR_TOKEN = 'Native Injector'; -/** - * Encapsulates Dependency Injection for a path of nodes - * - * UI-Router states are organized as a tree. - * A nested state has a path of ancestors to the root of the tree. - * When a state is being activated, each element in the path is wrapped as a [[PathNode]]. - * A `PathNode` is a stateful object that holds things like parameters and resolvables for the state being activated. - * - * The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path. - */ -var ResolveContext = /** @class */ (function () { + /** @module resolve */ + var whens = resolvePolicies.when; + var ALL_WHENS = [whens.EAGER, whens.LAZY]; + var EAGER_WHENS = [whens.EAGER]; + // tslint:disable-next-line:no-inferrable-types + var NATIVE_INJECTOR_TOKEN = 'Native Injector'; + /** + * Encapsulates Dependency Injection for a path of nodes + * + * UI-Router states are organized as a tree. + * A nested state has a path of ancestors to the root of the tree. + * When a state is being activated, each element in the path is wrapped as a [[PathNode]]. + * A `PathNode` is a stateful object that holds things like parameters and resolvables for the state being activated. + * + * The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path. + */ + var ResolveContext = /** @class */ (function() { function ResolveContext(_path) { - this._path = _path; + this._path = _path; } /** Gets all the tokens found in the resolve context, de-duplicated */ - ResolveContext.prototype.getTokens = function () { - return this._path.reduce(function (acc, node) { return acc.concat(node.resolvables.map(function (r) { return r.token; })); }, []).reduce(uniqR, []); + ResolveContext.prototype.getTokens = function() { + return this._path + .reduce(function(acc, node) { + return acc.concat( + node.resolvables.map(function(r) { + return r.token; + }), + ); + }, []) + .reduce(uniqR, []); }; /** * Gets the Resolvable that matches the token @@ -2773,16 +3039,21 @@ var ResolveContext = /** @class */ (function () { * Gets the last Resolvable that matches the token in this context, or undefined. * Throws an error if it doesn't exist in the ResolveContext */ - ResolveContext.prototype.getResolvable = function (token) { - var matching = this._path.map(function (node) { return node.resolvables; }) - .reduce(unnestR, []) - .filter(function (r) { return r.token === token; }); - return tail(matching); + ResolveContext.prototype.getResolvable = function(token) { + var matching = this._path + .map(function(node) { + return node.resolvables; + }) + .reduce(unnestR, []) + .filter(function(r) { + return r.token === token; + }); + return tail(matching); }; /** Returns the [[ResolvePolicy]] for the given [[Resolvable]] */ - ResolveContext.prototype.getPolicy = function (resolvable) { - var node = this.findNode(resolvable); - return resolvable.getPolicy(node.state); + ResolveContext.prototype.getPolicy = function(resolvable) { + var node = this.findNode(resolvable); + return resolvable.getPolicy(node.state); }; /** * Returns a ResolveContext that includes a portion of this one @@ -2807,8 +3078,12 @@ var ResolveContext = /** @class */ (function () { * When resolving for the `B` node, first take the full "To Path" Context `[A,B,C,D]` and limit to the subpath `[A,B]`. * `let AB = ABCD.subcontext(a)` */ - ResolveContext.prototype.subContext = function (state) { - return new ResolveContext(PathUtils.subPath(this._path, function (node) { return node.state === state; })); + ResolveContext.prototype.subContext = function(state) { + return new ResolveContext( + PathUtils.subPath(this._path, function(node) { + return node.state === state; + }), + ); }; /** * Adds Resolvables to the node that matches the state @@ -2825,10 +3100,16 @@ var ResolveContext = /** @class */ (function () { * @param newResolvables the new Resolvables * @param state Used to find the node to put the resolvable on */ - ResolveContext.prototype.addResolvables = function (newResolvables, state) { - var node = find(this._path, propEq('state', state)); - var keys = newResolvables.map(function (r) { return r.token; }); - node.resolvables = node.resolvables.filter(function (r) { return keys.indexOf(r.token) === -1; }).concat(newResolvables); + ResolveContext.prototype.addResolvables = function(newResolvables, state) { + var node = find(this._path, propEq('state', state)); + var keys = newResolvables.map(function(r) { + return r.token; + }); + node.resolvables = node.resolvables + .filter(function(r) { + return keys.indexOf(r.token) === -1; + }) + .concat(newResolvables); }; /** * Returns a promise for an array of resolved path Element promises @@ -2837,117 +3118,142 @@ var ResolveContext = /** @class */ (function () { * @param trans * @returns {Promise|any} */ - ResolveContext.prototype.resolvePath = function (when, trans) { - var _this = this; - if (when === void 0) { when = 'LAZY'; } - // This option determines which 'when' policy Resolvables we are about to fetch. - var whenOption = inArray(ALL_WHENS, when) ? when : 'LAZY'; - // If the caller specified EAGER, only the EAGER Resolvables are fetched. - // if the caller specified LAZY, both EAGER and LAZY Resolvables are fetched.` - var matchedWhens = whenOption === resolvePolicies.when.EAGER ? EAGER_WHENS : ALL_WHENS; - // get the subpath to the state argument, if provided - trace.traceResolvePath(this._path, when, trans); - var matchesPolicy = function (acceptedVals, whenOrAsync) { - return function (resolvable) { - return inArray(acceptedVals, _this.getPolicy(resolvable)[whenOrAsync]); - }; + ResolveContext.prototype.resolvePath = function(when, trans) { + var _this = this; + if (when === void 0) { + when = 'LAZY'; + } + // This option determines which 'when' policy Resolvables we are about to fetch. + var whenOption = inArray(ALL_WHENS, when) ? when : 'LAZY'; + // If the caller specified EAGER, only the EAGER Resolvables are fetched. + // if the caller specified LAZY, both EAGER and LAZY Resolvables are fetched.` + var matchedWhens = whenOption === resolvePolicies.when.EAGER ? EAGER_WHENS : ALL_WHENS; + // get the subpath to the state argument, if provided + trace.traceResolvePath(this._path, when, trans); + var matchesPolicy = function(acceptedVals, whenOrAsync) { + return function(resolvable) { + return inArray(acceptedVals, _this.getPolicy(resolvable)[whenOrAsync]); }; - // Trigger all the (matching) Resolvables in the path - // Reduce all the "WAIT" Resolvables into an array - var promises = this._path.reduce(function (acc, node) { - var nodeResolvables = node.resolvables.filter(matchesPolicy(matchedWhens, 'when')); - var nowait = nodeResolvables.filter(matchesPolicy(['NOWAIT'], 'async')); - var wait = nodeResolvables.filter(not(matchesPolicy(['NOWAIT'], 'async'))); - // For the matching Resolvables, start their async fetch process. - var subContext = _this.subContext(node.state); - var getResult = function (r) { return r.get(subContext, trans) - .then(function (value) { return ({ token: r.token, value: value }); }); }; - nowait.forEach(getResult); - return acc.concat(wait.map(getResult)); - }, []); - // Wait for all the "WAIT" resolvables - return services.$q.all(promises); + }; + // Trigger all the (matching) Resolvables in the path + // Reduce all the "WAIT" Resolvables into an array + var promises = this._path.reduce(function(acc, node) { + var nodeResolvables = node.resolvables.filter(matchesPolicy(matchedWhens, 'when')); + var nowait = nodeResolvables.filter(matchesPolicy(['NOWAIT'], 'async')); + var wait = nodeResolvables.filter(not(matchesPolicy(['NOWAIT'], 'async'))); + // For the matching Resolvables, start their async fetch process. + var subContext = _this.subContext(node.state); + var getResult = function(r) { + return ( + r + .get(subContext, trans) + // Return a tuple that includes the Resolvable's token + .then(function(value) { + return { token: r.token, value: value }; + }) + ); + }; + nowait.forEach(getResult); + return acc.concat(wait.map(getResult)); + }, []); + // Wait for all the "WAIT" resolvables + return services.$q.all(promises); }; - ResolveContext.prototype.injector = function () { - return this._injector || (this._injector = new UIInjectorImpl(this)); + ResolveContext.prototype.injector = function() { + return this._injector || (this._injector = new UIInjectorImpl(this)); }; - ResolveContext.prototype.findNode = function (resolvable) { - return find(this._path, function (node) { return inArray(node.resolvables, resolvable); }); + ResolveContext.prototype.findNode = function(resolvable) { + return find(this._path, function(node) { + return inArray(node.resolvables, resolvable); + }); }; /** * Gets the async dependencies of a Resolvable * * Given a Resolvable, returns its dependencies as a Resolvable[] */ - ResolveContext.prototype.getDependencies = function (resolvable) { - var _this = this; - var node = this.findNode(resolvable); - // Find which other resolvables are "visible" to the `resolvable` argument - // subpath stopping at resolvable's node, or the whole path (if the resolvable isn't in the path) - var subPath = PathUtils.subPath(this._path, function (x) { return x === node; }) || this._path; - var availableResolvables = subPath - .reduce(function (acc, _node) { return acc.concat(_node.resolvables); }, []) // all of subpath's resolvables - .filter(function (res) { return res !== resolvable; }); // filter out the `resolvable` argument - var getDependency = function (token) { - var matching = availableResolvables.filter(function (r) { return r.token === token; }); - if (matching.length) - return tail(matching); - var fromInjector = _this.injector().getNative(token); - if (isUndefined(fromInjector)) { - throw new Error('Could not find Dependency Injection token: ' + stringify(token)); - } - return new Resolvable(token, function () { return fromInjector; }, [], fromInjector); - }; - return resolvable.deps.map(getDependency); + ResolveContext.prototype.getDependencies = function(resolvable) { + var _this = this; + var node = this.findNode(resolvable); + // Find which other resolvables are "visible" to the `resolvable` argument + // subpath stopping at resolvable's node, or the whole path (if the resolvable isn't in the path) + var subPath = + PathUtils.subPath(this._path, function(x) { + return x === node; + }) || this._path; + var availableResolvables = subPath + .reduce(function(acc, _node) { + return acc.concat(_node.resolvables); + }, []) // all of subpath's resolvables + .filter(function(res) { + return res !== resolvable; + }); // filter out the `resolvable` argument + var getDependency = function(token) { + var matching = availableResolvables.filter(function(r) { + return r.token === token; + }); + if (matching.length) return tail(matching); + var fromInjector = _this.injector().getNative(token); + if (isUndefined(fromInjector)) { + throw new Error('Could not find Dependency Injection token: ' + stringify(token)); + } + return new Resolvable( + token, + function() { + return fromInjector; + }, + [], + fromInjector, + ); + }; + return resolvable.deps.map(getDependency); }; return ResolveContext; -}()); -var UIInjectorImpl = /** @class */ (function () { + })(); + var UIInjectorImpl = /** @class */ (function() { function UIInjectorImpl(context) { - this.context = context; - this.native = this.get(NATIVE_INJECTOR_TOKEN) || services.$injector; + this.context = context; + this.native = this.get(NATIVE_INJECTOR_TOKEN) || services.$injector; } - UIInjectorImpl.prototype.get = function (token) { - var resolvable = this.context.getResolvable(token); - if (resolvable) { - if (this.context.getPolicy(resolvable).async === 'NOWAIT') { - return resolvable.get(this.context); - } - if (!resolvable.resolved) { - throw new Error('Resolvable async .get() not complete:' + stringify(resolvable.token)); - } - return resolvable.data; + UIInjectorImpl.prototype.get = function(token) { + var resolvable = this.context.getResolvable(token); + if (resolvable) { + if (this.context.getPolicy(resolvable).async === 'NOWAIT') { + return resolvable.get(this.context); } - return this.getNative(token); + if (!resolvable.resolved) { + throw new Error('Resolvable async .get() not complete:' + stringify(resolvable.token)); + } + return resolvable.data; + } + return this.getNative(token); }; - UIInjectorImpl.prototype.getAsync = function (token) { - var resolvable = this.context.getResolvable(token); - if (resolvable) - return resolvable.get(this.context); - return services.$q.when(this.native.get(token)); + UIInjectorImpl.prototype.getAsync = function(token) { + var resolvable = this.context.getResolvable(token); + if (resolvable) return resolvable.get(this.context); + return services.$q.when(this.native.get(token)); }; - UIInjectorImpl.prototype.getNative = function (token) { - return this.native && this.native.get(token); + UIInjectorImpl.prototype.getNative = function(token) { + return this.native && this.native.get(token); }; return UIInjectorImpl; -}()); + })(); -/** - * @coreapi - * @module transition - */ -/** for typedoc */ -/** @hidden */ -var stateSelf = prop('self'); -/** - * Represents a transition between two states. - * - * When navigating to a state, we are transitioning **from** the current state **to** the new state. - * - * This object contains all contextual information about the to/from states, parameters, resolves. - * It has information about all states being entered and exited as a result of the transition. - */ -var Transition = /** @class */ (function () { + /** + * @coreapi + * @module transition + */ + /** @hidden */ + var stateSelf = prop('self'); + /** + * Represents a transition between two states. + * + * When navigating to a state, we are transitioning **from** the current state **to** the new state. + * + * This object contains all contextual information about the to/from states, parameters, resolves. + * It has information about all states being entered and exited as a result of the transition. + */ + var Transition = /** @class */ (function() { /** * Creates a new Transition object. * @@ -2961,88 +3267,113 @@ var Transition = /** @class */ (function () { * @param router The [[UIRouter]] instance */ function Transition(fromPath, targetState, router) { - var _this = this; - /** @hidden */ - this._deferred = services.$q.defer(); - /** - * This promise is resolved or rejected based on the outcome of the Transition. - * - * When the transition is successful, the promise is resolved - * When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error - */ - this.promise = this._deferred.promise; - /** @hidden Holds the hook registration functions such as those passed to Transition.onStart() */ - this._registeredHooks = {}; - /** @hidden */ - this._hookBuilder = new HookBuilder(this); - /** Checks if this transition is currently active/running. */ - this.isActive = function () { - return _this.router.globals.transition === _this; - }; - this.router = router; - this._targetState = targetState; - if (!targetState.valid()) { - throw new Error(targetState.error()); - } - // current() is assumed to come from targetState.options, but provide a naive implementation otherwise. - this._options = extend({ current: val(this) }, targetState.options()); - this.$id = router.transitionService._transitionCount++; - var toPath = PathUtils.buildToPath(fromPath, targetState); - this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState); - this.createTransitionHookRegFns(); - var onCreateHooks = this._hookBuilder.buildHooksForPhase(exports.TransitionHookPhase.CREATE); - TransitionHook.invokeHooks(onCreateHooks, function () { return null; }); - this.applyViewConfigs(router); + var _this = this; + /** @hidden */ + this._deferred = services.$q.defer(); + /** + * This promise is resolved or rejected based on the outcome of the Transition. + * + * When the transition is successful, the promise is resolved + * When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error + */ + this.promise = this._deferred.promise; + /** @hidden Holds the hook registration functions such as those passed to Transition.onStart() */ + this._registeredHooks = {}; + /** @hidden */ + this._hookBuilder = new HookBuilder(this); + /** Checks if this transition is currently active/running. */ + this.isActive = function() { + return _this.router.globals.transition === _this; + }; + this.router = router; + this._targetState = targetState; + if (!targetState.valid()) { + throw new Error(targetState.error()); + } + // current() is assumed to come from targetState.options, but provide a naive implementation otherwise. + this._options = extend({ current: val(this) }, targetState.options()); + this.$id = router.transitionService._transitionCount++; + var toPath = PathUtils.buildToPath(fromPath, targetState); + this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState); + this.createTransitionHookRegFns(); + var onCreateHooks = this._hookBuilder.buildHooksForPhase(exports.TransitionHookPhase.CREATE); + TransitionHook.invokeHooks(onCreateHooks, function() { + return null; + }); + this.applyViewConfigs(router); } /** @hidden */ - Transition.prototype.onBefore = function (criteria, callback, options) { return; }; + Transition.prototype.onBefore = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - Transition.prototype.onStart = function (criteria, callback, options) { return; }; + Transition.prototype.onStart = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - Transition.prototype.onExit = function (criteria, callback, options) { return; }; + Transition.prototype.onExit = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - Transition.prototype.onRetain = function (criteria, callback, options) { return; }; + Transition.prototype.onRetain = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - Transition.prototype.onEnter = function (criteria, callback, options) { return; }; + Transition.prototype.onEnter = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - Transition.prototype.onFinish = function (criteria, callback, options) { return; }; + Transition.prototype.onFinish = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - Transition.prototype.onSuccess = function (criteria, callback, options) { return; }; + Transition.prototype.onSuccess = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - Transition.prototype.onError = function (criteria, callback, options) { return; }; + Transition.prototype.onError = function(criteria, callback, options) { + return; + }; /** @hidden * Creates the transition-level hook registration functions * (which can then be used to register hooks) */ - Transition.prototype.createTransitionHookRegFns = function () { - var _this = this; - this.router.transitionService._pluginapi._getEvents() - .filter(function (type) { return type.hookPhase !== exports.TransitionHookPhase.CREATE; }) - .forEach(function (type) { return makeEvent(_this, _this.router.transitionService, type); }); + Transition.prototype.createTransitionHookRegFns = function() { + var _this = this; + this.router.transitionService._pluginapi + ._getEvents() + .filter(function(type) { + return type.hookPhase !== exports.TransitionHookPhase.CREATE; + }) + .forEach(function(type) { + return makeEvent(_this, _this.router.transitionService, type); + }); }; /** @internalapi */ - Transition.prototype.getHooks = function (hookName) { - return this._registeredHooks[hookName]; + Transition.prototype.getHooks = function(hookName) { + return this._registeredHooks[hookName]; }; - Transition.prototype.applyViewConfigs = function (router) { - var enteringStates = this._treeChanges.entering.map(function (node) { return node.state; }); - PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates); + Transition.prototype.applyViewConfigs = function(router) { + var enteringStates = this._treeChanges.entering.map(function(node) { + return node.state; + }); + PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates); }; /** * @internalapi * * @returns the internal from [State] object */ - Transition.prototype.$from = function () { - return tail(this._treeChanges.from).state; + Transition.prototype.$from = function() { + return tail(this._treeChanges.from).state; }; /** * @internalapi * * @returns the internal to [State] object */ - Transition.prototype.$to = function () { - return tail(this._treeChanges.to).state; + Transition.prototype.$to = function() { + return tail(this._treeChanges.to).state; }; /** * Returns the "from state" @@ -3051,8 +3382,8 @@ var Transition = /** @class */ (function () { * * @returns The state declaration object for the Transition's ("from state"). */ - Transition.prototype.from = function () { - return this.$from().self; + Transition.prototype.from = function() { + return this.$from().self; }; /** * Returns the "to state" @@ -3061,8 +3392,8 @@ var Transition = /** @class */ (function () { * * @returns The state declaration object for the Transition's target state ("to state"). */ - Transition.prototype.to = function () { - return this.$to().self; + Transition.prototype.to = function() { + return this.$to().self; }; /** * Gets the Target State @@ -3071,24 +3402,28 @@ var Transition = /** @class */ (function () { * * @returns the [[TargetState]] of this Transition */ - Transition.prototype.targetState = function () { - return this._targetState; + Transition.prototype.targetState = function() { + return this._targetState; }; /** * Determines whether two transitions are equivalent. * @deprecated */ - Transition.prototype.is = function (compare) { - if (compare instanceof Transition) { - // TODO: Also compare parameters - return this.is({ to: compare.$to().name, from: compare.$from().name }); - } - return !((compare.to && !matchState(this.$to(), compare.to)) || - (compare.from && !matchState(this.$from(), compare.from))); + Transition.prototype.is = function(compare) { + if (compare instanceof Transition) { + // TODO: Also compare parameters + return this.is({ to: compare.$to().name, from: compare.$from().name }); + } + return !( + (compare.to && !matchState(this.$to(), compare.to)) || + (compare.from && !matchState(this.$from(), compare.from)) + ); }; - Transition.prototype.params = function (pathname) { - if (pathname === void 0) { pathname = 'to'; } - return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {})); + Transition.prototype.params = function(pathname) { + if (pathname === void 0) { + pathname = 'to'; + } + return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {})); }; /** * Creates a [[UIInjector]] Dependency Injector @@ -3145,12 +3480,16 @@ var Transition = /** @class */ (function () { * * @returns a [[UIInjector]] */ - Transition.prototype.injector = function (state, pathName) { - if (pathName === void 0) { pathName = 'to'; } - var path = this._treeChanges[pathName]; - if (state) - path = PathUtils.subPath(path, function (node) { return node.state === state || node.state.name === state; }); - return new ResolveContext(path).injector(); + Transition.prototype.injector = function(state, pathName) { + if (pathName === void 0) { + pathName = 'to'; + } + var path = this._treeChanges[pathName]; + if (state) + path = PathUtils.subPath(path, function(node) { + return node.state === state || node.state.name === state; + }); + return new ResolveContext(path).injector(); }; /** * Gets all available resolve tokens (keys) @@ -3184,9 +3523,11 @@ var Transition = /** @class */ (function () { * * @returns an array of resolve tokens (keys) */ - Transition.prototype.getResolveTokens = function (pathname) { - if (pathname === void 0) { pathname = 'to'; } - return new ResolveContext(this._treeChanges[pathname]).getTokens(); + Transition.prototype.getResolveTokens = function(pathname) { + if (pathname === void 0) { + pathname = 'to'; + } + return new ResolveContext(this._treeChanges[pathname]).getTokens(); }; /** * Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition. @@ -3217,14 +3558,18 @@ var Transition = /** @class */ (function () { * @param resolvable a [[ResolvableLiteral]] object (or a [[Resolvable]]) * @param state the state in the "to path" which should receive the new resolve (otherwise, the root state) */ - Transition.prototype.addResolvable = function (resolvable, state) { - if (state === void 0) { state = ''; } - resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable); - var stateName = (typeof state === 'string') ? state : state.name; - var topath = this._treeChanges.to; - var targetNode = find(topath, function (node) { return node.state.name === stateName; }); - var resolveContext = new ResolveContext(topath); - resolveContext.addResolvables([resolvable], targetNode.state); + Transition.prototype.addResolvable = function(resolvable, state) { + if (state === void 0) { + state = ''; + } + resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable); + var stateName = typeof state === 'string' ? state : state.name; + var topath = this._treeChanges.to; + var targetNode = find(topath, function(node) { + return node.state.name === stateName; + }); + var resolveContext = new ResolveContext(topath); + resolveContext.addResolvables([resolvable], targetNode.state); }; /** * Gets the transition from which this transition was redirected. @@ -3243,8 +3588,8 @@ var Transition = /** @class */ (function () { * * @returns The previous Transition, or null if this Transition is not the result of a redirection */ - Transition.prototype.redirectedFrom = function () { - return this._options.redirectedFrom || null; + Transition.prototype.redirectedFrom = function() { + return this._options.redirectedFrom || null; }; /** * Gets the original transition in a redirect chain @@ -3272,33 +3617,35 @@ var Transition = /** @class */ (function () { * * @returns The original Transition that started a redirect chain */ - Transition.prototype.originalTransition = function () { - var rf = this.redirectedFrom(); - return (rf && rf.originalTransition()) || this; + Transition.prototype.originalTransition = function() { + var rf = this.redirectedFrom(); + return (rf && rf.originalTransition()) || this; }; /** * Get the transition options * * @returns the options for this Transition. */ - Transition.prototype.options = function () { - return this._options; + Transition.prototype.options = function() { + return this._options; }; /** * Gets the states being entered. * * @returns an array of states that will be entered during this transition. */ - Transition.prototype.entering = function () { - return map(this._treeChanges.entering, prop('state')).map(stateSelf); + Transition.prototype.entering = function() { + return map(this._treeChanges.entering, prop('state')).map(stateSelf); }; /** * Gets the states being exited. * * @returns an array of states that will be exited during this transition. */ - Transition.prototype.exiting = function () { - return map(this._treeChanges.exiting, prop('state')).map(stateSelf).reverse(); + Transition.prototype.exiting = function() { + return map(this._treeChanges.exiting, prop('state')) + .map(stateSelf) + .reverse(); }; /** * Gets the states being retained. @@ -3306,8 +3653,8 @@ var Transition = /** @class */ (function () { * @returns an array of states that are already entered from a previous Transition, that will not be * exited during this Transition */ - Transition.prototype.retained = function () { - return map(this._treeChanges.retained, prop('state')).map(stateSelf); + Transition.prototype.retained = function() { + return map(this._treeChanges.retained, prop('state')).map(stateSelf); }; /** * Get the [[ViewConfig]]s associated with this Transition @@ -3321,14 +3668,19 @@ var Transition = /** @class */ (function () { * * @returns a list of ViewConfig objects for the given path. */ - Transition.prototype.views = function (pathname, state) { - if (pathname === void 0) { pathname = 'entering'; } - var path = this._treeChanges[pathname]; - path = !state ? path : path.filter(propEq('state', state)); - return path.map(prop('views')).filter(identity).reduce(unnestR, []); + Transition.prototype.views = function(pathname, state) { + if (pathname === void 0) { + pathname = 'entering'; + } + var path = this._treeChanges[pathname]; + path = !state ? path : path.filter(propEq('state', state)); + return path + .map(prop('views')) + .filter(identity) + .reduce(unnestR, []); }; - Transition.prototype.treeChanges = function (pathname) { - return pathname ? this._treeChanges[pathname] : this._treeChanges; + Transition.prototype.treeChanges = function(pathname) { + return pathname ? this._treeChanges[pathname] : this._treeChanges; }; /** * Creates a new transition that is a redirection of the current one. @@ -3340,74 +3692,89 @@ var Transition = /** @class */ (function () { * * @returns Returns a new [[Transition]] instance. */ - Transition.prototype.redirect = function (targetState) { - var redirects = 1, trans = this; - // tslint:disable-next-line:no-conditional-assignment - while ((trans = trans.redirectedFrom()) != null) { - if (++redirects > 20) - throw new Error("Too many consecutive Transition redirects (20+)"); - } - var redirectOpts = { redirectedFrom: this, source: 'redirect' }; - // If the original transition was caused by URL sync, then use { location: 'replace' } - // on the new transition (unless the target state explicitly specifies location: false). - // This causes the original url to be replaced with the url for the redirect target - // so the original url disappears from the browser history. - if (this.options().source === 'url' && targetState.options().location !== false) { - redirectOpts.location = 'replace'; - } - var newOptions = extend({}, this.options(), targetState.options(), redirectOpts); - targetState = targetState.withOptions(newOptions, true); - var newTransition = this.router.transitionService.create(this._treeChanges.from, targetState); - var originalEnteringNodes = this._treeChanges.entering; - var redirectEnteringNodes = newTransition._treeChanges.entering; - // --- Re-use resolve data from original transition --- - // When redirecting from a parent state to a child state where the parent parameter values haven't changed - // (because of the redirect), the resolves fetched by the original transition are still valid in the - // redirected transition. - // - // This allows you to define a redirect on a parent state which depends on an async resolve value. - // You can wait for the resolve, then redirect to a child state based on the result. - // The redirected transition does not have to re-fetch the resolve. - // --------------------------------------------------------- - var nodeIsReloading = function (reloadState) { return function (node) { - return reloadState && node.state.includes[reloadState.name]; - }; }; - // Find any "entering" nodes in the redirect path that match the original path and aren't being reloaded - var matchingEnteringNodes = PathUtils.matching(redirectEnteringNodes, originalEnteringNodes, PathUtils.nonDynamicParams) - .filter(not(nodeIsReloading(targetState.options().reloadState))); - // Use the existing (possibly pre-resolved) resolvables for the matching entering nodes. - matchingEnteringNodes.forEach(function (node, idx) { - node.resolvables = originalEnteringNodes[idx].resolvables; - }); - return newTransition; + Transition.prototype.redirect = function(targetState) { + var redirects = 1, + trans = this; + // tslint:disable-next-line:no-conditional-assignment + while ((trans = trans.redirectedFrom()) != null) { + if (++redirects > 20) throw new Error('Too many consecutive Transition redirects (20+)'); + } + var redirectOpts = { redirectedFrom: this, source: 'redirect' }; + // If the original transition was caused by URL sync, then use { location: 'replace' } + // on the new transition (unless the target state explicitly specifies location: false). + // This causes the original url to be replaced with the url for the redirect target + // so the original url disappears from the browser history. + if (this.options().source === 'url' && targetState.options().location !== false) { + redirectOpts.location = 'replace'; + } + var newOptions = extend({}, this.options(), targetState.options(), redirectOpts); + targetState = targetState.withOptions(newOptions, true); + var newTransition = this.router.transitionService.create(this._treeChanges.from, targetState); + var originalEnteringNodes = this._treeChanges.entering; + var redirectEnteringNodes = newTransition._treeChanges.entering; + // --- Re-use resolve data from original transition --- + // When redirecting from a parent state to a child state where the parent parameter values haven't changed + // (because of the redirect), the resolves fetched by the original transition are still valid in the + // redirected transition. + // + // This allows you to define a redirect on a parent state which depends on an async resolve value. + // You can wait for the resolve, then redirect to a child state based on the result. + // The redirected transition does not have to re-fetch the resolve. + // --------------------------------------------------------- + var nodeIsReloading = function(reloadState) { + return function(node) { + return reloadState && node.state.includes[reloadState.name]; + }; + }; + // Find any "entering" nodes in the redirect path that match the original path and aren't being reloaded + var matchingEnteringNodes = PathUtils.matching( + redirectEnteringNodes, + originalEnteringNodes, + PathUtils.nonDynamicParams, + ).filter(not(nodeIsReloading(targetState.options().reloadState))); + // Use the existing (possibly pre-resolved) resolvables for the matching entering nodes. + matchingEnteringNodes.forEach(function(node, idx) { + node.resolvables = originalEnteringNodes[idx].resolvables; + }); + return newTransition; }; /** @hidden If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */ - Transition.prototype._changedParams = function () { - var tc = this._treeChanges; - /** Return undefined if it's not a "dynamic" transition, for the following reasons */ - // If user explicitly wants a reload - if (this._options.reload) - return undefined; - // If any states are exiting or entering - if (tc.exiting.length || tc.entering.length) - return undefined; - // If to/from path lengths differ - if (tc.to.length !== tc.from.length) - return undefined; - // If the to/from paths are different - var pathsDiffer = arrayTuples(tc.to, tc.from) - .map(function (tuple) { return tuple[0].state !== tuple[1].state; }) - .reduce(anyTrueR, false); - if (pathsDiffer) - return undefined; - // Find any parameter values that differ - var nodeSchemas = tc.to.map(function (node) { return node.paramSchema; }); - var _a = [tc.to, tc.from].map(function (path) { return path.map(function (x) { return x.paramValues; }); }), toValues = _a[0], fromValues = _a[1]; - var tuples = arrayTuples(nodeSchemas, toValues, fromValues); - return tuples.map(function (_a) { - var schema = _a[0], toVals = _a[1], fromVals = _a[2]; - return Param.changed(schema, toVals, fromVals); - }).reduce(unnestR, []); + Transition.prototype._changedParams = function() { + var tc = this._treeChanges; + /** Return undefined if it's not a "dynamic" transition, for the following reasons */ + // If user explicitly wants a reload + if (this._options.reload) return undefined; + // If any states are exiting or entering + if (tc.exiting.length || tc.entering.length) return undefined; + // If to/from path lengths differ + if (tc.to.length !== tc.from.length) return undefined; + // If the to/from paths are different + var pathsDiffer = arrayTuples(tc.to, tc.from) + .map(function(tuple) { + return tuple[0].state !== tuple[1].state; + }) + .reduce(anyTrueR, false); + if (pathsDiffer) return undefined; + // Find any parameter values that differ + var nodeSchemas = tc.to.map(function(node) { + return node.paramSchema; + }); + var _a = [tc.to, tc.from].map(function(path) { + return path.map(function(x) { + return x.paramValues; + }); + }), + toValues = _a[0], + fromValues = _a[1]; + var tuples = arrayTuples(nodeSchemas, toValues, fromValues); + return tuples + .map(function(_a) { + var schema = _a[0], + toVals = _a[1], + fromVals = _a[2]; + return Param.changed(schema, toVals, fromVals); + }) + .reduce(unnestR, []); }; /** * Returns true if the transition is dynamic. @@ -3416,9 +3783,15 @@ var Transition = /** @class */ (function () { * * @returns true if the Transition is dynamic */ - Transition.prototype.dynamic = function () { - var changes = this._changedParams(); - return !changes ? false : changes.map(function (x) { return x.dynamic; }).reduce(anyTrueR, false); + Transition.prototype.dynamic = function() { + var changes = this._changedParams(); + return !changes + ? false + : changes + .map(function(x) { + return x.dynamic; + }) + .reduce(anyTrueR, false); }; /** * Returns true if the transition is ignored. @@ -3427,25 +3800,28 @@ var Transition = /** @class */ (function () { * * @returns true if the Transition is ignored. */ - Transition.prototype.ignored = function () { - return !!this._ignoredReason(); + Transition.prototype.ignored = function() { + return !!this._ignoredReason(); }; /** @hidden */ - Transition.prototype._ignoredReason = function () { - var pending = this.router.globals.transition; - var reloadState = this._options.reloadState; - var same = function (pathA, pathB) { - if (pathA.length !== pathB.length) - return false; - var matching = PathUtils.matching(pathA, pathB); - return pathA.length === matching.filter(function (node) { return !reloadState || !node.state.includes[reloadState.name]; }).length; - }; - var newTC = this.treeChanges(); - var pendTC = pending && pending.treeChanges(); - if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) - return 'SameAsPending'; - if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) - return 'SameAsCurrent'; + Transition.prototype._ignoredReason = function() { + var pending = this.router.globals.transition; + var reloadState = this._options.reloadState; + var same = function(pathA, pathB) { + if (pathA.length !== pathB.length) return false; + var matching = PathUtils.matching(pathA, pathB); + return ( + pathA.length === + matching.filter(function(node) { + return !reloadState || !node.state.includes[reloadState.name]; + }).length + ); + }; + var newTC = this.treeChanges(); + var pendTC = pending && pending.treeChanges(); + if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) return 'SameAsPending'; + if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) + return 'SameAsCurrent'; }; /** * Runs the transition @@ -3456,55 +3832,57 @@ var Transition = /** @class */ (function () { * * @returns a promise for a successful transition. */ - Transition.prototype.run = function () { - var _this = this; - var runAllHooks = TransitionHook.runAllHooks; - // Gets transition hooks array for the given phase - var getHooksFor = function (phase) { - return _this._hookBuilder.buildHooksForPhase(phase); + Transition.prototype.run = function() { + var _this = this; + var runAllHooks = TransitionHook.runAllHooks; + // Gets transition hooks array for the given phase + var getHooksFor = function(phase) { + return _this._hookBuilder.buildHooksForPhase(phase); + }; + // When the chain is complete, then resolve or reject the deferred + var transitionSuccess = function() { + trace.traceSuccess(_this.$to(), _this); + _this.success = true; + _this._deferred.resolve(_this.to()); + runAllHooks(getHooksFor(exports.TransitionHookPhase.SUCCESS)); + }; + var transitionError = function(reason) { + trace.traceError(reason, _this); + _this.success = false; + _this._deferred.reject(reason); + _this._error = reason; + runAllHooks(getHooksFor(exports.TransitionHookPhase.ERROR)); + }; + var runTransition = function() { + // Wait to build the RUN hook chain until the BEFORE hooks are done + // This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object. + var allRunHooks = getHooksFor(exports.TransitionHookPhase.RUN); + var done = function() { + return services.$q.when(undefined); }; - // When the chain is complete, then resolve or reject the deferred - var transitionSuccess = function () { - trace.traceSuccess(_this.$to(), _this); - _this.success = true; - _this._deferred.resolve(_this.to()); - runAllHooks(getHooksFor(exports.TransitionHookPhase.SUCCESS)); - }; - var transitionError = function (reason) { - trace.traceError(reason, _this); - _this.success = false; - _this._deferred.reject(reason); - _this._error = reason; - runAllHooks(getHooksFor(exports.TransitionHookPhase.ERROR)); - }; - var runTransition = function () { - // Wait to build the RUN hook chain until the BEFORE hooks are done - // This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object. - var allRunHooks = getHooksFor(exports.TransitionHookPhase.RUN); - var done = function () { return services.$q.when(undefined); }; - return TransitionHook.invokeHooks(allRunHooks, done); - }; - var startTransition = function () { - var globals = _this.router.globals; - globals.lastStartedTransitionId = _this.$id; - globals.transition = _this; - globals.transitionHistory.enqueue(_this); - trace.traceTransitionStart(_this); - return services.$q.when(undefined); - }; - var allBeforeHooks = getHooksFor(exports.TransitionHookPhase.BEFORE); - TransitionHook.invokeHooks(allBeforeHooks, startTransition) - .then(runTransition) - .then(transitionSuccess, transitionError); - return this.promise; + return TransitionHook.invokeHooks(allRunHooks, done); + }; + var startTransition = function() { + var globals = _this.router.globals; + globals.lastStartedTransitionId = _this.$id; + globals.transition = _this; + globals.transitionHistory.enqueue(_this); + trace.traceTransitionStart(_this); + return services.$q.when(undefined); + }; + var allBeforeHooks = getHooksFor(exports.TransitionHookPhase.BEFORE); + TransitionHook.invokeHooks(allBeforeHooks, startTransition) + .then(runTransition) + .then(transitionSuccess, transitionError); + return this.promise; }; /** * Checks if the Transition is valid * * @returns true if the Transition is valid */ - Transition.prototype.valid = function () { - return !this.error() || this.success !== undefined; + Transition.prototype.valid = function() { + return !this.error() || this.success !== undefined; }; /** * Aborts this transition @@ -3512,11 +3890,11 @@ var Transition = /** @class */ (function () { * Imperative API to abort a Transition. * This only applies to Transitions that are not yet complete. */ - Transition.prototype.abort = function () { - // Do not set flag if the transition is already complete - if (isUndefined(this.success)) { - this._aborted = true; - } + Transition.prototype.abort = function() { + // Do not set flag if the transition is already complete + if (isUndefined(this.success)) { + this._aborted = true; + } }; /** * The Transition error reason. @@ -3524,332 +3902,376 @@ var Transition = /** @class */ (function () { * If the transition is invalid (and could not be run), returns the reason the transition is invalid. * If the transition was valid and ran, but was not successful, returns the reason the transition failed. * - * @returns an error message explaining why the transition is invalid, or the reason the transition failed. + * @returns a transition rejection explaining why the transition is invalid, or the reason the transition failed. */ - Transition.prototype.error = function () { - var state = this.$to(); - if (state.self.abstract) - return "Cannot transition to abstract state '" + state.name + "'"; - var paramDefs = state.parameters(), values$$1 = this.params(); - var invalidParams = paramDefs.filter(function (param) { return !param.validates(values$$1[param.id]); }); - if (invalidParams.length) { - return "Param values not valid for state '" + state.name + "'. Invalid params: [ " + invalidParams.map(function (param) { return param.id; }).join(', ') + " ]"; - } - if (this.success === false) - return this._error; + Transition.prototype.error = function() { + var state = this.$to(); + if (state.self.abstract) { + return Rejection.invalid("Cannot transition to abstract state '" + state.name + "'"); + } + var paramDefs = state.parameters(); + var values$$1 = this.params(); + var invalidParams = paramDefs.filter(function(param) { + return !param.validates(values$$1[param.id]); + }); + if (invalidParams.length) { + var invalidValues = invalidParams + .map(function(param) { + return '[' + param.id + ':' + stringify(values$$1[param.id]) + ']'; + }) + .join(', '); + var detail = "The following parameter values are not valid for state '" + state.name + "': " + invalidValues; + return Rejection.invalid(detail); + } + if (this.success === false) return this._error; }; /** * A string representation of the Transition * * @returns A string representation of the Transition */ - Transition.prototype.toString = function () { - var fromStateOrName = this.from(); - var toStateOrName = this.to(); - var avoidEmptyHash = function (params) { - return (params['#'] !== null && params['#'] !== undefined) ? params : omit(params, ['#']); - }; - // (X) means the to state is invalid. - var id = this.$id, from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName, fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))), toValid = this.valid() ? '' : '(X) ', to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName, toParams = stringify(avoidEmptyHash(this.params())); - return "Transition#" + id + "( '" + from + "'" + fromParams + " -> " + toValid + "'" + to + "'" + toParams + " )"; + Transition.prototype.toString = function() { + var fromStateOrName = this.from(); + var toStateOrName = this.to(); + var avoidEmptyHash = function(params) { + return params['#'] !== null && params['#'] !== undefined ? params : omit(params, ['#']); + }; + // (X) means the to state is invalid. + var id = this.$id, + from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName, + fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))), + toValid = this.valid() ? '' : '(X) ', + to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName, + toParams = stringify(avoidEmptyHash(this.params())); + return 'Transition#' + id + "( '" + from + "'" + fromParams + ' -> ' + toValid + "'" + to + "'" + toParams + ' )'; }; /** @hidden */ Transition.diToken = Transition; return Transition; -}()); + })(); /** */ -/** - * Functions that manipulate strings - * - * Although these functions are exported, they are subject to change without notice. - * - * @module common_strings - */ /** */ -/** - * Returns a string shortened to a maximum length - * - * If the string is already less than the `max` length, return the string. - * Else return the string, shortened to `max - 3` and append three dots ("..."). - * - * @param max the maximum length of the string to return - * @param str the input string - */ -function maxLength(max, str) { - if (str.length <= max) - return str; + /** + * Functions that manipulate strings + * + * Although these functions are exported, they are subject to change without notice. + * + * @module common_strings + */ /** + * Returns a string shortened to a maximum length + * + * If the string is already less than the `max` length, return the string. + * Else return the string, shortened to `max - 3` and append three dots ("..."). + * + * @param max the maximum length of the string to return + * @param str the input string + */ + function maxLength(max, str) { + if (str.length <= max) return str; return str.substr(0, max - 3) + '...'; -} -/** - * Returns a string, with spaces added to the end, up to a desired str length - * - * If the string is already longer than the desired length, return the string. - * Else returns the string, with extra spaces on the end, such that it reaches `length` characters. - * - * @param length the desired length of the string to return - * @param str the input string - */ -function padString(length, str) { - while (str.length < length) - str += ' '; + } + /** + * Returns a string, with spaces added to the end, up to a desired str length + * + * If the string is already longer than the desired length, return the string. + * Else returns the string, with extra spaces on the end, such that it reaches `length` characters. + * + * @param length the desired length of the string to return + * @param str the input string + */ + function padString(length, str) { + while (str.length < length) str += ' '; return str; -} -function kebobString(camelCase) { + } + function kebobString(camelCase) { return camelCase - .replace(/^([A-Z])/, function ($1) { return $1.toLowerCase(); }) // replace first char - .replace(/([A-Z])/g, function ($1) { return '-' + $1.toLowerCase(); }); // replace rest -} -function functionToString(fn) { + .replace(/^([A-Z])/, function($1) { + return $1.toLowerCase(); + }) // replace first char + .replace(/([A-Z])/g, function($1) { + return '-' + $1.toLowerCase(); + }); // replace rest + } + function functionToString(fn) { var fnStr = fnToString(fn); var namedFunctionMatch = fnStr.match(/^(function [^ ]+\([^)]*\))/); var toStr = namedFunctionMatch ? namedFunctionMatch[1] : fnStr; var fnName = fn['name'] || ''; if (fnName && toStr.match(/function \(/)) { - return 'function ' + fnName + toStr.substr(9); + return 'function ' + fnName + toStr.substr(9); } return toStr; -} -function fnToString(fn) { + } + function fnToString(fn) { var _fn = isArray(fn) ? fn.slice(-1)[0] : fn; - return _fn && _fn.toString() || 'undefined'; -} -var stringifyPatternFn = null; -var stringifyPattern = function (value) { + return (_fn && _fn.toString()) || 'undefined'; + } + var stringifyPatternFn = null; + var stringifyPattern = function(value) { var isRejection = Rejection.isRejectionPromise; - stringifyPatternFn = stringifyPatternFn || pattern([ + stringifyPatternFn = + stringifyPatternFn || + pattern([ [not(isDefined), val('undefined')], [isNull, val('null')], [isPromise, val('[Promise]')], - [isRejection, function (x) { return x._transitionRejection.toString(); }], + [ + isRejection, + function(x) { + return x._transitionRejection.toString(); + }, + ], [is(Rejection), invoke('toString')], [is(Transition), invoke('toString')], [is(Resolvable), invoke('toString')], [isInjectable, functionToString], [val(true), identity], - ]); + ]); return stringifyPatternFn(value); -}; -function stringify(o) { + }; + function stringify(o) { var seen = []; function format(value) { - if (isObject(value)) { - if (seen.indexOf(value) !== -1) - return '[circular ref]'; - seen.push(value); - } - return stringifyPattern(value); + if (isObject(value)) { + if (seen.indexOf(value) !== -1) return '[circular ref]'; + seen.push(value); + } + return stringifyPattern(value); } - return JSON.stringify(o, function (key, value) { return format(value); }).replace(/\\"/g, '"'); -} -/** Returns a function that splits a string on a character or substring */ -var beforeAfterSubstr = function (char) { return function (str) { - if (!str) - return ['', '']; - var idx = str.indexOf(char); - if (idx === -1) - return [str, '']; - return [str.substr(0, idx), str.substr(idx + 1)]; -}; }; -var hostRegex = new RegExp('^(?:[a-z]+:)?//[^/]+/'); -var stripLastPathElement = function (str) { return str.replace(/\/[^/]*$/, ''); }; -var splitHash = beforeAfterSubstr('#'); -var splitQuery = beforeAfterSubstr('?'); -var splitEqual = beforeAfterSubstr('='); -var trimHashVal = function (str) { return str ? str.replace(/^#/, '') : ''; }; -/** - * Splits on a delimiter, but returns the delimiters in the array - * - * #### Example: - * ```js - * var splitOnSlashes = splitOnDelim('/'); - * splitOnSlashes("/foo"); // ["/", "foo"] - * splitOnSlashes("/foo/"); // ["/", "foo", "/"] - * ``` - */ -function splitOnDelim(delim) { - var re = new RegExp('(' + delim + ')', 'g'); - return function (str) { - return str.split(re).filter(identity); + return JSON.stringify(o, function(key, value) { + return format(value); + }).replace(/\\"/g, '"'); + } + /** Returns a function that splits a string on a character or substring */ + var beforeAfterSubstr = function(char) { + return function(str) { + if (!str) return ['', '']; + var idx = str.indexOf(char); + if (idx === -1) return [str, '']; + return [str.substr(0, idx), str.substr(idx + 1)]; }; -} -/** - * Reduce fn that joins neighboring strings - * - * Given an array of strings, returns a new array - * where all neighboring strings have been joined. - * - * #### Example: - * ```js - * let arr = ["foo", "bar", 1, "baz", "", "qux" ]; - * arr.reduce(joinNeighborsR, []) // ["foobar", 1, "bazqux" ] - * ``` - */ -function joinNeighborsR(acc, x) { - if (isString(tail(acc)) && isString(x)) - return acc.slice(0, -1).concat(tail(acc) + x); + }; + var hostRegex = new RegExp('^(?:[a-z]+:)?//[^/]+/'); + var stripLastPathElement = function(str) { + return str.replace(/\/[^/]*$/, ''); + }; + var splitHash = beforeAfterSubstr('#'); + var splitQuery = beforeAfterSubstr('?'); + var splitEqual = beforeAfterSubstr('='); + var trimHashVal = function(str) { + return str ? str.replace(/^#/, '') : ''; + }; + /** + * Splits on a delimiter, but returns the delimiters in the array + * + * #### Example: + * ```js + * var splitOnSlashes = splitOnDelim('/'); + * splitOnSlashes("/foo"); // ["/", "foo"] + * splitOnSlashes("/foo/"); // ["/", "foo", "/"] + * ``` + */ + function splitOnDelim(delim) { + var re = new RegExp('(' + delim + ')', 'g'); + return function(str) { + return str.split(re).filter(identity); + }; + } + /** + * Reduce fn that joins neighboring strings + * + * Given an array of strings, returns a new array + * where all neighboring strings have been joined. + * + * #### Example: + * ```js + * let arr = ["foo", "bar", 1, "baz", "", "qux" ]; + * arr.reduce(joinNeighborsR, []) // ["foobar", 1, "bazqux" ] + * ``` + */ + function joinNeighborsR(acc, x) { + if (isString(tail(acc)) && isString(x)) return acc.slice(0, -1).concat(tail(acc) + x); return pushR(acc, x); -} + } /** for typedoc */ -/** @module common */ /** for typedoc */ - -/** - * @coreapi - * @module params - */ -/** */ -/** - * A registry for parameter types. - * - * This registry manages the built-in (and custom) parameter types. - * - * The built-in parameter types are: - * - * - [[string]] - * - [[path]] - * - [[query]] - * - [[hash]] - * - [[int]] - * - [[bool]] - * - [[date]] - * - [[json]] - * - [[any]] - */ -var ParamTypes = /** @class */ (function () { + /** @module common */ /** + * @coreapi + * @module params + */ + /** + * A registry for parameter types. + * + * This registry manages the built-in (and custom) parameter types. + * + * The built-in parameter types are: + * + * - [[string]] + * - [[path]] + * - [[query]] + * - [[hash]] + * - [[int]] + * - [[bool]] + * - [[date]] + * - [[json]] + * - [[any]] + */ + var ParamTypes = /** @class */ (function() { /** @internalapi */ function ParamTypes() { - /** @hidden */ - this.enqueue = true; - /** @hidden */ - this.typeQueue = []; - /** @internalapi */ - this.defaultTypes = pick(ParamTypes.prototype, ['hash', 'string', 'query', 'path', 'int', 'bool', 'date', 'json', 'any']); - // Register default types. Store them in the prototype of this.types. - var makeType = function (definition, name) { - return new ParamType(extend({ name: name }, definition)); - }; - this.types = inherit(map(this.defaultTypes, makeType), {}); + /** @hidden */ + this.enqueue = true; + /** @hidden */ + this.typeQueue = []; + /** @internalapi */ + this.defaultTypes = pick(ParamTypes.prototype, [ + 'hash', + 'string', + 'query', + 'path', + 'int', + 'bool', + 'date', + 'json', + 'any', + ]); + // Register default types. Store them in the prototype of this.types. + var makeType = function(definition, name) { + return new ParamType(extend({ name: name }, definition)); + }; + this.types = inherit(map(this.defaultTypes, makeType), {}); } /** @internalapi */ - ParamTypes.prototype.dispose = function () { - this.types = {}; + ParamTypes.prototype.dispose = function() { + this.types = {}; }; /** * Registers a parameter type * * End users should call [[UrlMatcherFactory.type]], which delegates to this method. */ - ParamTypes.prototype.type = function (name, definition, definitionFn) { - if (!isDefined(definition)) - return this.types[name]; - if (this.types.hasOwnProperty(name)) - throw new Error("A type named '" + name + "' has already been defined."); - this.types[name] = new ParamType(extend({ name: name }, definition)); - if (definitionFn) { - this.typeQueue.push({ name: name, def: definitionFn }); - if (!this.enqueue) - this._flushTypeQueue(); - } - return this; + ParamTypes.prototype.type = function(name, definition, definitionFn) { + if (!isDefined(definition)) return this.types[name]; + if (this.types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined."); + this.types[name] = new ParamType(extend({ name: name }, definition)); + if (definitionFn) { + this.typeQueue.push({ name: name, def: definitionFn }); + if (!this.enqueue) this._flushTypeQueue(); + } + return this; }; /** @internalapi */ - ParamTypes.prototype._flushTypeQueue = function () { - while (this.typeQueue.length) { - var type = this.typeQueue.shift(); - if (type.pattern) - throw new Error("You cannot override a type's .pattern at runtime."); - extend(this.types[type.name], services.$injector.invoke(type.def)); - } + ParamTypes.prototype._flushTypeQueue = function() { + while (this.typeQueue.length) { + var type = this.typeQueue.shift(); + if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime."); + extend(this.types[type.name], services.$injector.invoke(type.def)); + } }; return ParamTypes; -}()); -/** @hidden */ -function initDefaultTypes() { - var makeDefaultType = function (def) { - var valToString = function (val$$1) { - return val$$1 != null ? val$$1.toString() : val$$1; - }; - var defaultTypeBase = { - encode: valToString, - decode: valToString, - is: is(String), - pattern: /.*/, - // tslint:disable-next-line:triple-equals - equals: function (a, b) { return a == b; }, - }; - return extend({}, defaultTypeBase, def); + })(); + /** @hidden */ + function initDefaultTypes() { + var makeDefaultType = function(def) { + var valToString = function(val$$1) { + return val$$1 != null ? val$$1.toString() : val$$1; + }; + var defaultTypeBase = { + encode: valToString, + decode: valToString, + is: is(String), + pattern: /.*/, + // tslint:disable-next-line:triple-equals + equals: function(a, b) { + return a == b; + }, + }; + return extend({}, defaultTypeBase, def); }; // Default Parameter Type Definitions extend(ParamTypes.prototype, { - string: makeDefaultType({}), - path: makeDefaultType({ - pattern: /[^/]*/, - }), - query: makeDefaultType({}), - hash: makeDefaultType({ - inherit: false, - }), - int: makeDefaultType({ - decode: function (val$$1) { return parseInt(val$$1, 10); }, - is: function (val$$1) { - return !isNullOrUndefined(val$$1) && this.decode(val$$1.toString()) === val$$1; - }, - pattern: /-?\d+/, - }), - bool: makeDefaultType({ - encode: function (val$$1) { return val$$1 && 1 || 0; }, - decode: function (val$$1) { return parseInt(val$$1, 10) !== 0; }, - is: is(Boolean), - pattern: /0|1/, - }), - date: makeDefaultType({ - encode: function (val$$1) { - return !this.is(val$$1) ? undefined : [ - val$$1.getFullYear(), - ('0' + (val$$1.getMonth() + 1)).slice(-2), - ('0' + val$$1.getDate()).slice(-2), - ].join('-'); - }, - decode: function (val$$1) { - if (this.is(val$$1)) - return val$$1; - var match = this.capture.exec(val$$1); - return match ? new Date(match[1], match[2] - 1, match[3]) : undefined; - }, - is: function (val$$1) { return val$$1 instanceof Date && !isNaN(val$$1.valueOf()); }, - equals: function (l, r) { - return ['getFullYear', 'getMonth', 'getDate'] - .reduce(function (acc, fn) { return acc && l[fn]() === r[fn](); }, true); - }, - pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/, - capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/, - }), - json: makeDefaultType({ - encode: toJson, - decode: fromJson, - is: is(Object), - equals: equals, - pattern: /[^/]*/, - }), - // does not encode/decode - any: makeDefaultType({ - encode: identity, - decode: identity, - is: function () { return true; }, - equals: equals, - }), + string: makeDefaultType({}), + path: makeDefaultType({ + pattern: /[^/]*/, + }), + query: makeDefaultType({}), + hash: makeDefaultType({ + inherit: false, + }), + int: makeDefaultType({ + decode: function(val$$1) { + return parseInt(val$$1, 10); + }, + is: function(val$$1) { + return !isNullOrUndefined(val$$1) && this.decode(val$$1.toString()) === val$$1; + }, + pattern: /-?\d+/, + }), + bool: makeDefaultType({ + encode: function(val$$1) { + return (val$$1 && 1) || 0; + }, + decode: function(val$$1) { + return parseInt(val$$1, 10) !== 0; + }, + is: is(Boolean), + pattern: /0|1/, + }), + date: makeDefaultType({ + encode: function(val$$1) { + return !this.is(val$$1) + ? undefined + : [ + val$$1.getFullYear(), + ('0' + (val$$1.getMonth() + 1)).slice(-2), + ('0' + val$$1.getDate()).slice(-2), + ].join('-'); + }, + decode: function(val$$1) { + if (this.is(val$$1)) return val$$1; + var match = this.capture.exec(val$$1); + return match ? new Date(match[1], match[2] - 1, match[3]) : undefined; + }, + is: function(val$$1) { + return val$$1 instanceof Date && !isNaN(val$$1.valueOf()); + }, + equals: function(l, r) { + return ['getFullYear', 'getMonth', 'getDate'].reduce(function(acc, fn) { + return acc && l[fn]() === r[fn](); + }, true); + }, + pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/, + capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/, + }), + json: makeDefaultType({ + encode: toJson, + decode: fromJson, + is: is(Object), + equals: equals, + pattern: /[^/]*/, + }), + // does not encode/decode + any: makeDefaultType({ + encode: identity, + decode: identity, + is: function() { + return true; + }, + equals: equals, + }), }); -} -initDefaultTypes(); + } + initDefaultTypes(); -/** - * @coreapi - * @module params - */ -/** */ -/** @internalapi */ -var StateParams = /** @class */ (function () { + /** + * @coreapi + * @module params + */ + /** @internalapi */ + var StateParams = /** @class */ (function() { function StateParams(params) { - if (params === void 0) { params = {}; } - extend(this, params); + if (params === void 0) { + params = {}; + } + extend(this, params); } /** * Merges a set of parameters with all parameters inherited between the common parents of the @@ -3859,226 +4281,313 @@ var StateParams = /** @class */ (function () { * @param {Object} $current Internal definition of object representing the current state. * @param {Object} $to Internal definition of object representing state to transition to. */ - StateParams.prototype.$inherit = function (newParams, $current, $to) { - var parentParams; - var parents = ancestors($current, $to), inherited = {}, inheritList = []; - for (var i in parents) { - if (!parents[i] || !parents[i].params) - continue; - parentParams = Object.keys(parents[i].params); - if (!parentParams.length) - continue; - for (var j in parentParams) { - if (inheritList.indexOf(parentParams[j]) >= 0) - continue; - inheritList.push(parentParams[j]); - inherited[parentParams[j]] = this[parentParams[j]]; - } + StateParams.prototype.$inherit = function(newParams, $current, $to) { + var parentParams; + var parents = ancestors($current, $to), + inherited = {}, + inheritList = []; + for (var i in parents) { + if (!parents[i] || !parents[i].params) continue; + parentParams = Object.keys(parents[i].params); + if (!parentParams.length) continue; + for (var j in parentParams) { + if (inheritList.indexOf(parentParams[j]) >= 0) continue; + inheritList.push(parentParams[j]); + inherited[parentParams[j]] = this[parentParams[j]]; } - return extend({}, inherited, newParams); + } + return extend({}, inherited, newParams); }; return StateParams; -}()); + })(); /** for typedoc */ /** for typedoc */ /** for typedoc */ -/** @module path */ /** for typedoc */ - -/** @module resolve */ /** for typedoc */ - -/** @module state */ /** for typedoc */ -var parseUrl = function (url) { - if (!isString(url)) - return false; + /** @module path */ /** @module resolve */ /** @module state */ var parseUrl = function(url) { + if (!isString(url)) return false; var root$$1 = url.charAt(0) === '^'; return { val: root$$1 ? url.substring(1) : url, root: root$$1 }; -}; -function nameBuilder(state) { + }; + function nameBuilder(state) { return state.name; -} -function selfBuilder(state) { - state.self.$$state = function () { return state; }; + } + function selfBuilder(state) { + state.self.$$state = function() { + return state; + }; return state.self; -} -function dataBuilder(state) { + } + function dataBuilder(state) { if (state.parent && state.parent.data) { - state.data = state.self.data = inherit(state.parent.data, state.data); + state.data = state.self.data = inherit(state.parent.data, state.data); } return state.data; -} -var getUrlBuilder = function ($urlMatcherFactoryProvider, root$$1) { + } + var getUrlBuilder = function($urlMatcherFactoryProvider, root$$1) { return function urlBuilder(state) { - var stateDec = state; - // For future states, i.e., states whose name ends with `.**`, - // match anything that starts with the url prefix - if (stateDec && stateDec.url && stateDec.name && stateDec.name.match(/\.\*\*$/)) { - stateDec.url += '{remainder:any}'; // match any path (.*) - } - var parsed = parseUrl(stateDec.url), parent = state.parent; - var url = !parsed ? stateDec.url : $urlMatcherFactoryProvider.compile(parsed.val, { + var stateDec = state; + // For future states, i.e., states whose name ends with `.**`, + // match anything that starts with the url prefix + if (stateDec && stateDec.url && stateDec.name && stateDec.name.match(/\.\*\*$/)) { + stateDec.url += '{remainder:any}'; // match any path (.*) + } + var parsed = parseUrl(stateDec.url), + parent = state.parent; + var url = !parsed + ? stateDec.url + : $urlMatcherFactoryProvider.compile(parsed.val, { params: state.params || {}, - paramMap: function (paramConfig, isSearch) { - if (stateDec.reloadOnSearch === false && isSearch) - paramConfig = extend(paramConfig || {}, { dynamic: true }); - return paramConfig; + paramMap: function(paramConfig, isSearch) { + if (stateDec.reloadOnSearch === false && isSearch) + paramConfig = extend(paramConfig || {}, { dynamic: true }); + return paramConfig; }, - }); - if (!url) - return null; - if (!$urlMatcherFactoryProvider.isMatcher(url)) - throw new Error("Invalid url '" + url + "' in state '" + state + "'"); - return (parsed && parsed.root) ? url : ((parent && parent.navigable) || root$$1()).url.append(url); + }); + if (!url) return null; + if (!$urlMatcherFactoryProvider.isMatcher(url)) + throw new Error("Invalid url '" + url + "' in state '" + state + "'"); + return parsed && parsed.root ? url : ((parent && parent.navigable) || root$$1()).url.append(url); }; -}; -var getNavigableBuilder = function (isRoot) { + }; + var getNavigableBuilder = function(isRoot) { return function navigableBuilder(state) { - return !isRoot(state) && state.url ? state : (state.parent ? state.parent.navigable : null); + return !isRoot(state) && state.url ? state : state.parent ? state.parent.navigable : null; }; -}; -var getParamsBuilder = function (paramFactory) { + }; + var getParamsBuilder = function(paramFactory) { return function paramsBuilder(state) { - var makeConfigParam = function (config, id) { return paramFactory.fromConfig(id, null, config); }; - var urlParams = (state.url && state.url.parameters({ inherit: false })) || []; - var nonUrlParams = values(mapObj(omit(state.params || {}, urlParams.map(prop('id'))), makeConfigParam)); - return urlParams.concat(nonUrlParams).map(function (p) { return [p.id, p]; }).reduce(applyPairs, {}); + var makeConfigParam = function(config, id) { + return paramFactory.fromConfig(id, null, config); + }; + var urlParams = (state.url && state.url.parameters({ inherit: false })) || []; + var nonUrlParams = values(mapObj(omit(state.params || {}, urlParams.map(prop('id'))), makeConfigParam)); + return urlParams + .concat(nonUrlParams) + .map(function(p) { + return [p.id, p]; + }) + .reduce(applyPairs, {}); }; -}; -function pathBuilder(state) { + }; + function pathBuilder(state) { return state.parent ? state.parent.path.concat(state) : /*root*/ [state]; -} -function includesBuilder(state) { + } + function includesBuilder(state) { var includes = state.parent ? extend({}, state.parent.includes) : {}; includes[state.name] = true; return includes; -} -/** - * This is a [[StateBuilder.builder]] function for the `resolve:` block on a [[StateDeclaration]]. - * - * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder - * validates the `resolve` property and converts it to a [[Resolvable]] array. - * - * resolve: input value can be: - * - * { - * // analyzed but not injected - * myFooResolve: function() { return "myFooData"; }, - * - * // function.toString() parsed, "DependencyName" dep as string (not min-safe) - * myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() }, - * - * // Array split; "DependencyName" dep as string - * myBazResolve: [ "DependencyName", function(dep) { return dep.fetchSomethingAsPromise() }, - * - * // Array split; DependencyType dep as token (compared using ===) - * myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() }, - * - * // val.$inject used as deps - * // where: - * // corgeResolve.$inject = ["DependencyName"]; - * // function corgeResolve(dep) { dep.fetchSometingAsPromise() } - * // then "DependencyName" dep as string - * myCorgeResolve: corgeResolve, - * - * // inject service by name - * // When a string is found, desugar creating a resolve that injects the named service - * myGraultResolve: "SomeService" - * } - * - * or: - * - * [ - * new Resolvable("myFooResolve", function() { return "myFooData" }), - * new Resolvable("myBarResolve", function(dep) { return dep.fetchSomethingAsPromise() }, [ "DependencyName" ]), - * { provide: "myBazResolve", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ "DependencyName" ] } - * ] - */ -function resolvablesBuilder(state) { + } + /** + * This is a [[StateBuilder.builder]] function for the `resolve:` block on a [[StateDeclaration]]. + * + * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder + * validates the `resolve` property and converts it to a [[Resolvable]] array. + * + * resolve: input value can be: + * + * { + * // analyzed but not injected + * myFooResolve: function() { return "myFooData"; }, + * + * // function.toString() parsed, "DependencyName" dep as string (not min-safe) + * myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() }, + * + * // Array split; "DependencyName" dep as string + * myBazResolve: [ "DependencyName", function(dep) { return dep.fetchSomethingAsPromise() }, + * + * // Array split; DependencyType dep as token (compared using ===) + * myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() }, + * + * // val.$inject used as deps + * // where: + * // corgeResolve.$inject = ["DependencyName"]; + * // function corgeResolve(dep) { dep.fetchSometingAsPromise() } + * // then "DependencyName" dep as string + * myCorgeResolve: corgeResolve, + * + * // inject service by name + * // When a string is found, desugar creating a resolve that injects the named service + * myGraultResolve: "SomeService" + * } + * + * or: + * + * [ + * new Resolvable("myFooResolve", function() { return "myFooData" }), + * new Resolvable("myBarResolve", function(dep) { return dep.fetchSomethingAsPromise() }, [ "DependencyName" ]), + * { provide: "myBazResolve", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ "DependencyName" ] } + * ] + */ + function resolvablesBuilder(state) { /** convert resolve: {} and resolvePolicy: {} objects to an array of tuples */ - var objects2Tuples = function (resolveObj, resolvePolicies) { - return Object.keys(resolveObj || {}).map(function (token) { return ({ token: token, val: resolveObj[token], deps: undefined, policy: resolvePolicies[token] }); }); + var objects2Tuples = function(resolveObj, resolvePolicies) { + return Object.keys(resolveObj || {}).map(function(token) { + return { + token: token, + val: resolveObj[token], + deps: undefined, + policy: resolvePolicies[token], + }; + }); }; /** fetch DI annotations from a function or ng1-style array */ - var annotate = function (fn) { - var $injector = services.$injector; - // ng1 doesn't have an $injector until runtime. - // If the $injector doesn't exist, use "deferred" literal as a - // marker indicating they should be annotated when runtime starts - return fn['$inject'] || ($injector && $injector.annotate(fn, $injector.strictDi)) || 'deferred'; + var annotate = function(fn) { + var $injector = services.$injector; + // ng1 doesn't have an $injector until runtime. + // If the $injector doesn't exist, use "deferred" literal as a + // marker indicating they should be annotated when runtime starts + return fn['$inject'] || ($injector && $injector.annotate(fn, $injector.strictDi)) || 'deferred'; }; /** true if the object has both `token` and `resolveFn`, and is probably a [[ResolveLiteral]] */ - var isResolveLiteral = function (obj) { return !!(obj.token && obj.resolveFn); }; + var isResolveLiteral = function(obj) { + return !!(obj.token && obj.resolveFn); + }; /** true if the object looks like a provide literal, or a ng2 Provider */ - var isLikeNg2Provider = function (obj) { return !!((obj.provide || obj.token) && (obj.useValue || obj.useFactory || obj.useExisting || obj.useClass)); }; + var isLikeNg2Provider = function(obj) { + return !!((obj.provide || obj.token) && (obj.useValue || obj.useFactory || obj.useExisting || obj.useClass)); + }; /** true if the object looks like a tuple from obj2Tuples */ - var isTupleFromObj = function (obj) { return !!(obj && obj.val && (isString(obj.val) || isArray(obj.val) || isFunction(obj.val))); }; + var isTupleFromObj = function(obj) { + return !!(obj && obj.val && (isString(obj.val) || isArray(obj.val) || isFunction(obj.val))); + }; /** extracts the token from a Provider or provide literal */ - var getToken = function (p) { return p.provide || p.token; }; + var getToken = function(p) { + return p.provide || p.token; + }; /** Given a literal resolve or provider object, returns a Resolvable */ var literal2Resolvable = pattern([ - [prop('resolveFn'), function (p) { return new Resolvable(getToken(p), p.resolveFn, p.deps, p.policy); }], - [prop('useFactory'), function (p) { return new Resolvable(getToken(p), p.useFactory, (p.deps || p.dependencies), p.policy); }], - [prop('useClass'), function (p) { return new Resolvable(getToken(p), function () { return new p.useClass(); }, [], p.policy); }], - [prop('useValue'), function (p) { return new Resolvable(getToken(p), function () { return p.useValue; }, [], p.policy, p.useValue); }], - [prop('useExisting'), function (p) { return new Resolvable(getToken(p), identity, [p.useExisting], p.policy); }], + [ + prop('resolveFn'), + function(p) { + return new Resolvable(getToken(p), p.resolveFn, p.deps, p.policy); + }, + ], + [ + prop('useFactory'), + function(p) { + return new Resolvable(getToken(p), p.useFactory, p.deps || p.dependencies, p.policy); + }, + ], + [ + prop('useClass'), + function(p) { + return new Resolvable( + getToken(p), + function() { + return new p.useClass(); + }, + [], + p.policy, + ); + }, + ], + [ + prop('useValue'), + function(p) { + return new Resolvable( + getToken(p), + function() { + return p.useValue; + }, + [], + p.policy, + p.useValue, + ); + }, + ], + [ + prop('useExisting'), + function(p) { + return new Resolvable(getToken(p), identity, [p.useExisting], p.policy); + }, + ], ]); var tuple2Resolvable = pattern([ - [pipe(prop('val'), isString), function (tuple) { return new Resolvable(tuple.token, identity, [tuple.val], tuple.policy); }], - [pipe(prop('val'), isArray), function (tuple) { return new Resolvable(tuple.token, tail(tuple.val), tuple.val.slice(0, -1), tuple.policy); }], - [pipe(prop('val'), isFunction), function (tuple) { return new Resolvable(tuple.token, tuple.val, annotate(tuple.val), tuple.policy); }], + [ + pipe(prop('val'), isString), + function(tuple) { + return new Resolvable(tuple.token, identity, [tuple.val], tuple.policy); + }, + ], + [ + pipe(prop('val'), isArray), + function(tuple) { + return new Resolvable(tuple.token, tail(tuple.val), tuple.val.slice(0, -1), tuple.policy); + }, + ], + [ + pipe(prop('val'), isFunction), + function(tuple) { + return new Resolvable(tuple.token, tuple.val, annotate(tuple.val), tuple.policy); + }, + ], ]); var item2Resolvable = pattern([ - [is(Resolvable), function (r) { return r; }], - [isResolveLiteral, literal2Resolvable], - [isLikeNg2Provider, literal2Resolvable], - [isTupleFromObj, tuple2Resolvable], - [val(true), function (obj) { throw new Error('Invalid resolve value: ' + stringify(obj)); }], + [ + is(Resolvable), + function(r) { + return r; + }, + ], + [isResolveLiteral, literal2Resolvable], + [isLikeNg2Provider, literal2Resolvable], + [isTupleFromObj, tuple2Resolvable], + [ + val(true), + function(obj) { + throw new Error('Invalid resolve value: ' + stringify(obj)); + }, + ], ]); // If resolveBlock is already an array, use it as-is. // Otherwise, assume it's an object and convert to an Array of tuples var decl = state.resolve; var items = isArray(decl) ? decl : objects2Tuples(decl, state.resolvePolicy || {}); return items.map(item2Resolvable); -} -/** - * @internalapi A internal global service - * - * StateBuilder is a factory for the internal [[StateObject]] objects. - * - * When you register a state with the [[StateRegistry]], you register a plain old javascript object which - * conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding - * [[StateObject]] object, which has an API and is used internally. - * - * Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function - * using the [[builder]] method. - */ -var StateBuilder = /** @class */ (function () { + } + /** + * @internalapi A internal global service + * + * StateBuilder is a factory for the internal [[StateObject]] objects. + * + * When you register a state with the [[StateRegistry]], you register a plain old javascript object which + * conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding + * [[StateObject]] object, which has an API and is used internally. + * + * Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function + * using the [[builder]] method. + */ + var StateBuilder = /** @class */ (function() { function StateBuilder(matcher, urlMatcherFactory) { - this.matcher = matcher; - var self = this; - var root$$1 = function () { return matcher.find(''); }; - var isRoot = function (state) { return state.name === ''; }; - function parentBuilder(state) { - if (isRoot(state)) - return null; - return matcher.find(self.parentName(state)) || root$$1(); - } - this.builders = { - name: [nameBuilder], - self: [selfBuilder], - parent: [parentBuilder], - data: [dataBuilder], - // Build a URLMatcher if necessary, either via a relative or absolute URL - url: [getUrlBuilder(urlMatcherFactory, root$$1)], - // Keep track of the closest ancestor state that has a URL (i.e. is navigable) - navigable: [getNavigableBuilder(isRoot)], - params: [getParamsBuilder(urlMatcherFactory.paramFactory)], - // Each framework-specific ui-router implementation should define its own `views` builder - // e.g., src/ng1/statebuilders/views.ts - views: [], - // Keep a full path from the root down to this state as this is needed for state activation. - path: [pathBuilder], - // Speed up $state.includes() as it's used a lot - includes: [includesBuilder], - resolvables: [resolvablesBuilder], - }; + this.matcher = matcher; + var self = this; + var root$$1 = function() { + return matcher.find(''); + }; + var isRoot = function(state) { + return state.name === ''; + }; + function parentBuilder(state) { + if (isRoot(state)) return null; + return matcher.find(self.parentName(state)) || root$$1(); + } + this.builders = { + name: [nameBuilder], + self: [selfBuilder], + parent: [parentBuilder], + data: [dataBuilder], + // Build a URLMatcher if necessary, either via a relative or absolute URL + url: [getUrlBuilder(urlMatcherFactory, root$$1)], + // Keep track of the closest ancestor state that has a URL (i.e. is navigable) + navigable: [getNavigableBuilder(isRoot)], + params: [getParamsBuilder(urlMatcherFactory.paramFactory)], + // Each framework-specific ui-router implementation should define its own `views` builder + // e.g., src/ng1/statebuilders/views.ts + views: [], + // Keep a full path from the root down to this state as this is needed for state activation. + path: [pathBuilder], + // Speed up $state.includes() as it's used a lot + includes: [includesBuilder], + resolvables: [resolvablesBuilder], + }; } /** * Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g., `parent`, `url`, or `path`). @@ -4090,17 +4599,17 @@ var StateBuilder = /** @class */ (function () { * @param fn The BuilderFunction which will be used to build the State property * @returns a function which deregisters the BuilderFunction */ - StateBuilder.prototype.builder = function (name, fn) { - var builders = this.builders; - var array = builders[name] || []; - // Backwards compat: if only one builder exists, return it, else return whole arary. - if (isString(name) && !isDefined(fn)) - return array.length > 1 ? array : array[0]; - if (!isString(name) || !isFunction(fn)) - return; - builders[name] = array; - builders[name].push(fn); - return function () { return builders[name].splice(builders[name].indexOf(fn, 1)) && null; }; + StateBuilder.prototype.builder = function(name, fn) { + var builders = this.builders; + var array = builders[name] || []; + // Backwards compat: if only one builder exists, return it, else return whole arary. + if (isString(name) && !isDefined(fn)) return array.length > 1 ? array : array[0]; + if (!isString(name) || !isFunction(fn)) return; + builders[name] = array; + builders[name].push(fn); + return function() { + return builders[name].splice(builders[name].indexOf(fn, 1)) && null; + }; }; /** * Builds all of the properties on an essentially blank State object, returning a State object which has all its @@ -4109,232 +4618,247 @@ var StateBuilder = /** @class */ (function () { * @param state an uninitialized State object * @returns the built State object */ - StateBuilder.prototype.build = function (state) { - var _a = this, matcher = _a.matcher, builders = _a.builders; - var parent = this.parentName(state); - if (parent && !matcher.find(parent, undefined, false)) { - return null; - } - for (var key in builders) { - if (!builders.hasOwnProperty(key)) - continue; - var chain = builders[key].reduce(function (parentFn, step) { return function (_state) { return step(_state, parentFn); }; }, noop); - state[key] = chain(state); - } - return state; + StateBuilder.prototype.build = function(state) { + var _a = this, + matcher = _a.matcher, + builders = _a.builders; + var parent = this.parentName(state); + if (parent && !matcher.find(parent, undefined, false)) { + return null; + } + for (var key in builders) { + if (!builders.hasOwnProperty(key)) continue; + var chain = builders[key].reduce(function(parentFn, step) { + return function(_state) { + return step(_state, parentFn); + }; + }, noop); + state[key] = chain(state); + } + return state; }; - StateBuilder.prototype.parentName = function (state) { - // name = 'foo.bar.baz.**' - var name = state.name || ''; - // segments = ['foo', 'bar', 'baz', '.**'] - var segments = name.split('.'); - // segments = ['foo', 'bar', 'baz'] - var lastSegment = segments.pop(); - // segments = ['foo', 'bar'] (ignore .** segment for future states) - if (lastSegment === '**') - segments.pop(); - if (segments.length) { - if (state.parent) { - throw new Error("States that specify the 'parent:' property should not have a '.' in their name (" + name + ")"); - } - // 'foo.bar' - return segments.join('.'); + StateBuilder.prototype.parentName = function(state) { + // name = 'foo.bar.baz.**' + var name = state.name || ''; + // segments = ['foo', 'bar', 'baz', '.**'] + var segments = name.split('.'); + // segments = ['foo', 'bar', 'baz'] + var lastSegment = segments.pop(); + // segments = ['foo', 'bar'] (ignore .** segment for future states) + if (lastSegment === '**') segments.pop(); + if (segments.length) { + if (state.parent) { + throw new Error( + "States that specify the 'parent:' property should not have a '.' in their name (" + name + ')', + ); } - if (!state.parent) - return ''; - return isString(state.parent) ? state.parent : state.parent.name; + // 'foo.bar' + return segments.join('.'); + } + if (!state.parent) return ''; + return isString(state.parent) ? state.parent : state.parent.name; }; - StateBuilder.prototype.name = function (state) { - var name = state.name; - if (name.indexOf('.') !== -1 || !state.parent) - return name; - var parentName = isString(state.parent) ? state.parent : state.parent.name; - return parentName ? parentName + '.' + name : name; + StateBuilder.prototype.name = function(state) { + var name = state.name; + if (name.indexOf('.') !== -1 || !state.parent) return name; + var parentName = isString(state.parent) ? state.parent : state.parent.name; + return parentName ? parentName + '.' + name : name; }; return StateBuilder; -}()); + })(); /** for typedoc */ -/** @module state */ /** for typedoc */ -var StateMatcher = /** @class */ (function () { + /** @module state */ var StateMatcher = /** @class */ (function() { function StateMatcher(_states) { - this._states = _states; + this._states = _states; } - StateMatcher.prototype.isRelative = function (stateName) { - stateName = stateName || ''; - return stateName.indexOf('.') === 0 || stateName.indexOf('^') === 0; + StateMatcher.prototype.isRelative = function(stateName) { + stateName = stateName || ''; + return stateName.indexOf('.') === 0 || stateName.indexOf('^') === 0; }; - StateMatcher.prototype.find = function (stateOrName, base, matchGlob) { - if (matchGlob === void 0) { matchGlob = true; } - if (!stateOrName && stateOrName !== '') - return undefined; - var isStr = isString(stateOrName); - var name = isStr ? stateOrName : stateOrName.name; - if (this.isRelative(name)) - name = this.resolvePath(name, base); - var state = this._states[name]; - if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { - return state; + StateMatcher.prototype.find = function(stateOrName, base, matchGlob) { + if (matchGlob === void 0) { + matchGlob = true; + } + if (!stateOrName && stateOrName !== '') return undefined; + var isStr = isString(stateOrName); + var name = isStr ? stateOrName : stateOrName.name; + if (this.isRelative(name)) name = this.resolvePath(name, base); + var state = this._states[name]; + if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { + return state; + } else if (isStr && matchGlob) { + var _states = values(this._states); + var matches = _states.filter(function(_state) { + return _state.__stateObjectCache.nameGlob && _state.__stateObjectCache.nameGlob.matches(name); + }); + if (matches.length > 1) { + // tslint:disable-next-line:no-console + console.log( + 'stateMatcher.find: Found multiple matches for ' + name + ' using glob: ', + matches.map(function(match) { + return match.name; + }), + ); } - else if (isStr && matchGlob) { - var _states = values(this._states); - var matches = _states.filter(function (_state) { - return _state.__stateObjectCache.nameGlob && - _state.__stateObjectCache.nameGlob.matches(name); - }); - if (matches.length > 1) { - // tslint:disable-next-line:no-console - console.log("stateMatcher.find: Found multiple matches for " + name + " using glob: ", matches.map(function (match) { return match.name; })); - } - return matches[0]; - } - return undefined; + return matches[0]; + } + return undefined; }; - StateMatcher.prototype.resolvePath = function (name, base) { - if (!base) - throw new Error("No reference point given for path '" + name + "'"); - var baseState = this.find(base); - var splitName = name.split('.'); - var pathLength = splitName.length; - var i = 0, current = baseState; - for (; i < pathLength; i++) { - if (splitName[i] === '' && i === 0) { - current = baseState; - continue; - } - if (splitName[i] === '^') { - if (!current.parent) - throw new Error("Path '" + name + "' not valid for state '" + baseState.name + "'"); - current = current.parent; - continue; - } - break; + StateMatcher.prototype.resolvePath = function(name, base) { + if (!base) throw new Error("No reference point given for path '" + name + "'"); + var baseState = this.find(base); + var splitName = name.split('.'); + var pathLength = splitName.length; + var i = 0, + current = baseState; + for (; i < pathLength; i++) { + if (splitName[i] === '' && i === 0) { + current = baseState; + continue; } - var relName = splitName.slice(i).join('.'); - return current.name + (current.name && relName ? '.' : '') + relName; + if (splitName[i] === '^') { + if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + baseState.name + "'"); + current = current.parent; + continue; + } + break; + } + var relName = splitName.slice(i).join('.'); + return current.name + (current.name && relName ? '.' : '') + relName; }; return StateMatcher; -}()); + })(); /** for typedoc */ -/** @module state */ /** for typedoc */ -/** @internalapi */ -var StateQueueManager = /** @class */ (function () { + /** @module state */ /** @internalapi */ + var StateQueueManager = /** @class */ (function() { function StateQueueManager($registry, $urlRouter, states, builder, listeners) { - this.$registry = $registry; - this.$urlRouter = $urlRouter; - this.states = states; - this.builder = builder; - this.listeners = listeners; - this.queue = []; - this.matcher = $registry.matcher; + this.$registry = $registry; + this.$urlRouter = $urlRouter; + this.states = states; + this.builder = builder; + this.listeners = listeners; + this.queue = []; + this.matcher = $registry.matcher; } /** @internalapi */ - StateQueueManager.prototype.dispose = function () { - this.queue = []; + StateQueueManager.prototype.dispose = function() { + this.queue = []; }; - StateQueueManager.prototype.register = function (stateDecl) { - var queue = this.queue; - var state = StateObject.create(stateDecl); - var name = state.name; - if (!isString(name)) - throw new Error('State must have a valid name'); - if (this.states.hasOwnProperty(name) || inArray(queue.map(prop('name')), name)) - throw new Error("State '" + name + "' is already defined"); - queue.push(state); - this.flush(); - return state; + StateQueueManager.prototype.register = function(stateDecl) { + var queue = this.queue; + var state = StateObject.create(stateDecl); + var name = state.name; + if (!isString(name)) throw new Error('State must have a valid name'); + if (this.states.hasOwnProperty(name) || inArray(queue.map(prop('name')), name)) + throw new Error("State '" + name + "' is already defined"); + queue.push(state); + this.flush(); + return state; }; - StateQueueManager.prototype.flush = function () { - var _this = this; - var _a = this, queue = _a.queue, states = _a.states, builder = _a.builder; - var registered = [], // states that got registered + StateQueueManager.prototype.flush = function() { + var _this = this; + var _a = this, + queue = _a.queue, + states = _a.states, + builder = _a.builder; + var registered = [], // states that got registered orphans = [], // states that don't yet have a parent registered previousQueueLength = {}; // keep track of how long the queue when an orphan was first encountered - var getState = function (name) { - return _this.states.hasOwnProperty(name) && _this.states[name]; - }; - while (queue.length > 0) { - var state = queue.shift(); - var name_1 = state.name; - var result = builder.build(state); - var orphanIdx = orphans.indexOf(state); - if (result) { - var existingState = getState(name_1); - if (existingState && existingState.name === name_1) { - throw new Error("State '" + name_1 + "' is already defined"); - } - var existingFutureState = getState(name_1 + '.**'); - if (existingFutureState) { - // Remove future state of the same name - this.$registry.deregister(existingFutureState); - } - states[name_1] = state; - this.attachRoute(state); - if (orphanIdx >= 0) - orphans.splice(orphanIdx, 1); - registered.push(state); - continue; - } - var prev = previousQueueLength[name_1]; - previousQueueLength[name_1] = queue.length; - if (orphanIdx >= 0 && prev === queue.length) { - // Wait until two consecutive iterations where no additional states were dequeued successfully. - // throw new Error(`Cannot register orphaned state '${name}'`); - queue.push(state); - return states; - } - else if (orphanIdx < 0) { - orphans.push(state); - } - queue.push(state); - } + var getState = function(name) { + return _this.states.hasOwnProperty(name) && _this.states[name]; + }; + var notifyListeners = function() { if (registered.length) { - this.listeners.forEach(function (listener) { return listener('registered', registered.map(function (s) { return s.self; })); }); + _this.listeners.forEach(function(listener) { + return listener( + 'registered', + registered.map(function(s) { + return s.self; + }), + ); + }); } - return states; + }; + while (queue.length > 0) { + var state = queue.shift(); + var name_1 = state.name; + var result = builder.build(state); + var orphanIdx = orphans.indexOf(state); + if (result) { + var existingState = getState(name_1); + if (existingState && existingState.name === name_1) { + throw new Error("State '" + name_1 + "' is already defined"); + } + var existingFutureState = getState(name_1 + '.**'); + if (existingFutureState) { + // Remove future state of the same name + this.$registry.deregister(existingFutureState); + } + states[name_1] = state; + this.attachRoute(state); + if (orphanIdx >= 0) orphans.splice(orphanIdx, 1); + registered.push(state); + continue; + } + var prev = previousQueueLength[name_1]; + previousQueueLength[name_1] = queue.length; + if (orphanIdx >= 0 && prev === queue.length) { + // Wait until two consecutive iterations where no additional states were dequeued successfully. + // throw new Error(`Cannot register orphaned state '${name}'`); + queue.push(state); + notifyListeners(); + return states; + } else if (orphanIdx < 0) { + orphans.push(state); + } + queue.push(state); + } + notifyListeners(); + return states; }; - StateQueueManager.prototype.attachRoute = function (state) { - if (state.abstract || !state.url) - return; - this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(state)); + StateQueueManager.prototype.attachRoute = function(state) { + if (state.abstract || !state.url) return; + this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(state)); }; return StateQueueManager; -}()); + })(); /** for typedoc */ -/** - * @coreapi - * @module state - */ /** for typedoc */ -var StateRegistry = /** @class */ (function () { + /** + * @coreapi + * @module state + */ var StateRegistry = /** @class */ (function() { /** @internalapi */ function StateRegistry(_router) { - this._router = _router; - this.states = {}; - this.listeners = []; - this.matcher = new StateMatcher(this.states); - this.builder = new StateBuilder(this.matcher, _router.urlMatcherFactory); - this.stateQueue = new StateQueueManager(this, _router.urlRouter, this.states, this.builder, this.listeners); - this._registerRoot(); + this._router = _router; + this.states = {}; + this.listeners = []; + this.matcher = new StateMatcher(this.states); + this.builder = new StateBuilder(this.matcher, _router.urlMatcherFactory); + this.stateQueue = new StateQueueManager(this, _router.urlRouter, this.states, this.builder, this.listeners); + this._registerRoot(); } /** @internalapi */ - StateRegistry.prototype._registerRoot = function () { - var rootStateDef = { - name: '', - url: '^', - views: null, - params: { - '#': { value: null, type: 'hash', dynamic: true }, - }, - abstract: true, - }; - var _root = this._root = this.stateQueue.register(rootStateDef); - _root.navigable = null; + StateRegistry.prototype._registerRoot = function() { + var rootStateDef = { + name: '', + url: '^', + views: null, + params: { + '#': { value: null, type: 'hash', dynamic: true }, + }, + abstract: true, + }; + var _root = (this._root = this.stateQueue.register(rootStateDef)); + _root.navigable = null; }; /** @internalapi */ - StateRegistry.prototype.dispose = function () { - var _this = this; - this.stateQueue.dispose(); - this.listeners = []; - this.get().forEach(function (state) { return _this.get(state) && _this.deregister(state); }); + StateRegistry.prototype.dispose = function() { + var _this = this; + this.stateQueue.dispose(); + this.listeners = []; + this.get().forEach(function(state) { + return _this.get(state) && _this.deregister(state); + }); }; /** * Listen for a State Registry events @@ -4366,11 +4890,11 @@ var StateRegistry = /** @class */ (function () { * See [[StateRegistryListener]] * @return a function that deregisters the listener */ - StateRegistry.prototype.onStatesChanged = function (listener) { - this.listeners.push(listener); - return function deregisterListener() { - removeFrom(this.listeners)(listener); - }.bind(this); + StateRegistry.prototype.onStatesChanged = function(listener) { + this.listeners.push(listener); + return function deregisterListener() { + removeFrom(this.listeners)(listener); + }.bind(this); }; /** * Gets the implicit root state @@ -4381,8 +4905,8 @@ var StateRegistry = /** @class */ (function () { * * @return the root [[StateObject]] */ - StateRegistry.prototype.root = function () { - return this._root; + StateRegistry.prototype.root = function() { + return this._root; }; /** * Adds a state to the registry @@ -4396,27 +4920,34 @@ var StateRegistry = /** @class */ (function () { * If the state was successfully registered, then the object is fully built (See: [[StateBuilder]]). * If the state was only queued, then the object is not fully built. */ - StateRegistry.prototype.register = function (stateDefinition) { - return this.stateQueue.register(stateDefinition); + StateRegistry.prototype.register = function(stateDefinition) { + return this.stateQueue.register(stateDefinition); }; /** @hidden */ - StateRegistry.prototype._deregisterTree = function (state) { - var _this = this; - var all$$1 = this.get().map(function (s) { return s.$$state(); }); - var getChildren = function (states) { - var _children = all$$1.filter(function (s) { return states.indexOf(s.parent) !== -1; }); - return _children.length === 0 ? _children : _children.concat(getChildren(_children)); - }; - var children = getChildren([state]); - var deregistered = [state].concat(children).reverse(); - deregistered.forEach(function (_state) { - var $ur = _this._router.urlRouter; - // Remove URL rule - $ur.rules().filter(propEq('state', _state)).forEach($ur.removeRule.bind($ur)); - // Remove state from registry - delete _this.states[_state.name]; + StateRegistry.prototype._deregisterTree = function(state) { + var _this = this; + var all$$1 = this.get().map(function(s) { + return s.$$state(); + }); + var getChildren = function(states) { + var _children = all$$1.filter(function(s) { + return states.indexOf(s.parent) !== -1; }); - return deregistered; + return _children.length === 0 ? _children : _children.concat(getChildren(_children)); + }; + var children = getChildren([state]); + var deregistered = [state].concat(children).reverse(); + deregistered.forEach(function(_state) { + var $ur = _this._router.urlRouter; + // Remove URL rule + $ur + .rules() + .filter(propEq('state', _state)) + .forEach($ur.removeRule.bind($ur)); + // Remove state from registry + delete _this.states[_state.name]; + }); + return deregistered; }; /** * Removes a state from the registry @@ -4427,109 +4958,116 @@ var StateRegistry = /** @class */ (function () { * @param stateOrName the state's name or object representation * @returns {StateObject[]} a list of removed states */ - StateRegistry.prototype.deregister = function (stateOrName) { - var _state = this.get(stateOrName); - if (!_state) - throw new Error("Can't deregister state; not found: " + stateOrName); - var deregisteredStates = this._deregisterTree(_state.$$state()); - this.listeners.forEach(function (listener) { return listener('deregistered', deregisteredStates.map(function (s) { return s.self; })); }); - return deregisteredStates; + StateRegistry.prototype.deregister = function(stateOrName) { + var _state = this.get(stateOrName); + if (!_state) throw new Error("Can't deregister state; not found: " + stateOrName); + var deregisteredStates = this._deregisterTree(_state.$$state()); + this.listeners.forEach(function(listener) { + return listener( + 'deregistered', + deregisteredStates.map(function(s) { + return s.self; + }), + ); + }); + return deregisteredStates; }; - StateRegistry.prototype.get = function (stateOrName, base) { - var _this = this; - if (arguments.length === 0) - return Object.keys(this.states).map(function (name) { return _this.states[name].self; }); - var found = this.matcher.find(stateOrName, base); - return found && found.self || null; + StateRegistry.prototype.get = function(stateOrName, base) { + var _this = this; + if (arguments.length === 0) + return Object.keys(this.states).map(function(name) { + return _this.states[name].self; + }); + var found = this.matcher.find(stateOrName, base); + return (found && found.self) || null; }; - StateRegistry.prototype.decorator = function (name, func) { - return this.builder.builder(name, func); + StateRegistry.prototype.decorator = function(name, func) { + return this.builder.builder(name, func); }; return StateRegistry; -}()); + })(); -/** - * @coreapi - * @module url - */ -/** for typedoc */ -/** @hidden */ -function quoteRegExp(str, param) { - var surroundPattern = ['', ''], result = str.replace(/[\\\[\]\^$*+?.()|{}]/g, '\\$&'); - if (!param) - return result; + /** + * @coreapi + * @module url + */ + /** @hidden */ + function quoteRegExp(str, param) { + var surroundPattern = ['', ''], + result = str.replace(/[\\\[\]\^$*+?.()|{}]/g, '\\$&'); + if (!param) return result; switch (param.squash) { - case false: - surroundPattern = ['(', ')' + (param.isOptional ? '?' : '')]; - break; - case true: - result = result.replace(/\/$/, ''); - surroundPattern = ['(?:\/(', ')|\/)?']; - break; - default: - surroundPattern = ["(" + param.squash + "|", ')?']; - break; + case false: + surroundPattern = ['(', ')' + (param.isOptional ? '?' : '')]; + break; + case true: + result = result.replace(/\/$/, ''); + surroundPattern = ['(?:/(', ')|/)?']; + break; + default: + surroundPattern = ['(' + param.squash + '|', ')?']; + break; } return result + surroundPattern[0] + param.type.pattern.source + surroundPattern[1]; -} -/** @hidden */ -var memoizeTo = function (obj, _prop, fn) { - return obj[_prop] = obj[_prop] || fn(); -}; -/** @hidden */ -var splitOnSlash = splitOnDelim('/'); -/** - * Matches URLs against patterns. - * - * Matches URLs against patterns and extracts named parameters from the path or the search - * part of the URL. - * - * A URL pattern consists of a path pattern, optionally followed by '?' and a list of search (query) - * parameters. Multiple search parameter names are separated by '&'. Search parameters - * do not influence whether or not a URL is matched, but their values are passed through into - * the matched parameters returned by [[UrlMatcher.exec]]. - * - * - *Path parameters* are defined using curly brace placeholders (`/somepath/{param}`) - * or colon placeholders (`/somePath/:param`). - * - * - *A parameter RegExp* may be defined for a param after a colon - * (`/somePath/{param:[a-zA-Z0-9]+}`) in a curly brace placeholder. - * The regexp must match for the url to be matched. - * Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash. - * - * Note: a RegExp parameter will encode its value using either [[ParamTypes.path]] or [[ParamTypes.query]]. - * - * - *Custom parameter types* may also be specified after a colon (`/somePath/{param:int}`) in curly brace parameters. - * See [[UrlMatcherFactory.type]] for more information. - * - * - *Catch-all parameters* are defined using an asterisk placeholder (`/somepath/*catchallparam`). - * A catch-all * parameter value will contain the remainder of the URL. - * - * --- - * - * Parameter names may contain only word characters (latin letters, digits, and underscore) and - * must be unique within the pattern (across both path and search parameters). - * A path parameter matches any number of characters other than '/'. For catch-all - * placeholders the path parameter matches any number of characters. - * - * Examples: - * - * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for - * trailing slashes, and patterns have to match the entire path, not just a prefix. - * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or - * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. - * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. - * * `'/user/{id:[^/]*}'` - Same as the previous example. - * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id - * parameter consists of 1 to 8 hex digits. - * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the - * path into the parameter 'path'. - * * `'/files/*path'` - ditto. - * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined - * in the built-in `date` ParamType matches `2014-11-12`) and provides a Date object in $stateParams.start - * - */ -var UrlMatcher = /** @class */ (function () { + } + /** @hidden */ + var memoizeTo = function(obj, _prop, fn) { + return (obj[_prop] = obj[_prop] || fn()); + }; + /** @hidden */ + var splitOnSlash = splitOnDelim('/'); + /** + * Matches URLs against patterns. + * + * Matches URLs against patterns and extracts named parameters from the path or the search + * part of the URL. + * + * A URL pattern consists of a path pattern, optionally followed by '?' and a list of search (query) + * parameters. Multiple search parameter names are separated by '&'. Search parameters + * do not influence whether or not a URL is matched, but their values are passed through into + * the matched parameters returned by [[UrlMatcher.exec]]. + * + * - *Path parameters* are defined using curly brace placeholders (`/somepath/{param}`) + * or colon placeholders (`/somePath/:param`). + * + * - *A parameter RegExp* may be defined for a param after a colon + * (`/somePath/{param:[a-zA-Z0-9]+}`) in a curly brace placeholder. + * The regexp must match for the url to be matched. + * Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash. + * + * Note: a RegExp parameter will encode its value using either [[ParamTypes.path]] or [[ParamTypes.query]]. + * + * - *Custom parameter types* may also be specified after a colon (`/somePath/{param:int}`) in curly brace parameters. + * See [[UrlMatcherFactory.type]] for more information. + * + * - *Catch-all parameters* are defined using an asterisk placeholder (`/somepath/*catchallparam`). + * A catch-all * parameter value will contain the remainder of the URL. + * + * --- + * + * Parameter names may contain only word characters (latin letters, digits, and underscore) and + * must be unique within the pattern (across both path and search parameters). + * A path parameter matches any number of characters other than '/'. For catch-all + * placeholders the path parameter matches any number of characters. + * + * Examples: + * + * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for + * trailing slashes, and patterns have to match the entire path, not just a prefix. + * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or + * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. + * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. + * * `'/user/{id:[^/]*}'` - Same as the previous example. + * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id + * parameter consists of 1 to 8 hex digits. + * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the + * path into the parameter 'path'. + * * `'/files/*path'` - ditto. + * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined + * in the built-in `date` ParamType matches `2014-11-12`) and provides a Date object in $stateParams.start + * + */ + var UrlMatcher = /** @class */ (function() { /** * @param pattern The pattern to compile into a matcher. * @param paramTypes The [[ParamTypes]] registry @@ -4538,113 +5076,134 @@ var UrlMatcher = /** @class */ (function () { * - `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`. */ function UrlMatcher(pattern$$1, paramTypes, paramFactory, config) { - var _this = this; - this.config = config; - /** @hidden */ - this._cache = { path: [this] }; - /** @hidden */ - this._children = []; - /** @hidden */ - this._params = []; - /** @hidden */ - this._segments = []; - /** @hidden */ - this._compiled = []; - this.pattern = pattern$$1; - this.config = defaults(this.config, { - params: {}, - strict: true, - caseInsensitive: false, - paramMap: identity, - }); - // Find all placeholders and create a compiled pattern, using either classic or curly syntax: - // '*' name - // ':' name - // '{' name '}' - // '{' name ':' regexp '}' - // The regular expression is somewhat complicated due to the need to allow curly braces - // inside the regular expression. The placeholder regexp breaks down as follows: - // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case) - // \{([\w\[\]]+)(?:\:\s*( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case - // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either - // [^{}\\]+ - anything other than curly braces or backslash - // \\. - a backslash escape - // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms - var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g; - var searchPlaceholder = /([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g; - var patterns = []; - var last = 0, matchArray; - var checkParamErrors = function (id) { - if (!UrlMatcher.nameValidator.test(id)) - throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern$$1 + "'"); - if (find(_this._params, propEq('id', id))) - throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern$$1 + "'"); + var _this = this; + this.config = config; + /** @hidden */ + this._cache = { path: [this] }; + /** @hidden */ + this._children = []; + /** @hidden */ + this._params = []; + /** @hidden */ + this._segments = []; + /** @hidden */ + this._compiled = []; + this.pattern = pattern$$1; + this.config = defaults(this.config, { + params: {}, + strict: true, + caseInsensitive: false, + paramMap: identity, + }); + // Find all placeholders and create a compiled pattern, using either classic or curly syntax: + // '*' name + // ':' name + // '{' name '}' + // '{' name ':' regexp '}' + // The regular expression is somewhat complicated due to the need to allow curly braces + // inside the regular expression. The placeholder regexp breaks down as follows: + // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case) + // \{([\w\[\]]+)(?:\:\s*( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case + // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either + // [^{}\\]+ - anything other than curly braces or backslash + // \\. - a backslash escape + // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms + var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g; + var searchPlaceholder = /([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g; + var patterns = []; + var last = 0, + matchArray; + var checkParamErrors = function(id) { + if (!UrlMatcher.nameValidator.test(id)) + throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern$$1 + "'"); + if (find(_this._params, propEq('id', id))) + throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern$$1 + "'"); + }; + // Split into static segments separated by path parameter placeholders. + // The number of segments is always 1 more than the number of parameters. + var matchDetails = function(m, isSearch) { + // IE[78] returns '' for unmatched groups instead of null + var id = m[2] || m[3]; + var regexp = isSearch ? m[4] : m[4] || (m[1] === '*' ? '[\\s\\S]*' : null); + var makeRegexpType = function(str) { + return inherit(paramTypes.type(isSearch ? 'query' : 'path'), { + pattern: new RegExp(str, _this.config.caseInsensitive ? 'i' : undefined), + }); }; - // Split into static segments separated by path parameter placeholders. - // The number of segments is always 1 more than the number of parameters. - var matchDetails = function (m, isSearch) { - // IE[78] returns '' for unmatched groups instead of null - var id = m[2] || m[3]; - var regexp = isSearch ? m[4] : m[4] || (m[1] === '*' ? '[\\s\\S]*' : null); - var makeRegexpType = function (str) { return inherit(paramTypes.type(isSearch ? 'query' : 'path'), { - pattern: new RegExp(str, _this.config.caseInsensitive ? 'i' : undefined), - }); }; - return { - id: id, - regexp: regexp, - cfg: _this.config.params[id], - segment: pattern$$1.substring(last, m.index), - type: !regexp ? null : paramTypes.type(regexp) || makeRegexpType(regexp), - }; + return { + id: id, + regexp: regexp, + cfg: _this.config.params[id], + segment: pattern$$1.substring(last, m.index), + type: !regexp ? null : paramTypes.type(regexp) || makeRegexpType(regexp), }; - var p, segment; - // tslint:disable-next-line:no-conditional-assignment - while ((matchArray = placeholder.exec(pattern$$1))) { - p = matchDetails(matchArray, false); - if (p.segment.indexOf('?') >= 0) - break; // we're into the search part + }; + var p, segment; + // tslint:disable-next-line:no-conditional-assignment + while ((matchArray = placeholder.exec(pattern$$1))) { + p = matchDetails(matchArray, false); + if (p.segment.indexOf('?') >= 0) break; // we're into the search part + checkParamErrors(p.id); + this._params.push(paramFactory.fromPath(p.id, p.type, this.config.paramMap(p.cfg, false))); + this._segments.push(p.segment); + patterns.push([p.segment, tail(this._params)]); + last = placeholder.lastIndex; + } + segment = pattern$$1.substring(last); + // Find any search parameter names and remove them from the last segment + var i = segment.indexOf('?'); + if (i >= 0) { + var search = segment.substring(i); + segment = segment.substring(0, i); + if (search.length > 0) { + last = 0; + // tslint:disable-next-line:no-conditional-assignment + while ((matchArray = searchPlaceholder.exec(search))) { + p = matchDetails(matchArray, true); checkParamErrors(p.id); - this._params.push(paramFactory.fromPath(p.id, p.type, this.config.paramMap(p.cfg, false))); - this._segments.push(p.segment); - patterns.push([p.segment, tail(this._params)]); + this._params.push(paramFactory.fromSearch(p.id, p.type, this.config.paramMap(p.cfg, true))); last = placeholder.lastIndex; + // check if ?& + } } - segment = pattern$$1.substring(last); - // Find any search parameter names and remove them from the last segment - var i = segment.indexOf('?'); - if (i >= 0) { - var search = segment.substring(i); - segment = segment.substring(0, i); - if (search.length > 0) { - last = 0; - // tslint:disable-next-line:no-conditional-assignment - while ((matchArray = searchPlaceholder.exec(search))) { - p = matchDetails(matchArray, true); - checkParamErrors(p.id); - this._params.push(paramFactory.fromSearch(p.id, p.type, this.config.paramMap(p.cfg, true))); - last = placeholder.lastIndex; - // check if ?& - } - } - } - this._segments.push(segment); - this._compiled = patterns.map(function (_pattern) { return quoteRegExp.apply(null, _pattern); }).concat(quoteRegExp(segment)); + } + this._segments.push(segment); + this._compiled = patterns + .map(function(_pattern) { + return quoteRegExp.apply(null, _pattern); + }) + .concat(quoteRegExp(segment)); } /** @hidden */ - UrlMatcher.encodeDashes = function (str) { - return encodeURIComponent(str).replace(/-/g, function (c) { return "%5C%" + c.charCodeAt(0).toString(16).toUpperCase(); }); + UrlMatcher.encodeDashes = function(str) { + // Replace dashes with encoded "\-" + return encodeURIComponent(str).replace(/-/g, function(c) { + return ( + '%5C%' + + c + .charCodeAt(0) + .toString(16) + .toUpperCase() + ); + }); }; /** @hidden Given a matcher, return an array with the matcher's path segments and path params, in order */ - UrlMatcher.pathSegmentsAndParams = function (matcher) { - var staticSegments = matcher._segments; - var pathParams = matcher._params.filter(function (p) { return p.location === exports.DefType.PATH; }); - return arrayTuples(staticSegments, pathParams.concat(undefined)) - .reduce(unnestR, []) - .filter(function (x) { return x !== '' && isDefined(x); }); + UrlMatcher.pathSegmentsAndParams = function(matcher) { + var staticSegments = matcher._segments; + var pathParams = matcher._params.filter(function(p) { + return p.location === exports.DefType.PATH; + }); + return arrayTuples(staticSegments, pathParams.concat(undefined)) + .reduce(unnestR, []) + .filter(function(x) { + return x !== '' && isDefined(x); + }); }; /** @hidden Given a matcher, return an array with the matcher's query params */ - UrlMatcher.queryParams = function (matcher) { - return matcher._params.filter(function (p) { return p.location === exports.DefType.SEARCH; }); + UrlMatcher.queryParams = function(matcher) { + return matcher._params.filter(function(p) { + return p.location === exports.DefType.SEARCH; + }); }; /** * Compare two UrlMatchers @@ -4655,62 +5214,62 @@ var UrlMatcher = /** @class */ (function () { * * The comparison function sorts static segments before dynamic ones. */ - UrlMatcher.compare = function (a, b) { - /** - * Turn a UrlMatcher and all its parent matchers into an array - * of slash literals '/', string literals, and Param objects - * - * This example matcher matches strings like "/foo/:param/tail": - * var matcher = $umf.compile("/foo").append($umf.compile("/:param")).append($umf.compile("/")).append($umf.compile("tail")); - * var result = segments(matcher); // [ '/', 'foo', '/', Param, '/', 'tail' ] - * - * Caches the result as `matcher._cache.segments` - */ - var segments = function (matcher) { - return matcher._cache.segments = matcher._cache.segments || - matcher._cache.path.map(UrlMatcher.pathSegmentsAndParams) - .reduce(unnestR, []) - .reduce(joinNeighborsR, []) - .map(function (x) { return isString(x) ? splitOnSlash(x) : x; }) - .reduce(unnestR, []); - }; - /** - * Gets the sort weight for each segment of a UrlMatcher - * - * Caches the result as `matcher._cache.weights` - */ - var weights = function (matcher) { - return matcher._cache.weights = matcher._cache.weights || - segments(matcher).map(function (segment) { - // Sort slashes first, then static strings, the Params - if (segment === '/') - return 1; - if (isString(segment)) - return 2; - if (segment instanceof Param) - return 3; - }); - }; - /** - * Pads shorter array in-place (mutates) - */ - var padArrays = function (l, r, padVal) { - var len = Math.max(l.length, r.length); - while (l.length < len) - l.push(padVal); - while (r.length < len) - r.push(padVal); - }; - var weightsA = weights(a), weightsB = weights(b); - padArrays(weightsA, weightsB, 0); - var _pairs = arrayTuples(weightsA, weightsB); - var cmp, i; - for (i = 0; i < _pairs.length; i++) { - cmp = _pairs[i][0] - _pairs[i][1]; - if (cmp !== 0) - return cmp; - } - return 0; + UrlMatcher.compare = function(a, b) { + /** + * Turn a UrlMatcher and all its parent matchers into an array + * of slash literals '/', string literals, and Param objects + * + * This example matcher matches strings like "/foo/:param/tail": + * var matcher = $umf.compile("/foo").append($umf.compile("/:param")).append($umf.compile("/")).append($umf.compile("tail")); + * var result = segments(matcher); // [ '/', 'foo', '/', Param, '/', 'tail' ] + * + * Caches the result as `matcher._cache.segments` + */ + var segments = function(matcher) { + return (matcher._cache.segments = + matcher._cache.segments || + matcher._cache.path + .map(UrlMatcher.pathSegmentsAndParams) + .reduce(unnestR, []) + .reduce(joinNeighborsR, []) + .map(function(x) { + return isString(x) ? splitOnSlash(x) : x; + }) + .reduce(unnestR, [])); + }; + /** + * Gets the sort weight for each segment of a UrlMatcher + * + * Caches the result as `matcher._cache.weights` + */ + var weights = function(matcher) { + return (matcher._cache.weights = + matcher._cache.weights || + segments(matcher).map(function(segment) { + // Sort slashes first, then static strings, the Params + if (segment === '/') return 1; + if (isString(segment)) return 2; + if (segment instanceof Param) return 3; + })); + }; + /** + * Pads shorter array in-place (mutates) + */ + var padArrays = function(l, r, padVal) { + var len = Math.max(l.length, r.length); + while (l.length < len) l.push(padVal); + while (r.length < len) r.push(padVal); + }; + var weightsA = weights(a), + weightsB = weights(b); + padArrays(weightsA, weightsB, 0); + var _pairs = arrayTuples(weightsA, weightsB); + var cmp, i; + for (i = 0; i < _pairs.length; i++) { + cmp = _pairs[i][0] - _pairs[i][1]; + if (cmp !== 0) return cmp; + } + return 0; }; /** * Creates a new concatenated UrlMatcher @@ -4719,22 +5278,22 @@ var UrlMatcher = /** @class */ (function () { * * @param url A `UrlMatcher` instance to append as a child of the current `UrlMatcher`. */ - UrlMatcher.prototype.append = function (url) { - this._children.push(url); - url._cache = { - path: this._cache.path.concat(url), - parent: this, - pattern: null, - }; - return url; + UrlMatcher.prototype.append = function(url) { + this._children.push(url); + url._cache = { + path: this._cache.path.concat(url), + parent: this, + pattern: null, + }; + return url; }; /** @hidden */ - UrlMatcher.prototype.isRoot = function () { - return this._cache.path[0] === this; + UrlMatcher.prototype.isRoot = function() { + return this._cache.path[0] === this; }; /** Returns the input pattern string */ - UrlMatcher.prototype.toString = function () { - return this.pattern; + UrlMatcher.prototype.toString = function() { + return this.pattern; }; /** * Tests the specified url/path against this matcher. @@ -4762,58 +5321,79 @@ var UrlMatcher = /** @class */ (function () { * * @returns The captured parameter values. */ - UrlMatcher.prototype.exec = function (path, search, hash, options) { - var _this = this; - if (search === void 0) { search = {}; } - if (options === void 0) { options = {}; } - var match = memoizeTo(this._cache, 'pattern', function () { - return new RegExp([ - '^', - unnest(_this._cache.path.map(prop('_compiled'))).join(''), - _this.config.strict === false ? '\/?' : '', - '$', - ].join(''), _this.config.caseInsensitive ? 'i' : undefined); - }).exec(path); - if (!match) - return null; - // options = defaults(options, { isolate: false }); - var allParams = this.parameters(), pathParams = allParams.filter(function (param) { return !param.isSearch(); }), searchParams = allParams.filter(function (param) { return param.isSearch(); }), nPathSegments = this._cache.path.map(function (urlm) { return urlm._segments.length - 1; }).reduce(function (a, x) { return a + x; }), values$$1 = {}; - if (nPathSegments !== match.length - 1) - throw new Error("Unbalanced capture group in route '" + this.pattern + "'"); - function decodePathArray(paramVal) { - var reverseString = function (str) { return str.split('').reverse().join(''); }; - var unquoteDashes = function (str) { return str.replace(/\\-/g, '-'); }; - var split = reverseString(paramVal).split(/-(?!\\)/); - var allReversed = map(split, reverseString); - return map(allReversed, unquoteDashes).reverse(); + UrlMatcher.prototype.exec = function(path, search, hash, options) { + var _this = this; + if (search === void 0) { + search = {}; + } + if (options === void 0) { + options = {}; + } + var match = memoizeTo(this._cache, 'pattern', function() { + return new RegExp( + [ + '^', + unnest(_this._cache.path.map(prop('_compiled'))).join(''), + _this.config.strict === false ? '/?' : '', + '$', + ].join(''), + _this.config.caseInsensitive ? 'i' : undefined, + ); + }).exec(path); + if (!match) return null; + // options = defaults(options, { isolate: false }); + var allParams = this.parameters(), + pathParams = allParams.filter(function(param) { + return !param.isSearch(); + }), + searchParams = allParams.filter(function(param) { + return param.isSearch(); + }), + nPathSegments = this._cache.path + .map(function(urlm) { + return urlm._segments.length - 1; + }) + .reduce(function(a, x) { + return a + x; + }), + values$$1 = {}; + if (nPathSegments !== match.length - 1) + throw new Error("Unbalanced capture group in route '" + this.pattern + "'"); + function decodePathArray(paramVal) { + var reverseString = function(str) { + return str + .split('') + .reverse() + .join(''); + }; + var unquoteDashes = function(str) { + return str.replace(/\\-/g, '-'); + }; + var split = reverseString(paramVal).split(/-(?!\\)/); + var allReversed = map(split, reverseString); + return map(allReversed, unquoteDashes).reverse(); + } + for (var i = 0; i < nPathSegments; i++) { + var param = pathParams[i]; + var value = match[i + 1]; + // if the param value matches a pre-replace pair, replace the value before decoding. + for (var j = 0; j < param.replace.length; j++) { + if (param.replace[j].from === value) value = param.replace[j].to; } - for (var i = 0; i < nPathSegments; i++) { - var param = pathParams[i]; - var value = match[i + 1]; - // if the param value matches a pre-replace pair, replace the value before decoding. - for (var j = 0; j < param.replace.length; j++) { - if (param.replace[j].from === value) - value = param.replace[j].to; - } - if (value && param.array === true) - value = decodePathArray(value); - if (isDefined(value)) - value = param.type.decode(value); - values$$1[param.id] = param.value(value); + if (value && param.array === true) value = decodePathArray(value); + if (isDefined(value)) value = param.type.decode(value); + values$$1[param.id] = param.value(value); + } + searchParams.forEach(function(param) { + var value = search[param.id]; + for (var j = 0; j < param.replace.length; j++) { + if (param.replace[j].from === value) value = param.replace[j].to; } - searchParams.forEach(function (param) { - var value = search[param.id]; - for (var j = 0; j < param.replace.length; j++) { - if (param.replace[j].from === value) - value = param.replace[j].to; - } - if (isDefined(value)) - value = param.type.decode(value); - values$$1[param.id] = param.value(value); - }); - if (hash) - values$$1['#'] = hash; - return values$$1; + if (isDefined(value)) value = param.type.decode(value); + values$$1[param.id] = param.value(value); + }); + if (hash) values$$1['#'] = hash; + return values$$1; }; /** * @hidden @@ -4822,11 +5402,16 @@ var UrlMatcher = /** @class */ (function () { * @returns {Array.} An array of [[Param]] objects. Must be treated as read-only. If the * pattern has no parameters, an empty array is returned. */ - UrlMatcher.prototype.parameters = function (opts) { - if (opts === void 0) { opts = {}; } - if (opts.inherit === false) - return this._params; - return unnest(this._cache.path.map(function (matcher) { return matcher._params; })); + UrlMatcher.prototype.parameters = function(opts) { + if (opts === void 0) { + opts = {}; + } + if (opts.inherit === false) return this._params; + return unnest( + this._cache.path.map(function(matcher) { + return matcher._params; + }), + ); }; /** * @hidden @@ -4836,18 +5421,19 @@ var UrlMatcher = /** @class */ (function () { * @param opts * @returns {T|Param|any|boolean|UrlMatcher|null} */ - UrlMatcher.prototype.parameter = function (id, opts) { - var _this = this; - if (opts === void 0) { opts = {}; } - var findParam = function () { - for (var _i = 0, _a = _this._params; _i < _a.length; _i++) { - var param = _a[_i]; - if (param.id === id) - return param; - } - }; - var parent = this._cache.parent; - return findParam() || (opts.inherit !== false && parent && parent.parameter(id, opts)) || null; + UrlMatcher.prototype.parameter = function(id, opts) { + var _this = this; + if (opts === void 0) { + opts = {}; + } + var findParam = function() { + for (var _i = 0, _a = _this._params; _i < _a.length; _i++) { + var param = _a[_i]; + if (param.id === id) return param; + } + }; + var parent = this._cache.parent; + return findParam() || (opts.inherit !== false && parent && parent.parameter(id, opts)) || null; }; /** * Validates the input parameter values against this UrlMatcher @@ -4858,14 +5444,20 @@ var UrlMatcher = /** @class */ (function () { * @param params The object hash of parameters to validate. * @returns Returns `true` if `params` validates, otherwise `false`. */ - UrlMatcher.prototype.validates = function (params) { - var validParamVal = function (param, val$$1) { - return !param || param.validates(val$$1); - }; - params = params || {}; - // I'm not sure why this checks only the param keys passed in, and not all the params known to the matcher - var paramSchema = this.parameters().filter(function (paramDef) { return params.hasOwnProperty(paramDef.id); }); - return paramSchema.map(function (paramDef) { return validParamVal(paramDef, params[paramDef.id]); }).reduce(allTrueR, true); + UrlMatcher.prototype.validates = function(params) { + var validParamVal = function(param, val$$1) { + return !param || param.validates(val$$1); + }; + params = params || {}; + // I'm not sure why this checks only the param keys passed in, and not all the params known to the matcher + var paramSchema = this.parameters().filter(function(paramDef) { + return params.hasOwnProperty(paramDef.id); + }); + return paramSchema + .map(function(paramDef) { + return validParamVal(paramDef, params[paramDef.id]); + }) + .reduce(allTrueR, true); }; /** * Given a set of parameter values, creates a URL from this UrlMatcher. @@ -4882,136 +5474,150 @@ var UrlMatcher = /** @class */ (function () { * @param values the values to substitute for the parameters in this pattern. * @returns the formatted URL (path and optionally search part). */ - UrlMatcher.prototype.format = function (values$$1) { - if (values$$1 === void 0) { values$$1 = {}; } - // Build the full path of UrlMatchers (including all parent UrlMatchers) - var urlMatchers = this._cache.path; - // Extract all the static segments and Params (processed as ParamDetails) - // into an ordered array - var pathSegmentsAndParams = urlMatchers.map(UrlMatcher.pathSegmentsAndParams) - .reduce(unnestR, []) - .map(function (x) { return isString(x) ? x : getDetails(x); }); - // Extract the query params into a separate array - var queryParams = urlMatchers.map(UrlMatcher.queryParams) - .reduce(unnestR, []) - .map(getDetails); - var isInvalid = function (param) { return param.isValid === false; }; - if (pathSegmentsAndParams.concat(queryParams).filter(isInvalid).length) { - return null; - } - /** - * Given a Param, applies the parameter value, then returns detailed information about it - */ - function getDetails(param) { - // Normalize to typed value - var value = param.value(values$$1[param.id]); - var isValid = param.validates(value); - var isDefaultValue = param.isDefaultValue(value); - // Check if we're in squash mode for the parameter - var squash = isDefaultValue ? param.squash : false; - // Allow the Parameter's Type to encode the value - var encoded = param.type.encode(value); - return { param: param, value: value, isValid: isValid, isDefaultValue: isDefaultValue, squash: squash, encoded: encoded }; - } - // Build up the path-portion from the list of static segments and parameters - var pathString = pathSegmentsAndParams.reduce(function (acc, x) { - // The element is a static segment (a raw string); just append it - if (isString(x)) - return acc + x; - // Otherwise, it's a ParamDetails. - var squash = x.squash, encoded = x.encoded, param = x.param; - // If squash is === true, try to remove a slash from the path - if (squash === true) - return (acc.match(/\/$/)) ? acc.slice(0, -1) : acc; - // If squash is a string, use the string for the param value - if (isString(squash)) - return acc + squash; - if (squash !== false) - return acc; // ? - if (encoded == null) - return acc; - // If this parameter value is an array, encode the value using encodeDashes - if (isArray(encoded)) - return acc + map(encoded, UrlMatcher.encodeDashes).join('-'); - // If the parameter type is "raw", then do not encodeURIComponent - if (param.raw) - return acc + encoded; - // Encode the value - return acc + encodeURIComponent(encoded); - }, ''); - // Build the query string by applying parameter values (array or regular) - // then mapping to key=value, then flattening and joining using "&" - var queryString = queryParams.map(function (paramDetails) { - var param = paramDetails.param, squash = paramDetails.squash, encoded = paramDetails.encoded, isDefaultValue = paramDetails.isDefaultValue; - if (encoded == null || (isDefaultValue && squash !== false)) - return; - if (!isArray(encoded)) - encoded = [encoded]; - if (encoded.length === 0) - return; - if (!param.raw) - encoded = map(encoded, encodeURIComponent); - return encoded.map(function (val$$1) { return param.id + "=" + val$$1; }); - }).filter(identity).reduce(unnestR, []).join('&'); - // Concat the pathstring with the queryString (if exists) and the hashString (if exists) - return pathString + (queryString ? "?" + queryString : '') + (values$$1['#'] ? '#' + values$$1['#'] : ''); + UrlMatcher.prototype.format = function(values$$1) { + if (values$$1 === void 0) { + values$$1 = {}; + } + // Build the full path of UrlMatchers (including all parent UrlMatchers) + var urlMatchers = this._cache.path; + // Extract all the static segments and Params (processed as ParamDetails) + // into an ordered array + var pathSegmentsAndParams = urlMatchers + .map(UrlMatcher.pathSegmentsAndParams) + .reduce(unnestR, []) + .map(function(x) { + return isString(x) ? x : getDetails(x); + }); + // Extract the query params into a separate array + var queryParams = urlMatchers + .map(UrlMatcher.queryParams) + .reduce(unnestR, []) + .map(getDetails); + var isInvalid = function(param) { + return param.isValid === false; + }; + if (pathSegmentsAndParams.concat(queryParams).filter(isInvalid).length) { + return null; + } + /** + * Given a Param, applies the parameter value, then returns detailed information about it + */ + function getDetails(param) { + // Normalize to typed value + var value = param.value(values$$1[param.id]); + var isValid = param.validates(value); + var isDefaultValue = param.isDefaultValue(value); + // Check if we're in squash mode for the parameter + var squash = isDefaultValue ? param.squash : false; + // Allow the Parameter's Type to encode the value + var encoded = param.type.encode(value); + return { + param: param, + value: value, + isValid: isValid, + isDefaultValue: isDefaultValue, + squash: squash, + encoded: encoded, + }; + } + // Build up the path-portion from the list of static segments and parameters + var pathString = pathSegmentsAndParams.reduce(function(acc, x) { + // The element is a static segment (a raw string); just append it + if (isString(x)) return acc + x; + // Otherwise, it's a ParamDetails. + var squash = x.squash, + encoded = x.encoded, + param = x.param; + // If squash is === true, try to remove a slash from the path + if (squash === true) return acc.match(/\/$/) ? acc.slice(0, -1) : acc; + // If squash is a string, use the string for the param value + if (isString(squash)) return acc + squash; + if (squash !== false) return acc; // ? + if (encoded == null) return acc; + // If this parameter value is an array, encode the value using encodeDashes + if (isArray(encoded)) return acc + map(encoded, UrlMatcher.encodeDashes).join('-'); + // If the parameter type is "raw", then do not encodeURIComponent + if (param.raw) return acc + encoded; + // Encode the value + return acc + encodeURIComponent(encoded); + }, ''); + // Build the query string by applying parameter values (array or regular) + // then mapping to key=value, then flattening and joining using "&" + var queryString = queryParams + .map(function(paramDetails) { + var param = paramDetails.param, + squash = paramDetails.squash, + encoded = paramDetails.encoded, + isDefaultValue = paramDetails.isDefaultValue; + if (encoded == null || (isDefaultValue && squash !== false)) return; + if (!isArray(encoded)) encoded = [encoded]; + if (encoded.length === 0) return; + if (!param.raw) encoded = map(encoded, encodeURIComponent); + return encoded.map(function(val$$1) { + return param.id + '=' + val$$1; + }); + }) + .filter(identity) + .reduce(unnestR, []) + .join('&'); + // Concat the pathstring with the queryString (if exists) and the hashString (if exists) + return pathString + (queryString ? '?' + queryString : '') + (values$$1['#'] ? '#' + values$$1['#'] : ''); }; /** @hidden */ UrlMatcher.nameValidator = /^\w+([-.]+\w+)*(?:\[\])?$/; return UrlMatcher; -}()); + })(); /** for typedoc */ -/** - * @internalapi - * @module url - */ /** for typedoc */ -/** - * Factory for [[UrlMatcher]] instances. - * - * The factory is available to ng1 services as - * `$urlMatcherFactory` or ng1 providers as `$urlMatcherFactoryProvider`. - */ -var UrlMatcherFactory = /** @class */ (function () { + /** + * @internalapi + * @module url + */ /** + * Factory for [[UrlMatcher]] instances. + * + * The factory is available to ng1 services as + * `$urlMatcherFactory` or ng1 providers as `$urlMatcherFactoryProvider`. + */ + var UrlMatcherFactory = /** @class */ (function() { function UrlMatcherFactory() { - var _this = this; - /** @hidden */ this.paramTypes = new ParamTypes(); - /** @hidden */ this._isCaseInsensitive = false; - /** @hidden */ this._isStrictMode = true; - /** @hidden */ this._defaultSquashPolicy = false; - /** @internalapi Creates a new [[Param]] for a given location (DefType) */ - this.paramFactory = { - /** Creates a new [[Param]] from a CONFIG block */ - fromConfig: function (id, type, config) { - return new Param(id, type, config, exports.DefType.CONFIG, _this); - }, - /** Creates a new [[Param]] from a url PATH */ - fromPath: function (id, type, config) { - return new Param(id, type, config, exports.DefType.PATH, _this); - }, - /** Creates a new [[Param]] from a url SEARCH */ - fromSearch: function (id, type, config) { - return new Param(id, type, config, exports.DefType.SEARCH, _this); - }, - }; - /** @hidden */ - this._getConfig = function (config) { - return extend({ strict: _this._isStrictMode, caseInsensitive: _this._isCaseInsensitive }, config); - }; - extend(this, { UrlMatcher: UrlMatcher, Param: Param }); + var _this = this; + /** @hidden */ this.paramTypes = new ParamTypes(); + /** @hidden */ this._isCaseInsensitive = false; + /** @hidden */ this._isStrictMode = true; + /** @hidden */ this._defaultSquashPolicy = false; + /** @internalapi Creates a new [[Param]] for a given location (DefType) */ + this.paramFactory = { + /** Creates a new [[Param]] from a CONFIG block */ + fromConfig: function(id, type, config) { + return new Param(id, type, config, exports.DefType.CONFIG, _this); + }, + /** Creates a new [[Param]] from a url PATH */ + fromPath: function(id, type, config) { + return new Param(id, type, config, exports.DefType.PATH, _this); + }, + /** Creates a new [[Param]] from a url SEARCH */ + fromSearch: function(id, type, config) { + return new Param(id, type, config, exports.DefType.SEARCH, _this); + }, + }; + /** @hidden */ + this._getConfig = function(config) { + return extend({ strict: _this._isStrictMode, caseInsensitive: _this._isCaseInsensitive }, config); + }; + extend(this, { UrlMatcher: UrlMatcher, Param: Param }); } /** @inheritdoc */ - UrlMatcherFactory.prototype.caseInsensitive = function (value) { - return this._isCaseInsensitive = isDefined(value) ? value : this._isCaseInsensitive; + UrlMatcherFactory.prototype.caseInsensitive = function(value) { + return (this._isCaseInsensitive = isDefined(value) ? value : this._isCaseInsensitive); }; /** @inheritdoc */ - UrlMatcherFactory.prototype.strictMode = function (value) { - return this._isStrictMode = isDefined(value) ? value : this._isStrictMode; + UrlMatcherFactory.prototype.strictMode = function(value) { + return (this._isStrictMode = isDefined(value) ? value : this._isStrictMode); }; /** @inheritdoc */ - UrlMatcherFactory.prototype.defaultSquashPolicy = function (value) { - if (isDefined(value) && value !== true && value !== false && !isString(value)) - throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string"); - return this._defaultSquashPolicy = isDefined(value) ? value : this._defaultSquashPolicy; + UrlMatcherFactory.prototype.defaultSquashPolicy = function(value) { + if (isDefined(value) && value !== true && value !== false && !isString(value)) + throw new Error('Invalid squash policy: ' + value + '. Valid policies: false, true, arbitrary-string'); + return (this._defaultSquashPolicy = isDefined(value) ? value : this._defaultSquashPolicy); }; /** * Creates a [[UrlMatcher]] for the specified pattern. @@ -5020,8 +5626,8 @@ var UrlMatcherFactory = /** @class */ (function () { * @param config The config object hash. * @returns The UrlMatcher. */ - UrlMatcherFactory.prototype.compile = function (pattern, config) { - return new UrlMatcher(pattern, this.paramTypes, this.paramFactory, this._getConfig(config)); + UrlMatcherFactory.prototype.compile = function(pattern, config) { + return new UrlMatcher(pattern, this.paramTypes, this.paramFactory, this._getConfig(config)); }; /** * Returns true if the specified object is a [[UrlMatcher]], or false otherwise. @@ -5030,16 +5636,14 @@ var UrlMatcherFactory = /** @class */ (function () { * @returns `true` if the object matches the `UrlMatcher` interface, by * implementing all the same methods. */ - UrlMatcherFactory.prototype.isMatcher = function (object) { - // TODO: typeof? - if (!isObject(object)) - return false; - var result = true; - forEach(UrlMatcher.prototype, function (val, name) { - if (isFunction(val)) - result = result && (isDefined(object[name]) && isFunction(object[name])); - }); - return result; + UrlMatcherFactory.prototype.isMatcher = function(object) { + // TODO: typeof? + if (!isObject(object)) return false; + var result = true; + forEach(UrlMatcher.prototype, function(val, name) { + if (isFunction(val)) result = result && (isDefined(object[name]) && isFunction(object[name])); + }); + return result; }; /** * Creates and registers a custom [[ParamType]] object @@ -5060,58 +5664,81 @@ var UrlMatcherFactory = /** @class */ (function () { * * See [[ParamTypeDefinition]] for examples */ - UrlMatcherFactory.prototype.type = function (name, definition, definitionFn) { - var type = this.paramTypes.type(name, definition, definitionFn); - return !isDefined(definition) ? type : this; + UrlMatcherFactory.prototype.type = function(name, definition, definitionFn) { + var type = this.paramTypes.type(name, definition, definitionFn); + return !isDefined(definition) ? type : this; }; /** @hidden */ - UrlMatcherFactory.prototype.$get = function () { - this.paramTypes.enqueue = false; - this.paramTypes._flushTypeQueue(); - return this; + UrlMatcherFactory.prototype.$get = function() { + this.paramTypes.enqueue = false; + this.paramTypes._flushTypeQueue(); + return this; }; /** @internalapi */ - UrlMatcherFactory.prototype.dispose = function () { - this.paramTypes.dispose(); + UrlMatcherFactory.prototype.dispose = function() { + this.paramTypes.dispose(); }; return UrlMatcherFactory; -}()); + })(); /** */ -/** - * @coreapi - * @module url - */ /** */ -/** - * Creates a [[UrlRule]] - * - * Creates a [[UrlRule]] from a: - * - * - `string` - * - [[UrlMatcher]] - * - `RegExp` - * - [[StateObject]] - * @internalapi - */ -var UrlRuleFactory = /** @class */ (function () { + /** + * @coreapi + * @module url + */ /** + * Creates a [[UrlRule]] + * + * Creates a [[UrlRule]] from a: + * + * - `string` + * - [[UrlMatcher]] + * - `RegExp` + * - [[StateObject]] + * @internalapi + */ + var UrlRuleFactory = /** @class */ (function() { function UrlRuleFactory(router) { - this.router = router; + this.router = router; } - UrlRuleFactory.prototype.compile = function (str) { - return this.router.urlMatcherFactory.compile(str); + UrlRuleFactory.prototype.compile = function(str) { + return this.router.urlMatcherFactory.compile(str); }; - UrlRuleFactory.prototype.create = function (what, handler) { - var _this = this; - var makeRule = pattern([ - [isString, function (_what) { return makeRule(_this.compile(_what)); }], - [is(UrlMatcher), function (_what) { return _this.fromUrlMatcher(_what, handler); }], - [isState, function (_what) { return _this.fromState(_what, _this.router); }], - [is(RegExp), function (_what) { return _this.fromRegExp(_what, handler); }], - [isFunction, function (_what) { return new BaseUrlRule(_what, handler); }], - ]); - var rule = makeRule(what); - if (!rule) - throw new Error("invalid 'what' in when()"); - return rule; + UrlRuleFactory.prototype.create = function(what, handler) { + var _this = this; + var makeRule = pattern([ + [ + isString, + function(_what) { + return makeRule(_this.compile(_what)); + }, + ], + [ + is(UrlMatcher), + function(_what) { + return _this.fromUrlMatcher(_what, handler); + }, + ], + [ + isState, + function(_what) { + return _this.fromState(_what, _this.router); + }, + ], + [ + is(RegExp), + function(_what) { + return _this.fromRegExp(_what, handler); + }, + ], + [ + isFunction, + function(_what) { + return new BaseUrlRule(_what, handler); + }, + ], + ]); + var rule = makeRule(what); + if (!rule) throw new Error("invalid 'what' in when()"); + return rule; }; /** * A UrlRule which matches based on a UrlMatcher @@ -5149,30 +5776,34 @@ var UrlRuleFactory = /** @class */ (function () { * var result = rule.handler(match); // '/home/123/456' * ``` */ - UrlRuleFactory.prototype.fromUrlMatcher = function (urlMatcher, handler) { - var _handler = handler; - if (isString(handler)) - handler = this.router.urlMatcherFactory.compile(handler); - if (is(UrlMatcher)(handler)) - _handler = function (match) { return handler.format(match); }; - function matchUrlParamters(url) { - var params = urlMatcher.exec(url.path, url.search, url.hash); - return urlMatcher.validates(params) && params; - } - // Prioritize URLs, lowest to highest: - // - Some optional URL parameters, but none matched - // - No optional parameters in URL - // - Some optional parameters, some matched - // - Some optional parameters, all matched - function matchPriority(params) { - var optional = urlMatcher.parameters().filter(function (param) { return param.isOptional; }); - if (!optional.length) - return 0.000001; - var matched = optional.filter(function (param) { return params[param.id]; }); - return matched.length / optional.length; - } - var details = { urlMatcher: urlMatcher, matchPriority: matchPriority, type: 'URLMATCHER' }; - return extend(new BaseUrlRule(matchUrlParamters, _handler), details); + UrlRuleFactory.prototype.fromUrlMatcher = function(urlMatcher, handler) { + var _handler = handler; + if (isString(handler)) handler = this.router.urlMatcherFactory.compile(handler); + if (is(UrlMatcher)(handler)) + _handler = function(match) { + return handler.format(match); + }; + function matchUrlParamters(url) { + var params = urlMatcher.exec(url.path, url.search, url.hash); + return urlMatcher.validates(params) && params; + } + // Prioritize URLs, lowest to highest: + // - Some optional URL parameters, but none matched + // - No optional parameters in URL + // - Some optional parameters, some matched + // - Some optional parameters, all matched + function matchPriority(params) { + var optional = urlMatcher.parameters().filter(function(param) { + return param.isOptional; + }); + if (!optional.length) return 0.000001; + var matched = optional.filter(function(param) { + return params[param.id]; + }); + return matched.length / optional.length; + } + var details = { urlMatcher: urlMatcher, matchPriority: matchPriority, type: 'URLMATCHER' }; + return extend(new BaseUrlRule(matchUrlParamters, _handler), details); }; /** * A UrlRule which matches a state by its url @@ -5185,23 +5816,23 @@ var UrlRuleFactory = /** @class */ (function () { * // Starts a transition to 'foo' with params: { fooId: '123', barId: '456' } * ``` */ - UrlRuleFactory.prototype.fromState = function (state, router) { - /** - * Handles match by transitioning to matched state - * - * First checks if the router should start a new transition. - * A new transition is not required if the current state's URL - * and the new URL are already identical - */ - var handler = function (match) { - var $state = router.stateService; - var globals = router.globals; - if ($state.href(state, match) !== $state.href(globals.current, globals.params)) { - $state.transitionTo(state, match, { inherit: true, source: 'url' }); - } - }; - var details = { state: state, type: 'STATE' }; - return extend(this.fromUrlMatcher(state.url, handler), details); + UrlRuleFactory.prototype.fromState = function(state, router) { + /** + * Handles match by transitioning to matched state + * + * First checks if the router should start a new transition. + * A new transition is not required if the current state's URL + * and the new URL are already identical + */ + var handler = function(match) { + var $state = router.stateService; + var globals = router.globals; + if ($state.href(state, match) !== $state.href(globals.current, globals.params)) { + $state.transitionTo(state, match, { inherit: true, source: 'url' }); + } + }; + var details = { state: state, type: 'STATE' }; + return extend(this.fromUrlMatcher(state.url, handler), details); }; /** * A UrlRule which matches based on a regular expression @@ -5235,230 +5866,249 @@ var UrlRuleFactory = /** @class */ (function () { * var result = rule.handler(match); // '/home/bar' * ``` */ - UrlRuleFactory.prototype.fromRegExp = function (regexp, handler) { - if (regexp.global || regexp.sticky) - throw new Error('Rule RegExp must not be global or sticky'); - /** - * If handler is a string, the url will be replaced by the string. - * If the string has any String.replace() style variables in it (like `$2`), - * they will be replaced by the captures from [[match]] - */ - var redirectUrlTo = function (match) { - // Interpolates matched values into $1 $2, etc using a String.replace()-style pattern - return handler.replace(/\$(\$|\d{1,2})/, function (m, what) { - return match[what === '$' ? 0 : Number(what)]; - }); - }; - var _handler = isString(handler) ? redirectUrlTo : handler; - var matchParamsFromRegexp = function (url) { - return regexp.exec(url.path); - }; - var details = { regexp: regexp, type: 'REGEXP' }; - return extend(new BaseUrlRule(matchParamsFromRegexp, _handler), details); + UrlRuleFactory.prototype.fromRegExp = function(regexp, handler) { + if (regexp.global || regexp.sticky) throw new Error('Rule RegExp must not be global or sticky'); + /** + * If handler is a string, the url will be replaced by the string. + * If the string has any String.replace() style variables in it (like `$2`), + * they will be replaced by the captures from [[match]] + */ + var redirectUrlTo = function(match) { + // Interpolates matched values into $1 $2, etc using a String.replace()-style pattern + return handler.replace(/\$(\$|\d{1,2})/, function(m, what) { + return match[what === '$' ? 0 : Number(what)]; + }); + }; + var _handler = isString(handler) ? redirectUrlTo : handler; + var matchParamsFromRegexp = function(url) { + return regexp.exec(url.path); + }; + var details = { regexp: regexp, type: 'REGEXP' }; + return extend(new BaseUrlRule(matchParamsFromRegexp, _handler), details); }; - UrlRuleFactory.isUrlRule = function (obj) { - return obj && ['type', 'match', 'handler'].every(function (key) { return isDefined(obj[key]); }); + UrlRuleFactory.isUrlRule = function(obj) { + return ( + obj && + ['type', 'match', 'handler'].every(function(key) { + return isDefined(obj[key]); + }) + ); }; return UrlRuleFactory; -}()); -/** - * A base rule which calls `match` - * - * The value from the `match` function is passed through to the `handler`. - * @internalapi - */ -var BaseUrlRule = /** @class */ (function () { + })(); + /** + * A base rule which calls `match` + * + * The value from the `match` function is passed through to the `handler`. + * @internalapi + */ + var BaseUrlRule = /** @class */ (function() { function BaseUrlRule(match, handler) { - var _this = this; - this.match = match; - this.type = 'RAW'; - this.matchPriority = function (match) { return 0 - _this.$id; }; - this.handler = handler || identity; + var _this = this; + this.match = match; + this.type = 'RAW'; + this.matchPriority = function(match) { + return 0 - _this.$id; + }; + this.handler = handler || identity; } return BaseUrlRule; -}()); + })(); -/** - * @internalapi - * @module url - */ -/** for typedoc */ -/** @hidden */ -function appendBasePath(url, isHtml5, absolute, baseHref) { - if (baseHref === '/') - return url; - if (isHtml5) - return stripLastPathElement(baseHref) + url; - if (absolute) - return baseHref.slice(1) + url; + /** + * @internalapi + * @module url + */ + /** @hidden */ + function appendBasePath(url, isHtml5, absolute, baseHref) { + if (baseHref === '/') return url; + if (isHtml5) return stripLastPathElement(baseHref) + url; + if (absolute) return baseHref.slice(1) + url; return url; -} -/** @hidden */ -var prioritySort = function (a, b) { + } + /** @hidden */ + var prioritySort = function(a, b) { return (b.priority || 0) - (a.priority || 0); -}; -/** @hidden */ -var typeSort = function (a, b) { - var weights = { 'STATE': 4, 'URLMATCHER': 4, 'REGEXP': 3, 'RAW': 2, 'OTHER': 1 }; + }; + /** @hidden */ + var typeSort = function(a, b) { + var weights = { STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1 }; return (weights[a.type] || 0) - (weights[b.type] || 0); -}; -/** @hidden */ -var urlMatcherSort = function (a, b) { + }; + /** @hidden */ + var urlMatcherSort = function(a, b) { return !a.urlMatcher || !b.urlMatcher ? 0 : UrlMatcher.compare(a.urlMatcher, b.urlMatcher); -}; -/** @hidden */ -var idSort = function (a, b) { + }; + /** @hidden */ + var idSort = function(a, b) { // Identically sorted STATE and URLMATCHER best rule will be chosen by `matchPriority` after each rule matches the URL var useMatchPriority = { STATE: true, URLMATCHER: true }; var equal = useMatchPriority[a.type] && useMatchPriority[b.type]; return equal ? 0 : (a.$id || 0) - (b.$id || 0); -}; -/** - * Default rule priority sorting function. - * - * Sorts rules by: - * - * - Explicit priority (set rule priority using [[UrlRulesApi.when]]) - * - Rule type (STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1) - * - `UrlMatcher` specificity ([[UrlMatcher.compare]]): works for STATE and URLMATCHER types to pick the most specific rule. - * - Rule registration order (for rule types other than STATE and URLMATCHER) - * - Equally sorted State and UrlMatcher rules will each match the URL. - * Then, the *best* match is chosen based on how many parameter values were matched. - * - * @coreapi - */ -var defaultRuleSortFn; -defaultRuleSortFn = function (a, b) { + }; + /** + * Default rule priority sorting function. + * + * Sorts rules by: + * + * - Explicit priority (set rule priority using [[UrlRulesApi.when]]) + * - Rule type (STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1) + * - `UrlMatcher` specificity ([[UrlMatcher.compare]]): works for STATE and URLMATCHER types to pick the most specific rule. + * - Rule registration order (for rule types other than STATE and URLMATCHER) + * - Equally sorted State and UrlMatcher rules will each match the URL. + * Then, the *best* match is chosen based on how many parameter values were matched. + * + * @coreapi + */ + var defaultRuleSortFn; + defaultRuleSortFn = function(a, b) { var cmp = prioritySort(a, b); - if (cmp !== 0) - return cmp; + if (cmp !== 0) return cmp; cmp = typeSort(a, b); - if (cmp !== 0) - return cmp; + if (cmp !== 0) return cmp; cmp = urlMatcherSort(a, b); - if (cmp !== 0) - return cmp; + if (cmp !== 0) return cmp; return idSort(a, b); -}; -/** - * Updates URL and responds to URL changes - * - * ### Deprecation warning: - * This class is now considered to be an internal API - * Use the [[UrlService]] instead. - * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]]. - * - * This class updates the URL when the state changes. - * It also responds to changes in the URL. - */ -var UrlRouter = /** @class */ (function () { + }; + /** + * Updates URL and responds to URL changes + * + * ### Deprecation warning: + * This class is now considered to be an internal API + * Use the [[UrlService]] instead. + * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]]. + * + * This class updates the URL when the state changes. + * It also responds to changes in the URL. + */ + var UrlRouter = /** @class */ (function() { /** @hidden */ function UrlRouter(router) { - /** @hidden */ this._sortFn = defaultRuleSortFn; - /** @hidden */ this._rules = []; - /** @hidden */ this.interceptDeferred = false; - /** @hidden */ this._id = 0; - /** @hidden */ this._sorted = false; - this._router = router; - this.urlRuleFactory = new UrlRuleFactory(router); - createProxyFunctions(val(UrlRouter.prototype), this, val(this)); + /** @hidden */ this._sortFn = defaultRuleSortFn; + /** @hidden */ this._rules = []; + /** @hidden */ this.interceptDeferred = false; + /** @hidden */ this._id = 0; + /** @hidden */ this._sorted = false; + this._router = router; + this.urlRuleFactory = new UrlRuleFactory(router); + createProxyFunctions(val(UrlRouter.prototype), this, val(this)); } /** @internalapi */ - UrlRouter.prototype.dispose = function () { - this.listen(false); - this._rules = []; - delete this._otherwiseFn; + UrlRouter.prototype.dispose = function() { + this.listen(false); + this._rules = []; + delete this._otherwiseFn; }; /** @inheritdoc */ - UrlRouter.prototype.sort = function (compareFn) { - this._rules = this.stableSort(this._rules, this._sortFn = compareFn || this._sortFn); - this._sorted = true; + UrlRouter.prototype.sort = function(compareFn) { + this._rules = this.stableSort(this._rules, (this._sortFn = compareFn || this._sortFn)); + this._sorted = true; }; - UrlRouter.prototype.ensureSorted = function () { - this._sorted || this.sort(); + UrlRouter.prototype.ensureSorted = function() { + this._sorted || this.sort(); }; - UrlRouter.prototype.stableSort = function (arr, compareFn) { - var arrOfWrapper = arr.map(function (elem, idx) { return ({ elem: elem, idx: idx }); }); - arrOfWrapper.sort(function (wrapperA, wrapperB) { - var cmpDiff = compareFn(wrapperA.elem, wrapperB.elem); - return cmpDiff === 0 - ? wrapperA.idx - wrapperB.idx - : cmpDiff; - }); - return arrOfWrapper.map(function (wrapper) { return wrapper.elem; }); + UrlRouter.prototype.stableSort = function(arr, compareFn) { + var arrOfWrapper = arr.map(function(elem, idx) { + return { elem: elem, idx: idx }; + }); + arrOfWrapper.sort(function(wrapperA, wrapperB) { + var cmpDiff = compareFn(wrapperA.elem, wrapperB.elem); + return cmpDiff === 0 ? wrapperA.idx - wrapperB.idx : cmpDiff; + }); + return arrOfWrapper.map(function(wrapper) { + return wrapper.elem; + }); }; /** * Given a URL, check all rules and return the best [[MatchResult]] * @param url * @returns {MatchResult} */ - UrlRouter.prototype.match = function (url) { - var _this = this; - this.ensureSorted(); - url = extend({ path: '', search: {}, hash: '' }, url); - var rules = this.rules(); - if (this._otherwiseFn) - rules.push(this._otherwiseFn); - // Checks a single rule. Returns { rule: rule, match: match, weight: weight } if it matched, or undefined - var checkRule = function (rule) { - var match = rule.match(url, _this._router); - return match && { match: match, rule: rule, weight: rule.matchPriority(match) }; - }; - // The rules are pre-sorted. - // - Find the first matching rule. - // - Find any other matching rule that sorted *exactly the same*, according to `.sort()`. - // - Choose the rule with the highest match weight. - var best; - for (var i = 0; i < rules.length; i++) { - // Stop when there is a 'best' rule and the next rule sorts differently than it. - if (best && this._sortFn(rules[i], best.rule) !== 0) - break; - var current = checkRule(rules[i]); - // Pick the best MatchResult - best = (!best || current && current.weight > best.weight) ? current : best; - } - return best; + UrlRouter.prototype.match = function(url) { + var _this = this; + this.ensureSorted(); + url = extend({ path: '', search: {}, hash: '' }, url); + var rules = this.rules(); + if (this._otherwiseFn) rules.push(this._otherwiseFn); + // Checks a single rule. Returns { rule: rule, match: match, weight: weight } if it matched, or undefined + var checkRule = function(rule) { + var match = rule.match(url, _this._router); + return match && { match: match, rule: rule, weight: rule.matchPriority(match) }; + }; + // The rules are pre-sorted. + // - Find the first matching rule. + // - Find any other matching rule that sorted *exactly the same*, according to `.sort()`. + // - Choose the rule with the highest match weight. + var best; + for (var i = 0; i < rules.length; i++) { + // Stop when there is a 'best' rule and the next rule sorts differently than it. + if (best && this._sortFn(rules[i], best.rule) !== 0) break; + var current = checkRule(rules[i]); + // Pick the best MatchResult + best = !best || (current && current.weight > best.weight) ? current : best; + } + return best; }; /** @inheritdoc */ - UrlRouter.prototype.sync = function (evt) { - if (evt && evt.defaultPrevented) - return; - var router = this._router, $url = router.urlService, $state = router.stateService; - var url = { - path: $url.path(), search: $url.search(), hash: $url.hash(), - }; - var best = this.match(url); - var applyResult = pattern([ - [isString, function (newurl) { return $url.url(newurl, true); }], - [TargetState.isDef, function (def) { return $state.go(def.state, def.params, def.options); }], - [is(TargetState), function (target) { return $state.go(target.state(), target.params(), target.options()); }], - ]); - applyResult(best && best.rule.handler(best.match, url, router)); + UrlRouter.prototype.sync = function(evt) { + if (evt && evt.defaultPrevented) return; + var router = this._router, + $url = router.urlService, + $state = router.stateService; + var url = { + path: $url.path(), + search: $url.search(), + hash: $url.hash(), + }; + var best = this.match(url); + var applyResult = pattern([ + [ + isString, + function(newurl) { + return $url.url(newurl, true); + }, + ], + [ + TargetState.isDef, + function(def) { + return $state.go(def.state, def.params, def.options); + }, + ], + [ + is(TargetState), + function(target) { + return $state.go(target.state(), target.params(), target.options()); + }, + ], + ]); + applyResult(best && best.rule.handler(best.match, url, router)); }; /** @inheritdoc */ - UrlRouter.prototype.listen = function (enabled) { - var _this = this; - if (enabled === false) { - this._stopFn && this._stopFn(); - delete this._stopFn; - } - else { - return this._stopFn = this._stopFn || this._router.urlService.onChange(function (evt) { return _this.sync(evt); }); - } + UrlRouter.prototype.listen = function(enabled) { + var _this = this; + if (enabled === false) { + this._stopFn && this._stopFn(); + delete this._stopFn; + } else { + return (this._stopFn = + this._stopFn || + this._router.urlService.onChange(function(evt) { + return _this.sync(evt); + })); + } }; /** * Internal API. * @internalapi */ - UrlRouter.prototype.update = function (read) { - var $url = this._router.locationService; - if (read) { - this.location = $url.url(); - return; - } - if ($url.url() === this.location) - return; - $url.url(this.location, true); + UrlRouter.prototype.update = function(read) { + var $url = this._router.locationService; + if (read) { + this.location = $url.url(); + return; + } + if ($url.url() === this.location) return; + $url.url(this.location, true); }; /** * Internal API. @@ -5470,9 +6120,9 @@ var UrlRouter = /** @class */ (function () { * @param params * @param options */ - UrlRouter.prototype.push = function (urlMatcher, params, options) { - var replace = options && !!options.replace; - this._router.urlService.url(urlMatcher.format(params || {}), replace); + UrlRouter.prototype.push = function(urlMatcher, params, options) { + var replace = options && !!options.replace; + this._router.urlService.url(urlMatcher.format(params || {}), replace); }; /** * Builds and returns a URL with interpolated parameters @@ -5493,24 +6143,23 @@ var UrlRouter = /** @class */ (function () { * * @returns Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher` */ - UrlRouter.prototype.href = function (urlMatcher, params, options) { - var url = urlMatcher.format(params); - if (url == null) - return null; - options = options || { absolute: false }; - var cfg = this._router.urlService.config; - var isHtml5 = cfg.html5Mode(); - if (!isHtml5 && url !== null) { - url = '#' + cfg.hashPrefix() + url; - } - url = appendBasePath(url, isHtml5, options.absolute, cfg.baseHref()); - if (!options.absolute || !url) { - return url; - } - var slash = (!isHtml5 && url ? '/' : ''); - var cfgPort = cfg.port(); - var port = (cfgPort === 80 || cfgPort === 443 ? '' : ':' + cfgPort); - return [cfg.protocol(), '://', cfg.host(), port, slash, url].join(''); + UrlRouter.prototype.href = function(urlMatcher, params, options) { + var url = urlMatcher.format(params); + if (url == null) return null; + options = options || { absolute: false }; + var cfg = this._router.urlService.config; + var isHtml5 = cfg.html5Mode(); + if (!isHtml5 && url !== null) { + url = '#' + cfg.hashPrefix() + url; + } + url = appendBasePath(url, isHtml5, options.absolute, cfg.baseHref()); + if (!options.absolute || !url) { + return url; + } + var slash = !isHtml5 && url ? '/' : ''; + var cfgPort = cfg.port(); + var port = cfgPort === 80 || cfgPort === 443 ? '' : ':' + cfgPort; + return [cfg.protocol(), '://', cfg.host(), port, slash, url].join(''); }; /** * Manually adds a URL Rule. @@ -5524,99 +6173,103 @@ var UrlRouter = /** @class */ (function () { * * @return a function that deregisters the rule */ - UrlRouter.prototype.rule = function (rule) { - var _this = this; - if (!UrlRuleFactory.isUrlRule(rule)) - throw new Error('invalid rule'); - rule.$id = this._id++; - rule.priority = rule.priority || 0; - this._rules.push(rule); - this._sorted = false; - return function () { return _this.removeRule(rule); }; + UrlRouter.prototype.rule = function(rule) { + var _this = this; + if (!UrlRuleFactory.isUrlRule(rule)) throw new Error('invalid rule'); + rule.$id = this._id++; + rule.priority = rule.priority || 0; + this._rules.push(rule); + this._sorted = false; + return function() { + return _this.removeRule(rule); + }; }; /** @inheritdoc */ - UrlRouter.prototype.removeRule = function (rule) { - removeFrom(this._rules, rule); + UrlRouter.prototype.removeRule = function(rule) { + removeFrom(this._rules, rule); }; /** @inheritdoc */ - UrlRouter.prototype.rules = function () { - this.ensureSorted(); - return this._rules.slice(); + UrlRouter.prototype.rules = function() { + this.ensureSorted(); + return this._rules.slice(); }; /** @inheritdoc */ - UrlRouter.prototype.otherwise = function (handler) { - var handlerFn = getHandlerFn(handler); - this._otherwiseFn = this.urlRuleFactory.create(val(true), handlerFn); - this._sorted = false; + UrlRouter.prototype.otherwise = function(handler) { + var handlerFn = getHandlerFn(handler); + this._otherwiseFn = this.urlRuleFactory.create(val(true), handlerFn); + this._sorted = false; }; /** @inheritdoc */ - UrlRouter.prototype.initial = function (handler) { - var handlerFn = getHandlerFn(handler); - var matchFn = function (urlParts, router) { - return router.globals.transitionHistory.size() === 0 && !!/^\/?$/.exec(urlParts.path); - }; - this.rule(this.urlRuleFactory.create(matchFn, handlerFn)); + UrlRouter.prototype.initial = function(handler) { + var handlerFn = getHandlerFn(handler); + var matchFn = function(urlParts, router) { + return router.globals.transitionHistory.size() === 0 && !!/^\/?$/.exec(urlParts.path); + }; + this.rule(this.urlRuleFactory.create(matchFn, handlerFn)); }; /** @inheritdoc */ - UrlRouter.prototype.when = function (matcher, handler, options) { - var rule = this.urlRuleFactory.create(matcher, handler); - if (isDefined(options && options.priority)) - rule.priority = options.priority; - this.rule(rule); - return rule; + UrlRouter.prototype.when = function(matcher, handler, options) { + var rule = this.urlRuleFactory.create(matcher, handler); + if (isDefined(options && options.priority)) rule.priority = options.priority; + this.rule(rule); + return rule; }; /** @inheritdoc */ - UrlRouter.prototype.deferIntercept = function (defer) { - if (defer === undefined) - defer = true; - this.interceptDeferred = defer; + UrlRouter.prototype.deferIntercept = function(defer) { + if (defer === undefined) defer = true; + this.interceptDeferred = defer; }; return UrlRouter; -}()); -function getHandlerFn(handler) { + })(); + function getHandlerFn(handler) { if (!isFunction(handler) && !isString(handler) && !is(TargetState)(handler) && !TargetState.isDef(handler)) { - throw new Error("'handler' must be a string, function, TargetState, or have a state: 'newtarget' property"); + throw new Error("'handler' must be a string, function, TargetState, or have a state: 'newtarget' property"); } return isFunction(handler) ? handler : val(handler); -} + } /** for typedoc */ -/** - * @coreapi - * @module view - */ /** for typedoc */ -/** - * The View service - * - * This service pairs existing `ui-view` components (which live in the DOM) - * with view configs (from the state declaration objects: [[StateDeclaration.views]]). - * - * - After a successful Transition, the views from the newly entered states are activated via [[activateViewConfig]]. - * The views from exited states are deactivated via [[deactivateViewConfig]]. - * (See: the [[registerActivateViews]] Transition Hook) - * - * - As `ui-view` components pop in and out of existence, they register themselves using [[registerUIView]]. - * - * - When the [[sync]] function is called, the registered `ui-view`(s) ([[ActiveUIView]]) - * are configured with the matching [[ViewConfig]](s) - * - */ -var ViewService = /** @class */ (function () { + /** + * @coreapi + * @module view + */ /** + * The View service + * + * This service pairs existing `ui-view` components (which live in the DOM) + * with view configs (from the state declaration objects: [[StateDeclaration.views]]). + * + * - After a successful Transition, the views from the newly entered states are activated via [[activateViewConfig]]. + * The views from exited states are deactivated via [[deactivateViewConfig]]. + * (See: the [[registerActivateViews]] Transition Hook) + * + * - As `ui-view` components pop in and out of existence, they register themselves using [[registerUIView]]. + * + * - When the [[sync]] function is called, the registered `ui-view`(s) ([[ActiveUIView]]) + * are configured with the matching [[ViewConfig]](s) + * + */ + var ViewService = /** @class */ (function() { function ViewService() { - var _this = this; - this._uiViews = []; - this._viewConfigs = []; - this._viewConfigFactories = {}; - this._listeners = []; - this._pluginapi = { - _rootViewContext: this._rootViewContext.bind(this), - _viewConfigFactory: this._viewConfigFactory.bind(this), - _registeredUIViews: function () { return _this._uiViews; }, - _activeViewConfigs: function () { return _this._viewConfigs; }, - _onSync: function (listener) { - _this._listeners.push(listener); - return function () { return removeFrom(_this._listeners, listener); }; - }, - }; + var _this = this; + this._uiViews = []; + this._viewConfigs = []; + this._viewConfigFactories = {}; + this._listeners = []; + this._pluginapi = { + _rootViewContext: this._rootViewContext.bind(this), + _viewConfigFactory: this._viewConfigFactory.bind(this), + _registeredUIViews: function() { + return _this._uiViews; + }, + _activeViewConfigs: function() { + return _this._viewConfigs; + }, + _onSync: function(listener) { + _this._listeners.push(listener); + return function() { + return removeFrom(_this._listeners, listener); + }; + }, + }; } /** * Normalizes a view's name from a state.views configuration block. @@ -5629,50 +6282,51 @@ var ViewService = /** @class */ (function () { * * @returns the normalized uiViewName and uiViewContextAnchor that the view targets */ - ViewService.normalizeUIViewTarget = function (context, rawViewName) { - if (rawViewName === void 0) { rawViewName = ''; } - // TODO: Validate incoming view name with a regexp to allow: - // ex: "view.name@foo.bar" , "^.^.view.name" , "view.name@^.^" , "" , - // "@" , "$default@^" , "!$default.$default" , "!foo.bar" - var viewAtContext = rawViewName.split('@'); - var uiViewName = viewAtContext[0] || '$default'; // default to unnamed view - var uiViewContextAnchor = isString(viewAtContext[1]) ? viewAtContext[1] : '^'; // default to parent context - // Handle relative view-name sugar syntax. - // Matches rawViewName "^.^.^.foo.bar" into array: ["^.^.^.foo.bar", "^.^.^", "foo.bar"], - var relativeViewNameSugar = /^(\^(?:\.\^)*)\.(.*$)/.exec(uiViewName); - if (relativeViewNameSugar) { - // Clobbers existing contextAnchor (rawViewName validation will fix this) - uiViewContextAnchor = relativeViewNameSugar[1]; // set anchor to "^.^.^" - uiViewName = relativeViewNameSugar[2]; // set view-name to "foo.bar" - } - if (uiViewName.charAt(0) === '!') { - uiViewName = uiViewName.substr(1); - uiViewContextAnchor = ''; // target absolutely from root - } - // handle parent relative targeting "^.^.^" - var relativeMatch = /^(\^(?:\.\^)*)$/; - if (relativeMatch.exec(uiViewContextAnchor)) { - var anchorState = uiViewContextAnchor.split('.') - .reduce((function (anchor, x) { return anchor.parent; }), context); - uiViewContextAnchor = anchorState.name; - } - else if (uiViewContextAnchor === '.') { - uiViewContextAnchor = context.name; - } - return { uiViewName: uiViewName, uiViewContextAnchor: uiViewContextAnchor }; + ViewService.normalizeUIViewTarget = function(context, rawViewName) { + if (rawViewName === void 0) { + rawViewName = ''; + } + // TODO: Validate incoming view name with a regexp to allow: + // ex: "view.name@foo.bar" , "^.^.view.name" , "view.name@^.^" , "" , + // "@" , "$default@^" , "!$default.$default" , "!foo.bar" + var viewAtContext = rawViewName.split('@'); + var uiViewName = viewAtContext[0] || '$default'; // default to unnamed view + var uiViewContextAnchor = isString(viewAtContext[1]) ? viewAtContext[1] : '^'; // default to parent context + // Handle relative view-name sugar syntax. + // Matches rawViewName "^.^.^.foo.bar" into array: ["^.^.^.foo.bar", "^.^.^", "foo.bar"], + var relativeViewNameSugar = /^(\^(?:\.\^)*)\.(.*$)/.exec(uiViewName); + if (relativeViewNameSugar) { + // Clobbers existing contextAnchor (rawViewName validation will fix this) + uiViewContextAnchor = relativeViewNameSugar[1]; // set anchor to "^.^.^" + uiViewName = relativeViewNameSugar[2]; // set view-name to "foo.bar" + } + if (uiViewName.charAt(0) === '!') { + uiViewName = uiViewName.substr(1); + uiViewContextAnchor = ''; // target absolutely from root + } + // handle parent relative targeting "^.^.^" + var relativeMatch = /^(\^(?:\.\^)*)$/; + if (relativeMatch.exec(uiViewContextAnchor)) { + var anchorState = uiViewContextAnchor.split('.').reduce(function(anchor, x) { + return anchor.parent; + }, context); + uiViewContextAnchor = anchorState.name; + } else if (uiViewContextAnchor === '.') { + uiViewContextAnchor = context.name; + } + return { uiViewName: uiViewName, uiViewContextAnchor: uiViewContextAnchor }; }; - ViewService.prototype._rootViewContext = function (context) { - return this._rootContext = context || this._rootContext; + ViewService.prototype._rootViewContext = function(context) { + return (this._rootContext = context || this._rootContext); }; - ViewService.prototype._viewConfigFactory = function (viewType, factory) { - this._viewConfigFactories[viewType] = factory; + ViewService.prototype._viewConfigFactory = function(viewType, factory) { + this._viewConfigFactories[viewType] = factory; }; - ViewService.prototype.createViewConfig = function (path, decl) { - var cfgFactory = this._viewConfigFactories[decl.$type]; - if (!cfgFactory) - throw new Error('ViewService: No view config factory registered for type ' + decl.$type); - var cfgs = cfgFactory(path, decl); - return isArray(cfgs) ? cfgs : [cfgs]; + ViewService.prototype.createViewConfig = function(path, decl) { + var cfgFactory = this._viewConfigFactories[decl.$type]; + if (!cfgFactory) throw new Error('ViewService: No view config factory registered for type ' + decl.$type); + var cfgs = cfgFactory(path, decl); + return isArray(cfgs) ? cfgs : [cfgs]; }; /** * Deactivates a ViewConfig. @@ -5682,61 +6336,74 @@ var ViewService = /** @class */ (function () { * * @param viewConfig The ViewConfig view to deregister. */ - ViewService.prototype.deactivateViewConfig = function (viewConfig) { - trace.traceViewServiceEvent('<- Removing', viewConfig); - removeFrom(this._viewConfigs, viewConfig); + ViewService.prototype.deactivateViewConfig = function(viewConfig) { + trace.traceViewServiceEvent('<- Removing', viewConfig); + removeFrom(this._viewConfigs, viewConfig); }; - ViewService.prototype.activateViewConfig = function (viewConfig) { - trace.traceViewServiceEvent('-> Registering', viewConfig); - this._viewConfigs.push(viewConfig); + ViewService.prototype.activateViewConfig = function(viewConfig) { + trace.traceViewServiceEvent('-> Registering', viewConfig); + this._viewConfigs.push(viewConfig); }; - ViewService.prototype.sync = function () { - var _this = this; - var uiViewsByFqn = this._uiViews.map(function (uiv) { return [uiv.fqn, uiv]; }).reduce(applyPairs, {}); - // Return a weighted depth value for a uiView. - // The depth is the nesting depth of ui-views (based on FQN; times 10,000) - // plus the depth of the state that is populating the uiView - function uiViewDepth(uiView) { - var stateDepth = function (context) { - return context && context.parent ? stateDepth(context.parent) + 1 : 1; - }; - return (uiView.fqn.split('.').length * 10000) + stateDepth(uiView.creationContext); - } - // Return the ViewConfig's context's depth in the context tree. - function viewConfigDepth(config) { - var context = config.viewDecl.$context, count = 0; - while (++count && context.parent) - context = context.parent; - return count; - } - // Given a depth function, returns a compare function which can return either ascending or descending order - var depthCompare = curry(function (depthFn, posNeg, left, right) { return posNeg * (depthFn(left) - depthFn(right)); }); - var matchingConfigPair = function (uiView) { - var matchingConfigs = _this._viewConfigs.filter(ViewService.matches(uiViewsByFqn, uiView)); - if (matchingConfigs.length > 1) { - // This is OK. Child states can target a ui-view that the parent state also targets (the child wins) - // Sort by depth and return the match from the deepest child - // console.log(`Multiple matching view configs for ${uiView.fqn}`, matchingConfigs); - matchingConfigs.sort(depthCompare(viewConfigDepth, -1)); // descending - } - return { uiView: uiView, viewConfig: matchingConfigs[0] }; + ViewService.prototype.sync = function() { + var _this = this; + var uiViewsByFqn = this._uiViews + .map(function(uiv) { + return [uiv.fqn, uiv]; + }) + .reduce(applyPairs, {}); + // Return a weighted depth value for a uiView. + // The depth is the nesting depth of ui-views (based on FQN; times 10,000) + // plus the depth of the state that is populating the uiView + function uiViewDepth(uiView) { + var stateDepth = function(context) { + return context && context.parent ? stateDepth(context.parent) + 1 : 1; }; - var configureUIView = function (tuple) { - // If a parent ui-view is reconfigured, it could destroy child ui-views. - // Before configuring a child ui-view, make sure it's still in the active uiViews array. - if (_this._uiViews.indexOf(tuple.uiView) !== -1) - tuple.uiView.configUpdated(tuple.viewConfig); - }; - // Sort views by FQN and state depth. Process uiviews nearest the root first. - var uiViewTuples = this._uiViews.sort(depthCompare(uiViewDepth, 1)).map(matchingConfigPair); - var matchedViewConfigs = uiViewTuples.map(function (tuple) { return tuple.viewConfig; }); - var unmatchedConfigTuples = this._viewConfigs - .filter(function (config) { return !inArray(matchedViewConfigs, config); }) - .map(function (viewConfig) { return ({ uiView: undefined, viewConfig: viewConfig }); }); - uiViewTuples.forEach(configureUIView); - var allTuples = uiViewTuples.concat(unmatchedConfigTuples); - this._listeners.forEach(function (cb) { return cb(allTuples); }); - trace.traceViewSync(allTuples); + return uiView.fqn.split('.').length * 10000 + stateDepth(uiView.creationContext); + } + // Return the ViewConfig's context's depth in the context tree. + function viewConfigDepth(config) { + var context = config.viewDecl.$context, + count = 0; + while (++count && context.parent) context = context.parent; + return count; + } + // Given a depth function, returns a compare function which can return either ascending or descending order + var depthCompare = curry(function(depthFn, posNeg, left, right) { + return posNeg * (depthFn(left) - depthFn(right)); + }); + var matchingConfigPair = function(uiView) { + var matchingConfigs = _this._viewConfigs.filter(ViewService.matches(uiViewsByFqn, uiView)); + if (matchingConfigs.length > 1) { + // This is OK. Child states can target a ui-view that the parent state also targets (the child wins) + // Sort by depth and return the match from the deepest child + // console.log(`Multiple matching view configs for ${uiView.fqn}`, matchingConfigs); + matchingConfigs.sort(depthCompare(viewConfigDepth, -1)); // descending + } + return { uiView: uiView, viewConfig: matchingConfigs[0] }; + }; + var configureUIView = function(tuple) { + // If a parent ui-view is reconfigured, it could destroy child ui-views. + // Before configuring a child ui-view, make sure it's still in the active uiViews array. + if (_this._uiViews.indexOf(tuple.uiView) !== -1) tuple.uiView.configUpdated(tuple.viewConfig); + }; + // Sort views by FQN and state depth. Process uiviews nearest the root first. + var uiViewTuples = this._uiViews.sort(depthCompare(uiViewDepth, 1)).map(matchingConfigPair); + var matchedViewConfigs = uiViewTuples.map(function(tuple) { + return tuple.viewConfig; + }); + var unmatchedConfigTuples = this._viewConfigs + .filter(function(config) { + return !inArray(matchedViewConfigs, config); + }) + .map(function(viewConfig) { + return { uiView: undefined, viewConfig: viewConfig }; + }); + uiViewTuples.forEach(configureUIView); + var allTuples = uiViewTuples.concat(unmatchedConfigTuples); + this._listeners.forEach(function(cb) { + return cb(allTuples); + }); + trace.traceViewSync(allTuples); }; /** * Registers a `ui-view` component @@ -5753,39 +6420,41 @@ var ViewService = /** @class */ (function () { * @param uiView The metadata for a UIView * @return a de-registration function used when the view is destroyed. */ - ViewService.prototype.registerUIView = function (uiView) { - trace.traceViewServiceUIViewEvent('-> Registering', uiView); - var uiViews = this._uiViews; - var fqnAndTypeMatches = function (uiv) { return uiv.fqn === uiView.fqn && uiv.$type === uiView.$type; }; - if (uiViews.filter(fqnAndTypeMatches).length) - trace.traceViewServiceUIViewEvent('!!!! duplicate uiView named:', uiView); - uiViews.push(uiView); - this.sync(); - return function () { - var idx = uiViews.indexOf(uiView); - if (idx === -1) { - trace.traceViewServiceUIViewEvent('Tried removing non-registered uiView', uiView); - return; - } - trace.traceViewServiceUIViewEvent('<- Deregistering', uiView); - removeFrom(uiViews)(uiView); - }; + ViewService.prototype.registerUIView = function(uiView) { + trace.traceViewServiceUIViewEvent('-> Registering', uiView); + var uiViews = this._uiViews; + var fqnAndTypeMatches = function(uiv) { + return uiv.fqn === uiView.fqn && uiv.$type === uiView.$type; + }; + if (uiViews.filter(fqnAndTypeMatches).length) + trace.traceViewServiceUIViewEvent('!!!! duplicate uiView named:', uiView); + uiViews.push(uiView); + this.sync(); + return function() { + var idx = uiViews.indexOf(uiView); + if (idx === -1) { + trace.traceViewServiceUIViewEvent('Tried removing non-registered uiView', uiView); + return; + } + trace.traceViewServiceUIViewEvent('<- Deregistering', uiView); + removeFrom(uiViews)(uiView); + }; }; /** * Returns the list of views currently available on the page, by fully-qualified name. * * @return {Array} Returns an array of fully-qualified view names. */ - ViewService.prototype.available = function () { - return this._uiViews.map(prop('fqn')); + ViewService.prototype.available = function() { + return this._uiViews.map(prop('fqn')); }; /** * Returns the list of views on the page containing loaded content. * * @return {Array} Returns an array of fully-qualified view names. */ - ViewService.prototype.active = function () { - return this._uiViews.filter(prop('$config')).map(prop('name')); + ViewService.prototype.active = function() { + return this._uiViews.filter(prop('$config')).map(prop('name')); }; /** * Given a ui-view and a ViewConfig, determines if they "match". @@ -5844,106 +6513,132 @@ var ViewService = /** @class */ (function () { * * @internalapi */ - ViewService.matches = function (uiViewsByFqn, uiView) { return function (viewConfig) { + ViewService.matches = function(uiViewsByFqn, uiView) { + return function(viewConfig) { // Don't supply an ng1 ui-view with an ng2 ViewConfig, etc - if (uiView.$type !== viewConfig.viewDecl.$type) - return false; + if (uiView.$type !== viewConfig.viewDecl.$type) return false; // Split names apart from both viewConfig and uiView into segments var vc = viewConfig.viewDecl; var vcSegments = vc.$uiViewName.split('.'); var uivSegments = uiView.fqn.split('.'); // Check if the tails of the segment arrays match. ex, these arrays' tails match: // vc: ["foo", "bar"], uiv fqn: ["$default", "foo", "bar"] - if (!equals(vcSegments, uivSegments.slice(0 - vcSegments.length))) - return false; + if (!equals(vcSegments, uivSegments.slice(0 - vcSegments.length))) return false; // Now check if the fqn ending at the first segment of the viewConfig matches the context: // ["$default", "foo"].join(".") == "$default.foo", does the ui-view $default.foo context match? - var negOffset = (1 - vcSegments.length) || undefined; + var negOffset = 1 - vcSegments.length || undefined; var fqnToFirstSegment = uivSegments.slice(0, negOffset).join('.'); var uiViewContext = uiViewsByFqn[fqnToFirstSegment].creationContext; return vc.$uiViewContextAnchor === (uiViewContext && uiViewContext.name); - }; }; + }; + }; return ViewService; -}()); + })(); /** */ -/** - * @coreapi - * @module core - */ /** */ -/** - * Global router state - * - * This is where we hold the global mutable state such as current state, current - * params, current transition, etc. - */ -var UIRouterGlobals = /** @class */ (function () { + /** + * @coreapi + * @module core + */ /** + * Global router state + * + * This is where we hold the global mutable state such as current state, current + * params, current transition, etc. + */ + var UIRouterGlobals = /** @class */ (function() { function UIRouterGlobals() { - /** - * Current parameter values - * - * The parameter values from the latest successful transition - */ - this.params = new StateParams(); - /** @internalapi */ - this.lastStartedTransitionId = -1; - /** @internalapi */ - this.transitionHistory = new Queue([], 1); - /** @internalapi */ - this.successfulTransitions = new Queue([], 1); + /** + * Current parameter values + * + * The parameter values from the latest successful transition + */ + this.params = new StateParams(); + /** @internalapi */ + this.lastStartedTransitionId = -1; + /** @internalapi */ + this.transitionHistory = new Queue([], 1); + /** @internalapi */ + this.successfulTransitions = new Queue([], 1); } - UIRouterGlobals.prototype.dispose = function () { - this.transitionHistory.clear(); - this.successfulTransitions.clear(); - this.transition = null; + UIRouterGlobals.prototype.dispose = function() { + this.transitionHistory.clear(); + this.successfulTransitions.clear(); + this.transition = null; }; return UIRouterGlobals; -}()); + })(); /** */ -/** - * @coreapi - * @module url - */ /** */ -/** @hidden */ -var makeStub = function (keys) { - return keys.reduce(function (acc, key) { return (acc[key] = notImplemented(key), acc); }, { dispose: noop }); -}; -/* tslint:disable:align */ -/** @hidden */ var locationServicesFns = ['url', 'path', 'search', 'hash', 'onChange']; -/** @hidden */ var locationConfigFns = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix']; -/** @hidden */ var umfFns = ['type', 'caseInsensitive', 'strictMode', 'defaultSquashPolicy']; -/** @hidden */ var rulesFns = ['sort', 'when', 'initial', 'otherwise', 'rules', 'rule', 'removeRule']; -/** @hidden */ var syncFns = ['deferIntercept', 'listen', 'sync', 'match']; -/* tslint:enable:align */ -/** - * API for URL management - */ -var UrlService = /** @class */ (function () { + /** + * @coreapi + * @module url + */ /** @hidden */ + var makeStub = function(keys) { + return keys.reduce( + function(acc, key) { + return (acc[key] = notImplemented(key)), acc; + }, + { dispose: noop }, + ); + }; + /** @hidden */ + var locationServicesFns = ['url', 'path', 'search', 'hash', 'onChange']; + /** @hidden */ + var locationConfigFns = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix']; + /** @hidden */ + var umfFns = ['type', 'caseInsensitive', 'strictMode', 'defaultSquashPolicy']; + /** @hidden */ + var rulesFns = ['sort', 'when', 'initial', 'otherwise', 'rules', 'rule', 'removeRule']; + /** @hidden */ + var syncFns = ['deferIntercept', 'listen', 'sync', 'match']; + /** + * API for URL management + */ + var UrlService = /** @class */ (function() { /** @hidden */ function UrlService(router, lateBind) { - if (lateBind === void 0) { lateBind = true; } - this.router = router; - this.rules = {}; - this.config = {}; - // proxy function calls from UrlService to the LocationService/LocationConfig - var locationServices = function () { return router.locationService; }; - createProxyFunctions(locationServices, this, locationServices, locationServicesFns, lateBind); - var locationConfig = function () { return router.locationConfig; }; - createProxyFunctions(locationConfig, this.config, locationConfig, locationConfigFns, lateBind); - var umf = function () { return router.urlMatcherFactory; }; - createProxyFunctions(umf, this.config, umf, umfFns); - var urlRouter = function () { return router.urlRouter; }; - createProxyFunctions(urlRouter, this.rules, urlRouter, rulesFns); - createProxyFunctions(urlRouter, this, urlRouter, syncFns); + if (lateBind === void 0) { + lateBind = true; + } + this.router = router; + this.rules = {}; + this.config = {}; + // proxy function calls from UrlService to the LocationService/LocationConfig + var locationServices = function() { + return router.locationService; + }; + createProxyFunctions(locationServices, this, locationServices, locationServicesFns, lateBind); + var locationConfig = function() { + return router.locationConfig; + }; + createProxyFunctions(locationConfig, this.config, locationConfig, locationConfigFns, lateBind); + var umf = function() { + return router.urlMatcherFactory; + }; + createProxyFunctions(umf, this.config, umf, umfFns); + var urlRouter = function() { + return router.urlRouter; + }; + createProxyFunctions(urlRouter, this.rules, urlRouter, rulesFns); + createProxyFunctions(urlRouter, this, urlRouter, syncFns); } - UrlService.prototype.url = function (newurl, replace, state) { return; }; + UrlService.prototype.url = function(newurl, replace, state) { + return; + }; /** @inheritdoc */ - UrlService.prototype.path = function () { return; }; + UrlService.prototype.path = function() { + return; + }; /** @inheritdoc */ - UrlService.prototype.search = function () { return; }; + UrlService.prototype.search = function() { + return; + }; /** @inheritdoc */ - UrlService.prototype.hash = function () { return; }; + UrlService.prototype.hash = function() { + return; + }; /** @inheritdoc */ - UrlService.prototype.onChange = function (callback) { return; }; + UrlService.prototype.onChange = function(callback) { + return; + }; /** * Returns the current URL parts * @@ -5951,47 +6646,54 @@ var UrlService = /** @class */ (function () { * * @returns the current url parts */ - UrlService.prototype.parts = function () { - return { path: this.path(), search: this.search(), hash: this.hash() }; + UrlService.prototype.parts = function() { + return { path: this.path(), search: this.search(), hash: this.hash() }; }; - UrlService.prototype.dispose = function () { }; + UrlService.prototype.dispose = function() {}; /** @inheritdoc */ - UrlService.prototype.sync = function (evt) { return; }; + UrlService.prototype.sync = function(evt) { + return; + }; /** @inheritdoc */ - UrlService.prototype.listen = function (enabled) { return; }; + UrlService.prototype.listen = function(enabled) { + return; + }; /** @inheritdoc */ - UrlService.prototype.deferIntercept = function (defer) { return; }; + UrlService.prototype.deferIntercept = function(defer) { + return; + }; /** @inheritdoc */ - UrlService.prototype.match = function (urlParts) { return; }; + UrlService.prototype.match = function(urlParts) { + return; + }; /** @hidden */ UrlService.locationServiceStub = makeStub(locationServicesFns); /** @hidden */ UrlService.locationConfigStub = makeStub(locationConfigFns); return UrlService; -}()); + })(); /** */ -/** - * @coreapi - * @module core - */ /** */ -/** @hidden */ -var _routerInstance = 0; -/** - * The master class used to instantiate an instance of UI-Router. - * - * UI-Router (for each specific framework) will create an instance of this class during bootstrap. - * This class instantiates and wires the UI-Router services together. - * - * After a new instance of the UIRouter class is created, it should be configured for your app. - * For instance, app states should be registered with the [[UIRouter.stateRegistry]]. - * - * --- - * - * Normally the framework code will bootstrap UI-Router. - * If you are bootstrapping UIRouter manually, tell it to monitor the URL by calling - * [[UrlService.listen]] then [[UrlService.sync]]. - */ -var UIRouter = /** @class */ (function () { + /** + * @coreapi + * @module core + */ /** @hidden */ + var _routerInstance = 0; + /** + * The master class used to instantiate an instance of UI-Router. + * + * UI-Router (for each specific framework) will create an instance of this class during bootstrap. + * This class instantiates and wires the UI-Router services together. + * + * After a new instance of the UIRouter class is created, it should be configured for your app. + * For instance, app states should be registered with the [[UIRouter.stateRegistry]]. + * + * --- + * + * Normally the framework code will bootstrap UI-Router. + * If you are bootstrapping UIRouter manually, tell it to monitor the URL by calling + * [[UrlService.listen]] then [[UrlService.sync]]. + */ + var UIRouter = /** @class */ (function() { /** * Creates a new `UIRouter` object * @@ -6000,53 +6702,57 @@ var UIRouter = /** @class */ (function () { * @internalapi */ function UIRouter(locationService, locationConfig) { - if (locationService === void 0) { locationService = UrlService.locationServiceStub; } - if (locationConfig === void 0) { locationConfig = UrlService.locationConfigStub; } - this.locationService = locationService; - this.locationConfig = locationConfig; - /** @hidden */ this.$id = _routerInstance++; - /** @hidden */ this._disposed = false; - /** @hidden */ this._disposables = []; - /** Provides trace information to the console */ - this.trace = trace; - /** Provides services related to ui-view synchronization */ - this.viewService = new ViewService(); - /** Global router state */ - this.globals = new UIRouterGlobals(); - /** Provides services related to Transitions */ - this.transitionService = new TransitionService(this); - /** - * Deprecated for public use. Use [[urlService]] instead. - * @deprecated Use [[urlService]] instead - */ - this.urlMatcherFactory = new UrlMatcherFactory(); - /** - * Deprecated for public use. Use [[urlService]] instead. - * @deprecated Use [[urlService]] instead - */ - this.urlRouter = new UrlRouter(this); - /** Provides a registry for states, and related registration services */ - this.stateRegistry = new StateRegistry(this); - /** Provides services related to states */ - this.stateService = new StateService(this); - /** Provides services related to the URL */ - this.urlService = new UrlService(this); - /** @hidden plugin instances are registered here */ - this._plugins = {}; - this.viewService._pluginapi._rootViewContext(this.stateRegistry.root()); - this.globals.$current = this.stateRegistry.root(); - this.globals.current = this.globals.$current.self; - this.disposable(this.globals); - this.disposable(this.stateService); - this.disposable(this.stateRegistry); - this.disposable(this.transitionService); - this.disposable(this.urlRouter); - this.disposable(locationService); - this.disposable(locationConfig); + if (locationService === void 0) { + locationService = UrlService.locationServiceStub; + } + if (locationConfig === void 0) { + locationConfig = UrlService.locationConfigStub; + } + this.locationService = locationService; + this.locationConfig = locationConfig; + /** @hidden */ this.$id = _routerInstance++; + /** @hidden */ this._disposed = false; + /** @hidden */ this._disposables = []; + /** Provides trace information to the console */ + this.trace = trace; + /** Provides services related to ui-view synchronization */ + this.viewService = new ViewService(); + /** Global router state */ + this.globals = new UIRouterGlobals(); + /** Provides services related to Transitions */ + this.transitionService = new TransitionService(this); + /** + * Deprecated for public use. Use [[urlService]] instead. + * @deprecated Use [[urlService]] instead + */ + this.urlMatcherFactory = new UrlMatcherFactory(); + /** + * Deprecated for public use. Use [[urlService]] instead. + * @deprecated Use [[urlService]] instead + */ + this.urlRouter = new UrlRouter(this); + /** Provides a registry for states, and related registration services */ + this.stateRegistry = new StateRegistry(this); + /** Provides services related to states */ + this.stateService = new StateService(this); + /** Provides services related to the URL */ + this.urlService = new UrlService(this); + /** @hidden plugin instances are registered here */ + this._plugins = {}; + this.viewService._pluginapi._rootViewContext(this.stateRegistry.root()); + this.globals.$current = this.stateRegistry.root(); + this.globals.current = this.globals.$current.self; + this.disposable(this.globals); + this.disposable(this.stateService); + this.disposable(this.stateRegistry); + this.disposable(this.transitionService); + this.disposable(this.urlRouter); + this.disposable(locationService); + this.disposable(locationConfig); } /** Registers an object to be notified when the router is disposed */ - UIRouter.prototype.disposable = function (disposable) { - this._disposables.push(disposable); + UIRouter.prototype.disposable = function(disposable) { + this._disposables.push(disposable); }; /** * Disposes this router instance @@ -6058,20 +6764,19 @@ var UIRouter = /** @class */ (function () { * * @param disposable (optional) the disposable to dispose */ - UIRouter.prototype.dispose = function (disposable) { - var _this = this; - if (disposable && isFunction(disposable.dispose)) { - disposable.dispose(this); - return undefined; - } - this._disposed = true; - this._disposables.slice().forEach(function (d) { - try { - typeof d.dispose === 'function' && d.dispose(_this); - removeFrom(_this._disposables, d); - } - catch (ignored) { } - }); + UIRouter.prototype.dispose = function(disposable) { + var _this = this; + if (disposable && isFunction(disposable.dispose)) { + disposable.dispose(this); + return undefined; + } + this._disposed = true; + this._disposables.slice().forEach(function(d) { + try { + typeof d.dispose === 'function' && d.dispose(_this); + removeFrom(_this._disposables, d); + } catch (ignored) {} + }); }; /** * Adds a plugin to UI-Router @@ -6126,275 +6831,301 @@ var UIRouter = /** @class */ (function () { * @param options options to pass to the plugin class/factory * @returns the registered plugin instance */ - UIRouter.prototype.plugin = function (plugin, options) { - if (options === void 0) { options = {}; } - var pluginInstance = new plugin(this, options); - if (!pluginInstance.name) - throw new Error('Required property `name` missing on plugin: ' + pluginInstance); - this._disposables.push(pluginInstance); - return this._plugins[pluginInstance.name] = pluginInstance; + UIRouter.prototype.plugin = function(plugin, options) { + if (options === void 0) { + options = {}; + } + var pluginInstance = new plugin(this, options); + if (!pluginInstance.name) throw new Error('Required property `name` missing on plugin: ' + pluginInstance); + this._disposables.push(pluginInstance); + return (this._plugins[pluginInstance.name] = pluginInstance); }; - UIRouter.prototype.getPlugin = function (pluginName) { - return pluginName ? this._plugins[pluginName] : values(this._plugins); + UIRouter.prototype.getPlugin = function(pluginName) { + return pluginName ? this._plugins[pluginName] : values(this._plugins); }; return UIRouter; -}()); + })(); /** */ -/** @module hooks */ /** */ -function addCoreResolvables(trans) { + /** @module hooks */ function addCoreResolvables(trans) { trans.addResolvable(Resolvable.fromData(UIRouter, trans.router), ''); trans.addResolvable(Resolvable.fromData(Transition, trans), ''); trans.addResolvable(Resolvable.fromData('$transition$', trans), ''); trans.addResolvable(Resolvable.fromData('$stateParams', trans.params()), ''); - trans.entering().forEach(function (state) { - trans.addResolvable(Resolvable.fromData('$state$', state), state); + trans.entering().forEach(function(state) { + trans.addResolvable(Resolvable.fromData('$state$', state), state); }); -} -var registerAddCoreResolvables = function (transitionService) { + } + var registerAddCoreResolvables = function(transitionService) { return transitionService.onCreate({}, addCoreResolvables); -}; -var TRANSITION_TOKENS = ['$transition$', Transition]; -var isTransition = inArray(TRANSITION_TOKENS); -// References to Transition in the treeChanges pathnodes makes all -// previous Transitions reachable in memory, causing a memory leak -// This function removes resolves for '$transition$' and `Transition` from the treeChanges. -// Do not use this on current transitions, only on old ones. -var treeChangesCleanup = function (trans) { - var nodes = values(trans.treeChanges()).reduce(unnestR, []).reduce(uniqR, []); + }; + var TRANSITION_TOKENS = ['$transition$', Transition]; + var isTransition = inArray(TRANSITION_TOKENS); + // References to Transition in the treeChanges pathnodes makes all + // previous Transitions reachable in memory, causing a memory leak + // This function removes resolves for '$transition$' and `Transition` from the treeChanges. + // Do not use this on current transitions, only on old ones. + var treeChangesCleanup = function(trans) { + var nodes = values(trans.treeChanges()) + .reduce(unnestR, []) + .reduce(uniqR, []); // If the resolvable is a Transition, return a new resolvable with null data - var replaceTransitionWithNull = function (r) { - return isTransition(r.token) ? Resolvable.fromData(r.token, null) : r; + var replaceTransitionWithNull = function(r) { + return isTransition(r.token) ? Resolvable.fromData(r.token, null) : r; }; - nodes.forEach(function (node) { - node.resolvables = node.resolvables.map(replaceTransitionWithNull); + nodes.forEach(function(node) { + node.resolvables = node.resolvables.map(replaceTransitionWithNull); }); -}; + }; /** */ -/** @module hooks */ /** */ -/** - * A [[TransitionHookFn]] that redirects to a different state or params - * - * Registered using `transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectHook);` - * - * See [[StateDeclaration.redirectTo]] - */ -var redirectToHook = function (trans) { + /** @module hooks */ /** + * A [[TransitionHookFn]] that redirects to a different state or params + * + * Registered using `transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectHook);` + * + * See [[StateDeclaration.redirectTo]] + */ + var redirectToHook = function(trans) { var redirect = trans.to().redirectTo; - if (!redirect) - return; + if (!redirect) return; var $state = trans.router.stateService; function handleResult(result) { - if (!result) - return; - if (result instanceof TargetState) - return result; - if (isString(result)) - return $state.target(result, trans.params(), trans.options()); - if (result['state'] || result['params']) - return $state.target(result['state'] || trans.to(), result['params'] || trans.params(), trans.options()); + if (!result) return; + if (result instanceof TargetState) return result; + if (isString(result)) return $state.target(result, trans.params(), trans.options()); + if (result['state'] || result['params']) + return $state.target(result['state'] || trans.to(), result['params'] || trans.params(), trans.options()); } if (isFunction(redirect)) { - return services.$q.when(redirect(trans)).then(handleResult); + return services.$q.when(redirect(trans)).then(handleResult); } return handleResult(redirect); -}; -var registerRedirectToHook = function (transitionService) { - return transitionService.onStart({ to: function (state) { return !!state.redirectTo; } }, redirectToHook); -}; + }; + var registerRedirectToHook = function(transitionService) { + return transitionService.onStart( + { + to: function(state) { + return !!state.redirectTo; + }, + }, + redirectToHook, + ); + }; -/** - * A factory which creates an onEnter, onExit or onRetain transition hook function - * - * The returned function invokes the (for instance) state.onEnter hook when the - * state is being entered. - * - * @hidden - */ -function makeEnterExitRetainHook(hookName) { - return function (transition, state) { - var _state = state.$$state(); - var hookFn = _state[hookName]; - return hookFn(transition, state); + /** + * A factory which creates an onEnter, onExit or onRetain transition hook function + * + * The returned function invokes the (for instance) state.onEnter hook when the + * state is being entered. + * + * @hidden + */ + function makeEnterExitRetainHook(hookName) { + return function(transition, state) { + var _state = state.$$state(); + var hookFn = _state[hookName]; + return hookFn(transition, state); }; -} -/** - * The [[TransitionStateHookFn]] for onExit - * - * When the state is being exited, the state's .onExit function is invoked. - * - * Registered using `transitionService.onExit({ exiting: (state) => !!state.onExit }, onExitHook);` - * - * See: [[IHookRegistry.onExit]] - */ -var onExitHook = makeEnterExitRetainHook('onExit'); -var registerOnExitHook = function (transitionService) { - return transitionService.onExit({ exiting: function (state) { return !!state.onExit; } }, onExitHook); -}; -/** - * The [[TransitionStateHookFn]] for onRetain - * - * When the state was already entered, and is not being exited or re-entered, the state's .onRetain function is invoked. - * - * Registered using `transitionService.onRetain({ retained: (state) => !!state.onRetain }, onRetainHook);` - * - * See: [[IHookRegistry.onRetain]] - */ -var onRetainHook = makeEnterExitRetainHook('onRetain'); -var registerOnRetainHook = function (transitionService) { - return transitionService.onRetain({ retained: function (state) { return !!state.onRetain; } }, onRetainHook); -}; -/** - * The [[TransitionStateHookFn]] for onEnter - * - * When the state is being entered, the state's .onEnter function is invoked. - * - * Registered using `transitionService.onEnter({ entering: (state) => !!state.onEnter }, onEnterHook);` - * - * See: [[IHookRegistry.onEnter]] - */ -var onEnterHook = makeEnterExitRetainHook('onEnter'); -var registerOnEnterHook = function (transitionService) { - return transitionService.onEnter({ entering: function (state) { return !!state.onEnter; } }, onEnterHook); -}; + } + /** + * The [[TransitionStateHookFn]] for onExit + * + * When the state is being exited, the state's .onExit function is invoked. + * + * Registered using `transitionService.onExit({ exiting: (state) => !!state.onExit }, onExitHook);` + * + * See: [[IHookRegistry.onExit]] + */ + var onExitHook = makeEnterExitRetainHook('onExit'); + var registerOnExitHook = function(transitionService) { + return transitionService.onExit( + { + exiting: function(state) { + return !!state.onExit; + }, + }, + onExitHook, + ); + }; + /** + * The [[TransitionStateHookFn]] for onRetain + * + * When the state was already entered, and is not being exited or re-entered, the state's .onRetain function is invoked. + * + * Registered using `transitionService.onRetain({ retained: (state) => !!state.onRetain }, onRetainHook);` + * + * See: [[IHookRegistry.onRetain]] + */ + var onRetainHook = makeEnterExitRetainHook('onRetain'); + var registerOnRetainHook = function(transitionService) { + return transitionService.onRetain( + { + retained: function(state) { + return !!state.onRetain; + }, + }, + onRetainHook, + ); + }; + /** + * The [[TransitionStateHookFn]] for onEnter + * + * When the state is being entered, the state's .onEnter function is invoked. + * + * Registered using `transitionService.onEnter({ entering: (state) => !!state.onEnter }, onEnterHook);` + * + * See: [[IHookRegistry.onEnter]] + */ + var onEnterHook = makeEnterExitRetainHook('onEnter'); + var registerOnEnterHook = function(transitionService) { + return transitionService.onEnter( + { + entering: function(state) { + return !!state.onEnter; + }, + }, + onEnterHook, + ); + }; -/** @module hooks */ -/** for typedoc */ -var RESOLVE_HOOK_PRIORITY = 1000; -/** - * A [[TransitionHookFn]] which resolves all EAGER Resolvables in the To Path - * - * Registered using `transitionService.onStart({}, eagerResolvePath, { priority: 1000 });` - * - * When a Transition starts, this hook resolves all the EAGER Resolvables, which the transition then waits for. - * - * See [[StateDeclaration.resolve]] - */ -var eagerResolvePath = function (trans) { - return new ResolveContext(trans.treeChanges().to) - .resolvePath('EAGER', trans) - .then(noop); -}; -var registerEagerResolvePath = function (transitionService) { + /** @module hooks */ + var RESOLVE_HOOK_PRIORITY = 1000; + /** + * A [[TransitionHookFn]] which resolves all EAGER Resolvables in the To Path + * + * Registered using `transitionService.onStart({}, eagerResolvePath, { priority: 1000 });` + * + * When a Transition starts, this hook resolves all the EAGER Resolvables, which the transition then waits for. + * + * See [[StateDeclaration.resolve]] + */ + var eagerResolvePath = function(trans) { + return new ResolveContext(trans.treeChanges().to).resolvePath('EAGER', trans).then(noop); + }; + var registerEagerResolvePath = function(transitionService) { return transitionService.onStart({}, eagerResolvePath, { priority: RESOLVE_HOOK_PRIORITY }); -}; -/** - * A [[TransitionHookFn]] which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path - * - * Registered using `transitionService.onEnter({ entering: () => true }, lazyResolveState, { priority: 1000 });` - * - * When a State is being entered, this hook resolves all the Resolvables for this state, which the transition then waits for. - * - * See [[StateDeclaration.resolve]] - */ -var lazyResolveState = function (trans, state) { + }; + /** + * A [[TransitionHookFn]] which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path + * + * Registered using `transitionService.onEnter({ entering: () => true }, lazyResolveState, { priority: 1000 });` + * + * When a State is being entered, this hook resolves all the Resolvables for this state, which the transition then waits for. + * + * See [[StateDeclaration.resolve]] + */ + var lazyResolveState = function(trans, state) { return new ResolveContext(trans.treeChanges().to) - .subContext(state.$$state()) - .resolvePath('LAZY', trans) - .then(noop); -}; -var registerLazyResolveState = function (transitionService) { + .subContext(state.$$state()) + .resolvePath('LAZY', trans) + .then(noop); + }; + var registerLazyResolveState = function(transitionService) { return transitionService.onEnter({ entering: val(true) }, lazyResolveState, { priority: RESOLVE_HOOK_PRIORITY }); -}; -/** - * A [[TransitionHookFn]] which resolves any dynamically added (LAZY or EAGER) Resolvables. - * - * Registered using `transitionService.onFinish({}, eagerResolvePath, { priority: 1000 });` - * - * After all entering states have been entered, this hook resolves any remaining Resolvables. - * These are typically dynamic resolves which were added by some Transition Hook using [[Transition.addResolvable]]. - * - * See [[StateDeclaration.resolve]] - */ -var resolveRemaining = function (trans) { - return new ResolveContext(trans.treeChanges().to) - .resolvePath('LAZY', trans) - .then(noop); -}; -var registerResolveRemaining = function (transitionService) { + }; + /** + * A [[TransitionHookFn]] which resolves any dynamically added (LAZY or EAGER) Resolvables. + * + * Registered using `transitionService.onFinish({}, eagerResolvePath, { priority: 1000 });` + * + * After all entering states have been entered, this hook resolves any remaining Resolvables. + * These are typically dynamic resolves which were added by some Transition Hook using [[Transition.addResolvable]]. + * + * See [[StateDeclaration.resolve]] + */ + var resolveRemaining = function(trans) { + return new ResolveContext(trans.treeChanges().to).resolvePath('LAZY', trans).then(noop); + }; + var registerResolveRemaining = function(transitionService) { return transitionService.onFinish({}, resolveRemaining, { priority: RESOLVE_HOOK_PRIORITY }); -}; + }; /** for typedoc */ -/** @module hooks */ /** for typedoc */ -/** - * A [[TransitionHookFn]] which waits for the views to load - * - * Registered using `transitionService.onStart({}, loadEnteringViews);` - * - * Allows the views to do async work in [[ViewConfig.load]] before the transition continues. - * In angular 1, this includes loading the templates. - */ -var loadEnteringViews = function (transition) { + /** @module hooks */ /** + * A [[TransitionHookFn]] which waits for the views to load + * + * Registered using `transitionService.onStart({}, loadEnteringViews);` + * + * Allows the views to do async work in [[ViewConfig.load]] before the transition continues. + * In angular 1, this includes loading the templates. + */ + var loadEnteringViews = function(transition) { var $q = services.$q; var enteringViews = transition.views('entering'); - if (!enteringViews.length) - return; - return $q.all(enteringViews.map(function (view) { return $q.when(view.load()); })).then(noop); -}; -var registerLoadEnteringViews = function (transitionService) { + if (!enteringViews.length) return; + return $q + .all( + enteringViews.map(function(view) { + return $q.when(view.load()); + }), + ) + .then(noop); + }; + var registerLoadEnteringViews = function(transitionService) { return transitionService.onFinish({}, loadEnteringViews); -}; -/** - * A [[TransitionHookFn]] which activates the new views when a transition is successful. - * - * Registered using `transitionService.onSuccess({}, activateViews);` - * - * After a transition is complete, this hook deactivates the old views from the previous state, - * and activates the new views from the destination state. - * - * See [[ViewService]] - */ -var activateViews = function (transition) { + }; + /** + * A [[TransitionHookFn]] which activates the new views when a transition is successful. + * + * Registered using `transitionService.onSuccess({}, activateViews);` + * + * After a transition is complete, this hook deactivates the old views from the previous state, + * and activates the new views from the destination state. + * + * See [[ViewService]] + */ + var activateViews = function(transition) { var enteringViews = transition.views('entering'); var exitingViews = transition.views('exiting'); - if (!enteringViews.length && !exitingViews.length) - return; + if (!enteringViews.length && !exitingViews.length) return; var $view = transition.router.viewService; - exitingViews.forEach(function (vc) { return $view.deactivateViewConfig(vc); }); - enteringViews.forEach(function (vc) { return $view.activateViewConfig(vc); }); + exitingViews.forEach(function(vc) { + return $view.deactivateViewConfig(vc); + }); + enteringViews.forEach(function(vc) { + return $view.activateViewConfig(vc); + }); $view.sync(); -}; -var registerActivateViews = function (transitionService) { + }; + var registerActivateViews = function(transitionService) { return transitionService.onSuccess({}, activateViews); -}; + }; -/** - * A [[TransitionHookFn]] which updates global UI-Router state - * - * Registered using `transitionService.onBefore({}, updateGlobalState);` - * - * Before a [[Transition]] starts, updates the global value of "the current transition" ([[Globals.transition]]). - * After a successful [[Transition]], updates the global values of "the current state" - * ([[Globals.current]] and [[Globals.$current]]) and "the current param values" ([[Globals.params]]). - * - * See also the deprecated properties: - * [[StateService.transition]], [[StateService.current]], [[StateService.params]] - */ -var updateGlobalState = function (trans) { + /** + * A [[TransitionHookFn]] which updates global UI-Router state + * + * Registered using `transitionService.onBefore({}, updateGlobalState);` + * + * Before a [[Transition]] starts, updates the global value of "the current transition" ([[Globals.transition]]). + * After a successful [[Transition]], updates the global values of "the current state" + * ([[Globals.current]] and [[Globals.$current]]) and "the current param values" ([[Globals.params]]). + * + * See also the deprecated properties: + * [[StateService.transition]], [[StateService.current]], [[StateService.params]] + */ + var updateGlobalState = function(trans) { var globals = trans.router.globals; - var transitionSuccessful = function () { - globals.successfulTransitions.enqueue(trans); - globals.$current = trans.$to(); - globals.current = globals.$current.self; - copy(trans.params(), globals.params); + var transitionSuccessful = function() { + globals.successfulTransitions.enqueue(trans); + globals.$current = trans.$to(); + globals.current = globals.$current.self; + copy(trans.params(), globals.params); }; - var clearCurrentTransition = function () { - // Do not clear globals.transition if a different transition has started in the meantime - if (globals.transition === trans) - globals.transition = null; + var clearCurrentTransition = function() { + // Do not clear globals.transition if a different transition has started in the meantime + if (globals.transition === trans) globals.transition = null; }; trans.onSuccess({}, transitionSuccessful, { priority: 10000 }); trans.promise.then(clearCurrentTransition, clearCurrentTransition); -}; -var registerUpdateGlobalState = function (transitionService) { + }; + var registerUpdateGlobalState = function(transitionService) { return transitionService.onCreate({}, updateGlobalState); -}; + }; -/** - * A [[TransitionHookFn]] which updates the URL after a successful transition - * - * Registered using `transitionService.onSuccess({}, updateUrl);` - */ -var updateUrl = function (transition) { + /** + * A [[TransitionHookFn]] which updates the URL after a successful transition + * + * Registered using `transitionService.onSuccess({}, updateUrl);` + */ + var updateUrl = function(transition) { var options = transition.options(); var $state = transition.router.stateService; var $urlRouter = transition.router.urlRouter; @@ -6403,233 +7134,262 @@ var updateUrl = function (transition) { // The user doesn't want the url to update (options.location === false) // The destination state, and all parents have no navigable url if (options.source !== 'url' && options.location && $state.$current.navigable) { - var urlOptions = { replace: options.location === 'replace' }; - $urlRouter.push($state.$current.navigable.url, $state.params, urlOptions); + var urlOptions = { replace: options.location === 'replace' }; + $urlRouter.push($state.$current.navigable.url, $state.params, urlOptions); } $urlRouter.update(true); -}; -var registerUpdateUrl = function (transitionService) { + }; + var registerUpdateUrl = function(transitionService) { return transitionService.onSuccess({}, updateUrl, { priority: 9999 }); -}; + }; -/** - * A [[TransitionHookFn]] that performs lazy loading - * - * When entering a state "abc" which has a `lazyLoad` function defined: - * - Invoke the `lazyLoad` function (unless it is already in process) - * - Flag the hook function as "in process" - * - The function should return a promise (that resolves when lazy loading is complete) - * - Wait for the promise to settle - * - If the promise resolves to a [[LazyLoadResult]], then register those states - * - Flag the hook function as "not in process" - * - If the hook was successful - * - Remove the `lazyLoad` function from the state declaration - * - If all the hooks were successful - * - Retry the transition (by returning a TargetState) - * - * ``` - * .state('abc', { - * component: 'fooComponent', - * lazyLoad: () => System.import('./fooComponent') - * }); - * ``` - * - * See [[StateDeclaration.lazyLoad]] - */ -var lazyLoadHook = function (transition) { + /** + * A [[TransitionHookFn]] that performs lazy loading + * + * When entering a state "abc" which has a `lazyLoad` function defined: + * - Invoke the `lazyLoad` function (unless it is already in process) + * - Flag the hook function as "in process" + * - The function should return a promise (that resolves when lazy loading is complete) + * - Wait for the promise to settle + * - If the promise resolves to a [[LazyLoadResult]], then register those states + * - Flag the hook function as "not in process" + * - If the hook was successful + * - Remove the `lazyLoad` function from the state declaration + * - If all the hooks were successful + * - Retry the transition (by returning a TargetState) + * + * ``` + * .state('abc', { + * component: 'fooComponent', + * lazyLoad: () => System.import('./fooComponent') + * }); + * ``` + * + * See [[StateDeclaration.lazyLoad]] + */ + var lazyLoadHook = function(transition) { var router = transition.router; function retryTransition() { - if (transition.originalTransition().options().source !== 'url') { - // The original transition was not triggered via url sync - // The lazy state should be loaded now, so re-try the original transition - var orig = transition.targetState(); - return router.stateService.target(orig.identifier(), orig.params(), orig.options()); - } - // The original transition was triggered via url sync - // Run the URL rules and find the best match - var $url = router.urlService; - var result = $url.match($url.parts()); - var rule = result && result.rule; - // If the best match is a state, redirect the transition (instead - // of calling sync() which supersedes the current transition) - if (rule && rule.type === 'STATE') { - var state = rule.state; - var params = result.match; - return router.stateService.target(state, params, transition.options()); - } - // No matching state found, so let .sync() choose the best non-state match/otherwise - router.urlService.sync(); + if (transition.originalTransition().options().source !== 'url') { + // The original transition was not triggered via url sync + // The lazy state should be loaded now, so re-try the original transition + var orig = transition.targetState(); + return router.stateService.target(orig.identifier(), orig.params(), orig.options()); + } + // The original transition was triggered via url sync + // Run the URL rules and find the best match + var $url = router.urlService; + var result = $url.match($url.parts()); + var rule = result && result.rule; + // If the best match is a state, redirect the transition (instead + // of calling sync() which supersedes the current transition) + if (rule && rule.type === 'STATE') { + var state = rule.state; + var params = result.match; + return router.stateService.target(state, params, transition.options()); + } + // No matching state found, so let .sync() choose the best non-state match/otherwise + router.urlService.sync(); } - var promises = transition.entering() - .filter(function (state) { return !!state.$$state().lazyLoad; }) - .map(function (state) { return lazyLoadState(transition, state); }); + var promises = transition + .entering() + .filter(function(state) { + return !!state.$$state().lazyLoad; + }) + .map(function(state) { + return lazyLoadState(transition, state); + }); return services.$q.all(promises).then(retryTransition); -}; -var registerLazyLoadHook = function (transitionService) { - return transitionService.onBefore({ entering: function (state) { return !!state.lazyLoad; } }, lazyLoadHook); -}; -/** - * Invokes a state's lazy load function - * - * @param transition a Transition context - * @param state the state to lazy load - * @returns A promise for the lazy load result - */ -function lazyLoadState(transition, state) { + }; + var registerLazyLoadHook = function(transitionService) { + return transitionService.onBefore( + { + entering: function(state) { + return !!state.lazyLoad; + }, + }, + lazyLoadHook, + ); + }; + /** + * Invokes a state's lazy load function + * + * @param transition a Transition context + * @param state the state to lazy load + * @returns A promise for the lazy load result + */ + function lazyLoadState(transition, state) { var lazyLoadFn = state.$$state().lazyLoad; // Store/get the lazy load promise on/from the hookfn so it doesn't get re-invoked var promise = lazyLoadFn['_promise']; if (!promise) { - var success = function (result) { - delete state.lazyLoad; - delete state.$$state().lazyLoad; - delete lazyLoadFn['_promise']; - return result; - }; - var error = function (err) { - delete lazyLoadFn['_promise']; - return services.$q.reject(err); - }; - promise = lazyLoadFn['_promise'] = - services.$q.when(lazyLoadFn(transition, state)) - .then(updateStateRegistry) - .then(success, error); + var success = function(result) { + delete state.lazyLoad; + delete state.$$state().lazyLoad; + delete lazyLoadFn['_promise']; + return result; + }; + var error = function(err) { + delete lazyLoadFn['_promise']; + return services.$q.reject(err); + }; + promise = lazyLoadFn['_promise'] = services.$q + .when(lazyLoadFn(transition, state)) + .then(updateStateRegistry) + .then(success, error); } /** Register any lazy loaded state definitions */ function updateStateRegistry(result) { - if (result && Array.isArray(result.states)) { - result.states.forEach(function (_state) { return transition.router.stateRegistry.register(_state); }); - } - return result; + if (result && Array.isArray(result.states)) { + result.states.forEach(function(_state) { + return transition.router.stateRegistry.register(_state); + }); + } + return result; } return promise; -} + } -/** - * This class defines a type of hook, such as `onBefore` or `onEnter`. - * Plugins can define custom hook types, such as sticky states does for `onInactive`. - * - * @interalapi - */ -var TransitionEventType = /** @class */ (function () { + /** + * This class defines a type of hook, such as `onBefore` or `onEnter`. + * Plugins can define custom hook types, such as sticky states does for `onInactive`. + * + * @interalapi + */ + var TransitionEventType = /** @class */ (function() { /* tslint:disable:no-inferrable-types */ - function TransitionEventType(name, hookPhase, hookOrder, criteriaMatchPath, reverseSort, getResultHandler, getErrorHandler, synchronous) { - if (reverseSort === void 0) { reverseSort = false; } - if (getResultHandler === void 0) { getResultHandler = TransitionHook.HANDLE_RESULT; } - if (getErrorHandler === void 0) { getErrorHandler = TransitionHook.REJECT_ERROR; } - if (synchronous === void 0) { synchronous = false; } - this.name = name; - this.hookPhase = hookPhase; - this.hookOrder = hookOrder; - this.criteriaMatchPath = criteriaMatchPath; - this.reverseSort = reverseSort; - this.getResultHandler = getResultHandler; - this.getErrorHandler = getErrorHandler; - this.synchronous = synchronous; + function TransitionEventType( + name, + hookPhase, + hookOrder, + criteriaMatchPath, + reverseSort, + getResultHandler, + getErrorHandler, + synchronous, + ) { + if (reverseSort === void 0) { + reverseSort = false; + } + if (getResultHandler === void 0) { + getResultHandler = TransitionHook.HANDLE_RESULT; + } + if (getErrorHandler === void 0) { + getErrorHandler = TransitionHook.REJECT_ERROR; + } + if (synchronous === void 0) { + synchronous = false; + } + this.name = name; + this.hookPhase = hookPhase; + this.hookOrder = hookOrder; + this.criteriaMatchPath = criteriaMatchPath; + this.reverseSort = reverseSort; + this.getResultHandler = getResultHandler; + this.getErrorHandler = getErrorHandler; + this.synchronous = synchronous; } return TransitionEventType; -}()); + })(); /** */ -/** @module hooks */ /** */ -/** - * A [[TransitionHookFn]] that skips a transition if it should be ignored - * - * This hook is invoked at the end of the onBefore phase. - * - * If the transition should be ignored (because no parameter or states changed) - * then the transition is ignored and not processed. - */ -function ignoredHook(trans) { + /** @module hooks */ /** + * A [[TransitionHookFn]] that skips a transition if it should be ignored + * + * This hook is invoked at the end of the onBefore phase. + * + * If the transition should be ignored (because no parameter or states changed) + * then the transition is ignored and not processed. + */ + function ignoredHook(trans) { var ignoredReason = trans._ignoredReason(); - if (!ignoredReason) - return; + if (!ignoredReason) return; trace.traceTransitionIgnored(trans); var pending = trans.router.globals.transition; // The user clicked a link going back to the *current state* ('A') // However, there is also a pending transition in flight (to 'B') // Abort the transition to 'B' because the user now wants to be back at 'A'. if (ignoredReason === 'SameAsCurrent' && pending) { - pending.abort(); + pending.abort(); } return Rejection.ignored().toPromise(); -} -var registerIgnoredTransitionHook = function (transitionService) { + } + var registerIgnoredTransitionHook = function(transitionService) { return transitionService.onBefore({}, ignoredHook, { priority: -9999 }); -}; + }; /** */ -/** @module hooks */ /** */ -/** - * A [[TransitionHookFn]] that rejects the Transition if it is invalid - * - * This hook is invoked at the end of the onBefore phase. - * If the transition is invalid (for example, param values do not validate) - * then the transition is rejected. - */ -function invalidTransitionHook(trans) { + /** @module hooks */ /** + * A [[TransitionHookFn]] that rejects the Transition if it is invalid + * + * This hook is invoked at the end of the onBefore phase. + * If the transition is invalid (for example, param values do not validate) + * then the transition is rejected. + */ + function invalidTransitionHook(trans) { if (!trans.valid()) { - throw new Error(trans.error()); + throw new Error(trans.error().toString()); } -} -var registerInvalidTransitionHook = function (transitionService) { + } + var registerInvalidTransitionHook = function(transitionService) { return transitionService.onBefore({}, invalidTransitionHook, { priority: -10000 }); -}; + }; -/** - * @coreapi - * @module transition - */ -/** for typedoc */ -/** - * The default [[Transition]] options. - * - * Include this object when applying custom defaults: - * let reloadOpts = { reload: true, notify: true } - * let options = defaults(theirOpts, customDefaults, defaultOptions); - */ -var defaultTransOpts = { + /** + * @coreapi + * @module transition + */ + /** + * The default [[Transition]] options. + * + * Include this object when applying custom defaults: + * let reloadOpts = { reload: true, notify: true } + * let options = defaults(theirOpts, customDefaults, defaultOptions); + */ + var defaultTransOpts = { location: true, relative: null, inherit: false, notify: true, reload: false, custom: {}, - current: function () { return null; }, + current: function() { + return null; + }, source: 'unknown', -}; -/** - * This class provides services related to Transitions. - * - * - Most importantly, it allows global Transition Hooks to be registered. - * - It allows the default transition error handler to be set. - * - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]). - * - * At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class. - */ -var TransitionService = /** @class */ (function () { + }; + /** + * This class provides services related to Transitions. + * + * - Most importantly, it allows global Transition Hooks to be registered. + * - It allows the default transition error handler to be set. + * - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]). + * + * At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class. + */ + var TransitionService = /** @class */ (function() { /** @hidden */ function TransitionService(_router) { - /** @hidden */ - this._transitionCount = 0; - /** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */ - this._eventTypes = []; - /** @hidden The registered transition hooks */ - this._registeredHooks = {}; - /** @hidden The paths on a criteria object */ - this._criteriaPaths = {}; - this._router = _router; - this.$view = _router.viewService; - this._deregisterHookFns = {}; - this._pluginapi = createProxyFunctions(val(this), {}, val(this), [ - '_definePathType', - '_defineEvent', - '_getPathTypes', - '_getEvents', - 'getHooks', - ]); - this._defineCorePaths(); - this._defineCoreEvents(); - this._registerCoreTransitionHooks(); - _router.globals.successfulTransitions.onEvict(treeChangesCleanup); + /** @hidden */ + this._transitionCount = 0; + /** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */ + this._eventTypes = []; + /** @hidden The registered transition hooks */ + this._registeredHooks = {}; + /** @hidden The paths on a criteria object */ + this._criteriaPaths = {}; + this._router = _router; + this.$view = _router.viewService; + this._deregisterHookFns = {}; + this._pluginapi = createProxyFunctions(val(this), {}, val(this), [ + '_definePathType', + '_defineEvent', + '_getPathTypes', + '_getEvents', + 'getHooks', + ]); + this._defineCorePaths(); + this._defineCoreEvents(); + this._registerCoreTransitionHooks(); + _router.globals.successfulTransitions.onEvict(treeChangesCleanup); } /** * Registers a [[TransitionHookFn]], called *while a transition is being constructed*. @@ -6654,32 +7414,52 @@ var TransitionService = /** @class */ (function () { * @param options the registration options * @returns a function which deregisters the hook. */ - TransitionService.prototype.onCreate = function (criteria, callback, options) { return; }; + TransitionService.prototype.onCreate = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onBefore = function (criteria, callback, options) { return; }; + TransitionService.prototype.onBefore = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onStart = function (criteria, callback, options) { return; }; + TransitionService.prototype.onStart = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onExit = function (criteria, callback, options) { return; }; + TransitionService.prototype.onExit = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onRetain = function (criteria, callback, options) { return; }; + TransitionService.prototype.onRetain = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onEnter = function (criteria, callback, options) { return; }; + TransitionService.prototype.onEnter = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onFinish = function (criteria, callback, options) { return; }; + TransitionService.prototype.onFinish = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onSuccess = function (criteria, callback, options) { return; }; + TransitionService.prototype.onSuccess = function(criteria, callback, options) { + return; + }; /** @inheritdoc */ - TransitionService.prototype.onError = function (criteria, callback, options) { return; }; + TransitionService.prototype.onError = function(criteria, callback, options) { + return; + }; /** * dispose * @internalapi */ - TransitionService.prototype.dispose = function (router) { - values(this._registeredHooks).forEach(function (hooksArray) { return hooksArray.forEach(function (hook) { - hook._deregistered = true; - removeFrom(hooksArray, hook); - }); }); + TransitionService.prototype.dispose = function(router) { + values(this._registeredHooks).forEach(function(hooksArray) { + return hooksArray.forEach(function(hook) { + hook._deregistered = true; + removeFrom(hooksArray, hook); + }); + }); }; /** * Creates a new [[Transition]] object @@ -6691,54 +7471,112 @@ var TransitionService = /** @class */ (function () { * @param targetState the target state (destination) * @returns a Transition */ - TransitionService.prototype.create = function (fromPath, targetState) { - return new Transition(fromPath, targetState, this._router); + TransitionService.prototype.create = function(fromPath, targetState) { + return new Transition(fromPath, targetState, this._router); }; /** @hidden */ - TransitionService.prototype._defineCoreEvents = function () { - var Phase = exports.TransitionHookPhase; - var TH = TransitionHook; - var paths = this._criteriaPaths; - var NORMAL_SORT = false, REVERSE_SORT = true; - var SYNCHRONOUS = true; - this._defineEvent('onCreate', Phase.CREATE, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.THROW_ERROR, SYNCHRONOUS); - this._defineEvent('onBefore', Phase.BEFORE, 0, paths.to); - this._defineEvent('onStart', Phase.RUN, 0, paths.to); - this._defineEvent('onExit', Phase.RUN, 100, paths.exiting, REVERSE_SORT); - this._defineEvent('onRetain', Phase.RUN, 200, paths.retained); - this._defineEvent('onEnter', Phase.RUN, 300, paths.entering); - this._defineEvent('onFinish', Phase.RUN, 400, paths.to); - this._defineEvent('onSuccess', Phase.SUCCESS, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.LOG_ERROR, SYNCHRONOUS); - this._defineEvent('onError', Phase.ERROR, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.LOG_ERROR, SYNCHRONOUS); + TransitionService.prototype._defineCoreEvents = function() { + var Phase = exports.TransitionHookPhase; + var TH = TransitionHook; + var paths = this._criteriaPaths; + var NORMAL_SORT = false, + REVERSE_SORT = true; + var SYNCHRONOUS = true; + this._defineEvent( + 'onCreate', + Phase.CREATE, + 0, + paths.to, + NORMAL_SORT, + TH.LOG_REJECTED_RESULT, + TH.THROW_ERROR, + SYNCHRONOUS, + ); + this._defineEvent('onBefore', Phase.BEFORE, 0, paths.to); + this._defineEvent('onStart', Phase.RUN, 0, paths.to); + this._defineEvent('onExit', Phase.RUN, 100, paths.exiting, REVERSE_SORT); + this._defineEvent('onRetain', Phase.RUN, 200, paths.retained); + this._defineEvent('onEnter', Phase.RUN, 300, paths.entering); + this._defineEvent('onFinish', Phase.RUN, 400, paths.to); + this._defineEvent( + 'onSuccess', + Phase.SUCCESS, + 0, + paths.to, + NORMAL_SORT, + TH.LOG_REJECTED_RESULT, + TH.LOG_ERROR, + SYNCHRONOUS, + ); + this._defineEvent( + 'onError', + Phase.ERROR, + 0, + paths.to, + NORMAL_SORT, + TH.LOG_REJECTED_RESULT, + TH.LOG_ERROR, + SYNCHRONOUS, + ); }; /** @hidden */ - TransitionService.prototype._defineCorePaths = function () { - var STATE = exports.TransitionHookScope.STATE, TRANSITION = exports.TransitionHookScope.TRANSITION; - this._definePathType('to', TRANSITION); - this._definePathType('from', TRANSITION); - this._definePathType('exiting', STATE); - this._definePathType('retained', STATE); - this._definePathType('entering', STATE); + TransitionService.prototype._defineCorePaths = function() { + var STATE = exports.TransitionHookScope.STATE, + TRANSITION = exports.TransitionHookScope.TRANSITION; + this._definePathType('to', TRANSITION); + this._definePathType('from', TRANSITION); + this._definePathType('exiting', STATE); + this._definePathType('retained', STATE); + this._definePathType('entering', STATE); }; /** @hidden */ - TransitionService.prototype._defineEvent = function (name, hookPhase, hookOrder, criteriaMatchPath, reverseSort, getResultHandler, getErrorHandler, synchronous) { - if (reverseSort === void 0) { reverseSort = false; } - if (getResultHandler === void 0) { getResultHandler = TransitionHook.HANDLE_RESULT; } - if (getErrorHandler === void 0) { getErrorHandler = TransitionHook.REJECT_ERROR; } - if (synchronous === void 0) { synchronous = false; } - var eventType = new TransitionEventType(name, hookPhase, hookOrder, criteriaMatchPath, reverseSort, getResultHandler, getErrorHandler, synchronous); - this._eventTypes.push(eventType); - makeEvent(this, this, eventType); + TransitionService.prototype._defineEvent = function( + name, + hookPhase, + hookOrder, + criteriaMatchPath, + reverseSort, + getResultHandler, + getErrorHandler, + synchronous, + ) { + if (reverseSort === void 0) { + reverseSort = false; + } + if (getResultHandler === void 0) { + getResultHandler = TransitionHook.HANDLE_RESULT; + } + if (getErrorHandler === void 0) { + getErrorHandler = TransitionHook.REJECT_ERROR; + } + if (synchronous === void 0) { + synchronous = false; + } + var eventType = new TransitionEventType( + name, + hookPhase, + hookOrder, + criteriaMatchPath, + reverseSort, + getResultHandler, + getErrorHandler, + synchronous, + ); + this._eventTypes.push(eventType); + makeEvent(this, this, eventType); }; - /** @hidden */ // tslint:disable-next-line - TransitionService.prototype._getEvents = function (phase) { - var transitionHookTypes = isDefined(phase) ? - this._eventTypes.filter(function (type) { return type.hookPhase === phase; }) : - this._eventTypes.slice(); - return transitionHookTypes.sort(function (l, r) { - var cmpByPhase = l.hookPhase - r.hookPhase; - return cmpByPhase === 0 ? l.hookOrder - r.hookOrder : cmpByPhase; - }); + /** @hidden */ + // tslint:disable-next-line + TransitionService.prototype._getEvents = function(phase) { + var transitionHookTypes = isDefined(phase) + ? this._eventTypes.filter(function(type) { + return type.hookPhase === phase; + }) + : this._eventTypes.slice(); + return transitionHookTypes.sort(function(l, r) { + var cmpByPhase = l.hookPhase - r.hookPhase; + return cmpByPhase === 0 ? l.hookOrder - r.hookOrder : cmpByPhase; + }); }; /** * Adds a Path to be used as a criterion against a TreeChanges path @@ -6753,126 +7591,131 @@ var TransitionService = /** @class */ (function () { * * @hidden */ - TransitionService.prototype._definePathType = function (name, hookScope) { - this._criteriaPaths[name] = { name: name, scope: hookScope }; + TransitionService.prototype._definePathType = function(name, hookScope) { + this._criteriaPaths[name] = { name: name, scope: hookScope }; }; - /** * @hidden */ // tslint:disable-next-line - TransitionService.prototype._getPathTypes = function () { - return this._criteriaPaths; + /** * @hidden */ + // tslint:disable-next-line + TransitionService.prototype._getPathTypes = function() { + return this._criteriaPaths; }; /** @hidden */ - TransitionService.prototype.getHooks = function (hookName) { - return this._registeredHooks[hookName]; + TransitionService.prototype.getHooks = function(hookName) { + return this._registeredHooks[hookName]; }; /** @hidden */ - TransitionService.prototype._registerCoreTransitionHooks = function () { - var fns = this._deregisterHookFns; - fns.addCoreResolves = registerAddCoreResolvables(this); - fns.ignored = registerIgnoredTransitionHook(this); - fns.invalid = registerInvalidTransitionHook(this); - // Wire up redirectTo hook - fns.redirectTo = registerRedirectToHook(this); - // Wire up onExit/Retain/Enter state hooks - fns.onExit = registerOnExitHook(this); - fns.onRetain = registerOnRetainHook(this); - fns.onEnter = registerOnEnterHook(this); - // Wire up Resolve hooks - fns.eagerResolve = registerEagerResolvePath(this); - fns.lazyResolve = registerLazyResolveState(this); - fns.resolveAll = registerResolveRemaining(this); - // Wire up the View management hooks - fns.loadViews = registerLoadEnteringViews(this); - fns.activateViews = registerActivateViews(this); - // Updates global state after a transition - fns.updateGlobals = registerUpdateGlobalState(this); - // After globals.current is updated at priority: 10000 - fns.updateUrl = registerUpdateUrl(this); - // Lazy load state trees - fns.lazyLoad = registerLazyLoadHook(this); + TransitionService.prototype._registerCoreTransitionHooks = function() { + var fns = this._deregisterHookFns; + fns.addCoreResolves = registerAddCoreResolvables(this); + fns.ignored = registerIgnoredTransitionHook(this); + fns.invalid = registerInvalidTransitionHook(this); + // Wire up redirectTo hook + fns.redirectTo = registerRedirectToHook(this); + // Wire up onExit/Retain/Enter state hooks + fns.onExit = registerOnExitHook(this); + fns.onRetain = registerOnRetainHook(this); + fns.onEnter = registerOnEnterHook(this); + // Wire up Resolve hooks + fns.eagerResolve = registerEagerResolvePath(this); + fns.lazyResolve = registerLazyResolveState(this); + fns.resolveAll = registerResolveRemaining(this); + // Wire up the View management hooks + fns.loadViews = registerLoadEnteringViews(this); + fns.activateViews = registerActivateViews(this); + // Updates global state after a transition + fns.updateGlobals = registerUpdateGlobalState(this); + // After globals.current is updated at priority: 10000 + fns.updateUrl = registerUpdateUrl(this); + // Lazy load state trees + fns.lazyLoad = registerLazyLoadHook(this); }; return TransitionService; -}()); + })(); -/** - * @coreapi - * @module state - */ -/** */ -/** - * Provides state related service functions - * - * This class provides services related to ui-router states. - * An instance of this class is located on the global [[UIRouter]] object. - */ -var StateService = /** @class */ (function () { + /** + * @coreapi + * @module state + */ + /** + * Provides state related service functions + * + * This class provides services related to ui-router states. + * An instance of this class is located on the global [[UIRouter]] object. + */ + var StateService = /** @class */ (function() { /** @internalapi */ function StateService(router) { - this.router = router; - /** @internalapi */ - this.invalidCallbacks = []; - /** @hidden */ - this._defaultErrorHandler = function $defaultErrorHandler($error$) { - if ($error$ instanceof Error && $error$.stack) { - console.error($error$); - console.error($error$.stack); - } - else if ($error$ instanceof Rejection) { - console.error($error$.toString()); - if ($error$.detail && $error$.detail.stack) - console.error($error$.detail.stack); - } - else { - console.error($error$); - } - }; - var getters = ['current', '$current', 'params', 'transition']; - var boundFns = Object.keys(StateService.prototype).filter(not(inArray(getters))); - createProxyFunctions(val(StateService.prototype), this, val(this), boundFns); + this.router = router; + /** @internalapi */ + this.invalidCallbacks = []; + /** @hidden */ + this._defaultErrorHandler = function $defaultErrorHandler($error$) { + if ($error$ instanceof Error && $error$.stack) { + console.error($error$); + console.error($error$.stack); + } else if ($error$ instanceof Rejection) { + console.error($error$.toString()); + if ($error$.detail && $error$.detail.stack) console.error($error$.detail.stack); + } else { + console.error($error$); + } + }; + var getters = ['current', '$current', 'params', 'transition']; + var boundFns = Object.keys(StateService.prototype).filter(not(inArray(getters))); + createProxyFunctions(val(StateService.prototype), this, val(this), boundFns); } - Object.defineProperty(StateService.prototype, "transition", { - /** - * The [[Transition]] currently in progress (or null) - * - * This is a passthrough through to [[UIRouterGlobals.transition]] - */ - get: function () { return this.router.globals.transition; }, - enumerable: true, - configurable: true + Object.defineProperty(StateService.prototype, 'transition', { + /** + * The [[Transition]] currently in progress (or null) + * + * This is a passthrough through to [[UIRouterGlobals.transition]] + */ + get: function() { + return this.router.globals.transition; + }, + enumerable: true, + configurable: true, }); - Object.defineProperty(StateService.prototype, "params", { - /** - * The latest successful state parameters - * - * This is a passthrough through to [[UIRouterGlobals.params]] - */ - get: function () { return this.router.globals.params; }, - enumerable: true, - configurable: true + Object.defineProperty(StateService.prototype, 'params', { + /** + * The latest successful state parameters + * + * This is a passthrough through to [[UIRouterGlobals.params]] + */ + get: function() { + return this.router.globals.params; + }, + enumerable: true, + configurable: true, }); - Object.defineProperty(StateService.prototype, "current", { - /** - * The current [[StateDeclaration]] - * - * This is a passthrough through to [[UIRouterGlobals.current]] - */ - get: function () { return this.router.globals.current; }, - enumerable: true, - configurable: true + Object.defineProperty(StateService.prototype, 'current', { + /** + * The current [[StateDeclaration]] + * + * This is a passthrough through to [[UIRouterGlobals.current]] + */ + get: function() { + return this.router.globals.current; + }, + enumerable: true, + configurable: true, }); - Object.defineProperty(StateService.prototype, "$current", { - /** - * The current [[StateObject]] - * - * This is a passthrough through to [[UIRouterGlobals.$current]] - */ - get: function () { return this.router.globals.$current; }, - enumerable: true, - configurable: true + Object.defineProperty(StateService.prototype, '$current', { + /** + * The current [[StateObject]] + * + * This is a passthrough through to [[UIRouterGlobals.$current]] + */ + get: function() { + return this.router.globals.$current; + }, + enumerable: true, + configurable: true, }); /** @internalapi */ - StateService.prototype.dispose = function () { - this.defaultErrorHandler(noop); - this.invalidCallbacks = []; + StateService.prototype.dispose = function() { + this.defaultErrorHandler(noop); + this.invalidCallbacks = []; }; /** * Handler for when [[transitionTo]] is called with an invalid state. @@ -6885,37 +7728,40 @@ var StateService = /** @class */ (function () { * * @internalapi */ - StateService.prototype._handleInvalidTargetState = function (fromPath, toState) { - var _this = this; - var fromState = PathUtils.makeTargetState(this.router.stateRegistry, fromPath); - var globals = this.router.globals; - var latestThing = function () { return globals.transitionHistory.peekTail(); }; - var latest = latestThing(); - var callbackQueue = new Queue(this.invalidCallbacks.slice()); - var injector = new ResolveContext(fromPath).injector(); - var checkForRedirect = function (result) { - if (!(result instanceof TargetState)) { - return; - } - var target = result; - // Recreate the TargetState, in case the state is now defined. - target = _this.target(target.identifier(), target.params(), target.options()); - if (!target.valid()) { - return Rejection.invalid(target.error()).toPromise(); - } - if (latestThing() !== latest) { - return Rejection.superseded().toPromise(); - } - return _this.transitionTo(target.identifier(), target.params(), target.options()); - }; - function invokeNextCallback() { - var nextCallback = callbackQueue.dequeue(); - if (nextCallback === undefined) - return Rejection.invalid(toState.error()).toPromise(); - var callbackResult = services.$q.when(nextCallback(toState, fromState, injector)); - return callbackResult.then(checkForRedirect).then(function (result) { return result || invokeNextCallback(); }); + StateService.prototype._handleInvalidTargetState = function(fromPath, toState) { + var _this = this; + var fromState = PathUtils.makeTargetState(this.router.stateRegistry, fromPath); + var globals = this.router.globals; + var latestThing = function() { + return globals.transitionHistory.peekTail(); + }; + var latest = latestThing(); + var callbackQueue = new Queue(this.invalidCallbacks.slice()); + var injector = new ResolveContext(fromPath).injector(); + var checkForRedirect = function(result) { + if (!(result instanceof TargetState)) { + return; } - return invokeNextCallback(); + var target = result; + // Recreate the TargetState, in case the state is now defined. + target = _this.target(target.identifier(), target.params(), target.options()); + if (!target.valid()) { + return Rejection.invalid(target.error()).toPromise(); + } + if (latestThing() !== latest) { + return Rejection.superseded().toPromise(); + } + return _this.transitionTo(target.identifier(), target.params(), target.options()); + }; + function invokeNextCallback() { + var nextCallback = callbackQueue.dequeue(); + if (nextCallback === undefined) return Rejection.invalid(toState.error()).toPromise(); + var callbackResult = services.$q.when(nextCallback(toState, fromState, injector)); + return callbackResult.then(checkForRedirect).then(function(result) { + return result || invokeNextCallback(); + }); + } + return invokeNextCallback(); }; /** * Registers an Invalid State handler @@ -6941,11 +7787,11 @@ var StateService = /** @class */ (function () { * * @returns a function which deregisters the callback */ - StateService.prototype.onInvalid = function (callback) { - this.invalidCallbacks.push(callback); - return function deregisterListener() { - removeFrom(this.invalidCallbacks)(callback); - }.bind(this); + StateService.prototype.onInvalid = function(callback) { + this.invalidCallbacks.push(callback); + return function deregisterListener() { + removeFrom(this.invalidCallbacks)(callback); + }.bind(this); }; /** * Reloads the current state @@ -6991,12 +7837,12 @@ var StateService = /** @class */ (function () { * * @returns A promise representing the state of the new transition. See [[StateService.go]] */ - StateService.prototype.reload = function (reloadState) { - return this.transitionTo(this.current, this.params, { - reload: isDefined(reloadState) ? reloadState : true, - inherit: false, - notify: false, - }); + StateService.prototype.reload = function(reloadState) { + return this.transitionTo(this.current, this.params, { + reload: isDefined(reloadState) ? reloadState : true, + inherit: false, + notify: false, + }); }; /** * Transition to a different state and/or parameters @@ -7038,10 +7884,10 @@ var StateService = /** @class */ (function () { * * @returns {promise} A promise representing the state of the new transition. */ - StateService.prototype.go = function (to, params, options) { - var defautGoOpts = { relative: this.$current, inherit: true }; - var transOpts = defaults(options, defautGoOpts, defaultTransOpts); - return this.transitionTo(to, params, transOpts); + StateService.prototype.go = function(to, params, options) { + var defautGoOpts = { relative: this.$current, inherit: true }; + var transOpts = defaults(options, defautGoOpts, defaultTransOpts); + return this.transitionTo(to, params, transOpts); }; /** * Creates a [[TargetState]] @@ -7050,23 +7896,28 @@ var StateService = /** @class */ (function () { * * This may be returned from a Transition Hook to redirect a transition, for example. */ - StateService.prototype.target = function (identifier, params, options) { - if (options === void 0) { options = {}; } - // If we're reloading, find the state object to reload from - if (isObject(options.reload) && !options.reload.name) - throw new Error('Invalid reload state object'); - var reg = this.router.stateRegistry; - options.reloadState = options.reload === true ? reg.root() : reg.matcher.find(options.reload, options.relative); - if (options.reload && !options.reloadState) - throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'"); - return new TargetState(this.router.stateRegistry, identifier, params, options); + StateService.prototype.target = function(identifier, params, options) { + if (options === void 0) { + options = {}; + } + // If we're reloading, find the state object to reload from + if (isObject(options.reload) && !options.reload.name) throw new Error('Invalid reload state object'); + var reg = this.router.stateRegistry; + options.reloadState = options.reload === true ? reg.root() : reg.matcher.find(options.reload, options.relative); + if (options.reload && !options.reloadState) + throw new Error( + "No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'", + ); + return new TargetState(this.router.stateRegistry, identifier, params, options); }; - StateService.prototype.getCurrentPath = function () { - var _this = this; - var globals = this.router.globals; - var latestSuccess = globals.successfulTransitions.peekTail(); - var rootPath = function () { return [new PathNode(_this.router.stateRegistry.root())]; }; - return latestSuccess ? latestSuccess.treeChanges().to : rootPath(); + StateService.prototype.getCurrentPath = function() { + var _this = this; + var globals = this.router.globals; + var latestSuccess = globals.successfulTransitions.peekTail(); + var rootPath = function() { + return [new PathNode(_this.router.stateRegistry.root())]; + }; + return latestSuccess ? latestSuccess.treeChanges().to : rootPath(); }; /** * Low-level method for transitioning to a new state. @@ -7091,61 +7942,65 @@ var StateService = /** @class */ (function () { * * @returns A promise representing the state of the new transition. See [[go]] */ - StateService.prototype.transitionTo = function (to, toParams, options) { - var _this = this; - if (toParams === void 0) { toParams = {}; } - if (options === void 0) { options = {}; } - var router = this.router; - var globals = router.globals; - options = defaults(options, defaultTransOpts); - var getCurrent = function () { - return globals.transition; - }; - options = extend(options, { current: getCurrent }); - var ref = this.target(to, toParams, options); - var currentPath = this.getCurrentPath(); - if (!ref.exists()) - return this._handleInvalidTargetState(currentPath, ref); - if (!ref.valid()) - return silentRejection(ref.error()); - /** - * Special handling for Ignored, Aborted, and Redirected transitions - * - * The semantics for the transition.run() promise and the StateService.transitionTo() - * promise differ. For instance, the run() promise may be rejected because it was - * IGNORED, but the transitionTo() promise is resolved because from the user perspective - * no error occurred. Likewise, the transition.run() promise may be rejected because of - * a Redirect, but the transitionTo() promise is chained to the new Transition's promise. - */ - var rejectedTransitionHandler = function (trans) { return function (error) { - if (error instanceof Rejection) { - var isLatest = router.globals.lastStartedTransitionId === trans.$id; - if (error.type === exports.RejectType.IGNORED) { - isLatest && router.urlRouter.update(); - // Consider ignored `Transition.run()` as a successful `transitionTo` - return services.$q.when(globals.current); - } - var detail = error.detail; - if (error.type === exports.RejectType.SUPERSEDED && error.redirected && detail instanceof TargetState) { - // If `Transition.run()` was redirected, allow the `transitionTo()` promise to resolve successfully - // by returning the promise for the new (redirect) `Transition.run()`. - var redirect = trans.redirect(detail); - return redirect.run().catch(rejectedTransitionHandler(redirect)); - } - if (error.type === exports.RejectType.ABORTED) { - isLatest && router.urlRouter.update(); - return services.$q.reject(error); - } + StateService.prototype.transitionTo = function(to, toParams, options) { + var _this = this; + if (toParams === void 0) { + toParams = {}; + } + if (options === void 0) { + options = {}; + } + var router = this.router; + var globals = router.globals; + options = defaults(options, defaultTransOpts); + var getCurrent = function() { + return globals.transition; + }; + options = extend(options, { current: getCurrent }); + var ref = this.target(to, toParams, options); + var currentPath = this.getCurrentPath(); + if (!ref.exists()) return this._handleInvalidTargetState(currentPath, ref); + if (!ref.valid()) return silentRejection(ref.error()); + /** + * Special handling for Ignored, Aborted, and Redirected transitions + * + * The semantics for the transition.run() promise and the StateService.transitionTo() + * promise differ. For instance, the run() promise may be rejected because it was + * IGNORED, but the transitionTo() promise is resolved because from the user perspective + * no error occurred. Likewise, the transition.run() promise may be rejected because of + * a Redirect, but the transitionTo() promise is chained to the new Transition's promise. + */ + var rejectedTransitionHandler = function(trans) { + return function(error) { + if (error instanceof Rejection) { + var isLatest = router.globals.lastStartedTransitionId === trans.$id; + if (error.type === exports.RejectType.IGNORED) { + isLatest && router.urlRouter.update(); + // Consider ignored `Transition.run()` as a successful `transitionTo` + return services.$q.when(globals.current); } - var errorHandler = _this.defaultErrorHandler(); - errorHandler(error); - return services.$q.reject(error); - }; }; - var transition = this.router.transitionService.create(currentPath, ref); - var transitionToPromise = transition.run().catch(rejectedTransitionHandler(transition)); - silenceUncaughtInPromise(transitionToPromise); // issue #2676 - // Return a promise for the transition, which also has the transition object on it. - return extend(transitionToPromise, { transition: transition }); + var detail = error.detail; + if (error.type === exports.RejectType.SUPERSEDED && error.redirected && detail instanceof TargetState) { + // If `Transition.run()` was redirected, allow the `transitionTo()` promise to resolve successfully + // by returning the promise for the new (redirect) `Transition.run()`. + var redirect = trans.redirect(detail); + return redirect.run().catch(rejectedTransitionHandler(redirect)); + } + if (error.type === exports.RejectType.ABORTED) { + isLatest && router.urlRouter.update(); + return services.$q.reject(error); + } + } + var errorHandler = _this.defaultErrorHandler(); + errorHandler(error); + return services.$q.reject(error); + }; + }; + var transition = this.router.transitionService.create(currentPath, ref); + var transitionToPromise = transition.run().catch(rejectedTransitionHandler(transition)); + silenceUncaughtInPromise(transitionToPromise); // issue #2676 + // Return a promise for the transition, which also has the transition object on it. + return extend(transitionToPromise, { transition: transition }); }; /** * Checks if the current state *is* the provided state @@ -7178,17 +8033,14 @@ var StateService = /** @class */ (function () { * * @returns Returns true if it is the state. */ - StateService.prototype.is = function (stateOrName, params, options) { - options = defaults(options, { relative: this.$current }); - var state = this.router.stateRegistry.matcher.find(stateOrName, options.relative); - if (!isDefined(state)) - return undefined; - if (this.$current !== state) - return false; - if (!params) - return true; - var schema = state.parameters({ inherit: true, matchingKeys: params }); - return Param.equals(schema, Param.values(schema, params), this.params); + StateService.prototype.is = function(stateOrName, params, options) { + options = defaults(options, { relative: this.$current }); + var state = this.router.stateRegistry.matcher.find(stateOrName, options.relative); + if (!isDefined(state)) return undefined; + if (this.$current !== state) return false; + if (!params) return true; + var schema = state.parameters({ inherit: true, matchingKeys: params }); + return Param.equals(schema, Param.values(schema, params), this.params); }; /** * Checks if the current state *includes* the provided state @@ -7228,23 +8080,20 @@ var StateService = /** @class */ (function () { * * @returns {boolean} Returns true if it does include the state */ - StateService.prototype.includes = function (stateOrName, params, options) { - options = defaults(options, { relative: this.$current }); - var glob = isString(stateOrName) && Glob.fromString(stateOrName); - if (glob) { - if (!glob.matches(this.$current.name)) - return false; - stateOrName = this.$current.name; - } - var state = this.router.stateRegistry.matcher.find(stateOrName, options.relative), include = this.$current.includes; - if (!isDefined(state)) - return undefined; - if (!isDefined(include[state.name])) - return false; - if (!params) - return true; - var schema = state.parameters({ inherit: true, matchingKeys: params }); - return Param.equals(schema, Param.values(schema, params), this.params); + StateService.prototype.includes = function(stateOrName, params, options) { + options = defaults(options, { relative: this.$current }); + var glob = isString(stateOrName) && Glob.fromString(stateOrName); + if (glob) { + if (!glob.matches(this.$current.name)) return false; + stateOrName = this.$current.name; + } + var state = this.router.stateRegistry.matcher.find(stateOrName, options.relative), + include = this.$current.includes; + if (!isDefined(state)) return undefined; + if (!isDefined(include[state.name])) return false; + if (!params) return true; + var schema = state.parameters({ inherit: true, matchingKeys: params }); + return Param.equals(schema, Param.values(schema, params), this.params); }; /** * Generates a URL for a state and parameters @@ -7262,27 +8111,25 @@ var StateService = /** @class */ (function () { * * @returns {string} compiled state url */ - StateService.prototype.href = function (stateOrName, params, options) { - var defaultHrefOpts = { - lossy: true, - inherit: true, - absolute: false, - relative: this.$current, - }; - options = defaults(options, defaultHrefOpts); - params = params || {}; - var state = this.router.stateRegistry.matcher.find(stateOrName, options.relative); - if (!isDefined(state)) - return null; - if (options.inherit) - params = this.params.$inherit(params, this.$current, state); - var nav = (state && options.lossy) ? state.navigable : state; - if (!nav || nav.url === undefined || nav.url === null) { - return null; - } - return this.router.urlRouter.href(nav.url, params, { - absolute: options.absolute, - }); + StateService.prototype.href = function(stateOrName, params, options) { + var defaultHrefOpts = { + lossy: true, + inherit: true, + absolute: false, + relative: this.$current, + }; + options = defaults(options, defaultHrefOpts); + params = params || {}; + var state = this.router.stateRegistry.matcher.find(stateOrName, options.relative); + if (!isDefined(state)) return null; + if (options.inherit) params = this.params.$inherit(params, this.$current, state); + var nav = state && options.lossy ? state.navigable : state; + if (!nav || nav.url === undefined || nav.url === null) { + return null; + } + return this.router.urlRouter.href(nav.url, params, { + absolute: options.absolute, + }); }; /** * Sets or gets the default [[transitionTo]] error handler. @@ -7308,14 +8155,13 @@ var StateService = /** @class */ (function () { * @param handler a global error handler function * @returns the current global error handler */ - StateService.prototype.defaultErrorHandler = function (handler) { - return this._defaultErrorHandler = handler || this._defaultErrorHandler; + StateService.prototype.defaultErrorHandler = function(handler) { + return (this._defaultErrorHandler = handler || this._defaultErrorHandler); }; - StateService.prototype.get = function (stateOrName, base) { - var reg = this.router.stateRegistry; - if (arguments.length === 0) - return reg.get(); - return reg.get(stateOrName, base || this.$current); + StateService.prototype.get = function(stateOrName, base) { + var reg = this.router.stateRegistry; + if (arguments.length === 0) return reg.get(); + return reg.get(stateOrName, base || this.$current); }; /** * Lazy loads a state @@ -7329,146 +8175,159 @@ var StateService = /** @class */ (function () { * * @returns a promise to lazy load */ - StateService.prototype.lazyLoad = function (stateOrName, transition) { - var state = this.get(stateOrName); - if (!state || !state.lazyLoad) - throw new Error('Can not lazy load ' + stateOrName); - var currentPath = this.getCurrentPath(); - var target = PathUtils.makeTargetState(this.router.stateRegistry, currentPath); - transition = transition || this.router.transitionService.create(currentPath, target); - return lazyLoadState(transition, state); + StateService.prototype.lazyLoad = function(stateOrName, transition) { + var state = this.get(stateOrName); + if (!state || !state.lazyLoad) throw new Error('Can not lazy load ' + stateOrName); + var currentPath = this.getCurrentPath(); + var target = PathUtils.makeTargetState(this.router.stateRegistry, currentPath); + transition = transition || this.router.transitionService.create(currentPath, target); + return lazyLoadState(transition, state); }; return StateService; -}()); + })(); /** for typedoc */ -/** - * # Transition subsystem - * - * This module contains APIs related to a Transition. - * - * See: - * - [[TransitionService]] - * - [[Transition]] - * - [[HookFn]], [[TransitionHookFn]], [[TransitionStateHookFn]], [[HookMatchCriteria]], [[HookResult]] - * - * @coreapi - * @preferred - * @module transition - */ /** for typedoc */ - -/** - * @internalapi - * @module vanilla - */ -/** */ -/** - * An angular1-like promise api - * - * This object implements four methods similar to the - * [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q) - * - * UI-Router evolved from an angular 1 library to a framework agnostic library. - * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection. - * - * This API provides native ES6 promise support wrapped as a $q-like API. - * Internally, UI-Router uses this $q object to perform promise operations. - * The `angular-ui-router` (ui-router for angular 1) uses the $q API provided by angular. - * - * $q-like promise api - */ -var $q = { + /** + * # Transition subsystem + * + * This module contains APIs related to a Transition. + * + * See: + * - [[TransitionService]] + * - [[Transition]] + * - [[HookFn]], [[TransitionHookFn]], [[TransitionStateHookFn]], [[HookMatchCriteria]], [[HookResult]] + * + * @coreapi + * @preferred + * @module transition + */ /** + * @internalapi + * @module vanilla + */ + /** + * An angular1-like promise api + * + * This object implements four methods similar to the + * [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q) + * + * UI-Router evolved from an angular 1 library to a framework agnostic library. + * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection. + * + * This API provides native ES6 promise support wrapped as a $q-like API. + * Internally, UI-Router uses this $q object to perform promise operations. + * The `angular-ui-router` (ui-router for angular 1) uses the $q API provided by angular. + * + * $q-like promise api + */ + var $q = { /** Normalizes a value as a promise */ - when: function (val) { return new Promise(function (resolve, reject) { return resolve(val); }); }, + when: function(val$$1) { + return new Promise(function(resolve, reject) { + return resolve(val$$1); + }); + }, /** Normalizes a value as a promise rejection */ - reject: function (val) { return new Promise(function (resolve, reject) { reject(val); }); }, + reject: function(val$$1) { + return new Promise(function(resolve, reject) { + reject(val$$1); + }); + }, /** @returns a deferred object, which has `resolve` and `reject` functions */ - defer: function () { - var deferred = {}; - deferred.promise = new Promise(function (resolve, reject) { - deferred.resolve = resolve; - deferred.reject = reject; - }); - return deferred; + defer: function() { + var deferred = {}; + deferred.promise = new Promise(function(resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }); + return deferred; }, /** Like Promise.all(), but also supports object key/promise notation like $q */ - all: function (promises) { - if (isArray(promises)) { - return Promise.all(promises); - } - if (isObject(promises)) { - // Convert promises map to promises array. - // When each promise resolves, map it to a tuple { key: key, val: val } - var chain = Object.keys(promises) - .map(function (key) { return promises[key].then(function (val) { return ({ key: key, val: val }); }); }); - // Then wait for all promises to resolve, and convert them back to an object - return $q.all(chain).then(function (values) { - return values.reduce(function (acc, tuple) { acc[tuple.key] = tuple.val; return acc; }, {}); - }); - } + all: function(promises) { + if (isArray(promises)) { + return Promise.all(promises); + } + if (isObject(promises)) { + // Convert promises map to promises array. + // When each promise resolves, map it to a tuple { key: key, val: val } + var chain = Object.keys(promises).map(function(key) { + return promises[key].then(function(val$$1) { + return { key: key, val: val$$1 }; + }); + }); + // Then wait for all promises to resolve, and convert them back to an object + return $q.all(chain).then(function(values$$1) { + return values$$1.reduce(function(acc, tuple) { + acc[tuple.key] = tuple.val; + return acc; + }, {}); + }); + } }, -}; + }; -/** - * @internalapi - * @module vanilla - */ -/** */ -// globally available injectables -var globals = {}; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; -var ARGUMENT_NAMES = /([^\s,]+)/g; -/** - * A basic angular1-like injector api - * - * This object implements four methods similar to the - * [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector) - * - * UI-Router evolved from an angular 1 library to a framework agnostic library. - * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection. - * - * This object provides a naive implementation of a globally scoped dependency injection system. - * It supports the following DI approaches: - * - * ### Function parameter names - * - * A function's `.toString()` is called, and the parameter names are parsed. - * This only works when the parameter names aren't "mangled" by a minifier such as UglifyJS. - * - * ```js - * function injectedFunction(FooService, BarService) { - * // FooService and BarService are injected - * } - * ``` - * - * ### Function annotation - * - * A function may be annotated with an array of dependency names as the `$inject` property. - * - * ```js - * injectedFunction.$inject = [ 'FooService', 'BarService' ]; - * function injectedFunction(fs, bs) { - * // FooService and BarService are injected as fs and bs parameters - * } - * ``` - * - * ### Array notation - * - * An array provides the names of the dependencies to inject (as strings). - * The function is the last element of the array. - * - * ```js - * [ 'FooService', 'BarService', function (fs, bs) { - * // FooService and BarService are injected as fs and bs parameters - * }] - * ``` - * - * @type {$InjectorLike} - */ -var $injector = { + /** + * @internalapi + * @module vanilla + */ + // globally available injectables + var globals = {}; + var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm; + var ARGUMENT_NAMES = /([^\s,]+)/g; + /** + * A basic angular1-like injector api + * + * This object implements four methods similar to the + * [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector) + * + * UI-Router evolved from an angular 1 library to a framework agnostic library. + * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection. + * + * This object provides a naive implementation of a globally scoped dependency injection system. + * It supports the following DI approaches: + * + * ### Function parameter names + * + * A function's `.toString()` is called, and the parameter names are parsed. + * This only works when the parameter names aren't "mangled" by a minifier such as UglifyJS. + * + * ```js + * function injectedFunction(FooService, BarService) { + * // FooService and BarService are injected + * } + * ``` + * + * ### Function annotation + * + * A function may be annotated with an array of dependency names as the `$inject` property. + * + * ```js + * injectedFunction.$inject = [ 'FooService', 'BarService' ]; + * function injectedFunction(fs, bs) { + * // FooService and BarService are injected as fs and bs parameters + * } + * ``` + * + * ### Array notation + * + * An array provides the names of the dependencies to inject (as strings). + * The function is the last element of the array. + * + * ```js + * [ 'FooService', 'BarService', function (fs, bs) { + * // FooService and BarService are injected as fs and bs parameters + * }] + * ``` + * + * @type {$InjectorLike} + */ + var $injector = { /** Gets an object from DI based on a string token */ - get: function (name) { return globals[name]; }, + get: function(name) { + return globals[name]; + }, /** Returns true if an object named `name` exists in global DI */ - has: function (name) { return $injector.get(name) != null; }, + has: function(name) { + return $injector.get(name) != null; + }, /** * Injects a function * @@ -7476,15 +8335,22 @@ var $injector = { * @param context the function's `this` binding * @param locals An object with additional DI tokens and values, such as `{ someToken: { foo: 1 } }` */ - invoke: function (fn, context, locals) { - var all = extend({}, globals, locals || {}); - var params = $injector.annotate(fn); - var ensureExist = assertPredicate(function (key) { return all.hasOwnProperty(key); }, function (key) { return "DI can't find injectable: '" + key + "'"; }); - var args = params.filter(ensureExist).map(function (x) { return all[x]; }); - if (isFunction(fn)) - return fn.apply(context, args); - else - return fn.slice(-1)[0].apply(context, args); + invoke: function(fn, context, locals) { + var all$$1 = extend({}, globals, locals || {}); + var params = $injector.annotate(fn); + var ensureExist = assertPredicate( + function(key) { + return all$$1.hasOwnProperty(key); + }, + function(key) { + return "DI can't find injectable: '" + key + "'"; + }, + ); + var args = params.filter(ensureExist).map(function(x) { + return all$$1[x]; + }); + if (isFunction(fn)) return fn.apply(context, args); + else return fn.slice(-1)[0].apply(context, args); }, /** * Returns a function's dependencies @@ -7492,195 +8358,240 @@ var $injector = { * Analyzes a function (or array) and returns an array of DI tokens that the function requires. * @return an array of `string`s */ - annotate: function (fn) { - if (!isInjectable(fn)) - throw new Error("Not an injectable function: " + fn); - if (fn && fn.$inject) - return fn.$inject; - if (isArray(fn)) - return fn.slice(0, -1); - var fnStr = fn.toString().replace(STRIP_COMMENTS, ''); - var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); - return result || []; + annotate: function(fn) { + if (!isInjectable(fn)) throw new Error('Not an injectable function: ' + fn); + if (fn && fn.$inject) return fn.$inject; + if (isArray(fn)) return fn.slice(0, -1); + var fnStr = fn.toString().replace(STRIP_COMMENTS, ''); + var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); + return result || []; }, -}; + }; -/** - * @internalapi - * @module vanilla - */ -/** */ -var keyValsToObjectR = function (accum, _a) { - var key = _a[0], val = _a[1]; + /** + * @internalapi + * @module vanilla + */ + var keyValsToObjectR = function(accum, _a) { + var key = _a[0], + val$$1 = _a[1]; if (!accum.hasOwnProperty(key)) { - accum[key] = val; - } - else if (isArray(accum[key])) { - accum[key].push(val); - } - else { - accum[key] = [accum[key], val]; + accum[key] = val$$1; + } else if (isArray(accum[key])) { + accum[key].push(val$$1); + } else { + accum[key] = [accum[key], val$$1]; } return accum; -}; -var getParams = function (queryString) { - return queryString.split('&').filter(identity).map(splitEqual).reduce(keyValsToObjectR, {}); -}; -function parseUrl$1(url) { - var orEmptyString = function (x) { return x || ''; }; - var _a = splitHash(url).map(orEmptyString), beforehash = _a[0], hash = _a[1]; - var _b = splitQuery(beforehash).map(orEmptyString), path = _b[0], search = _b[1]; + }; + var getParams = function(queryString) { + return queryString + .split('&') + .filter(identity) + .map(splitEqual) + .reduce(keyValsToObjectR, {}); + }; + function parseUrl$1(url) { + var orEmptyString = function(x) { + return x || ''; + }; + var _a = splitHash(url).map(orEmptyString), + beforehash = _a[0], + hash = _a[1]; + var _b = splitQuery(beforehash).map(orEmptyString), + path = _b[0], + search = _b[1]; return { path: path, search: search, hash: hash, url: url }; -} -var buildUrl = function (loc) { + } + var buildUrl = function(loc) { var path = loc.path(); var searchObject = loc.search(); var hash = loc.hash(); - var search = Object.keys(searchObject).map(function (key) { + var search = Object.keys(searchObject) + .map(function(key) { var param = searchObject[key]; var vals = isArray(param) ? param : [param]; - return vals.map(function (val) { return key + '=' + val; }); - }).reduce(unnestR, []).join('&'); + return vals.map(function(val$$1) { + return key + '=' + val$$1; + }); + }) + .reduce(unnestR, []) + .join('&'); return path + (search ? '?' + search : '') + (hash ? '#' + hash : ''); -}; -function locationPluginFactory(name, isHtml5, serviceClass, configurationClass) { - return function (uiRouter) { - var service = uiRouter.locationService = new serviceClass(uiRouter); - var configuration = uiRouter.locationConfig = new configurationClass(uiRouter, isHtml5); - function dispose(router) { - router.dispose(service); - router.dispose(configuration); - } - return { name: name, service: service, configuration: configuration, dispose: dispose }; + }; + function locationPluginFactory(name, isHtml5, serviceClass, configurationClass) { + return function(uiRouter) { + var service = (uiRouter.locationService = new serviceClass(uiRouter)); + var configuration = (uiRouter.locationConfig = new configurationClass(uiRouter, isHtml5)); + function dispose(router) { + router.dispose(service); + router.dispose(configuration); + } + return { name: name, service: service, configuration: configuration, dispose: dispose }; }; -} + } /** */ -/** - * @internalapi - * @module vanilla - */ /** */ -/** A base `LocationServices` */ -var BaseLocationServices = /** @class */ (function () { + /** + * @internalapi + * @module vanilla + */ /** A base `LocationServices` */ + var BaseLocationServices = /** @class */ (function() { function BaseLocationServices(router, fireAfterUpdate) { - var _this = this; - this.fireAfterUpdate = fireAfterUpdate; - this._listeners = []; - this._listener = function (evt) { return _this._listeners.forEach(function (cb) { return cb(evt); }); }; - this.hash = function () { return parseUrl$1(_this._get()).hash; }; - this.path = function () { return parseUrl$1(_this._get()).path; }; - this.search = function () { return getParams(parseUrl$1(_this._get()).search); }; - this._location = root.location; - this._history = root.history; + var _this = this; + this.fireAfterUpdate = fireAfterUpdate; + this._listeners = []; + this._listener = function(evt) { + return _this._listeners.forEach(function(cb) { + return cb(evt); + }); + }; + this.hash = function() { + return parseUrl$1(_this._get()).hash; + }; + this.path = function() { + return parseUrl$1(_this._get()).path; + }; + this.search = function() { + return getParams(parseUrl$1(_this._get()).search); + }; + this._location = root.location; + this._history = root.history; } - BaseLocationServices.prototype.url = function (url, replace) { - if (replace === void 0) { replace = true; } - if (isDefined(url) && url !== this._get()) { - this._set(null, null, url, replace); - if (this.fireAfterUpdate) { - this._listeners.forEach(function (cb) { return cb({ url: url }); }); - } + BaseLocationServices.prototype.url = function(url, replace) { + if (replace === void 0) { + replace = true; + } + if (isDefined(url) && url !== this._get()) { + this._set(null, null, url, replace); + if (this.fireAfterUpdate) { + this._listeners.forEach(function(cb) { + return cb({ url: url }); + }); } - return buildUrl(this); + } + return buildUrl(this); }; - BaseLocationServices.prototype.onChange = function (cb) { - var _this = this; - this._listeners.push(cb); - return function () { return removeFrom(_this._listeners, cb); }; + BaseLocationServices.prototype.onChange = function(cb) { + var _this = this; + this._listeners.push(cb); + return function() { + return removeFrom(_this._listeners, cb); + }; }; - BaseLocationServices.prototype.dispose = function (router) { - deregAll(this._listeners); + BaseLocationServices.prototype.dispose = function(router) { + deregAll(this._listeners); }; return BaseLocationServices; -}()); + })(); -var __extends = (undefined && undefined.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { + var __extends = + (undefined && undefined.__extends) || + (function() { + var extendStatics = + Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && + function(d, b) { + d.__proto__ = b; + }) || + function(d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + return function(d, b) { extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -/** - * @internalapi - * @module vanilla - */ -/** */ -/** A `LocationServices` that uses the browser hash "#" to get/set the current location */ -var HashLocationService = /** @class */ (function (_super) { + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __()); + }; + })(); + /** A `LocationServices` that uses the browser hash "#" to get/set the current location */ + var HashLocationService = /** @class */ (function(_super) { __extends(HashLocationService, _super); function HashLocationService(router) { - var _this = _super.call(this, router, false) || this; - root.addEventListener('hashchange', _this._listener, false); - return _this; + var _this = _super.call(this, router, false) || this; + root.addEventListener('hashchange', _this._listener, false); + return _this; } - HashLocationService.prototype._get = function () { - return trimHashVal(this._location.hash); + HashLocationService.prototype._get = function() { + return trimHashVal(this._location.hash); }; - HashLocationService.prototype._set = function (state, title, url, replace) { - this._location.hash = url; + HashLocationService.prototype._set = function(state, title, url, replace) { + this._location.hash = url; }; - HashLocationService.prototype.dispose = function (router) { - _super.prototype.dispose.call(this, router); - root.removeEventListener('hashchange', this._listener); + HashLocationService.prototype.dispose = function(router) { + _super.prototype.dispose.call(this, router); + root.removeEventListener('hashchange', this._listener); }; return HashLocationService; -}(BaseLocationServices)); + })(BaseLocationServices); -var __extends$1 = (undefined && undefined.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { + var __extends$1 = + (undefined && undefined.__extends) || + (function() { + var extendStatics = + Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && + function(d, b) { + d.__proto__ = b; + }) || + function(d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + return function(d, b) { extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -/** - * @internalapi - * @module vanilla - */ -/** */ -/** A `LocationServices` that gets/sets the current location from an in-memory object */ -var MemoryLocationService = /** @class */ (function (_super) { + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __()); + }; + })(); + /** A `LocationServices` that gets/sets the current location from an in-memory object */ + var MemoryLocationService = /** @class */ (function(_super) { __extends$1(MemoryLocationService, _super); function MemoryLocationService(router) { - return _super.call(this, router, true) || this; + return _super.call(this, router, true) || this; } - MemoryLocationService.prototype._get = function () { - return this._url; + MemoryLocationService.prototype._get = function() { + return this._url; }; - MemoryLocationService.prototype._set = function (state, title, url, replace) { - this._url = url; + MemoryLocationService.prototype._set = function(state, title, url, replace) { + this._url = url; }; return MemoryLocationService; -}(BaseLocationServices)); + })(BaseLocationServices); -var __extends$2 = (undefined && undefined.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return function (d, b) { + var __extends$2 = + (undefined && undefined.__extends) || + (function() { + var extendStatics = + Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && + function(d, b) { + d.__proto__ = b; + }) || + function(d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + return function(d, b) { extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -/** - * A `LocationServices` that gets/sets the current location using the browser's `location` and `history` apis - * - * Uses `history.pushState` and `history.replaceState` - */ -var PushStateLocationService = /** @class */ (function (_super) { + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __()); + }; + })(); + /** + * A `LocationServices` that gets/sets the current location using the browser's `location` and `history` apis + * + * Uses `history.pushState` and `history.replaceState` + */ + var PushStateLocationService = /** @class */ (function(_super) { __extends$2(PushStateLocationService, _super); function PushStateLocationService(router) { - var _this = _super.call(this, router, true) || this; - _this._config = router.urlService.config; - root.addEventListener('popstate', _this._listener, false); - return _this; + var _this = _super.call(this, router, true) || this; + _this._config = router.urlService.config; + root.addEventListener('popstate', _this._listener, false); + return _this; } /** * Gets the base prefix without: @@ -7698,432 +8609,506 @@ var PushStateLocationService = /** @class */ (function (_super) { * * See: https://html.spec.whatwg.org/dev/semantics.html#the-base-element */ - PushStateLocationService.prototype._getBasePrefix = function () { - return stripLastPathElement(this._config.baseHref()); + PushStateLocationService.prototype._getBasePrefix = function() { + return stripLastPathElement(this._config.baseHref()); }; - PushStateLocationService.prototype._get = function () { - var _a = this._location, pathname = _a.pathname, hash = _a.hash, search = _a.search; - search = splitQuery(search)[1]; // strip ? if found - hash = splitHash(hash)[1]; // strip # if found - var basePrefix = this._getBasePrefix(); - var exactBaseHrefMatch = pathname === this._config.baseHref(); - var startsWithBase = pathname.substr(0, basePrefix.length) === basePrefix; - pathname = exactBaseHrefMatch ? '/' : startsWithBase ? pathname.substring(basePrefix.length) : pathname; - return pathname + (search ? '?' + search : '') + (hash ? '#' + hash : ''); + PushStateLocationService.prototype._get = function() { + var _a = this._location, + pathname = _a.pathname, + hash = _a.hash, + search = _a.search; + search = splitQuery(search)[1]; // strip ? if found + hash = splitHash(hash)[1]; // strip # if found + var basePrefix = this._getBasePrefix(); + var exactBaseHrefMatch = pathname === this._config.baseHref(); + var startsWithBase = pathname.substr(0, basePrefix.length) === basePrefix; + pathname = exactBaseHrefMatch ? '/' : startsWithBase ? pathname.substring(basePrefix.length) : pathname; + return pathname + (search ? '?' + search : '') + (hash ? '#' + hash : ''); }; - PushStateLocationService.prototype._set = function (state, title, url, replace) { - var basePrefix = this._getBasePrefix(); - var slash = url && url[0] !== '/' ? '/' : ''; - var fullUrl = (url === '' || url === '/') ? this._config.baseHref() : basePrefix + slash + url; - if (replace) { - this._history.replaceState(state, title, fullUrl); - } - else { - this._history.pushState(state, title, fullUrl); - } + PushStateLocationService.prototype._set = function(state, title, url, replace) { + var basePrefix = this._getBasePrefix(); + var slash = url && url[0] !== '/' ? '/' : ''; + var fullUrl = url === '' || url === '/' ? this._config.baseHref() : basePrefix + slash + url; + if (replace) { + this._history.replaceState(state, title, fullUrl); + } else { + this._history.pushState(state, title, fullUrl); + } }; - PushStateLocationService.prototype.dispose = function (router) { - _super.prototype.dispose.call(this, router); - root.removeEventListener('popstate', this._listener); + PushStateLocationService.prototype.dispose = function(router) { + _super.prototype.dispose.call(this, router); + root.removeEventListener('popstate', this._listener); }; return PushStateLocationService; -}(BaseLocationServices)); + })(BaseLocationServices); -/** A `LocationConfig` mock that gets/sets all config from an in-memory object */ -var MemoryLocationConfig = /** @class */ (function () { + /** A `LocationConfig` mock that gets/sets all config from an in-memory object */ + var MemoryLocationConfig = /** @class */ (function() { function MemoryLocationConfig() { - var _this = this; - this.dispose = noop; - this._baseHref = ''; - this._port = 80; - this._protocol = 'http'; - this._host = 'localhost'; - this._hashPrefix = ''; - this.port = function () { return _this._port; }; - this.protocol = function () { return _this._protocol; }; - this.host = function () { return _this._host; }; - this.baseHref = function () { return _this._baseHref; }; - this.html5Mode = function () { return false; }; - this.hashPrefix = function (newval) { return isDefined(newval) ? _this._hashPrefix = newval : _this._hashPrefix; }; + var _this = this; + this.dispose = noop; + this._baseHref = ''; + this._port = 80; + this._protocol = 'http'; + this._host = 'localhost'; + this._hashPrefix = ''; + this.port = function() { + return _this._port; + }; + this.protocol = function() { + return _this._protocol; + }; + this.host = function() { + return _this._host; + }; + this.baseHref = function() { + return _this._baseHref; + }; + this.html5Mode = function() { + return false; + }; + this.hashPrefix = function(newval) { + return isDefined(newval) ? (_this._hashPrefix = newval) : _this._hashPrefix; + }; } return MemoryLocationConfig; -}()); + })(); -/** - * @internalapi - * @module vanilla - */ -/** */ -/** A `LocationConfig` that delegates to the browser's `location` object */ -var BrowserLocationConfig = /** @class */ (function () { + /** + * @internalapi + * @module vanilla + */ + /** A `LocationConfig` that delegates to the browser's `location` object */ + var BrowserLocationConfig = /** @class */ (function() { function BrowserLocationConfig(router, _isHtml5) { - if (_isHtml5 === void 0) { _isHtml5 = false; } - this._isHtml5 = _isHtml5; - this._baseHref = undefined; - this._hashPrefix = ''; + if (_isHtml5 === void 0) { + _isHtml5 = false; + } + this._isHtml5 = _isHtml5; + this._baseHref = undefined; + this._hashPrefix = ''; } - BrowserLocationConfig.prototype.port = function () { - if (location.port) { - return Number(location.port); - } - return this.protocol() === 'https' ? 443 : 80; + BrowserLocationConfig.prototype.port = function() { + if (location.port) { + return Number(location.port); + } + return this.protocol() === 'https' ? 443 : 80; }; - BrowserLocationConfig.prototype.protocol = function () { - return location.protocol.replace(/:/g, ''); + BrowserLocationConfig.prototype.protocol = function() { + return location.protocol.replace(/:/g, ''); }; - BrowserLocationConfig.prototype.host = function () { - return location.hostname; + BrowserLocationConfig.prototype.host = function() { + return location.hostname; }; - BrowserLocationConfig.prototype.html5Mode = function () { - return this._isHtml5; + BrowserLocationConfig.prototype.html5Mode = function() { + return this._isHtml5; }; - BrowserLocationConfig.prototype.hashPrefix = function (newprefix) { - return isDefined(newprefix) ? this._hashPrefix = newprefix : this._hashPrefix; + BrowserLocationConfig.prototype.hashPrefix = function(newprefix) { + return isDefined(newprefix) ? (this._hashPrefix = newprefix) : this._hashPrefix; }; - BrowserLocationConfig.prototype.baseHref = function (href) { - return isDefined(href) ? this._baseHref = href : - isDefined(this._baseHref) ? this._baseHref : this.applyDocumentBaseHref(); + BrowserLocationConfig.prototype.baseHref = function(href) { + return isDefined(href) + ? (this._baseHref = href) + : isDefined(this._baseHref) + ? this._baseHref + : this.applyDocumentBaseHref(); }; - BrowserLocationConfig.prototype.applyDocumentBaseHref = function () { - var baseTag = document.getElementsByTagName('base')[0]; - return this._baseHref = baseTag ? baseTag.href.substr(location.origin.length) : location.pathname || '/'; + BrowserLocationConfig.prototype.applyDocumentBaseHref = function() { + var baseTag = document.getElementsByTagName('base')[0]; + return (this._baseHref = baseTag ? baseTag.href.substr(location.origin.length) : location.pathname || '/'); }; - BrowserLocationConfig.prototype.dispose = function () { }; + BrowserLocationConfig.prototype.dispose = function() {}; return BrowserLocationConfig; -}()); + })(); -/** - * @internalapi - * @module vanilla - */ -/** */ -function servicesPlugin(router) { + /** + * @internalapi + * @module vanilla + */ + function servicesPlugin(router) { services.$injector = $injector; services.$q = $q; - return { name: 'vanilla.services', $q: $q, $injector: $injector, dispose: function () { return null; } }; -} -/** A `UIRouterPlugin` uses the browser hash to get/set the current location */ -var hashLocationPlugin = locationPluginFactory('vanilla.hashBangLocation', false, HashLocationService, BrowserLocationConfig); -/** A `UIRouterPlugin` that gets/sets the current location using the browser's `location` and `history` apis */ -var pushStateLocationPlugin = locationPluginFactory('vanilla.pushStateLocation', true, PushStateLocationService, BrowserLocationConfig); -/** A `UIRouterPlugin` that gets/sets the current location from an in-memory object */ -var memoryLocationPlugin = locationPluginFactory('vanilla.memoryLocation', false, MemoryLocationService, MemoryLocationConfig); - -/** - * @internalapi - * @module vanilla - */ -/** */ - -/** - * # Core classes and interfaces - * - * The classes and interfaces that are core to ui-router and do not belong - * to a more specific subsystem (such as resolve). - * - * @coreapi - * @preferred - * @module core - */ /** for typedoc */ -/** @internalapi */ -var UIRouterPluginBase = /** @class */ (function () { - function UIRouterPluginBase() { - } - UIRouterPluginBase.prototype.dispose = function (router) { }; - return UIRouterPluginBase; -}()); - -/** - * @coreapi - * @module common - */ /** */ - - - -var index = Object.freeze({ - root: root, - fromJson: fromJson, - toJson: toJson, - forEach: forEach, - extend: extend, - equals: equals, - identity: identity, - noop: noop, - createProxyFunctions: createProxyFunctions, - inherit: inherit, - inArray: inArray, - _inArray: _inArray, - removeFrom: removeFrom, - _removeFrom: _removeFrom, - pushTo: pushTo, - _pushTo: _pushTo, - deregAll: deregAll, - defaults: defaults, - mergeR: mergeR, - ancestors: ancestors, - pick: pick, - omit: omit, - pluck: pluck, - filter: filter, - find: find, - mapObj: mapObj, - map: map, - values: values, - allTrueR: allTrueR, - anyTrueR: anyTrueR, - unnestR: unnestR, - flattenR: flattenR, - pushR: pushR, - uniqR: uniqR, - unnest: unnest, - flatten: flatten, - assertPredicate: assertPredicate, - assertMap: assertMap, - assertFn: assertFn, - pairs: pairs, - arrayTuples: arrayTuples, - applyPairs: applyPairs, - tail: tail, - copy: copy, - _extend: _extend, - silenceUncaughtInPromise: silenceUncaughtInPromise, - silentRejection: silentRejection, - notImplemented: notImplemented, - services: services, - Glob: Glob, - curry: curry, - compose: compose, - pipe: pipe, - prop: prop, - propEq: propEq, - parse: parse, - not: not, - and: and, - or: or, - all: all, - any: any, - is: is, - eq: eq, - val: val, - invoke: invoke, - pattern: pattern, - isUndefined: isUndefined, - isDefined: isDefined, - isNull: isNull, - isNullOrUndefined: isNullOrUndefined, - isFunction: isFunction, - isNumber: isNumber, - isString: isString, - isObject: isObject, - isArray: isArray, - isDate: isDate, - isRegExp: isRegExp, - isState: isState, - isInjectable: isInjectable, - isPromise: isPromise, - Queue: Queue, - maxLength: maxLength, - padString: padString, - kebobString: kebobString, - functionToString: functionToString, - fnToString: fnToString, - stringify: stringify, - beforeAfterSubstr: beforeAfterSubstr, - hostRegex: hostRegex, - stripLastPathElement: stripLastPathElement, - splitHash: splitHash, - splitQuery: splitQuery, - splitEqual: splitEqual, - trimHashVal: trimHashVal, - splitOnDelim: splitOnDelim, - joinNeighborsR: joinNeighborsR, - get Category () { return exports.Category; }, - Trace: Trace, - trace: trace, - get DefType () { return exports.DefType; }, - Param: Param, - ParamTypes: ParamTypes, - StateParams: StateParams, - ParamType: ParamType, - PathNode: PathNode, - PathUtils: PathUtils, - resolvePolicies: resolvePolicies, - defaultResolvePolicy: defaultResolvePolicy, - Resolvable: Resolvable, - NATIVE_INJECTOR_TOKEN: NATIVE_INJECTOR_TOKEN, - ResolveContext: ResolveContext, - resolvablesBuilder: resolvablesBuilder, - StateBuilder: StateBuilder, - StateObject: StateObject, - StateMatcher: StateMatcher, - StateQueueManager: StateQueueManager, - StateRegistry: StateRegistry, - StateService: StateService, - TargetState: TargetState, - get TransitionHookPhase () { return exports.TransitionHookPhase; }, - get TransitionHookScope () { return exports.TransitionHookScope; }, - HookBuilder: HookBuilder, - matchState: matchState, - RegisteredHook: RegisteredHook, - makeEvent: makeEvent, - get RejectType () { return exports.RejectType; }, - Rejection: Rejection, - Transition: Transition, - TransitionHook: TransitionHook, - TransitionEventType: TransitionEventType, - defaultTransOpts: defaultTransOpts, - TransitionService: TransitionService, - UrlMatcher: UrlMatcher, - UrlMatcherFactory: UrlMatcherFactory, - UrlRouter: UrlRouter, - UrlRuleFactory: UrlRuleFactory, - BaseUrlRule: BaseUrlRule, - UrlService: UrlService, - ViewService: ViewService, - UIRouterGlobals: UIRouterGlobals, - UIRouter: UIRouter, - $q: $q, - $injector: $injector, - BaseLocationServices: BaseLocationServices, - HashLocationService: HashLocationService, - MemoryLocationService: MemoryLocationService, - PushStateLocationService: PushStateLocationService, - MemoryLocationConfig: MemoryLocationConfig, - BrowserLocationConfig: BrowserLocationConfig, - keyValsToObjectR: keyValsToObjectR, - getParams: getParams, - parseUrl: parseUrl$1, - buildUrl: buildUrl, - locationPluginFactory: locationPluginFactory, - servicesPlugin: servicesPlugin, - hashLocationPlugin: hashLocationPlugin, - pushStateLocationPlugin: pushStateLocationPlugin, - memoryLocationPlugin: memoryLocationPlugin, - UIRouterPluginBase: UIRouterPluginBase -}); - -function getNg1ViewConfigFactory() { - var templateFactory = null; - return function (path, view) { - templateFactory = templateFactory || services.$injector.get('$templateFactory'); - return [new Ng1ViewConfig(path, view, templateFactory)]; + return { + name: 'vanilla.services', + $q: $q, + $injector: $injector, + dispose: function() { + return null; + }, }; -} -var hasAnyKey = function (keys, obj) { - return keys.reduce(function (acc, key) { return acc || isDefined(obj[key]); }, false); -}; -/** - * This is a [[StateBuilder.builder]] function for angular1 `views`. - * - * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder - * handles the `views` property with logic specific to @uirouter/angularjs (ng1). - * - * If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object - * and applies the state-level configuration to a view named `$default`. - */ -function ng1ViewsBuilder(state) { + } + /** A `UIRouterPlugin` uses the browser hash to get/set the current location */ + var hashLocationPlugin = locationPluginFactory( + 'vanilla.hashBangLocation', + false, + HashLocationService, + BrowserLocationConfig, + ); + /** A `UIRouterPlugin` that gets/sets the current location using the browser's `location` and `history` apis */ + var pushStateLocationPlugin = locationPluginFactory( + 'vanilla.pushStateLocation', + true, + PushStateLocationService, + BrowserLocationConfig, + ); + /** A `UIRouterPlugin` that gets/sets the current location from an in-memory object */ + var memoryLocationPlugin = locationPluginFactory( + 'vanilla.memoryLocation', + false, + MemoryLocationService, + MemoryLocationConfig, + ); /** for typedoc */ + + /** + * @internalapi + * @module vanilla + */ + + /** + * # Core classes and interfaces + * + * The classes and interfaces that are core to ui-router and do not belong + * to a more specific subsystem (such as resolve). + * + * @coreapi + * @preferred + * @module core + */ /** @internalapi */ + var UIRouterPluginBase = /** @class */ (function() { + function UIRouterPluginBase() {} + UIRouterPluginBase.prototype.dispose = function(router) {}; + return UIRouterPluginBase; + })(); /** */ + + /** + * @coreapi + * @module common + */ var index = /*#__PURE__*/ Object.freeze({ + root: root, + fromJson: fromJson, + toJson: toJson, + forEach: forEach, + extend: extend, + equals: equals, + identity: identity, + noop: noop, + createProxyFunctions: createProxyFunctions, + inherit: inherit, + inArray: inArray, + _inArray: _inArray, + removeFrom: removeFrom, + _removeFrom: _removeFrom, + pushTo: pushTo, + _pushTo: _pushTo, + deregAll: deregAll, + defaults: defaults, + mergeR: mergeR, + ancestors: ancestors, + pick: pick, + omit: omit, + pluck: pluck, + filter: filter, + find: find, + mapObj: mapObj, + map: map, + values: values, + allTrueR: allTrueR, + anyTrueR: anyTrueR, + unnestR: unnestR, + flattenR: flattenR, + pushR: pushR, + uniqR: uniqR, + unnest: unnest, + flatten: flatten, + assertPredicate: assertPredicate, + assertMap: assertMap, + assertFn: assertFn, + pairs: pairs, + arrayTuples: arrayTuples, + applyPairs: applyPairs, + tail: tail, + copy: copy, + _extend: _extend, + silenceUncaughtInPromise: silenceUncaughtInPromise, + silentRejection: silentRejection, + notImplemented: notImplemented, + services: services, + Glob: Glob, + curry: curry, + compose: compose, + pipe: pipe, + prop: prop, + propEq: propEq, + parse: parse, + not: not, + and: and, + or: or, + all: all, + any: any, + is: is, + eq: eq, + val: val, + invoke: invoke, + pattern: pattern, + isUndefined: isUndefined, + isDefined: isDefined, + isNull: isNull, + isNullOrUndefined: isNullOrUndefined, + isFunction: isFunction, + isNumber: isNumber, + isString: isString, + isObject: isObject, + isArray: isArray, + isDate: isDate, + isRegExp: isRegExp, + isState: isState, + isInjectable: isInjectable, + isPromise: isPromise, + Queue: Queue, + maxLength: maxLength, + padString: padString, + kebobString: kebobString, + functionToString: functionToString, + fnToString: fnToString, + stringify: stringify, + beforeAfterSubstr: beforeAfterSubstr, + hostRegex: hostRegex, + stripLastPathElement: stripLastPathElement, + splitHash: splitHash, + splitQuery: splitQuery, + splitEqual: splitEqual, + trimHashVal: trimHashVal, + splitOnDelim: splitOnDelim, + joinNeighborsR: joinNeighborsR, + get Category() { + return exports.Category; + }, + Trace: Trace, + trace: trace, + get DefType() { + return exports.DefType; + }, + Param: Param, + ParamTypes: ParamTypes, + StateParams: StateParams, + ParamType: ParamType, + PathNode: PathNode, + PathUtils: PathUtils, + resolvePolicies: resolvePolicies, + defaultResolvePolicy: defaultResolvePolicy, + Resolvable: Resolvable, + NATIVE_INJECTOR_TOKEN: NATIVE_INJECTOR_TOKEN, + ResolveContext: ResolveContext, + resolvablesBuilder: resolvablesBuilder, + StateBuilder: StateBuilder, + StateObject: StateObject, + StateMatcher: StateMatcher, + StateQueueManager: StateQueueManager, + StateRegistry: StateRegistry, + StateService: StateService, + TargetState: TargetState, + get TransitionHookPhase() { + return exports.TransitionHookPhase; + }, + get TransitionHookScope() { + return exports.TransitionHookScope; + }, + HookBuilder: HookBuilder, + matchState: matchState, + RegisteredHook: RegisteredHook, + makeEvent: makeEvent, + get RejectType() { + return exports.RejectType; + }, + Rejection: Rejection, + Transition: Transition, + TransitionHook: TransitionHook, + TransitionEventType: TransitionEventType, + defaultTransOpts: defaultTransOpts, + TransitionService: TransitionService, + UrlMatcher: UrlMatcher, + UrlMatcherFactory: UrlMatcherFactory, + UrlRouter: UrlRouter, + UrlRuleFactory: UrlRuleFactory, + BaseUrlRule: BaseUrlRule, + UrlService: UrlService, + ViewService: ViewService, + UIRouterGlobals: UIRouterGlobals, + UIRouter: UIRouter, + $q: $q, + $injector: $injector, + BaseLocationServices: BaseLocationServices, + HashLocationService: HashLocationService, + MemoryLocationService: MemoryLocationService, + PushStateLocationService: PushStateLocationService, + MemoryLocationConfig: MemoryLocationConfig, + BrowserLocationConfig: BrowserLocationConfig, + keyValsToObjectR: keyValsToObjectR, + getParams: getParams, + parseUrl: parseUrl$1, + buildUrl: buildUrl, + locationPluginFactory: locationPluginFactory, + servicesPlugin: servicesPlugin, + hashLocationPlugin: hashLocationPlugin, + pushStateLocationPlugin: pushStateLocationPlugin, + memoryLocationPlugin: memoryLocationPlugin, + UIRouterPluginBase: UIRouterPluginBase, + }); + + function getNg1ViewConfigFactory() { + var templateFactory = null; + return function(path, view) { + templateFactory = templateFactory || services.$injector.get('$templateFactory'); + return [new Ng1ViewConfig(path, view, templateFactory)]; + }; + } + var hasAnyKey = function(keys, obj) { + return keys.reduce(function(acc, key) { + return acc || isDefined(obj[key]); + }, false); + }; + /** + * This is a [[StateBuilder.builder]] function for angular1 `views`. + * + * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder + * handles the `views` property with logic specific to @uirouter/angularjs (ng1). + * + * If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object + * and applies the state-level configuration to a view named `$default`. + */ + function ng1ViewsBuilder(state) { // Do not process root state - if (!state.parent) - return {}; - var tplKeys = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'], ctrlKeys = ['controller', 'controllerProvider', 'controllerAs', 'resolveAs'], compKeys = ['component', 'bindings', 'componentProvider'], nonCompKeys = tplKeys.concat(ctrlKeys), allViewKeys = compKeys.concat(nonCompKeys); + if (!state.parent) return {}; + var tplKeys = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'], + ctrlKeys = ['controller', 'controllerProvider', 'controllerAs', 'resolveAs'], + compKeys = ['component', 'bindings', 'componentProvider'], + nonCompKeys = tplKeys.concat(ctrlKeys), + allViewKeys = compKeys.concat(nonCompKeys); // Do not allow a state to have both state-level props and also a `views: {}` property. // A state without a `views: {}` property can declare properties for the `$default` view as properties of the state. // However, the `$default` approach should not be mixed with a separate `views: ` block. if (isDefined(state.views) && hasAnyKey(allViewKeys, state)) { - throw new Error("State '" + state.name + "' has a 'views' object. " + - "It cannot also have \"view properties\" at the state level. " + - "Move the following properties into a view (in the 'views' object): " + - (" " + allViewKeys.filter(function (key) { return isDefined(state[key]); }).join(', '))); + throw new Error( + "State '" + + state.name + + "' has a 'views' object. " + + 'It cannot also have "view properties" at the state level. ' + + "Move the following properties into a view (in the 'views' object): " + + (' ' + + allViewKeys + .filter(function(key) { + return isDefined(state[key]); + }) + .join(', ')), + ); } - var views = {}, viewsObject = state.views || { '$default': pick(state, allViewKeys) }; - forEach(viewsObject, function (config, name) { - // Account for views: { "": { template... } } - name = name || '$default'; - // Account for views: { header: "headerComponent" } - if (isString(config)) - config = { component: config }; - // Make a shallow copy of the config object - config = extend({}, config); - // Do not allow a view to mix props for component-style view with props for template/controller-style view - if (hasAnyKey(compKeys, config) && hasAnyKey(nonCompKeys, config)) { - throw new Error("Cannot combine: " + compKeys.join('|') + " with: " + nonCompKeys.join('|') + " in stateview: '" + name + "@" + state.name + "'"); - } - config.resolveAs = config.resolveAs || '$resolve'; - config.$type = 'ng1'; - config.$context = state; - config.$name = name; - var normalized = ViewService.normalizeUIViewTarget(config.$context, config.$name); - config.$uiViewName = normalized.uiViewName; - config.$uiViewContextAnchor = normalized.uiViewContextAnchor; - views[name] = config; + var views = {}, + viewsObject = state.views || { $default: pick(state, allViewKeys) }; + forEach(viewsObject, function(config, name) { + // Account for views: { "": { template... } } + name = name || '$default'; + // Account for views: { header: "headerComponent" } + if (isString(config)) config = { component: config }; + // Make a shallow copy of the config object + config = extend({}, config); + // Do not allow a view to mix props for component-style view with props for template/controller-style view + if (hasAnyKey(compKeys, config) && hasAnyKey(nonCompKeys, config)) { + throw new Error( + 'Cannot combine: ' + + compKeys.join('|') + + ' with: ' + + nonCompKeys.join('|') + + " in stateview: '" + + name + + '@' + + state.name + + "'", + ); + } + config.resolveAs = config.resolveAs || '$resolve'; + config.$type = 'ng1'; + config.$context = state; + config.$name = name; + var normalized = ViewService.normalizeUIViewTarget(config.$context, config.$name); + config.$uiViewName = normalized.uiViewName; + config.$uiViewContextAnchor = normalized.uiViewContextAnchor; + views[name] = config; }); return views; -} -var id$1 = 0; -var Ng1ViewConfig = /** @class */ (function () { + } + var id$1 = 0; + var Ng1ViewConfig = /** @class */ (function() { function Ng1ViewConfig(path, viewDecl, factory) { - var _this = this; - this.path = path; - this.viewDecl = viewDecl; - this.factory = factory; - this.$id = id$1++; - this.loaded = false; - this.getTemplate = function (uiView, context) { - return _this.component ? _this.factory.makeComponentTemplate(uiView, context, _this.component, _this.viewDecl.bindings) : _this.template; - }; + var _this = this; + this.path = path; + this.viewDecl = viewDecl; + this.factory = factory; + this.$id = id$1++; + this.loaded = false; + this.getTemplate = function(uiView, context) { + return _this.component + ? _this.factory.makeComponentTemplate(uiView, context, _this.component, _this.viewDecl.bindings) + : _this.template; + }; } - Ng1ViewConfig.prototype.load = function () { - var _this = this; - var $q = services.$q; - var context = new ResolveContext(this.path); - var params = this.path.reduce(function (acc, node) { return extend(acc, node.paramValues); }, {}); - var promises = { - template: $q.when(this.factory.fromConfig(this.viewDecl, params, context)), - controller: $q.when(this.getController(context)), - }; - return $q.all(promises).then(function (results) { - trace.traceViewServiceEvent('Loaded', _this); - _this.controller = results.controller; - extend(_this, results.template); // Either { template: "tpl" } or { component: "cmpName" } - return _this; - }); + Ng1ViewConfig.prototype.load = function() { + var _this = this; + var $q$$1 = services.$q; + var context = new ResolveContext(this.path); + var params = this.path.reduce(function(acc, node) { + return extend(acc, node.paramValues); + }, {}); + var promises = { + template: $q$$1.when(this.factory.fromConfig(this.viewDecl, params, context)), + controller: $q$$1.when(this.getController(context)), + }; + return $q$$1.all(promises).then(function(results) { + trace.traceViewServiceEvent('Loaded', _this); + _this.controller = results.controller; + extend(_this, results.template); // Either { template: "tpl" } or { component: "cmpName" } + return _this; + }); }; /** * Gets the controller for a view configuration. * * @returns {Function|Promise.} Returns a controller, or a promise that resolves to a controller. */ - Ng1ViewConfig.prototype.getController = function (context) { - var provider = this.viewDecl.controllerProvider; - if (!isInjectable(provider)) - return this.viewDecl.controller; - var deps = services.$injector.annotate(provider); - var providerFn = isArray(provider) ? tail(provider) : provider; - var resolvable = new Resolvable('', providerFn, deps); - return resolvable.get(context); + Ng1ViewConfig.prototype.getController = function(context) { + var provider = this.viewDecl.controllerProvider; + if (!isInjectable(provider)) return this.viewDecl.controller; + var deps = services.$injector.annotate(provider); + var providerFn = isArray(provider) ? tail(provider) : provider; + var resolvable = new Resolvable('', providerFn, deps); + return resolvable.get(context); }; return Ng1ViewConfig; -}()); + })(); -/** @module view */ -/** for typedoc */ -/** - * Service which manages loading of templates from a ViewConfig. - */ -var TemplateFactory = /** @class */ (function () { + /** @module view */ + /** + * Service which manages loading of templates from a ViewConfig. + */ + var TemplateFactory = /** @class */ (function() { function TemplateFactory() { - var _this = this; - /** @hidden */ this._useHttp = ng.version.minor < 3; - /** @hidden */ this.$get = ['$http', '$templateCache', '$injector', function ($http, $templateCache, $injector) { - _this.$templateRequest = $injector.has && $injector.has('$templateRequest') && $injector.get('$templateRequest'); - _this.$http = $http; - _this.$templateCache = $templateCache; - return _this; - }]; + var _this = this; + /** @hidden */ this._useHttp = ng.version.minor < 3; + /** @hidden */ this.$get = [ + '$http', + '$templateCache', + '$injector', + function($http, $templateCache, $injector$$1) { + _this.$templateRequest = + $injector$$1.has && $injector$$1.has('$templateRequest') && $injector$$1.get('$templateRequest'); + _this.$http = $http; + _this.$templateCache = $templateCache; + return _this; + }, + ]; } /** @hidden */ - TemplateFactory.prototype.useHttpService = function (value) { - this._useHttp = value; + TemplateFactory.prototype.useHttpService = function(value) { + this._useHttp = value; }; /** * Creates a template from a configuration object. @@ -8138,16 +9123,29 @@ var TemplateFactory = /** @class */ (function () { * @return {string|object} The template html as a string, or a promise for * that string,or `null` if no template is configured. */ - TemplateFactory.prototype.fromConfig = function (config, params, context) { - var defaultTemplate = ''; - var asTemplate = function (result) { return services.$q.when(result).then(function (str) { return ({ template: str }); }); }; - var asComponent = function (result) { return services.$q.when(result).then(function (str) { return ({ component: str }); }); }; - return (isDefined(config.template) ? asTemplate(this.fromString(config.template, params)) : - isDefined(config.templateUrl) ? asTemplate(this.fromUrl(config.templateUrl, params)) : - isDefined(config.templateProvider) ? asTemplate(this.fromProvider(config.templateProvider, params, context)) : - isDefined(config.component) ? asComponent(config.component) : - isDefined(config.componentProvider) ? asComponent(this.fromComponentProvider(config.componentProvider, params, context)) : - asTemplate(defaultTemplate)); + TemplateFactory.prototype.fromConfig = function(config, params, context) { + var defaultTemplate = ''; + var asTemplate = function(result) { + return services.$q.when(result).then(function(str) { + return { template: str }; + }); + }; + var asComponent = function(result) { + return services.$q.when(result).then(function(str) { + return { component: str }; + }); + }; + return isDefined(config.template) + ? asTemplate(this.fromString(config.template, params)) + : isDefined(config.templateUrl) + ? asTemplate(this.fromUrl(config.templateUrl, params)) + : isDefined(config.templateProvider) + ? asTemplate(this.fromProvider(config.templateProvider, params, context)) + : isDefined(config.component) + ? asComponent(config.component) + : isDefined(config.componentProvider) + ? asComponent(this.fromComponentProvider(config.componentProvider, params, context)) + : asTemplate(defaultTemplate); }; /** * Creates a template from a string or a function returning a string. @@ -8158,8 +9156,8 @@ var TemplateFactory = /** @class */ (function () { * @return {string|object} The template html as a string, or a promise for that * string. */ - TemplateFactory.prototype.fromString = function (template, params) { - return isFunction(template) ? template(params) : template; + TemplateFactory.prototype.fromString = function(template, params) { + return isFunction(template) ? template(params) : template; }; /** * Loads a template from the a URL via `$http` and `$templateCache`. @@ -8170,18 +9168,17 @@ var TemplateFactory = /** @class */ (function () { * @return {string|Promise.} The template html as a string, or a promise * for that string. */ - TemplateFactory.prototype.fromUrl = function (url, params) { - if (isFunction(url)) - url = url(params); - if (url == null) - return null; - if (this._useHttp) { - return this.$http.get(url, { cache: this.$templateCache, headers: { Accept: 'text/html' } }) - .then(function (response) { - return response.data; - }); - } - return this.$templateRequest(url); + TemplateFactory.prototype.fromUrl = function(url, params) { + if (isFunction(url)) url = url(params); + if (url == null) return null; + if (this._useHttp) { + return this.$http + .get(url, { cache: this.$templateCache, headers: { Accept: 'text/html' } }) + .then(function(response) { + return response.data; + }); + } + return this.$templateRequest(url); }; /** * Creates a template by invoking an injectable provider function. @@ -8191,11 +9188,11 @@ var TemplateFactory = /** @class */ (function () { * @return {string|Promise.} The template html as a string, or a promise * for that string. */ - TemplateFactory.prototype.fromProvider = function (provider, params, context) { - var deps = services.$injector.annotate(provider); - var providerFn = isArray(provider) ? tail(provider) : provider; - var resolvable = new Resolvable('', providerFn, deps); - return resolvable.get(context); + TemplateFactory.prototype.fromProvider = function(provider, params, context) { + var deps = services.$injector.annotate(provider); + var providerFn = isArray(provider) ? tail(provider) : provider; + var resolvable = new Resolvable('', providerFn, deps); + return resolvable.get(context); }; /** * Creates a component's template by invoking an injectable provider function. @@ -8204,11 +9201,11 @@ var TemplateFactory = /** @class */ (function () { * @param {Function} injectFn a function used to invoke the template provider * @return {string} The template html as a string: "". */ - TemplateFactory.prototype.fromComponentProvider = function (provider, params, context) { - var deps = services.$injector.annotate(provider); - var providerFn = isArray(provider) ? tail(provider) : provider; - var resolvable = new Resolvable('', providerFn, deps); - return resolvable.get(context); + TemplateFactory.prototype.fromComponentProvider = function(provider, params, context) { + var deps = services.$injector.annotate(provider); + var providerFn = isArray(provider) ? tail(provider) : provider; + var resolvable = new Resolvable('', providerFn, deps); + return resolvable.get(context); }; /** * Creates a template from a component's name @@ -8224,91 +9221,102 @@ var TemplateFactory = /** @class */ (function () { * @param bindings An object defining the component's bindings: {foo: '<'} * @return {string} The template as a string: "". */ - TemplateFactory.prototype.makeComponentTemplate = function (uiView, context, component, bindings) { - bindings = bindings || {}; - // Bind once prefix - var prefix = ng.version.minor >= 3 ? '::' : ''; - // Convert to kebob name. Add x- prefix if the string starts with `x-` or `data-` - var kebob = function (camelCase) { - var kebobed = kebobString(camelCase); - return /^(x|data)-/.exec(kebobed) ? "x-" + kebobed : kebobed; - }; - var attributeTpl = function (input) { - var name = input.name, type = input.type; - var attrName = kebob(name); - // If the ui-view has an attribute which matches a binding on the routed component - // then pass that attribute through to the routed component template. - // Prefer ui-view wired mappings to resolve data, unless the resolve was explicitly bound using `bindings:` - if (uiView.attr(attrName) && !bindings[name]) - return attrName + "='" + uiView.attr(attrName) + "'"; - var resolveName = bindings[name] || name; - // Pre-evaluate the expression for "@" bindings by enclosing in {{ }} - // some-attr="{{ ::$resolve.someResolveName }}" - if (type === '@') - return attrName + "='{{" + prefix + "$resolve." + resolveName + "}}'"; - // Wire "&" callbacks to resolves that return a callback function - // Get the result of the resolve (should be a function) and annotate it to get its arguments. - // some-attr="$resolve.someResolveResultName(foo, bar)" - if (type === '&') { - var res = context.getResolvable(resolveName); - var fn = res && res.data; - var args = fn && services.$injector.annotate(fn) || []; - // account for array style injection, i.e., ['foo', function(foo) {}] - var arrayIdxStr = isArray(fn) ? "[" + (fn.length - 1) + "]" : ''; - return attrName + "='$resolve." + resolveName + arrayIdxStr + "(" + args.join(',') + ")'"; - } - // some-attr="::$resolve.someResolveName" - return attrName + "='" + prefix + "$resolve." + resolveName + "'"; - }; - var attrs = getComponentBindings(component).map(attributeTpl).join(' '); - var kebobName = kebob(component); - return "<" + kebobName + " " + attrs + ">"; + TemplateFactory.prototype.makeComponentTemplate = function(uiView, context, component, bindings) { + bindings = bindings || {}; + // Bind once prefix + var prefix = ng.version.minor >= 3 ? '::' : ''; + // Convert to kebob name. Add x- prefix if the string starts with `x-` or `data-` + var kebob = function(camelCase) { + var kebobed = kebobString(camelCase); + return /^(x|data)-/.exec(kebobed) ? 'x-' + kebobed : kebobed; + }; + var attributeTpl = function(input) { + var name = input.name, + type = input.type; + var attrName = kebob(name); + // If the ui-view has an attribute which matches a binding on the routed component + // then pass that attribute through to the routed component template. + // Prefer ui-view wired mappings to resolve data, unless the resolve was explicitly bound using `bindings:` + if (uiView.attr(attrName) && !bindings[name]) return attrName + "='" + uiView.attr(attrName) + "'"; + var resolveName = bindings[name] || name; + // Pre-evaluate the expression for "@" bindings by enclosing in {{ }} + // some-attr="{{ ::$resolve.someResolveName }}" + if (type === '@') return attrName + "='{{" + prefix + '$resolve.' + resolveName + "}}'"; + // Wire "&" callbacks to resolves that return a callback function + // Get the result of the resolve (should be a function) and annotate it to get its arguments. + // some-attr="$resolve.someResolveResultName(foo, bar)" + if (type === '&') { + var res = context.getResolvable(resolveName); + var fn = res && res.data; + var args = (fn && services.$injector.annotate(fn)) || []; + // account for array style injection, i.e., ['foo', function(foo) {}] + var arrayIdxStr = isArray(fn) ? '[' + (fn.length - 1) + ']' : ''; + return attrName + "='$resolve." + resolveName + arrayIdxStr + '(' + args.join(',') + ")'"; + } + // some-attr="::$resolve.someResolveName" + return attrName + "='" + prefix + '$resolve.' + resolveName + "'"; + }; + var attrs = getComponentBindings(component) + .map(attributeTpl) + .join(' '); + var kebobName = kebob(component); + return '<' + kebobName + ' ' + attrs + '>'; }; return TemplateFactory; -}()); -// Gets all the directive(s)' inputs ('@', '=', and '<') and outputs ('&') -function getComponentBindings(name) { + })(); + // Gets all the directive(s)' inputs ('@', '=', and '<') and outputs ('&') + function getComponentBindings(name) { var cmpDefs = services.$injector.get(name + 'Directive'); // could be multiple - if (!cmpDefs || !cmpDefs.length) - throw new Error("Unable to find component named '" + name + "'"); + if (!cmpDefs || !cmpDefs.length) throw new Error("Unable to find component named '" + name + "'"); return cmpDefs.map(getBindings).reduce(unnestR, []); -} -// Given a directive definition, find its object input attributes -// Use different properties, depending on the type of directive (component, bindToController, normal) -var getBindings = function (def) { - if (isObject(def.bindToController)) - return scopeBindings(def.bindToController); + } + // Given a directive definition, find its object input attributes + // Use different properties, depending on the type of directive (component, bindToController, normal) + var getBindings = function(def) { + if (isObject(def.bindToController)) return scopeBindings(def.bindToController); return scopeBindings(def.scope); -}; -// for ng 1.2 style, process the scope: { input: "=foo" } -// for ng 1.3 through ng 1.5, process the component's bindToController: { input: "=foo" } object -var scopeBindings = function (bindingsObj) { return Object.keys(bindingsObj || {}) - .map(function (key) { return [key, /^([=<@&])[?]?(.*)/.exec(bindingsObj[key])]; }) - .filter(function (tuple) { return isDefined(tuple) && isArray(tuple[1]); }) - .map(function (tuple) { return ({ name: tuple[1][2] || tuple[0], type: tuple[1][1] }); }); }; + }; + // for ng 1.2 style, process the scope: { input: "=foo" } + // for ng 1.3 through ng 1.5, process the component's bindToController: { input: "=foo" } object + var scopeBindings = function(bindingsObj) { + return ( + Object.keys(bindingsObj || {}) + // [ 'input', [ '=foo', '=', 'foo' ] ] + .map(function(key) { + return [key, /^([=<@&])[?]?(.*)/.exec(bindingsObj[key])]; + }) + // skip malformed values + .filter(function(tuple) { + return isDefined(tuple) && isArray(tuple[1]); + }) + // { name: ('foo' || 'input'), type: '=' } + .map(function(tuple) { + return { name: tuple[1][2] || tuple[0], type: tuple[1][1] }; + }) + ); + }; /** for typedoc */ -/** @module ng1 */ /** for typedoc */ -/** - * The Angular 1 `StateProvider` - * - * The `$stateProvider` works similar to Angular's v1 router, but it focuses purely - * on state. - * - * A state corresponds to a "place" in the application in terms of the overall UI and - * navigation. A state describes (via the controller / template / view properties) what - * the UI looks like and does at that place. - * - * States often have things in common, and the primary way of factoring out these - * commonalities in this model is via the state hierarchy, i.e. parent/child states aka - * nested states. - * - * The `$stateProvider` provides interfaces to declare these states for your app. - */ -var StateProvider = /** @class */ (function () { + /** @module ng1 */ /** + * The Angular 1 `StateProvider` + * + * The `$stateProvider` works similar to Angular's v1 router, but it focuses purely + * on state. + * + * A state corresponds to a "place" in the application in terms of the overall UI and + * navigation. A state describes (via the controller / template / view properties) what + * the UI looks like and does at that place. + * + * States often have things in common, and the primary way of factoring out these + * commonalities in this model is via the state hierarchy, i.e. parent/child states aka + * nested states. + * + * The `$stateProvider` provides interfaces to declare these states for your app. + */ + var StateProvider = /** @class */ (function() { function StateProvider(stateRegistry, stateService) { - this.stateRegistry = stateRegistry; - this.stateService = stateService; - createProxyFunctions(val(StateProvider.prototype), this, val(this)); + this.stateRegistry = stateRegistry; + this.stateService = stateService; + createProxyFunctions(val(StateProvider.prototype), this, val(this)); } /** * Decorates states when they are registered @@ -8399,66 +9407,63 @@ var StateProvider = /** @class */ (function () { * * @return {object} $stateProvider - $stateProvider instance */ - StateProvider.prototype.decorator = function (name, func) { - return this.stateRegistry.decorator(name, func) || this; + StateProvider.prototype.decorator = function(name, func) { + return this.stateRegistry.decorator(name, func) || this; }; - StateProvider.prototype.state = function (name, definition) { - if (isObject(name)) { - definition = name; - } - else { - definition.name = name; - } - this.stateRegistry.register(definition); - return this; + StateProvider.prototype.state = function(name, definition) { + if (isObject(name)) { + definition = name; + } else { + definition.name = name; + } + this.stateRegistry.register(definition); + return this; }; /** * Registers an invalid state handler * * This is a passthrough to [[StateService.onInvalid]] for ng1. */ - StateProvider.prototype.onInvalid = function (callback) { - return this.stateService.onInvalid(callback); + StateProvider.prototype.onInvalid = function(callback) { + return this.stateService.onInvalid(callback); }; return StateProvider; -}()); + })(); /** */ -/** @module ng1 */ /** */ -/** - * This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`, - * `onRetain` callback hooks on a [[Ng1StateDeclaration]]. - * - * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder - * ensures that those hooks are injectable for @uirouter/angularjs (ng1). - */ -var getStateHookBuilder = function (hookName) { + /** @module ng1 */ /** + * This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`, + * `onRetain` callback hooks on a [[Ng1StateDeclaration]]. + * + * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder + * ensures that those hooks are injectable for @uirouter/angularjs (ng1). + */ + var getStateHookBuilder = function(hookName) { return function stateHookBuilder(stateObject, parentFn) { - var hook = stateObject[hookName]; - var pathname = hookName === 'onExit' ? 'from' : 'to'; - function decoratedNg1Hook(trans, state) { - var resolveContext = new ResolveContext(trans.treeChanges(pathname)); - var subContext = resolveContext.subContext(state.$$state()); - var locals = extend(getLocals(subContext), { $state$: state, $transition$: trans }); - return services.$injector.invoke(hook, this, locals); - } - return hook ? decoratedNg1Hook : undefined; + var hook = stateObject[hookName]; + var pathname = hookName === 'onExit' ? 'from' : 'to'; + function decoratedNg1Hook(trans, state) { + var resolveContext = new ResolveContext(trans.treeChanges(pathname)); + var subContext = resolveContext.subContext(state.$$state()); + var locals = extend(getLocals(subContext), { $state$: state, $transition$: trans }); + return services.$injector.invoke(hook, this, locals); + } + return hook ? decoratedNg1Hook : undefined; }; -}; + }; /** */ -/** - * @internalapi - * @module ng1 - */ /** */ -/** - * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service - */ -var Ng1LocationServices = /** @class */ (function () { + /** + * @internalapi + * @module ng1 + */ /** + * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service + */ + var Ng1LocationServices = /** @class */ (function() { function Ng1LocationServices($locationProvider) { - // .onChange() registry - this._urlListeners = []; - this.$locationProvider = $locationProvider; - var _lp = val($locationProvider); - createProxyFunctions(_lp, this, _lp, ['hashPrefix']); + // .onChange() registry + this._urlListeners = []; + this.$locationProvider = $locationProvider; + var _lp = val($locationProvider); + createProxyFunctions(_lp, this, _lp, ['hashPrefix']); } /** * Applys ng1-specific path parameter encoding @@ -8472,87 +9477,98 @@ var Ng1LocationServices = /** @class */ (function () { * * @param router */ - Ng1LocationServices.monkeyPatchPathParameterType = function (router) { - var pathType = router.urlMatcherFactory.type('path'); - pathType.encode = function (x) { - return x != null ? x.toString().replace(/(~|\/)/g, function (m) { return ({ '~': '~~', '/': '~2F' }[m]); }) : x; - }; - pathType.decode = function (x) { - return x != null ? x.toString().replace(/(~~|~2F)/g, function (m) { return ({ '~~': '~', '~2F': '/' }[m]); }) : x; - }; + Ng1LocationServices.monkeyPatchPathParameterType = function(router) { + var pathType = router.urlMatcherFactory.type('path'); + pathType.encode = function(x) { + return x != null + ? x.toString().replace(/(~|\/)/g, function(m) { + return { '~': '~~', '/': '~2F' }[m]; + }) + : x; + }; + pathType.decode = function(x) { + return x != null + ? x.toString().replace(/(~~|~2F)/g, function(m) { + return { '~~': '~', '~2F': '/' }[m]; + }) + : x; + }; }; - Ng1LocationServices.prototype.dispose = function () { }; - Ng1LocationServices.prototype.onChange = function (callback) { - var _this = this; - this._urlListeners.push(callback); - return function () { return removeFrom(_this._urlListeners)(callback); }; + Ng1LocationServices.prototype.dispose = function() {}; + Ng1LocationServices.prototype.onChange = function(callback) { + var _this = this; + this._urlListeners.push(callback); + return function() { + return removeFrom(_this._urlListeners)(callback); + }; }; - Ng1LocationServices.prototype.html5Mode = function () { - var html5Mode = this.$locationProvider.html5Mode(); - html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode; - return html5Mode && this.$sniffer.history; + Ng1LocationServices.prototype.html5Mode = function() { + var html5Mode = this.$locationProvider.html5Mode(); + html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode; + return html5Mode && this.$sniffer.history; }; - Ng1LocationServices.prototype.url = function (newUrl, replace, state) { - if (replace === void 0) { replace = false; } - if (isDefined(newUrl)) - this.$location.url(newUrl); - if (replace) - this.$location.replace(); - if (state) - this.$location.state(state); - return this.$location.url(); + Ng1LocationServices.prototype.url = function(newUrl, replace, state) { + if (replace === void 0) { + replace = false; + } + if (isDefined(newUrl)) this.$location.url(newUrl); + if (replace) this.$location.replace(); + if (state) this.$location.state(state); + return this.$location.url(); }; - Ng1LocationServices.prototype._runtimeServices = function ($rootScope, $location, $sniffer, $browser) { - var _this = this; - this.$location = $location; - this.$sniffer = $sniffer; - // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange - $rootScope.$on('$locationChangeSuccess', function (evt) { return _this._urlListeners.forEach(function (fn) { return fn(evt); }); }); - var _loc = val($location); - var _browser = val($browser); - // Bind these LocationService functions to $location - createProxyFunctions(_loc, this, _loc, ['replace', 'path', 'search', 'hash']); - // Bind these LocationConfig functions to $location - createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']); - // Bind these LocationConfig functions to $browser - createProxyFunctions(_browser, this, _browser, ['baseHref']); + Ng1LocationServices.prototype._runtimeServices = function($rootScope, $location, $sniffer, $browser) { + var _this = this; + this.$location = $location; + this.$sniffer = $sniffer; + // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange + $rootScope.$on('$locationChangeSuccess', function(evt) { + return _this._urlListeners.forEach(function(fn) { + return fn(evt); + }); + }); + var _loc = val($location); + var _browser = val($browser); + // Bind these LocationService functions to $location + createProxyFunctions(_loc, this, _loc, ['replace', 'path', 'search', 'hash']); + // Bind these LocationConfig functions to $location + createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']); + // Bind these LocationConfig functions to $browser + createProxyFunctions(_browser, this, _browser, ['baseHref']); }; return Ng1LocationServices; -}()); + })(); /** */ -/** @module url */ /** */ -/** - * Manages rules for client-side URL - * - * ### Deprecation warning: - * This class is now considered to be an internal API - * Use the [[UrlService]] instead. - * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]]. - * - * This class manages the router rules for what to do when the URL changes. - * - * This provider remains for backwards compatibility. - * - * @deprecated - */ -var UrlRouterProvider = /** @class */ (function () { + /** @module url */ /** + * Manages rules for client-side URL + * + * ### Deprecation warning: + * This class is now considered to be an internal API + * Use the [[UrlService]] instead. + * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]]. + * + * This class manages the router rules for what to do when the URL changes. + * + * This provider remains for backwards compatibility. + * + * @deprecated + */ + var UrlRouterProvider = /** @class */ (function() { /** @hidden */ function UrlRouterProvider(router) { - this._router = router; - this._urlRouter = router.urlRouter; + this._router = router; + this._urlRouter = router.urlRouter; } - UrlRouterProvider.injectableHandler = function (router, handler) { - return function (match) { - return services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params }); - }; + UrlRouterProvider.injectableHandler = function(router, handler) { + return function(match) { + return services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params }); + }; }; /** @hidden */ - UrlRouterProvider.prototype.$get = function () { - var urlRouter = this._urlRouter; - urlRouter.update(true); - if (!urlRouter.interceptDeferred) - urlRouter.listen(); - return urlRouter; + UrlRouterProvider.prototype.$get = function() { + var urlRouter = this._urlRouter; + urlRouter.update(true); + if (!urlRouter.interceptDeferred) urlRouter.listen(); + return urlRouter; }; /** * Registers a url handler function. @@ -8585,16 +9601,15 @@ var UrlRouterProvider = /** @class */ (function () { * * @return [[UrlRouterProvider]] (`this`) */ - UrlRouterProvider.prototype.rule = function (ruleFn) { - var _this = this; - if (!isFunction(ruleFn)) - throw new Error("'rule' must be a function"); - var match = function () { - return ruleFn(services.$injector, _this._router.locationService); - }; - var rule = new BaseUrlRule(match, identity); - this._urlRouter.rule(rule); - return this; + UrlRouterProvider.prototype.rule = function(ruleFn) { + var _this = this; + if (!isFunction(ruleFn)) throw new Error("'rule' must be a function"); + var match = function() { + return ruleFn(services.$injector, _this._router.locationService); + }; + var rule = new BaseUrlRule(match, identity); + this._urlRouter.rule(rule); + return this; }; /** * Defines the path or behavior to use when no url can be matched. @@ -8622,19 +9637,19 @@ var UrlRouterProvider = /** @class */ (function () { * * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance */ - UrlRouterProvider.prototype.otherwise = function (rule) { - var _this = this; - var urlRouter = this._urlRouter; - if (isString(rule)) { - urlRouter.otherwise(rule); - } - else if (isFunction(rule)) { - urlRouter.otherwise(function () { return rule(services.$injector, _this._router.locationService); }); - } - else { - throw new Error("'rule' must be a string or function"); - } - return this; + UrlRouterProvider.prototype.otherwise = function(rule) { + var _this = this; + var urlRouter = this._urlRouter; + if (isString(rule)) { + urlRouter.otherwise(rule); + } else if (isFunction(rule)) { + urlRouter.otherwise(function() { + return rule(services.$injector, _this._router.locationService); + }); + } else { + throw new Error("'rule' must be a string or function"); + } + return this; }; /** * Registers a handler for a given url matching. @@ -8674,12 +9689,12 @@ var UrlRouterProvider = /** @class */ (function () { * * Note: the handler may also invoke arbitrary code, such as `$state.go()` */ - UrlRouterProvider.prototype.when = function (what, handler) { - if (isArray(handler) || isFunction(handler)) { - handler = UrlRouterProvider.injectableHandler(this._router, handler); - } - this._urlRouter.when(what, handler); - return this; + UrlRouterProvider.prototype.when = function(what, handler) { + if (isArray(handler) || isFunction(handler)) { + handler = UrlRouterProvider.injectableHandler(this._router, handler); + } + this._urlRouter.when(what, handler); + return this; }; /** * Disables monitoring of the URL. @@ -8711,35 +9726,34 @@ var UrlRouterProvider = /** @class */ (function () { * @param defer Indicates whether to defer location change interception. * Passing no parameter is equivalent to `true`. */ - UrlRouterProvider.prototype.deferIntercept = function (defer) { - this._urlRouter.deferIntercept(defer); + UrlRouterProvider.prototype.deferIntercept = function(defer) { + this._urlRouter.deferIntercept(defer); }; return UrlRouterProvider; -}()); + })(); -/** - * # Angular 1 types - * - * UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc. - * The customizations to the core types for Angular UI-Router are documented here. - * - * The optional [[$resolve]] service is also documented here. - * - * @module ng1 - * @preferred - */ -/** for typedoc */ -ng.module('ui.router.angular1', []); -var mod_init = ng.module('ui.router.init', []); -var mod_util = ng.module('ui.router.util', ['ng', 'ui.router.init']); -var mod_rtr = ng.module('ui.router.router', ['ui.router.util']); -var mod_state = ng.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']); -var mod_main = ng.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']); -var mod_cmpt = ng.module('ui.router.compat', ['ui.router']); // tslint:disable-line -var router = null; -$uiRouterProvider.$inject = ['$locationProvider']; -/** This angular 1 provider instantiates a Router and exposes its services via the angular injector */ -function $uiRouterProvider($locationProvider) { + /** + * # Angular 1 types + * + * UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc. + * The customizations to the core types for Angular UI-Router are documented here. + * + * The optional [[$resolve]] service is also documented here. + * + * @module ng1 + * @preferred + */ + ng.module('ui.router.angular1', []); + var mod_init = ng.module('ui.router.init', []); + var mod_util = ng.module('ui.router.util', ['ng', 'ui.router.init']); + var mod_rtr = ng.module('ui.router.router', ['ui.router.util']); + var mod_state = ng.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']); + var mod_main = ng.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']); + var mod_cmpt = ng.module('ui.router.compat', ['ui.router']); // tslint:disable-line + var router = null; + $uiRouterProvider.$inject = ['$locationProvider']; + /** This angular 1 provider instantiates a Router and exposes its services via the angular injector */ + function $uiRouterProvider($locationProvider) { // Create a new instance of the Router when the $uiRouterProvider is initialized router = this.router = new UIRouter(); router.stateProvider = new StateProvider(router.stateRegistry, router.stateService); @@ -8749,1392 +9763,1495 @@ function $uiRouterProvider($locationProvider) { router.stateRegistry.decorator('onRetain', getStateHookBuilder('onRetain')); router.stateRegistry.decorator('onEnter', getStateHookBuilder('onEnter')); router.viewService._pluginapi._viewConfigFactory('ng1', getNg1ViewConfigFactory()); - var ng1LocationService = router.locationService = router.locationConfig = new Ng1LocationServices($locationProvider); + var ng1LocationService = (router.locationService = router.locationConfig = new Ng1LocationServices( + $locationProvider, + )); Ng1LocationServices.monkeyPatchPathParameterType(router); // backwards compat: also expose router instance as $uiRouterProvider.router router['router'] = router; router['$get'] = $get; $get.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache']; function $get($location, $browser, $sniffer, $rootScope, $http, $templateCache) { - ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser); - delete router['router']; - delete router['$get']; - return router; + ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser); + delete router['router']; + delete router['$get']; + return router; } return router; -} -var getProviderFor = function (serviceName) { return ['$uiRouterProvider', function ($urp) { + } + var getProviderFor = function(serviceName) { + return [ + '$uiRouterProvider', + function($urp) { var service = $urp.router[serviceName]; - service['$get'] = function () { return service; }; + service['$get'] = function() { + return service; + }; return service; - }]; }; -// This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime) -runBlock.$inject = ['$injector', '$q', '$uiRouter']; -function runBlock($injector, $q, $uiRouter) { - services.$injector = $injector; - services.$q = $q; + }, + ]; + }; + // This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime) + runBlock.$inject = ['$injector', '$q', '$uiRouter']; + function runBlock($injector$$1, $q$$1, $uiRouter) { + services.$injector = $injector$$1; + services.$q = $q$$1; // The $injector is now available. // Find any resolvables that had dependency annotation deferred - $uiRouter.stateRegistry.get() - .map(function (x) { return x.$$state().resolvables; }) - .reduce(unnestR, []) - .filter(function (x) { return x.deps === 'deferred'; }) - .forEach(function (resolvable) { return resolvable.deps = $injector.annotate(resolvable.resolveFn, $injector.strictDi); }); -} -// $urlRouter service and $urlRouterProvider -var getUrlRouterProvider = function (uiRouter) { - return uiRouter.urlRouterProvider = new UrlRouterProvider(uiRouter); -}; -// $state service and $stateProvider -// $urlRouter service and $urlRouterProvider -var getStateProvider = function () { - return extend(router.stateProvider, { $get: function () { return router.stateService; } }); -}; -watchDigests.$inject = ['$rootScope']; -function watchDigests($rootScope) { - $rootScope.$watch(function () { trace.approximateDigests++; }); -} -mod_init.provider('$uiRouter', $uiRouterProvider); -mod_rtr.provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]); -mod_util.provider('$urlService', getProviderFor('urlService')); -mod_util.provider('$urlMatcherFactory', ['$uiRouterProvider', function () { return router.urlMatcherFactory; }]); -mod_util.provider('$templateFactory', function () { return new TemplateFactory(); }); -mod_state.provider('$stateRegistry', getProviderFor('stateRegistry')); -mod_state.provider('$uiRouterGlobals', getProviderFor('globals')); -mod_state.provider('$transitions', getProviderFor('transitionService')); -mod_state.provider('$state', ['$uiRouterProvider', getStateProvider]); -mod_state.factory('$stateParams', ['$uiRouter', function ($uiRouter) { return $uiRouter.globals.params; }]); -mod_main.factory('$view', function () { return router.viewService; }); -mod_main.service('$trace', function () { return trace; }); -mod_main.run(watchDigests); -mod_util.run(['$urlMatcherFactory', function ($urlMatcherFactory) { }]); -mod_state.run(['$state', function ($state) { }]); -mod_rtr.run(['$urlRouter', function ($urlRouter) { }]); -mod_init.run(runBlock); -/** @hidden TODO: find a place to move this */ -var getLocals = function (ctx) { + $uiRouter.stateRegistry + .get() + .map(function(x) { + return x.$$state().resolvables; + }) + .reduce(unnestR, []) + .filter(function(x) { + return x.deps === 'deferred'; + }) + .forEach(function(resolvable) { + return (resolvable.deps = $injector$$1.annotate(resolvable.resolveFn, $injector$$1.strictDi)); + }); + } + // $urlRouter service and $urlRouterProvider + var getUrlRouterProvider = function(uiRouter) { + return (uiRouter.urlRouterProvider = new UrlRouterProvider(uiRouter)); + }; + // $state service and $stateProvider + // $urlRouter service and $urlRouterProvider + var getStateProvider = function() { + return extend(router.stateProvider, { + $get: function() { + return router.stateService; + }, + }); + }; + watchDigests.$inject = ['$rootScope']; + function watchDigests($rootScope) { + $rootScope.$watch(function() { + trace.approximateDigests++; + }); + } + mod_init.provider('$uiRouter', $uiRouterProvider); + mod_rtr.provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]); + mod_util.provider('$urlService', getProviderFor('urlService')); + mod_util.provider('$urlMatcherFactory', [ + '$uiRouterProvider', + function() { + return router.urlMatcherFactory; + }, + ]); + mod_util.provider('$templateFactory', function() { + return new TemplateFactory(); + }); + mod_state.provider('$stateRegistry', getProviderFor('stateRegistry')); + mod_state.provider('$uiRouterGlobals', getProviderFor('globals')); + mod_state.provider('$transitions', getProviderFor('transitionService')); + mod_state.provider('$state', ['$uiRouterProvider', getStateProvider]); + mod_state.factory('$stateParams', [ + '$uiRouter', + function($uiRouter) { + return $uiRouter.globals.params; + }, + ]); + mod_main.factory('$view', function() { + return router.viewService; + }); + mod_main.service('$trace', function() { + return trace; + }); + mod_main.run(watchDigests); + mod_util.run(['$urlMatcherFactory', function($urlMatcherFactory) {}]); + mod_state.run(['$state', function($state) {}]); + mod_rtr.run(['$urlRouter', function($urlRouter) {}]); + mod_init.run(runBlock); + /** @hidden TODO: find a place to move this */ + var getLocals = function(ctx) { var tokens = ctx.getTokens().filter(isString); - var tuples = tokens.map(function (key) { - var resolvable = ctx.getResolvable(key); - var waitPolicy = ctx.getPolicy(resolvable).async; - return [key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data]; + var tuples = tokens.map(function(key) { + var resolvable = ctx.getResolvable(key); + var waitPolicy = ctx.getPolicy(resolvable).async; + return [key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data]; }); return tuples.reduce(applyPairs, {}); -}; + }; /** for typedoc */ -/** - * The current (or pending) State Parameters - * - * An injectable global **Service Object** which holds the state parameters for the latest **SUCCESSFUL** transition. - * - * The values are not updated until *after* a `Transition` successfully completes. - * - * **Also:** an injectable **Per-Transition Object** object which holds the pending state parameters for the pending `Transition` currently running. - * - * ### Deprecation warning: - * - * The value injected for `$stateParams` is different depending on where it is injected. - * - * - When injected into an angular service, the object injected is the global **Service Object** with the parameter values for the latest successful `Transition`. - * - When injected into transition hooks, resolves, or view controllers, the object is the **Per-Transition Object** with the parameter values for the running `Transition`. - * - * Because of these confusing details, this service is deprecated. - * - * ### Instead of using the global `$stateParams` service object, - * inject [[$uiRouterGlobals]] and use [[UIRouterGlobals.params]] - * - * ```js - * MyService.$inject = ['$uiRouterGlobals']; - * function MyService($uiRouterGlobals) { - * return { - * paramValues: function () { - * return $uiRouterGlobals.params; - * } - * } - * } - * ``` - * - * ### Instead of using the per-transition `$stateParams` object, - * inject the current `Transition` (as [[$transition$]]) and use [[Transition.params]] - * - * ```js - * MyController.$inject = ['$transition$']; - * function MyController($transition$) { - * var username = $transition$.params().username; - * // .. do something with username - * } - * ``` - * - * --- - * - * This object can be injected into other services. - * - * #### Deprecated Example: - * ```js - * SomeService.$inject = ['$http', '$stateParams']; - * function SomeService($http, $stateParams) { - * return { - * getUser: function() { - * return $http.get('/api/users/' + $stateParams.username); - * } - * } - * }; - * angular.service('SomeService', SomeService); - * ``` - * @deprecated - */ + /** + * The current (or pending) State Parameters + * + * An injectable global **Service Object** which holds the state parameters for the latest **SUCCESSFUL** transition. + * + * The values are not updated until *after* a `Transition` successfully completes. + * + * **Also:** an injectable **Per-Transition Object** object which holds the pending state parameters for the pending `Transition` currently running. + * + * ### Deprecation warning: + * + * The value injected for `$stateParams` is different depending on where it is injected. + * + * - When injected into an angular service, the object injected is the global **Service Object** with the parameter values for the latest successful `Transition`. + * - When injected into transition hooks, resolves, or view controllers, the object is the **Per-Transition Object** with the parameter values for the running `Transition`. + * + * Because of these confusing details, this service is deprecated. + * + * ### Instead of using the global `$stateParams` service object, + * inject [[$uiRouterGlobals]] and use [[UIRouterGlobals.params]] + * + * ```js + * MyService.$inject = ['$uiRouterGlobals']; + * function MyService($uiRouterGlobals) { + * return { + * paramValues: function () { + * return $uiRouterGlobals.params; + * } + * } + * } + * ``` + * + * ### Instead of using the per-transition `$stateParams` object, + * inject the current `Transition` (as [[$transition$]]) and use [[Transition.params]] + * + * ```js + * MyController.$inject = ['$transition$']; + * function MyController($transition$) { + * var username = $transition$.params().username; + * // .. do something with username + * } + * ``` + * + * --- + * + * This object can be injected into other services. + * + * #### Deprecated Example: + * ```js + * SomeService.$inject = ['$http', '$stateParams']; + * function SomeService($http, $stateParams) { + * return { + * getUser: function() { + * return $http.get('/api/users/' + $stateParams.username); + * } + * } + * }; + * angular.service('SomeService', SomeService); + * ``` + * @deprecated + */ -/** - * # Angular 1 Directives - * - * These are the directives included in UI-Router for Angular 1. - * These directives are used in templates to create viewports and link/navigate to states. - * - * @ng1api - * @preferred - * @module directives - */ /** for typedoc */ -/** @hidden */ -function parseStateRef(ref) { + /** + * # Angular 1 Directives + * + * These are the directives included in UI-Router for Angular 1. + * These directives are used in templates to create viewports and link/navigate to states. + * + * @ng1api + * @preferred + * @module directives + */ /** @hidden */ + function parseStateRef(ref) { var parsed; var paramsOnly = ref.match(/^\s*({[^}]*})\s*$/); - if (paramsOnly) - ref = '(' + paramsOnly[1] + ')'; + if (paramsOnly) ref = '(' + paramsOnly[1] + ')'; parsed = ref.replace(/\n/g, ' ').match(/^\s*([^(]*?)\s*(\((.*)\))?\s*$/); - if (!parsed || parsed.length !== 4) - throw new Error("Invalid state ref '" + ref + "'"); + if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'"); return { state: parsed[1] || null, paramExpr: parsed[3] || null }; -} -/** @hidden */ -function stateContext(el) { + } + /** @hidden */ + function stateContext(el) { var $uiView = el.parent().inheritedData('$uiView'); var path = parse('$cfg.path')($uiView); return path ? tail(path).state.name : undefined; -} -/** @hidden */ -function processedDef($state, $element, def) { + } + /** @hidden */ + function processedDef($state, $element, def) { var uiState = def.uiState || $state.current.name; var uiStateOpts = extend(defaultOpts($element, $state), def.uiStateOpts || {}); var href = $state.href(uiState, def.uiStateParams, uiStateOpts); return { uiState: uiState, uiStateParams: def.uiStateParams, uiStateOpts: uiStateOpts, href: href }; -} -/** @hidden */ -function getTypeInfo(el) { + } + /** @hidden */ + function getTypeInfo(el) { // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]'; var isForm = el[0].nodeName === 'FORM'; return { - attr: isForm ? 'action' : (isSvg ? 'xlink:href' : 'href'), - isAnchor: el.prop('tagName').toUpperCase() === 'A', - clickable: !isForm, + attr: isForm ? 'action' : isSvg ? 'xlink:href' : 'href', + isAnchor: el.prop('tagName').toUpperCase() === 'A', + clickable: !isForm, }; -} -/** @hidden */ -function clickHook(el, $state, $timeout, type, getDef) { - return function (e) { - var button = e.which || e.button, target = getDef(); - if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) { - // HACK: This is to allow ng-clicks to be processed before the transition is initiated: - var transition_1 = $timeout(function () { - $state.go(target.uiState, target.uiStateParams, target.uiStateOpts); - }); - e.preventDefault(); - // if the state has no URL, ignore one preventDefault from the directive. - var ignorePreventDefaultCount_1 = type.isAnchor && !target.href ? 1 : 0; - e.preventDefault = function () { - if (ignorePreventDefaultCount_1-- <= 0) - $timeout.cancel(transition_1); - }; - } + } + /** @hidden */ + function clickHook(el, $state, $timeout, type, getDef) { + return function(e) { + var button = e.which || e.button, + target = getDef(); + if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) { + // HACK: This is to allow ng-clicks to be processed before the transition is initiated: + var transition_1 = $timeout(function() { + $state.go(target.uiState, target.uiStateParams, target.uiStateOpts); + }); + e.preventDefault(); + // if the state has no URL, ignore one preventDefault from the directive. + var ignorePreventDefaultCount_1 = type.isAnchor && !target.href ? 1 : 0; + e.preventDefault = function() { + if (ignorePreventDefaultCount_1-- <= 0) $timeout.cancel(transition_1); + }; + } }; -} -/** @hidden */ -function defaultOpts(el, $state) { + } + /** @hidden */ + function defaultOpts(el, $state) { return { - relative: stateContext(el) || $state.$current, - inherit: true, - source: 'sref', + relative: stateContext(el) || $state.$current, + inherit: true, + source: 'sref', }; -} -/** @hidden */ -function bindEvents(element, scope, hookFn, uiStateOpts) { + } + /** @hidden */ + function bindEvents(element, scope, hookFn, uiStateOpts) { var events; if (uiStateOpts) { - events = uiStateOpts.events; + events = uiStateOpts.events; } if (!isArray(events)) { - events = ['click']; + events = ['click']; } var on = element.on ? 'on' : 'bind'; for (var _i = 0, events_1 = events; _i < events_1.length; _i++) { - var event_1 = events_1[_i]; - element[on](event_1, hookFn); + var event_1 = events_1[_i]; + element[on](event_1, hookFn); } - scope.$on('$destroy', function () { - var off = element.off ? 'off' : 'unbind'; - for (var _i = 0, events_2 = events; _i < events_2.length; _i++) { - var event_2 = events_2[_i]; - element[off](event_2, hookFn); - } + scope.$on('$destroy', function() { + var off = element.off ? 'off' : 'unbind'; + for (var _i = 0, events_2 = events; _i < events_2.length; _i++) { + var event_2 = events_2[_i]; + element[off](event_2, hookFn); + } }); -} -/** - * `ui-sref`: A directive for linking to a state - * - * A directive which links to a state (and optionally, parameters). - * When clicked, this directive activates the linked state with the supplied parameter values. - * - * ### Linked State - * The attribute value of the `ui-sref` is the name of the state to link to. - * - * #### Example: - * This will activate the `home` state when the link is clicked. - * ```html - * Home - * ``` - * - * ### Relative Links - * You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]). - * You just need to be aware that the path is relative to the state that *created* the link. - * This allows a state to create a relative `ui-sref` which always targets the same destination. - * - * #### Example: - * Both these links are relative to the parent state, even when a child state is currently active. - * ```html - * child 1 state - * child 2 state - * ``` - * - * This link activates the parent state. - * ```html - * Return - * ``` - * - * ### hrefs - * If the linked state has a URL, the directive will automatically generate and - * update the `href` attribute (using the [[StateService.href]] method). - * - * #### Example: - * Assuming the `users` state has a url of `/users/` - * ```html - * Users - * ``` - * - * ### Parameter Values - * In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state. - * Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses. - * The content inside the parentheses is an expression, evaluated to the parameter values. - * - * #### Example: - * This example renders a list of links to users. - * The state's `userId` parameter value comes from each user's `user.id` property. - * ```html - *
  • - * {{ user.displayName }} - *
  • - * ``` - * - * Note: - * The parameter values expression is `$watch`ed for updates. - * - * ### Transition Options - * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute. - * Options are restricted to `location`, `inherit`, and `reload`. - * - * #### Example: - * ```html - * Home - * ``` - * - * ### Other DOM Events - * - * You can also customize which DOM events to respond to (instead of `click`) by - * providing an `events` array in the `ui-sref-opts` attribute. - * - * #### Example: - * ```html - * - * ``` - * - * ### Highlighting the active link - * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link. - * - * ### Examples - * If you have the following template: - * - * ```html - * Home - * About - * Next page - * - * - * ``` - * - * Then (assuming the current state is `contacts`) the rendered html including hrefs would be: - * - * ```html - * Home - * About - * Next page - * - *
      - *
    • - * Joe - *
    • - *
    • - * Alice - *
    • - *
    • - * Bob - *
    • - *
    - * - * Home - * ``` - * - * ### Notes - * - * - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses. - * #### Example: - * Sets the `lang` parameter to `en` and remains on the same state. - * - * ```html - * English - * ``` - * - * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example. - * - * - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons). - * If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive. - */ -var uiSrefDirective; -uiSrefDirective = ['$uiRouter', '$timeout', + } + /** + * `ui-sref`: A directive for linking to a state + * + * A directive which links to a state (and optionally, parameters). + * When clicked, this directive activates the linked state with the supplied parameter values. + * + * ### Linked State + * The attribute value of the `ui-sref` is the name of the state to link to. + * + * #### Example: + * This will activate the `home` state when the link is clicked. + * ```html + * Home + * ``` + * + * ### Relative Links + * You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]). + * You just need to be aware that the path is relative to the state that *created* the link. + * This allows a state to create a relative `ui-sref` which always targets the same destination. + * + * #### Example: + * Both these links are relative to the parent state, even when a child state is currently active. + * ```html + * child 1 state + * child 2 state + * ``` + * + * This link activates the parent state. + * ```html + * Return + * ``` + * + * ### hrefs + * If the linked state has a URL, the directive will automatically generate and + * update the `href` attribute (using the [[StateService.href]] method). + * + * #### Example: + * Assuming the `users` state has a url of `/users/` + * ```html + * Users + * ``` + * + * ### Parameter Values + * In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state. + * Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses. + * The content inside the parentheses is an expression, evaluated to the parameter values. + * + * #### Example: + * This example renders a list of links to users. + * The state's `userId` parameter value comes from each user's `user.id` property. + * ```html + *
  • + * {{ user.displayName }} + *
  • + * ``` + * + * Note: + * The parameter values expression is `$watch`ed for updates. + * + * ### Transition Options + * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute. + * Options are restricted to `location`, `inherit`, and `reload`. + * + * #### Example: + * ```html + * Home + * ``` + * + * ### Other DOM Events + * + * You can also customize which DOM events to respond to (instead of `click`) by + * providing an `events` array in the `ui-sref-opts` attribute. + * + * #### Example: + * ```html + * + * ``` + * + * ### Highlighting the active link + * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link. + * + * ### Examples + * If you have the following template: + * + * ```html + * Home + * About + * Next page + * + * + * ``` + * + * Then (assuming the current state is `contacts`) the rendered html including hrefs would be: + * + * ```html + * Home + * About + * Next page + * + *
      + *
    • + * Joe + *
    • + *
    • + * Alice + *
    • + *
    • + * Bob + *
    • + *
    + * + * Home + * ``` + * + * ### Notes + * + * - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses. + * #### Example: + * Sets the `lang` parameter to `en` and remains on the same state. + * + * ```html + * English + * ``` + * + * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example. + * + * - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons). + * If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive. + */ + var uiSrefDirective; + uiSrefDirective = [ + '$uiRouter', + '$timeout', function $StateRefDirective($uiRouter, $timeout) { - var $state = $uiRouter.stateService; - return { - restrict: 'A', - require: ['?^uiSrefActive', '?^uiSrefActiveEq'], - link: function (scope, element, attrs, uiSrefActive) { - var type = getTypeInfo(element); - var active = uiSrefActive[1] || uiSrefActive[0]; - var unlinkInfoFn = null; - var hookFn; - var rawDef = {}; - var getDef = function () { return processedDef($state, element, rawDef); }; - var ref = parseStateRef(attrs.uiSref); - rawDef.uiState = ref.state; - rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {}; - function update() { - var def = getDef(); - if (unlinkInfoFn) - unlinkInfoFn(); - if (active) - unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams); - if (def.href != null) - attrs.$set(type.attr, def.href); - } - if (ref.paramExpr) { - scope.$watch(ref.paramExpr, function (val) { - rawDef.uiStateParams = extend({}, val); - update(); - }, true); - rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr)); - } + var $state = $uiRouter.stateService; + return { + restrict: 'A', + require: ['?^uiSrefActive', '?^uiSrefActiveEq'], + link: function(scope, element, attrs, uiSrefActive) { + var type = getTypeInfo(element); + var active = uiSrefActive[1] || uiSrefActive[0]; + var unlinkInfoFn = null; + var hookFn; + var rawDef = {}; + var getDef = function() { + return processedDef($state, element, rawDef); + }; + var ref = parseStateRef(attrs.uiSref); + rawDef.uiState = ref.state; + rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {}; + function update() { + var def = getDef(); + if (unlinkInfoFn) unlinkInfoFn(); + if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams); + if (def.href != null) attrs.$set(type.attr, def.href); + } + if (ref.paramExpr) { + scope.$watch( + ref.paramExpr, + function(val$$1) { + rawDef.uiStateParams = extend({}, val$$1); update(); - scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update)); - scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update)); - if (!type.clickable) - return; - hookFn = clickHook(element, $state, $timeout, type, getDef); - bindEvents(element, scope, hookFn, rawDef.uiStateOpts); - }, - }; - }]; -/** - * `ui-state`: A fully dynamic directive for linking to a state - * - * A directive which links to a state (and optionally, parameters). - * When clicked, this directive activates the linked state with the supplied parameter values. - * - * **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.** - * - * A directive which links to a state (and optionally, parameters). - * When clicked, this directive activates the linked state with the supplied parameter values. - * - * ### Linked State - * The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to. - * **This is in contrast with `ui-sref`, which takes a state name as a string literal.** - * - * #### Example: - * Create a list of links. - * ```html - *
  • - * {{ link.displayName }} - *
  • - * ``` - * - * ### Relative Links - * If the expression evaluates to a relative path, it is processed like [[uiSref]]. - * You just need to be aware that the path is relative to the state that *created* the link. - * This allows a state to create relative `ui-state` which always targets the same destination. - * - * ### hrefs - * If the linked state has a URL, the directive will automatically generate and - * update the `href` attribute (using the [[StateService.href]] method). - * - * ### Parameter Values - * In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state. - * Param values should be provided using the `ui-state-params` attribute. - * The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression. - * - * #### Example: - * This example renders a list of links with param values. - * The state's `userId` parameter value comes from each user's `user.id` property. - * ```html - *
  • - * {{ link.displayName }} - *
  • - * ``` - * - * ### Transition Options - * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute. - * Options are restricted to `location`, `inherit`, and `reload`. - * The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression. - * - * #### Example: - * ```html - * Home - * ``` - * - * ### Other DOM Events - * - * You can also customize which DOM events to respond to (instead of `click`) by - * providing an `events` array in the `ui-state-opts` attribute. - * - * #### Example: - * ```html - * - * ``` - * - * ### Highlighting the active link - * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link. - * - * ### Notes - * - * - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`. - * However, it might be simpler to use [[uiSref]] parameter-only links. - * - * #### Example: - * Sets the `lang` parameter to `en` and remains on the same state. - * - * ```html - * English - * ``` - * - * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example. - * ``` - */ -var uiStateDirective; -uiStateDirective = ['$uiRouter', '$timeout', + }, + true, + ); + rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr)); + } + update(); + scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update)); + scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update)); + if (!type.clickable) return; + hookFn = clickHook(element, $state, $timeout, type, getDef); + bindEvents(element, scope, hookFn, rawDef.uiStateOpts); + }, + }; + }, + ]; + /** + * `ui-state`: A fully dynamic directive for linking to a state + * + * A directive which links to a state (and optionally, parameters). + * When clicked, this directive activates the linked state with the supplied parameter values. + * + * **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.** + * + * A directive which links to a state (and optionally, parameters). + * When clicked, this directive activates the linked state with the supplied parameter values. + * + * ### Linked State + * The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to. + * **This is in contrast with `ui-sref`, which takes a state name as a string literal.** + * + * #### Example: + * Create a list of links. + * ```html + *
  • + * {{ link.displayName }} + *
  • + * ``` + * + * ### Relative Links + * If the expression evaluates to a relative path, it is processed like [[uiSref]]. + * You just need to be aware that the path is relative to the state that *created* the link. + * This allows a state to create relative `ui-state` which always targets the same destination. + * + * ### hrefs + * If the linked state has a URL, the directive will automatically generate and + * update the `href` attribute (using the [[StateService.href]] method). + * + * ### Parameter Values + * In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state. + * Param values should be provided using the `ui-state-params` attribute. + * The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression. + * + * #### Example: + * This example renders a list of links with param values. + * The state's `userId` parameter value comes from each user's `user.id` property. + * ```html + *
  • + * {{ link.displayName }} + *
  • + * ``` + * + * ### Transition Options + * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute. + * Options are restricted to `location`, `inherit`, and `reload`. + * The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression. + * + * #### Example: + * ```html + * Home + * ``` + * + * ### Other DOM Events + * + * You can also customize which DOM events to respond to (instead of `click`) by + * providing an `events` array in the `ui-state-opts` attribute. + * + * #### Example: + * ```html + * + * ``` + * + * ### Highlighting the active link + * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link. + * + * ### Notes + * + * - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`. + * However, it might be simpler to use [[uiSref]] parameter-only links. + * + * #### Example: + * Sets the `lang` parameter to `en` and remains on the same state. + * + * ```html + * English + * ``` + * + * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example. + * ``` + */ + var uiStateDirective; + uiStateDirective = [ + '$uiRouter', + '$timeout', function $StateRefDynamicDirective($uiRouter, $timeout) { - var $state = $uiRouter.stateService; - return { - restrict: 'A', - require: ['?^uiSrefActive', '?^uiSrefActiveEq'], - link: function (scope, element, attrs, uiSrefActive) { - var type = getTypeInfo(element); - var active = uiSrefActive[1] || uiSrefActive[0]; - var unlinkInfoFn = null; - var hookFn; - var rawDef = {}; - var getDef = function () { return processedDef($state, element, rawDef); }; - var inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts']; - var watchDeregFns = inputAttrs.reduce(function (acc, attr) { return (acc[attr] = noop, acc); }, {}); - function update() { - var def = getDef(); - if (unlinkInfoFn) - unlinkInfoFn(); - if (active) - unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams); - if (def.href != null) - attrs.$set(type.attr, def.href); - } - inputAttrs.forEach(function (field) { - rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null; - attrs.$observe(field, function (expr) { - watchDeregFns[field](); - watchDeregFns[field] = scope.$watch(expr, function (newval) { - rawDef[field] = newval; - update(); - }, true); - }); - }); - update(); - scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update)); - scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update)); - if (!type.clickable) - return; - hookFn = clickHook(element, $state, $timeout, type, getDef); - bindEvents(element, scope, hookFn, rawDef.uiStateOpts); - }, - }; - }]; -/** - * `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active - * - * A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the - * related directive's state is active (and remove them when it is inactive). - * - * The primary use-case is to highlight the active link in navigation menus, - * distinguishing it from the inactive menu items. - * - * ### Linking to a `ui-sref` or `ui-state` - * `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element. - * If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**. - * - * ### Matching - * - * The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**. - * This is a "fuzzy match" which uses [[StateService.includes]]. - * - * The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active). - * This is an "exact match" which uses [[StateService.is]]. - * - * ### Parameter values - * If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted. - * This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted. - * - * #### Example: - * ```html - *
  • - * {{ user.lastName }} - *
  • - * ``` - * - * ### Examples - * - * Given the following template: - * #### Example: - * ```html - * - * ``` - * - * When the app state is `app.user` (or any child state), - * and contains the state parameter "user" with value "bilbobaggins", - * the resulting HTML will appear as (note the 'active' class): - * - * ```html - * - * ``` - * - * ### Glob mode - * - * It is possible to pass `ui-sref-active` an expression that evaluates to an object. - * The objects keys represent active class names and values represent the respective state names/globs. - * `ui-sref-active` will match if the current active state **includes** any of - * the specified state names/globs, even the abstract ones. - * - * #### Example: - * Given the following template, with "admin" being an abstract state: - * ```html - *
    - * Roles - *
    - * ``` - * - * Arrays are also supported as values in the `ngClass`-like interface. - * This allows multiple states to add `active` class. - * - * #### Example: - * Given the following template, with "admin.roles" being the current state, the class will be added too: - * ```html - *
    - * Roles - *
    - * ``` - * - * When the current state is "admin.roles" the "active" class will be applied to both the `
    ` and `` elements. - * It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`. - * - * ### Notes: - * - * - The class name is interpolated **once** during the directives link time (any further changes to the - * interpolated value are ignored). - * - * - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'` - */ -var uiSrefActiveDirective; -uiSrefActiveDirective = ['$state', '$stateParams', '$interpolate', '$uiRouter', + var $state = $uiRouter.stateService; + return { + restrict: 'A', + require: ['?^uiSrefActive', '?^uiSrefActiveEq'], + link: function(scope, element, attrs, uiSrefActive) { + var type = getTypeInfo(element); + var active = uiSrefActive[1] || uiSrefActive[0]; + var unlinkInfoFn = null; + var hookFn; + var rawDef = {}; + var getDef = function() { + return processedDef($state, element, rawDef); + }; + var inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts']; + var watchDeregFns = inputAttrs.reduce(function(acc, attr) { + return (acc[attr] = noop), acc; + }, {}); + function update() { + var def = getDef(); + if (unlinkInfoFn) unlinkInfoFn(); + if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams); + if (def.href != null) attrs.$set(type.attr, def.href); + } + inputAttrs.forEach(function(field) { + rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null; + attrs.$observe(field, function(expr) { + watchDeregFns[field](); + watchDeregFns[field] = scope.$watch( + expr, + function(newval) { + rawDef[field] = newval; + update(); + }, + true, + ); + }); + }); + update(); + scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update)); + scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update)); + if (!type.clickable) return; + hookFn = clickHook(element, $state, $timeout, type, getDef); + bindEvents(element, scope, hookFn, rawDef.uiStateOpts); + }, + }; + }, + ]; + /** + * `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active + * + * A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the + * related directive's state is active (and remove them when it is inactive). + * + * The primary use-case is to highlight the active link in navigation menus, + * distinguishing it from the inactive menu items. + * + * ### Linking to a `ui-sref` or `ui-state` + * `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element. + * If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**. + * + * ### Matching + * + * The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**. + * This is a "fuzzy match" which uses [[StateService.includes]]. + * + * The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active). + * This is an "exact match" which uses [[StateService.is]]. + * + * ### Parameter values + * If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted. + * This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted. + * + * #### Example: + * ```html + *
  • + * {{ user.lastName }} + *
  • + * ``` + * + * ### Examples + * + * Given the following template: + * #### Example: + * ```html + * + * ``` + * + * When the app state is `app.user` (or any child state), + * and contains the state parameter "user" with value "bilbobaggins", + * the resulting HTML will appear as (note the 'active' class): + * + * ```html + * + * ``` + * + * ### Glob mode + * + * It is possible to pass `ui-sref-active` an expression that evaluates to an object. + * The objects keys represent active class names and values represent the respective state names/globs. + * `ui-sref-active` will match if the current active state **includes** any of + * the specified state names/globs, even the abstract ones. + * + * #### Example: + * Given the following template, with "admin" being an abstract state: + * ```html + *
    + * Roles + *
    + * ``` + * + * Arrays are also supported as values in the `ngClass`-like interface. + * This allows multiple states to add `active` class. + * + * #### Example: + * Given the following template, with "admin.roles" being the current state, the class will be added too: + * ```html + *
    + * Roles + *
    + * ``` + * + * When the current state is "admin.roles" the "active" class will be applied to both the `
    ` and `` elements. + * It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`. + * + * ### Notes: + * + * - The class name is interpolated **once** during the directives link time (any further changes to the + * interpolated value are ignored). + * + * - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'` + */ + var uiSrefActiveDirective; + uiSrefActiveDirective = [ + '$state', + '$stateParams', + '$interpolate', + '$uiRouter', function $StateRefActiveDirective($state, $stateParams, $interpolate, $uiRouter) { - return { - restrict: 'A', - controller: ['$scope', '$element', '$attrs', - function ($scope, $element, $attrs) { - var states = []; - var activeEqClass; - var uiSrefActive; - // There probably isn't much point in $observing this - // uiSrefActive and uiSrefActiveEq share the same directive object with some - // slight difference in logic routing - activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope); - try { - uiSrefActive = $scope.$eval($attrs.uiSrefActive); - } - catch (e) { - // Do nothing. uiSrefActive is not a valid expression. - // Fall back to using $interpolate below - } - uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope); - setStatesFromDefinitionObject(uiSrefActive); - // Allow uiSref to communicate with uiSrefActive[Equals] - this.$$addStateInfo = function (newState, newParams) { - // we already got an explicit state provided by ui-sref-active, so we - // shadow the one that comes from ui-sref - if (isObject(uiSrefActive) && states.length > 0) { - return; - } - var deregister = addState(newState, newParams, uiSrefActive); - update(); - return deregister; - }; - function updateAfterTransition(trans) { - trans.promise.then(update, noop); - } - $scope.$on('$destroy', setupEventListeners()); - if ($uiRouter.globals.transition) { - updateAfterTransition($uiRouter.globals.transition); - } - function setupEventListeners() { - var deregisterStatesChangedListener = $uiRouter.stateRegistry.onStatesChanged(handleStatesChanged); - var deregisterOnStartListener = $uiRouter.transitionService.onStart({}, updateAfterTransition); - var deregisterStateChangeSuccessListener = $scope.$on('$stateChangeSuccess', update); - return function cleanUp() { - deregisterStatesChangedListener(); - deregisterOnStartListener(); - deregisterStateChangeSuccessListener(); - }; - } - function handleStatesChanged() { - setStatesFromDefinitionObject(uiSrefActive); - } - function setStatesFromDefinitionObject(statesDefinition) { - if (isObject(statesDefinition)) { - states = []; - forEach(statesDefinition, function (stateOrName, activeClass) { - // Helper function to abstract adding state. - var addStateForClass = function (stateOrName, activeClass) { - var ref = parseStateRef(stateOrName); - addState(ref.state, $scope.$eval(ref.paramExpr), activeClass); - }; - if (isString(stateOrName)) { - // If state is string, just add it. - addStateForClass(stateOrName, activeClass); - } - else if (isArray(stateOrName)) { - // If state is an array, iterate over it and add each array item individually. - forEach(stateOrName, function (stateOrName) { - addStateForClass(stateOrName, activeClass); - }); - } - }); - } - } - function addState(stateName, stateParams, activeClass) { - var state = $state.get(stateName, stateContext($element)); - var stateInfo = { - state: state || { name: stateName }, - params: stateParams, - activeClass: activeClass, - }; - states.push(stateInfo); - return function removeState() { - removeFrom(states)(stateInfo); - }; - } - // Update route state - function update() { - var splitClasses = function (str) { - return str.split(/\s/).filter(identity); - }; - var getClasses = function (stateList) { - return stateList.map(function (x) { return x.activeClass; }).map(splitClasses).reduce(unnestR, []); - }; - var allClasses = getClasses(states).concat(splitClasses(activeEqClass)).reduce(uniqR, []); - var fuzzyClasses = getClasses(states.filter(function (x) { return $state.includes(x.state.name, x.params); })); - var exactlyMatchesAny = !!states.filter(function (x) { return $state.is(x.state.name, x.params); }).length; - var exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : []; - var addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []); - var removeClasses = allClasses.filter(function (cls) { return !inArray(addClasses, cls); }); - $scope.$evalAsync(function () { - addClasses.forEach(function (className) { return $element.addClass(className); }); - removeClasses.forEach(function (className) { return $element.removeClass(className); }); - }); - } - update(); - }], - }; - }]; -ng.module('ui.router.state') + return { + restrict: 'A', + controller: [ + '$scope', + '$element', + '$attrs', + function($scope, $element, $attrs) { + var states = []; + var activeEqClass; + var uiSrefActive; + // There probably isn't much point in $observing this + // uiSrefActive and uiSrefActiveEq share the same directive object with some + // slight difference in logic routing + activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope); + try { + uiSrefActive = $scope.$eval($attrs.uiSrefActive); + } catch (e) { + // Do nothing. uiSrefActive is not a valid expression. + // Fall back to using $interpolate below + } + uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope); + setStatesFromDefinitionObject(uiSrefActive); + // Allow uiSref to communicate with uiSrefActive[Equals] + this.$$addStateInfo = function(newState, newParams) { + // we already got an explicit state provided by ui-sref-active, so we + // shadow the one that comes from ui-sref + if (isObject(uiSrefActive) && states.length > 0) { + return; + } + var deregister = addState(newState, newParams, uiSrefActive); + update(); + return deregister; + }; + function updateAfterTransition(trans) { + trans.promise.then(update, noop); + } + $scope.$on('$destroy', setupEventListeners()); + if ($uiRouter.globals.transition) { + updateAfterTransition($uiRouter.globals.transition); + } + function setupEventListeners() { + var deregisterStatesChangedListener = $uiRouter.stateRegistry.onStatesChanged(handleStatesChanged); + var deregisterOnStartListener = $uiRouter.transitionService.onStart({}, updateAfterTransition); + var deregisterStateChangeSuccessListener = $scope.$on('$stateChangeSuccess', update); + return function cleanUp() { + deregisterStatesChangedListener(); + deregisterOnStartListener(); + deregisterStateChangeSuccessListener(); + }; + } + function handleStatesChanged() { + setStatesFromDefinitionObject(uiSrefActive); + } + function setStatesFromDefinitionObject(statesDefinition) { + if (isObject(statesDefinition)) { + states = []; + forEach(statesDefinition, function(stateOrName, activeClass) { + // Helper function to abstract adding state. + var addStateForClass = function(stateOrName, activeClass) { + var ref = parseStateRef(stateOrName); + addState(ref.state, $scope.$eval(ref.paramExpr), activeClass); + }; + if (isString(stateOrName)) { + // If state is string, just add it. + addStateForClass(stateOrName, activeClass); + } else if (isArray(stateOrName)) { + // If state is an array, iterate over it and add each array item individually. + forEach(stateOrName, function(stateOrName) { + addStateForClass(stateOrName, activeClass); + }); + } + }); + } + } + function addState(stateName, stateParams, activeClass) { + var state = $state.get(stateName, stateContext($element)); + var stateInfo = { + state: state || { name: stateName }, + params: stateParams, + activeClass: activeClass, + }; + states.push(stateInfo); + return function removeState() { + removeFrom(states)(stateInfo); + }; + } + // Update route state + function update() { + var splitClasses = function(str) { + return str.split(/\s/).filter(identity); + }; + var getClasses = function(stateList) { + return stateList + .map(function(x) { + return x.activeClass; + }) + .map(splitClasses) + .reduce(unnestR, []); + }; + var allClasses = getClasses(states) + .concat(splitClasses(activeEqClass)) + .reduce(uniqR, []); + var fuzzyClasses = getClasses( + states.filter(function(x) { + return $state.includes(x.state.name, x.params); + }), + ); + var exactlyMatchesAny = !!states.filter(function(x) { + return $state.is(x.state.name, x.params); + }).length; + var exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : []; + var addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []); + var removeClasses = allClasses.filter(function(cls) { + return !inArray(addClasses, cls); + }); + $scope.$evalAsync(function() { + addClasses.forEach(function(className) { + return $element.addClass(className); + }); + removeClasses.forEach(function(className) { + return $element.removeClass(className); + }); + }); + } + update(); + }, + ], + }; + }, + ]; + ng + .module('ui.router.state') .directive('uiSref', uiSrefDirective) .directive('uiSrefActive', uiSrefActiveDirective) .directive('uiSrefActiveEq', uiSrefActiveDirective) - .directive('uiState', uiStateDirective); + .directive('uiState', uiStateDirective); /** for typedoc */ -/** @module ng1 */ /** for typedoc */ -/** - * `isState` Filter: truthy if the current state is the parameter - * - * Translates to [[StateService.is]] `$state.is("stateName")`. - * - * #### Example: - * ```html - *
    show if state is 'stateName'
    - * ``` - */ -$IsStateFilter.$inject = ['$state']; -function $IsStateFilter($state) { - var isFilter = function (state, params, options) { - return $state.is(state, params, options); + /** @module ng1 */ /** + * `isState` Filter: truthy if the current state is the parameter + * + * Translates to [[StateService.is]] `$state.is("stateName")`. + * + * #### Example: + * ```html + *
    show if state is 'stateName'
    + * ``` + */ + $IsStateFilter.$inject = ['$state']; + function $IsStateFilter($state) { + var isFilter = function(state, params, options) { + return $state.is(state, params, options); }; isFilter.$stateful = true; return isFilter; -} -/** - * `includedByState` Filter: truthy if the current state includes the parameter - * - * Translates to [[StateService.includes]]` $state.is("fullOrPartialStateName")`. - * - * #### Example: - * ```html - *
    show if state includes 'fullOrPartialStateName'
    - * ``` - */ -$IncludedByStateFilter.$inject = ['$state']; -function $IncludedByStateFilter($state) { - var includesFilter = function (state, params, options) { - return $state.includes(state, params, options); + } + /** + * `includedByState` Filter: truthy if the current state includes the parameter + * + * Translates to [[StateService.includes]]` $state.is("fullOrPartialStateName")`. + * + * #### Example: + * ```html + *
    show if state includes 'fullOrPartialStateName'
    + * ``` + */ + $IncludedByStateFilter.$inject = ['$state']; + function $IncludedByStateFilter($state) { + var includesFilter = function(state, params, options) { + return $state.includes(state, params, options); }; includesFilter.$stateful = true; return includesFilter; -} -ng.module('ui.router.state') + } + ng + .module('ui.router.state') .filter('isState', $IsStateFilter) .filter('includedByState', $IncludedByStateFilter); -/** - * @ng1api - * @module directives - */ /** for typedoc */ -/** - * `ui-view`: A viewport directive which is filled in by a view from the active state. - * - * ### Attributes - * - * - `name`: (Optional) A view name. - * The name should be unique amongst the other views in the same state. - * You can have views of the same name that live in different states. - * The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]). - * - * - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated. - * Uses [[$uiViewScroll]] to do the scrolling. - * - * - `onload`: Expression to evaluate whenever the view updates. - * - * #### Example: - * A view can be unnamed or named. - * ```html - * - *
    - * - * - *
    - * - * - * - * ``` - * - * You can only have one unnamed view within any template (or root html). If you are only using a - * single view and it is unnamed then you can populate it like so: - * - * ```html - *
    - * $stateProvider.state("home", { - * template: "

    HELLO!

    " - * }) - * ``` - * - * The above is a convenient shortcut equivalent to specifying your view explicitly with the - * [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name: - * - * ```js - * $stateProvider.state("home", { - * views: { - * "": { - * template: "

    HELLO!

    " - * } - * } - * }) - * ``` - * - * But typically you'll only use the views property if you name your view or have more than one view - * in the same template. There's not really a compelling reason to name a view if its the only one, - * but you could if you wanted, like so: - * - * ```html - *
    - * ``` - * - * ```js - * $stateProvider.state("home", { - * views: { - * "main": { - * template: "

    HELLO!

    " - * } - * } - * }) - * ``` - * - * Really though, you'll use views to set up multiple views: - * - * ```html - *
    - *
    - *
    - * ``` - * - * ```js - * $stateProvider.state("home", { - * views: { - * "": { - * template: "

    HELLO!

    " - * }, - * "chart": { - * template: "" - * }, - * "data": { - * template: "" - * } - * } - * }) - * ``` - * - * #### Examples for `autoscroll`: - * ```html - * - * - * - * - * - * - * - * ``` - * - * Resolve data: - * - * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this - * can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template. - * - * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the - * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which - * depends on `$resolve` data. - * - * #### Example: - * ```js - * $stateProvider.state('home', { - * template: '', - * resolve: { - * user: function(UserService) { return UserService.fetchUser(); } - * } - * }); - * ``` - */ -var uiView; -uiView = ['$view', '$animate', '$uiViewScroll', '$interpolate', '$q', - function $ViewDirective($view, $animate, $uiViewScroll, $interpolate, $q) { - function getRenderer(attrs, scope) { - return { - enter: function (element, target, cb) { - if (ng.version.minor > 2) { - $animate.enter(element, null, target).then(cb); - } - else { - $animate.enter(element, null, target, cb); - } - }, - leave: function (element, cb) { - if (ng.version.minor > 2) { - $animate.leave(element).then(cb); - } - else { - $animate.leave(element, cb); - } - }, + /** + * @ng1api + * @module directives + */ + /** + * `ui-view`: A viewport directive which is filled in by a view from the active state. + * + * ### Attributes + * + * - `name`: (Optional) A view name. + * The name should be unique amongst the other views in the same state. + * You can have views of the same name that live in different states. + * The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]). + * + * - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated. + * Uses [[$uiViewScroll]] to do the scrolling. + * + * - `onload`: Expression to evaluate whenever the view updates. + * + * #### Example: + * A view can be unnamed or named. + * ```html + * + *
    + * + * + *
    + * + * + * + * ``` + * + * You can only have one unnamed view within any template (or root html). If you are only using a + * single view and it is unnamed then you can populate it like so: + * + * ```html + *
    + * $stateProvider.state("home", { + * template: "

    HELLO!

    " + * }) + * ``` + * + * The above is a convenient shortcut equivalent to specifying your view explicitly with the + * [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name: + * + * ```js + * $stateProvider.state("home", { + * views: { + * "": { + * template: "

    HELLO!

    " + * } + * } + * }) + * ``` + * + * But typically you'll only use the views property if you name your view or have more than one view + * in the same template. There's not really a compelling reason to name a view if its the only one, + * but you could if you wanted, like so: + * + * ```html + *
    + * ``` + * + * ```js + * $stateProvider.state("home", { + * views: { + * "main": { + * template: "

    HELLO!

    " + * } + * } + * }) + * ``` + * + * Really though, you'll use views to set up multiple views: + * + * ```html + *
    + *
    + *
    + * ``` + * + * ```js + * $stateProvider.state("home", { + * views: { + * "": { + * template: "

    HELLO!

    " + * }, + * "chart": { + * template: "" + * }, + * "data": { + * template: "" + * } + * } + * }) + * ``` + * + * #### Examples for `autoscroll`: + * ```html + * + * + * + * + * + * + * + * ``` + * + * Resolve data: + * + * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this + * can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template. + * + * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the + * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which + * depends on `$resolve` data. + * + * #### Example: + * ```js + * $stateProvider.state('home', { + * template: '', + * resolve: { + * user: function(UserService) { return UserService.fetchUser(); } + * } + * }); + * ``` + */ + var uiView; + uiView = [ + '$view', + '$animate', + '$uiViewScroll', + '$interpolate', + '$q', + function $ViewDirective($view, $animate, $uiViewScroll, $interpolate, $q$$1) { + function getRenderer(attrs, scope) { + return { + enter: function(element, target, cb) { + if (ng.version.minor > 2) { + $animate.enter(element, null, target).then(cb); + } else { + $animate.enter(element, null, target, cb); + } + }, + leave: function(element, cb) { + if (ng.version.minor > 2) { + $animate.leave(element).then(cb); + } else { + $animate.leave(element, cb); + } + }, + }; + } + function configsEqual(config1, config2) { + return config1 === config2; + } + var rootData = { + $cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } }, + $uiView: {}, + }; + var directive = { + count: 0, + restrict: 'ECA', + terminal: true, + priority: 400, + transclude: 'element', + compile: function(tElement, tAttrs, $transclude) { + return function(scope, $element, attrs) { + var onloadExp = attrs['onload'] || '', + autoScrollExp = attrs['autoscroll'], + renderer = getRenderer(attrs, scope), + inherited = $element.inheritedData('$uiView') || rootData, + name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default'; + var previousEl, currentEl, currentScope, viewConfig, unregister; + var activeUIView = { + $type: 'ng1', + id: directive.count++, + name: name, + fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + '.' + name : name, + config: null, + configUpdated: configUpdatedCallback, + get creationContext() { + // The context in which this ui-view "tag" was created + var fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited); + // Allow + // See https://github.com/angular-ui/ui-router/issues/3355 + var fromParentTag = parse('$uiView.creationContext')(inherited); + return fromParentTagConfig || fromParentTag; + }, }; - } - function configsEqual(config1, config2) { - return config1 === config2; - } - var rootData = { - $cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } }, - $uiView: {}, - }; - var directive = { - count: 0, - restrict: 'ECA', - terminal: true, - priority: 400, - transclude: 'element', - compile: function (tElement, tAttrs, $transclude) { - return function (scope, $element, attrs) { - var onloadExp = attrs['onload'] || '', autoScrollExp = attrs['autoscroll'], renderer = getRenderer(attrs, scope), inherited = $element.inheritedData('$uiView') || rootData, name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default'; - var previousEl, currentEl, currentScope, viewConfig, unregister; - var activeUIView = { - $type: 'ng1', - id: directive.count++, - name: name, - fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + '.' + name : name, - config: null, - configUpdated: configUpdatedCallback, - get creationContext() { - var fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited); - // Allow - // See https://github.com/angular-ui/ui-router/issues/3355 - var fromParentTag = parse('$uiView.creationContext')(inherited); - return fromParentTagConfig || fromParentTag; - }, - }; - trace.traceUIViewEvent('Linking', activeUIView); - function configUpdatedCallback(config) { - if (config && !(config instanceof Ng1ViewConfig)) - return; - if (configsEqual(viewConfig, config)) - return; - trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context); - viewConfig = config; - updateView(config); - } - $element.data('$uiView', { $uiView: activeUIView }); - updateView(); - unregister = $view.registerUIView(activeUIView); - scope.$on('$destroy', function () { - trace.traceUIViewEvent('Destroying/Unregistering', activeUIView); - unregister(); - }); - function cleanupLastView() { - if (previousEl) { - trace.traceUIViewEvent('Removing (previous) el', previousEl.data('$uiView')); - previousEl.remove(); - previousEl = null; - } - if (currentScope) { - trace.traceUIViewEvent('Destroying scope', activeUIView); - currentScope.$destroy(); - currentScope = null; - } - if (currentEl) { - var _viewData_1 = currentEl.data('$uiViewAnim'); - trace.traceUIViewEvent('Animate out', _viewData_1); - renderer.leave(currentEl, function () { - _viewData_1.$$animLeave.resolve(); - previousEl = null; - }); - previousEl = currentEl; - currentEl = null; - } - } - function updateView(config) { - var newScope = scope.$new(); - var animEnter = $q.defer(), animLeave = $q.defer(); - var $uiViewData = { - $cfg: config, - $uiView: activeUIView, - }; - var $uiViewAnim = { - $animEnter: animEnter.promise, - $animLeave: animLeave.promise, - $$animLeave: animLeave, - }; - /** - * @ngdoc event - * @name ui.router.state.directive:ui-view#$viewContentLoading - * @eventOf ui.router.state.directive:ui-view - * @eventType emits on ui-view directive scope - * @description - * - * Fired once the view **begins loading**, *before* the DOM is rendered. - * - * @param {Object} event Event object. - * @param {string} viewName Name of the view. - */ - newScope.$emit('$viewContentLoading', name); - var cloned = $transclude(newScope, function (clone) { - clone.data('$uiViewAnim', $uiViewAnim); - clone.data('$uiView', $uiViewData); - renderer.enter(clone, $element, function onUIViewEnter() { - animEnter.resolve(); - if (currentScope) - currentScope.$emit('$viewContentAnimationEnded'); - if (isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) { - $uiViewScroll(clone); - } - }); - cleanupLastView(); - }); - currentEl = cloned; - currentScope = newScope; - /** - * @ngdoc event - * @name ui.router.state.directive:ui-view#$viewContentLoaded - * @eventOf ui.router.state.directive:ui-view - * @eventType emits on ui-view directive scope - * @description * - * Fired once the view is **loaded**, *after* the DOM is rendered. - * - * @param {Object} event Event object. - */ - currentScope.$emit('$viewContentLoaded', config || viewConfig); - currentScope.$eval(onloadExp); - } - }; - }, - }; - return directive; - }]; -$ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout']; -/** @hidden */ -function $ViewDirectiveFill($compile, $controller, $transitions, $view, $q, $timeout) { + trace.traceUIViewEvent('Linking', activeUIView); + function configUpdatedCallback(config) { + if (config && !(config instanceof Ng1ViewConfig)) return; + if (configsEqual(viewConfig, config)) return; + trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context); + viewConfig = config; + updateView(config); + } + $element.data('$uiView', { $uiView: activeUIView }); + updateView(); + unregister = $view.registerUIView(activeUIView); + scope.$on('$destroy', function() { + trace.traceUIViewEvent('Destroying/Unregistering', activeUIView); + unregister(); + }); + function cleanupLastView() { + if (previousEl) { + trace.traceUIViewEvent('Removing (previous) el', previousEl.data('$uiView')); + previousEl.remove(); + previousEl = null; + } + if (currentScope) { + trace.traceUIViewEvent('Destroying scope', activeUIView); + currentScope.$destroy(); + currentScope = null; + } + if (currentEl) { + var _viewData_1 = currentEl.data('$uiViewAnim'); + trace.traceUIViewEvent('Animate out', _viewData_1); + renderer.leave(currentEl, function() { + _viewData_1.$$animLeave.resolve(); + previousEl = null; + }); + previousEl = currentEl; + currentEl = null; + } + } + function updateView(config) { + var newScope = scope.$new(); + var animEnter = $q$$1.defer(), + animLeave = $q$$1.defer(); + var $uiViewData = { + $cfg: config, + $uiView: activeUIView, + }; + var $uiViewAnim = { + $animEnter: animEnter.promise, + $animLeave: animLeave.promise, + $$animLeave: animLeave, + }; + /** + * @ngdoc event + * @name ui.router.state.directive:ui-view#$viewContentLoading + * @eventOf ui.router.state.directive:ui-view + * @eventType emits on ui-view directive scope + * @description + * + * Fired once the view **begins loading**, *before* the DOM is rendered. + * + * @param {Object} event Event object. + * @param {string} viewName Name of the view. + */ + newScope.$emit('$viewContentLoading', name); + var cloned = $transclude(newScope, function(clone) { + clone.data('$uiViewAnim', $uiViewAnim); + clone.data('$uiView', $uiViewData); + renderer.enter(clone, $element, function onUIViewEnter() { + animEnter.resolve(); + if (currentScope) currentScope.$emit('$viewContentAnimationEnded'); + if ((isDefined(autoScrollExp) && !autoScrollExp) || scope.$eval(autoScrollExp)) { + $uiViewScroll(clone); + } + }); + cleanupLastView(); + }); + currentEl = cloned; + currentScope = newScope; + /** + * @ngdoc event + * @name ui.router.state.directive:ui-view#$viewContentLoaded + * @eventOf ui.router.state.directive:ui-view + * @eventType emits on ui-view directive scope + * @description * + * Fired once the view is **loaded**, *after* the DOM is rendered. + * + * @param {Object} event Event object. + */ + currentScope.$emit('$viewContentLoaded', config || viewConfig); + currentScope.$eval(onloadExp); + } + }; + }, + }; + return directive; + }, + ]; + $ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout']; + /** @hidden */ + function $ViewDirectiveFill($compile, $controller, $transitions, $view, $q$$1, $timeout) { var getControllerAs = parse('viewDecl.controllerAs'); var getResolveAs = parse('viewDecl.resolveAs'); return { - restrict: 'ECA', - priority: -400, - compile: function (tElement) { - var initial = tElement.html(); - tElement.empty(); - return function (scope, $element) { - var data = $element.data('$uiView'); - if (!data) { - $element.html(initial); - $compile($element.contents())(scope); - return; - } - var cfg = data.$cfg || { viewDecl: {}, getTemplate: noop }; - var resolveCtx = cfg.path && new ResolveContext(cfg.path); - $element.html(cfg.getTemplate($element, resolveCtx) || initial); - trace.traceUIViewFill(data.$uiView, $element.html()); - var link = $compile($element.contents()); - var controller = cfg.controller; - var controllerAs = getControllerAs(cfg); - var resolveAs = getResolveAs(cfg); - var locals = resolveCtx && getLocals(resolveCtx); - scope[resolveAs] = locals; - if (controller) { - var controllerInstance = $controller(controller, extend({}, locals, { $scope: scope, $element: $element })); - if (controllerAs) { - scope[controllerAs] = controllerInstance; - scope[controllerAs][resolveAs] = locals; - } - // TODO: Use $view service as a central point for registering component-level hooks - // Then, when a component is created, tell the $view service, so it can invoke hooks - // $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element }); - // scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element })); - $element.data('$ngControllerController', controllerInstance); - $element.children().data('$ngControllerController', controllerInstance); - registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg); - } - // Wait for the component to appear in the DOM - if (isString(cfg.viewDecl.component)) { - var cmp_1 = cfg.viewDecl.component; - var kebobName = kebobString(cmp_1); - var tagRegexp_1 = new RegExp("^(x-|data-)?" + kebobName + "$", 'i'); - var getComponentController = function () { - var directiveEl = [].slice.call($element[0].children) - .filter(function (el) { return el && el.tagName && tagRegexp_1.exec(el.tagName); }); - return directiveEl && ng.element(directiveEl).data("$" + cmp_1 + "Controller"); - }; - var deregisterWatch_1 = scope.$watch(getComponentController, function (ctrlInstance) { - if (!ctrlInstance) - return; - registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg); - deregisterWatch_1(); - }); - } - link(scope); + restrict: 'ECA', + priority: -400, + compile: function(tElement) { + var initial = tElement.html(); + tElement.empty(); + return function(scope, $element) { + var data = $element.data('$uiView'); + if (!data) { + $element.html(initial); + $compile($element.contents())(scope); + return; + } + var cfg = data.$cfg || { viewDecl: {}, getTemplate: noop }; + var resolveCtx = cfg.path && new ResolveContext(cfg.path); + $element.html(cfg.getTemplate($element, resolveCtx) || initial); + trace.traceUIViewFill(data.$uiView, $element.html()); + var link = $compile($element.contents()); + var controller = cfg.controller; + var controllerAs = getControllerAs(cfg); + var resolveAs = getResolveAs(cfg); + var locals = resolveCtx && getLocals(resolveCtx); + scope[resolveAs] = locals; + if (controller) { + var controllerInstance = $controller(controller, extend({}, locals, { $scope: scope, $element: $element })); + if (controllerAs) { + scope[controllerAs] = controllerInstance; + scope[controllerAs][resolveAs] = locals; + } + // TODO: Use $view service as a central point for registering component-level hooks + // Then, when a component is created, tell the $view service, so it can invoke hooks + // $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element }); + // scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element })); + $element.data('$ngControllerController', controllerInstance); + $element.children().data('$ngControllerController', controllerInstance); + registerControllerCallbacks($q$$1, $transitions, controllerInstance, scope, cfg); + } + // Wait for the component to appear in the DOM + if (isString(cfg.viewDecl.component)) { + var cmp_1 = cfg.viewDecl.component; + var kebobName = kebobString(cmp_1); + var tagRegexp_1 = new RegExp('^(x-|data-)?' + kebobName + '$', 'i'); + var getComponentController = function() { + var directiveEl = [].slice.call($element[0].children).filter(function(el) { + return el && el.tagName && tagRegexp_1.exec(el.tagName); + }); + return directiveEl && ng.element(directiveEl).data('$' + cmp_1 + 'Controller'); }; - }, + var deregisterWatch_1 = scope.$watch(getComponentController, function(ctrlInstance) { + if (!ctrlInstance) return; + registerControllerCallbacks($q$$1, $transitions, ctrlInstance, scope, cfg); + deregisterWatch_1(); + }); + } + link(scope); + }; + }, }; -} -/** @hidden */ -var hasComponentImpl = typeof ng.module('ui.router')['component'] === 'function'; -/** @hidden incrementing id */ -var _uiCanExitId = 0; -/** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */ -function registerControllerCallbacks($q, $transitions, controllerInstance, $scope, cfg) { + } + /** @hidden */ + var hasComponentImpl = typeof ng.module('ui.router')['component'] === 'function'; + /** @hidden incrementing id */ + var _uiCanExitId = 0; + /** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */ + function registerControllerCallbacks($q$$1, $transitions, controllerInstance, $scope, cfg) { // Call $onInit() ASAP if (isFunction(controllerInstance.$onInit) && !(cfg.viewDecl.component && hasComponentImpl)) { - controllerInstance.$onInit(); + controllerInstance.$onInit(); } var viewState = tail(cfg.path).state.self; var hookOptions = { bind: controllerInstance }; - // Add component-level hook for onParamsChange + // Add component-level hook for onUiParamsChanged if (isFunction(controllerInstance.uiOnParamsChanged)) { - var resolveContext = new ResolveContext(cfg.path); - var viewCreationTrans_1 = resolveContext.getResolvable('$transition$').data; - // Fire callback on any successful transition - var paramsUpdated = function ($transition$) { - // Exit early if the $transition$ is the same as the view was created within. - // Exit early if the $transition$ will exit the state the view is for. - if ($transition$ === viewCreationTrans_1 || $transition$.exiting().indexOf(viewState) !== -1) - return; - var toParams = $transition$.params('to'); - var fromParams = $transition$.params('from'); - var toSchema = $transition$.treeChanges().to.map(function (node) { return node.paramSchema; }).reduce(unnestR, []); - var fromSchema = $transition$.treeChanges().from.map(function (node) { return node.paramSchema; }).reduce(unnestR, []); - // Find the to params that have different values than the from params - var changedToParams = toSchema.filter(function (param) { - var idx = fromSchema.indexOf(param); - return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]); - }); - // Only trigger callback if a to param has changed or is new - if (changedToParams.length) { - var changedKeys_1 = changedToParams.map(function (x) { return x.id; }); - // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params. - var newValues = filter(toParams, function (val, key) { return changedKeys_1.indexOf(key) !== -1; }); - controllerInstance.uiOnParamsChanged(newValues, $transition$); - } + var resolveContext = new ResolveContext(cfg.path); + var viewCreationTrans_1 = resolveContext.getResolvable('$transition$').data; + // Fire callback on any successful transition + var paramsUpdated = function($transition$) { + // Exit early if the $transition$ is the same as the view was created within. + // Exit early if the $transition$ will exit the state the view is for. + if ($transition$ === viewCreationTrans_1 || $transition$.exiting().indexOf(viewState) !== -1) return; + var toParams = $transition$.params('to'); + var fromParams = $transition$.params('from'); + var getNodeSchema = function(node) { + return node.paramSchema; }; - $scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions)); + var toSchema = $transition$ + .treeChanges('to') + .map(getNodeSchema) + .reduce(unnestR, []); + var fromSchema = $transition$ + .treeChanges('from') + .map(getNodeSchema) + .reduce(unnestR, []); + // Find the to params that have different values than the from params + var changedToParams = toSchema.filter(function(param) { + var idx = fromSchema.indexOf(param); + return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]); + }); + // Only trigger callback if a to param has changed or is new + if (changedToParams.length) { + var changedKeys_1 = changedToParams.map(function(x) { + return x.id; + }); + // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params. + var newValues = filter(toParams, function(val$$1, key) { + return changedKeys_1.indexOf(key) !== -1; + }); + controllerInstance.uiOnParamsChanged(newValues, $transition$); + } + }; + $scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions)); } // Add component-level hook for uiCanExit if (isFunction(controllerInstance.uiCanExit)) { - var id_1 = _uiCanExitId++; - var cacheProp_1 = '_uiCanExitIds'; - // Returns true if a redirect transition already answered truthy - var prevTruthyAnswer_1 = function (trans) { - return !!trans && (trans[cacheProp_1] && trans[cacheProp_1][id_1] === true || prevTruthyAnswer_1(trans.redirectedFrom())); - }; - // If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition - var wrappedHook = function (trans) { - var promise; - var ids = trans[cacheProp_1] = trans[cacheProp_1] || {}; - if (!prevTruthyAnswer_1(trans)) { - promise = $q.when(controllerInstance.uiCanExit(trans)); - promise.then(function (val) { return ids[id_1] = (val !== false); }); - } - return promise; - }; - var criteria = { exiting: viewState.name }; - $scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions)); + var id_1 = _uiCanExitId++; + var cacheProp_1 = '_uiCanExitIds'; + // Returns true if a redirect transition already answered truthy + var prevTruthyAnswer_1 = function(trans) { + return ( + !!trans && + ((trans[cacheProp_1] && trans[cacheProp_1][id_1] === true) || prevTruthyAnswer_1(trans.redirectedFrom())) + ); + }; + // If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition + var wrappedHook = function(trans) { + var promise; + var ids = (trans[cacheProp_1] = trans[cacheProp_1] || {}); + if (!prevTruthyAnswer_1(trans)) { + promise = $q$$1.when(controllerInstance.uiCanExit(trans)); + promise.then(function(val$$1) { + return (ids[id_1] = val$$1 !== false); + }); + } + return promise; + }; + var criteria = { exiting: viewState.name }; + $scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions)); } -} -ng.module('ui.router.state').directive('uiView', uiView); -ng.module('ui.router.state').directive('uiView', $ViewDirectiveFill); + } + ng.module('ui.router.state').directive('uiView', uiView); + ng.module('ui.router.state').directive('uiView', $ViewDirectiveFill); /** */ -/** @module ng1 */ /** */ -/** @hidden */ -function $ViewScrollProvider() { + /** @module ng1 */ /** @hidden */ + function $ViewScrollProvider() { var useAnchorScroll = false; - this.useAnchorScroll = function () { - useAnchorScroll = true; + this.useAnchorScroll = function() { + useAnchorScroll = true; }; - this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) { - if (useAnchorScroll) { - return $anchorScroll; - } - return function ($element) { - return $timeout(function () { - $element[0].scrollIntoView(); - }, 0, false); - }; - }]; -} -ng.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider); + this.$get = [ + '$anchorScroll', + '$timeout', + function($anchorScroll, $timeout) { + if (useAnchorScroll) { + return $anchorScroll; + } + return function($element) { + return $timeout( + function() { + $element[0].scrollIntoView(); + }, + 0, + false, + ); + }; + }, + ]; + } + ng.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider); /** */ -/** - * Main entry point for angular 1.x build - * @module ng1 - */ /** */ -var index$1 = 'ui.router'; + /** + * Main entry point for angular 1.x build + * @module ng1 + */ var index$1 = 'ui.router'; -exports.default = index$1; -exports.core = index; -exports.watchDigests = watchDigests; -exports.getLocals = getLocals; -exports.getNg1ViewConfigFactory = getNg1ViewConfigFactory; -exports.ng1ViewsBuilder = ng1ViewsBuilder; -exports.Ng1ViewConfig = Ng1ViewConfig; -exports.StateProvider = StateProvider; -exports.UrlRouterProvider = UrlRouterProvider; -exports.root = root; -exports.fromJson = fromJson; -exports.toJson = toJson; -exports.forEach = forEach; -exports.extend = extend; -exports.equals = equals; -exports.identity = identity; -exports.noop = noop; -exports.createProxyFunctions = createProxyFunctions; -exports.inherit = inherit; -exports.inArray = inArray; -exports._inArray = _inArray; -exports.removeFrom = removeFrom; -exports._removeFrom = _removeFrom; -exports.pushTo = pushTo; -exports._pushTo = _pushTo; -exports.deregAll = deregAll; -exports.defaults = defaults; -exports.mergeR = mergeR; -exports.ancestors = ancestors; -exports.pick = pick; -exports.omit = omit; -exports.pluck = pluck; -exports.filter = filter; -exports.find = find; -exports.mapObj = mapObj; -exports.map = map; -exports.values = values; -exports.allTrueR = allTrueR; -exports.anyTrueR = anyTrueR; -exports.unnestR = unnestR; -exports.flattenR = flattenR; -exports.pushR = pushR; -exports.uniqR = uniqR; -exports.unnest = unnest; -exports.flatten = flatten; -exports.assertPredicate = assertPredicate; -exports.assertMap = assertMap; -exports.assertFn = assertFn; -exports.pairs = pairs; -exports.arrayTuples = arrayTuples; -exports.applyPairs = applyPairs; -exports.tail = tail; -exports.copy = copy; -exports._extend = _extend; -exports.silenceUncaughtInPromise = silenceUncaughtInPromise; -exports.silentRejection = silentRejection; -exports.notImplemented = notImplemented; -exports.services = services; -exports.Glob = Glob; -exports.curry = curry; -exports.compose = compose; -exports.pipe = pipe; -exports.prop = prop; -exports.propEq = propEq; -exports.parse = parse; -exports.not = not; -exports.and = and; -exports.or = or; -exports.all = all; -exports.any = any; -exports.is = is; -exports.eq = eq; -exports.val = val; -exports.invoke = invoke; -exports.pattern = pattern; -exports.isUndefined = isUndefined; -exports.isDefined = isDefined; -exports.isNull = isNull; -exports.isNullOrUndefined = isNullOrUndefined; -exports.isFunction = isFunction; -exports.isNumber = isNumber; -exports.isString = isString; -exports.isObject = isObject; -exports.isArray = isArray; -exports.isDate = isDate; -exports.isRegExp = isRegExp; -exports.isState = isState; -exports.isInjectable = isInjectable; -exports.isPromise = isPromise; -exports.Queue = Queue; -exports.maxLength = maxLength; -exports.padString = padString; -exports.kebobString = kebobString; -exports.functionToString = functionToString; -exports.fnToString = fnToString; -exports.stringify = stringify; -exports.beforeAfterSubstr = beforeAfterSubstr; -exports.hostRegex = hostRegex; -exports.stripLastPathElement = stripLastPathElement; -exports.splitHash = splitHash; -exports.splitQuery = splitQuery; -exports.splitEqual = splitEqual; -exports.trimHashVal = trimHashVal; -exports.splitOnDelim = splitOnDelim; -exports.joinNeighborsR = joinNeighborsR; -exports.Trace = Trace; -exports.trace = trace; -exports.Param = Param; -exports.ParamTypes = ParamTypes; -exports.StateParams = StateParams; -exports.ParamType = ParamType; -exports.PathNode = PathNode; -exports.PathUtils = PathUtils; -exports.resolvePolicies = resolvePolicies; -exports.defaultResolvePolicy = defaultResolvePolicy; -exports.Resolvable = Resolvable; -exports.NATIVE_INJECTOR_TOKEN = NATIVE_INJECTOR_TOKEN; -exports.ResolveContext = ResolveContext; -exports.resolvablesBuilder = resolvablesBuilder; -exports.StateBuilder = StateBuilder; -exports.StateObject = StateObject; -exports.StateMatcher = StateMatcher; -exports.StateQueueManager = StateQueueManager; -exports.StateRegistry = StateRegistry; -exports.StateService = StateService; -exports.TargetState = TargetState; -exports.HookBuilder = HookBuilder; -exports.matchState = matchState; -exports.RegisteredHook = RegisteredHook; -exports.makeEvent = makeEvent; -exports.Rejection = Rejection; -exports.Transition = Transition; -exports.TransitionHook = TransitionHook; -exports.TransitionEventType = TransitionEventType; -exports.defaultTransOpts = defaultTransOpts; -exports.TransitionService = TransitionService; -exports.UrlMatcher = UrlMatcher; -exports.UrlMatcherFactory = UrlMatcherFactory; -exports.UrlRouter = UrlRouter; -exports.UrlRuleFactory = UrlRuleFactory; -exports.BaseUrlRule = BaseUrlRule; -exports.UrlService = UrlService; -exports.ViewService = ViewService; -exports.UIRouterGlobals = UIRouterGlobals; -exports.UIRouter = UIRouter; -exports.$q = $q; -exports.$injector = $injector; -exports.BaseLocationServices = BaseLocationServices; -exports.HashLocationService = HashLocationService; -exports.MemoryLocationService = MemoryLocationService; -exports.PushStateLocationService = PushStateLocationService; -exports.MemoryLocationConfig = MemoryLocationConfig; -exports.BrowserLocationConfig = BrowserLocationConfig; -exports.keyValsToObjectR = keyValsToObjectR; -exports.getParams = getParams; -exports.parseUrl = parseUrl$1; -exports.buildUrl = buildUrl; -exports.locationPluginFactory = locationPluginFactory; -exports.servicesPlugin = servicesPlugin; -exports.hashLocationPlugin = hashLocationPlugin; -exports.pushStateLocationPlugin = pushStateLocationPlugin; -exports.memoryLocationPlugin = memoryLocationPlugin; -exports.UIRouterPluginBase = UIRouterPluginBase; + exports.default = index$1; + exports.core = index; + exports.watchDigests = watchDigests; + exports.getLocals = getLocals; + exports.getNg1ViewConfigFactory = getNg1ViewConfigFactory; + exports.ng1ViewsBuilder = ng1ViewsBuilder; + exports.Ng1ViewConfig = Ng1ViewConfig; + exports.StateProvider = StateProvider; + exports.UrlRouterProvider = UrlRouterProvider; + exports.root = root; + exports.fromJson = fromJson; + exports.toJson = toJson; + exports.forEach = forEach; + exports.extend = extend; + exports.equals = equals; + exports.identity = identity; + exports.noop = noop; + exports.createProxyFunctions = createProxyFunctions; + exports.inherit = inherit; + exports.inArray = inArray; + exports._inArray = _inArray; + exports.removeFrom = removeFrom; + exports._removeFrom = _removeFrom; + exports.pushTo = pushTo; + exports._pushTo = _pushTo; + exports.deregAll = deregAll; + exports.defaults = defaults; + exports.mergeR = mergeR; + exports.ancestors = ancestors; + exports.pick = pick; + exports.omit = omit; + exports.pluck = pluck; + exports.filter = filter; + exports.find = find; + exports.mapObj = mapObj; + exports.map = map; + exports.values = values; + exports.allTrueR = allTrueR; + exports.anyTrueR = anyTrueR; + exports.unnestR = unnestR; + exports.flattenR = flattenR; + exports.pushR = pushR; + exports.uniqR = uniqR; + exports.unnest = unnest; + exports.flatten = flatten; + exports.assertPredicate = assertPredicate; + exports.assertMap = assertMap; + exports.assertFn = assertFn; + exports.pairs = pairs; + exports.arrayTuples = arrayTuples; + exports.applyPairs = applyPairs; + exports.tail = tail; + exports.copy = copy; + exports._extend = _extend; + exports.silenceUncaughtInPromise = silenceUncaughtInPromise; + exports.silentRejection = silentRejection; + exports.notImplemented = notImplemented; + exports.services = services; + exports.Glob = Glob; + exports.curry = curry; + exports.compose = compose; + exports.pipe = pipe; + exports.prop = prop; + exports.propEq = propEq; + exports.parse = parse; + exports.not = not; + exports.and = and; + exports.or = or; + exports.all = all; + exports.any = any; + exports.is = is; + exports.eq = eq; + exports.val = val; + exports.invoke = invoke; + exports.pattern = pattern; + exports.isUndefined = isUndefined; + exports.isDefined = isDefined; + exports.isNull = isNull; + exports.isNullOrUndefined = isNullOrUndefined; + exports.isFunction = isFunction; + exports.isNumber = isNumber; + exports.isString = isString; + exports.isObject = isObject; + exports.isArray = isArray; + exports.isDate = isDate; + exports.isRegExp = isRegExp; + exports.isState = isState; + exports.isInjectable = isInjectable; + exports.isPromise = isPromise; + exports.Queue = Queue; + exports.maxLength = maxLength; + exports.padString = padString; + exports.kebobString = kebobString; + exports.functionToString = functionToString; + exports.fnToString = fnToString; + exports.stringify = stringify; + exports.beforeAfterSubstr = beforeAfterSubstr; + exports.hostRegex = hostRegex; + exports.stripLastPathElement = stripLastPathElement; + exports.splitHash = splitHash; + exports.splitQuery = splitQuery; + exports.splitEqual = splitEqual; + exports.trimHashVal = trimHashVal; + exports.splitOnDelim = splitOnDelim; + exports.joinNeighborsR = joinNeighborsR; + exports.Trace = Trace; + exports.trace = trace; + exports.Param = Param; + exports.ParamTypes = ParamTypes; + exports.StateParams = StateParams; + exports.ParamType = ParamType; + exports.PathNode = PathNode; + exports.PathUtils = PathUtils; + exports.resolvePolicies = resolvePolicies; + exports.defaultResolvePolicy = defaultResolvePolicy; + exports.Resolvable = Resolvable; + exports.NATIVE_INJECTOR_TOKEN = NATIVE_INJECTOR_TOKEN; + exports.ResolveContext = ResolveContext; + exports.resolvablesBuilder = resolvablesBuilder; + exports.StateBuilder = StateBuilder; + exports.StateObject = StateObject; + exports.StateMatcher = StateMatcher; + exports.StateQueueManager = StateQueueManager; + exports.StateRegistry = StateRegistry; + exports.StateService = StateService; + exports.TargetState = TargetState; + exports.HookBuilder = HookBuilder; + exports.matchState = matchState; + exports.RegisteredHook = RegisteredHook; + exports.makeEvent = makeEvent; + exports.Rejection = Rejection; + exports.Transition = Transition; + exports.TransitionHook = TransitionHook; + exports.TransitionEventType = TransitionEventType; + exports.defaultTransOpts = defaultTransOpts; + exports.TransitionService = TransitionService; + exports.UrlMatcher = UrlMatcher; + exports.UrlMatcherFactory = UrlMatcherFactory; + exports.UrlRouter = UrlRouter; + exports.UrlRuleFactory = UrlRuleFactory; + exports.BaseUrlRule = BaseUrlRule; + exports.UrlService = UrlService; + exports.ViewService = ViewService; + exports.UIRouterGlobals = UIRouterGlobals; + exports.UIRouter = UIRouter; + exports.$q = $q; + exports.$injector = $injector; + exports.BaseLocationServices = BaseLocationServices; + exports.HashLocationService = HashLocationService; + exports.MemoryLocationService = MemoryLocationService; + exports.PushStateLocationService = PushStateLocationService; + exports.MemoryLocationConfig = MemoryLocationConfig; + exports.BrowserLocationConfig = BrowserLocationConfig; + exports.keyValsToObjectR = keyValsToObjectR; + exports.getParams = getParams; + exports.parseUrl = parseUrl$1; + exports.buildUrl = buildUrl; + exports.locationPluginFactory = locationPluginFactory; + exports.servicesPlugin = servicesPlugin; + exports.hashLocationPlugin = hashLocationPlugin; + exports.pushStateLocationPlugin = pushStateLocationPlugin; + exports.memoryLocationPlugin = memoryLocationPlugin; + exports.UIRouterPluginBase = UIRouterPluginBase; -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); + Object.defineProperty(exports, '__esModule', { value: true }); +}); //# sourceMappingURL=angular-ui-router.js.map diff --git a/UI/WebServerResources/js/vendor/angular-ui-router.js.map b/UI/WebServerResources/js/vendor/angular-ui-router.js.map index eb3b27e11..b55e3edaa 100644 --- a/UI/WebServerResources/js/vendor/angular-ui-router.js.map +++ b/UI/WebServerResources/js/vendor/angular-ui-router.js.map @@ -85,87 +85,87 @@ "@uirouter/angularjs/src/index.ts" ], "sourcesContent": [ - "/**\n * @hidden\n * @module ng1\n */ /** */\ndeclare var angular;\nimport * as ng_from_import from 'angular';\nconst ng_from_global = angular;\n\nexport const ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;\n", - "/**\n * Higher order functions\n *\n * These utility functions are exported, but are subject to change without notice.\n *\n * @module common_hof\n */ /** */\n\nimport { Predicate } from './common';\n/**\n * Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function.\n *\n * Given a function with N parameters, returns a new function that supports partial application.\n * The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters,\n * where M is less than N, it returns a new function that accepts the remaining parameters. It continues to\n * accept more parameters until all N parameters have been supplied.\n *\n *\n * This contrived example uses a partially applied function as an predicate, which returns true\n * if an object is found in both arrays.\n * @example\n * ```\n * // returns true if an object is in both of the two arrays\n * function inBoth(array1, array2, object) {\n * return array1.indexOf(object) !== -1 &&\n * array2.indexOf(object) !== 1;\n * }\n * let obj1, obj2, obj3, obj4, obj5, obj6, obj7\n * let foos = [obj1, obj3]\n * let bars = [obj3, obj4, obj5]\n *\n * // A curried \"copy\" of inBoth\n * let curriedInBoth = curry(inBoth);\n * // Partially apply both the array1 and array2\n * let inFoosAndBars = curriedInBoth(foos, bars);\n *\n * // Supply the final argument; since all arguments are\n * // supplied, the original inBoth function is then called.\n * let obj1InBoth = inFoosAndBars(obj1); // false\n *\n * // Use the inFoosAndBars as a predicate.\n * // Filter, on each iteration, supplies the final argument\n * let allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ];\n * let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ]\n *\n * ```\n *\n * Stolen from: http://stackoverflow.com/questions/4394747/javascript-curry-function\n *\n * @param fn\n * @returns {*|function(): (*|any)}\n */\nexport function curry(fn: Function): Function {\n const initial_args = [].slice.apply(arguments, [1]);\n const func_args_length = fn.length;\n\n function curried(args: any[]) {\n if (args.length >= func_args_length)\n return fn.apply(null, args);\n return function () {\n return curried(args.concat([].slice.apply(arguments)));\n };\n }\n return curried(initial_args);\n}\n\n\n\n/**\n * Given a varargs list of functions, returns a function that composes the argument functions, right-to-left\n * given: f(x), g(x), h(x)\n * let composed = compose(f,g,h)\n * then, composed is: f(g(h(x)))\n */\nexport function compose() {\n const args = arguments;\n const start = args.length - 1;\n return function() {\n let i = start, result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n}\n\n/**\n * Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right\n * given: f(x), g(x), h(x)\n * let piped = pipe(f,g,h);\n * then, piped is: h(g(f(x)))\n */\nexport function pipe(...funcs: Function[]): (obj: any) => any {\n return compose.apply(null, [].slice.call(arguments).reverse());\n}\n\n/**\n * Given a property name, returns a function that returns that property from an object\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = prop(\"name\");\n * getName(obj) === \"blarg\"\n */\nexport const prop = (name: string) =>\n (obj: any) => obj && obj[name];\n\n/**\n * Given a property name and a value, returns a function that returns a boolean based on whether\n * the passed object has a property that matches the value\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = propEq(\"name\", \"blarg\");\n * getName(obj) === true\n */\nexport const propEq = curry((name: string, _val: any, obj: any) => obj && obj[name] === _val);\n\n/**\n * Given a dotted property name, returns a function that returns a nested property from an object, or undefined\n * let obj = { id: 1, nestedObj: { foo: 1, name: \"blarg\" }, };\n * let getName = prop(\"nestedObj.name\");\n * getName(obj) === \"blarg\"\n * let propNotFound = prop(\"this.property.doesnt.exist\");\n * propNotFound(obj) === undefined\n */\nexport const parse = (name: string) =>\n pipe.apply(null, name.split('.').map(prop));\n\n/**\n * Given a function that returns a truthy or falsey value, returns a\n * function that returns the opposite (falsey or truthy) value given the same inputs\n */\nexport const not: (fn: Predicate) => Predicate = (fn: Predicate) =>\n (...args: any[]) => !fn.apply(null, args);\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if both functions return truthy for the given arguments\n */\nexport function and(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) && fn2.apply(null, args);\n}\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if at least one of the functions returns truthy for the given arguments\n */\nexport function or(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) || fn2.apply(null, args);\n}\n\n/**\n * Check if all the elements of an array match a predicate function\n *\n * @param fn1 a predicate function `fn1`\n * @returns a function which takes an array and returns true if `fn1` is true for all elements of the array\n */\nexport const all = (fn1: Predicate) =>\n (arr: any[]) => arr.reduce((b, x) => b && !!fn1(x), true) as boolean;\n\n// tslint:disable-next-line:variable-name\nexport const any = (fn1: Predicate) =>\n (arr: any[]) => arr.reduce((b, x) => b || !!fn1(x), false) as boolean;\n\n/** Given a class, returns a Predicate function that returns true if the object is of that class */\nexport const is = (ctor: { new(...args): T }) =>\n (obj: any): obj is T =>\n (obj != null && obj.constructor === ctor || obj instanceof ctor);\n\n/** Given a value, returns a Predicate function that returns true if another value is === equal to the original value */\nexport const eq: (comp: any) => Predicate = (value: any) => (other: any) =>\n value === other;\n\n/** Given a value, returns a function which returns the value */\nexport const val = (v: T) => () => v;\n\n\n\nexport function invoke(fnName: string): Function;\nexport function invoke(fnName: string, args: any[]): Function;\nexport function invoke(fnName: string, args?: any[]): Function {\n return (obj: any) =>\n obj[fnName].apply(obj, args);\n}\n\n/**\n * Sorta like Pattern Matching (a functional programming conditional construct)\n *\n * See http://c2.com/cgi/wiki?PatternMatching\n *\n * This is a conditional construct which allows a series of predicates and output functions\n * to be checked and then applied. Each predicate receives the input. If the predicate\n * returns truthy, then its matching output function (mapping function) is provided with\n * the input and, then the result is returned.\n *\n * Each combination (2-tuple) of predicate + output function should be placed in an array\n * of size 2: [ predicate, mapFn ]\n *\n * These 2-tuples should be put in an outer array.\n *\n * @example\n * ```\n *\n * // Here's a 2-tuple where the first element is the isString predicate\n * // and the second element is a function that returns a description of the input\n * let firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ];\n *\n * // Second tuple: predicate \"isNumber\", mapfn returns a description\n * let secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ];\n *\n * let third = [ (input) => input === null, (input) => `Oh, null...` ];\n *\n * let fourth = [ (input) => input === undefined, (input) => `notdefined` ];\n *\n * let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]);\n *\n * console.log(descriptionOf(undefined)); // 'notdefined'\n * console.log(descriptionOf(55)); // '(55) That's a number!'\n * console.log(descriptionOf(\"foo\")); // 'Here's your string foo'\n * ```\n *\n * @param struct A 2D array. Each element of the array should be an array, a 2-tuple,\n * with a Predicate and a mapping/output function\n * @returns {function(any): *}\n */\nexport function pattern(struct: Function[][]): Function {\n return function(x: any) {\n for (let i = 0; i < struct.length; i++) {\n if (struct[i][0](x)) return struct[i][1](x);\n }\n };\n}\n\n", - "/**\n * @coreapi\n * @module core\n */\n/**\n * Matches state names using glob-like pattern strings.\n *\n * Globs can be used in specific APIs including:\n *\n * - [[StateService.is]]\n * - [[StateService.includes]]\n * - The first argument to Hook Registration functions like [[TransitionService.onStart]]\n * - [[HookMatchCriteria]] and [[HookMatchCriterion]]\n *\n * A `Glob` string is a pattern which matches state names.\n * Nested state names are split into segments (separated by a dot) when processing.\n * The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz']\n *\n * Globs work according to the following rules:\n *\n * ### Exact match:\n *\n * The glob `'A.B'` matches the state named exactly `'A.B'`.\n *\n * | Glob |Matches states named|Does not match state named|\n * |:------------|:--------------------|:---------------------|\n * | `'A'` | `'A'` | `'B'` , `'A.C'` |\n * | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` |\n * | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`|\n *\n * ### Single star (`*`)\n *\n * A single star (`*`) is a wildcard that matches exactly one segment.\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:---------------------|:--------------------------|\n * | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` |\n * | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` |\n * | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`|\n *\n * ### Double star (`**`)\n *\n * A double star (`'**'`) is a wildcard that matches *zero or more segments*\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:----------------------------------------------|:----------------------------------|\n * | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) |\n * | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` |\n * | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` |\n * | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` |\n *\n */\nexport class Glob {\n text: string;\n glob: Array;\n regexp: RegExp;\n\n /** Returns true if the string has glob-like characters in it */\n static is(text: string) {\n return !!/[!,*]+/.exec(text);\n }\n\n /** Returns a glob from the string, or null if the string isn't Glob-like */\n static fromString(text: string) {\n return Glob.is(text) ? new Glob(text) : null;\n }\n\n constructor(text: string) {\n this.text = text;\n this.glob = text.split('.');\n\n const regexpString = this.text.split('.')\n .map(seg => {\n if (seg === '**') return '(?:|(?:\\\\.[^.]*)*)';\n if (seg === '*') return '\\\\.[^.]*';\n return '\\\\.' + seg;\n }).join('');\n\n this.regexp = new RegExp('^' + regexpString + '$');\n }\n\n matches(name: string) {\n return this.regexp.test('.' + name);\n }\n}\n", - "/**\n * @coreapi\n * @module state\n */\n/** for typedoc */\nimport { StateDeclaration, _ViewDeclaration, _StateDeclaration, LazyLoadResult } from './interface';\nimport { defaults, values, find, inherit } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { Param } from '../params/param';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { TargetState } from './targetState';\nimport { Transition } from '../transition/transition';\nimport { Glob } from '../common/glob';\nimport { isObject, isFunction } from '../common/predicates';\n\n/**\n * Internal representation of a UI-Router state.\n *\n * Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]].\n *\n * A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object.\n *\n * This class prototypally inherits from the corresponding [[StateDeclaration]].\n * Each of its own properties (i.e., `hasOwnProperty`) are built using builders from the [[StateBuilder]].\n */\nexport class StateObject {\n /** The parent [[StateObject]] */\n public parent: StateObject;\n\n /** The name used to register the state */\n public name: string;\n\n /** Prototypally inherits from [[StateDeclaration.abstract]] */\n public abstract: boolean;\n\n /** Prototypally inherits from [[StateDeclaration.resolve]] */\n public resolve: ({ [key: string]: (string|any[]|Function) }|any[]);\n\n /** A list of [[Resolvable]] objects. The internal representation of [[resolve]]. */\n public resolvables: Resolvable[];\n\n /** Prototypally inherits from [[StateDeclaration.resolvePolicy]] */\n public resolvePolicy: any;\n\n /** A compiled URLMatcher which detects when the state's URL is matched */\n public url: UrlMatcher;\n\n /** The parameters for the state, built from the URL and [[StateDeclaration.params]] */\n public params: { [key: string]: Param };\n\n /**\n * The views for the state.\n * Note: `@uirouter/core` does not register a builder for views.\n * The framework specific code should register a `views` builder.\n */\n public views: { [key: string]: _ViewDeclaration; };\n\n /**\n * The original [[StateDeclaration]] used to build this [[StateObject]].\n * Note: `this` object also prototypally inherits from the `self` declaration object.\n */\n public self: StateDeclaration;\n\n /** The nearest parent [[StateObject]] which has a URL */\n public navigable: StateObject;\n\n /** The parent [[StateObject]] objects from this state up to the root */\n public path: StateObject[];\n\n /**\n * Prototypally inherits from [[StateDeclaration.data]]\n * Note: This is the only field on the [[StateDeclaration]] which is mutated.\n * The definition object's `data` field is replaced with a new object\n * which prototypally inherits from the parent state definition's `data` field.\n */\n public data: any;\n\n /**\n * An object containing the parent States' names as keys and\n * true as their values.\n */\n public includes: { [name: string]: boolean };\n\n /** Prototypally inherits from [[StateDeclaration.onExit]] */\n public onExit: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onRetain]] */\n public onRetain: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onEnter]] */\n public onEnter: TransitionStateHookFn;\n\n /** Prototypally inherits from [[StateDeclaration.lazyLoad]] */\n public lazyLoad: (transition: Transition, state: StateDeclaration) => Promise;\n\n /** Prototypally inherits from [[StateDeclaration.redirectTo]] */\n redirectTo: (\n string |\n (($transition$: Transition) => TargetState) |\n { state: (string|StateDeclaration), params: { [key: string]: any }}\n );\n\n /** @hidden */\n __stateObjectCache: {\n /** Might be null */\n nameGlob?: Glob,\n };\n\n /**\n * Create a state object to put the private/internal implementation details onto.\n * The object's prototype chain looks like:\n * (Internal State Object) -> (Copy of State.prototype) -> (State Declaration object) -> (State Declaration's prototype...)\n *\n * @param stateDecl the user-supplied State Declaration\n * @returns {StateObject} an internal State object\n */\n static create(stateDecl: _StateDeclaration): StateObject {\n stateDecl = StateObject.isStateClass(stateDecl) ? new stateDecl() : stateDecl;\n\n const state = inherit(inherit(stateDecl, StateObject.prototype)) as StateObject;\n stateDecl.$$state = () => state;\n state.self = stateDecl;\n state.__stateObjectCache = {\n nameGlob: Glob.fromString(state.name), // might return null\n };\n return state;\n }\n\n /** Predicate which returns true if the object is an class with @State() decorator */\n static isStateClass = (stateDecl: _StateDeclaration): stateDecl is ({ new (): StateDeclaration }) =>\n isFunction(stateDecl) && stateDecl['__uiRouterState'] === true;\n\n /** Predicate which returns true if the object is an internal [[StateObject]] object */\n static isState = (obj: any): obj is StateObject =>\n isObject(obj['__stateObjectCache']);\n\n\n /** @deprecated use State.create() */\n constructor(config?: StateDeclaration) {\n return StateObject.create(config || {});\n }\n\n /**\n * Returns true if the provided parameter is the same state.\n *\n * Compares the identity of the state against the passed value, which is either an object\n * reference to the actual `State` instance, the original definition object passed to\n * `$stateProvider.state()`, or the fully-qualified name.\n *\n * @param ref Can be one of (a) a `State` instance, (b) an object that was passed\n * into `$stateProvider.state()`, (c) the fully-qualified name of a state as a string.\n * @returns Returns `true` if `ref` matches the current `State` instance.\n */\n is(ref: StateObject|StateDeclaration|string): boolean {\n return this === ref || this.self === ref || this.fqn() === ref;\n }\n\n /**\n * @deprecated this does not properly handle dot notation\n * @returns Returns a dot-separated name of the state.\n */\n fqn(): string {\n if (!this.parent || !(this.parent instanceof this.constructor)) return this.name;\n const name = this.parent.fqn();\n return name ? name + '.' + this.name : this.name;\n }\n\n /**\n * Returns the root node of this state's tree.\n *\n * @returns The root of this state's tree.\n */\n root(): StateObject {\n return this.parent && this.parent.root() || this;\n }\n\n /**\n * Gets the state's `Param` objects\n *\n * Gets the list of [[Param]] objects owned by the state.\n * If `opts.inherit` is true, it also includes the ancestor states' [[Param]] objects.\n * If `opts.matchingKeys` exists, returns only `Param`s whose `id` is a key on the `matchingKeys` object\n *\n * @param opts options\n */\n parameters(opts?: { inherit?: boolean, matchingKeys?: any }): Param[] {\n opts = defaults(opts, { inherit: true, matchingKeys: null });\n const inherited = opts.inherit && this.parent && this.parent.parameters() || [];\n return inherited.concat(values(this.params))\n .filter(param => !opts.matchingKeys || opts.matchingKeys.hasOwnProperty(param.id));\n }\n\n /**\n * Returns a single [[Param]] that is owned by the state\n *\n * If `opts.inherit` is true, it also searches the ancestor states` [[Param]]s.\n * @param id the name of the [[Param]] to return\n * @param opts options\n */\n parameter(id: string, opts: { inherit?: boolean } = {}): Param {\n return (\n this.url && this.url.parameter(id, opts) ||\n find(values(this.params), propEq('id', id)) ||\n opts.inherit && this.parent && this.parent.parameter(id)\n );\n }\n\n toString() {\n return this.fqn();\n }\n}\n", - "/** Predicates\n *\n * These predicates return true/false based on the input.\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_predicates\n */\n/** */\nimport { and, not, pipe, prop, or } from './hof';\nimport { Predicate } from './common'; // has or is using\nimport { StateObject } from '../state/stateObject';\n\nconst toStr = Object.prototype.toString;\nconst tis = (t: string) => (x: any) => typeof(x) === t;\nexport const isUndefined = tis('undefined');\nexport const isDefined = not(isUndefined);\nexport const isNull = (o: any) => o === null;\nexport const isNullOrUndefined = or(isNull, isUndefined);\nexport const isFunction: (x: any) => x is Function = tis('function');\nexport const isNumber: (x: any) => x is number = tis('number');\nexport const isString = <(x: any) => x is string> tis('string');\nexport const isObject = (x: any) => x !== null && typeof x === 'object';\nexport const isArray = Array.isArray;\nexport const isDate: (x: any) => x is Date = ((x: any) => toStr.call(x) === '[object Date]');\nexport const isRegExp: (x: any) => x is RegExp = ((x: any) => toStr.call(x) === '[object RegExp]');\nexport const isState: (x: any) => x is StateObject = StateObject.isState;\n\n/**\n * Predicate which checks if a value is injectable\n *\n * A value is \"injectable\" if it is a function, or if it is an ng1 array-notation-style array\n * where all the elements in the array are Strings, except the last one, which is a Function\n */\nexport function isInjectable(val: any) {\n if (isArray(val) && val.length) {\n const head = val.slice(0, -1), tail = val.slice(-1);\n return !(head.filter(not(isString)).length || tail.filter(not(isFunction)).length);\n }\n return isFunction(val);\n}\n\n/**\n * Predicate which checks if a value looks like a Promise\n *\n * It is probably a Promise if it's an object, and it has a `then` property which is a Function\n */\nexport const isPromise = <(x: any) => x is Promise> and(isObject, pipe(prop('then'), isFunction));\n\n", + "/**\n * @hidden\n * @module ng1\n */ /** */\ndeclare var angular;\nimport * as ng_from_import from 'angular';\nconst ng_from_global = angular;\n\nexport const ng = ng_from_import && ng_from_import.module ? ng_from_import : ng_from_global;\n", + "/**\n * Higher order functions\n *\n * These utility functions are exported, but are subject to change without notice.\n *\n * @module common_hof\n */ /** */\n\nimport { Predicate } from './common';\n/**\n * Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function.\n *\n * Given a function with N parameters, returns a new function that supports partial application.\n * The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters,\n * where M is less than N, it returns a new function that accepts the remaining parameters. It continues to\n * accept more parameters until all N parameters have been supplied.\n *\n *\n * This contrived example uses a partially applied function as an predicate, which returns true\n * if an object is found in both arrays.\n * @example\n * ```\n * // returns true if an object is in both of the two arrays\n * function inBoth(array1, array2, object) {\n * return array1.indexOf(object) !== -1 &&\n * array2.indexOf(object) !== 1;\n * }\n * let obj1, obj2, obj3, obj4, obj5, obj6, obj7\n * let foos = [obj1, obj3]\n * let bars = [obj3, obj4, obj5]\n *\n * // A curried \"copy\" of inBoth\n * let curriedInBoth = curry(inBoth);\n * // Partially apply both the array1 and array2\n * let inFoosAndBars = curriedInBoth(foos, bars);\n *\n * // Supply the final argument; since all arguments are\n * // supplied, the original inBoth function is then called.\n * let obj1InBoth = inFoosAndBars(obj1); // false\n *\n * // Use the inFoosAndBars as a predicate.\n * // Filter, on each iteration, supplies the final argument\n * let allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ];\n * let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ]\n *\n * ```\n *\n * Stolen from: http://stackoverflow.com/questions/4394747/javascript-curry-function\n *\n * @param fn\n * @returns {*|function(): (*|any)}\n */\nexport function curry(fn: Function): Function {\n const initial_args = [].slice.apply(arguments, [1]);\n const func_args_length = fn.length;\n\n function curried(args: any[]) {\n if (args.length >= func_args_length) return fn.apply(null, args);\n return function() {\n return curried(args.concat([].slice.apply(arguments)));\n };\n }\n return curried(initial_args);\n}\n\n/**\n * Given a varargs list of functions, returns a function that composes the argument functions, right-to-left\n * given: f(x), g(x), h(x)\n * let composed = compose(f,g,h)\n * then, composed is: f(g(h(x)))\n */\nexport function compose() {\n const args = arguments;\n const start = args.length - 1;\n return function() {\n let i = start,\n result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n}\n\n/**\n * Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right\n * given: f(x), g(x), h(x)\n * let piped = pipe(f,g,h);\n * then, piped is: h(g(f(x)))\n */\nexport function pipe(...funcs: Function[]): (obj: any) => any {\n return compose.apply(null, [].slice.call(arguments).reverse());\n}\n\n/**\n * Given a property name, returns a function that returns that property from an object\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = prop(\"name\");\n * getName(obj) === \"blarg\"\n */\nexport const prop = (name: string) => (obj: any) => obj && obj[name];\n\n/**\n * Given a property name and a value, returns a function that returns a boolean based on whether\n * the passed object has a property that matches the value\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = propEq(\"name\", \"blarg\");\n * getName(obj) === true\n */\nexport const propEq = curry((name: string, _val: any, obj: any) => obj && obj[name] === _val);\n\n/**\n * Given a dotted property name, returns a function that returns a nested property from an object, or undefined\n * let obj = { id: 1, nestedObj: { foo: 1, name: \"blarg\" }, };\n * let getName = prop(\"nestedObj.name\");\n * getName(obj) === \"blarg\"\n * let propNotFound = prop(\"this.property.doesnt.exist\");\n * propNotFound(obj) === undefined\n */\nexport const parse = (name: string) => pipe.apply(null, name.split('.').map(prop));\n\n/**\n * Given a function that returns a truthy or falsey value, returns a\n * function that returns the opposite (falsey or truthy) value given the same inputs\n */\nexport const not: (fn: Predicate) => Predicate = (fn: Predicate) => (...args: any[]) =>\n !fn.apply(null, args);\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if both functions return truthy for the given arguments\n */\nexport function and(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) && fn2.apply(null, args);\n}\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if at least one of the functions returns truthy for the given arguments\n */\nexport function or(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) || fn2.apply(null, args);\n}\n\n/**\n * Check if all the elements of an array match a predicate function\n *\n * @param fn1 a predicate function `fn1`\n * @returns a function which takes an array and returns true if `fn1` is true for all elements of the array\n */\nexport const all = (fn1: Predicate) => (arr: any[]) => arr.reduce((b, x) => b && !!fn1(x), true) as boolean;\n\n// tslint:disable-next-line:variable-name\nexport const any = (fn1: Predicate) => (arr: any[]) => arr.reduce((b, x) => b || !!fn1(x), false) as boolean;\n\n/** Given a class, returns a Predicate function that returns true if the object is of that class */\nexport const is = (ctor: { new (...args): T }) => (obj: any): obj is T =>\n (obj != null && obj.constructor === ctor) || obj instanceof ctor;\n\n/** Given a value, returns a Predicate function that returns true if another value is === equal to the original value */\nexport const eq: (comp: any) => Predicate = (value: any) => (other: any) => value === other;\n\n/** Given a value, returns a function which returns the value */\nexport const val = (v: T) => () => v;\n\nexport function invoke(fnName: string): Function;\nexport function invoke(fnName: string, args: any[]): Function;\nexport function invoke(fnName: string, args?: any[]): Function {\n return (obj: any) => obj[fnName].apply(obj, args);\n}\n\n/**\n * Sorta like Pattern Matching (a functional programming conditional construct)\n *\n * See http://c2.com/cgi/wiki?PatternMatching\n *\n * This is a conditional construct which allows a series of predicates and output functions\n * to be checked and then applied. Each predicate receives the input. If the predicate\n * returns truthy, then its matching output function (mapping function) is provided with\n * the input and, then the result is returned.\n *\n * Each combination (2-tuple) of predicate + output function should be placed in an array\n * of size 2: [ predicate, mapFn ]\n *\n * These 2-tuples should be put in an outer array.\n *\n * @example\n * ```\n *\n * // Here's a 2-tuple where the first element is the isString predicate\n * // and the second element is a function that returns a description of the input\n * let firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ];\n *\n * // Second tuple: predicate \"isNumber\", mapfn returns a description\n * let secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ];\n *\n * let third = [ (input) => input === null, (input) => `Oh, null...` ];\n *\n * let fourth = [ (input) => input === undefined, (input) => `notdefined` ];\n *\n * let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]);\n *\n * console.log(descriptionOf(undefined)); // 'notdefined'\n * console.log(descriptionOf(55)); // '(55) That's a number!'\n * console.log(descriptionOf(\"foo\")); // 'Here's your string foo'\n * ```\n *\n * @param struct A 2D array. Each element of the array should be an array, a 2-tuple,\n * with a Predicate and a mapping/output function\n * @returns {function(any): *}\n */\nexport function pattern(struct: Function[][]): Function {\n return function(x: any) {\n for (let i = 0; i < struct.length; i++) {\n if (struct[i][0](x)) return struct[i][1](x);\n }\n };\n}\n", + "/**\n * @coreapi\n * @module core\n */\n/**\n * Matches state names using glob-like pattern strings.\n *\n * Globs can be used in specific APIs including:\n *\n * - [[StateService.is]]\n * - [[StateService.includes]]\n * - The first argument to Hook Registration functions like [[TransitionService.onStart]]\n * - [[HookMatchCriteria]] and [[HookMatchCriterion]]\n *\n * A `Glob` string is a pattern which matches state names.\n * Nested state names are split into segments (separated by a dot) when processing.\n * The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz']\n *\n * Globs work according to the following rules:\n *\n * ### Exact match:\n *\n * The glob `'A.B'` matches the state named exactly `'A.B'`.\n *\n * | Glob |Matches states named|Does not match state named|\n * |:------------|:--------------------|:---------------------|\n * | `'A'` | `'A'` | `'B'` , `'A.C'` |\n * | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` |\n * | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`|\n *\n * ### Single star (`*`)\n *\n * A single star (`*`) is a wildcard that matches exactly one segment.\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:---------------------|:--------------------------|\n * | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` |\n * | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` |\n * | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`|\n *\n * ### Double star (`**`)\n *\n * A double star (`'**'`) is a wildcard that matches *zero or more segments*\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:----------------------------------------------|:----------------------------------|\n * | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) |\n * | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` |\n * | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` |\n * | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` |\n *\n */\nexport class Glob {\n text: string;\n glob: Array;\n regexp: RegExp;\n\n /** Returns true if the string has glob-like characters in it */\n static is(text: string) {\n return !!/[!,*]+/.exec(text);\n }\n\n /** Returns a glob from the string, or null if the string isn't Glob-like */\n static fromString(text: string) {\n return Glob.is(text) ? new Glob(text) : null;\n }\n\n constructor(text: string) {\n this.text = text;\n this.glob = text.split('.');\n\n const regexpString = this.text\n .split('.')\n .map(seg => {\n if (seg === '**') return '(?:|(?:\\\\.[^.]*)*)';\n if (seg === '*') return '\\\\.[^.]*';\n return '\\\\.' + seg;\n })\n .join('');\n\n this.regexp = new RegExp('^' + regexpString + '$');\n }\n\n matches(name: string) {\n return this.regexp.test('.' + name);\n }\n}\n", + "/**\n * @coreapi\n * @module state\n */\n/** for typedoc */\nimport { StateDeclaration, _ViewDeclaration, _StateDeclaration, LazyLoadResult } from './interface';\nimport { defaults, values, find, inherit } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { Param } from '../params/param';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { TargetState } from './targetState';\nimport { Transition } from '../transition/transition';\nimport { Glob } from '../common/glob';\nimport { isObject, isFunction } from '../common/predicates';\n\n/**\n * Internal representation of a UI-Router state.\n *\n * Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]].\n *\n * A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object.\n *\n * This class prototypally inherits from the corresponding [[StateDeclaration]].\n * Each of its own properties (i.e., `hasOwnProperty`) are built using builders from the [[StateBuilder]].\n */\nexport class StateObject {\n /** The parent [[StateObject]] */\n public parent: StateObject;\n\n /** The name used to register the state */\n public name: string;\n\n /** Prototypally inherits from [[StateDeclaration.abstract]] */\n public abstract: boolean;\n\n /** Prototypally inherits from [[StateDeclaration.resolve]] */\n public resolve: { [key: string]: string | any[] | Function } | any[];\n\n /** A list of [[Resolvable]] objects. The internal representation of [[resolve]]. */\n public resolvables: Resolvable[];\n\n /** Prototypally inherits from [[StateDeclaration.resolvePolicy]] */\n public resolvePolicy: any;\n\n /** A compiled URLMatcher which detects when the state's URL is matched */\n public url: UrlMatcher;\n\n /** The parameters for the state, built from the URL and [[StateDeclaration.params]] */\n public params: { [key: string]: Param };\n\n /**\n * The views for the state.\n * Note: `@uirouter/core` does not register a builder for views.\n * The framework specific code should register a `views` builder.\n */\n public views: { [key: string]: _ViewDeclaration };\n\n /**\n * The original [[StateDeclaration]] used to build this [[StateObject]].\n * Note: `this` object also prototypally inherits from the `self` declaration object.\n */\n public self: StateDeclaration;\n\n /** The nearest parent [[StateObject]] which has a URL */\n public navigable: StateObject;\n\n /** The parent [[StateObject]] objects from this state up to the root */\n public path: StateObject[];\n\n /**\n * Prototypally inherits from [[StateDeclaration.data]]\n * Note: This is the only field on the [[StateDeclaration]] which is mutated.\n * The definition object's `data` field is replaced with a new object\n * which prototypally inherits from the parent state definition's `data` field.\n */\n public data: any;\n\n /**\n * An object containing the parent States' names as keys and\n * true as their values.\n */\n public includes: { [name: string]: boolean };\n\n /** Prototypally inherits from [[StateDeclaration.onExit]] */\n public onExit: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onRetain]] */\n public onRetain: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onEnter]] */\n public onEnter: TransitionStateHookFn;\n\n /** Prototypally inherits from [[StateDeclaration.lazyLoad]] */\n public lazyLoad: (transition: Transition, state: StateDeclaration) => Promise;\n\n /** Prototypally inherits from [[StateDeclaration.redirectTo]] */\n redirectTo:\n | string\n | (($transition$: Transition) => TargetState)\n | { state: string | StateDeclaration; params: { [key: string]: any } };\n\n /** @hidden */\n __stateObjectCache: {\n /** Might be null */\n nameGlob?: Glob;\n };\n\n /**\n * Create a state object to put the private/internal implementation details onto.\n * The object's prototype chain looks like:\n * (Internal State Object) -> (Copy of State.prototype) -> (State Declaration object) -> (State Declaration's prototype...)\n *\n * @param stateDecl the user-supplied State Declaration\n * @returns {StateObject} an internal State object\n */\n static create(stateDecl: _StateDeclaration): StateObject {\n stateDecl = StateObject.isStateClass(stateDecl) ? new stateDecl() : stateDecl;\n\n const state = inherit(inherit(stateDecl, StateObject.prototype)) as StateObject;\n stateDecl.$$state = () => state;\n state.self = stateDecl;\n state.__stateObjectCache = {\n nameGlob: Glob.fromString(state.name), // might return null\n };\n return state;\n }\n\n /** Predicate which returns true if the object is an class with @State() decorator */\n static isStateClass = (stateDecl: _StateDeclaration): stateDecl is { new (): StateDeclaration } =>\n isFunction(stateDecl) && stateDecl['__uiRouterState'] === true;\n\n /** Predicate which returns true if the object is an internal [[StateObject]] object */\n static isState = (obj: any): obj is StateObject => isObject(obj['__stateObjectCache']);\n\n /** @deprecated use State.create() */\n constructor(config?: StateDeclaration) {\n return StateObject.create(config || {});\n }\n\n /**\n * Returns true if the provided parameter is the same state.\n *\n * Compares the identity of the state against the passed value, which is either an object\n * reference to the actual `State` instance, the original definition object passed to\n * `$stateProvider.state()`, or the fully-qualified name.\n *\n * @param ref Can be one of (a) a `State` instance, (b) an object that was passed\n * into `$stateProvider.state()`, (c) the fully-qualified name of a state as a string.\n * @returns Returns `true` if `ref` matches the current `State` instance.\n */\n is(ref: StateObject | StateDeclaration | string): boolean {\n return this === ref || this.self === ref || this.fqn() === ref;\n }\n\n /**\n * @deprecated this does not properly handle dot notation\n * @returns Returns a dot-separated name of the state.\n */\n fqn(): string {\n if (!this.parent || !(this.parent instanceof this.constructor)) return this.name;\n const name = this.parent.fqn();\n return name ? name + '.' + this.name : this.name;\n }\n\n /**\n * Returns the root node of this state's tree.\n *\n * @returns The root of this state's tree.\n */\n root(): StateObject {\n return (this.parent && this.parent.root()) || this;\n }\n\n /**\n * Gets the state's `Param` objects\n *\n * Gets the list of [[Param]] objects owned by the state.\n * If `opts.inherit` is true, it also includes the ancestor states' [[Param]] objects.\n * If `opts.matchingKeys` exists, returns only `Param`s whose `id` is a key on the `matchingKeys` object\n *\n * @param opts options\n */\n parameters(opts?: { inherit?: boolean; matchingKeys?: any }): Param[] {\n opts = defaults(opts, { inherit: true, matchingKeys: null });\n const inherited = (opts.inherit && this.parent && this.parent.parameters()) || [];\n return inherited\n .concat(values(this.params))\n .filter(param => !opts.matchingKeys || opts.matchingKeys.hasOwnProperty(param.id));\n }\n\n /**\n * Returns a single [[Param]] that is owned by the state\n *\n * If `opts.inherit` is true, it also searches the ancestor states` [[Param]]s.\n * @param id the name of the [[Param]] to return\n * @param opts options\n */\n parameter(id: string, opts: { inherit?: boolean } = {}): Param {\n return (\n (this.url && this.url.parameter(id, opts)) ||\n find(values(this.params), propEq('id', id)) ||\n (opts.inherit && this.parent && this.parent.parameter(id))\n );\n }\n\n toString() {\n return this.fqn();\n }\n}\n", + "/** Predicates\n *\n * These predicates return true/false based on the input.\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_predicates\n */\n/** */\nimport { and, not, pipe, prop, or } from './hof';\nimport { Predicate } from './common'; // has or is using\nimport { StateObject } from '../state/stateObject';\n\nconst toStr = Object.prototype.toString;\nconst tis = (t: string) => (x: any) => typeof x === t;\nexport const isUndefined = tis('undefined');\nexport const isDefined = not(isUndefined);\nexport const isNull = (o: any) => o === null;\nexport const isNullOrUndefined = or(isNull, isUndefined);\nexport const isFunction: (x: any) => x is Function = tis('function');\nexport const isNumber: (x: any) => x is number = tis('number');\nexport const isString = <(x: any) => x is string>tis('string');\nexport const isObject = (x: any) => x !== null && typeof x === 'object';\nexport const isArray = Array.isArray;\nexport const isDate: (x: any) => x is Date = ((x: any) => toStr.call(x) === '[object Date]');\nexport const isRegExp: (x: any) => x is RegExp = ((x: any) => toStr.call(x) === '[object RegExp]');\nexport const isState: (x: any) => x is StateObject = StateObject.isState;\n\n/**\n * Predicate which checks if a value is injectable\n *\n * A value is \"injectable\" if it is a function, or if it is an ng1 array-notation-style array\n * where all the elements in the array are Strings, except the last one, which is a Function\n */\nexport function isInjectable(val: any) {\n if (isArray(val) && val.length) {\n const head = val.slice(0, -1),\n tail = val.slice(-1);\n return !(head.filter(not(isString)).length || tail.filter(not(isFunction)).length);\n }\n return isFunction(val);\n}\n\n/**\n * Predicate which checks if a value looks like a Promise\n *\n * It is probably a Promise if it's an object, and it has a `then` property which is a Function\n */\nexport const isPromise = <(x: any) => x is Promise>and(isObject, pipe(prop('then'), isFunction));\n", "/**\n * This module is a stub for core services such as Dependency Injection or Browser Location.\n * Core services may be implemented by a specific framework, such as ng1 or ng2, or be pure javascript.\n *\n * @module common\n */\n/** for typedoc */\nimport { IInjectable, Obj } from './common';\nimport { Disposable } from '../interface';\nimport { UrlParts } from '../url/interface';\n\nexport let notImplemented = (fnname: string) => () => {\n throw new Error(`${fnname}(): No coreservices implementation for UI-Router is loaded.`);\n};\n\nconst services: CoreServices = {\n $q: undefined,\n $injector: undefined,\n};\n\nexport interface $QLikeDeferred {\n resolve: (val?: any) => void;\n reject: (reason?: any) => void;\n promise: Promise;\n}\n\nexport interface $QLike {\n when(value?: T | PromiseLike): Promise;\n reject(reason: any): Promise;\n defer(): $QLikeDeferred;\n all(promises: { [key: string]: Promise }): Promise;\n all(promises: Promise[]): Promise;\n}\n\nexport interface $InjectorLike {\n strictDi?: boolean;\n get(token: any): any;\n get(token: any): T;\n has(token: any): boolean;\n invoke(fn: IInjectable, context?: any, locals?: Obj): any;\n annotate(fn: IInjectable, strictDi?: boolean): any[];\n}\n\nexport interface CoreServices {\n $q: $QLike;\n $injector: $InjectorLike;\n}\n\nexport interface LocationServices extends Disposable {\n /**\n * Gets the current url string\n *\n * The URL is normalized using the internal [[path]]/[[search]]/[[hash]] values.\n *\n * For example, the URL may be stored in the hash ([[HashLocationServices]]) or\n * have a base HREF prepended ([[PushStateLocationServices]]).\n *\n * The raw URL in the browser might be:\n *\n * ```\n * http://mysite.com/somepath/index.html#/internal/path/123?param1=foo#anchor\n * ```\n *\n * or\n *\n * ```\n * http://mysite.com/basepath/internal/path/123?param1=foo#anchor\n * ```\n *\n * then this method returns:\n *\n * ```\n * /internal/path/123?param1=foo#anchor\n * ```\n *\n *\n * #### Example:\n * ```js\n * locationServices.url(); // \"/some/path?query=value#anchor\"\n * ```\n *\n * @returns the current value of the url, as a string.\n */\n url(): string;\n\n /**\n * Updates the url, or gets the current url\n *\n * Updates the url, changing it to the value in `newurl`\n *\n * #### Example:\n * ```js\n * locationServices.url(\"/some/path?query=value#anchor\", true);\n * ```\n *\n * @param newurl The new value for the URL.\n * This url should reflect only the new internal [[path]], [[search]], and [[hash]] values.\n * It should not include the protocol, site, port, or base path of an absolute HREF.\n * @param replace When true, replaces the current history entry (instead of appending it) with this new url\n * @param state The history's state object, i.e., pushState (if the LocationServices implementation supports it)\n * @return the url (after potentially being processed)\n */\n url(newurl: string, replace?: boolean, state?: any): string;\n\n /**\n * Gets the path part of the current url\n *\n * If the current URL is `/some/path?query=value#anchor`, this returns `/some/path`\n *\n * @return the path portion of the url\n */\n path(): string;\n\n /**\n * Gets the search part of the current url as an object\n *\n * If the current URL is `/some/path?query=value#anchor`, this returns `{ query: 'value' }`\n *\n * @return the search (querystring) portion of the url, as an object\n */\n search(): { [key: string]: any };\n\n /**\n * Gets the hash part of the current url\n *\n * If the current URL is `/some/path?query=value#anchor`, this returns `anchor`\n *\n * @return the hash (anchor) portion of the url\n */\n hash(): string;\n\n /**\n * Registers a url change handler\n *\n * #### Example:\n * ```js\n * let deregisterFn = locationServices.onChange((evt) => console.log(\"url change\", evt));\n * ```\n *\n * @param callback a function that will be called when the url is changing\n * @return a function that de-registers the callback\n */\n onChange(callback: Function): Function;\n}\n\n/**\n * This service returns the location configuration\n *\n * This service returns information about the location configuration.\n * This service is primarily used when building URLs (e.g., for `hrefs`)\n */\nexport interface LocationConfig extends Disposable {\n /**\n * Gets the port, e.g., `80`\n *\n * @return the port number\n */\n port(): number;\n /**\n * Gets the protocol, e.g., `http`\n *\n * @return the protocol\n */\n protocol(): string;\n /**\n * Gets the host, e.g., `localhost`\n *\n * @return the protocol\n */\n host(): string;\n /**\n * Gets the base Href, e.g., `http://localhost/approot/`\n *\n * @return the application's base href\n */\n baseHref(): string;\n /**\n * Returns true when running in pushstate mode\n *\n * @return true when running in pushstate mode\n */\n html5Mode(): boolean;\n /**\n * Gets the hashPrefix (when not running in pushstate mode)\n *\n * If the current url is `http://localhost/app#!/uirouter/path/#anchor`, it returns `!` which is the prefix for the \"hashbang\" portion.\n *\n * @return the hash prefix\n */\n hashPrefix(): string;\n /**\n * Sets the hashPrefix (when not running in pushstate mode)\n *\n * @return the new hash prefix\n */\n hashPrefix(newprefix: string): string;\n}\n\nexport { services };\n", - "/**\n * Random utility functions used in the UI-Router code\n *\n * These functions are exported, but are subject to change without notice.\n *\n * @preferred\n * @module common\n */\n/** for typedoc */\nimport { isFunction, isString, isArray, isRegExp, isDate } from './predicates';\nimport { all, any, prop, curry, not } from './hof';\nimport { services } from './coreservices';\nimport { StateObject } from '../state/stateObject';\n\ndeclare const global;\nexport const root: any = (typeof self === 'object' && self.self === self && self) ||\n (typeof global === 'object' && global.global === global && global) || this;\nconst angular = root.angular || {};\n\nexport const fromJson = angular.fromJson || JSON.parse.bind(JSON);\nexport const toJson = angular.toJson || JSON.stringify.bind(JSON);\nexport const forEach = angular.forEach || _forEach;\nexport const extend = Object.assign || _extend;\nexport const equals = angular.equals || _equals;\nexport function identity(x: any) { return x; }\nexport function noop(): any {}\n\nexport type Mapper = (x: X, key?: (string|number)) => T;\nexport interface TypedMap { [key: string]: T; }\nexport type Predicate = (x?: X) => boolean;\n/**\n * An ng1-style injectable\n *\n * This could be a (non-minified) function such as:\n * ```js\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an explicitly annotated function (minify safe)\n * ```js\n * injectableFunction.$inject = [ 'SomeDependency' ];\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an array style annotated function (minify safe)\n * ```js\n * ['SomeDependency', function injectableFunction(SomeDependency) {\n *\n * }];\n * ```\n *\n * @publicapi\n */\nexport type IInjectable = (Function|any[]);\n\nexport interface Obj extends Object {\n [key: string]: any;\n}\n\n/**\n * Builds proxy functions on the `to` object which pass through to the `from` object.\n *\n * For each key in `fnNames`, creates a proxy function on the `to` object.\n * The proxy function calls the real function on the `from` object.\n *\n *\n * #### Example:\n * This example creates an new class instance whose functions are prebound to the new'd object.\n * ```js\n * class Foo {\n * constructor(data) {\n * // Binds all functions from Foo.prototype to 'this',\n * // then copies them to 'this'\n * bindFunctions(Foo.prototype, this, this);\n * this.data = data;\n * }\n *\n * log() {\n * console.log(this.data);\n * }\n * }\n *\n * let myFoo = new Foo([1,2,3]);\n * var logit = myFoo.log;\n * logit(); // logs [1, 2, 3] from the myFoo 'this' instance\n * ```\n *\n * #### Example:\n * This example creates a bound version of a service function, and copies it to another object\n * ```\n *\n * var SomeService = {\n * this.data = [3, 4, 5];\n * this.log = function() {\n * console.log(this.data);\n * }\n * }\n *\n * // Constructor fn\n * function OtherThing() {\n * // Binds all functions from SomeService to SomeService,\n * // then copies them to 'this'\n * bindFunctions(SomeService, this, SomeService);\n * }\n *\n * let myOtherThing = new OtherThing();\n * myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'\n * ```\n *\n * @param source A function that returns the source object which contains the original functions to be bound\n * @param target A function that returns the target object which will receive the bound functions\n * @param bind A function that returns the object which the functions will be bound to\n * @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object)\n * @param latebind If true, the binding of the function is delayed until the first time it's invoked\n */\nexport function createProxyFunctions(source: Function, target: Obj, bind: Function, fnNames?: string[], latebind = false): Obj {\n const bindFunction = (fnName) =>\n source()[fnName].bind(bind());\n\n const makeLateRebindFn = fnName => function lateRebindFunction() {\n target[fnName] = bindFunction(fnName);\n return target[fnName].apply(null, arguments);\n };\n\n fnNames = fnNames || Object.keys(source());\n\n return fnNames.reduce((acc, name) => {\n acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name);\n return acc;\n }, target);\n}\n\n\n/**\n * prototypal inheritance helper.\n * Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it\n */\nexport const inherit = (parent: Obj, extra?: Obj) =>\n extend(Object.create(parent), extra);\n\n/** Given an array, returns true if the object is found in the array, (using indexOf) */\nexport const inArray: typeof _inArray = curry(_inArray) as any;\nexport function _inArray(array: any[], obj: any): boolean;\nexport function _inArray(array: any[]): (obj: any) => boolean;\nexport function _inArray(array, obj?): any {\n return array.indexOf(obj) !== -1;\n}\n\n/**\n * Given an array, and an item, if the item is found in the array, it removes it (in-place).\n * The same array is returned\n */\nexport const removeFrom: typeof _removeFrom = curry(_removeFrom) as any;\nexport function _removeFrom(array: T[], obj: T): T[];\nexport function _removeFrom(array: T[]): (obj: T) => T[];\nexport function _removeFrom(array, obj?) {\n const idx = array.indexOf(obj);\n if (idx >= 0) array.splice(idx, 1);\n return array;\n}\n\n/** pushes a values to an array and returns the value */\nexport const pushTo: typeof _pushTo = curry(_pushTo) as any;\nexport function _pushTo(arr: T[], val: T): T ;\nexport function _pushTo(arr: T[]): (val: T) => T ;\nexport function _pushTo(arr, val?): any {\n return (arr.push(val), val);\n}\n\n/** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */\nexport const deregAll = (functions: Function[]) =>\n functions.slice().forEach(fn => {\n typeof fn === 'function' && fn();\n removeFrom(functions, fn);\n });\n/**\n * Applies a set of defaults to an options object. The options object is filtered\n * to only those properties of the objects in the defaultsList.\n * Earlier objects in the defaultsList take precedence when applying defaults.\n */\nexport function defaults(opts, ...defaultsList: Obj[]) {\n const _defaultsList = defaultsList.concat({}).reverse();\n const defaultVals = extend.apply(null, _defaultsList);\n return extend({}, defaultVals, pick(opts || {}, Object.keys(defaultVals)));\n}\n\n/** Reduce function that merges each element of the list into a single object, using extend */\nexport const mergeR = (memo: Obj, item: Obj) => extend(memo, item);\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nexport function ancestors(first: StateObject, second: StateObject) {\n const path: StateObject[] = [];\n\n for (const n in first.path) { // tslint:disable-line:forin\n if (first.path[n] !== second.path[n]) break;\n path.push(first.path[n]);\n }\n return path;\n}\n\n/**\n * Return a copy of the object only containing the whitelisted properties.\n *\n * #### Example:\n * ```\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the whitelisted property names\n */\nexport function pick(obj: Obj, propNames: string[]): Obj {\n const objCopy = {};\n for (const _prop in obj) {\n if (propNames.indexOf(_prop) !== -1) {\n objCopy[_prop] = obj[_prop];\n }\n }\n return objCopy;\n}\n\n/**\n * Return a copy of the object omitting the blacklisted properties.\n *\n * @example\n * ```\n *\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = omit(foo, ['a', 'b']); // { c: 3 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the blacklisted property names\n */\nexport function omit(obj: Obj, propNames: string[]): Obj {\n return Object.keys(obj)\n .filter(not(inArray(propNames)))\n .reduce((acc, key) => (acc[key] = obj[key], acc), {});\n}\n\n\n/** Given an array of objects, maps each element to a named property of the element. */\nexport function pluck(collection: Obj[], propName: string): T[];\n/** Given an object, maps each property of the object to a named property of the property. */\nexport function pluck(collection: { [key: string]: any }, propName: string): { [key: string]: any };\n/**\n * Maps an array, or object to a property (by name)\n */\nexport function pluck(collection: any, propName: string): any {\n return map(collection, > prop(propName));\n}\n\n\n/** Given an array of objects, returns a new array containing only the elements which passed the callback predicate */\nexport function filter(collection: T[], callback: (t: T, key?: number) => boolean): T[];\n/** Given an object, returns a new object with only those properties that passed the callback predicate */\nexport function filter(collection: TypedMap, callback: (t: T, key?: string) => boolean): TypedMap;\n/** Filters an Array or an Object's properties based on a predicate */\nexport function filter(collection: any, callback: Function): T {\n const arr = isArray(collection), result: any = arr ? [] : {};\n const accept = arr ? x => result.push(x) : (x, key) => result[key] = x;\n forEach(collection, function(item, i) {\n if (callback(item, i)) accept(item, i);\n });\n return result;\n}\n\n\n/** Given an object, return the first property of that object which passed the callback predicate */\nexport function find(collection: TypedMap, callback: Predicate): T;\n/** Given an array of objects, returns the first object which passed the callback predicate */\nexport function find(collection: T[], callback: Predicate): T;\n/** Finds an object from an array, or a property of an object, that matches a predicate */\nexport function find(collection: any, callback: any) {\n let result;\n\n forEach(collection, function(item, i) {\n if (result) return;\n if (callback(item, i)) result = item;\n });\n\n return result;\n}\n\n/** Given an object, returns a new object, where each property is transformed by the callback function */\nexport let mapObj: (collection: { [key: string]: T }, callback: Mapper, target?: typeof collection) => { [key: string]: U } = map;\n/** Given an array, returns a new array, where each element is transformed by the callback function */\nexport function map(collection: T[], callback: Mapper, target?: typeof collection): U[];\nexport function map(collection: { [key: string]: T }, callback: Mapper, target?: typeof collection): { [key: string]: U };\n/** Maps an array or object properties using a callback function */\nexport function map(collection: any, callback: any, target: typeof collection): any {\n target = target || (isArray(collection) ? [] : {});\n forEach(collection, (item, i) => target[i] = callback(item, i));\n return target;\n}\n\n/**\n * Given an object, return its enumerable property values\n *\n * @example\n * ```\n *\n * let foo = { a: 1, b: 2, c: 3 }\n * let vals = values(foo); // [ 1, 2, 3 ]\n * ```\n */\nexport const values: ( (obj: TypedMap) => T[]) = (obj: Obj) =>\n Object.keys(obj).map(key => obj[key]);\n\n/**\n * Reduce function that returns true if all of the values are truthy.\n *\n * @example\n * ```\n *\n * let vals = [ 1, true, {}, \"hello world\"];\n * vals.reduce(allTrueR, true); // true\n *\n * vals.push(0);\n * vals.reduce(allTrueR, true); // false\n * ```\n */\nexport const allTrueR = (memo: boolean, elem: any) => memo && elem;\n\n/**\n * Reduce function that returns true if any of the values are truthy.\n *\n * * @example\n * ```\n *\n * let vals = [ 0, null, undefined ];\n * vals.reduce(anyTrueR, true); // false\n *\n * vals.push(\"hello world\");\n * vals.reduce(anyTrueR, true); // true\n * ```\n */\nexport const anyTrueR = (memo: boolean, elem: any) => memo || elem;\n\n/**\n * Reduce function which un-nests a single level of arrays\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnestR = (memo: any[], elem: any[]) => memo.concat(elem);\n\n/**\n * Reduce function which recursively un-nests all arrays\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flattenR = (memo: any[], elem: any) =>\n isArray(elem) ? memo.concat(elem.reduce(flattenR, [])) : pushR(memo, elem);\n\n/**\n * Reduce function that pushes an object to an array, then returns the array.\n * Mostly just for [[flattenR]] and [[uniqR]]\n */\nexport function pushR(arr: any[], obj: any) {\n arr.push(obj);\n return arr;\n}\n\n/** Reduce function that filters out duplicates */\nexport const uniqR = (acc: T[], token: T): T[] =>\n inArray(acc, token) ? acc : pushR(acc, token);\n\n/**\n * Return a new array with a single level of arrays unnested.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * unnest(input) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnest = (arr: any[]) => arr.reduce(unnestR, []);\n/**\n * Return a completely flattened version of an array.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * flatten(input) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flatten = (arr: any[]) => arr.reduce(flattenR, []);\n\n/**\n * Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.\n * @example\n * ```\n *\n * let isNumber = (obj) => typeof(obj) === 'number';\n * let allNumbers = [ 1, 2, 3, 4, 5 ];\n * allNumbers.filter(assertPredicate(isNumber)); //OK\n *\n * let oneString = [ 1, 2, 3, 4, \"5\" ];\n * oneString.filter(assertPredicate(isNumber, \"Not all numbers\")); // throws Error(\"\"Not all numbers\"\");\n * ```\n */\nexport const assertPredicate: (predicate: Predicate, errMsg: (string|Function)) => Predicate = assertFn;\n/**\n * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.\n * @example\n * ```\n *\n * var data = { foo: 1, bar: 2 };\n *\n * let keys = [ 'foo', 'bar' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // values is [1, 2]\n *\n * let keys = [ 'foo', 'bar', 'baz' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // throws Error(\"Key not found\")\n * ```\n */\nexport const assertMap: (mapFn: (t: T) => U, errMsg: (string|Function)) => (t: T) => U = assertFn;\nexport function assertFn(predicateOrMap: Function, errMsg: (string|Function) = 'assert failure'): any {\n return (obj) => {\n const result = predicateOrMap(obj);\n if (!result) {\n throw new Error(isFunction(errMsg) ? ( errMsg)(obj) : errMsg);\n }\n return result;\n };\n}\n\n/**\n * Like _.pairs: Given an object, returns an array of key/value pairs\n *\n * @example\n * ```\n *\n * pairs({ foo: \"FOO\", bar: \"BAR }) // [ [ \"foo\", \"FOO\" ], [ \"bar\": \"BAR\" ] ]\n * ```\n */\nexport const pairs = (obj: Obj) =>\n Object.keys(obj).map(key => [ key, obj[key]] );\n\n/**\n * Given two or more parallel arrays, returns an array of tuples where\n * each tuple is composed of [ a[i], b[i], ... z[i] ]\n *\n * @example\n * ```\n *\n * let foo = [ 0, 2, 4, 6 ];\n * let bar = [ 1, 3, 5, 7 ];\n * let baz = [ 10, 30, 50, 70 ];\n * arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]\n * arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]\n * ```\n */\nexport function arrayTuples(...args: any[]): any[] {\n if (args.length === 0) return [];\n const maxArrayLen = args.reduce((min, arr) => Math.min(arr.length, min), 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER\n const result = [];\n\n for (let i = 0; i < maxArrayLen; i++) {\n // This is a hot function\n // Unroll when there are 1-4 arguments\n switch (args.length) {\n case 1: result.push([args[0][i]]); break;\n case 2: result.push([args[0][i], args[1][i]]); break;\n case 3: result.push([args[0][i], args[1][i], args[2][i]]); break;\n case 4: result.push([args[0][i], args[1][i], args[2][i], args[3][i]]); break;\n default:\n result.push(args.map(array => array[i])); break;\n }\n }\n\n return result;\n}\n\n/**\n * Reduce function which builds an object from an array of [key, value] pairs.\n *\n * Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.\n *\n * Each keyValueTuple should be an array with values [ key: string, value: any ]\n *\n * @example\n * ```\n *\n * var pairs = [ [\"fookey\", \"fooval\"], [\"barkey\", \"barval\"] ]\n *\n * var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n *\n * // Or, more simply:\n * var pairsToObj = pairs.reduce(applyPairs, {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n * ```\n */\nexport function applyPairs(memo: TypedMap, keyValTuple: any[]) {\n let key: string, value: any;\n if (isArray(keyValTuple)) [key, value] = keyValTuple;\n if (!isString(key)) throw new Error('invalid parameters to applyPairs');\n memo[key] = value;\n return memo;\n}\n\n/** Get the last element of an array */\nexport function tail(arr: T[]): T {\n return arr.length && arr[arr.length - 1] || undefined;\n}\n\n/**\n * shallow copy from src to dest\n */\nexport function copy(src: Obj, dest?: Obj) {\n if (dest) Object.keys(dest).forEach(key => delete dest[key]);\n if (!dest) dest = {};\n return extend(dest, src);\n}\n\n/** Naive forEach implementation works with Objects or Arrays */\nfunction _forEach(obj: (any[]|any), cb: (el, idx?) => void, _this: Obj) {\n if (isArray(obj)) return obj.forEach(cb, _this);\n Object.keys(obj).forEach(key => cb(obj[key], key));\n}\n\n/** Like Object.assign() */\nexport function _extend(toObj: Obj, ...fromObjs: Obj[]): any;\nexport function _extend(toObj: Obj): any {\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n if (!obj) continue;\n const keys = Object.keys(obj);\n\n for (let j = 0; j < keys.length; j++) {\n toObj[keys[j]] = obj[keys[j]];\n }\n }\n\n return toObj;\n}\n\nfunction _equals(o1: any, o2: any): boolean {\n if (o1 === o2) return true;\n if (o1 === null || o2 === null) return false;\n if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n const t1 = typeof o1, t2 = typeof o2;\n if (t1 !== t2 || t1 !== 'object') return false;\n\n const tup = [o1, o2];\n if (all(isArray)(tup)) return _arraysEq(o1, o2);\n if (all(isDate)(tup)) return o1.getTime() === o2.getTime();\n if (all(isRegExp)(tup)) return o1.toString() === o2.toString();\n if (all(isFunction)(tup)) return true; // meh\n\n const predicates = [isFunction, isArray, isDate, isRegExp];\n if (predicates.map(any).reduce((b, fn) => b || !!fn(tup), false)) return false;\n\n const keys: { [i: string]: boolean } = {};\n for (const key in o1) { // tslint:disable-line:forin\n if (!_equals(o1[key], o2[key])) return false;\n keys[key] = true;\n }\n for (const key in o2) {\n if (!keys[key]) return false;\n }\n\n return true;\n}\n\nfunction _arraysEq(a1: any[], a2: any[]) {\n if (a1.length !== a2.length) return false;\n return arrayTuples(a1, a2).reduce((b, t) => b && _equals(t[0], t[1]), true);\n}\n\n// issue #2676\nexport const silenceUncaughtInPromise = (promise: Promise) =>\n promise.catch(e => 0) && promise;\nexport const silentRejection = (error: any) =>\n silenceUncaughtInPromise(services.$q.reject(error));\n", - "/** @module common */\nimport { pushTo } from './common';\n\nexport class Queue {\n private _evictListeners: ((item: T) => void)[] = [];\n public onEvict = pushTo(this._evictListeners);\n\n constructor(private _items: T[] = [], private _limit: number = null) { }\n\n enqueue(item: T) {\n const items = this._items;\n items.push(item);\n if (this._limit && items.length > this._limit) this.evict();\n return item;\n }\n\n evict(): T {\n const item: T = this._items.shift();\n this._evictListeners.forEach(fn => fn(item));\n return item;\n }\n\n dequeue(): T {\n if (this.size())\n return this._items.splice(0, 1)[0];\n }\n\n clear(): Array {\n const current = this._items;\n this._items = [];\n return current;\n }\n\n size(): number {\n return this._items.length;\n }\n\n remove(item: T) {\n const idx = this._items.indexOf(item);\n return idx > -1 && this._items.splice(idx, 1)[0];\n }\n\n peekTail(): T {\n return this._items[this._items.length - 1];\n }\n\n peekHead(): T {\n if (this.size())\n return this._items[0];\n }\n}\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n'use strict';\nimport { extend, silentRejection } from '../common/common';\nimport { stringify } from '../common/strings';\nimport { is } from '../common/hof';\n\nexport enum RejectType {\n SUPERSEDED = 2, ABORTED = 3, INVALID = 4, IGNORED = 5, ERROR = 6,\n}\n\n/** @hidden */\nlet id = 0;\n\nexport class Rejection {\n $id = id++;\n type: number;\n message: string;\n detail: any;\n redirected: boolean;\n\n /** Returns true if the obj is a rejected promise created from the `asPromise` factory */\n static isRejectionPromise(obj: any): boolean {\n return obj && (typeof obj.then === 'function') && is(Rejection)(obj._transitionRejection);\n }\n\n /** Returns a Rejection due to transition superseded */\n static superseded(detail?: any, options?: any): Rejection {\n const message = 'The transition has been superseded by a different transition';\n const rejection = new Rejection(RejectType.SUPERSEDED, message, detail);\n if (options && options.redirected) {\n rejection.redirected = true;\n }\n return rejection;\n }\n\n /** Returns a Rejection due to redirected transition */\n static redirected(detail?: any): Rejection {\n return Rejection.superseded(detail, { redirected: true });\n }\n\n /** Returns a Rejection due to invalid transition */\n static invalid(detail?: any): Rejection {\n const message = 'This transition is invalid';\n return new Rejection(RejectType.INVALID, message, detail);\n }\n\n /** Returns a Rejection due to ignored transition */\n static ignored(detail?: any): Rejection {\n const message = 'The transition was ignored';\n return new Rejection(RejectType.IGNORED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static aborted(detail?: any): Rejection {\n const message = 'The transition has been aborted';\n return new Rejection(RejectType.ABORTED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static errored(detail?: any): Rejection {\n const message = 'The transition errored';\n return new Rejection(RejectType.ERROR, message, detail);\n }\n\n /**\n * Returns a Rejection\n *\n * Normalizes a value as a Rejection.\n * If the value is already a Rejection, returns it.\n * Otherwise, wraps and returns the value as a Rejection (Rejection type: ERROR).\n *\n * @returns `detail` if it is already a `Rejection`, else returns an ERROR Rejection.\n */\n static normalize(detail?: Rejection | Error | any): Rejection {\n return is(Rejection)(detail) ? detail : Rejection.errored(detail);\n }\n\n constructor(type: number, message?: string, detail?: any) {\n this.type = type;\n this.message = message;\n this.detail = detail;\n }\n\n toString() {\n const detailString = (d: any) =>\n d && d.toString !== Object.prototype.toString ? d.toString() : stringify(d);\n const detail = detailString(this.detail);\n const { $id, type, message } = this;\n return `Transition Rejection($id: ${$id} type: ${type}, message: ${message}, detail: ${detail})`;\n }\n\n toPromise(): Promise {\n return extend(silentRejection(this), { _transitionRejection: this });\n }\n}\n", - "/**\n * # Transition tracing (debug)\n *\n * Enable transition tracing to print transition information to the console,\n * in order to help debug your application.\n * Tracing logs detailed information about each Transition to your console.\n *\n * To enable tracing, import the [[Trace]] singleton and enable one or more categories.\n *\n * ### ES6\n * ```js\n * import {trace} from \"ui-router-ng2\"; // or \"angular-ui-router\"\n * trace.enable(1, 5); // TRANSITION and VIEWCONFIG\n * ```\n *\n * ### CJS\n * ```js\n * let trace = require(\"angular-ui-router\").trace; // or \"ui-router-ng2\"\n * trace.enable(\"TRANSITION\", \"VIEWCONFIG\");\n * ```\n *\n * ### Globals\n * ```js\n * let trace = window[\"angular-ui-router\"].trace; // or \"ui-router-ng2\"\n * trace.enable(); // Trace everything (very verbose)\n * ```\n *\n * ### Angular 1:\n * ```js\n * app.run($trace => $trace.enable());\n * ```\n *\n * @coreapi\n * @module trace\n */\n/* tslint:disable:no-console */\nimport { parse } from '../common/hof';\nimport { isFunction, isNumber } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { ViewTuple } from '../view';\nimport { ActiveUIView, ViewConfig, ViewContext } from '../view/interface';\nimport { stringify, functionToString, maxLength, padString } from './strings';\nimport { Resolvable } from '../resolve/resolvable';\nimport { PathNode } from '../path/pathNode';\nimport { PolicyWhen } from '../resolve/interface';\nimport { TransitionHook } from '../transition/transitionHook';\nimport { HookResult } from '../transition/interface';\nimport { StateObject } from '../state/stateObject';\n\n/** @hidden */\nfunction uiViewString (uiview: ActiveUIView) {\n if (!uiview) return 'ui-view (defunct)';\n const state = uiview.creationContext ? uiview.creationContext.name || '(root)' : '(none)';\n return `[ui-view#${uiview.id} ${uiview.$type}:${uiview.fqn} (${uiview.name}@${state})]`;\n}\n\n/** @hidden */\nconst viewConfigString = (viewConfig: ViewConfig) => {\n const view = viewConfig.viewDecl;\n const state = view.$context.name || '(root)';\n return `[View#${viewConfig.$id} from '${state}' state]: target ui-view: '${view.$uiViewName}@${view.$uiViewContextAnchor}'`;\n};\n\n/** @hidden */\nfunction normalizedCat(input: Category|string): string {\n return isNumber(input) ? Category[input] : Category[Category[input]];\n}\n\n/** @hidden */\nconst consoleLog = Function.prototype.bind.call(console.log, console);\n\n/** @hidden */\nconst consoletable = isFunction(console.table) ? console.table.bind(console) : consoleLog.bind(console);\n\n\n/**\n * Trace categories Enum\n *\n * Enable or disable a category using [[Trace.enable]] or [[Trace.disable]]\n *\n * `trace.enable(Category.TRANSITION)`\n *\n * These can also be provided using a matching string, or position ordinal\n *\n * `trace.enable(\"TRANSITION\")`\n *\n * `trace.enable(1)`\n */\nexport enum Category {\n RESOLVE, TRANSITION, HOOK, UIVIEW, VIEWCONFIG,\n}\n\n/** @hidden */\nconst _tid = parse('$id');\n\n/** @hidden */\nconst _rid = parse('router.$id');\n\n/** @hidden */\nconst transLbl = (trans) => `Transition #${_tid(trans)}-${_rid(trans)}`;\n\n/**\n * Prints UI-Router Transition trace information to the console.\n */\nexport class Trace {\n /** @hidden */\n approximateDigests: number;\n\n /** @hidden */\n private _enabled: { [key: string]: boolean } = {};\n\n /** @hidden */\n constructor() {\n this.approximateDigests = 0;\n }\n\n /** @hidden */\n private _set(enabled: boolean, categories: Category[]) {\n if (!categories.length) {\n categories = Object.keys(Category)\n .map(k => parseInt(k, 10))\n .filter(k => !isNaN(k))\n .map(key => Category[key]);\n }\n categories.map(normalizedCat).forEach(category => this._enabled[category] = enabled);\n }\n\n /**\n * Enables a trace [[Category]]\n *\n * ```js\n * trace.enable(\"TRANSITION\");\n * ```\n *\n * @param categories categories to enable. If `categories` is omitted, all categories are enabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n enable(...categories: (Category|string|number)[]);\n enable(...categories: any[]) { this._set(true, categories); }\n /**\n * Disables a trace [[Category]]\n *\n * ```js\n * trace.disable(\"VIEWCONFIG\");\n * ```\n *\n * @param categories categories to disable. If `categories` is omitted, all categories are disabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n disable(...categories: (Category|string|number)[]);\n disable(...categories: any[]) { this._set(false, categories); }\n\n /**\n * Retrieves the enabled stateus of a [[Category]]\n *\n * ```js\n * trace.enabled(\"VIEWCONFIG\"); // true or false\n * ```\n *\n * @returns boolean true if the category is enabled\n */\n enabled(category: (Category|string|number)): boolean {\n return !!this._enabled[normalizedCat(category)];\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionStart(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Started -> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionIgnored(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Ignored <> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookInvocation(step: TransitionHook, trans: Transition, options: any) {\n if (!this.enabled(Category.HOOK)) return;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = functionToString((step as any).registeredHook.callback);\n console.log(`${transLbl(trans)}: Hook -> ${event} context: ${context}, ${maxLength(200, name)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookResult(hookResult: HookResult, trans: Transition, transitionOptions: any) {\n if (!this.enabled(Category.HOOK)) return;\n console.log(`${transLbl(trans)}: <- Hook returned: ${maxLength(200, stringify(hookResult))}`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvePath(path: PathNode[], when: PolicyWhen, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(`${transLbl(trans)}: Resolving ${path} (${when})`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvableResolved(resolvable: Resolvable, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(`${transLbl(trans)}: <- Resolved ${resolvable} to: ${maxLength(200, stringify(resolvable.data))}`);\n }\n\n /** @internalapi called by ui-router code */\n traceError(reason: any, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Rejected ${stringify(trans)}, reason: ${reason}`);\n }\n\n /** @internalapi called by ui-router code */\n traceSuccess(finalState: StateObject, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Success ${stringify(trans)}, final state: ${finalState.name}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewEvent(event: string, viewData: ActiveUIView, extra = '') {\n if (!this.enabled(Category.UIVIEW)) return;\n console.log(`ui-view: ${padString(30, event)} ${uiViewString(viewData)}${extra}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewConfigUpdated(viewData: ActiveUIView, context: ViewContext) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Updating', viewData, ` with ViewConfig from context='${context}'`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewFill(viewData: ActiveUIView, html: string) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Fill', viewData, ` with: ${maxLength(200, html)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewSync(pairs: ViewTuple[]) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n const uivheader = 'uiview component fqn';\n const cfgheader = 'view config state (view name)';\n const mapping = pairs.map(({ uiView, viewConfig }) => {\n const uiv = uiView && uiView.fqn;\n const cfg = viewConfig && `${viewConfig.viewDecl.$context.name}: (${viewConfig.viewDecl.$name})`;\n return { [uivheader]: uiv, [cfgheader]: cfg };\n }).sort((a, b) => (a[uivheader] || '').localeCompare(b[uivheader] || ''));\n\n consoletable(mapping);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceEvent(event: string, viewConfig: ViewConfig) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${viewConfigString(viewConfig)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceUIViewEvent(event: string, viewData: ActiveUIView) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${uiViewString(viewData)}`);\n }\n}\n\n/**\n * The [[Trace]] singleton\n *\n * #### Example:\n * ```js\n * import {trace} from \"angular-ui-router\";\n * trace.enable(1, 5);\n * ```\n */\nconst trace = new Trace();\nexport { trace };\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { StateDeclaration } from '../state/interface';\nimport { Predicate } from '../common/common';\n\nimport { Transition } from './transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TargetState } from '../state/targetState';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * The TransitionOptions object can be used to change the behavior of a transition.\n *\n * It is passed as the third argument to [[StateService.go]], [[StateService.transitionTo]].\n * It can also be used with a `uiSref`.\n */\nexport interface TransitionOptions {\n /**\n * This option changes how the Transition interacts with the browser's location bar (URL).\n *\n * - If `true`, it will update the url in the location bar.\n * - If `false`, it will not update the url in the location bar.\n * - If it is the string `\"replace\"`, it will update the url and also replace the last history record.\n *\n * @default `true`\n */\n location ?: (boolean|string);\n\n /**\n * When transitioning to relative path (e.g '`^`'), this option defines which state to be relative from.\n * @default `$state.current`\n */\n relative ?: (string|StateDeclaration|StateObject);\n\n /**\n * This option sets whether or not the transition's parameter values should be inherited from\n * the current parameter values.\n *\n * - If `true`, it will inherit parameter values from the current parameter values.\n * - If `false`, only the parameters which are provided to `transitionTo` will be used.\n *\n * @default `false`\n */\n inherit ?: boolean;\n\n /**\n * @deprecated\n */\n notify ?: boolean;\n\n /**\n * This option may be used to force states which are currently active to reload.\n *\n * During a normal transition, a state is \"retained\" if:\n * - It was previously active\n * - The state's parameter values have not changed\n * - All the parent states' parameter values have not changed\n *\n * Forcing a reload of a state will cause it to be exited and entered, which will:\n * - Refetch that state's resolve data\n * - Exit the state (onExit hook)\n * - Re-enter the state (onEnter hook)\n * - Re-render the views (controllers and templates)\n *\n * - When `true`, the destination state (and all parent states) will be reloaded.\n * - When it is a string and is the name of a state, or when it is a State object,\n * that state and any children states will be reloaded.\n *\n * @default `false`\n */\n reload ?: (boolean|string|StateDeclaration|StateObject);\n /**\n * You can define your own Transition Options inside this property and use them, e.g., from a Transition Hook\n */\n custom ?: any;\n /** @internalapi */\n reloadState ?: (StateObject);\n /** @internalapi\n * If this transition is a redirect, this property should be the original Transition (which was redirected to this one)\n */\n redirectedFrom?: Transition;\n /** @internalapi */\n current ?: () => Transition;\n /** @internalapi */\n source ?: 'sref' | 'url' | 'redirect' | 'otherwise' | 'unknown';\n}\n\n/** @internalapi */\nexport interface TransitionHookOptions {\n current ?: () => Transition; // path?\n transition ?: Transition;\n hookType ?: string;\n target ?: any;\n traceData ?: any;\n bind ?: any;\n stateHook ?: boolean;\n}\n\n/**\n * TreeChanges encapsulates the various Paths that are involved in a Transition.\n *\n * Get a TreeChanges object using [[Transition.treeChanges]]\n *\n * A UI-Router Transition is from one Path in a State Tree to another Path. For a given Transition,\n * this object stores the \"to\" and \"from\" paths, as well as subsets of those: the \"retained\",\n * \"exiting\" and \"entering\" paths.\n *\n * Each path in TreeChanges is an array of [[PathNode]] objects. Each PathNode in the array corresponds to a portion\n * of a nested state.\n *\n * For example, if you had a nested state named `foo.bar.baz`, it would have three\n * portions, `foo, bar, baz`. If you transitioned **to** `foo.bar.baz` and inspected the [[TreeChanges.to]]\n * Path, you would find a node in the array for each portion: `foo`, `bar`, and `baz`.\n *\n * ---\n *\n * @todo show visual state tree\n */\nexport interface TreeChanges {\n /** @nodoc */\n [key: string]: PathNode[];\n\n /** The path of nodes in the state tree that the transition is coming *from* */\n from: PathNode[];\n\n /** The path of nodes in the state tree that the transition is going *to* */\n to: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n */\n retained: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining with updated \"to params\" applied.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n *\n * This is a shallow copy of [[retained]], but with new (dynamic) parameter values from [[to]] applied.\n */\n retainedWithToParams: PathNode[];\n\n /**\n * The path of previously active nodes that the transition is exiting.\n *\n * After the Transition is successful, these nodes are no longer active.\n *\n * Note that a state that is being reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n exiting: PathNode[];\n\n /**\n * The path of nodes that the transition is entering.\n *\n * After the Transition is successful, these nodes will be active.\n * Because they are entering, they have their resolves fetched, `onEnter` hooks run, and their views\n * (component(s) or controller(s)+template(s)) refreshed.\n *\n * Note that a state that is reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n entering: PathNode[];\n}\n\nexport type IHookRegistration = (matchCriteria: HookMatchCriteria, callback: HookFn, options?: HookRegOptions) => Function;\n\n/**\n * The signature for Transition Hooks.\n *\n * Transition hooks are callback functions that hook into the lifecycle of transitions.\n * As a transition runs, it reaches certain lifecycle events.\n * As each event occurs, the hooks which are registered for the event are called (in priority order).\n *\n * A transition hook may alter a Transition by returning a [[HookResult]].\n *\n * #### See:\n *\n * - [[IHookRegistry.onBefore]]\n * - [[IHookRegistry.onStart]]\n * - [[IHookRegistry.onFinish]]\n * - [[IHookRegistry.onSuccess]]\n * - [[IHookRegistry.onError]]\n *\n * @param transition the current [[Transition]]\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n *\n */\nexport interface TransitionHookFn {\n (transition: Transition): HookResult;\n}\n\n/**\n * The signature for Transition State Hooks.\n *\n * A function which hooks into a lifecycle event for a specific state.\n *\n * Transition State Hooks are callback functions that hook into the lifecycle events of specific states during a transition.\n * As a transition runs, it may exit some states, retain (keep) states, and enter states.\n * As each lifecycle event occurs, the hooks which are registered for the event and that state are called (in priority order).\n *\n * #### See:\n *\n * - [[IHookRegistry.onExit]]\n * - [[IHookRegistry.onRetain]]\n * - [[IHookRegistry.onEnter]]\n *\n * @param transition the current [[Transition]]\n * @param state the [[StateObject]] that the hook is bound to\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n */\nexport interface TransitionStateHookFn {\n (transition: Transition, state: StateDeclaration): HookResult;\n}\n\n/**\n * The signature for Transition onCreate Hooks.\n *\n * Transition onCreate Hooks are callbacks that allow customization or preprocessing of\n * a Transition before it is returned from [[TransitionService.create]]\n *\n * @param transition the [[Transition]] that was just created\n * @return a [[Transition]] which will then be returned from [[TransitionService.create]]\n */\nexport interface TransitionCreateHookFn {\n (transition: Transition): void;\n}\n\nexport type HookFn = (TransitionHookFn|TransitionStateHookFn|TransitionCreateHookFn);\n\n/**\n * The return value of a [[TransitionHookFn]] or [[TransitionStateHookFn]]\n *\n * When returned from a [[TransitionHookFn]] or [[TransitionStateHookFn]], these values alter the running [[Transition]]:\n *\n * - `false`: the transition will be cancelled.\n * - [[TargetState]]: the transition will be redirected to the new target state (see: [[StateService.target]])\n * - `Promise`: the transition will wait for the promise to resolve or reject\n * - If the promise is rejected (or resolves to `false`), the transition will be cancelled\n * - If the promise resolves to a [[TargetState]], the transition will be redirected\n * - If the promise resolves to anything else, the transition will resume\n * - Anything else: the transition will resume\n */\nexport type HookResult = (boolean | TargetState | void | Promise);\n\n/**\n * These options may be provided when registering a Transition Hook (such as `onStart`)\n */\nexport interface HookRegOptions {\n /**\n * Sets the priority of the registered hook\n *\n * Hooks of the same type (onBefore, onStart, etc) are invoked in priority order. A hook with a higher priority\n * is invoked before a hook with a lower priority.\n *\n * The default hook priority is 0\n */\n priority?: number;\n\n /**\n * Specifies what `this` is bound to during hook invocation.\n */\n bind?: any;\n\n /**\n * Limits the number of times that the hook will be invoked.\n * Once the hook has been invoked this many times, it is automatically deregistered.\n */\n invokeLimit?: number;\n}\n\n/**\n * This interface specifies the api for registering Transition Hooks. Both the\n * [[TransitionService]] and also the [[Transition]] object itself implement this interface.\n * Note: the Transition object only allows hooks to be registered before the Transition is started.\n */\nexport interface IHookRegistry {\n /** @hidden place to store the hooks */\n _registeredHooks: { [key: string]: RegisteredHook[] };\n\n /**\n * Registers a [[TransitionHookFn]], called *before a transition starts*.\n *\n * Registers a transition lifecycle hook, which is invoked before a transition even begins.\n * This hook can be useful to implement logic which prevents a transition from even starting, such\n * as authentication, redirection\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onBefore` hooks are invoked *before a Transition starts*.\n * No resolves have been fetched yet.\n * Each `onBefore` hook is invoked synchronously, in the same call stack as [[StateService.transitionTo]].\n * The registered `onBefore` hooks are invoked in priority order.\n *\n * Note: during the `onBefore` phase, additional hooks can be added to the specific [[Transition]] instance.\n * These \"on-the-fly\" hooks only affect the currently running transition..\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * If any hook modifies the transition *synchronously* (by throwing, returning `false`, or returning\n * a [[TargetState]]), the remainder of the hooks are skipped.\n * If a hook returns a promise, the remainder of the `onBefore` hooks are still invoked synchronously.\n * All promises are resolved, and processed asynchronously before the `onStart` phase of the Transition.\n *\n * ### Examples\n *\n * #### Default Substate\n *\n * This example redirects any transition from 'home' to 'home.dashboard'. This is commonly referred to as a\n * \"default substate\".\n *\n * @example\n * ```js\n * // ng2\n * transitionService.onBefore({ to: 'home' }, (trans: Transition) =>\n * trans.router.stateService.target(\"home.dashboard\"));\n * ```\n *\n * #### Data Driven Default Substate\n *\n * This example provides data-driven default substate functionality. It matches on a transition to any state\n * which has `defaultSubstate: \"some.sub.state\"` defined. See: [[Transition.to]] which returns the \"to state\"\n * definition.\n *\n * @example\n * ```js\n * // ng1\n * // state declaration\n * {\n * name: 'home',\n * template: '
    ',\n * defaultSubstate: 'home.dashboard'\n * }\n *\n * var criteria = {\n * to: function(state) {\n * return state.defaultSubstate != null;\n * }\n * }\n *\n * $transitions.onBefore(criteria, function(trans: Transition) {\n * var substate = trans.to().defaultSubstate;\n * return trans.router.stateService.target(substate);\n * });\n * ```\n *\n *\n * #### Require authentication\n *\n * This example cancels a transition to a state which requires authentication, if the user is not currently authenticated.\n *\n * This example assumes a state tree where all states which require authentication are children of a parent `'requireauth'` state.\n * This example assumes `MyAuthService` synchronously returns a boolean from `isAuthenticated()`.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onBefore( { to: 'requireauth.**' }, function(trans) {\n * var myAuthService = trans.injector().get('MyAuthService');\n * // If isAuthenticated returns false, the transition is cancelled.\n * return myAuthService.isAuthenticated();\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @returns a function which deregisters the hook.\n */\n onBefore(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called when a transition starts.\n *\n * Registers a transition lifecycle hook, which is invoked as a transition starts running.\n * This hook can be useful to perform some asynchronous action before completing a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onStart` hooks are invoked asynchronously when the Transition starts running.\n * This happens after the `onBefore` phase is complete.\n * At this point, the Transition has not yet exited nor entered any states.\n * The registered `onStart` hooks are invoked in priority order.\n *\n * Note: A built-in `onStart` hook with high priority is used to fetch any eager resolve data.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Example\n *\n * #### Login during transition\n *\n * This example intercepts any transition to a state which requires authentication, when the user is\n * not currently authenticated. It allows the user to authenticate asynchronously, then resumes the\n * transition. If the user did not authenticate successfully, it redirects to the \"guest\" state, which\n * does not require authentication.\n *\n * This example assumes:\n * - a state tree where all states which require authentication are children of a parent `'auth'` state.\n * - `MyAuthService.isAuthenticated()` synchronously returns a boolean.\n * - `MyAuthService.authenticate()` presents a login dialog, and returns a promise which is resolved\n * or rejected, whether or not the login attempt was successful.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onStart( { to: 'auth.**' }, function(trans) {\n * var $state = trans.router.stateService;\n * var MyAuthService = trans.injector().get('MyAuthService');\n *\n * // If the user is not authenticated\n * if (!MyAuthService.isAuthenticated()) {\n *\n * // Then return a promise for a successful login.\n * // The transition will wait for this promise to settle\n *\n * return MyAuthService.authenticate().catch(function() {\n *\n * // If the authenticate() method failed for whatever reason,\n * // redirect to a 'guest' state which doesn't require auth.\n * return $state.target(\"guest\");\n * });\n * }\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onStart(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is entered.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being entered.\n *\n * Since this hook is run only when the specific state is being *entered*, it can be useful for\n * performing tasks when entering a submodule/feature area such as initializing a stateful service,\n * or for guarding access to a submodule/feature area.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onEnter` hooks generally specify `{ entering: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onEnter` hooks are invoked when the Transition is entering a state.\n * States are entered after the `onRetain` phase is complete.\n * If more than one state is being entered, the parent state is entered first.\n * The registered `onEnter` hooks for a state are invoked in priority order.\n *\n * Note: A built-in `onEnter` hook with high priority is used to fetch lazy resolve data for states being entered.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onEnter` hooks using the [[TransitionService]], you may define an `onEnter` hook\n * directly on a state declaration (see: [[StateDeclaration.onEnter]]).\n *\n *\n * ### Examples\n *\n * #### Audit Log\n *\n * This example uses a service to log that a user has entered the admin section of an app.\n * This assumes that there are substates of the \"admin\" state, such as \"admin.users\", \"admin.pages\", etc.\n * @example\n * ```\n *\n * $transitions.onEnter({ entering: 'admin' }, function(transition, state) {\n * var AuditService = trans.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * ```\n *\n * #### Audit Log (inside a state declaration)\n *\n * The `onEnter` inside this state declaration is syntactic sugar for the previous Audit Log example.\n * ```\n * {\n * name: 'admin',\n * component: 'admin',\n * onEnter: function($transition$, $state$) {\n * var AuditService = $transition$.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * }\n * ```\n *\n * Note: A state declaration's `onEnter` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onEnter(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is retained/kept.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) for\n * a specific state that was previously active will remain active (is not being entered nor exited).\n *\n * This hook is invoked when a state is \"retained\" or \"kept\".\n * It means the transition is coming *from* a substate of the retained state *to* a substate of the retained state.\n * This hook can be used to perform actions when the user moves from one substate to another, such as between steps in a wizard.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onRetain` hooks generally specify `{ retained: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onRetain` hooks are invoked after any `onExit` hooks have been fired.\n * If more than one state is retained, the child states' `onRetain` hooks are invoked first.\n * The registered `onRetain` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onRetain` hooks using the [[TransitionService]], you may define an `onRetain` hook\n * directly on a state declaration (see: [[StateDeclaration.onRetain]]).\n *\n * Note: A state declaration's `onRetain` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onRetain(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is exited.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being exited.\n *\n * Since this hook is run only when the specific state is being *exited*, it can be useful for\n * performing tasks when leaving a submodule/feature area such as cleaning up a stateful service,\n * or for preventing the user from leaving a state or submodule until some criteria is satisfied.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onExit` hooks generally specify `{ exiting: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onExit` hooks are invoked when the Transition is exiting a state.\n * States are exited after any `onStart` phase is complete.\n * If more than one state is being exited, the child states are exited first.\n * The registered `onExit` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onExit` hooks using the [[TransitionService]], you may define an `onExit` hook\n * directly on a state declaration (see: [[StateDeclaration.onExit]]).\n *\n * Note: A state declaration's `onExit` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onExit(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called *just before a transition finishes*.\n *\n * Registers a transition lifecycle hook, which is invoked just before a transition finishes.\n * This hook is a last chance to cancel or redirect a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onFinish` hooks are invoked after the `onEnter` phase is complete.\n * These hooks are invoked just before the transition is \"committed\".\n * Each hook is invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onFinish(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a successful transition completed.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition successfully completes.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onSuccess` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If the Transition is successful and its promise is resolved, then the `onSuccess` hooks are invoked.\n * Since these hooks are run after the transition is over, their return value is ignored.\n * The `onSuccess` hooks are invoked in priority order.\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onSuccess(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a transition has errored.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition has been rejected for any reason.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * The `onError` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If a Transition fails, its promise is rejected and the `onError` hooks are invoked.\n * The `onError` hooks are invoked in priority order.\n *\n * Since these hooks are run after the transition is over, their return value is ignored.\n *\n * A transition \"errors\" if it was started, but failed to complete (for any reason).\n * A *non-exhaustive list* of reasons a transition can error:\n *\n * - A transition was cancelled because a new transition started while it was still running (`Transition superseded`)\n * - A transition was cancelled by a Transition Hook returning false\n * - A transition was redirected by a Transition Hook returning a [[TargetState]]\n * - A Transition Hook or resolve function threw an error\n * - A Transition Hook returned a rejected promise\n * - A resolve function returned a rejected promise\n *\n * To check the failure reason, inspect the return value of [[Transition.error]].\n *\n * Note: `onError` should be used for targeted error handling, or error recovery.\n * For simple catch-all error reporting, use [[StateService.defaultErrorHandler]].\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onError(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Returns all the registered hooks of a given `hookName` type\n *\n * #### Example:\n * ```\n * $transitions.getHooks(\"onEnter\")\n * ```\n */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/** A predicate type which tests if a [[StateObject]] passes some test. Returns a boolean. */\nexport type IStateMatch = Predicate;\n\n/**\n * This object is used to configure whether or not a Transition Hook is invoked for a particular transition,\n * based on the Transition's \"to state\" and \"from state\".\n *\n * Each property (`to`, `from`, `exiting`, `retained`, and `entering`) can be a state [[Glob]] string,\n * a boolean, or a function that takes a state and returns a boolean (see [[HookMatchCriterion]])\n *\n * All properties are optional. If any property is omitted, it is replaced with the value `true`, and always matches.\n * To match any transition, use an empty criteria object `{}`.\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from the `parent` state and going to the `parent.child` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.child'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any substate of `parent` and going directly to the `parent` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any substate of `mymodule`\n * var match = {\n * to: 'mymodule.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any state that has `data.authRequired`\n * // set to a truthy value.\n * var match = {\n * to: function(state) {\n * return state.data != null && state.data.authRequired === true;\n * }\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition that is exiting `parent.child`\n * var match = {\n * exiting: 'parent.child'\n * }\n * ```\n */\nexport interface HookMatchCriteria {\n [key: string]: HookMatchCriterion | undefined;\n\n /** A [[HookMatchCriterion]] to match the destination state */\n to?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match the original (from) state */\n from?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be exiting */\n exiting?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be retained */\n retained?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be entering */\n entering?: HookMatchCriterion;\n}\n\nexport interface IMatchingNodes {\n [key: string]: PathNode[];\n\n to: PathNode[];\n from: PathNode[];\n exiting: PathNode[];\n retained: PathNode[];\n entering: PathNode[];\n}\n\n/** @hidden */\nexport interface RegisteredHooks {\n [key: string]: RegisteredHook[];\n}\n\n/** @hidden */\nexport interface PathTypes {\n [key: string]: PathType;\n\n to: PathType;\n from: PathType;\n exiting: PathType;\n retained: PathType;\n entering: PathType;\n}\n\n/** @hidden */\nexport interface PathType {\n name: string;\n scope: TransitionHookScope;\n}\n\n/**\n * Hook Criterion used to match a transition.\n *\n * A [[Glob]] string that matches the name of a state.\n *\n * Or, a function with the signature `function(state) { return matches; }`\n * which should return a boolean to indicate if a state matches.\n *\n * Or, `true` to always match\n */\nexport type HookMatchCriterion = (string|IStateMatch|boolean);\n\nexport enum TransitionHookPhase { CREATE, BEFORE, RUN, SUCCESS, ERROR }\nexport enum TransitionHookScope { TRANSITION, STATE }\n", - "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateDeclaration, StateOrName, TargetStateDef } from './interface';\nimport { TransitionOptions } from '../transition/interface';\nimport { StateObject } from './stateObject';\nimport { isString } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { extend } from '../common';\nimport { StateRegistry } from './stateRegistry';\nimport { RawParams } from '../params';\n\n/**\n * Encapsulate the target (destination) state/params/options of a [[Transition]].\n *\n * This class is frequently used to redirect a transition to a new destination.\n *\n * See:\n *\n * - [[HookResult]]\n * - [[TransitionHookFn]]\n * - [[TransitionService.onStart]]\n *\n * To create a `TargetState`, use [[StateService.target]].\n *\n * ---\n *\n * This class wraps:\n *\n * 1) an identifier for a state\n * 2) a set of parameters\n * 3) and transition options\n * 4) the registered state object (the [[StateDeclaration]])\n *\n * Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can\n * either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string).\n * The `TargetState` class normalizes those options.\n *\n * A `TargetState` may be valid (the state being targeted exists in the registry)\n * or invalid (the state being targeted is not registered).\n */\nexport class TargetState {\n private _definition: StateObject;\n private _params: RawParams;\n private _options: TransitionOptions;\n\n /** Returns true if the object has a state property that might be a state or state name */\n static isDef = (obj): obj is TargetStateDef =>\n obj && obj.state && (isString(obj.state) || isString(obj.state.name));\n\n /**\n * The TargetState constructor\n *\n * Note: Do not construct a `TargetState` manually.\n * To create a `TargetState`, use the [[StateService.target]] factory method.\n *\n * @param _stateRegistry The StateRegistry to use to look up the _definition\n * @param _identifier An identifier for a state.\n * Either a fully-qualified state name, or the object used to define the state.\n * @param _params Parameters for the target state\n * @param _options Transition options.\n *\n * @internalapi\n */\n constructor(\n private _stateRegistry: StateRegistry,\n private _identifier: StateOrName,\n _params?: RawParams,\n _options?: TransitionOptions,\n ) {\n this._identifier = _identifier;\n this._params = extend({}, _params || {});\n this._options = extend({}, _options || {});\n this._definition = _stateRegistry.matcher.find(_identifier, this._options.relative);\n }\n\n /** The name of the state this object targets */\n name(): string {\n return this._definition && this._definition.name || this._identifier;\n }\n\n /** The identifier used when creating this TargetState */\n identifier(): StateOrName {\n return this._identifier;\n }\n\n /** The target parameter values */\n params(): RawParams {\n return this._params;\n }\n\n /** The internal state object (if it was found) */\n $state(): StateObject {\n return this._definition;\n }\n\n /** The internal state declaration (if it was found) */\n state(): StateDeclaration {\n return this._definition && this._definition.self;\n }\n\n /** The target options */\n options() {\n return this._options;\n }\n\n /** True if the target state was found */\n exists(): boolean {\n return !!(this._definition && this._definition.self);\n }\n\n /** True if the object is valid */\n valid(): boolean {\n return !this.error();\n }\n\n /** If the object is invalid, returns the reason why */\n error(): string {\n const base = this.options().relative;\n if (!this._definition && !!base) {\n const stateName = base.name ? base.name : base;\n return `Could not resolve '${this.name()}' from state '${stateName}'`;\n }\n if (!this._definition)\n return `No such state '${this.name()}'`;\n if (!this._definition.self)\n return `State '${this.name()}' has an invalid definition`;\n }\n\n toString() {\n return `'${this.name()}'${stringify(this.params())}`;\n }\n\n /**\n * Returns a copy of this TargetState which targets a different state.\n * The new TargetState has the same parameter values and transition options.\n *\n * @param state The new state that should be targeted\n */\n withState(state: StateOrName): TargetState {\n return new TargetState(this._stateRegistry, state, this._params, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified parameter values.\n *\n * @param params the new parameter values to use\n * @param replace When false (default) the new parameter values will be merged with the current values.\n * When true the parameter values will be used instead of the current values.\n */\n withParams(params: RawParams, replace = false): TargetState {\n const newParams: RawParams = replace ? params : extend({}, this._params, params);\n return new TargetState(this._stateRegistry, this._identifier, newParams, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified Transition Options.\n *\n * @param options the new options to use\n * @param replace When false (default) the new options will be merged with the current options.\n * When true the options will be used instead of the current options.\n */\n withOptions(options: TransitionOptions, replace = false): TargetState {\n const newOpts = replace ? options : extend({}, this._options, options);\n return new TargetState(this._stateRegistry, this._identifier, this._params, newOpts);\n }\n}\n", - "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { TransitionHookOptions, HookResult, TransitionHookPhase } from './interface';\nimport { defaults, noop, silentRejection } from '../common/common';\nimport { fnToString, maxLength } from '../common/strings';\nimport { isPromise } from '../common/predicates';\nimport { is, parse } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { Rejection } from './rejectFactory';\nimport { TargetState } from '../state/targetState';\nimport { Transition } from './transition';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\nimport { StateDeclaration } from '../state/interface';\n\nconst defaultOptions: TransitionHookOptions = {\n current: noop,\n transition: null,\n traceData: {},\n bind: null,\n};\n\nexport type GetResultHandler = (hook: TransitionHook) => ResultHandler;\nexport type GetErrorHandler = (hook: TransitionHook) => ErrorHandler;\n\nexport type ResultHandler = (result: HookResult) => Promise;\nexport type ErrorHandler = (error: any) => Promise;\n\n/** @hidden */\nexport class TransitionHook {\n type: TransitionEventType;\n\n /**\n * These GetResultHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetResultHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static HANDLE_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) =>\n hook.handleHookResult(result);\n\n /**\n * If the result is a promise rejection, log it.\n * Otherwise, ignore the result.\n */\n static LOG_REJECTED_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) => {\n isPromise(result) && result.catch(err =>\n hook.logError(Rejection.normalize(err)));\n return undefined;\n }\n\n /**\n * These GetErrorHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetErrorHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static LOG_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) =>\n hook.logError(error);\n\n static REJECT_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) =>\n silentRejection(error);\n\n static THROW_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => {\n throw error;\n }\n\n /**\n * Chains together an array of TransitionHooks.\n *\n * Given a list of [[TransitionHook]] objects, chains them together.\n * Each hook is invoked after the previous one completes.\n *\n * #### Example:\n * ```js\n * var hooks: TransitionHook[] = getHooks();\n * let promise: Promise = TransitionHook.chain(hooks);\n *\n * promise.then(handleSuccess, handleError);\n * ```\n *\n * @param hooks the list of hooks to chain together\n * @param waitFor if provided, the chain is `.then()`'ed off this promise\n * @returns a `Promise` for sequentially invoking the hooks (in order)\n */\n static chain(hooks: TransitionHook[], waitFor?: Promise): Promise {\n // Chain the next hook off the previous\n const createHookChainR = (prev: Promise, nextHook: TransitionHook) =>\n prev.then(() => nextHook.invokeHook());\n return hooks.reduce(createHookChainR, waitFor || services.$q.when());\n }\n\n\n /**\n * Invokes all the provided TransitionHooks, in order.\n * Each hook's return value is checked.\n * If any hook returns a promise, then the rest of the hooks are chained off that promise, and the promise is returned.\n * If no hook returns a promise, then all hooks are processed synchronously.\n *\n * @param hooks the list of TransitionHooks to invoke\n * @param doneCallback a callback that is invoked after all the hooks have successfully completed\n *\n * @returns a promise for the async result, or the result of the callback\n */\n static invokeHooks(hooks: TransitionHook[], doneCallback: (result?: HookResult) => T): Promise | T {\n for (let idx = 0; idx < hooks.length; idx++) {\n const hookResult = hooks[idx].invokeHook();\n\n if (isPromise(hookResult)) {\n const remainingHooks = hooks.slice(idx + 1);\n\n return TransitionHook.chain(remainingHooks, hookResult)\n .then(doneCallback);\n }\n }\n\n return doneCallback();\n }\n\n /**\n * Run all TransitionHooks, ignoring their return value.\n */\n static runAllHooks(hooks: TransitionHook[]): void {\n hooks.forEach(hook => hook.invokeHook());\n }\n\n constructor(private transition: Transition,\n private stateContext: StateDeclaration,\n private registeredHook: RegisteredHook,\n private options: TransitionHookOptions) {\n this.options = defaults(options, defaultOptions);\n this.type = registeredHook.eventType;\n }\n\n private isSuperseded = () =>\n this.type.hookPhase === TransitionHookPhase.RUN && !this.options.transition.isActive();\n\n logError(err): any {\n this.transition.router.stateService.defaultErrorHandler()(err);\n }\n\n invokeHook(): Promise | void {\n const hook = this.registeredHook;\n if (hook._deregistered) return;\n\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n const options = this.options;\n trace.traceHookInvocation(this, this.transition, options);\n\n const invokeCallback = () =>\n hook.callback.call(options.bind, this.transition, this.stateContext);\n\n const normalizeErr = err =>\n Rejection.normalize(err).toPromise();\n\n const handleError = err =>\n hook.eventType.getErrorHandler(this)(err);\n\n const handleResult = result =>\n hook.eventType.getResultHandler(this)(result);\n\n try {\n const result = invokeCallback();\n\n if (!this.type.synchronous && isPromise(result)) {\n return result.catch(normalizeErr)\n .then(handleResult, handleError);\n } else {\n return handleResult(result);\n }\n } catch (err) {\n // If callback throws (synchronously)\n return handleError(Rejection.normalize(err));\n } finally {\n if (hook.invokeLimit && ++hook.invokeCount >= hook.invokeLimit) {\n hook.deregister();\n }\n }\n }\n\n /**\n * This method handles the return value of a Transition Hook.\n *\n * A hook can return false (cancel), a TargetState (redirect),\n * or a promise (which may later resolve to false or a redirect)\n *\n * This also handles \"transition superseded\" -- when a new transition\n * was started while the hook was still running\n */\n handleHookResult(result: HookResult): Promise {\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n // Hook returned a promise\n if (isPromise(result)) {\n // Wait for the promise, then reprocess with the resulting value\n return result.then(val => this.handleHookResult(val));\n }\n\n trace.traceHookResult(result, this.transition, this.options);\n\n // Hook returned false\n if (result === false) {\n // Abort this Transition\n return Rejection.aborted('Hook aborted transition').toPromise();\n }\n\n const isTargetState = is(TargetState);\n // hook returned a TargetState\n if (isTargetState(result)) {\n // Halt the current Transition and redirect (a new Transition) to the TargetState.\n return Rejection.redirected(result).toPromise();\n }\n }\n\n\n /**\n * Return a Rejection promise if the transition is no longer current due\n * to a stopped router (disposed), or a new transition has started and superseded this one.\n */\n private getNotCurrentRejection() {\n const router = this.transition.router;\n\n // The router is stopped\n if (router._disposed) {\n return Rejection.aborted(`UIRouter instance #${router.$id} has been stopped (disposed)`).toPromise();\n }\n\n if (this.transition._aborted) {\n return Rejection.aborted().toPromise();\n }\n\n // This transition is no longer current.\n // Another transition started while this hook was still running.\n if (this.isSuperseded()) {\n // Abort this transition\n return Rejection.superseded(this.options.current()).toPromise();\n }\n }\n\n toString() {\n const { options, registeredHook } = this;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = fnToString(registeredHook.callback);\n return `${event} context: ${context}, ${maxLength(200, name)}`;\n }\n\n}\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { isString, isFunction, Glob, extend, removeFrom, tail, values, identity, mapObj } from '../common';\nimport { PathNode } from '../path/pathNode';\nimport {\n TransitionStateHookFn, TransitionHookFn, TransitionHookPhase, // has or is using\n TransitionHookScope, IHookRegistry, PathType,\n} from './interface';\n\nimport { HookRegOptions, HookMatchCriteria, TreeChanges, HookMatchCriterion, IMatchingNodes, HookFn } from './interface';\nimport { StateObject } from '../state/stateObject';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionService } from './transitionService';\n\n/**\n * Determines if the given state matches the matchCriteria\n *\n * @hidden\n *\n * @param state a State Object to test against\n * @param criterion\n * - If a string, matchState uses the string as a glob-matcher against the state name\n * - If an array (of strings), matchState uses each string in the array as a glob-matchers against the state name\n * and returns a positive match if any of the globs match.\n * - If a function, matchState calls the function with the state and returns true if the function's result is truthy.\n * @returns {boolean}\n */\nexport function matchState(state: StateObject, criterion: HookMatchCriterion) {\n const toMatch = isString(criterion) ? [criterion] : criterion;\n\n function matchGlobs(_state: StateObject) {\n const globStrings = toMatch;\n for (let i = 0; i < globStrings.length; i++) {\n const glob = new Glob(globStrings[i]);\n\n if ((glob && glob.matches(_state.name)) || (!glob && globStrings[i] === _state.name)) {\n return true;\n }\n }\n return false;\n }\n\n const matchFn = (isFunction(toMatch) ? toMatch : matchGlobs);\n return !!matchFn(state);\n}\n\n/**\n * @internalapi\n * The registration data for a registered transition hook\n */\nexport class RegisteredHook {\n priority: number;\n bind: any;\n invokeCount = 0;\n invokeLimit: number;\n _deregistered = false;\n\n constructor(public tranSvc: TransitionService,\n public eventType: TransitionEventType,\n public callback: HookFn,\n public matchCriteria: HookMatchCriteria,\n public removeHookFromRegistry: (hook: RegisteredHook) => void,\n options: HookRegOptions = {} as any) {\n this.priority = options.priority || 0;\n this.bind = options.bind || null;\n this.invokeLimit = options.invokeLimit;\n }\n\n /**\n * Gets the matching [[PathNode]]s\n *\n * Given an array of [[PathNode]]s, and a [[HookMatchCriterion]], returns an array containing\n * the [[PathNode]]s that the criteria matches, or `null` if there were no matching nodes.\n *\n * Returning `null` is significant to distinguish between the default\n * \"match-all criterion value\" of `true` compared to a `() => true` function,\n * when the nodes is an empty array.\n *\n * This is useful to allow a transition match criteria of `entering: true`\n * to still match a transition, even when `entering === []`. Contrast that\n * with `entering: (state) => true` which only matches when a state is actually\n * being entered.\n */\n private _matchingNodes(nodes: PathNode[], criterion: HookMatchCriterion): PathNode[] {\n if (criterion === true) return nodes;\n const matching = nodes.filter(node => matchState(node.state, criterion));\n return matching.length ? matching : null;\n }\n\n /**\n * Gets the default match criteria (all `true`)\n *\n * Returns an object which has all the criteria match paths as keys and `true` as values, i.e.:\n *\n * ```js\n * {\n * to: true,\n * from: true,\n * entering: true,\n * exiting: true,\n * retained: true,\n * }\n */\n private _getDefaultMatchCriteria(): HookMatchCriteria {\n return mapObj(this.tranSvc._pluginapi._getPathTypes(), () => true);\n }\n\n /**\n * Gets matching nodes as [[IMatchingNodes]]\n *\n * Create a IMatchingNodes object from the TransitionHookTypes that is roughly equivalent to:\n *\n * ```js\n * let matches: IMatchingNodes = {\n * to: _matchingNodes([tail(treeChanges.to)], mc.to),\n * from: _matchingNodes([tail(treeChanges.from)], mc.from),\n * exiting: _matchingNodes(treeChanges.exiting, mc.exiting),\n * retained: _matchingNodes(treeChanges.retained, mc.retained),\n * entering: _matchingNodes(treeChanges.entering, mc.entering),\n * };\n * ```\n */\n private _getMatchingNodes(treeChanges: TreeChanges): IMatchingNodes {\n const criteria = extend(this._getDefaultMatchCriteria(), this.matchCriteria);\n const paths: PathType[] = values(this.tranSvc._pluginapi._getPathTypes());\n\n return paths.reduce((mn: IMatchingNodes, pathtype: PathType) => {\n // STATE scope criteria matches against every node in the path.\n // TRANSITION scope criteria matches against only the last node in the path\n const isStateHook = pathtype.scope === TransitionHookScope.STATE;\n const path = treeChanges[pathtype.name] || [];\n const nodes: PathNode[] = isStateHook ? path : [tail(path)];\n\n mn[pathtype.name] = this._matchingNodes(nodes, criteria[pathtype.name]);\n return mn;\n }, {} as IMatchingNodes);\n }\n\n /**\n * Determines if this hook's [[matchCriteria]] match the given [[TreeChanges]]\n *\n * @returns an IMatchingNodes object, or null. If an IMatchingNodes object is returned, its values\n * are the matching [[PathNode]]s for each [[HookMatchCriterion]] (to, from, exiting, retained, entering)\n */\n matches(treeChanges: TreeChanges): IMatchingNodes {\n const matches = this._getMatchingNodes(treeChanges);\n\n // Check if all the criteria matched the TreeChanges object\n const allMatched = values(matches).every(identity);\n return allMatched ? matches : null;\n }\n\n deregister() {\n this.removeHookFromRegistry(this);\n this._deregistered = true;\n }\n}\n\n/** @hidden Return a registration function of the requested type. */\nexport function makeEvent(registry: IHookRegistry, transitionService: TransitionService, eventType: TransitionEventType) {\n // Create the object which holds the registered transition hooks.\n const _registeredHooks = registry._registeredHooks = (registry._registeredHooks || {});\n const hooks = _registeredHooks[eventType.name] = [];\n const removeHookFn: (hook: RegisteredHook) => void = removeFrom(hooks);\n\n // Create hook registration function on the IHookRegistry for the event\n registry[eventType.name] = hookRegistrationFn;\n\n function hookRegistrationFn(matchObject, callback, options = {}) {\n const registeredHook = new RegisteredHook(transitionService, eventType, callback, matchObject, removeHookFn, options);\n hooks.push(registeredHook);\n return registeredHook.deregister.bind(registeredHook);\n }\n\n return hookRegistrationFn;\n}\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n\nimport { extend, tail, assertPredicate, unnestR, identity } from '../common/common';\nimport { isArray } from '../common/predicates';\n\nimport {\n TransitionOptions, TransitionHookOptions, IHookRegistry, TreeChanges, IMatchingNodes,\n TransitionHookPhase, TransitionHookScope,\n} from './interface';\n\nimport { Transition } from './transition';\nimport { TransitionHook } from './transitionHook';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TransitionService } from './transitionService';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * This class returns applicable TransitionHooks for a specific Transition instance.\n *\n * Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g.\n * myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is\n * determined by the type of hook)\n *\n * The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition.\n *\n * The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder\n * instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private\n * in the Transition class, so we must also provide the Transition's _treeChanges)\n *\n */\nexport class HookBuilder {\n constructor(private transition: Transition) { }\n\n buildHooksForPhase(phase: TransitionHookPhase): TransitionHook[] {\n const $transitions = this.transition.router.transitionService;\n return $transitions._pluginapi._getEvents(phase)\n .map(type => this.buildHooks(type))\n .reduce(unnestR, [])\n .filter(identity);\n }\n\n /**\n * Returns an array of newly built TransitionHook objects.\n *\n * - Finds all RegisteredHooks registered for the given `hookType` which matched the transition's [[TreeChanges]].\n * - Finds [[PathNode]] (or `PathNode[]`) to use as the TransitionHook context(s)\n * - For each of the [[PathNode]]s, creates a TransitionHook\n *\n * @param hookType the type of the hook registration function, e.g., 'onEnter', 'onFinish'.\n */\n buildHooks(hookType: TransitionEventType): TransitionHook[] {\n const transition = this.transition;\n const treeChanges = transition.treeChanges();\n\n // Find all the matching registered hooks for a given hook type\n const matchingHooks = this.getMatchingHooks(hookType, treeChanges);\n if (!matchingHooks) return [];\n\n const baseHookOptions = {\n transition: transition,\n current: transition.options().current,\n };\n\n const makeTransitionHooks = (hook: RegisteredHook) => {\n // Fetch the Nodes that caused this hook to match.\n const matches: IMatchingNodes = hook.matches(treeChanges);\n // Select the PathNode[] that will be used as TransitionHook context objects\n const matchingNodes: PathNode[] = matches[hookType.criteriaMatchPath.name];\n\n // Return an array of HookTuples\n return matchingNodes.map(node => {\n const _options = extend({\n bind: hook.bind,\n traceData: { hookType: hookType.name, context: node },\n }, baseHookOptions);\n\n const state = hookType.criteriaMatchPath.scope === TransitionHookScope.STATE ? node.state.self : null;\n const transitionHook = new TransitionHook(transition, state, hook, _options);\n return { hook, node, transitionHook };\n });\n };\n\n return matchingHooks.map(makeTransitionHooks)\n .reduce(unnestR, [])\n .sort(tupleSort(hookType.reverseSort))\n .map(tuple => tuple.transitionHook);\n }\n\n /**\n * Finds all RegisteredHooks from:\n * - The Transition object instance hook registry\n * - The TransitionService ($transitions) global hook registry\n *\n * which matched:\n * - the eventType\n * - the matchCriteria (to, from, exiting, retained, entering)\n *\n * @returns an array of matched [[RegisteredHook]]s\n */\n public getMatchingHooks(hookType: TransitionEventType, treeChanges: TreeChanges): RegisteredHook[] {\n const isCreate = hookType.hookPhase === TransitionHookPhase.CREATE;\n\n // Instance and Global hook registries\n const $transitions = this.transition.router.transitionService;\n const registries = isCreate ? [ $transitions ] : [ this.transition, $transitions ];\n\n return registries.map((reg: IHookRegistry) => reg.getHooks(hookType.name)) // Get named hooks from registries\n .filter(assertPredicate(isArray, `broken event named: ${hookType.name}`)) // Sanity check\n .reduce(unnestR, []) // Un-nest RegisteredHook[][] to RegisteredHook[] array\n .filter(hook => hook.matches(treeChanges)); // Only those satisfying matchCriteria\n }\n}\n\ninterface HookTuple { hook: RegisteredHook, node: PathNode, transitionHook: TransitionHook }\n\n/**\n * A factory for a sort function for HookTuples.\n *\n * The sort function first compares the PathNode depth (how deep in the state tree a node is), then compares\n * the EventHook priority.\n *\n * @param reverseDepthSort a boolean, when true, reverses the sort order for the node depth\n * @returns a tuple sort function\n */\nfunction tupleSort(reverseDepthSort = false) {\n return function nodeDepthThenPriority(l: HookTuple, r: HookTuple): number {\n const factor = reverseDepthSort ? -1 : 1;\n const depthDelta = (l.node.state.path.length - r.node.state.path.length) * factor;\n return depthDelta !== 0 ? depthDelta : r.hook.priority - l.hook.priority;\n };\n}\n", - "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, filter, map } from '../common/common';\nimport { isArray, isDefined } from '../common/predicates';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * An internal class which implements [[ParamTypeDefinition]].\n *\n * A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types.\n * When a param type definition is registered, an instance of this class is created internally.\n *\n * This class has naive implementations for all the [[ParamTypeDefinition]] methods.\n *\n * Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values.\n *\n * #### Example:\n * ```js\n * var paramTypeDef = {\n * decode: function(val) { return parseInt(val, 10); },\n * encode: function(val) { return val && val.toString(); },\n * equals: function(a, b) { return this.is(a) && a === b; },\n * is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; },\n * pattern: /\\d+/\n * }\n *\n * var paramType = new ParamType(paramTypeDef);\n * ```\n * @internalapi\n */\nexport class ParamType implements ParamTypeDefinition {\n /** @inheritdoc */\n pattern: RegExp = /.*/;\n /** The name/id of the parameter type */\n name: string;\n /** @inheritdoc */\n raw: boolean;\n /** @inheritdoc */\n dynamic: boolean;\n /** @inheritdoc */\n inherit = true;\n\n /**\n * @param def A configuration object which contains the custom type definition. The object's\n * properties will override the default methods and/or pattern in `ParamType`'s public interface.\n * @returns a new ParamType object\n */\n constructor(def: ParamTypeDefinition) {\n extend(this, def);\n }\n\n\n // consider these four methods to be \"abstract methods\" that should be overridden\n /** @inheritdoc */\n is(val: any, key?: string): boolean { return true; }\n /** @inheritdoc */\n encode(val: any, key?: string): (string|string[]) { return val; }\n /** @inheritdoc */\n decode(val: string, key?: string): any { return val; }\n /** @inheritdoc */\n equals(a: any, b: any): boolean { return a == b; } // tslint:disable-line:triple-equals\n\n\n $subPattern() {\n const sub = this.pattern.toString();\n return sub.substr(1, sub.length - 2);\n }\n\n toString() {\n return `{ParamType:${this.name}}`;\n }\n\n /** Given an encoded string, or a decoded object, returns a decoded object */\n $normalize(val: any) {\n return this.is(val) ? val : this.decode(val);\n }\n\n /**\n * Wraps an existing custom ParamType as an array of ParamType, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\n $asArray(mode: (boolean|'auto'), isSearch: boolean) {\n if (!mode) return this;\n if (mode === 'auto' && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n return new ( ArrayType)(this, mode);\n }\n}\n\n/**\n * Wraps up a `ParamType` object to handle array values.\n * @internalapi\n */\nfunction ArrayType(type: ParamType, mode: (boolean|'auto')) {\n // Wrap non-array value as array\n function arrayWrap(val: any): any[] {\n return isArray(val) ? val : (isDefined(val) ? [ val ] : []);\n }\n\n // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n function arrayUnwrap(val: any) {\n switch (val.length) {\n case 0: return undefined;\n case 1: return mode === 'auto' ? val[0] : val;\n default: return val;\n }\n }\n\n // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n function arrayHandler(callback: (x: any) => any, allTruthyMode?: boolean) {\n return function handleArray(val: any) {\n if (isArray(val) && val.length === 0) return val;\n const arr = arrayWrap(val);\n const result = map(arr, callback);\n return (allTruthyMode === true) ? filter(result, x => !x).length === 0 : arrayUnwrap(result);\n };\n }\n\n // Wraps type (.equals) functions to operate on each value of an array\n function arrayEqualsHandler(callback: (l: any, r: any) => boolean) {\n return function handleArray(val1: any, val2: any) {\n const left = arrayWrap(val1), right = arrayWrap(val2);\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!callback(left[i], right[i])) return false;\n }\n return true;\n };\n }\n\n ['encode', 'decode', 'equals', '$normalize'].forEach(name => {\n const paramTypeFn = type[name].bind(type);\n const wrapperFn: Function = name === 'equals' ? arrayEqualsHandler : arrayHandler;\n this[name] = wrapperFn(paramTypeFn);\n });\n\n extend(this, {\n dynamic: type.dynamic,\n name: type.name,\n pattern: type.pattern,\n inherit: type.inherit,\n is: arrayHandler(type.is.bind(type), true),\n $arrayMode: mode,\n });\n}\n", - "/**\n * @coreapi\n * @module params\n */ /** for typedoc */\nimport { extend, filter, map, allTrueR } from '../common/common';\nimport { prop } from '../common/hof';\nimport { isInjectable, isDefined, isString, isArray, isUndefined } from '../common/predicates';\nimport { RawParams, ParamDeclaration } from '../params/interface';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypes } from './paramTypes';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\n\n/** @hidden */\nconst hasOwn = Object.prototype.hasOwnProperty;\n\n/** @hidden */\nconst isShorthand = (cfg: ParamDeclaration) =>\n ['value', 'type', 'squash', 'array', 'dynamic'].filter(hasOwn.bind(cfg || {})).length === 0;\n\n/** @internalapi */\nexport enum DefType {\n PATH,\n SEARCH,\n CONFIG,\n}\n\n/** @hidden */\nfunction unwrapShorthand(cfg: ParamDeclaration): ParamDeclaration {\n cfg = isShorthand(cfg) && { value: cfg } as any || cfg;\n\n getStaticDefaultValue['__cacheable'] = true;\n function getStaticDefaultValue() {\n return cfg.value;\n }\n\n return extend(cfg, {\n $$fn: isInjectable(cfg.value) ? cfg.value : getStaticDefaultValue,\n });\n}\n\n/** @hidden */\nfunction getType(cfg: ParamDeclaration, urlType: ParamType, location: DefType, id: string, paramTypes: ParamTypes) {\n if (cfg.type && urlType && urlType.name !== 'string') throw new Error(`Param '${id}' has two type configurations.`);\n if (cfg.type && urlType && urlType.name === 'string' && paramTypes.type(cfg.type as string)) return paramTypes.type(cfg.type as string);\n if (urlType) return urlType;\n if (!cfg.type) {\n const type = location === DefType.CONFIG ? 'any' :\n location === DefType.PATH ? 'path' :\n location === DefType.SEARCH ? 'query' : 'string';\n return paramTypes.type(type);\n }\n return cfg.type instanceof ParamType ? cfg.type : paramTypes.type(cfg.type as string);\n}\n\n/**\n * @internalapi\n * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n */\nfunction getSquashPolicy(config: ParamDeclaration, isOptional: boolean, defaultPolicy: (boolean|string)) {\n const squash = config.squash;\n if (!isOptional || squash === false) return false;\n if (!isDefined(squash) || squash == null) return defaultPolicy;\n if (squash === true || isString(squash)) return squash;\n throw new Error(`Invalid squash policy: '${squash}'. Valid policies: false, true, or arbitrary string`);\n}\n\n/** @internalapi */\nfunction getReplace(config: ParamDeclaration, arrayMode: boolean, isOptional: boolean, squash: (string|boolean)) {\n const defaultPolicy = [\n { from: '', to: (isOptional || arrayMode ? undefined : '') },\n { from: null, to: (isOptional || arrayMode ? undefined : '') },\n ];\n\n const replace = isArray(config.replace) ? config.replace : [];\n if (isString(squash)) replace.push({ from: squash, to: undefined });\n\n const configuredKeys = map(replace, prop('from'));\n return filter(defaultPolicy, item => configuredKeys.indexOf(item.from) === -1).concat(replace);\n}\n\n\n/** @internalapi */\nexport class Param {\n id: string;\n type: ParamType;\n location: DefType;\n isOptional: boolean;\n dynamic: boolean;\n raw: boolean;\n squash: (boolean|string);\n replace: [{ to: any, from: any }];\n inherit: boolean;\n array: boolean;\n config: any;\n /** Cache the default value if it is a static value */\n _defaultValueCache: {\n defaultValue: any,\n };\n\n static values(params: Param[], values: RawParams = {}): RawParams {\n const paramValues = {} as RawParams;\n for (const param of params) {\n paramValues[param.id] = param.value(values[param.id]);\n }\n return paramValues;\n }\n\n /**\n * Finds [[Param]] objects which have different param values\n *\n * Filters a list of [[Param]] objects to only those whose parameter values differ in two param value objects\n *\n * @param params: The list of Param objects to filter\n * @param values1: The first set of parameter values\n * @param values2: the second set of parameter values\n *\n * @returns any Param objects whose values were different between values1 and values2\n */\n static changed(params: Param[], values1: RawParams = {}, values2: RawParams = {}): Param[] {\n return params.filter(param => !param.type.equals(values1[param.id], values2[param.id]));\n }\n\n /**\n * Checks if two param value objects are equal (for a set of [[Param]] objects)\n *\n * @param params The list of [[Param]] objects to check\n * @param values1 The first set of param values\n * @param values2 The second set of param values\n *\n * @returns true if the param values in values1 and values2 are equal\n */\n static equals(params: Param[], values1 = {}, values2 = {}): boolean {\n return Param.changed(params, values1, values2).length === 0;\n }\n\n /** Returns true if a the parameter values are valid, according to the Param definitions */\n static validates(params: Param[], values: RawParams = {}): boolean {\n return params.map(param => param.validates(values[param.id])).reduce(allTrueR, true);\n }\n\n constructor(id: string, type: ParamType, config: ParamDeclaration, location: DefType, urlMatcherFactory: UrlMatcherFactory) {\n config = unwrapShorthand(config);\n type = getType(config, type, location, id, urlMatcherFactory.paramTypes);\n const arrayMode = getArrayMode();\n type = arrayMode ? type.$asArray(arrayMode, location === DefType.SEARCH) : type;\n const isOptional = config.value !== undefined || location === DefType.SEARCH;\n const dynamic = isDefined(config.dynamic) ? !!config.dynamic : !!type.dynamic;\n const raw = isDefined(config.raw) ? !!config.raw : !!type.raw;\n const squash = getSquashPolicy(config, isOptional, urlMatcherFactory.defaultSquashPolicy());\n const replace = getReplace(config, arrayMode, isOptional, squash);\n const inherit = isDefined(config.inherit) ? !!config.inherit : !!type.inherit;\n\n // array config: param name (param[]) overrides default settings. explicit config overrides param name.\n function getArrayMode() {\n const arrayDefaults = { array: (location === DefType.SEARCH ? 'auto' : false) };\n const arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n return extend(arrayDefaults, arrayParamNomenclature, config).array;\n }\n\n extend(this, { id, type, location, isOptional, dynamic, raw, squash, replace, inherit, array: arrayMode, config });\n }\n\n isDefaultValue(value: any): boolean {\n return this.isOptional && this.type.equals(this.value(), value);\n }\n\n /**\n * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n * default value, which may be the result of an injectable function.\n */\n value(value?: any): any {\n /**\n * [Internal] Get the default value of a parameter, which may be an injectable function.\n */\n const getDefaultValue = () => {\n if (this._defaultValueCache) return this._defaultValueCache.defaultValue;\n\n if (!services.$injector) throw new Error('Injectable functions cannot be called at configuration time');\n\n const defaultValue = services.$injector.invoke(this.config.$$fn);\n\n if (defaultValue !== null && defaultValue !== undefined && !this.type.is(defaultValue))\n throw new Error(`Default value (${defaultValue}) for parameter '${this.id}' is not an instance of ParamType (${this.type.name})`);\n\n if (this.config.$$fn['__cacheable']) {\n this._defaultValueCache = { defaultValue };\n }\n\n return defaultValue;\n };\n\n const replaceSpecialValues = (val: any) => {\n for (const tuple of this.replace) {\n if (tuple.from === val) return tuple.to;\n }\n return val;\n };\n\n value = replaceSpecialValues(value);\n\n return isUndefined(value) ? getDefaultValue() : this.type.$normalize(value);\n }\n\n isSearch(): boolean {\n return this.location === DefType.SEARCH;\n }\n\n validates(value: any): boolean {\n // There was no parameter value, but the param is optional\n if ((isUndefined(value) || value === null) && this.isOptional) return true;\n\n // The value was not of the correct ParamType, and could not be decoded to the correct ParamType\n const normalized = this.type.$normalize(value);\n if (!this.type.is(normalized)) return false;\n\n // The value was of the correct type, but when encoded, did not match the ParamType's regexp\n const encoded = this.type.encode(normalized);\n return !(isString(encoded) && !this.type.pattern.exec( encoded));\n }\n\n toString() {\n return `{Param:${this.id} ${this.type} squash: '${this.squash}' optional: ${this.isOptional}}`;\n }\n}\n", - "/** @module path */ /** for typedoc */\nimport { extend, applyPairs, find, allTrueR, pairs, arrayTuples } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\n\n/**\n * @internalapi\n *\n * A node in a [[TreeChanges]] path\n *\n * For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path.\n * Each PathNode corresponds to a state being entered, exited, or retained.\n * The stateful information includes parameter values and resolve data.\n */\nexport class PathNode {\n /** The state being entered, exited, or retained */\n public state: StateObject;\n /** The parameters declared on the state */\n public paramSchema: Param[];\n /** The parameter values that belong to the state */\n public paramValues: { [key: string]: any };\n /** The individual (stateful) resolvable objects that belong to the state */\n public resolvables: Resolvable[];\n /** The state's declared view configuration objects */\n public views: ViewConfig[];\n\n /**\n * Returns a clone of the PathNode\n * @deprecated use instance method `node.clone()`\n */\n static clone = (node: PathNode) => node.clone();\n\n /** Creates a copy of a PathNode */\n constructor(node: PathNode);\n /** Creates a new (empty) PathNode for a State */\n constructor(state: StateObject);\n constructor(stateOrNode: any) {\n if (stateOrNode instanceof PathNode) {\n const node: PathNode = stateOrNode;\n this.state = node.state;\n this.paramSchema = node.paramSchema.slice();\n this.paramValues = extend({}, node.paramValues);\n this.resolvables = node.resolvables.slice();\n this.views = node.views && node.views.slice();\n } else {\n const state: StateObject = stateOrNode;\n this.state = state;\n this.paramSchema = state.parameters({ inherit: false });\n this.paramValues = {};\n this.resolvables = state.resolvables.map(res => res.clone());\n }\n }\n\n clone() {\n return new PathNode(this);\n }\n\n /** Sets [[paramValues]] for the node, from the values of an object hash */\n applyRawParams(params: RawParams): PathNode {\n const getParamVal = (paramDef: Param) => [ paramDef.id, paramDef.value(params[paramDef.id]) ];\n this.paramValues = this.paramSchema.reduce((memo, pDef) => applyPairs(memo, getParamVal(pDef)), {});\n return this;\n }\n\n /** Gets a specific [[Param]] metadata that belongs to the node */\n parameter(name: string): Param {\n return find(this.paramSchema, propEq('id', name));\n }\n\n /**\n * @returns true if the state and parameter values for another PathNode are\n * equal to the state and param values for this PathNode\n */\n equals(node: PathNode, paramsFn?: GetParamsFn): boolean {\n const diff = this.diff(node, paramsFn);\n return diff && diff.length === 0;\n }\n\n /**\n * Finds Params with different parameter values on another PathNode.\n *\n * Given another node (of the same state), finds the parameter values which differ.\n * Returns the [[Param]] (schema objects) whose parameter values differ.\n *\n * Given another node for a different state, returns `false`\n *\n * @param node The node to compare to\n * @param paramsFn A function that returns which parameters should be compared.\n * @returns The [[Param]]s which differ, or null if the two nodes are for different states\n */\n diff(node: PathNode, paramsFn?: GetParamsFn): Param[] | false {\n if (this.state !== node.state) return false;\n\n const params: Param[] = paramsFn ? paramsFn(this) : this.paramSchema;\n return Param.changed(params, this.paramValues, node.paramValues);\n }\n}\n\n/** @hidden */\nexport type GetParamsFn = (pathNode: PathNode) => Param[];\n", - "/** @module path */ /** for typedoc */\n\nimport {\n extend, find, pick, omit, tail, mergeR, values, unnestR, Predicate, inArray, arrayTuples,\n} from '../common/common';\nimport { prop, propEq, not } from '../common/hof';\n\nimport { RawParams } from '../params/interface';\nimport { TreeChanges } from '../transition/interface';\nimport { ViewConfig } from '../view/interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { GetParamsFn, PathNode } from './pathNode';\nimport { ViewService } from '../view/view';\nimport { Param } from '../params/param';\nimport { StateRegistry } from '../state';\n\n/**\n * This class contains functions which convert TargetStates, Nodes and paths from one type to another.\n */\nexport class PathUtils {\n /** Given a PathNode[], create an TargetState */\n static makeTargetState(registry: StateRegistry, path: PathNode[]): TargetState {\n const state = tail(path).state;\n return new TargetState(registry, state, path.map(prop('paramValues')).reduce(mergeR, {}), {});\n }\n\n static buildPath(targetState: TargetState) {\n const toParams = targetState.params();\n return targetState.$state().path.map(state => new PathNode(state).applyRawParams(toParams));\n }\n\n /** Given a fromPath: PathNode[] and a TargetState, builds a toPath: PathNode[] */\n static buildToPath(fromPath: PathNode[], targetState: TargetState): PathNode[] {\n const toPath: PathNode[] = PathUtils.buildPath(targetState);\n if (targetState.options().inherit) {\n return PathUtils.inheritParams(fromPath, toPath, Object.keys(targetState.params()));\n }\n return toPath;\n }\n\n /**\n * Creates ViewConfig objects and adds to nodes.\n *\n * On each [[PathNode]], creates ViewConfig objects from the views: property of the node's state\n */\n static applyViewConfigs($view: ViewService, path: PathNode[], states: StateObject[]) {\n // Only apply the viewConfigs to the nodes for the given states\n path.filter(node => inArray(states, node.state)).forEach(node => {\n const viewDecls: _ViewDeclaration[] = values(node.state.views || {});\n const subPath = PathUtils.subPath(path, n => n === node);\n const viewConfigs: ViewConfig[][] = viewDecls.map(view => $view.createViewConfig(subPath, view));\n node.views = viewConfigs.reduce(unnestR, []);\n });\n }\n\n /**\n * Given a fromPath and a toPath, returns a new to path which inherits parameters from the fromPath\n *\n * For a parameter in a node to be inherited from the from path:\n * - The toPath's node must have a matching node in the fromPath (by state).\n * - The parameter name must not be found in the toKeys parameter array.\n *\n * Note: the keys provided in toKeys are intended to be those param keys explicitly specified by some\n * caller, for instance, $state.transitionTo(..., toParams). If a key was found in toParams,\n * it is not inherited from the fromPath.\n */\n static inheritParams(fromPath: PathNode[], toPath: PathNode[], toKeys: string[] = []): PathNode[] {\n function nodeParamVals(path: PathNode[], state: StateObject): RawParams {\n const node: PathNode = find(path, propEq('state', state));\n return extend({}, node && node.paramValues);\n }\n\n const noInherit = fromPath.map(node => node.paramSchema)\n .reduce(unnestR, [])\n .filter(param => !param.inherit)\n .map(prop('id'));\n\n /**\n * Given an [[PathNode]] \"toNode\", return a new [[PathNode]] with param values inherited from the\n * matching node in fromPath. Only inherit keys that aren't found in \"toKeys\" from the node in \"fromPath\"\"\n */\n function makeInheritedParamsNode(toNode: PathNode): PathNode {\n // All param values for the node (may include default key/vals, when key was not found in toParams)\n let toParamVals = extend({}, toNode && toNode.paramValues);\n // limited to only those keys found in toParams\n const incomingParamVals = pick(toParamVals, toKeys);\n toParamVals = omit(toParamVals, toKeys);\n const fromParamVals = omit(nodeParamVals(fromPath, toNode.state) || {}, noInherit);\n // extend toParamVals with any fromParamVals, then override any of those those with incomingParamVals\n const ownParamVals: RawParams = extend(toParamVals, fromParamVals, incomingParamVals);\n return new PathNode(toNode.state).applyRawParams(ownParamVals);\n }\n\n // The param keys specified by the incoming toParams\n return toPath.map(makeInheritedParamsNode);\n }\n\n static nonDynamicParams = (node: PathNode): Param[] =>\n node.state.parameters({ inherit: false })\n .filter(param => !param.dynamic);\n\n /**\n * Computes the tree changes (entering, exiting) between a fromPath and toPath.\n */\n static treeChanges(fromPath: PathNode[], toPath: PathNode[], reloadState: StateObject): TreeChanges {\n const max = Math.min(fromPath.length, toPath.length);\n let keep = 0;\n\n const nodesMatch = (node1: PathNode, node2: PathNode) =>\n node1.equals(node2, PathUtils.nonDynamicParams);\n\n while (keep < max && fromPath[keep].state !== reloadState && nodesMatch(fromPath[keep], toPath[keep])) {\n keep++;\n }\n\n /** Given a retained node, return a new node which uses the to node's param values */\n function applyToParams(retainedNode: PathNode, idx: number): PathNode {\n const cloned = retainedNode.clone();\n cloned.paramValues = toPath[idx].paramValues;\n return cloned;\n }\n\n let from: PathNode[], retained: PathNode[], exiting: PathNode[], entering: PathNode[], to: PathNode[];\n\n from = fromPath;\n retained = from.slice(0, keep);\n exiting = from.slice(keep);\n\n // Create a new retained path (with shallow copies of nodes) which have the params of the toPath mapped\n const retainedWithToParams = retained.map(applyToParams);\n entering = toPath.slice(keep);\n to = (retainedWithToParams).concat(entering);\n\n return { from, to, retained, retainedWithToParams, exiting, entering };\n }\n\n /**\n * Returns a new path which is: the subpath of the first path which matches the second path.\n *\n * The new path starts from root and contains any nodes that match the nodes in the second path.\n * It stops before the first non-matching node.\n *\n * Nodes are compared using their state property and their parameter values.\n * If a `paramsFn` is provided, only the [[Param]] returned by the function will be considered when comparing nodes.\n *\n * @param pathA the first path\n * @param pathB the second path\n * @param paramsFn a function which returns the parameters to consider when comparing\n *\n * @returns an array of PathNodes from the first path which match the nodes in the second path\n */\n static matching(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): PathNode[] {\n let done = false;\n const tuples: PathNode[][] = arrayTuples(pathA, pathB);\n return tuples.reduce((matching, [nodeA, nodeB]) => {\n done = done || !nodeA.equals(nodeB, paramsFn);\n return done ? matching : matching.concat(nodeA);\n }, []);\n }\n\n /**\n * Returns true if two paths are identical.\n *\n * @param pathA\n * @param pathB\n * @param paramsFn a function which returns the parameters to consider when comparing\n * @returns true if the the states and parameter values for both paths are identical\n */\n static equals(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): boolean {\n return pathA.length === pathB.length &&\n PathUtils.matching(pathA, pathB, paramsFn).length === pathA.length;\n }\n\n /**\n * Return a subpath of a path, which stops at the first matching node\n *\n * Given an array of nodes, returns a subset of the array starting from the first node,\n * stopping when the first node matches the predicate.\n *\n * @param path a path of [[PathNode]]s\n * @param predicate a [[Predicate]] fn that matches [[PathNode]]s\n * @returns a subpath up to the matching node, or undefined if no match is found\n */\n static subPath(path: PathNode[], predicate: Predicate): PathNode[] {\n const node = find(path, predicate);\n const elementIdx = path.indexOf(node);\n return elementIdx === -1 ? undefined : path.slice(0, elementIdx + 1);\n }\n\n /** Gets the raw parameter values from a path */\n static paramValues = (path: PathNode[]) =>\n path.reduce((acc, node) => extend(acc, node.paramValues), {});\n}\n", - "/**\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { extend, equals, inArray, identity } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { trace } from '../common/trace';\nimport { ResolvePolicy, ResolvableLiteral, resolvePolicies } from './interface';\n\nimport { ResolveContext } from './resolveContext';\nimport { stringify } from '../common/strings';\nimport { isFunction, isObject } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { isNullOrUndefined } from '../common/predicates';\n\n\n// TODO: explicitly make this user configurable\nexport let defaultResolvePolicy: ResolvePolicy = {\n when: 'LAZY',\n async: 'WAIT',\n};\n\n/**\n * The basic building block for the resolve system.\n *\n * Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise),\n * and the unwrapped-when-complete (.data) result of the resolveFn.\n *\n * Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the\n * resolveFn) and returns the resulting promise.\n *\n * Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first\n * parameter to those fns.\n */\nexport class Resolvable implements ResolvableLiteral {\n token: any;\n policy: ResolvePolicy;\n resolveFn: Function;\n deps: any[];\n\n data: any;\n resolved = false;\n promise: Promise = undefined;\n\n static fromData = (token: any, data: any) =>\n new Resolvable(token, () => data, null, null, data);\n\n /** This constructor creates a Resolvable copy */\n constructor(resolvable: Resolvable)\n\n /** This constructor creates a new Resolvable from the plain old [[ResolvableLiteral]] javascript object */\n constructor(resolvable: ResolvableLiteral)\n\n /**\n * This constructor creates a new `Resolvable`\n *\n * #### Example:\n * ```js\n * var resolvable1 = new Resolvable('mytoken', http => http.get('foo.json').toPromise(), [Http]);\n *\n * var resolvable2 = new Resolvable(UserService, dep => new UserService(dep.data), [SomeDependency]);\n *\n * var resolvable1Clone = new Resolvable(resolvable1);\n * ```\n *\n * @param token The new resolvable's injection token, such as `\"userList\"` (a string) or `UserService` (a class).\n * When this token is used during injection, the resolved value will be injected.\n * @param resolveFn The function that returns the resolved value, or a promise for the resolved value\n * @param deps An array of dependencies, which will be injected into the `resolveFn`\n * @param policy the [[ResolvePolicy]] defines when and how the Resolvable is processed\n * @param data Pre-resolved data. If the resolve value is already known, it may be provided here.\n */\n constructor(token: any, resolveFn: Function, deps?: any[], policy?: ResolvePolicy, data?: any)\n constructor(arg1: any, resolveFn?: Function, deps?: any[], policy?: ResolvePolicy, data?: any) {\n if (arg1 instanceof Resolvable) {\n extend(this, arg1);\n } else if (isFunction(resolveFn)) {\n if (isNullOrUndefined(arg1)) throw new Error('new Resolvable(): token argument is required');\n if (!isFunction(resolveFn)) throw new Error('new Resolvable(): resolveFn argument must be a function');\n\n this.token = arg1;\n this.policy = policy;\n this.resolveFn = resolveFn;\n this.deps = deps || [];\n\n this.data = data;\n this.resolved = data !== undefined;\n this.promise = this.resolved ? services.$q.when(this.data) : undefined;\n } else if (isObject(arg1) && arg1.token && (arg1.hasOwnProperty('resolveFn') || arg1.hasOwnProperty('data'))) {\n const literal = arg1;\n return new Resolvable(literal.token, literal.resolveFn, literal.deps, literal.policy, literal.data);\n }\n }\n\n getPolicy(state: StateObject): ResolvePolicy {\n const thisPolicy = this.policy || {};\n const statePolicy = state && state.resolvePolicy || {};\n return {\n when: thisPolicy.when || statePolicy.when || defaultResolvePolicy.when,\n async: thisPolicy.async || statePolicy.async || defaultResolvePolicy.async,\n };\n }\n\n /**\n * Asynchronously resolve this Resolvable's data\n *\n * Given a ResolveContext that this Resolvable is found in:\n * Wait for this Resolvable's dependencies, then invoke this Resolvable's function\n * and update the Resolvable's state\n */\n resolve(resolveContext: ResolveContext, trans?: Transition) {\n const $q = services.$q;\n\n // Gets all dependencies from ResolveContext and wait for them to be resolved\n const getResolvableDependencies = () =>\n $q.all(resolveContext.getDependencies(this).map(resolvable =>\n resolvable.get(resolveContext, trans))) as Promise;\n\n // Invokes the resolve function passing the resolved dependencies as arguments\n const invokeResolveFn = (resolvedDeps: any[]) =>\n this.resolveFn.apply(null, resolvedDeps);\n\n /**\n * For RXWAIT policy:\n *\n * Given an observable returned from a resolve function:\n * - enables .cache() mode (this allows multicast subscribers)\n * - then calls toPromise() (this triggers subscribe() and thus fetches)\n * - Waits for the promise, then return the cached observable (not the first emitted value).\n */\n const waitForRx = (observable$: any) => {\n const cached = observable$.cache(1);\n return cached.take(1).toPromise().then(() => cached);\n };\n\n // If the resolve policy is RXWAIT, wait for the observable to emit something. otherwise pass through.\n const node: PathNode = resolveContext.findNode(this);\n const state: StateObject = node && node.state;\n const maybeWaitForRx = this.getPolicy(state).async === 'RXWAIT' ? waitForRx : identity;\n\n // After the final value has been resolved, update the state of the Resolvable\n const applyResolvedValue = (resolvedValue: any) => {\n this.data = resolvedValue;\n this.resolved = true;\n this.resolveFn = null;\n trace.traceResolvableResolved(this, trans);\n return this.data;\n };\n\n // Sets the promise property first, then getsResolvableDependencies in the context of the promise chain. Always waits one tick.\n return this.promise = $q.when()\n .then(getResolvableDependencies)\n .then(invokeResolveFn)\n .then(maybeWaitForRx)\n .then(applyResolvedValue);\n }\n\n /**\n * Gets a promise for this Resolvable's data.\n *\n * Fetches the data and returns a promise.\n * Returns the existing promise if it has already been fetched once.\n */\n get(resolveContext: ResolveContext, trans?: Transition): Promise {\n return this.promise || this.resolve(resolveContext, trans);\n }\n\n toString() {\n return `Resolvable(token: ${stringify(this.token)}, requires: [${this.deps.map(stringify)}])`;\n }\n\n clone(): Resolvable {\n return new Resolvable(this);\n }\n}\n", - "/**\n * # The Resolve subsystem\n *\n * This subsystem is an asynchronous, hierarchical Dependency Injection system.\n *\n * Typically, resolve is configured on a state using a [[StateDeclaration.resolve]] declaration.\n *\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { Resolvable } from './resolvable';\n\n/**\n * An interface which is similar to an Angular 2 `Provider`\n */\nexport interface ProviderLike {\n provide: any,\n useClass?: any,\n useFactory?: Function,\n useValue?: any,\n useExisting?: any,\n deps?: any[]\n}\n\n/**\n * A plain object used to describe a [[Resolvable]]\n *\n * These objects may be used in the [[StateDeclaration.resolve]] array to declare\n * async data that the state or substates require.\n *\n * #### Example:\n * ```js\n *\n * var state = {\n * name: 'main',\n * resolve: [\n * { token: 'myData', deps: [MyDataApi], resolveFn: (myDataApi) => myDataApi.getData() },\n * ],\n * }\n * ```\n */\nexport interface ResolvableLiteral {\n /**\n * A Dependency Injection token\n *\n * This Resolvable's DI token.\n * The Resolvable will be injectable elsewhere using the token.\n */\n token: any;\n\n /**\n * A function which fetches the Resolvable's data\n *\n * A function which returns one of:\n *\n * - The resolved value (synchronously)\n * - A promise for the resolved value\n * - An Observable of the resolved value(s)\n *\n * This function will be provided the dependencies listed in [[deps]] as its arguments.\n * The resolve system will asynchronously fetch the dependencies before invoking this function.\n */\n resolveFn: Function;\n\n /**\n * Defines the Resolve Policy\n *\n * A policy that defines when to invoke the resolve,\n * and whether to wait for async and unwrap the data\n */\n policy?: ResolvePolicy;\n\n /**\n * The Dependency Injection tokens\n *\n * This is an array of Dependency Injection tokens for the dependencies of the [[resolveFn]].\n *\n * The DI tokens are references to other `Resolvables`, or to other\n * services from the native DI system.\n */\n deps?: any[];\n\n /** Pre-resolved data. */\n data?: any\n}\n\n/**\n * Defines how a resolve is processed during a transition\n *\n * This object is the [[StateDeclaration.resolvePolicy]] property.\n *\n * #### Example:\n * ```js\n * // Fetched when the resolve's state is being entered.\n * // Wait for the promise to resolve.\n * var policy1 = { when: \"LAZY\", async: \"WAIT\" }\n *\n * // Fetched when the Transition is starting.\n * // Do not wait for the returned promise to resolve.\n * // Inject the raw promise/value\n * var policy2 = { when: \"EAGER\", async: \"NOWAIT\" }\n * ```\n *\n * The policy for a given Resolvable is merged from three sources (highest priority first):\n *\n * - 1) Individual resolve definition\n * - 2) State definition\n * - 3) Global default\n *\n * #### Example:\n * ```js\n * // Wait for an Observable to emit one item.\n * // Since `wait` is not specified, it uses the `wait`\n * // policy defined on the state, or the global default\n * // if no `wait` policy is defined on the state\n * var myResolvablePolicy = { async: \"RXWAIT\" }\n * ```\n */\nexport interface ResolvePolicy {\n /**\n * Defines when a Resolvable is resolved (fetched) during a transition\n *\n * - `LAZY` (default)\n * - Resolved as the resolve's state is being entered\n * - `EAGER`\n * - Resolved as the transition is starting\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched when each state is entered.\n * All of `main` resolves are processed before fetching `main.home` resolves.\n * ```js\n * var state = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n *\n * var state = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n * ```\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched at the same time when the transition starts.\n * This happens earlier in the lifecycle than when states are entered.\n * All of the `main` and `main.home` resolves are fetched as soon as possible.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n *\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n * ```\n */\n when?: PolicyWhen;\n\n /**\n * Determines the unwrapping behavior of asynchronous resolve values.\n *\n * - `WAIT` (default)\n * - If a promise is returned from the resolveFn, wait for the promise before proceeding\n * - The unwrapped value from the promise\n * - `NOWAIT`\n * - If a promise is returned from the resolve, do not wait for the promise.\n * - Any other value returned is wrapped in a promise.\n * - The promise will not be unwrapped.\n * - The promise itself will be provided when the resolve is injected or bound elsewhere.\n * - `RXWAIT`\n * - When an Observable is returned from the resolveFn, wait until the Observable emits at least one item.\n * - The Observable item will not be unwrapped.\n * - The Observable stream itself will be provided when the resolve is injected or bound elsewhere.\n *\n * #### Example:\n * The `Transition` will not wait for the resolve promise(s) from `main` to settle before continuing.\n * Resolves for `main` will be provided to components wrapped in a `Promise`.\n *\n * The `Transition` will wait for the `main.home` resolve promises.\n * Resolved values will be unwrapped before being provided to components.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { async: 'NOWAIT' },\n * }\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { async: 'WAIT' }, // default\n * }\n * ```\n */\n async?: PolicyAsync;\n}\n\nexport type PolicyWhen = 'LAZY' | 'EAGER' ;\nexport type PolicyAsync = 'WAIT' | 'NOWAIT' | 'RXWAIT' ;\n\n/** @internalapi */\nexport let resolvePolicies = {\n when: {\n LAZY: 'LAZY',\n EAGER: 'EAGER',\n },\n async: {\n WAIT: 'WAIT',\n NOWAIT: 'NOWAIT',\n RXWAIT: 'RXWAIT',\n },\n};\n", - "/** @module resolve */\n/** for typedoc */\nimport { find, tail, uniqR, unnestR, inArray } from '../common/common';\nimport { propEq, not } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services, $InjectorLike } from '../common/coreservices';\nimport { resolvePolicies, PolicyWhen, ResolvePolicy } from './interface';\nimport { PathNode } from '../path/pathNode';\nimport { Resolvable } from './resolvable';\nimport { StateObject } from '../state/stateObject';\nimport { PathUtils } from '../path/pathUtils';\nimport { stringify } from '../common/strings';\nimport { Transition } from '../transition/transition';\nimport { UIInjector } from '../interface';\nimport { isUndefined } from '../common';\n\nconst whens = resolvePolicies.when;\nconst ALL_WHENS = [whens.EAGER, whens.LAZY];\nconst EAGER_WHENS = [whens.EAGER];\n\n// tslint:disable-next-line:no-inferrable-types\nexport const NATIVE_INJECTOR_TOKEN: string = 'Native Injector';\n\n/**\n * Encapsulates Dependency Injection for a path of nodes\n *\n * UI-Router states are organized as a tree.\n * A nested state has a path of ancestors to the root of the tree.\n * When a state is being activated, each element in the path is wrapped as a [[PathNode]].\n * A `PathNode` is a stateful object that holds things like parameters and resolvables for the state being activated.\n *\n * The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path.\n */\nexport class ResolveContext {\n _injector: UIInjector;\n\n constructor(private _path: PathNode[]) { }\n\n /** Gets all the tokens found in the resolve context, de-duplicated */\n getTokens(): any[] {\n return this._path.reduce((acc, node) => acc.concat(node.resolvables.map(r => r.token)), []).reduce(uniqR, []);\n }\n\n /**\n * Gets the Resolvable that matches the token\n *\n * Gets the last Resolvable that matches the token in this context, or undefined.\n * Throws an error if it doesn't exist in the ResolveContext\n */\n getResolvable(token: any): Resolvable {\n const matching = this._path.map(node => node.resolvables)\n .reduce(unnestR, [])\n .filter((r: Resolvable) => r.token === token);\n return tail(matching);\n }\n\n /** Returns the [[ResolvePolicy]] for the given [[Resolvable]] */\n getPolicy(resolvable: Resolvable): ResolvePolicy {\n const node = this.findNode(resolvable);\n return resolvable.getPolicy(node.state);\n }\n\n /**\n * Returns a ResolveContext that includes a portion of this one\n *\n * Given a state, this method creates a new ResolveContext from this one.\n * The new context starts at the first node (root) and stops at the node for the `state` parameter.\n *\n * #### Why\n *\n * When a transition is created, the nodes in the \"To Path\" are injected from a ResolveContext.\n * A ResolveContext closes over a path of [[PathNode]]s and processes the resolvables.\n * The \"To State\" can inject values from its own resolvables, as well as those from all its ancestor state's (node's).\n * This method is used to create a narrower context when injecting ancestor nodes.\n *\n * @example\n * `let ABCD = new ResolveContext([A, B, C, D]);`\n *\n * Given a path `[A, B, C, D]`, where `A`, `B`, `C` and `D` are nodes for states `a`, `b`, `c`, `d`:\n * When injecting `D`, `D` should have access to all resolvables from `A`, `B`, `C`, `D`.\n * However, `B` should only be able to access resolvables from `A`, `B`.\n *\n * When resolving for the `B` node, first take the full \"To Path\" Context `[A,B,C,D]` and limit to the subpath `[A,B]`.\n * `let AB = ABCD.subcontext(a)`\n */\n subContext(state: StateObject): ResolveContext {\n return new ResolveContext(PathUtils.subPath(this._path, node => node.state === state));\n }\n\n /**\n * Adds Resolvables to the node that matches the state\n *\n * This adds a [[Resolvable]] (generally one created on the fly; not declared on a [[StateDeclaration.resolve]] block).\n * The resolvable is added to the node matching the `state` parameter.\n *\n * These new resolvables are not automatically fetched.\n * The calling code should either fetch them, fetch something that depends on them,\n * or rely on [[resolvePath]] being called when some state is being entered.\n *\n * Note: each resolvable's [[ResolvePolicy]] is merged with the state's policy, and the global default.\n *\n * @param newResolvables the new Resolvables\n * @param state Used to find the node to put the resolvable on\n */\n addResolvables(newResolvables: Resolvable[], state: StateObject) {\n const node = find(this._path, propEq('state', state));\n const keys = newResolvables.map(r => r.token);\n node.resolvables = node.resolvables.filter(r => keys.indexOf(r.token) === -1).concat(newResolvables);\n }\n\n /**\n * Returns a promise for an array of resolved path Element promises\n *\n * @param when\n * @param trans\n * @returns {Promise|any}\n */\n resolvePath(when: PolicyWhen = 'LAZY', trans?: Transition): Promise<{ token: any, value: any }[]> {\n // This option determines which 'when' policy Resolvables we are about to fetch.\n const whenOption: string = inArray(ALL_WHENS, when) ? when : 'LAZY';\n // If the caller specified EAGER, only the EAGER Resolvables are fetched.\n // if the caller specified LAZY, both EAGER and LAZY Resolvables are fetched.`\n const matchedWhens = whenOption === resolvePolicies.when.EAGER ? EAGER_WHENS : ALL_WHENS;\n\n // get the subpath to the state argument, if provided\n trace.traceResolvePath(this._path, when, trans);\n\n const matchesPolicy = (acceptedVals: string[], whenOrAsync: 'when'|'async') =>\n (resolvable: Resolvable) =>\n inArray(acceptedVals, this.getPolicy(resolvable)[whenOrAsync]);\n\n // Trigger all the (matching) Resolvables in the path\n // Reduce all the \"WAIT\" Resolvables into an array\n const promises: Promise[] = this._path.reduce((acc, node) => {\n const nodeResolvables = node.resolvables.filter(matchesPolicy(matchedWhens, 'when'));\n const nowait = nodeResolvables.filter(matchesPolicy(['NOWAIT'], 'async'));\n const wait = nodeResolvables.filter(not(matchesPolicy(['NOWAIT'], 'async')));\n\n // For the matching Resolvables, start their async fetch process.\n const subContext = this.subContext(node.state);\n const getResult = (r: Resolvable) => r.get(subContext, trans)\n // Return a tuple that includes the Resolvable's token\n .then(value => ({ token: r.token, value: value }));\n nowait.forEach(getResult);\n return acc.concat(wait.map(getResult));\n }, []);\n\n // Wait for all the \"WAIT\" resolvables\n return services.$q.all(promises);\n }\n\n injector(): UIInjector {\n return this._injector || (this._injector = new UIInjectorImpl(this));\n }\n\n findNode(resolvable: Resolvable): PathNode {\n return find(this._path, (node: PathNode) => inArray(node.resolvables, resolvable));\n }\n\n /**\n * Gets the async dependencies of a Resolvable\n *\n * Given a Resolvable, returns its dependencies as a Resolvable[]\n */\n getDependencies(resolvable: Resolvable): Resolvable[] {\n const node = this.findNode(resolvable);\n // Find which other resolvables are \"visible\" to the `resolvable` argument\n // subpath stopping at resolvable's node, or the whole path (if the resolvable isn't in the path)\n const subPath: PathNode[] = PathUtils.subPath(this._path, x => x === node) || this._path;\n const availableResolvables: Resolvable[] = subPath\n .reduce((acc, _node) => acc.concat(_node.resolvables), []) // all of subpath's resolvables\n .filter(res => res !== resolvable); // filter out the `resolvable` argument\n\n const getDependency = (token: any) => {\n const matching = availableResolvables.filter(r => r.token === token);\n if (matching.length) return tail(matching);\n\n const fromInjector = this.injector().getNative(token);\n if (isUndefined(fromInjector)) {\n throw new Error('Could not find Dependency Injection token: ' + stringify(token));\n }\n\n return new Resolvable(token, () => fromInjector, [], fromInjector);\n };\n\n return resolvable.deps.map(getDependency);\n }\n}\n\nclass UIInjectorImpl implements UIInjector {\n native: $InjectorLike;\n\n constructor(public context: ResolveContext) {\n this.native = this.get(NATIVE_INJECTOR_TOKEN) || services.$injector;\n }\n\n get(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) {\n if (this.context.getPolicy(resolvable).async === 'NOWAIT') {\n return resolvable.get(this.context);\n }\n\n if (!resolvable.resolved) {\n throw new Error('Resolvable async .get() not complete:' + stringify(resolvable.token));\n }\n return resolvable.data;\n }\n\n return this.getNative(token);\n }\n\n getAsync(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) return resolvable.get(this.context);\n return services.$q.when(this.native.get(token));\n }\n\n getNative(token: any) {\n return this.native && this.native.get(token);\n }\n}\n", - "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { stringify } from '../common/strings';\nimport { map, find, extend, mergeR, tail, omit, arrayTuples, unnestR, identity, anyTrueR } from '../common/common';\nimport { isObject, isUndefined } from '../common/predicates';\nimport { prop, propEq, val, not, is } from '../common/hof';\nimport { StateDeclaration, StateOrName } from '../state/interface';\nimport {\n TransitionOptions, TreeChanges, IHookRegistry, TransitionHookPhase, RegisteredHooks, HookRegOptions,\n HookMatchCriteria, TransitionStateHookFn, TransitionHookFn,\n} from './interface'; // has or is using\nimport { TransitionHook } from './transitionHook';\nimport { matchState, makeEvent, RegisteredHook } from './hookRegistry';\nimport { HookBuilder } from './hookBuilder';\nimport { PathNode } from '../path/pathNode';\nimport { PathUtils } from '../path/pathUtils';\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { RawParams } from '../params/interface';\nimport { ResolvableLiteral } from '../resolve/interface';\n\n/** @hidden */\nconst stateSelf: (_state: StateObject) => StateDeclaration = prop('self');\n\n/**\n * Represents a transition between two states.\n *\n * When navigating to a state, we are transitioning **from** the current state **to** the new state.\n *\n * This object contains all contextual information about the to/from states, parameters, resolves.\n * It has information about all states being entered and exited as a result of the transition.\n */\nexport class Transition implements IHookRegistry {\n\n /** @hidden */\n static diToken = Transition;\n\n /**\n * A unique identifier for the transition.\n *\n * This is an auto incrementing integer, starting from `0`.\n */\n $id: number;\n\n /**\n * A reference to the [[UIRouter]] instance\n *\n * This reference can be used to access the router services, such as the [[StateService]]\n */\n router: UIRouter;\n\n /** @hidden */\n private _deferred = services.$q.defer();\n /**\n * This promise is resolved or rejected based on the outcome of the Transition.\n *\n * When the transition is successful, the promise is resolved\n * When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error\n */\n promise: Promise = this._deferred.promise;\n /**\n * A boolean which indicates if the transition was successful\n *\n * After a successful transition, this value is set to true.\n * After an unsuccessful transition, this value is set to false.\n *\n * The value will be undefined if the transition is not complete\n */\n success: boolean;\n /** @hidden */\n _aborted: boolean;\n /** @hidden */\n private _error: any;\n\n /** @hidden Holds the hook registration functions such as those passed to Transition.onStart() */\n _registeredHooks: RegisteredHooks = { };\n\n /** @hidden */\n private _options: TransitionOptions;\n /** @hidden */\n private _treeChanges: TreeChanges;\n /** @hidden */\n private _targetState: TargetState;\n /** @hidden */\n private _hookBuilder = new HookBuilder(this);\n\n\n /** @hidden */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n\n /** @hidden\n * Creates the transition-level hook registration functions\n * (which can then be used to register hooks)\n */\n private createTransitionHookRegFns() {\n this.router.transitionService._pluginapi._getEvents()\n .filter(type => type.hookPhase !== TransitionHookPhase.CREATE)\n .forEach(type => makeEvent(this, this.router.transitionService, type));\n }\n\n /** @internalapi */\n getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /**\n * Creates a new Transition object.\n *\n * If the target state is not valid, an error is thrown.\n *\n * @internalapi\n *\n * @param fromPath The path of [[PathNode]]s from which the transition is leaving. The last node in the `fromPath`\n * encapsulates the \"from state\".\n * @param targetState The target state and parameters being transitioned to (also, the transition options)\n * @param router The [[UIRouter]] instance\n */\n constructor(fromPath: PathNode[], targetState: TargetState, router: UIRouter) {\n this.router = router;\n this._targetState = targetState;\n\n if (!targetState.valid()) {\n throw new Error(targetState.error());\n }\n\n // current() is assumed to come from targetState.options, but provide a naive implementation otherwise.\n this._options = extend({ current: val(this) }, targetState.options());\n this.$id = router.transitionService._transitionCount++;\n const toPath = PathUtils.buildToPath(fromPath, targetState);\n this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState);\n this.createTransitionHookRegFns();\n\n const onCreateHooks = this._hookBuilder.buildHooksForPhase(TransitionHookPhase.CREATE);\n TransitionHook.invokeHooks(onCreateHooks, () => null);\n\n this.applyViewConfigs(router);\n }\n\n private applyViewConfigs(router: UIRouter) {\n const enteringStates = this._treeChanges.entering.map(node => node.state);\n PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates);\n }\n\n /**\n * @internalapi\n *\n * @returns the internal from [State] object\n */\n $from() {\n return tail(this._treeChanges.from).state;\n }\n\n /**\n * @internalapi\n *\n * @returns the internal to [State] object\n */\n $to() {\n return tail(this._treeChanges.to).state;\n }\n\n /**\n * Returns the \"from state\"\n *\n * Returns the state that the transition is coming *from*.\n *\n * @returns The state declaration object for the Transition's (\"from state\").\n */\n from(): StateDeclaration {\n return this.$from().self;\n }\n\n /**\n * Returns the \"to state\"\n *\n * Returns the state that the transition is going *to*.\n *\n * @returns The state declaration object for the Transition's target state (\"to state\").\n */\n to(): StateDeclaration {\n return this.$to().self;\n }\n\n /**\n * Gets the Target State\n *\n * A transition's [[TargetState]] encapsulates the [[to]] state, the [[params]], and the [[options]] as a single object.\n *\n * @returns the [[TargetState]] of this Transition\n */\n targetState() {\n return this._targetState;\n }\n\n /**\n * Determines whether two transitions are equivalent.\n * @deprecated\n */\n is(compare: (Transition|{to?: any, from?: any})): boolean {\n if (compare instanceof Transition) {\n // TODO: Also compare parameters\n return this.is({ to: compare.$to().name, from: compare.$from().name });\n }\n return !(\n (compare.to && !matchState(this.$to(), compare.to)) ||\n (compare.from && !matchState(this.$from(), compare.from))\n );\n }\n\n /**\n * Gets transition parameter values\n *\n * Returns the parameter values for a transition as key/value pairs.\n * This object is immutable.\n *\n * By default, returns the new parameter values (for the \"to state\").\n *\n * #### Example:\n * ```js\n * var toParams = transition.params();\n * ```\n *\n * To return the previous parameter values, supply `'from'` as the `pathname` argument.\n *\n * #### Example:\n * ```js\n * var fromParams = transition.params('from');\n * ```\n *\n * @param pathname the name of the treeChanges path to get parameter values for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n *\n * @returns transition parameter values for the desired path.\n */\n params(pathname?: string): any;\n params(pathname?: string): T;\n params(pathname = 'to') {\n return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {}));\n }\n\n\n /**\n * Creates a [[UIInjector]] Dependency Injector\n *\n * Returns a Dependency Injector for the Transition's target state (to state).\n * The injector provides resolve values which the target state has access to.\n *\n * The `UIInjector` can also provide values from the native root/global injector (ng1/ng2).\n *\n * #### Example:\n * ```js\n * .onEnter({ entering: 'myState' }, trans => {\n * var myResolveValue = trans.injector().get('myResolve');\n * // Inject a global service from the global/native injector (if it exists)\n * var MyService = trans.injector().get('MyService');\n * })\n * ```\n *\n * In some cases (such as `onBefore`), you may need access to some resolve data but it has not yet been fetched.\n * You can use [[UIInjector.getAsync]] to get a promise for the data.\n * #### Example:\n * ```js\n * .onBefore({}, trans => {\n * return trans.injector().getAsync('myResolve').then(myResolveValue =>\n * return myResolveValue !== 'ABORT';\n * });\n * });\n * ```\n *\n * If a `state` is provided, the injector that is returned will be limited to resolve values that the provided state has access to.\n * This can be useful if both a parent state `foo` and a child state `foo.bar` have both defined a resolve such as `data`.\n * #### Example:\n * ```js\n * .onEnter({ to: 'foo.bar' }, trans => {\n * // returns result of `foo` state's `myResolve` resolve\n * // even though `foo.bar` also has a `myResolve` resolve\n * var fooData = trans.injector('foo').get('myResolve');\n * });\n * ```\n *\n * If you need resolve data from the exiting states, pass `'from'` as `pathName`.\n * The resolve data from the `from` path will be returned.\n * #### Example:\n * ```js\n * .onExit({ exiting: 'foo.bar' }, trans => {\n * // Gets the resolve value of `myResolve` from the state being exited\n * var fooData = trans.injector(null, 'from').get('myResolve');\n * });\n * ```\n *\n *\n * @param state Limits the resolves provided to only the resolves the provided state has access to.\n * @param pathName Default: `'to'`: Chooses the path for which to create the injector. Use this to access resolves for `exiting` states.\n *\n * @returns a [[UIInjector]]\n */\n injector(state?: StateOrName, pathName = 'to'): UIInjector {\n let path: PathNode[] = this._treeChanges[pathName];\n if (state) path = PathUtils.subPath(path, node => node.state === state || node.state.name === state);\n return new ResolveContext(path).injector();\n }\n\n /**\n * Gets all available resolve tokens (keys)\n *\n * This method can be used in conjunction with [[injector]] to inspect the resolve values\n * available to the Transition.\n *\n * This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states\n * in the Transition's [[TreeChanges.to]] path.\n *\n * #### Example:\n * This example logs all resolve values\n * ```js\n * let tokens = trans.getResolveTokens();\n * tokens.forEach(token => console.log(token + \" = \" + trans.injector().get(token)));\n * ```\n *\n * #### Example:\n * This example creates promises for each resolve value.\n * This triggers fetches of resolves (if any have not yet been fetched).\n * When all promises have all settled, it logs the resolve values.\n * ```js\n * let tokens = trans.getResolveTokens();\n * let promise = tokens.map(token => trans.injector().getAsync(token));\n * Promise.all(promises).then(values => console.log(\"Resolved values: \" + values));\n * ```\n *\n * Note: Angular 1 users whould use `$q.all()`\n *\n * @param pathname resolve context's path name (e.g., `to` or `from`)\n *\n * @returns an array of resolve tokens (keys)\n */\n getResolveTokens(pathname = 'to'): any[] {\n return new ResolveContext(this._treeChanges[pathname]).getTokens();\n }\n\n /**\n * Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.\n *\n * Allows a transition hook to dynamically add a Resolvable to this Transition.\n *\n * Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).\n *\n * If a `state` argument is provided, the Resolvable is processed when that state is being entered.\n * If no `state` is provided then the root state is used.\n * If the given `state` has already been entered, the Resolvable is processed when any child state is entered.\n * If no child states will be entered, the Resolvable is processed during the `onFinish` phase of the Transition.\n *\n * The `state` argument also scopes the resolved data.\n * The resolved data is available from the injector for that `state` and any children states.\n *\n * #### Example:\n * ```js\n * transitionService.onBefore({}, transition => {\n * transition.addResolvable({\n * token: 'myResolve',\n * deps: ['MyService'],\n * resolveFn: myService => myService.getData()\n * });\n * });\n * ```\n *\n * @param resolvable a [[ResolvableLiteral]] object (or a [[Resolvable]])\n * @param state the state in the \"to path\" which should receive the new resolve (otherwise, the root state)\n */\n addResolvable(resolvable: Resolvable|ResolvableLiteral, state: StateOrName = ''): void {\n resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable);\n\n const stateName: string = (typeof state === 'string') ? state : state.name;\n const topath = this._treeChanges.to;\n const targetNode = find(topath, node => node.state.name === stateName);\n const resolveContext: ResolveContext = new ResolveContext(topath);\n resolveContext.addResolvables([resolvable as Resolvable], targetNode.state);\n }\n\n /**\n * Gets the transition from which this transition was redirected.\n *\n * If the current transition is a redirect, this method returns the transition that was redirected.\n *\n * #### Example:\n * ```js\n * let transitionA = $state.go('A').transition\n * transitionA.onStart({}, () => $state.target('B'));\n * $transitions.onSuccess({ to: 'B' }, (trans) => {\n * trans.to().name === 'B'; // true\n * trans.redirectedFrom() === transitionA; // true\n * });\n * ```\n *\n * @returns The previous Transition, or null if this Transition is not the result of a redirection\n */\n redirectedFrom(): Transition {\n return this._options.redirectedFrom || null;\n }\n\n /**\n * Gets the original transition in a redirect chain\n *\n * A transition might belong to a long chain of multiple redirects.\n * This method walks the [[redirectedFrom]] chain back to the original (first) transition in the chain.\n *\n * #### Example:\n * ```js\n * // states\n * registry.register({ name: 'A', redirectTo: 'B' });\n * registry.register({ name: 'B', redirectTo: 'C' });\n * registry.register({ name: 'C', redirectTo: 'D' });\n * registry.register({ name: 'D' });\n *\n * let transitionA = $state.go('A').transition\n *\n * $transitions.onSuccess({ to: 'D' }, (trans) => {\n * trans.to().name === 'D'; // true\n * trans.redirectedFrom().to().name === 'C'; // true\n * trans.originalTransition() === transitionA; // true\n * trans.originalTransition().to().name === 'A'; // true\n * });\n * ```\n *\n * @returns The original Transition that started a redirect chain\n */\n originalTransition(): Transition {\n const rf = this.redirectedFrom();\n return (rf && rf.originalTransition()) || this;\n }\n\n /**\n * Get the transition options\n *\n * @returns the options for this Transition.\n */\n options(): TransitionOptions {\n return this._options;\n }\n\n /**\n * Gets the states being entered.\n *\n * @returns an array of states that will be entered during this transition.\n */\n entering(): StateDeclaration[] {\n return map(this._treeChanges.entering, prop('state')).map(stateSelf);\n }\n\n /**\n * Gets the states being exited.\n *\n * @returns an array of states that will be exited during this transition.\n */\n exiting(): StateDeclaration[] {\n return map(this._treeChanges.exiting, prop('state')).map(stateSelf).reverse();\n }\n\n /**\n * Gets the states being retained.\n *\n * @returns an array of states that are already entered from a previous Transition, that will not be\n * exited during this Transition\n */\n retained(): StateDeclaration[] {\n return map(this._treeChanges.retained, prop('state')).map(stateSelf);\n }\n\n /**\n * Get the [[ViewConfig]]s associated with this Transition\n *\n * Each state can define one or more views (template/controller), which are encapsulated as `ViewConfig` objects.\n * This method fetches the `ViewConfigs` for a given path in the Transition (e.g., \"to\" or \"entering\").\n *\n * @param pathname the name of the path to fetch views for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n * @param state If provided, only returns the `ViewConfig`s for a single state in the path\n *\n * @returns a list of ViewConfig objects for the given path.\n */\n views(pathname = 'entering', state?: StateObject): ViewConfig[] {\n let path = this._treeChanges[pathname];\n path = !state ? path : path.filter(propEq('state', state));\n return path.map(prop('views')).filter(identity).reduce(unnestR, []);\n }\n\n /**\n * Return the transition's tree changes\n *\n * A transition goes from one state/parameters to another state/parameters.\n * During a transition, states are entered and/or exited.\n *\n * This function returns various branches (paths) which represent the changes to the\n * active state tree that are caused by the transition.\n *\n * @param pathname The name of the tree changes path to get:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n */\n treeChanges(pathname: string): PathNode[];\n treeChanges(): TreeChanges;\n treeChanges(pathname?: string) {\n return pathname ? this._treeChanges[pathname] : this._treeChanges;\n }\n\n /**\n * Creates a new transition that is a redirection of the current one.\n *\n * This transition can be returned from a [[TransitionService]] hook to\n * redirect a transition to a new state and/or set of parameters.\n *\n * @internalapi\n *\n * @returns Returns a new [[Transition]] instance.\n */\n redirect(targetState: TargetState): Transition {\n let redirects = 1, trans: Transition = this;\n // tslint:disable-next-line:no-conditional-assignment\n while ((trans = trans.redirectedFrom()) != null) {\n if (++redirects > 20) throw new Error(`Too many consecutive Transition redirects (20+)`);\n }\n\n const redirectOpts: TransitionOptions = { redirectedFrom: this, source: 'redirect' };\n // If the original transition was caused by URL sync, then use { location: 'replace' }\n // on the new transition (unless the target state explicitly specifies location: false).\n // This causes the original url to be replaced with the url for the redirect target\n // so the original url disappears from the browser history.\n if (this.options().source === 'url' && targetState.options().location !== false) {\n redirectOpts.location = 'replace';\n }\n\n const newOptions = extend({}, this.options(), targetState.options(), redirectOpts);\n targetState = targetState.withOptions(newOptions, true);\n\n const newTransition = this.router.transitionService.create(this._treeChanges.from, targetState);\n const originalEnteringNodes = this._treeChanges.entering;\n const redirectEnteringNodes = newTransition._treeChanges.entering;\n\n // --- Re-use resolve data from original transition ---\n // When redirecting from a parent state to a child state where the parent parameter values haven't changed\n // (because of the redirect), the resolves fetched by the original transition are still valid in the\n // redirected transition.\n //\n // This allows you to define a redirect on a parent state which depends on an async resolve value.\n // You can wait for the resolve, then redirect to a child state based on the result.\n // The redirected transition does not have to re-fetch the resolve.\n // ---------------------------------------------------------\n\n const nodeIsReloading = (reloadState: StateObject) => (node: PathNode) => {\n return reloadState && node.state.includes[reloadState.name];\n };\n\n // Find any \"entering\" nodes in the redirect path that match the original path and aren't being reloaded\n const matchingEnteringNodes: PathNode[] = PathUtils.matching(redirectEnteringNodes, originalEnteringNodes, PathUtils.nonDynamicParams)\n .filter(not(nodeIsReloading(targetState.options().reloadState)));\n\n // Use the existing (possibly pre-resolved) resolvables for the matching entering nodes.\n matchingEnteringNodes.forEach((node, idx) => {\n node.resolvables = originalEnteringNodes[idx].resolvables;\n });\n\n return newTransition;\n }\n\n /** @hidden If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */\n private _changedParams(): Param[] {\n const tc = this._treeChanges;\n\n /** Return undefined if it's not a \"dynamic\" transition, for the following reasons */\n // If user explicitly wants a reload\n if (this._options.reload) return undefined;\n // If any states are exiting or entering\n if (tc.exiting.length || tc.entering.length) return undefined;\n // If to/from path lengths differ\n if (tc.to.length !== tc.from.length) return undefined;\n // If the to/from paths are different\n const pathsDiffer: boolean = arrayTuples(tc.to, tc.from)\n .map(tuple => tuple[0].state !== tuple[1].state)\n .reduce(anyTrueR, false);\n if (pathsDiffer) return undefined;\n\n // Find any parameter values that differ\n const nodeSchemas: Param[][] = tc.to.map((node: PathNode) => node.paramSchema);\n const [toValues, fromValues] = [tc.to, tc.from].map(path => path.map(x => x.paramValues));\n const tuples = arrayTuples(nodeSchemas, toValues, fromValues);\n\n return tuples.map(([schema, toVals, fromVals]) => Param.changed(schema, toVals, fromVals)).reduce(unnestR, []);\n }\n\n /**\n * Returns true if the transition is dynamic.\n *\n * A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.\n *\n * @returns true if the Transition is dynamic\n */\n dynamic(): boolean {\n const changes = this._changedParams();\n return !changes ? false : changes.map(x => x.dynamic).reduce(anyTrueR, false);\n }\n\n /**\n * Returns true if the transition is ignored.\n *\n * A transition is ignored if no states are entered nor exited, and no parameter values have changed.\n *\n * @returns true if the Transition is ignored.\n */\n ignored(): boolean {\n return !!this._ignoredReason();\n }\n\n /** @hidden */\n _ignoredReason(): 'SameAsCurrent'|'SameAsPending'|undefined {\n const pending = this.router.globals.transition;\n const reloadState = this._options.reloadState;\n\n const same = (pathA, pathB) => {\n if (pathA.length !== pathB.length) return false;\n const matching = PathUtils.matching(pathA, pathB);\n return pathA.length === matching.filter(node => !reloadState || !node.state.includes[reloadState.name]).length;\n };\n\n const newTC = this.treeChanges();\n const pendTC = pending && pending.treeChanges();\n\n if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) return 'SameAsPending';\n if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) return 'SameAsCurrent';\n }\n\n /**\n * Runs the transition\n *\n * This method is generally called from the [[StateService.transitionTo]]\n *\n * @internalapi\n *\n * @returns a promise for a successful transition.\n */\n run(): Promise {\n const runAllHooks = TransitionHook.runAllHooks;\n\n // Gets transition hooks array for the given phase\n const getHooksFor = (phase: TransitionHookPhase) =>\n this._hookBuilder.buildHooksForPhase(phase);\n\n // When the chain is complete, then resolve or reject the deferred\n const transitionSuccess = () => {\n trace.traceSuccess(this.$to(), this);\n this.success = true;\n this._deferred.resolve(this.to());\n runAllHooks(getHooksFor(TransitionHookPhase.SUCCESS));\n };\n\n const transitionError = (reason: any) => {\n trace.traceError(reason, this);\n this.success = false;\n this._deferred.reject(reason);\n this._error = reason;\n runAllHooks(getHooksFor(TransitionHookPhase.ERROR));\n };\n\n const runTransition = () => {\n // Wait to build the RUN hook chain until the BEFORE hooks are done\n // This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object.\n const allRunHooks = getHooksFor(TransitionHookPhase.RUN);\n const done = () => services.$q.when(undefined);\n return TransitionHook.invokeHooks(allRunHooks, done);\n };\n\n const startTransition = () => {\n const globals = this.router.globals;\n\n globals.lastStartedTransitionId = this.$id;\n globals.transition = this;\n globals.transitionHistory.enqueue(this);\n\n trace.traceTransitionStart(this);\n\n return services.$q.when(undefined);\n };\n\n const allBeforeHooks = getHooksFor(TransitionHookPhase.BEFORE);\n TransitionHook.invokeHooks(allBeforeHooks, startTransition)\n .then(runTransition)\n .then(transitionSuccess, transitionError);\n\n return this.promise;\n }\n\n /** Checks if this transition is currently active/running. */\n isActive = () =>\n this.router.globals.transition === this;\n\n /**\n * Checks if the Transition is valid\n *\n * @returns true if the Transition is valid\n */\n valid() {\n return !this.error() || this.success !== undefined;\n }\n\n /**\n * Aborts this transition\n *\n * Imperative API to abort a Transition.\n * This only applies to Transitions that are not yet complete.\n */\n abort() {\n // Do not set flag if the transition is already complete\n if (isUndefined(this.success)) {\n this._aborted = true;\n }\n }\n\n /**\n * The Transition error reason.\n *\n * If the transition is invalid (and could not be run), returns the reason the transition is invalid.\n * If the transition was valid and ran, but was not successful, returns the reason the transition failed.\n *\n * @returns an error message explaining why the transition is invalid, or the reason the transition failed.\n */\n error() {\n const state: StateObject = this.$to();\n\n if (state.self.abstract)\n return `Cannot transition to abstract state '${state.name}'`;\n\n const paramDefs = state.parameters(), values = this.params();\n const invalidParams = paramDefs.filter(param => !param.validates(values[param.id]));\n if (invalidParams.length) {\n return `Param values not valid for state '${state.name}'. Invalid params: [ ${invalidParams.map(param => param.id).join(', ')} ]`;\n }\n\n if (this.success === false)\n return this._error;\n }\n\n /**\n * A string representation of the Transition\n *\n * @returns A string representation of the Transition\n */\n toString () {\n const fromStateOrName = this.from();\n const toStateOrName = this.to();\n\n const avoidEmptyHash = (params: RawParams) =>\n (params['#'] !== null && params['#'] !== undefined) ? params : omit(params, ['#']);\n\n // (X) means the to state is invalid.\n const id = this.$id,\n from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName,\n fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))),\n toValid = this.valid() ? '' : '(X) ',\n to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName,\n toParams = stringify(avoidEmptyHash(this.params()));\n\n return `Transition#${id}( '${from}'${fromParams} -> ${toValid}'${to}'${toParams} )`;\n }\n}\n", - "/**\n * Functions that manipulate strings\n *\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_strings\n */ /** */\n\nimport { isString, isArray, isDefined, isNull, isPromise, isInjectable, isObject } from './predicates';\nimport { Rejection } from '../transition/rejectFactory';\nimport { IInjectable, identity, Obj, tail, pushR } from './common';\nimport { pattern, is, not, val, invoke } from './hof';\nimport { Transition } from '../transition/transition';\nimport { Resolvable } from '../resolve/resolvable';\n\n/**\n * Returns a string shortened to a maximum length\n *\n * If the string is already less than the `max` length, return the string.\n * Else return the string, shortened to `max - 3` and append three dots (\"...\").\n *\n * @param max the maximum length of the string to return\n * @param str the input string\n */\nexport function maxLength(max: number, str: string) {\n if (str.length <= max) return str;\n return str.substr(0, max - 3) + '...';\n}\n\n/**\n * Returns a string, with spaces added to the end, up to a desired str length\n *\n * If the string is already longer than the desired length, return the string.\n * Else returns the string, with extra spaces on the end, such that it reaches `length` characters.\n *\n * @param length the desired length of the string to return\n * @param str the input string\n */\nexport function padString(length: number, str: string) {\n while (str.length < length) str += ' ';\n return str;\n}\n\nexport function kebobString(camelCase: string) {\n return camelCase\n .replace(/^([A-Z])/, $1 => $1.toLowerCase()) // replace first char\n .replace(/([A-Z])/g, $1 => '-' + $1.toLowerCase()); // replace rest\n}\n\nfunction _toJson(obj: Obj) {\n return JSON.stringify(obj);\n}\n\nfunction _fromJson(json: string) {\n return isString(json) ? JSON.parse(json) : json;\n}\n\n\nfunction promiseToString(p: Promise) {\n return `Promise(${JSON.stringify(p)})`;\n}\n\nexport function functionToString(fn: Function) {\n const fnStr = fnToString(fn);\n const namedFunctionMatch = fnStr.match(/^(function [^ ]+\\([^)]*\\))/);\n const toStr = namedFunctionMatch ? namedFunctionMatch[1] : fnStr;\n\n const fnName = fn['name'] || '';\n if (fnName && toStr.match(/function \\(/)) {\n return 'function ' + fnName + toStr.substr(9);\n }\n return toStr;\n}\n\nexport function fnToString(fn: IInjectable) {\n const _fn = isArray(fn) ? fn.slice(-1)[0] : fn;\n return _fn && _fn.toString() || 'undefined';\n}\n\nlet stringifyPatternFn: (val: any) => string = null;\nconst stringifyPattern = function(value: any) {\n const isRejection = Rejection.isRejectionPromise;\n\n stringifyPatternFn = stringifyPatternFn || pattern([\n [not(isDefined), val('undefined')],\n [isNull, val('null')],\n [isPromise, val('[Promise]')],\n [isRejection, (x: any) => x._transitionRejection.toString()],\n [is(Rejection), invoke('toString')],\n [is(Transition), invoke('toString')],\n [is(Resolvable), invoke('toString')],\n [isInjectable, functionToString],\n [val(true), identity],\n ]);\n\n return stringifyPatternFn(value);\n};\n\nexport function stringify(o: any) {\n const seen: any[] = [];\n\n function format(value: any) {\n if (isObject(value)) {\n if (seen.indexOf(value) !== -1) return '[circular ref]';\n seen.push(value);\n }\n return stringifyPattern(value);\n }\n\n return JSON.stringify(o, (key, value) => format(value)).replace(/\\\\\"/g, '\"');\n}\n\n/** Returns a function that splits a string on a character or substring */\nexport const beforeAfterSubstr = (char: string) => (str: string): string[] => {\n if (!str) return ['', ''];\n const idx = str.indexOf(char);\n if (idx === -1) return [str, ''];\n return [str.substr(0, idx), str.substr(idx + 1)];\n};\n\nexport const hostRegex = new RegExp('^(?:[a-z]+:)?//[^/]+/');\nexport const stripLastPathElement = (str: string) => str.replace(/\\/[^/]*$/, '');\nexport const splitHash = beforeAfterSubstr('#');\nexport const splitQuery = beforeAfterSubstr('?');\nexport const splitEqual = beforeAfterSubstr('=');\nexport const trimHashVal = (str: string) => str ? str.replace(/^#/, '') : '';\n\n/**\n * Splits on a delimiter, but returns the delimiters in the array\n *\n * #### Example:\n * ```js\n * var splitOnSlashes = splitOnDelim('/');\n * splitOnSlashes(\"/foo\"); // [\"/\", \"foo\"]\n * splitOnSlashes(\"/foo/\"); // [\"/\", \"foo\", \"/\"]\n * ```\n */\nexport function splitOnDelim(delim: string) {\n const re = new RegExp('(' + delim + ')', 'g');\n return (str: string) =>\n str.split(re).filter(identity);\n}\n\n\n/**\n * Reduce fn that joins neighboring strings\n *\n * Given an array of strings, returns a new array\n * where all neighboring strings have been joined.\n *\n * #### Example:\n * ```js\n * let arr = [\"foo\", \"bar\", 1, \"baz\", \"\", \"qux\" ];\n * arr.reduce(joinNeighborsR, []) // [\"foobar\", 1, \"bazqux\" ]\n * ```\n */\nexport function joinNeighborsR(acc: any[], x: any) {\n if (isString(tail(acc)) && isString(x))\n return acc.slice(0, -1).concat(tail(acc) + x);\n return pushR(acc, x);\n}\n\n", + "/**\n * Random utility functions used in the UI-Router code\n *\n * These functions are exported, but are subject to change without notice.\n *\n * @preferred\n * @module common\n */\n/** for typedoc */\nimport { isFunction, isString, isArray, isRegExp, isDate } from './predicates';\nimport { all, any, prop, curry, not } from './hof';\nimport { services } from './coreservices';\nimport { StateObject } from '../state/stateObject';\n\ndeclare const global;\nexport const root: any =\n (typeof self === 'object' && self.self === self && self) ||\n (typeof global === 'object' && global.global === global && global) ||\n this;\nconst angular = root.angular || {};\n\nexport const fromJson = angular.fromJson || JSON.parse.bind(JSON);\nexport const toJson = angular.toJson || JSON.stringify.bind(JSON);\nexport const forEach = angular.forEach || _forEach;\nexport const extend = Object.assign || _extend;\nexport const equals = angular.equals || _equals;\nexport function identity(x: any) {\n return x;\n}\nexport function noop(): any {}\n\nexport type Mapper = (x: X, key?: string | number) => T;\nexport interface TypedMap {\n [key: string]: T;\n}\nexport type Predicate = (x?: X) => boolean;\n/**\n * An ng1-style injectable\n *\n * This could be a (non-minified) function such as:\n * ```js\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an explicitly annotated function (minify safe)\n * ```js\n * injectableFunction.$inject = [ 'SomeDependency' ];\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an array style annotated function (minify safe)\n * ```js\n * ['SomeDependency', function injectableFunction(SomeDependency) {\n *\n * }];\n * ```\n *\n * @publicapi\n */\nexport type IInjectable = Function | any[];\n\nexport interface Obj extends Object {\n [key: string]: any;\n}\n\n/**\n * Builds proxy functions on the `to` object which pass through to the `from` object.\n *\n * For each key in `fnNames`, creates a proxy function on the `to` object.\n * The proxy function calls the real function on the `from` object.\n *\n *\n * #### Example:\n * This example creates an new class instance whose functions are prebound to the new'd object.\n * ```js\n * class Foo {\n * constructor(data) {\n * // Binds all functions from Foo.prototype to 'this',\n * // then copies them to 'this'\n * bindFunctions(Foo.prototype, this, this);\n * this.data = data;\n * }\n *\n * log() {\n * console.log(this.data);\n * }\n * }\n *\n * let myFoo = new Foo([1,2,3]);\n * var logit = myFoo.log;\n * logit(); // logs [1, 2, 3] from the myFoo 'this' instance\n * ```\n *\n * #### Example:\n * This example creates a bound version of a service function, and copies it to another object\n * ```\n *\n * var SomeService = {\n * this.data = [3, 4, 5];\n * this.log = function() {\n * console.log(this.data);\n * }\n * }\n *\n * // Constructor fn\n * function OtherThing() {\n * // Binds all functions from SomeService to SomeService,\n * // then copies them to 'this'\n * bindFunctions(SomeService, this, SomeService);\n * }\n *\n * let myOtherThing = new OtherThing();\n * myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'\n * ```\n *\n * @param source A function that returns the source object which contains the original functions to be bound\n * @param target A function that returns the target object which will receive the bound functions\n * @param bind A function that returns the object which the functions will be bound to\n * @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object)\n * @param latebind If true, the binding of the function is delayed until the first time it's invoked\n */\nexport function createProxyFunctions(\n source: Function,\n target: Obj,\n bind: Function,\n fnNames?: string[],\n latebind = false,\n): Obj {\n const bindFunction = fnName => source()[fnName].bind(bind());\n\n const makeLateRebindFn = fnName =>\n function lateRebindFunction() {\n target[fnName] = bindFunction(fnName);\n return target[fnName].apply(null, arguments);\n };\n\n fnNames = fnNames || Object.keys(source());\n\n return fnNames.reduce((acc, name) => {\n acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name);\n return acc;\n }, target);\n}\n\n/**\n * prototypal inheritance helper.\n * Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it\n */\nexport const inherit = (parent: Obj, extra?: Obj) => extend(Object.create(parent), extra);\n\n/** Given an array, returns true if the object is found in the array, (using indexOf) */\nexport const inArray: typeof _inArray = curry(_inArray) as any;\nexport function _inArray(array: any[], obj: any): boolean;\nexport function _inArray(array: any[]): (obj: any) => boolean;\nexport function _inArray(array, obj?): any {\n return array.indexOf(obj) !== -1;\n}\n\n/**\n * Given an array, and an item, if the item is found in the array, it removes it (in-place).\n * The same array is returned\n */\nexport const removeFrom: typeof _removeFrom = curry(_removeFrom) as any;\nexport function _removeFrom(array: T[], obj: T): T[];\nexport function _removeFrom(array: T[]): (obj: T) => T[];\nexport function _removeFrom(array, obj?) {\n const idx = array.indexOf(obj);\n if (idx >= 0) array.splice(idx, 1);\n return array;\n}\n\n/** pushes a values to an array and returns the value */\nexport const pushTo: typeof _pushTo = curry(_pushTo) as any;\nexport function _pushTo(arr: T[], val: T): T;\nexport function _pushTo(arr: T[]): (val: T) => T;\nexport function _pushTo(arr, val?): any {\n return arr.push(val), val;\n}\n\n/** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */\nexport const deregAll = (functions: Function[]) =>\n functions.slice().forEach(fn => {\n typeof fn === 'function' && fn();\n removeFrom(functions, fn);\n });\n/**\n * Applies a set of defaults to an options object. The options object is filtered\n * to only those properties of the objects in the defaultsList.\n * Earlier objects in the defaultsList take precedence when applying defaults.\n */\nexport function defaults(opts, ...defaultsList: Obj[]) {\n const _defaultsList = defaultsList.concat({}).reverse();\n const defaultVals = extend.apply(null, _defaultsList);\n return extend({}, defaultVals, pick(opts || {}, Object.keys(defaultVals)));\n}\n\n/** Reduce function that merges each element of the list into a single object, using extend */\nexport const mergeR = (memo: Obj, item: Obj) => extend(memo, item);\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nexport function ancestors(first: StateObject, second: StateObject) {\n const path: StateObject[] = [];\n\n // tslint:disable-next-line:forin\n for (const n in first.path) {\n if (first.path[n] !== second.path[n]) break;\n path.push(first.path[n]);\n }\n return path;\n}\n\n/**\n * Return a copy of the object only containing the whitelisted properties.\n *\n * #### Example:\n * ```\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the whitelisted property names\n */\nexport function pick(obj: Obj, propNames: string[]): Obj {\n const objCopy = {};\n for (const _prop in obj) {\n if (propNames.indexOf(_prop) !== -1) {\n objCopy[_prop] = obj[_prop];\n }\n }\n return objCopy;\n}\n\n/**\n * Return a copy of the object omitting the blacklisted properties.\n *\n * @example\n * ```\n *\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = omit(foo, ['a', 'b']); // { c: 3 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the blacklisted property names\n */\nexport function omit(obj: Obj, propNames: string[]): Obj {\n return Object.keys(obj)\n .filter(not(inArray(propNames)))\n .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});\n}\n\n/** Given an array of objects, maps each element to a named property of the element. */\nexport function pluck(collection: Obj[], propName: string): T[];\n/** Given an object, maps each property of the object to a named property of the property. */\nexport function pluck(collection: { [key: string]: any }, propName: string): { [key: string]: any };\n/**\n * Maps an array, or object to a property (by name)\n */\nexport function pluck(collection: any, propName: string): any {\n return map(collection, >prop(propName));\n}\n\n/** Given an array of objects, returns a new array containing only the elements which passed the callback predicate */\nexport function filter(collection: T[], callback: (t: T, key?: number) => boolean): T[];\n/** Given an object, returns a new object with only those properties that passed the callback predicate */\nexport function filter(collection: TypedMap, callback: (t: T, key?: string) => boolean): TypedMap;\n/** Filters an Array or an Object's properties based on a predicate */\nexport function filter(collection: any, callback: Function): T {\n const arr = isArray(collection),\n result: any = arr ? [] : {};\n const accept = arr ? x => result.push(x) : (x, key) => (result[key] = x);\n forEach(collection, function(item, i) {\n if (callback(item, i)) accept(item, i);\n });\n return result;\n}\n\n/** Given an object, return the first property of that object which passed the callback predicate */\nexport function find(collection: TypedMap, callback: Predicate): T;\n/** Given an array of objects, returns the first object which passed the callback predicate */\nexport function find(collection: T[], callback: Predicate): T;\n/** Finds an object from an array, or a property of an object, that matches a predicate */\nexport function find(collection: any, callback: any) {\n let result;\n\n forEach(collection, function(item, i) {\n if (result) return;\n if (callback(item, i)) result = item;\n });\n\n return result;\n}\n\n/** Given an object, returns a new object, where each property is transformed by the callback function */\nexport let mapObj: (\n collection: { [key: string]: T },\n callback: Mapper,\n target?: typeof collection,\n) => { [key: string]: U } = map;\n/** Given an array, returns a new array, where each element is transformed by the callback function */\nexport function map(collection: T[], callback: Mapper, target?: typeof collection): U[];\nexport function map(\n collection: { [key: string]: T },\n callback: Mapper,\n target?: typeof collection,\n): { [key: string]: U };\n/** Maps an array or object properties using a callback function */\nexport function map(collection: any, callback: any, target: typeof collection): any {\n target = target || (isArray(collection) ? [] : {});\n forEach(collection, (item, i) => (target[i] = callback(item, i)));\n return target;\n}\n\n/**\n * Given an object, return its enumerable property values\n *\n * @example\n * ```\n *\n * let foo = { a: 1, b: 2, c: 3 }\n * let vals = values(foo); // [ 1, 2, 3 ]\n * ```\n */\nexport const values: ((obj: TypedMap) => T[]) = (obj: Obj) => Object.keys(obj).map(key => obj[key]);\n\n/**\n * Reduce function that returns true if all of the values are truthy.\n *\n * @example\n * ```\n *\n * let vals = [ 1, true, {}, \"hello world\"];\n * vals.reduce(allTrueR, true); // true\n *\n * vals.push(0);\n * vals.reduce(allTrueR, true); // false\n * ```\n */\nexport const allTrueR = (memo: boolean, elem: any) => memo && elem;\n\n/**\n * Reduce function that returns true if any of the values are truthy.\n *\n * * @example\n * ```\n *\n * let vals = [ 0, null, undefined ];\n * vals.reduce(anyTrueR, true); // false\n *\n * vals.push(\"hello world\");\n * vals.reduce(anyTrueR, true); // true\n * ```\n */\nexport const anyTrueR = (memo: boolean, elem: any) => memo || elem;\n\n/**\n * Reduce function which un-nests a single level of arrays\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnestR = (memo: any[], elem: any[]) => memo.concat(elem);\n\n/**\n * Reduce function which recursively un-nests all arrays\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flattenR = (memo: any[], elem: any) =>\n isArray(elem) ? memo.concat(elem.reduce(flattenR, [])) : pushR(memo, elem);\n\n/**\n * Reduce function that pushes an object to an array, then returns the array.\n * Mostly just for [[flattenR]] and [[uniqR]]\n */\nexport function pushR(arr: any[], obj: any) {\n arr.push(obj);\n return arr;\n}\n\n/** Reduce function that filters out duplicates */\nexport const uniqR = (acc: T[], token: T): T[] => (inArray(acc, token) ? acc : pushR(acc, token));\n\n/**\n * Return a new array with a single level of arrays unnested.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * unnest(input) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnest = (arr: any[]) => arr.reduce(unnestR, []);\n/**\n * Return a completely flattened version of an array.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * flatten(input) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flatten = (arr: any[]) => arr.reduce(flattenR, []);\n\n/**\n * Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.\n * @example\n * ```\n *\n * let isNumber = (obj) => typeof(obj) === 'number';\n * let allNumbers = [ 1, 2, 3, 4, 5 ];\n * allNumbers.filter(assertPredicate(isNumber)); //OK\n *\n * let oneString = [ 1, 2, 3, 4, \"5\" ];\n * oneString.filter(assertPredicate(isNumber, \"Not all numbers\")); // throws Error(\"\"Not all numbers\"\");\n * ```\n */\nexport const assertPredicate: (predicate: Predicate, errMsg: string | Function) => Predicate = assertFn;\n/**\n * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.\n * @example\n * ```\n *\n * var data = { foo: 1, bar: 2 };\n *\n * let keys = [ 'foo', 'bar' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // values is [1, 2]\n *\n * let keys = [ 'foo', 'bar', 'baz' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // throws Error(\"Key not found\")\n * ```\n */\nexport const assertMap: (mapFn: (t: T) => U, errMsg: string | Function) => (t: T) => U = assertFn;\nexport function assertFn(predicateOrMap: Function, errMsg: string | Function = 'assert failure'): any {\n return obj => {\n const result = predicateOrMap(obj);\n if (!result) {\n throw new Error(isFunction(errMsg) ? (errMsg)(obj) : errMsg);\n }\n return result;\n };\n}\n\n/**\n * Like _.pairs: Given an object, returns an array of key/value pairs\n *\n * @example\n * ```\n *\n * pairs({ foo: \"FOO\", bar: \"BAR }) // [ [ \"foo\", \"FOO\" ], [ \"bar\": \"BAR\" ] ]\n * ```\n */\nexport const pairs = (obj: Obj) => Object.keys(obj).map(key => [key, obj[key]]);\n\n/**\n * Given two or more parallel arrays, returns an array of tuples where\n * each tuple is composed of [ a[i], b[i], ... z[i] ]\n *\n * @example\n * ```\n *\n * let foo = [ 0, 2, 4, 6 ];\n * let bar = [ 1, 3, 5, 7 ];\n * let baz = [ 10, 30, 50, 70 ];\n * arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]\n * arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]\n * ```\n */\nexport function arrayTuples(...args: any[]): any[] {\n if (args.length === 0) return [];\n const maxArrayLen = args.reduce((min, arr) => Math.min(arr.length, min), 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER\n const result = [];\n\n for (let i = 0; i < maxArrayLen; i++) {\n // This is a hot function\n // Unroll when there are 1-4 arguments\n switch (args.length) {\n case 1:\n result.push([args[0][i]]);\n break;\n case 2:\n result.push([args[0][i], args[1][i]]);\n break;\n case 3:\n result.push([args[0][i], args[1][i], args[2][i]]);\n break;\n case 4:\n result.push([args[0][i], args[1][i], args[2][i], args[3][i]]);\n break;\n default:\n result.push(args.map(array => array[i]));\n break;\n }\n }\n\n return result;\n}\n\n/**\n * Reduce function which builds an object from an array of [key, value] pairs.\n *\n * Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.\n *\n * Each keyValueTuple should be an array with values [ key: string, value: any ]\n *\n * @example\n * ```\n *\n * var pairs = [ [\"fookey\", \"fooval\"], [\"barkey\", \"barval\"] ]\n *\n * var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n *\n * // Or, more simply:\n * var pairsToObj = pairs.reduce(applyPairs, {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n * ```\n */\nexport function applyPairs(memo: TypedMap, keyValTuple: any[]) {\n let key: string, value: any;\n if (isArray(keyValTuple)) [key, value] = keyValTuple;\n if (!isString(key)) throw new Error('invalid parameters to applyPairs');\n memo[key] = value;\n return memo;\n}\n\n/** Get the last element of an array */\nexport function tail(arr: T[]): T {\n return (arr.length && arr[arr.length - 1]) || undefined;\n}\n\n/**\n * shallow copy from src to dest\n */\nexport function copy(src: Obj, dest?: Obj) {\n if (dest) Object.keys(dest).forEach(key => delete dest[key]);\n if (!dest) dest = {};\n return extend(dest, src);\n}\n\n/** Naive forEach implementation works with Objects or Arrays */\nfunction _forEach(obj: any[] | any, cb: (el, idx?) => void, _this: Obj) {\n if (isArray(obj)) return obj.forEach(cb, _this);\n Object.keys(obj).forEach(key => cb(obj[key], key));\n}\n\n/** Like Object.assign() */\nexport function _extend(toObj: Obj, ...fromObjs: Obj[]): any;\nexport function _extend(toObj: Obj): any {\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n if (!obj) continue;\n const keys = Object.keys(obj);\n\n for (let j = 0; j < keys.length; j++) {\n toObj[keys[j]] = obj[keys[j]];\n }\n }\n\n return toObj;\n}\n\nfunction _equals(o1: any, o2: any): boolean {\n if (o1 === o2) return true;\n if (o1 === null || o2 === null) return false;\n if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n const t1 = typeof o1,\n t2 = typeof o2;\n if (t1 !== t2 || t1 !== 'object') return false;\n\n const tup = [o1, o2];\n if (all(isArray)(tup)) return _arraysEq(o1, o2);\n if (all(isDate)(tup)) return o1.getTime() === o2.getTime();\n if (all(isRegExp)(tup)) return o1.toString() === o2.toString();\n if (all(isFunction)(tup)) return true; // meh\n\n const predicates = [isFunction, isArray, isDate, isRegExp];\n if (predicates.map(any).reduce((b, fn) => b || !!fn(tup), false)) return false;\n\n const keys: { [i: string]: boolean } = {};\n // tslint:disable-next-line:forin\n for (const key in o1) {\n if (!_equals(o1[key], o2[key])) return false;\n keys[key] = true;\n }\n for (const key in o2) {\n if (!keys[key]) return false;\n }\n\n return true;\n}\n\nfunction _arraysEq(a1: any[], a2: any[]) {\n if (a1.length !== a2.length) return false;\n return arrayTuples(a1, a2).reduce((b, t) => b && _equals(t[0], t[1]), true);\n}\n\n// issue #2676\nexport const silenceUncaughtInPromise = (promise: Promise) => promise.catch(e => 0) && promise;\nexport const silentRejection = (error: any) => silenceUncaughtInPromise(services.$q.reject(error));\n", + "/** @module common */\nimport { pushTo } from './common';\n\nexport class Queue {\n private _evictListeners: ((item: T) => void)[] = [];\n public onEvict = pushTo(this._evictListeners);\n\n constructor(private _items: T[] = [], private _limit: number = null) {}\n\n enqueue(item: T) {\n const items = this._items;\n items.push(item);\n if (this._limit && items.length > this._limit) this.evict();\n return item;\n }\n\n evict(): T {\n const item: T = this._items.shift();\n this._evictListeners.forEach(fn => fn(item));\n return item;\n }\n\n dequeue(): T {\n if (this.size()) return this._items.splice(0, 1)[0];\n }\n\n clear(): Array {\n const current = this._items;\n this._items = [];\n return current;\n }\n\n size(): number {\n return this._items.length;\n }\n\n remove(item: T) {\n const idx = this._items.indexOf(item);\n return idx > -1 && this._items.splice(idx, 1)[0];\n }\n\n peekTail(): T {\n return this._items[this._items.length - 1];\n }\n\n peekHead(): T {\n if (this.size()) return this._items[0];\n }\n}\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n'use strict';\nimport { extend, silentRejection } from '../common/common';\nimport { stringify } from '../common/strings';\nimport { is } from '../common/hof';\n\nenum RejectType {\n /**\n * A new transition superseded this one.\n *\n * While this transition was running, a new transition started.\n * This transition is cancelled because it was superseded by new transition.\n */\n SUPERSEDED = 2,\n\n /**\n * The transition was aborted\n *\n * The transition was aborted by a hook which returned `false`\n */\n ABORTED = 3,\n\n /**\n * The transition was invalid\n *\n * The transition was never started because it was invalid\n */\n INVALID = 4,\n\n /**\n * The transition was ignored\n *\n * The transition was ignored because it would have no effect.\n *\n * Either:\n *\n * - The transition is targeting the current state and parameter values\n * - The transition is targeting the same state and parameter values as the currently running transition.\n */\n IGNORED = 5,\n\n /**\n * The transition errored.\n *\n * This generally means a hook threw an error or returned a rejected promise\n */\n ERROR = 6,\n}\n\nexport { RejectType };\n\n/** @hidden */\nlet id = 0;\n\nexport class Rejection {\n /** @hidden */\n $id = id++;\n /**\n * The type of the rejection.\n *\n * This value is an number representing the type of transition rejection.\n * If using Typescript, this is a Typescript enum.\n *\n * - [[RejectType.SUPERSEDED]] (`2`)\n * - [[RejectType.ABORTED]] (`3`)\n * - [[RejectType.INVALID]] (`4`)\n * - [[RejectType.IGNORED]] (`5`)\n * - [[RejectType.ERROR]] (`6`)\n *\n */\n type: RejectType;\n\n /**\n * A message describing the rejection\n */\n message: string;\n\n /**\n * A detail object\n *\n * This value varies based on the mechanism for rejecting the transition.\n * For example, if an error was thrown from a hook, the `detail` will be the `Error` object.\n * If a hook returned a rejected promise, the `detail` will be the rejected value.\n */\n detail: any;\n\n /**\n * Indicates if the transition was redirected.\n *\n * When a transition is redirected, the rejection [[type]] will be [[RejectType.SUPERSEDED]] and this flag will be true.\n */\n redirected: boolean;\n\n /** Returns true if the obj is a rejected promise created from the `asPromise` factory */\n static isRejectionPromise(obj: any): boolean {\n return obj && typeof obj.then === 'function' && is(Rejection)(obj._transitionRejection);\n }\n\n /** Returns a Rejection due to transition superseded */\n static superseded(detail?: any, options?: any): Rejection {\n const message = 'The transition has been superseded by a different transition';\n const rejection = new Rejection(RejectType.SUPERSEDED, message, detail);\n if (options && options.redirected) {\n rejection.redirected = true;\n }\n return rejection;\n }\n\n /** Returns a Rejection due to redirected transition */\n static redirected(detail?: any): Rejection {\n return Rejection.superseded(detail, { redirected: true });\n }\n\n /** Returns a Rejection due to invalid transition */\n static invalid(detail?: any): Rejection {\n const message = 'This transition is invalid';\n return new Rejection(RejectType.INVALID, message, detail);\n }\n\n /** Returns a Rejection due to ignored transition */\n static ignored(detail?: any): Rejection {\n const message = 'The transition was ignored';\n return new Rejection(RejectType.IGNORED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static aborted(detail?: any): Rejection {\n const message = 'The transition has been aborted';\n return new Rejection(RejectType.ABORTED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static errored(detail?: any): Rejection {\n const message = 'The transition errored';\n return new Rejection(RejectType.ERROR, message, detail);\n }\n\n /**\n * Returns a Rejection\n *\n * Normalizes a value as a Rejection.\n * If the value is already a Rejection, returns it.\n * Otherwise, wraps and returns the value as a Rejection (Rejection type: ERROR).\n *\n * @returns `detail` if it is already a `Rejection`, else returns an ERROR Rejection.\n */\n static normalize(detail?: Rejection | Error | any): Rejection {\n return is(Rejection)(detail) ? detail : Rejection.errored(detail);\n }\n\n constructor(type: number, message?: string, detail?: any) {\n this.type = type;\n this.message = message;\n this.detail = detail;\n }\n\n toString() {\n const detailString = (d: any) => (d && d.toString !== Object.prototype.toString ? d.toString() : stringify(d));\n const detail = detailString(this.detail);\n const { $id, type, message } = this;\n return `Transition Rejection($id: ${$id} type: ${type}, message: ${message}, detail: ${detail})`;\n }\n\n toPromise(): Promise {\n return extend(silentRejection(this), { _transitionRejection: this });\n }\n}\n", + "/**\n * # Transition tracing (debug)\n *\n * Enable transition tracing to print transition information to the console,\n * in order to help debug your application.\n * Tracing logs detailed information about each Transition to your console.\n *\n * To enable tracing, import the [[Trace]] singleton and enable one or more categories.\n *\n * ### ES6\n * ```js\n * import {trace} from \"@uirouter/core\";\n * trace.enable(1, 5); // TRANSITION and VIEWCONFIG\n * ```\n *\n * ### CJS\n * ```js\n * let trace = require(\"@uirouter/core\").trace;\n * trace.enable(\"TRANSITION\", \"VIEWCONFIG\");\n * ```\n *\n * ### Globals\n * ```js\n * let trace = window[\"@uirouter/core\"].trace;\n * trace.enable(); // Trace everything (very verbose)\n * ```\n *\n * ### Angular 1:\n * ```js\n * app.run($trace => $trace.enable());\n * ```\n *\n * @coreapi\n * @module trace\n */\n/* tslint:disable:no-console */\nimport { parse } from '../common/hof';\nimport { isFunction, isNumber } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { ViewTuple } from '../view';\nimport { ActiveUIView, ViewConfig, ViewContext } from '../view/interface';\nimport { stringify, functionToString, maxLength, padString } from './strings';\nimport { Resolvable } from '../resolve/resolvable';\nimport { PathNode } from '../path/pathNode';\nimport { PolicyWhen } from '../resolve/interface';\nimport { TransitionHook } from '../transition/transitionHook';\nimport { HookResult } from '../transition/interface';\nimport { StateObject } from '../state/stateObject';\n\n/** @hidden */\nfunction uiViewString(uiview: ActiveUIView) {\n if (!uiview) return 'ui-view (defunct)';\n const state = uiview.creationContext ? uiview.creationContext.name || '(root)' : '(none)';\n return `[ui-view#${uiview.id} ${uiview.$type}:${uiview.fqn} (${uiview.name}@${state})]`;\n}\n\n/** @hidden */\nconst viewConfigString = (viewConfig: ViewConfig) => {\n const view = viewConfig.viewDecl;\n const state = view.$context.name || '(root)';\n return `[View#${viewConfig.$id} from '${state}' state]: target ui-view: '${view.$uiViewName}@${\n view.$uiViewContextAnchor\n }'`;\n};\n\n/** @hidden */\nfunction normalizedCat(input: Category | string): string {\n return isNumber(input) ? Category[input] : Category[Category[input]];\n}\n\n/** @hidden */\nconst consoleLog = Function.prototype.bind.call(console.log, console);\n\n/** @hidden */\nconst consoletable = isFunction(console.table) ? console.table.bind(console) : consoleLog.bind(console);\n\n/**\n * Trace categories Enum\n *\n * Enable or disable a category using [[Trace.enable]] or [[Trace.disable]]\n *\n * `trace.enable(Category.TRANSITION)`\n *\n * These can also be provided using a matching string, or position ordinal\n *\n * `trace.enable(\"TRANSITION\")`\n *\n * `trace.enable(1)`\n */\nenum Category {\n RESOLVE,\n TRANSITION,\n HOOK,\n UIVIEW,\n VIEWCONFIG,\n}\n\nexport { Category };\n\n/** @hidden */\nconst _tid = parse('$id');\n\n/** @hidden */\nconst _rid = parse('router.$id');\n\n/** @hidden */\nconst transLbl = trans => `Transition #${_tid(trans)}-${_rid(trans)}`;\n\n/**\n * Prints UI-Router Transition trace information to the console.\n */\nexport class Trace {\n /** @hidden */\n approximateDigests: number;\n\n /** @hidden */\n private _enabled: { [key: string]: boolean } = {};\n\n /** @hidden */\n constructor() {\n this.approximateDigests = 0;\n }\n\n /** @hidden */\n private _set(enabled: boolean, categories: Category[]) {\n if (!categories.length) {\n categories = Object.keys(Category)\n .map(k => parseInt(k, 10))\n .filter(k => !isNaN(k))\n .map(key => Category[key]);\n }\n categories.map(normalizedCat).forEach(category => (this._enabled[category] = enabled));\n }\n\n /**\n * Enables a trace [[Category]]\n *\n * ```js\n * trace.enable(\"TRANSITION\");\n * ```\n *\n * @param categories categories to enable. If `categories` is omitted, all categories are enabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n enable(...categories: (Category | string | number)[]);\n enable(...categories: any[]) {\n this._set(true, categories);\n }\n /**\n * Disables a trace [[Category]]\n *\n * ```js\n * trace.disable(\"VIEWCONFIG\");\n * ```\n *\n * @param categories categories to disable. If `categories` is omitted, all categories are disabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n disable(...categories: (Category | string | number)[]);\n disable(...categories: any[]) {\n this._set(false, categories);\n }\n\n /**\n * Retrieves the enabled stateus of a [[Category]]\n *\n * ```js\n * trace.enabled(\"VIEWCONFIG\"); // true or false\n * ```\n *\n * @returns boolean true if the category is enabled\n */\n enabled(category: Category | string | number): boolean {\n return !!this._enabled[normalizedCat(category)];\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionStart(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Started -> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionIgnored(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Ignored <> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookInvocation(step: TransitionHook, trans: Transition, options: any) {\n if (!this.enabled(Category.HOOK)) return;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = functionToString((step as any).registeredHook.callback);\n console.log(`${transLbl(trans)}: Hook -> ${event} context: ${context}, ${maxLength(200, name)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookResult(hookResult: HookResult, trans: Transition, transitionOptions: any) {\n if (!this.enabled(Category.HOOK)) return;\n console.log(`${transLbl(trans)}: <- Hook returned: ${maxLength(200, stringify(hookResult))}`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvePath(path: PathNode[], when: PolicyWhen, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(`${transLbl(trans)}: Resolving ${path} (${when})`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvableResolved(resolvable: Resolvable, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(\n `${transLbl(trans)}: <- Resolved ${resolvable} to: ${maxLength(200, stringify(resolvable.data))}`,\n );\n }\n\n /** @internalapi called by ui-router code */\n traceError(reason: any, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Rejected ${stringify(trans)}, reason: ${reason}`);\n }\n\n /** @internalapi called by ui-router code */\n traceSuccess(finalState: StateObject, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Success ${stringify(trans)}, final state: ${finalState.name}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewEvent(event: string, viewData: ActiveUIView, extra = '') {\n if (!this.enabled(Category.UIVIEW)) return;\n console.log(`ui-view: ${padString(30, event)} ${uiViewString(viewData)}${extra}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewConfigUpdated(viewData: ActiveUIView, context: ViewContext) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Updating', viewData, ` with ViewConfig from context='${context}'`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewFill(viewData: ActiveUIView, html: string) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Fill', viewData, ` with: ${maxLength(200, html)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewSync(pairs: ViewTuple[]) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n const uivheader = 'uiview component fqn';\n const cfgheader = 'view config state (view name)';\n const mapping = pairs\n .map(({ uiView, viewConfig }) => {\n const uiv = uiView && uiView.fqn;\n const cfg = viewConfig && `${viewConfig.viewDecl.$context.name}: (${viewConfig.viewDecl.$name})`;\n return { [uivheader]: uiv, [cfgheader]: cfg };\n })\n .sort((a, b) => (a[uivheader] || '').localeCompare(b[uivheader] || ''));\n\n consoletable(mapping);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceEvent(event: string, viewConfig: ViewConfig) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${viewConfigString(viewConfig)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceUIViewEvent(event: string, viewData: ActiveUIView) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${uiViewString(viewData)}`);\n }\n}\n\n/**\n * The [[Trace]] singleton\n *\n * #### Example:\n * ```js\n * import {trace} from \"@uirouter/core\";\n * trace.enable(1, 5);\n * ```\n */\nconst trace = new Trace();\nexport { trace };\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { StateDeclaration } from '../state/interface';\nimport { Predicate } from '../common/common';\n\nimport { Transition } from './transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TargetState } from '../state/targetState';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * The TransitionOptions object can be used to change the behavior of a transition.\n *\n * It is passed as the third argument to [[StateService.go]], [[StateService.transitionTo]].\n * It can also be used with a `uiSref`.\n */\nexport interface TransitionOptions {\n /**\n * This option changes how the Transition interacts with the browser's location bar (URL).\n *\n * - If `true`, it will update the url in the location bar.\n * - If `false`, it will not update the url in the location bar.\n * - If it is the string `\"replace\"`, it will update the url and also replace the last history record.\n *\n * @default `true`\n */\n location?: boolean | string;\n\n /**\n * When transitioning to relative path (e.g '`^`'), this option defines which state to be relative from.\n * @default `$state.current`\n */\n relative?: string | StateDeclaration | StateObject;\n\n /**\n * This option sets whether or not the transition's parameter values should be inherited from\n * the current parameter values.\n *\n * - If `true`, it will inherit parameter values from the current parameter values.\n * - If `false`, only the parameters which are provided to `transitionTo` will be used.\n *\n * @default `false`\n */\n inherit?: boolean;\n\n /**\n * @deprecated\n */\n notify?: boolean;\n\n /**\n * This option may be used to force states which are currently active to reload.\n *\n * During a normal transition, a state is \"retained\" if:\n * - It was previously active\n * - The state's parameter values have not changed\n * - All the parent states' parameter values have not changed\n *\n * Forcing a reload of a state will cause it to be exited and entered, which will:\n * - Refetch that state's resolve data\n * - Exit the state (onExit hook)\n * - Re-enter the state (onEnter hook)\n * - Re-render the views (controllers and templates)\n *\n * - When `true`, the destination state (and all parent states) will be reloaded.\n * - When it is a string and is the name of a state, or when it is a State object,\n * that state and any children states will be reloaded.\n *\n * @default `false`\n */\n reload?: boolean | string | StateDeclaration | StateObject;\n /**\n * You can define your own Transition Options inside this property and use them, e.g., from a Transition Hook\n */\n custom?: any;\n /** @internalapi */\n reloadState?: StateObject;\n /** @internalapi\n * If this transition is a redirect, this property should be the original Transition (which was redirected to this one)\n */\n redirectedFrom?: Transition;\n /** @internalapi */\n current?: () => Transition;\n /** @internalapi */\n source?: 'sref' | 'url' | 'redirect' | 'otherwise' | 'unknown';\n}\n\n/** @internalapi */\nexport interface TransitionHookOptions {\n current?: () => Transition; // path?\n transition?: Transition;\n hookType?: string;\n target?: any;\n traceData?: any;\n bind?: any;\n stateHook?: boolean;\n}\n\n/**\n * TreeChanges encapsulates the various Paths that are involved in a Transition.\n *\n * Get a TreeChanges object using [[Transition.treeChanges]]\n *\n * A UI-Router Transition is from one Path in a State Tree to another Path. For a given Transition,\n * this object stores the \"to\" and \"from\" paths, as well as subsets of those: the \"retained\",\n * \"exiting\" and \"entering\" paths.\n *\n * Each path in TreeChanges is an array of [[PathNode]] objects. Each PathNode in the array corresponds to a portion\n * of a nested state.\n *\n * For example, if you had a nested state named `foo.bar.baz`, it would have three\n * portions, `foo, bar, baz`. If you transitioned **to** `foo.bar.baz` and inspected the [[TreeChanges.to]]\n * Path, you would find a node in the array for each portion: `foo`, `bar`, and `baz`.\n *\n * ---\n *\n * @todo show visual state tree\n */\nexport interface TreeChanges {\n /** @nodoc */\n [key: string]: PathNode[];\n\n /** The path of nodes in the state tree that the transition is coming *from* */\n from: PathNode[];\n\n /** The path of nodes in the state tree that the transition is going *to* */\n to: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n */\n retained: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining with updated \"to params\" applied.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n *\n * This is a shallow copy of [[retained]], but with new (dynamic) parameter values from [[to]] applied.\n */\n retainedWithToParams: PathNode[];\n\n /**\n * The path of previously active nodes that the transition is exiting.\n *\n * After the Transition is successful, these nodes are no longer active.\n *\n * Note that a state that is being reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n exiting: PathNode[];\n\n /**\n * The path of nodes that the transition is entering.\n *\n * After the Transition is successful, these nodes will be active.\n * Because they are entering, they have their resolves fetched, `onEnter` hooks run, and their views\n * (component(s) or controller(s)+template(s)) refreshed.\n *\n * Note that a state that is reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n entering: PathNode[];\n}\n\nexport type IHookRegistration = (\n matchCriteria: HookMatchCriteria,\n callback: HookFn,\n options?: HookRegOptions,\n) => Function;\n\n/**\n * The signature for Transition Hooks.\n *\n * Transition hooks are callback functions that hook into the lifecycle of transitions.\n * As a transition runs, it reaches certain lifecycle events.\n * As each event occurs, the hooks which are registered for the event are called (in priority order).\n *\n * A transition hook may alter a Transition by returning a [[HookResult]].\n *\n * #### See:\n *\n * - [[IHookRegistry.onBefore]]\n * - [[IHookRegistry.onStart]]\n * - [[IHookRegistry.onFinish]]\n * - [[IHookRegistry.onSuccess]]\n * - [[IHookRegistry.onError]]\n *\n * @param transition the current [[Transition]]\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n *\n */\nexport interface TransitionHookFn {\n (transition: Transition): HookResult;\n}\n\n/**\n * The signature for Transition State Hooks.\n *\n * A function which hooks into a lifecycle event for a specific state.\n *\n * Transition State Hooks are callback functions that hook into the lifecycle events of specific states during a transition.\n * As a transition runs, it may exit some states, retain (keep) states, and enter states.\n * As each lifecycle event occurs, the hooks which are registered for the event and that state are called (in priority order).\n *\n * #### See:\n *\n * - [[IHookRegistry.onExit]]\n * - [[IHookRegistry.onRetain]]\n * - [[IHookRegistry.onEnter]]\n *\n * @param transition the current [[Transition]]\n * @param state the [[StateObject]] that the hook is bound to\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n */\nexport interface TransitionStateHookFn {\n (transition: Transition, state: StateDeclaration): HookResult;\n}\n\n/**\n * The signature for Transition onCreate Hooks.\n *\n * Transition onCreate Hooks are callbacks that allow customization or preprocessing of\n * a Transition before it is returned from [[TransitionService.create]]\n *\n * @param transition the [[Transition]] that was just created\n * @return a [[Transition]] which will then be returned from [[TransitionService.create]]\n */\nexport interface TransitionCreateHookFn {\n (transition: Transition): void;\n}\n\nexport type HookFn = TransitionHookFn | TransitionStateHookFn | TransitionCreateHookFn;\n\n/**\n * The return value of a [[TransitionHookFn]] or [[TransitionStateHookFn]]\n *\n * When returned from a [[TransitionHookFn]] or [[TransitionStateHookFn]], these values alter the running [[Transition]]:\n *\n * - `false`: the transition will be cancelled.\n * - [[TargetState]]: the transition will be redirected to the new target state (see: [[StateService.target]])\n * - `Promise`: the transition will wait for the promise to resolve or reject\n * - If the promise is rejected (or resolves to `false`), the transition will be cancelled\n * - If the promise resolves to a [[TargetState]], the transition will be redirected\n * - If the promise resolves to anything else, the transition will resume\n * - Anything else: the transition will resume\n */\nexport type HookResult = boolean | TargetState | void | Promise;\n\n/**\n * These options may be provided when registering a Transition Hook (such as `onStart`)\n */\nexport interface HookRegOptions {\n /**\n * Sets the priority of the registered hook\n *\n * Hooks of the same type (onBefore, onStart, etc) are invoked in priority order. A hook with a higher priority\n * is invoked before a hook with a lower priority.\n *\n * The default hook priority is 0\n */\n priority?: number;\n\n /**\n * Specifies what `this` is bound to during hook invocation.\n */\n bind?: any;\n\n /**\n * Limits the number of times that the hook will be invoked.\n * Once the hook has been invoked this many times, it is automatically deregistered.\n */\n invokeLimit?: number;\n}\n\n/**\n * This interface specifies the api for registering Transition Hooks. Both the\n * [[TransitionService]] and also the [[Transition]] object itself implement this interface.\n * Note: the Transition object only allows hooks to be registered before the Transition is started.\n */\nexport interface IHookRegistry {\n /** @hidden place to store the hooks */\n _registeredHooks: { [key: string]: RegisteredHook[] };\n\n /**\n * Registers a [[TransitionHookFn]], called *before a transition starts*.\n *\n * Registers a transition lifecycle hook, which is invoked before a transition even begins.\n * This hook can be useful to implement logic which prevents a transition from even starting, such\n * as authentication, redirection\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onBefore` hooks are invoked *before a Transition starts*.\n * No resolves have been fetched yet.\n * Each `onBefore` hook is invoked synchronously, in the same call stack as [[StateService.transitionTo]].\n * The registered `onBefore` hooks are invoked in priority order.\n *\n * Note: during the `onBefore` phase, additional hooks can be added to the specific [[Transition]] instance.\n * These \"on-the-fly\" hooks only affect the currently running transition..\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * If any hook modifies the transition *synchronously* (by throwing, returning `false`, or returning\n * a [[TargetState]]), the remainder of the hooks are skipped.\n * If a hook returns a promise, the remainder of the `onBefore` hooks are still invoked synchronously.\n * All promises are resolved, and processed asynchronously before the `onStart` phase of the Transition.\n *\n * ### Examples\n *\n * #### Default Substate\n *\n * This example redirects any transition from 'home' to 'home.dashboard'. This is commonly referred to as a\n * \"default substate\".\n *\n * @example\n * ```js\n * // ng2\n * transitionService.onBefore({ to: 'home' }, (trans: Transition) =>\n * trans.router.stateService.target(\"home.dashboard\"));\n * ```\n *\n * #### Data Driven Default Substate\n *\n * This example provides data-driven default substate functionality. It matches on a transition to any state\n * which has `defaultSubstate: \"some.sub.state\"` defined. See: [[Transition.to]] which returns the \"to state\"\n * definition.\n *\n * @example\n * ```js\n * // ng1\n * // state declaration\n * {\n * name: 'home',\n * template: '
    ',\n * defaultSubstate: 'home.dashboard'\n * }\n *\n * var criteria = {\n * to: function(state) {\n * return state.defaultSubstate != null;\n * }\n * }\n *\n * $transitions.onBefore(criteria, function(trans: Transition) {\n * var substate = trans.to().defaultSubstate;\n * return trans.router.stateService.target(substate);\n * });\n * ```\n *\n *\n * #### Require authentication\n *\n * This example cancels a transition to a state which requires authentication, if the user is not currently authenticated.\n *\n * This example assumes a state tree where all states which require authentication are children of a parent `'requireauth'` state.\n * This example assumes `MyAuthService` synchronously returns a boolean from `isAuthenticated()`.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onBefore( { to: 'requireauth.**' }, function(trans) {\n * var myAuthService = trans.injector().get('MyAuthService');\n * // If isAuthenticated returns false, the transition is cancelled.\n * return myAuthService.isAuthenticated();\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @returns a function which deregisters the hook.\n */\n onBefore(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called when a transition starts.\n *\n * Registers a transition lifecycle hook, which is invoked as a transition starts running.\n * This hook can be useful to perform some asynchronous action before completing a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onStart` hooks are invoked asynchronously when the Transition starts running.\n * This happens after the `onBefore` phase is complete.\n * At this point, the Transition has not yet exited nor entered any states.\n * The registered `onStart` hooks are invoked in priority order.\n *\n * Note: A built-in `onStart` hook with high priority is used to fetch any eager resolve data.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Example\n *\n * #### Login during transition\n *\n * This example intercepts any transition to a state which requires authentication, when the user is\n * not currently authenticated. It allows the user to authenticate asynchronously, then resumes the\n * transition. If the user did not authenticate successfully, it redirects to the \"guest\" state, which\n * does not require authentication.\n *\n * This example assumes:\n * - a state tree where all states which require authentication are children of a parent `'auth'` state.\n * - `MyAuthService.isAuthenticated()` synchronously returns a boolean.\n * - `MyAuthService.authenticate()` presents a login dialog, and returns a promise which is resolved\n * or rejected, whether or not the login attempt was successful.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onStart( { to: 'auth.**' }, function(trans) {\n * var $state = trans.router.stateService;\n * var MyAuthService = trans.injector().get('MyAuthService');\n *\n * // If the user is not authenticated\n * if (!MyAuthService.isAuthenticated()) {\n *\n * // Then return a promise for a successful login.\n * // The transition will wait for this promise to settle\n *\n * return MyAuthService.authenticate().catch(function() {\n *\n * // If the authenticate() method failed for whatever reason,\n * // redirect to a 'guest' state which doesn't require auth.\n * return $state.target(\"guest\");\n * });\n * }\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onStart(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is entered.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being entered.\n *\n * Since this hook is run only when the specific state is being *entered*, it can be useful for\n * performing tasks when entering a submodule/feature area such as initializing a stateful service,\n * or for guarding access to a submodule/feature area.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onEnter` hooks generally specify `{ entering: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onEnter` hooks are invoked when the Transition is entering a state.\n * States are entered after the `onRetain` phase is complete.\n * If more than one state is being entered, the parent state is entered first.\n * The registered `onEnter` hooks for a state are invoked in priority order.\n *\n * Note: A built-in `onEnter` hook with high priority is used to fetch lazy resolve data for states being entered.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onEnter` hooks using the [[TransitionService]], you may define an `onEnter` hook\n * directly on a state declaration (see: [[StateDeclaration.onEnter]]).\n *\n *\n * ### Examples\n *\n * #### Audit Log\n *\n * This example uses a service to log that a user has entered the admin section of an app.\n * This assumes that there are substates of the \"admin\" state, such as \"admin.users\", \"admin.pages\", etc.\n * @example\n * ```\n *\n * $transitions.onEnter({ entering: 'admin' }, function(transition, state) {\n * var AuditService = trans.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * ```\n *\n * #### Audit Log (inside a state declaration)\n *\n * The `onEnter` inside this state declaration is syntactic sugar for the previous Audit Log example.\n * ```\n * {\n * name: 'admin',\n * component: 'admin',\n * onEnter: function($transition$, $state$) {\n * var AuditService = $transition$.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * }\n * ```\n *\n * Note: A state declaration's `onEnter` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onEnter(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is retained/kept.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) for\n * a specific state that was previously active will remain active (is not being entered nor exited).\n *\n * This hook is invoked when a state is \"retained\" or \"kept\".\n * It means the transition is coming *from* a substate of the retained state *to* a substate of the retained state.\n * This hook can be used to perform actions when the user moves from one substate to another, such as between steps in a wizard.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onRetain` hooks generally specify `{ retained: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onRetain` hooks are invoked after any `onExit` hooks have been fired.\n * If more than one state is retained, the child states' `onRetain` hooks are invoked first.\n * The registered `onRetain` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onRetain` hooks using the [[TransitionService]], you may define an `onRetain` hook\n * directly on a state declaration (see: [[StateDeclaration.onRetain]]).\n *\n * Note: A state declaration's `onRetain` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onRetain(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is exited.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being exited.\n *\n * Since this hook is run only when the specific state is being *exited*, it can be useful for\n * performing tasks when leaving a submodule/feature area such as cleaning up a stateful service,\n * or for preventing the user from leaving a state or submodule until some criteria is satisfied.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onExit` hooks generally specify `{ exiting: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onExit` hooks are invoked when the Transition is exiting a state.\n * States are exited after any `onStart` phase is complete.\n * If more than one state is being exited, the child states are exited first.\n * The registered `onExit` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onExit` hooks using the [[TransitionService]], you may define an `onExit` hook\n * directly on a state declaration (see: [[StateDeclaration.onExit]]).\n *\n * Note: A state declaration's `onExit` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onExit(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called *just before a transition finishes*.\n *\n * Registers a transition lifecycle hook, which is invoked just before a transition finishes.\n * This hook is a last chance to cancel or redirect a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onFinish` hooks are invoked after the `onEnter` phase is complete.\n * These hooks are invoked just before the transition is \"committed\".\n * Each hook is invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onFinish(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a successful transition completed.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition successfully completes.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onSuccess` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If the Transition is successful and its promise is resolved, then the `onSuccess` hooks are invoked.\n * Since these hooks are run after the transition is over, their return value is ignored.\n * The `onSuccess` hooks are invoked in priority order.\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onSuccess(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a transition has errored.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition has been rejected for any reason.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * The `onError` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If a Transition fails, its promise is rejected and the `onError` hooks are invoked.\n * The `onError` hooks are invoked in priority order.\n *\n * Since these hooks are run after the transition is over, their return value is ignored.\n *\n * A transition \"errors\" if it was started, but failed to complete (for any reason).\n * A *non-exhaustive list* of reasons a transition can error:\n *\n * - A transition was cancelled because a new transition started while it was still running (`Transition superseded`)\n * - A transition was cancelled by a Transition Hook returning false\n * - A transition was redirected by a Transition Hook returning a [[TargetState]]\n * - A Transition Hook or resolve function threw an error\n * - A Transition Hook returned a rejected promise\n * - A resolve function returned a rejected promise\n *\n * To check the failure reason, inspect the return value of [[Transition.error]].\n *\n * Note: `onError` should be used for targeted error handling, or error recovery.\n * For simple catch-all error reporting, use [[StateService.defaultErrorHandler]].\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onError(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Returns all the registered hooks of a given `hookName` type\n *\n * #### Example:\n * ```\n * $transitions.getHooks(\"onEnter\")\n * ```\n */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/** A predicate type which tests if a [[StateObject]] passes some test. Returns a boolean. */\nexport type IStateMatch = Predicate;\n\n/**\n * This object is used to configure whether or not a Transition Hook is invoked for a particular transition,\n * based on the Transition's \"to state\" and \"from state\".\n *\n * Each property (`to`, `from`, `exiting`, `retained`, and `entering`) can be a state [[Glob]] string,\n * a boolean, or a function that takes a state and returns a boolean (see [[HookMatchCriterion]])\n *\n * All properties are optional. If any property is omitted, it is replaced with the value `true`, and always matches.\n * To match any transition, use an empty criteria object `{}`.\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from the `parent` state and going to the `parent.child` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.child'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any substate of `parent` and going directly to the `parent` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any substate of `mymodule`\n * var match = {\n * to: 'mymodule.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any state that has `data.authRequired`\n * // set to a truthy value.\n * var match = {\n * to: function(state) {\n * return state.data != null && state.data.authRequired === true;\n * }\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition that is exiting `parent.child`\n * var match = {\n * exiting: 'parent.child'\n * }\n * ```\n */\nexport interface HookMatchCriteria {\n [key: string]: HookMatchCriterion | undefined;\n\n /** A [[HookMatchCriterion]] to match the destination state */\n to?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match the original (from) state */\n from?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be exiting */\n exiting?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be retained */\n retained?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be entering */\n entering?: HookMatchCriterion;\n}\n\nexport interface IMatchingNodes {\n [key: string]: PathNode[];\n\n to: PathNode[];\n from: PathNode[];\n exiting: PathNode[];\n retained: PathNode[];\n entering: PathNode[];\n}\n\n/** @hidden */\nexport interface RegisteredHooks {\n [key: string]: RegisteredHook[];\n}\n\n/** @hidden */\nexport interface PathTypes {\n [key: string]: PathType;\n\n to: PathType;\n from: PathType;\n exiting: PathType;\n retained: PathType;\n entering: PathType;\n}\n\n/** @hidden */\nexport interface PathType {\n name: string;\n scope: TransitionHookScope;\n}\n\n/**\n * Hook Criterion used to match a transition.\n *\n * A [[Glob]] string that matches the name of a state.\n *\n * Or, a function with the signature `function(state) { return matches; }`\n * which should return a boolean to indicate if a state matches.\n *\n * Or, `true` to always match\n */\nexport type HookMatchCriterion = string | IStateMatch | boolean;\n\nenum TransitionHookPhase {\n CREATE,\n BEFORE,\n RUN,\n SUCCESS,\n ERROR,\n}\nenum TransitionHookScope {\n TRANSITION,\n STATE,\n}\n\nexport { TransitionHookPhase, TransitionHookScope };\n", + "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateDeclaration, StateOrName, TargetStateDef } from './interface';\nimport { TransitionOptions } from '../transition/interface';\nimport { StateObject } from './stateObject';\nimport { isString } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { extend } from '../common';\nimport { StateRegistry } from './stateRegistry';\nimport { RawParams } from '../params';\n\n/**\n * Encapsulate the target (destination) state/params/options of a [[Transition]].\n *\n * This class is frequently used to redirect a transition to a new destination.\n *\n * See:\n *\n * - [[HookResult]]\n * - [[TransitionHookFn]]\n * - [[TransitionService.onStart]]\n *\n * To create a `TargetState`, use [[StateService.target]].\n *\n * ---\n *\n * This class wraps:\n *\n * 1) an identifier for a state\n * 2) a set of parameters\n * 3) and transition options\n * 4) the registered state object (the [[StateDeclaration]])\n *\n * Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can\n * either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string).\n * The `TargetState` class normalizes those options.\n *\n * A `TargetState` may be valid (the state being targeted exists in the registry)\n * or invalid (the state being targeted is not registered).\n */\nexport class TargetState {\n private _definition: StateObject;\n private _params: RawParams;\n private _options: TransitionOptions;\n\n /** Returns true if the object has a state property that might be a state or state name */\n static isDef = (obj): obj is TargetStateDef => obj && obj.state && (isString(obj.state) || isString(obj.state.name));\n\n /**\n * The TargetState constructor\n *\n * Note: Do not construct a `TargetState` manually.\n * To create a `TargetState`, use the [[StateService.target]] factory method.\n *\n * @param _stateRegistry The StateRegistry to use to look up the _definition\n * @param _identifier An identifier for a state.\n * Either a fully-qualified state name, or the object used to define the state.\n * @param _params Parameters for the target state\n * @param _options Transition options.\n *\n * @internalapi\n */\n constructor(\n private _stateRegistry: StateRegistry,\n private _identifier: StateOrName,\n _params?: RawParams,\n _options?: TransitionOptions,\n ) {\n this._identifier = _identifier;\n this._params = extend({}, _params || {});\n this._options = extend({}, _options || {});\n this._definition = _stateRegistry.matcher.find(_identifier, this._options.relative);\n }\n\n /** The name of the state this object targets */\n name(): string {\n return (this._definition && this._definition.name) || this._identifier;\n }\n\n /** The identifier used when creating this TargetState */\n identifier(): StateOrName {\n return this._identifier;\n }\n\n /** The target parameter values */\n params(): RawParams {\n return this._params;\n }\n\n /** The internal state object (if it was found) */\n $state(): StateObject {\n return this._definition;\n }\n\n /** The internal state declaration (if it was found) */\n state(): StateDeclaration {\n return this._definition && this._definition.self;\n }\n\n /** The target options */\n options() {\n return this._options;\n }\n\n /** True if the target state was found */\n exists(): boolean {\n return !!(this._definition && this._definition.self);\n }\n\n /** True if the object is valid */\n valid(): boolean {\n return !this.error();\n }\n\n /** If the object is invalid, returns the reason why */\n error(): string {\n const base = this.options().relative;\n if (!this._definition && !!base) {\n const stateName = base.name ? base.name : base;\n return `Could not resolve '${this.name()}' from state '${stateName}'`;\n }\n if (!this._definition) return `No such state '${this.name()}'`;\n if (!this._definition.self) return `State '${this.name()}' has an invalid definition`;\n }\n\n toString() {\n return `'${this.name()}'${stringify(this.params())}`;\n }\n\n /**\n * Returns a copy of this TargetState which targets a different state.\n * The new TargetState has the same parameter values and transition options.\n *\n * @param state The new state that should be targeted\n */\n withState(state: StateOrName): TargetState {\n return new TargetState(this._stateRegistry, state, this._params, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified parameter values.\n *\n * @param params the new parameter values to use\n * @param replace When false (default) the new parameter values will be merged with the current values.\n * When true the parameter values will be used instead of the current values.\n */\n withParams(params: RawParams, replace = false): TargetState {\n const newParams: RawParams = replace ? params : extend({}, this._params, params);\n return new TargetState(this._stateRegistry, this._identifier, newParams, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified Transition Options.\n *\n * @param options the new options to use\n * @param replace When false (default) the new options will be merged with the current options.\n * When true the options will be used instead of the current options.\n */\n withOptions(options: TransitionOptions, replace = false): TargetState {\n const newOpts = replace ? options : extend({}, this._options, options);\n return new TargetState(this._stateRegistry, this._identifier, this._params, newOpts);\n }\n}\n", + "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { TransitionHookOptions, HookResult, TransitionHookPhase } from './interface';\nimport { defaults, noop, silentRejection } from '../common/common';\nimport { fnToString, maxLength } from '../common/strings';\nimport { isPromise } from '../common/predicates';\nimport { is, parse } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { Rejection } from './rejectFactory';\nimport { TargetState } from '../state/targetState';\nimport { Transition } from './transition';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\nimport { StateDeclaration } from '../state/interface';\n\nconst defaultOptions: TransitionHookOptions = {\n current: noop,\n transition: null,\n traceData: {},\n bind: null,\n};\n\nexport type GetResultHandler = (hook: TransitionHook) => ResultHandler;\nexport type GetErrorHandler = (hook: TransitionHook) => ErrorHandler;\n\nexport type ResultHandler = (result: HookResult) => Promise;\nexport type ErrorHandler = (error: any) => Promise;\n\n/** @hidden */\nexport class TransitionHook {\n type: TransitionEventType;\n\n /**\n * These GetResultHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetResultHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static HANDLE_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) =>\n hook.handleHookResult(result);\n\n /**\n * If the result is a promise rejection, log it.\n * Otherwise, ignore the result.\n */\n static LOG_REJECTED_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) => {\n isPromise(result) && result.catch(err => hook.logError(Rejection.normalize(err)));\n return undefined;\n };\n\n /**\n * These GetErrorHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetErrorHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static LOG_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => hook.logError(error);\n\n static REJECT_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => silentRejection(error);\n\n static THROW_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => {\n throw error;\n };\n\n /**\n * Chains together an array of TransitionHooks.\n *\n * Given a list of [[TransitionHook]] objects, chains them together.\n * Each hook is invoked after the previous one completes.\n *\n * #### Example:\n * ```js\n * var hooks: TransitionHook[] = getHooks();\n * let promise: Promise = TransitionHook.chain(hooks);\n *\n * promise.then(handleSuccess, handleError);\n * ```\n *\n * @param hooks the list of hooks to chain together\n * @param waitFor if provided, the chain is `.then()`'ed off this promise\n * @returns a `Promise` for sequentially invoking the hooks (in order)\n */\n static chain(hooks: TransitionHook[], waitFor?: Promise): Promise {\n // Chain the next hook off the previous\n const createHookChainR = (prev: Promise, nextHook: TransitionHook) => prev.then(() => nextHook.invokeHook());\n return hooks.reduce(createHookChainR, waitFor || services.$q.when());\n }\n\n /**\n * Invokes all the provided TransitionHooks, in order.\n * Each hook's return value is checked.\n * If any hook returns a promise, then the rest of the hooks are chained off that promise, and the promise is returned.\n * If no hook returns a promise, then all hooks are processed synchronously.\n *\n * @param hooks the list of TransitionHooks to invoke\n * @param doneCallback a callback that is invoked after all the hooks have successfully completed\n *\n * @returns a promise for the async result, or the result of the callback\n */\n static invokeHooks(hooks: TransitionHook[], doneCallback: (result?: HookResult) => T): Promise | T {\n for (let idx = 0; idx < hooks.length; idx++) {\n const hookResult = hooks[idx].invokeHook();\n\n if (isPromise(hookResult)) {\n const remainingHooks = hooks.slice(idx + 1);\n\n return TransitionHook.chain(remainingHooks, hookResult).then(doneCallback);\n }\n }\n\n return doneCallback();\n }\n\n /**\n * Run all TransitionHooks, ignoring their return value.\n */\n static runAllHooks(hooks: TransitionHook[]): void {\n hooks.forEach(hook => hook.invokeHook());\n }\n\n constructor(\n private transition: Transition,\n private stateContext: StateDeclaration,\n private registeredHook: RegisteredHook,\n private options: TransitionHookOptions,\n ) {\n this.options = defaults(options, defaultOptions);\n this.type = registeredHook.eventType;\n }\n\n private isSuperseded = () => this.type.hookPhase === TransitionHookPhase.RUN && !this.options.transition.isActive();\n\n logError(err): any {\n this.transition.router.stateService.defaultErrorHandler()(err);\n }\n\n invokeHook(): Promise | void {\n const hook = this.registeredHook;\n if (hook._deregistered) return;\n\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n const options = this.options;\n trace.traceHookInvocation(this, this.transition, options);\n\n const invokeCallback = () => hook.callback.call(options.bind, this.transition, this.stateContext);\n\n const normalizeErr = err => Rejection.normalize(err).toPromise();\n\n const handleError = err => hook.eventType.getErrorHandler(this)(err);\n\n const handleResult = result => hook.eventType.getResultHandler(this)(result);\n\n try {\n const result = invokeCallback();\n\n if (!this.type.synchronous && isPromise(result)) {\n return result.catch(normalizeErr).then(handleResult, handleError);\n } else {\n return handleResult(result);\n }\n } catch (err) {\n // If callback throws (synchronously)\n return handleError(Rejection.normalize(err));\n } finally {\n if (hook.invokeLimit && ++hook.invokeCount >= hook.invokeLimit) {\n hook.deregister();\n }\n }\n }\n\n /**\n * This method handles the return value of a Transition Hook.\n *\n * A hook can return false (cancel), a TargetState (redirect),\n * or a promise (which may later resolve to false or a redirect)\n *\n * This also handles \"transition superseded\" -- when a new transition\n * was started while the hook was still running\n */\n handleHookResult(result: HookResult): Promise {\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n // Hook returned a promise\n if (isPromise(result)) {\n // Wait for the promise, then reprocess with the resulting value\n return result.then(val => this.handleHookResult(val));\n }\n\n trace.traceHookResult(result, this.transition, this.options);\n\n // Hook returned false\n if (result === false) {\n // Abort this Transition\n return Rejection.aborted('Hook aborted transition').toPromise();\n }\n\n const isTargetState = is(TargetState);\n // hook returned a TargetState\n if (isTargetState(result)) {\n // Halt the current Transition and redirect (a new Transition) to the TargetState.\n return Rejection.redirected(result).toPromise();\n }\n }\n\n /**\n * Return a Rejection promise if the transition is no longer current due\n * to a stopped router (disposed), or a new transition has started and superseded this one.\n */\n private getNotCurrentRejection() {\n const router = this.transition.router;\n\n // The router is stopped\n if (router._disposed) {\n return Rejection.aborted(`UIRouter instance #${router.$id} has been stopped (disposed)`).toPromise();\n }\n\n if (this.transition._aborted) {\n return Rejection.aborted().toPromise();\n }\n\n // This transition is no longer current.\n // Another transition started while this hook was still running.\n if (this.isSuperseded()) {\n // Abort this transition\n return Rejection.superseded(this.options.current()).toPromise();\n }\n }\n\n toString() {\n const { options, registeredHook } = this;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = fnToString(registeredHook.callback);\n return `${event} context: ${context}, ${maxLength(200, name)}`;\n }\n}\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { isString, isFunction, Glob, extend, removeFrom, tail, values, identity, mapObj } from '../common';\nimport { PathNode } from '../path/pathNode';\nimport {\n TransitionStateHookFn,\n TransitionHookFn,\n TransitionHookPhase, // has or is using\n TransitionHookScope,\n IHookRegistry,\n PathType,\n} from './interface';\n\nimport {\n HookRegOptions,\n HookMatchCriteria,\n TreeChanges,\n HookMatchCriterion,\n IMatchingNodes,\n HookFn,\n} from './interface';\nimport { StateObject } from '../state/stateObject';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionService } from './transitionService';\n\n/**\n * Determines if the given state matches the matchCriteria\n *\n * @hidden\n *\n * @param state a State Object to test against\n * @param criterion\n * - If a string, matchState uses the string as a glob-matcher against the state name\n * - If an array (of strings), matchState uses each string in the array as a glob-matchers against the state name\n * and returns a positive match if any of the globs match.\n * - If a function, matchState calls the function with the state and returns true if the function's result is truthy.\n * @returns {boolean}\n */\nexport function matchState(state: StateObject, criterion: HookMatchCriterion) {\n const toMatch = isString(criterion) ? [criterion] : criterion;\n\n function matchGlobs(_state: StateObject) {\n const globStrings = toMatch;\n for (let i = 0; i < globStrings.length; i++) {\n const glob = new Glob(globStrings[i]);\n\n if ((glob && glob.matches(_state.name)) || (!glob && globStrings[i] === _state.name)) {\n return true;\n }\n }\n return false;\n }\n\n const matchFn = (isFunction(toMatch) ? toMatch : matchGlobs);\n return !!matchFn(state);\n}\n\n/**\n * @internalapi\n * The registration data for a registered transition hook\n */\nexport class RegisteredHook {\n priority: number;\n bind: any;\n invokeCount = 0;\n invokeLimit: number;\n _deregistered = false;\n\n constructor(\n public tranSvc: TransitionService,\n public eventType: TransitionEventType,\n public callback: HookFn,\n public matchCriteria: HookMatchCriteria,\n public removeHookFromRegistry: (hook: RegisteredHook) => void,\n options: HookRegOptions = {} as any,\n ) {\n this.priority = options.priority || 0;\n this.bind = options.bind || null;\n this.invokeLimit = options.invokeLimit;\n }\n\n /**\n * Gets the matching [[PathNode]]s\n *\n * Given an array of [[PathNode]]s, and a [[HookMatchCriterion]], returns an array containing\n * the [[PathNode]]s that the criteria matches, or `null` if there were no matching nodes.\n *\n * Returning `null` is significant to distinguish between the default\n * \"match-all criterion value\" of `true` compared to a `() => true` function,\n * when the nodes is an empty array.\n *\n * This is useful to allow a transition match criteria of `entering: true`\n * to still match a transition, even when `entering === []`. Contrast that\n * with `entering: (state) => true` which only matches when a state is actually\n * being entered.\n */\n private _matchingNodes(nodes: PathNode[], criterion: HookMatchCriterion): PathNode[] {\n if (criterion === true) return nodes;\n const matching = nodes.filter(node => matchState(node.state, criterion));\n return matching.length ? matching : null;\n }\n\n /**\n * Gets the default match criteria (all `true`)\n *\n * Returns an object which has all the criteria match paths as keys and `true` as values, i.e.:\n *\n * ```js\n * {\n * to: true,\n * from: true,\n * entering: true,\n * exiting: true,\n * retained: true,\n * }\n */\n private _getDefaultMatchCriteria(): HookMatchCriteria {\n return mapObj(this.tranSvc._pluginapi._getPathTypes(), () => true);\n }\n\n /**\n * Gets matching nodes as [[IMatchingNodes]]\n *\n * Create a IMatchingNodes object from the TransitionHookTypes that is roughly equivalent to:\n *\n * ```js\n * let matches: IMatchingNodes = {\n * to: _matchingNodes([tail(treeChanges.to)], mc.to),\n * from: _matchingNodes([tail(treeChanges.from)], mc.from),\n * exiting: _matchingNodes(treeChanges.exiting, mc.exiting),\n * retained: _matchingNodes(treeChanges.retained, mc.retained),\n * entering: _matchingNodes(treeChanges.entering, mc.entering),\n * };\n * ```\n */\n private _getMatchingNodes(treeChanges: TreeChanges): IMatchingNodes {\n const criteria = extend(this._getDefaultMatchCriteria(), this.matchCriteria);\n const paths: PathType[] = values(this.tranSvc._pluginapi._getPathTypes());\n\n return paths.reduce(\n (mn: IMatchingNodes, pathtype: PathType) => {\n // STATE scope criteria matches against every node in the path.\n // TRANSITION scope criteria matches against only the last node in the path\n const isStateHook = pathtype.scope === TransitionHookScope.STATE;\n const path = treeChanges[pathtype.name] || [];\n const nodes: PathNode[] = isStateHook ? path : [tail(path)];\n\n mn[pathtype.name] = this._matchingNodes(nodes, criteria[pathtype.name]);\n return mn;\n },\n {} as IMatchingNodes,\n );\n }\n\n /**\n * Determines if this hook's [[matchCriteria]] match the given [[TreeChanges]]\n *\n * @returns an IMatchingNodes object, or null. If an IMatchingNodes object is returned, its values\n * are the matching [[PathNode]]s for each [[HookMatchCriterion]] (to, from, exiting, retained, entering)\n */\n matches(treeChanges: TreeChanges): IMatchingNodes {\n const matches = this._getMatchingNodes(treeChanges);\n\n // Check if all the criteria matched the TreeChanges object\n const allMatched = values(matches).every(identity);\n return allMatched ? matches : null;\n }\n\n deregister() {\n this.removeHookFromRegistry(this);\n this._deregistered = true;\n }\n}\n\n/** @hidden Return a registration function of the requested type. */\nexport function makeEvent(\n registry: IHookRegistry,\n transitionService: TransitionService,\n eventType: TransitionEventType,\n) {\n // Create the object which holds the registered transition hooks.\n const _registeredHooks = (registry._registeredHooks = registry._registeredHooks || {});\n const hooks = (_registeredHooks[eventType.name] = []);\n const removeHookFn: (hook: RegisteredHook) => void = removeFrom(hooks);\n\n // Create hook registration function on the IHookRegistry for the event\n registry[eventType.name] = hookRegistrationFn;\n\n function hookRegistrationFn(matchObject, callback, options = {}) {\n const registeredHook = new RegisteredHook(\n transitionService,\n eventType,\n callback,\n matchObject,\n removeHookFn,\n options,\n );\n hooks.push(registeredHook);\n return registeredHook.deregister.bind(registeredHook);\n }\n\n return hookRegistrationFn;\n}\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n\nimport { extend, tail, assertPredicate, unnestR, identity } from '../common/common';\nimport { isArray } from '../common/predicates';\n\nimport {\n TransitionOptions,\n TransitionHookOptions,\n IHookRegistry,\n TreeChanges,\n IMatchingNodes,\n TransitionHookPhase,\n TransitionHookScope,\n} from './interface';\n\nimport { Transition } from './transition';\nimport { TransitionHook } from './transitionHook';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TransitionService } from './transitionService';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * This class returns applicable TransitionHooks for a specific Transition instance.\n *\n * Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g.\n * myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is\n * determined by the type of hook)\n *\n * The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition.\n *\n * The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder\n * instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private\n * in the Transition class, so we must also provide the Transition's _treeChanges)\n *\n */\nexport class HookBuilder {\n constructor(private transition: Transition) {}\n\n buildHooksForPhase(phase: TransitionHookPhase): TransitionHook[] {\n const $transitions = this.transition.router.transitionService;\n return $transitions._pluginapi\n ._getEvents(phase)\n .map(type => this.buildHooks(type))\n .reduce(unnestR, [])\n .filter(identity);\n }\n\n /**\n * Returns an array of newly built TransitionHook objects.\n *\n * - Finds all RegisteredHooks registered for the given `hookType` which matched the transition's [[TreeChanges]].\n * - Finds [[PathNode]] (or `PathNode[]`) to use as the TransitionHook context(s)\n * - For each of the [[PathNode]]s, creates a TransitionHook\n *\n * @param hookType the type of the hook registration function, e.g., 'onEnter', 'onFinish'.\n */\n buildHooks(hookType: TransitionEventType): TransitionHook[] {\n const transition = this.transition;\n const treeChanges = transition.treeChanges();\n\n // Find all the matching registered hooks for a given hook type\n const matchingHooks = this.getMatchingHooks(hookType, treeChanges);\n if (!matchingHooks) return [];\n\n const baseHookOptions = {\n transition: transition,\n current: transition.options().current,\n };\n\n const makeTransitionHooks = (hook: RegisteredHook) => {\n // Fetch the Nodes that caused this hook to match.\n const matches: IMatchingNodes = hook.matches(treeChanges);\n // Select the PathNode[] that will be used as TransitionHook context objects\n const matchingNodes: PathNode[] = matches[hookType.criteriaMatchPath.name];\n\n // Return an array of HookTuples\n return matchingNodes.map(node => {\n const _options = extend(\n {\n bind: hook.bind,\n traceData: { hookType: hookType.name, context: node },\n },\n baseHookOptions,\n );\n\n const state = hookType.criteriaMatchPath.scope === TransitionHookScope.STATE ? node.state.self : null;\n const transitionHook = new TransitionHook(transition, state, hook, _options);\n return { hook, node, transitionHook };\n });\n };\n\n return matchingHooks\n .map(makeTransitionHooks)\n .reduce(unnestR, [])\n .sort(tupleSort(hookType.reverseSort))\n .map(tuple => tuple.transitionHook);\n }\n\n /**\n * Finds all RegisteredHooks from:\n * - The Transition object instance hook registry\n * - The TransitionService ($transitions) global hook registry\n *\n * which matched:\n * - the eventType\n * - the matchCriteria (to, from, exiting, retained, entering)\n *\n * @returns an array of matched [[RegisteredHook]]s\n */\n public getMatchingHooks(hookType: TransitionEventType, treeChanges: TreeChanges): RegisteredHook[] {\n const isCreate = hookType.hookPhase === TransitionHookPhase.CREATE;\n\n // Instance and Global hook registries\n const $transitions = this.transition.router.transitionService;\n const registries = isCreate ? [$transitions] : [this.transition, $transitions];\n\n return registries\n .map((reg: IHookRegistry) => reg.getHooks(hookType.name)) // Get named hooks from registries\n .filter(assertPredicate(isArray, `broken event named: ${hookType.name}`)) // Sanity check\n .reduce(unnestR, []) // Un-nest RegisteredHook[][] to RegisteredHook[] array\n .filter(hook => hook.matches(treeChanges)); // Only those satisfying matchCriteria\n }\n}\n\ninterface HookTuple {\n hook: RegisteredHook;\n node: PathNode;\n transitionHook: TransitionHook;\n}\n\n/**\n * A factory for a sort function for HookTuples.\n *\n * The sort function first compares the PathNode depth (how deep in the state tree a node is), then compares\n * the EventHook priority.\n *\n * @param reverseDepthSort a boolean, when true, reverses the sort order for the node depth\n * @returns a tuple sort function\n */\nfunction tupleSort(reverseDepthSort = false) {\n return function nodeDepthThenPriority(l: HookTuple, r: HookTuple): number {\n const factor = reverseDepthSort ? -1 : 1;\n const depthDelta = (l.node.state.path.length - r.node.state.path.length) * factor;\n return depthDelta !== 0 ? depthDelta : r.hook.priority - l.hook.priority;\n };\n}\n", + "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, filter, map } from '../common/common';\nimport { isArray, isDefined } from '../common/predicates';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * An internal class which implements [[ParamTypeDefinition]].\n *\n * A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types.\n * When a param type definition is registered, an instance of this class is created internally.\n *\n * This class has naive implementations for all the [[ParamTypeDefinition]] methods.\n *\n * Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values.\n *\n * #### Example:\n * ```js\n * var paramTypeDef = {\n * decode: function(val) { return parseInt(val, 10); },\n * encode: function(val) { return val && val.toString(); },\n * equals: function(a, b) { return this.is(a) && a === b; },\n * is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; },\n * pattern: /\\d+/\n * }\n *\n * var paramType = new ParamType(paramTypeDef);\n * ```\n * @internalapi\n */\nexport class ParamType implements ParamTypeDefinition {\n /** @inheritdoc */\n pattern: RegExp = /.*/;\n /** The name/id of the parameter type */\n name: string;\n /** @inheritdoc */\n raw: boolean;\n /** @inheritdoc */\n dynamic: boolean;\n /** @inheritdoc */\n inherit = true;\n\n /**\n * @param def A configuration object which contains the custom type definition. The object's\n * properties will override the default methods and/or pattern in `ParamType`'s public interface.\n * @returns a new ParamType object\n */\n constructor(def: ParamTypeDefinition) {\n extend(this, def);\n }\n\n // consider these four methods to be \"abstract methods\" that should be overridden\n /** @inheritdoc */\n is(val: any, key?: string): boolean {\n return true;\n }\n /** @inheritdoc */\n encode(val: any, key?: string): string | string[] {\n return val;\n }\n /** @inheritdoc */\n decode(val: string, key?: string): any {\n return val;\n }\n /** @inheritdoc */\n equals(a: any, b: any): boolean {\n // tslint:disable-next-line:triple-equals\n return a == b;\n }\n\n $subPattern() {\n const sub = this.pattern.toString();\n return sub.substr(1, sub.length - 2);\n }\n\n toString() {\n return `{ParamType:${this.name}}`;\n }\n\n /** Given an encoded string, or a decoded object, returns a decoded object */\n $normalize(val: any) {\n return this.is(val) ? val : this.decode(val);\n }\n\n /**\n * Wraps an existing custom ParamType as an array of ParamType, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\n $asArray(mode: boolean | 'auto', isSearch: boolean) {\n if (!mode) return this;\n if (mode === 'auto' && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n return new (ArrayType)(this, mode);\n }\n}\n\n/**\n * Wraps up a `ParamType` object to handle array values.\n * @internalapi\n */\nfunction ArrayType(type: ParamType, mode: boolean | 'auto') {\n // Wrap non-array value as array\n function arrayWrap(val: any): any[] {\n return isArray(val) ? val : isDefined(val) ? [val] : [];\n }\n\n // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n function arrayUnwrap(val: any) {\n switch (val.length) {\n case 0:\n return undefined;\n case 1:\n return mode === 'auto' ? val[0] : val;\n default:\n return val;\n }\n }\n\n // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n function arrayHandler(callback: (x: any) => any, allTruthyMode?: boolean) {\n return function handleArray(val: any) {\n if (isArray(val) && val.length === 0) return val;\n const arr = arrayWrap(val);\n const result = map(arr, callback);\n return allTruthyMode === true ? filter(result, x => !x).length === 0 : arrayUnwrap(result);\n };\n }\n\n // Wraps type (.equals) functions to operate on each value of an array\n function arrayEqualsHandler(callback: (l: any, r: any) => boolean) {\n return function handleArray(val1: any, val2: any) {\n const left = arrayWrap(val1),\n right = arrayWrap(val2);\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!callback(left[i], right[i])) return false;\n }\n return true;\n };\n }\n\n ['encode', 'decode', 'equals', '$normalize'].forEach(name => {\n const paramTypeFn = type[name].bind(type);\n const wrapperFn: Function = name === 'equals' ? arrayEqualsHandler : arrayHandler;\n this[name] = wrapperFn(paramTypeFn);\n });\n\n extend(this, {\n dynamic: type.dynamic,\n name: type.name,\n pattern: type.pattern,\n inherit: type.inherit,\n is: arrayHandler(type.is.bind(type), true),\n $arrayMode: mode,\n });\n}\n", + "/**\n * @coreapi\n * @module params\n */ /** for typedoc */\nimport { extend, filter, map, allTrueR } from '../common/common';\nimport { prop } from '../common/hof';\nimport { isInjectable, isDefined, isString, isArray, isUndefined } from '../common/predicates';\nimport { RawParams, ParamDeclaration } from '../params/interface';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypes } from './paramTypes';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\n\n/** @hidden */\nconst hasOwn = Object.prototype.hasOwnProperty;\n\n/** @hidden */\nconst isShorthand = (cfg: ParamDeclaration) =>\n ['value', 'type', 'squash', 'array', 'dynamic'].filter(hasOwn.bind(cfg || {})).length === 0;\n\n/** @internalapi */\nenum DefType {\n PATH,\n SEARCH,\n CONFIG,\n}\nexport { DefType };\n\n/** @hidden */\nfunction unwrapShorthand(cfg: ParamDeclaration): ParamDeclaration {\n cfg = (isShorthand(cfg) && ({ value: cfg } as any)) || cfg;\n\n getStaticDefaultValue['__cacheable'] = true;\n function getStaticDefaultValue() {\n return cfg.value;\n }\n\n return extend(cfg, {\n $$fn: isInjectable(cfg.value) ? cfg.value : getStaticDefaultValue,\n });\n}\n\n/** @hidden */\nfunction getType(cfg: ParamDeclaration, urlType: ParamType, location: DefType, id: string, paramTypes: ParamTypes) {\n if (cfg.type && urlType && urlType.name !== 'string') throw new Error(`Param '${id}' has two type configurations.`);\n if (cfg.type && urlType && urlType.name === 'string' && paramTypes.type(cfg.type as string))\n return paramTypes.type(cfg.type as string);\n if (urlType) return urlType;\n if (!cfg.type) {\n const type =\n location === DefType.CONFIG\n ? 'any'\n : location === DefType.PATH\n ? 'path'\n : location === DefType.SEARCH\n ? 'query'\n : 'string';\n return paramTypes.type(type);\n }\n return cfg.type instanceof ParamType ? cfg.type : paramTypes.type(cfg.type as string);\n}\n\n/**\n * @internalapi\n * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n */\nfunction getSquashPolicy(config: ParamDeclaration, isOptional: boolean, defaultPolicy: boolean | string) {\n const squash = config.squash;\n if (!isOptional || squash === false) return false;\n if (!isDefined(squash) || squash == null) return defaultPolicy;\n if (squash === true || isString(squash)) return squash;\n throw new Error(`Invalid squash policy: '${squash}'. Valid policies: false, true, or arbitrary string`);\n}\n\n/** @internalapi */\nfunction getReplace(config: ParamDeclaration, arrayMode: boolean, isOptional: boolean, squash: string | boolean) {\n const defaultPolicy = [\n { from: '', to: isOptional || arrayMode ? undefined : '' },\n { from: null, to: isOptional || arrayMode ? undefined : '' },\n ];\n\n const replace = isArray(config.replace) ? config.replace : [];\n if (isString(squash)) replace.push({ from: squash, to: undefined });\n\n const configuredKeys = map(replace, prop('from'));\n return filter(defaultPolicy, item => configuredKeys.indexOf(item.from) === -1).concat(replace);\n}\n\n/** @internalapi */\nexport class Param {\n id: string;\n type: ParamType;\n location: DefType;\n isOptional: boolean;\n dynamic: boolean;\n raw: boolean;\n squash: boolean | string;\n replace: [{ to: any; from: any }];\n inherit: boolean;\n array: boolean;\n config: any;\n /** Cache the default value if it is a static value */\n _defaultValueCache: {\n defaultValue: any;\n };\n\n static values(params: Param[], values: RawParams = {}): RawParams {\n const paramValues = {} as RawParams;\n for (const param of params) {\n paramValues[param.id] = param.value(values[param.id]);\n }\n return paramValues;\n }\n\n /**\n * Finds [[Param]] objects which have different param values\n *\n * Filters a list of [[Param]] objects to only those whose parameter values differ in two param value objects\n *\n * @param params: The list of Param objects to filter\n * @param values1: The first set of parameter values\n * @param values2: the second set of parameter values\n *\n * @returns any Param objects whose values were different between values1 and values2\n */\n static changed(params: Param[], values1: RawParams = {}, values2: RawParams = {}): Param[] {\n return params.filter(param => !param.type.equals(values1[param.id], values2[param.id]));\n }\n\n /**\n * Checks if two param value objects are equal (for a set of [[Param]] objects)\n *\n * @param params The list of [[Param]] objects to check\n * @param values1 The first set of param values\n * @param values2 The second set of param values\n *\n * @returns true if the param values in values1 and values2 are equal\n */\n static equals(params: Param[], values1 = {}, values2 = {}): boolean {\n return Param.changed(params, values1, values2).length === 0;\n }\n\n /** Returns true if a the parameter values are valid, according to the Param definitions */\n static validates(params: Param[], values: RawParams = {}): boolean {\n return params.map(param => param.validates(values[param.id])).reduce(allTrueR, true);\n }\n\n constructor(\n id: string,\n type: ParamType,\n config: ParamDeclaration,\n location: DefType,\n urlMatcherFactory: UrlMatcherFactory,\n ) {\n config = unwrapShorthand(config);\n type = getType(config, type, location, id, urlMatcherFactory.paramTypes);\n const arrayMode = getArrayMode();\n type = arrayMode ? type.$asArray(arrayMode, location === DefType.SEARCH) : type;\n const isOptional = config.value !== undefined || location === DefType.SEARCH;\n const dynamic = isDefined(config.dynamic) ? !!config.dynamic : !!type.dynamic;\n const raw = isDefined(config.raw) ? !!config.raw : !!type.raw;\n const squash = getSquashPolicy(config, isOptional, urlMatcherFactory.defaultSquashPolicy());\n const replace = getReplace(config, arrayMode, isOptional, squash);\n const inherit = isDefined(config.inherit) ? !!config.inherit : !!type.inherit;\n\n // array config: param name (param[]) overrides default settings. explicit config overrides param name.\n function getArrayMode() {\n const arrayDefaults = { array: location === DefType.SEARCH ? 'auto' : false };\n const arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n return extend(arrayDefaults, arrayParamNomenclature, config).array;\n }\n\n extend(this, { id, type, location, isOptional, dynamic, raw, squash, replace, inherit, array: arrayMode, config });\n }\n\n isDefaultValue(value: any): boolean {\n return this.isOptional && this.type.equals(this.value(), value);\n }\n\n /**\n * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n * default value, which may be the result of an injectable function.\n */\n value(value?: any): any {\n /**\n * [Internal] Get the default value of a parameter, which may be an injectable function.\n */\n const getDefaultValue = () => {\n if (this._defaultValueCache) return this._defaultValueCache.defaultValue;\n\n if (!services.$injector) throw new Error('Injectable functions cannot be called at configuration time');\n\n const defaultValue = services.$injector.invoke(this.config.$$fn);\n\n if (defaultValue !== null && defaultValue !== undefined && !this.type.is(defaultValue))\n throw new Error(\n `Default value (${defaultValue}) for parameter '${this.id}' is not an instance of ParamType (${\n this.type.name\n })`,\n );\n\n if (this.config.$$fn['__cacheable']) {\n this._defaultValueCache = { defaultValue };\n }\n\n return defaultValue;\n };\n\n const replaceSpecialValues = (val: any) => {\n for (const tuple of this.replace) {\n if (tuple.from === val) return tuple.to;\n }\n return val;\n };\n\n value = replaceSpecialValues(value);\n\n return isUndefined(value) ? getDefaultValue() : this.type.$normalize(value);\n }\n\n isSearch(): boolean {\n return this.location === DefType.SEARCH;\n }\n\n validates(value: any): boolean {\n // There was no parameter value, but the param is optional\n if ((isUndefined(value) || value === null) && this.isOptional) return true;\n\n // The value was not of the correct ParamType, and could not be decoded to the correct ParamType\n const normalized = this.type.$normalize(value);\n if (!this.type.is(normalized)) return false;\n\n // The value was of the correct type, but when encoded, did not match the ParamType's regexp\n const encoded = this.type.encode(normalized);\n return !(isString(encoded) && !this.type.pattern.exec(encoded));\n }\n\n toString() {\n return `{Param:${this.id} ${this.type} squash: '${this.squash}' optional: ${this.isOptional}}`;\n }\n}\n", + "/** @module path */ /** for typedoc */\nimport { extend, applyPairs, find, allTrueR, pairs, arrayTuples } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\n\n/**\n * @internalapi\n *\n * A node in a [[TreeChanges]] path\n *\n * For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path.\n * Each PathNode corresponds to a state being entered, exited, or retained.\n * The stateful information includes parameter values and resolve data.\n */\nexport class PathNode {\n /** The state being entered, exited, or retained */\n public state: StateObject;\n /** The parameters declared on the state */\n public paramSchema: Param[];\n /** The parameter values that belong to the state */\n public paramValues: { [key: string]: any };\n /** The individual (stateful) resolvable objects that belong to the state */\n public resolvables: Resolvable[];\n /** The state's declared view configuration objects */\n public views: ViewConfig[];\n\n /**\n * Returns a clone of the PathNode\n * @deprecated use instance method `node.clone()`\n */\n static clone = (node: PathNode) => node.clone();\n\n /** Creates a copy of a PathNode */\n constructor(node: PathNode);\n /** Creates a new (empty) PathNode for a State */\n constructor(state: StateObject);\n constructor(stateOrNode: any) {\n if (stateOrNode instanceof PathNode) {\n const node: PathNode = stateOrNode;\n this.state = node.state;\n this.paramSchema = node.paramSchema.slice();\n this.paramValues = extend({}, node.paramValues);\n this.resolvables = node.resolvables.slice();\n this.views = node.views && node.views.slice();\n } else {\n const state: StateObject = stateOrNode;\n this.state = state;\n this.paramSchema = state.parameters({ inherit: false });\n this.paramValues = {};\n this.resolvables = state.resolvables.map(res => res.clone());\n }\n }\n\n clone() {\n return new PathNode(this);\n }\n\n /** Sets [[paramValues]] for the node, from the values of an object hash */\n applyRawParams(params: RawParams): PathNode {\n const getParamVal = (paramDef: Param) => [paramDef.id, paramDef.value(params[paramDef.id])];\n this.paramValues = this.paramSchema.reduce((memo, pDef) => applyPairs(memo, getParamVal(pDef)), {});\n return this;\n }\n\n /** Gets a specific [[Param]] metadata that belongs to the node */\n parameter(name: string): Param {\n return find(this.paramSchema, propEq('id', name));\n }\n\n /**\n * @returns true if the state and parameter values for another PathNode are\n * equal to the state and param values for this PathNode\n */\n equals(node: PathNode, paramsFn?: GetParamsFn): boolean {\n const diff = this.diff(node, paramsFn);\n return diff && diff.length === 0;\n }\n\n /**\n * Finds Params with different parameter values on another PathNode.\n *\n * Given another node (of the same state), finds the parameter values which differ.\n * Returns the [[Param]] (schema objects) whose parameter values differ.\n *\n * Given another node for a different state, returns `false`\n *\n * @param node The node to compare to\n * @param paramsFn A function that returns which parameters should be compared.\n * @returns The [[Param]]s which differ, or null if the two nodes are for different states\n */\n diff(node: PathNode, paramsFn?: GetParamsFn): Param[] | false {\n if (this.state !== node.state) return false;\n\n const params: Param[] = paramsFn ? paramsFn(this) : this.paramSchema;\n return Param.changed(params, this.paramValues, node.paramValues);\n }\n}\n\n/** @hidden */\nexport type GetParamsFn = (pathNode: PathNode) => Param[];\n", + "/** @module path */ /** for typedoc */\n\nimport {\n extend,\n find,\n pick,\n omit,\n tail,\n mergeR,\n values,\n unnestR,\n Predicate,\n inArray,\n arrayTuples,\n} from '../common/common';\nimport { prop, propEq, not } from '../common/hof';\n\nimport { RawParams } from '../params/interface';\nimport { TreeChanges } from '../transition/interface';\nimport { ViewConfig } from '../view/interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { GetParamsFn, PathNode } from './pathNode';\nimport { ViewService } from '../view/view';\nimport { Param } from '../params/param';\nimport { StateRegistry } from '../state';\n\n/**\n * This class contains functions which convert TargetStates, Nodes and paths from one type to another.\n */\nexport class PathUtils {\n /** Given a PathNode[], create an TargetState */\n static makeTargetState(registry: StateRegistry, path: PathNode[]): TargetState {\n const state = tail(path).state;\n return new TargetState(registry, state, path.map(prop('paramValues')).reduce(mergeR, {}), {});\n }\n\n static buildPath(targetState: TargetState) {\n const toParams = targetState.params();\n return targetState.$state().path.map(state => new PathNode(state).applyRawParams(toParams));\n }\n\n /** Given a fromPath: PathNode[] and a TargetState, builds a toPath: PathNode[] */\n static buildToPath(fromPath: PathNode[], targetState: TargetState): PathNode[] {\n const toPath: PathNode[] = PathUtils.buildPath(targetState);\n if (targetState.options().inherit) {\n return PathUtils.inheritParams(fromPath, toPath, Object.keys(targetState.params()));\n }\n return toPath;\n }\n\n /**\n * Creates ViewConfig objects and adds to nodes.\n *\n * On each [[PathNode]], creates ViewConfig objects from the views: property of the node's state\n */\n static applyViewConfigs($view: ViewService, path: PathNode[], states: StateObject[]) {\n // Only apply the viewConfigs to the nodes for the given states\n path.filter(node => inArray(states, node.state)).forEach(node => {\n const viewDecls: _ViewDeclaration[] = values(node.state.views || {});\n const subPath = PathUtils.subPath(path, n => n === node);\n const viewConfigs: ViewConfig[][] = viewDecls.map(view => $view.createViewConfig(subPath, view));\n node.views = viewConfigs.reduce(unnestR, []);\n });\n }\n\n /**\n * Given a fromPath and a toPath, returns a new to path which inherits parameters from the fromPath\n *\n * For a parameter in a node to be inherited from the from path:\n * - The toPath's node must have a matching node in the fromPath (by state).\n * - The parameter name must not be found in the toKeys parameter array.\n *\n * Note: the keys provided in toKeys are intended to be those param keys explicitly specified by some\n * caller, for instance, $state.transitionTo(..., toParams). If a key was found in toParams,\n * it is not inherited from the fromPath.\n */\n static inheritParams(fromPath: PathNode[], toPath: PathNode[], toKeys: string[] = []): PathNode[] {\n function nodeParamVals(path: PathNode[], state: StateObject): RawParams {\n const node: PathNode = find(path, propEq('state', state));\n return extend({}, node && node.paramValues);\n }\n\n const noInherit = fromPath\n .map(node => node.paramSchema)\n .reduce(unnestR, [])\n .filter(param => !param.inherit)\n .map(prop('id'));\n\n /**\n * Given an [[PathNode]] \"toNode\", return a new [[PathNode]] with param values inherited from the\n * matching node in fromPath. Only inherit keys that aren't found in \"toKeys\" from the node in \"fromPath\"\"\n */\n function makeInheritedParamsNode(toNode: PathNode): PathNode {\n // All param values for the node (may include default key/vals, when key was not found in toParams)\n let toParamVals = extend({}, toNode && toNode.paramValues);\n // limited to only those keys found in toParams\n const incomingParamVals = pick(toParamVals, toKeys);\n toParamVals = omit(toParamVals, toKeys);\n const fromParamVals = omit(nodeParamVals(fromPath, toNode.state) || {}, noInherit);\n // extend toParamVals with any fromParamVals, then override any of those those with incomingParamVals\n const ownParamVals: RawParams = extend(toParamVals, fromParamVals, incomingParamVals);\n return new PathNode(toNode.state).applyRawParams(ownParamVals);\n }\n\n // The param keys specified by the incoming toParams\n return toPath.map(makeInheritedParamsNode);\n }\n\n static nonDynamicParams = (node: PathNode): Param[] =>\n node.state.parameters({ inherit: false }).filter(param => !param.dynamic);\n\n /**\n * Computes the tree changes (entering, exiting) between a fromPath and toPath.\n */\n static treeChanges(fromPath: PathNode[], toPath: PathNode[], reloadState: StateObject): TreeChanges {\n const max = Math.min(fromPath.length, toPath.length);\n let keep = 0;\n\n const nodesMatch = (node1: PathNode, node2: PathNode) => node1.equals(node2, PathUtils.nonDynamicParams);\n\n while (keep < max && fromPath[keep].state !== reloadState && nodesMatch(fromPath[keep], toPath[keep])) {\n keep++;\n }\n\n /** Given a retained node, return a new node which uses the to node's param values */\n function applyToParams(retainedNode: PathNode, idx: number): PathNode {\n const cloned = retainedNode.clone();\n cloned.paramValues = toPath[idx].paramValues;\n return cloned;\n }\n\n let from: PathNode[], retained: PathNode[], exiting: PathNode[], entering: PathNode[], to: PathNode[];\n\n from = fromPath;\n retained = from.slice(0, keep);\n exiting = from.slice(keep);\n\n // Create a new retained path (with shallow copies of nodes) which have the params of the toPath mapped\n const retainedWithToParams = retained.map(applyToParams);\n entering = toPath.slice(keep);\n to = retainedWithToParams.concat(entering);\n\n return { from, to, retained, retainedWithToParams, exiting, entering };\n }\n\n /**\n * Returns a new path which is: the subpath of the first path which matches the second path.\n *\n * The new path starts from root and contains any nodes that match the nodes in the second path.\n * It stops before the first non-matching node.\n *\n * Nodes are compared using their state property and their parameter values.\n * If a `paramsFn` is provided, only the [[Param]] returned by the function will be considered when comparing nodes.\n *\n * @param pathA the first path\n * @param pathB the second path\n * @param paramsFn a function which returns the parameters to consider when comparing\n *\n * @returns an array of PathNodes from the first path which match the nodes in the second path\n */\n static matching(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): PathNode[] {\n let done = false;\n const tuples: PathNode[][] = arrayTuples(pathA, pathB);\n return tuples.reduce((matching, [nodeA, nodeB]) => {\n done = done || !nodeA.equals(nodeB, paramsFn);\n return done ? matching : matching.concat(nodeA);\n }, []);\n }\n\n /**\n * Returns true if two paths are identical.\n *\n * @param pathA\n * @param pathB\n * @param paramsFn a function which returns the parameters to consider when comparing\n * @returns true if the the states and parameter values for both paths are identical\n */\n static equals(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): boolean {\n return pathA.length === pathB.length && PathUtils.matching(pathA, pathB, paramsFn).length === pathA.length;\n }\n\n /**\n * Return a subpath of a path, which stops at the first matching node\n *\n * Given an array of nodes, returns a subset of the array starting from the first node,\n * stopping when the first node matches the predicate.\n *\n * @param path a path of [[PathNode]]s\n * @param predicate a [[Predicate]] fn that matches [[PathNode]]s\n * @returns a subpath up to the matching node, or undefined if no match is found\n */\n static subPath(path: PathNode[], predicate: Predicate): PathNode[] {\n const node = find(path, predicate);\n const elementIdx = path.indexOf(node);\n return elementIdx === -1 ? undefined : path.slice(0, elementIdx + 1);\n }\n\n /** Gets the raw parameter values from a path */\n static paramValues = (path: PathNode[]) => path.reduce((acc, node) => extend(acc, node.paramValues), {});\n}\n", + "/**\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { extend, equals, inArray, identity } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { trace } from '../common/trace';\nimport { ResolvePolicy, ResolvableLiteral, resolvePolicies } from './interface';\n\nimport { ResolveContext } from './resolveContext';\nimport { stringify } from '../common/strings';\nimport { isFunction, isObject } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { isNullOrUndefined } from '../common/predicates';\n\n// TODO: explicitly make this user configurable\nexport let defaultResolvePolicy: ResolvePolicy = {\n when: 'LAZY',\n async: 'WAIT',\n};\n\n/**\n * The basic building block for the resolve system.\n *\n * Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise),\n * and the unwrapped-when-complete (.data) result of the resolveFn.\n *\n * Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the\n * resolveFn) and returns the resulting promise.\n *\n * Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first\n * parameter to those fns.\n */\nexport class Resolvable implements ResolvableLiteral {\n token: any;\n policy: ResolvePolicy;\n resolveFn: Function;\n deps: any[];\n\n data: any;\n resolved = false;\n promise: Promise = undefined;\n\n static fromData = (token: any, data: any) => new Resolvable(token, () => data, null, null, data);\n\n /** This constructor creates a Resolvable copy */\n constructor(resolvable: Resolvable);\n\n /** This constructor creates a new Resolvable from the plain old [[ResolvableLiteral]] javascript object */\n constructor(resolvable: ResolvableLiteral);\n\n /**\n * This constructor creates a new `Resolvable`\n *\n * #### Example:\n * ```js\n * var resolvable1 = new Resolvable('mytoken', http => http.get('foo.json').toPromise(), [Http]);\n *\n * var resolvable2 = new Resolvable(UserService, dep => new UserService(dep.data), [SomeDependency]);\n *\n * var resolvable1Clone = new Resolvable(resolvable1);\n * ```\n *\n * @param token The new resolvable's injection token, such as `\"userList\"` (a string) or `UserService` (a class).\n * When this token is used during injection, the resolved value will be injected.\n * @param resolveFn The function that returns the resolved value, or a promise for the resolved value\n * @param deps An array of dependencies, which will be injected into the `resolveFn`\n * @param policy the [[ResolvePolicy]] defines when and how the Resolvable is processed\n * @param data Pre-resolved data. If the resolve value is already known, it may be provided here.\n */\n constructor(token: any, resolveFn: Function, deps?: any[], policy?: ResolvePolicy, data?: any);\n constructor(arg1: any, resolveFn?: Function, deps?: any[], policy?: ResolvePolicy, data?: any) {\n if (arg1 instanceof Resolvable) {\n extend(this, arg1);\n } else if (isFunction(resolveFn)) {\n if (isNullOrUndefined(arg1)) throw new Error('new Resolvable(): token argument is required');\n if (!isFunction(resolveFn)) throw new Error('new Resolvable(): resolveFn argument must be a function');\n\n this.token = arg1;\n this.policy = policy;\n this.resolveFn = resolveFn;\n this.deps = deps || [];\n\n this.data = data;\n this.resolved = data !== undefined;\n this.promise = this.resolved ? services.$q.when(this.data) : undefined;\n } else if (isObject(arg1) && arg1.token && (arg1.hasOwnProperty('resolveFn') || arg1.hasOwnProperty('data'))) {\n const literal = arg1;\n return new Resolvable(literal.token, literal.resolveFn, literal.deps, literal.policy, literal.data);\n }\n }\n\n getPolicy(state: StateObject): ResolvePolicy {\n const thisPolicy = this.policy || {};\n const statePolicy = (state && state.resolvePolicy) || {};\n return {\n when: thisPolicy.when || statePolicy.when || defaultResolvePolicy.when,\n async: thisPolicy.async || statePolicy.async || defaultResolvePolicy.async,\n };\n }\n\n /**\n * Asynchronously resolve this Resolvable's data\n *\n * Given a ResolveContext that this Resolvable is found in:\n * Wait for this Resolvable's dependencies, then invoke this Resolvable's function\n * and update the Resolvable's state\n */\n resolve(resolveContext: ResolveContext, trans?: Transition) {\n const $q = services.$q;\n\n // Gets all dependencies from ResolveContext and wait for them to be resolved\n const getResolvableDependencies = () =>\n $q.all(resolveContext.getDependencies(this).map(resolvable => resolvable.get(resolveContext, trans))) as Promise<\n any[]\n >;\n\n // Invokes the resolve function passing the resolved dependencies as arguments\n const invokeResolveFn = (resolvedDeps: any[]) => this.resolveFn.apply(null, resolvedDeps);\n\n /**\n * For RXWAIT policy:\n *\n * Given an observable returned from a resolve function:\n * - enables .cache() mode (this allows multicast subscribers)\n * - then calls toPromise() (this triggers subscribe() and thus fetches)\n * - Waits for the promise, then return the cached observable (not the first emitted value).\n */\n const waitForRx = (observable$: any) => {\n const cached = observable$.cache(1);\n return cached\n .take(1)\n .toPromise()\n .then(() => cached);\n };\n\n // If the resolve policy is RXWAIT, wait for the observable to emit something. otherwise pass through.\n const node: PathNode = resolveContext.findNode(this);\n const state: StateObject = node && node.state;\n const maybeWaitForRx = this.getPolicy(state).async === 'RXWAIT' ? waitForRx : identity;\n\n // After the final value has been resolved, update the state of the Resolvable\n const applyResolvedValue = (resolvedValue: any) => {\n this.data = resolvedValue;\n this.resolved = true;\n this.resolveFn = null;\n trace.traceResolvableResolved(this, trans);\n return this.data;\n };\n\n // Sets the promise property first, then getsResolvableDependencies in the context of the promise chain. Always waits one tick.\n return (this.promise = $q\n .when()\n .then(getResolvableDependencies)\n .then(invokeResolveFn)\n .then(maybeWaitForRx)\n .then(applyResolvedValue));\n }\n\n /**\n * Gets a promise for this Resolvable's data.\n *\n * Fetches the data and returns a promise.\n * Returns the existing promise if it has already been fetched once.\n */\n get(resolveContext: ResolveContext, trans?: Transition): Promise {\n return this.promise || this.resolve(resolveContext, trans);\n }\n\n toString() {\n return `Resolvable(token: ${stringify(this.token)}, requires: [${this.deps.map(stringify)}])`;\n }\n\n clone(): Resolvable {\n return new Resolvable(this);\n }\n}\n", + "/**\n * # The Resolve subsystem\n *\n * This subsystem is an asynchronous, hierarchical Dependency Injection system.\n *\n * Typically, resolve is configured on a state using a [[StateDeclaration.resolve]] declaration.\n *\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { Resolvable } from './resolvable';\n\n/**\n * An interface which is similar to an Angular 2 `Provider`\n */\nexport interface ProviderLike {\n provide: any;\n useClass?: any;\n useFactory?: Function;\n useValue?: any;\n useExisting?: any;\n deps?: any[];\n}\n\n/**\n * A plain object used to describe a [[Resolvable]]\n *\n * These objects may be used in the [[StateDeclaration.resolve]] array to declare\n * async data that the state or substates require.\n *\n * #### Example:\n * ```js\n *\n * var state = {\n * name: 'main',\n * resolve: [\n * { token: 'myData', deps: [MyDataApi], resolveFn: (myDataApi) => myDataApi.getData() },\n * ],\n * }\n * ```\n */\nexport interface ResolvableLiteral {\n /**\n * A Dependency Injection token\n *\n * This Resolvable's DI token.\n * The Resolvable will be injectable elsewhere using the token.\n */\n token: any;\n\n /**\n * A function which fetches the Resolvable's data\n *\n * A function which returns one of:\n *\n * - The resolved value (synchronously)\n * - A promise for the resolved value\n * - An Observable of the resolved value(s)\n *\n * This function will be provided the dependencies listed in [[deps]] as its arguments.\n * The resolve system will asynchronously fetch the dependencies before invoking this function.\n */\n resolveFn: Function;\n\n /**\n * Defines the Resolve Policy\n *\n * A policy that defines when to invoke the resolve,\n * and whether to wait for async and unwrap the data\n */\n policy?: ResolvePolicy;\n\n /**\n * The Dependency Injection tokens\n *\n * This is an array of Dependency Injection tokens for the dependencies of the [[resolveFn]].\n *\n * The DI tokens are references to other `Resolvables`, or to other\n * services from the native DI system.\n */\n deps?: any[];\n\n /** Pre-resolved data. */\n data?: any;\n}\n\n/**\n * Defines how a resolve is processed during a transition\n *\n * This object is the [[StateDeclaration.resolvePolicy]] property.\n *\n * #### Example:\n * ```js\n * // Fetched when the resolve's state is being entered.\n * // Wait for the promise to resolve.\n * var policy1 = { when: \"LAZY\", async: \"WAIT\" }\n *\n * // Fetched when the Transition is starting.\n * // Do not wait for the returned promise to resolve.\n * // Inject the raw promise/value\n * var policy2 = { when: \"EAGER\", async: \"NOWAIT\" }\n * ```\n *\n * The policy for a given Resolvable is merged from three sources (highest priority first):\n *\n * - 1) Individual resolve definition\n * - 2) State definition\n * - 3) Global default\n *\n * #### Example:\n * ```js\n * // Wait for an Observable to emit one item.\n * // Since `wait` is not specified, it uses the `wait`\n * // policy defined on the state, or the global default\n * // if no `wait` policy is defined on the state\n * var myResolvablePolicy = { async: \"RXWAIT\" }\n * ```\n */\nexport interface ResolvePolicy {\n /**\n * Defines when a Resolvable is resolved (fetched) during a transition\n *\n * - `LAZY` (default)\n * - Resolved as the resolve's state is being entered\n * - `EAGER`\n * - Resolved as the transition is starting\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched when each state is entered.\n * All of `main` resolves are processed before fetching `main.home` resolves.\n * ```js\n * var state = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n *\n * var state = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n * ```\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched at the same time when the transition starts.\n * This happens earlier in the lifecycle than when states are entered.\n * All of the `main` and `main.home` resolves are fetched as soon as possible.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n *\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n * ```\n */\n when?: PolicyWhen;\n\n /**\n * Determines the unwrapping behavior of asynchronous resolve values.\n *\n * - `WAIT` (default)\n * - If a promise is returned from the resolveFn, wait for the promise before proceeding\n * - The unwrapped value from the promise\n * - `NOWAIT`\n * - If a promise is returned from the resolve, do not wait for the promise.\n * - Any other value returned is wrapped in a promise.\n * - The promise will not be unwrapped.\n * - The promise itself will be provided when the resolve is injected or bound elsewhere.\n * - `RXWAIT`\n * - When an Observable is returned from the resolveFn, wait until the Observable emits at least one item.\n * - The Observable item will not be unwrapped.\n * - The Observable stream itself will be provided when the resolve is injected or bound elsewhere.\n *\n * #### Example:\n * The `Transition` will not wait for the resolve promise(s) from `main` to settle before continuing.\n * Resolves for `main` will be provided to components wrapped in a `Promise`.\n *\n * The `Transition` will wait for the `main.home` resolve promises.\n * Resolved values will be unwrapped before being provided to components.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { async: 'NOWAIT' },\n * }\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { async: 'WAIT' }, // default\n * }\n * ```\n */\n async?: PolicyAsync;\n}\n\nexport type PolicyWhen = 'LAZY' | 'EAGER';\nexport type PolicyAsync = 'WAIT' | 'NOWAIT' | 'RXWAIT';\n\n/** @internalapi */\nexport let resolvePolicies = {\n when: {\n LAZY: 'LAZY',\n EAGER: 'EAGER',\n },\n async: {\n WAIT: 'WAIT',\n NOWAIT: 'NOWAIT',\n RXWAIT: 'RXWAIT',\n },\n};\n", + "/** @module resolve */\n/** for typedoc */\nimport { find, tail, uniqR, unnestR, inArray } from '../common/common';\nimport { propEq, not } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services, $InjectorLike } from '../common/coreservices';\nimport { resolvePolicies, PolicyWhen, ResolvePolicy } from './interface';\nimport { PathNode } from '../path/pathNode';\nimport { Resolvable } from './resolvable';\nimport { StateObject } from '../state/stateObject';\nimport { PathUtils } from '../path/pathUtils';\nimport { stringify } from '../common/strings';\nimport { Transition } from '../transition/transition';\nimport { UIInjector } from '../interface';\nimport { isUndefined } from '../common';\n\nconst whens = resolvePolicies.when;\nconst ALL_WHENS = [whens.EAGER, whens.LAZY];\nconst EAGER_WHENS = [whens.EAGER];\n\n// tslint:disable-next-line:no-inferrable-types\nexport const NATIVE_INJECTOR_TOKEN: string = 'Native Injector';\n\n/**\n * Encapsulates Dependency Injection for a path of nodes\n *\n * UI-Router states are organized as a tree.\n * A nested state has a path of ancestors to the root of the tree.\n * When a state is being activated, each element in the path is wrapped as a [[PathNode]].\n * A `PathNode` is a stateful object that holds things like parameters and resolvables for the state being activated.\n *\n * The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path.\n */\nexport class ResolveContext {\n _injector: UIInjector;\n\n constructor(private _path: PathNode[]) {}\n\n /** Gets all the tokens found in the resolve context, de-duplicated */\n getTokens(): any[] {\n return this._path.reduce((acc, node) => acc.concat(node.resolvables.map(r => r.token)), []).reduce(uniqR, []);\n }\n\n /**\n * Gets the Resolvable that matches the token\n *\n * Gets the last Resolvable that matches the token in this context, or undefined.\n * Throws an error if it doesn't exist in the ResolveContext\n */\n getResolvable(token: any): Resolvable {\n const matching = this._path\n .map(node => node.resolvables)\n .reduce(unnestR, [])\n .filter((r: Resolvable) => r.token === token);\n return tail(matching);\n }\n\n /** Returns the [[ResolvePolicy]] for the given [[Resolvable]] */\n getPolicy(resolvable: Resolvable): ResolvePolicy {\n const node = this.findNode(resolvable);\n return resolvable.getPolicy(node.state);\n }\n\n /**\n * Returns a ResolveContext that includes a portion of this one\n *\n * Given a state, this method creates a new ResolveContext from this one.\n * The new context starts at the first node (root) and stops at the node for the `state` parameter.\n *\n * #### Why\n *\n * When a transition is created, the nodes in the \"To Path\" are injected from a ResolveContext.\n * A ResolveContext closes over a path of [[PathNode]]s and processes the resolvables.\n * The \"To State\" can inject values from its own resolvables, as well as those from all its ancestor state's (node's).\n * This method is used to create a narrower context when injecting ancestor nodes.\n *\n * @example\n * `let ABCD = new ResolveContext([A, B, C, D]);`\n *\n * Given a path `[A, B, C, D]`, where `A`, `B`, `C` and `D` are nodes for states `a`, `b`, `c`, `d`:\n * When injecting `D`, `D` should have access to all resolvables from `A`, `B`, `C`, `D`.\n * However, `B` should only be able to access resolvables from `A`, `B`.\n *\n * When resolving for the `B` node, first take the full \"To Path\" Context `[A,B,C,D]` and limit to the subpath `[A,B]`.\n * `let AB = ABCD.subcontext(a)`\n */\n subContext(state: StateObject): ResolveContext {\n return new ResolveContext(PathUtils.subPath(this._path, node => node.state === state));\n }\n\n /**\n * Adds Resolvables to the node that matches the state\n *\n * This adds a [[Resolvable]] (generally one created on the fly; not declared on a [[StateDeclaration.resolve]] block).\n * The resolvable is added to the node matching the `state` parameter.\n *\n * These new resolvables are not automatically fetched.\n * The calling code should either fetch them, fetch something that depends on them,\n * or rely on [[resolvePath]] being called when some state is being entered.\n *\n * Note: each resolvable's [[ResolvePolicy]] is merged with the state's policy, and the global default.\n *\n * @param newResolvables the new Resolvables\n * @param state Used to find the node to put the resolvable on\n */\n addResolvables(newResolvables: Resolvable[], state: StateObject) {\n const node = find(this._path, propEq('state', state));\n const keys = newResolvables.map(r => r.token);\n node.resolvables = node.resolvables.filter(r => keys.indexOf(r.token) === -1).concat(newResolvables);\n }\n\n /**\n * Returns a promise for an array of resolved path Element promises\n *\n * @param when\n * @param trans\n * @returns {Promise|any}\n */\n resolvePath(when: PolicyWhen = 'LAZY', trans?: Transition): Promise<{ token: any; value: any }[]> {\n // This option determines which 'when' policy Resolvables we are about to fetch.\n const whenOption: string = inArray(ALL_WHENS, when) ? when : 'LAZY';\n // If the caller specified EAGER, only the EAGER Resolvables are fetched.\n // if the caller specified LAZY, both EAGER and LAZY Resolvables are fetched.`\n const matchedWhens = whenOption === resolvePolicies.when.EAGER ? EAGER_WHENS : ALL_WHENS;\n\n // get the subpath to the state argument, if provided\n trace.traceResolvePath(this._path, when, trans);\n\n const matchesPolicy = (acceptedVals: string[], whenOrAsync: 'when' | 'async') => (resolvable: Resolvable) =>\n inArray(acceptedVals, this.getPolicy(resolvable)[whenOrAsync]);\n\n // Trigger all the (matching) Resolvables in the path\n // Reduce all the \"WAIT\" Resolvables into an array\n const promises: Promise[] = this._path.reduce((acc, node) => {\n const nodeResolvables = node.resolvables.filter(matchesPolicy(matchedWhens, 'when'));\n const nowait = nodeResolvables.filter(matchesPolicy(['NOWAIT'], 'async'));\n const wait = nodeResolvables.filter(not(matchesPolicy(['NOWAIT'], 'async')));\n\n // For the matching Resolvables, start their async fetch process.\n const subContext = this.subContext(node.state);\n const getResult = (r: Resolvable) =>\n r\n .get(subContext, trans)\n // Return a tuple that includes the Resolvable's token\n .then(value => ({ token: r.token, value: value }));\n nowait.forEach(getResult);\n return acc.concat(wait.map(getResult));\n }, []);\n\n // Wait for all the \"WAIT\" resolvables\n return services.$q.all(promises);\n }\n\n injector(): UIInjector {\n return this._injector || (this._injector = new UIInjectorImpl(this));\n }\n\n findNode(resolvable: Resolvable): PathNode {\n return find(this._path, (node: PathNode) => inArray(node.resolvables, resolvable));\n }\n\n /**\n * Gets the async dependencies of a Resolvable\n *\n * Given a Resolvable, returns its dependencies as a Resolvable[]\n */\n getDependencies(resolvable: Resolvable): Resolvable[] {\n const node = this.findNode(resolvable);\n // Find which other resolvables are \"visible\" to the `resolvable` argument\n // subpath stopping at resolvable's node, or the whole path (if the resolvable isn't in the path)\n const subPath: PathNode[] = PathUtils.subPath(this._path, x => x === node) || this._path;\n const availableResolvables: Resolvable[] = subPath\n .reduce((acc, _node) => acc.concat(_node.resolvables), []) // all of subpath's resolvables\n .filter(res => res !== resolvable); // filter out the `resolvable` argument\n\n const getDependency = (token: any) => {\n const matching = availableResolvables.filter(r => r.token === token);\n if (matching.length) return tail(matching);\n\n const fromInjector = this.injector().getNative(token);\n if (isUndefined(fromInjector)) {\n throw new Error('Could not find Dependency Injection token: ' + stringify(token));\n }\n\n return new Resolvable(token, () => fromInjector, [], fromInjector);\n };\n\n return resolvable.deps.map(getDependency);\n }\n}\n\nclass UIInjectorImpl implements UIInjector {\n native: $InjectorLike;\n\n constructor(public context: ResolveContext) {\n this.native = this.get(NATIVE_INJECTOR_TOKEN) || services.$injector;\n }\n\n get(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) {\n if (this.context.getPolicy(resolvable).async === 'NOWAIT') {\n return resolvable.get(this.context);\n }\n\n if (!resolvable.resolved) {\n throw new Error('Resolvable async .get() not complete:' + stringify(resolvable.token));\n }\n return resolvable.data;\n }\n\n return this.getNative(token);\n }\n\n getAsync(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) return resolvable.get(this.context);\n return services.$q.when(this.native.get(token));\n }\n\n getNative(token: any) {\n return this.native && this.native.get(token);\n }\n}\n", + "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { stringify } from '../common/strings';\nimport { map, find, extend, mergeR, tail, omit, arrayTuples, unnestR, identity, anyTrueR } from '../common/common';\nimport { isObject, isUndefined } from '../common/predicates';\nimport { prop, propEq, val, not, is } from '../common/hof';\nimport { StateDeclaration, StateOrName } from '../state/interface';\nimport {\n TransitionOptions,\n TreeChanges,\n IHookRegistry,\n TransitionHookPhase,\n RegisteredHooks,\n HookRegOptions,\n HookMatchCriteria,\n TransitionStateHookFn,\n TransitionHookFn,\n} from './interface'; // has or is using\nimport { TransitionHook } from './transitionHook';\nimport { matchState, makeEvent, RegisteredHook } from './hookRegistry';\nimport { HookBuilder } from './hookBuilder';\nimport { PathNode } from '../path/pathNode';\nimport { PathUtils } from '../path/pathUtils';\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { RawParams } from '../params/interface';\nimport { ResolvableLiteral } from '../resolve/interface';\nimport { Rejection } from './rejectFactory';\n\n/** @hidden */\nconst stateSelf: (_state: StateObject) => StateDeclaration = prop('self');\n\n/**\n * Represents a transition between two states.\n *\n * When navigating to a state, we are transitioning **from** the current state **to** the new state.\n *\n * This object contains all contextual information about the to/from states, parameters, resolves.\n * It has information about all states being entered and exited as a result of the transition.\n */\nexport class Transition implements IHookRegistry {\n /** @hidden */\n static diToken = Transition;\n\n /**\n * A unique identifier for the transition.\n *\n * This is an auto incrementing integer, starting from `0`.\n */\n $id: number;\n\n /**\n * A reference to the [[UIRouter]] instance\n *\n * This reference can be used to access the router services, such as the [[StateService]]\n */\n router: UIRouter;\n\n /** @hidden */\n private _deferred = services.$q.defer();\n /**\n * This promise is resolved or rejected based on the outcome of the Transition.\n *\n * When the transition is successful, the promise is resolved\n * When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error\n */\n promise: Promise = this._deferred.promise;\n /**\n * A boolean which indicates if the transition was successful\n *\n * After a successful transition, this value is set to true.\n * After an unsuccessful transition, this value is set to false.\n *\n * The value will be undefined if the transition is not complete\n */\n success: boolean;\n /** @hidden */\n _aborted: boolean;\n /** @hidden */\n private _error: Rejection;\n\n /** @hidden Holds the hook registration functions such as those passed to Transition.onStart() */\n _registeredHooks: RegisteredHooks = {};\n\n /** @hidden */\n private _options: TransitionOptions;\n /** @hidden */\n private _treeChanges: TreeChanges;\n /** @hidden */\n private _targetState: TargetState;\n /** @hidden */\n private _hookBuilder = new HookBuilder(this);\n\n /** @hidden */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n\n /** @hidden\n * Creates the transition-level hook registration functions\n * (which can then be used to register hooks)\n */\n private createTransitionHookRegFns() {\n this.router.transitionService._pluginapi\n ._getEvents()\n .filter(type => type.hookPhase !== TransitionHookPhase.CREATE)\n .forEach(type => makeEvent(this, this.router.transitionService, type));\n }\n\n /** @internalapi */\n getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /**\n * Creates a new Transition object.\n *\n * If the target state is not valid, an error is thrown.\n *\n * @internalapi\n *\n * @param fromPath The path of [[PathNode]]s from which the transition is leaving. The last node in the `fromPath`\n * encapsulates the \"from state\".\n * @param targetState The target state and parameters being transitioned to (also, the transition options)\n * @param router The [[UIRouter]] instance\n */\n constructor(fromPath: PathNode[], targetState: TargetState, router: UIRouter) {\n this.router = router;\n this._targetState = targetState;\n\n if (!targetState.valid()) {\n throw new Error(targetState.error());\n }\n\n // current() is assumed to come from targetState.options, but provide a naive implementation otherwise.\n this._options = extend({ current: val(this) }, targetState.options());\n this.$id = router.transitionService._transitionCount++;\n const toPath = PathUtils.buildToPath(fromPath, targetState);\n this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState);\n this.createTransitionHookRegFns();\n\n const onCreateHooks = this._hookBuilder.buildHooksForPhase(TransitionHookPhase.CREATE);\n TransitionHook.invokeHooks(onCreateHooks, () => null);\n\n this.applyViewConfigs(router);\n }\n\n private applyViewConfigs(router: UIRouter) {\n const enteringStates = this._treeChanges.entering.map(node => node.state);\n PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates);\n }\n\n /**\n * @internalapi\n *\n * @returns the internal from [State] object\n */\n $from() {\n return tail(this._treeChanges.from).state;\n }\n\n /**\n * @internalapi\n *\n * @returns the internal to [State] object\n */\n $to() {\n return tail(this._treeChanges.to).state;\n }\n\n /**\n * Returns the \"from state\"\n *\n * Returns the state that the transition is coming *from*.\n *\n * @returns The state declaration object for the Transition's (\"from state\").\n */\n from(): StateDeclaration {\n return this.$from().self;\n }\n\n /**\n * Returns the \"to state\"\n *\n * Returns the state that the transition is going *to*.\n *\n * @returns The state declaration object for the Transition's target state (\"to state\").\n */\n to(): StateDeclaration {\n return this.$to().self;\n }\n\n /**\n * Gets the Target State\n *\n * A transition's [[TargetState]] encapsulates the [[to]] state, the [[params]], and the [[options]] as a single object.\n *\n * @returns the [[TargetState]] of this Transition\n */\n targetState() {\n return this._targetState;\n }\n\n /**\n * Determines whether two transitions are equivalent.\n * @deprecated\n */\n is(compare: Transition | { to?: any; from?: any }): boolean {\n if (compare instanceof Transition) {\n // TODO: Also compare parameters\n return this.is({ to: compare.$to().name, from: compare.$from().name });\n }\n return !(\n (compare.to && !matchState(this.$to(), compare.to)) ||\n (compare.from && !matchState(this.$from(), compare.from))\n );\n }\n\n /**\n * Gets transition parameter values\n *\n * Returns the parameter values for a transition as key/value pairs.\n * This object is immutable.\n *\n * By default, returns the new parameter values (for the \"to state\").\n *\n * #### Example:\n * ```js\n * var toParams = transition.params();\n * ```\n *\n * To return the previous parameter values, supply `'from'` as the `pathname` argument.\n *\n * #### Example:\n * ```js\n * var fromParams = transition.params('from');\n * ```\n *\n * @param pathname the name of the treeChanges path to get parameter values for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n *\n * @returns transition parameter values for the desired path.\n */\n params(pathname?: string): { [paramName: string]: any };\n params(pathname?: string): T;\n params(pathname = 'to') {\n return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {}));\n }\n\n /**\n * Creates a [[UIInjector]] Dependency Injector\n *\n * Returns a Dependency Injector for the Transition's target state (to state).\n * The injector provides resolve values which the target state has access to.\n *\n * The `UIInjector` can also provide values from the native root/global injector (ng1/ng2).\n *\n * #### Example:\n * ```js\n * .onEnter({ entering: 'myState' }, trans => {\n * var myResolveValue = trans.injector().get('myResolve');\n * // Inject a global service from the global/native injector (if it exists)\n * var MyService = trans.injector().get('MyService');\n * })\n * ```\n *\n * In some cases (such as `onBefore`), you may need access to some resolve data but it has not yet been fetched.\n * You can use [[UIInjector.getAsync]] to get a promise for the data.\n * #### Example:\n * ```js\n * .onBefore({}, trans => {\n * return trans.injector().getAsync('myResolve').then(myResolveValue =>\n * return myResolveValue !== 'ABORT';\n * });\n * });\n * ```\n *\n * If a `state` is provided, the injector that is returned will be limited to resolve values that the provided state has access to.\n * This can be useful if both a parent state `foo` and a child state `foo.bar` have both defined a resolve such as `data`.\n * #### Example:\n * ```js\n * .onEnter({ to: 'foo.bar' }, trans => {\n * // returns result of `foo` state's `myResolve` resolve\n * // even though `foo.bar` also has a `myResolve` resolve\n * var fooData = trans.injector('foo').get('myResolve');\n * });\n * ```\n *\n * If you need resolve data from the exiting states, pass `'from'` as `pathName`.\n * The resolve data from the `from` path will be returned.\n * #### Example:\n * ```js\n * .onExit({ exiting: 'foo.bar' }, trans => {\n * // Gets the resolve value of `myResolve` from the state being exited\n * var fooData = trans.injector(null, 'from').get('myResolve');\n * });\n * ```\n *\n *\n * @param state Limits the resolves provided to only the resolves the provided state has access to.\n * @param pathName Default: `'to'`: Chooses the path for which to create the injector. Use this to access resolves for `exiting` states.\n *\n * @returns a [[UIInjector]]\n */\n injector(state?: StateOrName, pathName = 'to'): UIInjector {\n let path: PathNode[] = this._treeChanges[pathName];\n if (state) path = PathUtils.subPath(path, node => node.state === state || node.state.name === state);\n return new ResolveContext(path).injector();\n }\n\n /**\n * Gets all available resolve tokens (keys)\n *\n * This method can be used in conjunction with [[injector]] to inspect the resolve values\n * available to the Transition.\n *\n * This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states\n * in the Transition's [[TreeChanges.to]] path.\n *\n * #### Example:\n * This example logs all resolve values\n * ```js\n * let tokens = trans.getResolveTokens();\n * tokens.forEach(token => console.log(token + \" = \" + trans.injector().get(token)));\n * ```\n *\n * #### Example:\n * This example creates promises for each resolve value.\n * This triggers fetches of resolves (if any have not yet been fetched).\n * When all promises have all settled, it logs the resolve values.\n * ```js\n * let tokens = trans.getResolveTokens();\n * let promise = tokens.map(token => trans.injector().getAsync(token));\n * Promise.all(promises).then(values => console.log(\"Resolved values: \" + values));\n * ```\n *\n * Note: Angular 1 users whould use `$q.all()`\n *\n * @param pathname resolve context's path name (e.g., `to` or `from`)\n *\n * @returns an array of resolve tokens (keys)\n */\n getResolveTokens(pathname = 'to'): any[] {\n return new ResolveContext(this._treeChanges[pathname]).getTokens();\n }\n\n /**\n * Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.\n *\n * Allows a transition hook to dynamically add a Resolvable to this Transition.\n *\n * Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).\n *\n * If a `state` argument is provided, the Resolvable is processed when that state is being entered.\n * If no `state` is provided then the root state is used.\n * If the given `state` has already been entered, the Resolvable is processed when any child state is entered.\n * If no child states will be entered, the Resolvable is processed during the `onFinish` phase of the Transition.\n *\n * The `state` argument also scopes the resolved data.\n * The resolved data is available from the injector for that `state` and any children states.\n *\n * #### Example:\n * ```js\n * transitionService.onBefore({}, transition => {\n * transition.addResolvable({\n * token: 'myResolve',\n * deps: ['MyService'],\n * resolveFn: myService => myService.getData()\n * });\n * });\n * ```\n *\n * @param resolvable a [[ResolvableLiteral]] object (or a [[Resolvable]])\n * @param state the state in the \"to path\" which should receive the new resolve (otherwise, the root state)\n */\n addResolvable(resolvable: Resolvable | ResolvableLiteral, state: StateOrName = ''): void {\n resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable);\n\n const stateName: string = typeof state === 'string' ? state : state.name;\n const topath = this._treeChanges.to;\n const targetNode = find(topath, node => node.state.name === stateName);\n const resolveContext: ResolveContext = new ResolveContext(topath);\n resolveContext.addResolvables([resolvable as Resolvable], targetNode.state);\n }\n\n /**\n * Gets the transition from which this transition was redirected.\n *\n * If the current transition is a redirect, this method returns the transition that was redirected.\n *\n * #### Example:\n * ```js\n * let transitionA = $state.go('A').transition\n * transitionA.onStart({}, () => $state.target('B'));\n * $transitions.onSuccess({ to: 'B' }, (trans) => {\n * trans.to().name === 'B'; // true\n * trans.redirectedFrom() === transitionA; // true\n * });\n * ```\n *\n * @returns The previous Transition, or null if this Transition is not the result of a redirection\n */\n redirectedFrom(): Transition {\n return this._options.redirectedFrom || null;\n }\n\n /**\n * Gets the original transition in a redirect chain\n *\n * A transition might belong to a long chain of multiple redirects.\n * This method walks the [[redirectedFrom]] chain back to the original (first) transition in the chain.\n *\n * #### Example:\n * ```js\n * // states\n * registry.register({ name: 'A', redirectTo: 'B' });\n * registry.register({ name: 'B', redirectTo: 'C' });\n * registry.register({ name: 'C', redirectTo: 'D' });\n * registry.register({ name: 'D' });\n *\n * let transitionA = $state.go('A').transition\n *\n * $transitions.onSuccess({ to: 'D' }, (trans) => {\n * trans.to().name === 'D'; // true\n * trans.redirectedFrom().to().name === 'C'; // true\n * trans.originalTransition() === transitionA; // true\n * trans.originalTransition().to().name === 'A'; // true\n * });\n * ```\n *\n * @returns The original Transition that started a redirect chain\n */\n originalTransition(): Transition {\n const rf = this.redirectedFrom();\n return (rf && rf.originalTransition()) || this;\n }\n\n /**\n * Get the transition options\n *\n * @returns the options for this Transition.\n */\n options(): TransitionOptions {\n return this._options;\n }\n\n /**\n * Gets the states being entered.\n *\n * @returns an array of states that will be entered during this transition.\n */\n entering(): StateDeclaration[] {\n return map(this._treeChanges.entering, prop('state')).map(stateSelf);\n }\n\n /**\n * Gets the states being exited.\n *\n * @returns an array of states that will be exited during this transition.\n */\n exiting(): StateDeclaration[] {\n return map(this._treeChanges.exiting, prop('state'))\n .map(stateSelf)\n .reverse();\n }\n\n /**\n * Gets the states being retained.\n *\n * @returns an array of states that are already entered from a previous Transition, that will not be\n * exited during this Transition\n */\n retained(): StateDeclaration[] {\n return map(this._treeChanges.retained, prop('state')).map(stateSelf);\n }\n\n /**\n * Get the [[ViewConfig]]s associated with this Transition\n *\n * Each state can define one or more views (template/controller), which are encapsulated as `ViewConfig` objects.\n * This method fetches the `ViewConfigs` for a given path in the Transition (e.g., \"to\" or \"entering\").\n *\n * @param pathname the name of the path to fetch views for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n * @param state If provided, only returns the `ViewConfig`s for a single state in the path\n *\n * @returns a list of ViewConfig objects for the given path.\n */\n views(pathname = 'entering', state?: StateObject): ViewConfig[] {\n let path = this._treeChanges[pathname];\n path = !state ? path : path.filter(propEq('state', state));\n return path\n .map(prop('views'))\n .filter(identity)\n .reduce(unnestR, []);\n }\n\n /**\n * Return the transition's tree changes\n *\n * A transition goes from one state/parameters to another state/parameters.\n * During a transition, states are entered and/or exited.\n *\n * This function returns various branches (paths) which represent the changes to the\n * active state tree that are caused by the transition.\n *\n * @param pathname The name of the tree changes path to get:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n */\n treeChanges(pathname: string): PathNode[];\n treeChanges(): TreeChanges;\n treeChanges(pathname?: string) {\n return pathname ? this._treeChanges[pathname] : this._treeChanges;\n }\n\n /**\n * Creates a new transition that is a redirection of the current one.\n *\n * This transition can be returned from a [[TransitionService]] hook to\n * redirect a transition to a new state and/or set of parameters.\n *\n * @internalapi\n *\n * @returns Returns a new [[Transition]] instance.\n */\n redirect(targetState: TargetState): Transition {\n let redirects = 1,\n trans: Transition = this;\n // tslint:disable-next-line:no-conditional-assignment\n while ((trans = trans.redirectedFrom()) != null) {\n if (++redirects > 20) throw new Error(`Too many consecutive Transition redirects (20+)`);\n }\n\n const redirectOpts: TransitionOptions = { redirectedFrom: this, source: 'redirect' };\n // If the original transition was caused by URL sync, then use { location: 'replace' }\n // on the new transition (unless the target state explicitly specifies location: false).\n // This causes the original url to be replaced with the url for the redirect target\n // so the original url disappears from the browser history.\n if (this.options().source === 'url' && targetState.options().location !== false) {\n redirectOpts.location = 'replace';\n }\n\n const newOptions = extend({}, this.options(), targetState.options(), redirectOpts);\n targetState = targetState.withOptions(newOptions, true);\n\n const newTransition = this.router.transitionService.create(this._treeChanges.from, targetState);\n const originalEnteringNodes = this._treeChanges.entering;\n const redirectEnteringNodes = newTransition._treeChanges.entering;\n\n // --- Re-use resolve data from original transition ---\n // When redirecting from a parent state to a child state where the parent parameter values haven't changed\n // (because of the redirect), the resolves fetched by the original transition are still valid in the\n // redirected transition.\n //\n // This allows you to define a redirect on a parent state which depends on an async resolve value.\n // You can wait for the resolve, then redirect to a child state based on the result.\n // The redirected transition does not have to re-fetch the resolve.\n // ---------------------------------------------------------\n\n const nodeIsReloading = (reloadState: StateObject) => (node: PathNode) => {\n return reloadState && node.state.includes[reloadState.name];\n };\n\n // Find any \"entering\" nodes in the redirect path that match the original path and aren't being reloaded\n const matchingEnteringNodes: PathNode[] = PathUtils.matching(\n redirectEnteringNodes,\n originalEnteringNodes,\n PathUtils.nonDynamicParams,\n ).filter(not(nodeIsReloading(targetState.options().reloadState)));\n\n // Use the existing (possibly pre-resolved) resolvables for the matching entering nodes.\n matchingEnteringNodes.forEach((node, idx) => {\n node.resolvables = originalEnteringNodes[idx].resolvables;\n });\n\n return newTransition;\n }\n\n /** @hidden If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */\n private _changedParams(): Param[] {\n const tc = this._treeChanges;\n\n /** Return undefined if it's not a \"dynamic\" transition, for the following reasons */\n // If user explicitly wants a reload\n if (this._options.reload) return undefined;\n // If any states are exiting or entering\n if (tc.exiting.length || tc.entering.length) return undefined;\n // If to/from path lengths differ\n if (tc.to.length !== tc.from.length) return undefined;\n // If the to/from paths are different\n const pathsDiffer: boolean = arrayTuples(tc.to, tc.from)\n .map(tuple => tuple[0].state !== tuple[1].state)\n .reduce(anyTrueR, false);\n if (pathsDiffer) return undefined;\n\n // Find any parameter values that differ\n const nodeSchemas: Param[][] = tc.to.map((node: PathNode) => node.paramSchema);\n const [toValues, fromValues] = [tc.to, tc.from].map(path => path.map(x => x.paramValues));\n const tuples = arrayTuples(nodeSchemas, toValues, fromValues);\n\n return tuples.map(([schema, toVals, fromVals]) => Param.changed(schema, toVals, fromVals)).reduce(unnestR, []);\n }\n\n /**\n * Returns true if the transition is dynamic.\n *\n * A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.\n *\n * @returns true if the Transition is dynamic\n */\n dynamic(): boolean {\n const changes = this._changedParams();\n return !changes ? false : changes.map(x => x.dynamic).reduce(anyTrueR, false);\n }\n\n /**\n * Returns true if the transition is ignored.\n *\n * A transition is ignored if no states are entered nor exited, and no parameter values have changed.\n *\n * @returns true if the Transition is ignored.\n */\n ignored(): boolean {\n return !!this._ignoredReason();\n }\n\n /** @hidden */\n _ignoredReason(): 'SameAsCurrent' | 'SameAsPending' | undefined {\n const pending = this.router.globals.transition;\n const reloadState = this._options.reloadState;\n\n const same = (pathA, pathB) => {\n if (pathA.length !== pathB.length) return false;\n const matching = PathUtils.matching(pathA, pathB);\n return pathA.length === matching.filter(node => !reloadState || !node.state.includes[reloadState.name]).length;\n };\n\n const newTC = this.treeChanges();\n const pendTC = pending && pending.treeChanges();\n\n if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) return 'SameAsPending';\n if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) return 'SameAsCurrent';\n }\n\n /**\n * Runs the transition\n *\n * This method is generally called from the [[StateService.transitionTo]]\n *\n * @internalapi\n *\n * @returns a promise for a successful transition.\n */\n run(): Promise {\n const runAllHooks = TransitionHook.runAllHooks;\n\n // Gets transition hooks array for the given phase\n const getHooksFor = (phase: TransitionHookPhase) => this._hookBuilder.buildHooksForPhase(phase);\n\n // When the chain is complete, then resolve or reject the deferred\n const transitionSuccess = () => {\n trace.traceSuccess(this.$to(), this);\n this.success = true;\n this._deferred.resolve(this.to());\n runAllHooks(getHooksFor(TransitionHookPhase.SUCCESS));\n };\n\n const transitionError = (reason: Rejection) => {\n trace.traceError(reason, this);\n this.success = false;\n this._deferred.reject(reason);\n this._error = reason;\n runAllHooks(getHooksFor(TransitionHookPhase.ERROR));\n };\n\n const runTransition = () => {\n // Wait to build the RUN hook chain until the BEFORE hooks are done\n // This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object.\n const allRunHooks = getHooksFor(TransitionHookPhase.RUN);\n const done = () => services.$q.when(undefined);\n return TransitionHook.invokeHooks(allRunHooks, done);\n };\n\n const startTransition = () => {\n const globals = this.router.globals;\n\n globals.lastStartedTransitionId = this.$id;\n globals.transition = this;\n globals.transitionHistory.enqueue(this);\n\n trace.traceTransitionStart(this);\n\n return services.$q.when(undefined);\n };\n\n const allBeforeHooks = getHooksFor(TransitionHookPhase.BEFORE);\n TransitionHook.invokeHooks(allBeforeHooks, startTransition)\n .then(runTransition)\n .then(transitionSuccess, transitionError);\n\n return this.promise;\n }\n\n /** Checks if this transition is currently active/running. */\n isActive = () => this.router.globals.transition === this;\n\n /**\n * Checks if the Transition is valid\n *\n * @returns true if the Transition is valid\n */\n valid() {\n return !this.error() || this.success !== undefined;\n }\n\n /**\n * Aborts this transition\n *\n * Imperative API to abort a Transition.\n * This only applies to Transitions that are not yet complete.\n */\n abort() {\n // Do not set flag if the transition is already complete\n if (isUndefined(this.success)) {\n this._aborted = true;\n }\n }\n\n /**\n * The Transition error reason.\n *\n * If the transition is invalid (and could not be run), returns the reason the transition is invalid.\n * If the transition was valid and ran, but was not successful, returns the reason the transition failed.\n *\n * @returns a transition rejection explaining why the transition is invalid, or the reason the transition failed.\n */\n error(): Rejection {\n const state: StateObject = this.$to();\n\n if (state.self.abstract) {\n return Rejection.invalid(`Cannot transition to abstract state '${state.name}'`);\n }\n\n const paramDefs = state.parameters();\n const values = this.params();\n const invalidParams = paramDefs.filter(param => !param.validates(values[param.id]));\n\n if (invalidParams.length) {\n const invalidValues = invalidParams.map(param => `[${param.id}:${stringify(values[param.id])}]`).join(', ');\n const detail = `The following parameter values are not valid for state '${state.name}': ${invalidValues}`;\n return Rejection.invalid(detail);\n }\n\n if (this.success === false) return this._error;\n }\n\n /**\n * A string representation of the Transition\n *\n * @returns A string representation of the Transition\n */\n toString() {\n const fromStateOrName = this.from();\n const toStateOrName = this.to();\n\n const avoidEmptyHash = (params: RawParams) =>\n params['#'] !== null && params['#'] !== undefined ? params : omit(params, ['#']);\n\n // (X) means the to state is invalid.\n const id = this.$id,\n from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName,\n fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))),\n toValid = this.valid() ? '' : '(X) ',\n to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName,\n toParams = stringify(avoidEmptyHash(this.params()));\n\n return `Transition#${id}( '${from}'${fromParams} -> ${toValid}'${to}'${toParams} )`;\n }\n}\n", + "/**\n * Functions that manipulate strings\n *\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_strings\n */ /** */\n\nimport { isString, isArray, isDefined, isNull, isPromise, isInjectable, isObject } from './predicates';\nimport { Rejection } from '../transition/rejectFactory';\nimport { IInjectable, identity, Obj, tail, pushR } from './common';\nimport { pattern, is, not, val, invoke } from './hof';\nimport { Transition } from '../transition/transition';\nimport { Resolvable } from '../resolve/resolvable';\n\n/**\n * Returns a string shortened to a maximum length\n *\n * If the string is already less than the `max` length, return the string.\n * Else return the string, shortened to `max - 3` and append three dots (\"...\").\n *\n * @param max the maximum length of the string to return\n * @param str the input string\n */\nexport function maxLength(max: number, str: string) {\n if (str.length <= max) return str;\n return str.substr(0, max - 3) + '...';\n}\n\n/**\n * Returns a string, with spaces added to the end, up to a desired str length\n *\n * If the string is already longer than the desired length, return the string.\n * Else returns the string, with extra spaces on the end, such that it reaches `length` characters.\n *\n * @param length the desired length of the string to return\n * @param str the input string\n */\nexport function padString(length: number, str: string) {\n while (str.length < length) str += ' ';\n return str;\n}\n\nexport function kebobString(camelCase: string) {\n return camelCase\n .replace(/^([A-Z])/, $1 => $1.toLowerCase()) // replace first char\n .replace(/([A-Z])/g, $1 => '-' + $1.toLowerCase()); // replace rest\n}\n\nfunction _toJson(obj: Obj) {\n return JSON.stringify(obj);\n}\n\nfunction _fromJson(json: string) {\n return isString(json) ? JSON.parse(json) : json;\n}\n\nfunction promiseToString(p: Promise) {\n return `Promise(${JSON.stringify(p)})`;\n}\n\nexport function functionToString(fn: Function) {\n const fnStr = fnToString(fn);\n const namedFunctionMatch = fnStr.match(/^(function [^ ]+\\([^)]*\\))/);\n const toStr = namedFunctionMatch ? namedFunctionMatch[1] : fnStr;\n\n const fnName = fn['name'] || '';\n if (fnName && toStr.match(/function \\(/)) {\n return 'function ' + fnName + toStr.substr(9);\n }\n return toStr;\n}\n\nexport function fnToString(fn: IInjectable) {\n const _fn = isArray(fn) ? fn.slice(-1)[0] : fn;\n return (_fn && _fn.toString()) || 'undefined';\n}\n\nlet stringifyPatternFn: (val: any) => string = null;\nconst stringifyPattern = function(value: any) {\n const isRejection = Rejection.isRejectionPromise;\n\n stringifyPatternFn =\n stringifyPatternFn ||\n pattern([\n [not(isDefined), val('undefined')],\n [isNull, val('null')],\n [isPromise, val('[Promise]')],\n [isRejection, (x: any) => x._transitionRejection.toString()],\n [is(Rejection), invoke('toString')],\n [is(Transition), invoke('toString')],\n [is(Resolvable), invoke('toString')],\n [isInjectable, functionToString],\n [val(true), identity],\n ]);\n\n return stringifyPatternFn(value);\n};\n\nexport function stringify(o: any) {\n const seen: any[] = [];\n\n function format(value: any) {\n if (isObject(value)) {\n if (seen.indexOf(value) !== -1) return '[circular ref]';\n seen.push(value);\n }\n return stringifyPattern(value);\n }\n\n return JSON.stringify(o, (key, value) => format(value)).replace(/\\\\\"/g, '\"');\n}\n\n/** Returns a function that splits a string on a character or substring */\nexport const beforeAfterSubstr = (char: string) => (str: string): string[] => {\n if (!str) return ['', ''];\n const idx = str.indexOf(char);\n if (idx === -1) return [str, ''];\n return [str.substr(0, idx), str.substr(idx + 1)];\n};\n\nexport const hostRegex = new RegExp('^(?:[a-z]+:)?//[^/]+/');\nexport const stripLastPathElement = (str: string) => str.replace(/\\/[^/]*$/, '');\nexport const splitHash = beforeAfterSubstr('#');\nexport const splitQuery = beforeAfterSubstr('?');\nexport const splitEqual = beforeAfterSubstr('=');\nexport const trimHashVal = (str: string) => (str ? str.replace(/^#/, '') : '');\n\n/**\n * Splits on a delimiter, but returns the delimiters in the array\n *\n * #### Example:\n * ```js\n * var splitOnSlashes = splitOnDelim('/');\n * splitOnSlashes(\"/foo\"); // [\"/\", \"foo\"]\n * splitOnSlashes(\"/foo/\"); // [\"/\", \"foo\", \"/\"]\n * ```\n */\nexport function splitOnDelim(delim: string) {\n const re = new RegExp('(' + delim + ')', 'g');\n return (str: string) => str.split(re).filter(identity);\n}\n\n/**\n * Reduce fn that joins neighboring strings\n *\n * Given an array of strings, returns a new array\n * where all neighboring strings have been joined.\n *\n * #### Example:\n * ```js\n * let arr = [\"foo\", \"bar\", 1, \"baz\", \"\", \"qux\" ];\n * arr.reduce(joinNeighborsR, []) // [\"foobar\", 1, \"bazqux\" ]\n * ```\n */\nexport function joinNeighborsR(acc: any[], x: any) {\n if (isString(tail(acc)) && isString(x)) return acc.slice(0, -1).concat(tail(acc) + x);\n return pushR(acc, x);\n}\n", "/** @module common */ /** for typedoc */\nexport * from './common';\nexport * from './coreservices';\nexport * from './glob';\nexport * from './hof';\nexport * from './predicates';\nexport * from './queue';\nexport * from './strings';\nexport * from './trace';\n", - "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { fromJson, toJson, identity, equals, inherit, map, extend, pick } from '../common/common';\nimport { isDefined, isNullOrUndefined } from '../common/predicates';\nimport { is } from '../common/hof';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * A registry for parameter types.\n *\n * This registry manages the built-in (and custom) parameter types.\n *\n * The built-in parameter types are:\n *\n * - [[string]]\n * - [[path]]\n * - [[query]]\n * - [[hash]]\n * - [[int]]\n * - [[bool]]\n * - [[date]]\n * - [[json]]\n * - [[any]]\n */\nexport class ParamTypes {\n /**\n * Built-in parameter type: `string`\n *\n * This parameter type coerces values to strings.\n * It matches anything (`new RegExp(\".*\")`) in the URL\n */\n static string: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `path`\n *\n * This parameter type is the default type for path parameters.\n * A path parameter is any parameter declared in the path portion of a url\n *\n * - `/foo/:param1/:param2`: two path parameters\n *\n * This parameter type behaves exactly like the [[string]] type with one exception.\n * When matching parameter values in the URL, the `path` type does not match forward slashes `/`.\n *\n * #### Angular 1 note:\n * In ng1, this type is overridden with one that pre-encodes slashes as `~2F` instead of `%2F`.\n * For more details about this angular 1 behavior, see: https://github.com/angular-ui/ui-router/issues/2598\n */\n static path: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `query`\n *\n * This parameter type is the default type for query/search parameters.\n * It behaves the same as the [[string]] parameter type.\n *\n * A query parameter is any parameter declared in the query/search portion of a url\n *\n * - `/bar?param2`: a query parameter\n */\n static query: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `hash`\n *\n * This parameter type is used for the `#` parameter (the hash)\n * It behaves the same as the [[string]] parameter type.\n * @coreapi\n */\n static hash: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `int`\n *\n * This parameter type serializes javascript integers (`number`s which represent an integer) to the URL.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'user',\n * url: '/user/{id:int}'\n * });\n * ```\n * ```js\n * $state.go('user', { id: 1298547 });\n * ```\n *\n * The URL will serialize to: `/user/1298547`.\n *\n * When the parameter value is read, it will be the `number` `1298547`, not the string `\"1298547\"`.\n */\n static int: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `bool`\n *\n * This parameter type serializes `true`/`false` as `1`/`0`\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'inbox',\n * url: '/inbox?{unread:bool}'\n * });\n * ```\n * ```js\n * $state.go('inbox', { unread: true });\n * ```\n *\n * The URL will serialize to: `/inbox?unread=1`.\n *\n * Conversely, if the url is `/inbox?unread=0`, the value of the `unread` parameter will be a `false`.\n */\n static bool: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `date`\n *\n * This parameter type can be used to serialize Javascript dates as parameter values.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'search',\n * url: '/search?{start:date}'\n * });\n * ```\n * ```js\n * $state.go('search', { start: new Date(2000, 0, 1) });\n * ```\n *\n * The URL will serialize to: `/search?start=2000-01-01`.\n *\n * Conversely, if the url is `/search?start=2016-12-25`, the value of the `start` parameter will be a `Date` object where:\n *\n * - `date.getFullYear() === 2016`\n * - `date.getMonth() === 11` (month is 0-based)\n * - `date.getDate() === 25`\n */\n static date: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `json`\n *\n * This parameter type can be used to serialize javascript objects into the URL using JSON serialization.\n *\n * #### Example:\n * This example serializes an plain javascript object to the URL\n * ```js\n * .state({\n * name: 'map',\n * url: '/map/{coords:json}'\n * });\n * ```\n * ```js\n * $state.go('map', { coords: { x: 10399.2, y: 49071 });\n * ```\n *\n * The URL will serialize to: `/map/%7B%22x%22%3A10399.2%2C%22y%22%3A49071%7D`\n */\n static json: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `any`\n *\n * This parameter type is used by default for url-less parameters (parameters that do not appear in the URL).\n * This type does not encode or decode.\n * It is compared using a deep `equals` comparison.\n *\n * #### Example:\n * This example defines a non-url parameter on a [[StateDeclaration]].\n * ```js\n * .state({\n * name: 'new',\n * url: '/new',\n * params: {\n * inrepyto: null\n * }\n * });\n * ```\n * ```js\n * $state.go('new', { inreplyto: currentMessage });\n * ```\n */\n static any: ParamTypeDefinition;\n\n\n /** @hidden */\n types: any;\n /** @hidden */\n enqueue = true;\n /** @hidden */\n typeQueue: any[] = [];\n\n /** @internalapi */\n private defaultTypes: any = pick(ParamTypes.prototype, ['hash', 'string', 'query', 'path', 'int', 'bool', 'date', 'json', 'any']);\n\n /** @internalapi */\n constructor() {\n // Register default types. Store them in the prototype of this.types.\n const makeType = (definition: ParamTypeDefinition, name: string) =>\n new ParamType(extend({ name }, definition));\n this.types = inherit(map(this.defaultTypes, makeType), {});\n }\n\n /** @internalapi */\n dispose() {\n this.types = {};\n }\n\n /**\n * Registers a parameter type\n *\n * End users should call [[UrlMatcherFactory.type]], which delegates to this method.\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n if (!isDefined(definition)) return this.types[name];\n if (this.types.hasOwnProperty(name)) throw new Error(`A type named '${name}' has already been defined.`);\n\n this.types[name] = new ParamType(extend({ name }, definition));\n\n if (definitionFn) {\n this.typeQueue.push({ name, def: definitionFn });\n if (!this.enqueue) this._flushTypeQueue();\n }\n\n return this;\n }\n\n /** @internalapi */\n _flushTypeQueue() {\n while (this.typeQueue.length) {\n const type = this.typeQueue.shift();\n if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n extend(this.types[type.name], services.$injector.invoke(type.def));\n }\n }\n}\n\n/** @hidden */\nfunction initDefaultTypes() {\n\n const makeDefaultType = (def) => {\n const valToString = (val: any) =>\n val != null ? val.toString() : val;\n\n const defaultTypeBase = {\n encode: valToString,\n decode: valToString,\n is: is(String),\n pattern: /.*/,\n // tslint:disable-next-line:triple-equals\n equals: (a: any, b: any) => a == b, // allow coersion for null/undefined/\"\"\n };\n\n return extend({}, defaultTypeBase, def) as ParamTypeDefinition;\n };\n\n // Default Parameter Type Definitions\n extend(ParamTypes.prototype, {\n string: makeDefaultType({}),\n\n path: makeDefaultType({\n pattern: /[^/]*/,\n }),\n\n query: makeDefaultType({}),\n\n hash: makeDefaultType({\n inherit: false,\n }),\n\n int: makeDefaultType({\n decode: (val: string) => parseInt(val, 10),\n is: function(val: any) {\n return !isNullOrUndefined(val) && this.decode(val.toString()) === val;\n },\n pattern: /-?\\d+/,\n }),\n\n bool: makeDefaultType({\n encode: (val: any) => val && 1 || 0,\n decode: (val: string) => parseInt(val, 10) !== 0,\n is: is(Boolean),\n pattern: /0|1/,\n }),\n\n date: makeDefaultType({\n encode: function(val: any) {\n return !this.is(val) ? undefined : [\n val.getFullYear(),\n ('0' + (val.getMonth() + 1)).slice(-2),\n ('0' + val.getDate()).slice(-2),\n ].join('-');\n },\n decode: function(val: string) {\n if (this.is(val)) return val as Date;\n const match = this.capture.exec(val);\n return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n },\n is: (val: any) => val instanceof Date && !isNaN(val.valueOf()),\n equals(l: any, r: any) {\n return ['getFullYear', 'getMonth', 'getDate']\n .reduce((acc, fn) => acc && l[fn]() === r[fn](), true);\n },\n pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/,\n }),\n\n json: makeDefaultType({\n encode: toJson,\n decode: fromJson,\n is: is(Object),\n equals: equals,\n pattern: /[^/]*/,\n }),\n\n // does not encode/decode\n any: makeDefaultType({\n encode: identity,\n decode: identity,\n is: () => true,\n equals: equals,\n }),\n });\n}\n\ninitDefaultTypes();\n\n", - "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, ancestors, Obj } from '../common/common';\nimport { StateObject } from '../state/stateObject';\n\n/** @internalapi */\nexport class StateParams {\n [key: string]: any;\n\n constructor(params: Obj = {}) {\n extend(this, params);\n }\n\n /**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\n $inherit(newParams: Obj, $current: StateObject, $to: StateObject) {\n let parentParams: string[];\n const parents = ancestors($current, $to),\n inherited: Obj = {},\n inheritList: string[] = [];\n\n for (const i in parents) {\n if (!parents[i] || !parents[i].params) continue;\n parentParams = Object.keys(parents[i].params);\n if (!parentParams.length) continue;\n\n for (const j in parentParams) {\n if (inheritList.indexOf(parentParams[j]) >= 0) continue;\n inheritList.push(parentParams[j]);\n inherited[parentParams[j]] = this[parentParams[j]];\n }\n }\n return extend({}, inherited, newParams);\n }\n}\n\n", + "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { fromJson, toJson, identity, equals, inherit, map, extend, pick } from '../common/common';\nimport { isDefined, isNullOrUndefined } from '../common/predicates';\nimport { is } from '../common/hof';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * A registry for parameter types.\n *\n * This registry manages the built-in (and custom) parameter types.\n *\n * The built-in parameter types are:\n *\n * - [[string]]\n * - [[path]]\n * - [[query]]\n * - [[hash]]\n * - [[int]]\n * - [[bool]]\n * - [[date]]\n * - [[json]]\n * - [[any]]\n */\nexport class ParamTypes {\n /**\n * Built-in parameter type: `string`\n *\n * This parameter type coerces values to strings.\n * It matches anything (`new RegExp(\".*\")`) in the URL\n */\n static string: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `path`\n *\n * This parameter type is the default type for path parameters.\n * A path parameter is any parameter declared in the path portion of a url\n *\n * - `/foo/:param1/:param2`: two path parameters\n *\n * This parameter type behaves exactly like the [[string]] type with one exception.\n * When matching parameter values in the URL, the `path` type does not match forward slashes `/`.\n *\n * #### Angular 1 note:\n * In ng1, this type is overridden with one that pre-encodes slashes as `~2F` instead of `%2F`.\n * For more details about this angular 1 behavior, see: https://github.com/angular-ui/ui-router/issues/2598\n */\n static path: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `query`\n *\n * This parameter type is the default type for query/search parameters.\n * It behaves the same as the [[string]] parameter type.\n *\n * A query parameter is any parameter declared in the query/search portion of a url\n *\n * - `/bar?param2`: a query parameter\n */\n static query: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `hash`\n *\n * This parameter type is used for the `#` parameter (the hash)\n * It behaves the same as the [[string]] parameter type.\n * @coreapi\n */\n static hash: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `int`\n *\n * This parameter type serializes javascript integers (`number`s which represent an integer) to the URL.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'user',\n * url: '/user/{id:int}'\n * });\n * ```\n * ```js\n * $state.go('user', { id: 1298547 });\n * ```\n *\n * The URL will serialize to: `/user/1298547`.\n *\n * When the parameter value is read, it will be the `number` `1298547`, not the string `\"1298547\"`.\n */\n static int: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `bool`\n *\n * This parameter type serializes `true`/`false` as `1`/`0`\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'inbox',\n * url: '/inbox?{unread:bool}'\n * });\n * ```\n * ```js\n * $state.go('inbox', { unread: true });\n * ```\n *\n * The URL will serialize to: `/inbox?unread=1`.\n *\n * Conversely, if the url is `/inbox?unread=0`, the value of the `unread` parameter will be a `false`.\n */\n static bool: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `date`\n *\n * This parameter type can be used to serialize Javascript dates as parameter values.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'search',\n * url: '/search?{start:date}'\n * });\n * ```\n * ```js\n * $state.go('search', { start: new Date(2000, 0, 1) });\n * ```\n *\n * The URL will serialize to: `/search?start=2000-01-01`.\n *\n * Conversely, if the url is `/search?start=2016-12-25`, the value of the `start` parameter will be a `Date` object where:\n *\n * - `date.getFullYear() === 2016`\n * - `date.getMonth() === 11` (month is 0-based)\n * - `date.getDate() === 25`\n */\n static date: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `json`\n *\n * This parameter type can be used to serialize javascript objects into the URL using JSON serialization.\n *\n * #### Example:\n * This example serializes an plain javascript object to the URL\n * ```js\n * .state({\n * name: 'map',\n * url: '/map/{coords:json}'\n * });\n * ```\n * ```js\n * $state.go('map', { coords: { x: 10399.2, y: 49071 });\n * ```\n *\n * The URL will serialize to: `/map/%7B%22x%22%3A10399.2%2C%22y%22%3A49071%7D`\n */\n static json: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `any`\n *\n * This parameter type is used by default for url-less parameters (parameters that do not appear in the URL).\n * This type does not encode or decode.\n * It is compared using a deep `equals` comparison.\n *\n * #### Example:\n * This example defines a non-url parameter on a [[StateDeclaration]].\n * ```js\n * .state({\n * name: 'new',\n * url: '/new',\n * params: {\n * inrepyto: null\n * }\n * });\n * ```\n * ```js\n * $state.go('new', { inreplyto: currentMessage });\n * ```\n */\n static any: ParamTypeDefinition;\n\n /** @hidden */\n types: any;\n /** @hidden */\n enqueue = true;\n /** @hidden */\n typeQueue: any[] = [];\n\n /** @internalapi */\n private defaultTypes: any = pick(ParamTypes.prototype, [\n 'hash',\n 'string',\n 'query',\n 'path',\n 'int',\n 'bool',\n 'date',\n 'json',\n 'any',\n ]);\n\n /** @internalapi */\n constructor() {\n // Register default types. Store them in the prototype of this.types.\n const makeType = (definition: ParamTypeDefinition, name: string) => new ParamType(extend({ name }, definition));\n this.types = inherit(map(this.defaultTypes, makeType), {});\n }\n\n /** @internalapi */\n dispose() {\n this.types = {};\n }\n\n /**\n * Registers a parameter type\n *\n * End users should call [[UrlMatcherFactory.type]], which delegates to this method.\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n if (!isDefined(definition)) return this.types[name];\n if (this.types.hasOwnProperty(name)) throw new Error(`A type named '${name}' has already been defined.`);\n\n this.types[name] = new ParamType(extend({ name }, definition));\n\n if (definitionFn) {\n this.typeQueue.push({ name, def: definitionFn });\n if (!this.enqueue) this._flushTypeQueue();\n }\n\n return this;\n }\n\n /** @internalapi */\n _flushTypeQueue() {\n while (this.typeQueue.length) {\n const type = this.typeQueue.shift();\n if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n extend(this.types[type.name], services.$injector.invoke(type.def));\n }\n }\n}\n\n/** @hidden */\nfunction initDefaultTypes() {\n const makeDefaultType = def => {\n const valToString = (val: any) => (val != null ? val.toString() : val);\n\n const defaultTypeBase = {\n encode: valToString,\n decode: valToString,\n is: is(String),\n pattern: /.*/,\n // tslint:disable-next-line:triple-equals\n equals: (a: any, b: any) => a == b, // allow coersion for null/undefined/\"\"\n };\n\n return extend({}, defaultTypeBase, def) as ParamTypeDefinition;\n };\n\n // Default Parameter Type Definitions\n extend(ParamTypes.prototype, {\n string: makeDefaultType({}),\n\n path: makeDefaultType({\n pattern: /[^/]*/,\n }),\n\n query: makeDefaultType({}),\n\n hash: makeDefaultType({\n inherit: false,\n }),\n\n int: makeDefaultType({\n decode: (val: string) => parseInt(val, 10),\n is: function(val: any) {\n return !isNullOrUndefined(val) && this.decode(val.toString()) === val;\n },\n pattern: /-?\\d+/,\n }),\n\n bool: makeDefaultType({\n encode: (val: any) => (val && 1) || 0,\n decode: (val: string) => parseInt(val, 10) !== 0,\n is: is(Boolean),\n pattern: /0|1/,\n }),\n\n date: makeDefaultType({\n encode: function(val: any) {\n return !this.is(val)\n ? undefined\n : [val.getFullYear(), ('0' + (val.getMonth() + 1)).slice(-2), ('0' + val.getDate()).slice(-2)].join('-');\n },\n decode: function(val: string) {\n if (this.is(val)) return (val) as Date;\n const match = this.capture.exec(val);\n return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n },\n is: (val: any) => val instanceof Date && !isNaN(val.valueOf()),\n equals(l: any, r: any) {\n return ['getFullYear', 'getMonth', 'getDate'].reduce((acc, fn) => acc && l[fn]() === r[fn](), true);\n },\n pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/,\n }),\n\n json: makeDefaultType({\n encode: toJson,\n decode: fromJson,\n is: is(Object),\n equals: equals,\n pattern: /[^/]*/,\n }),\n\n // does not encode/decode\n any: makeDefaultType({\n encode: identity,\n decode: identity,\n is: () => true,\n equals: equals,\n }),\n });\n}\n\ninitDefaultTypes();\n", + "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, ancestors, Obj } from '../common/common';\nimport { StateObject } from '../state/stateObject';\n\n/** @internalapi */\nexport class StateParams {\n [key: string]: any;\n\n constructor(params: Obj = {}) {\n extend(this, params);\n }\n\n /**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\n $inherit(newParams: Obj, $current: StateObject, $to: StateObject) {\n let parentParams: string[];\n const parents = ancestors($current, $to),\n inherited: Obj = {},\n inheritList: string[] = [];\n\n for (const i in parents) {\n if (!parents[i] || !parents[i].params) continue;\n parentParams = Object.keys(parents[i].params);\n if (!parentParams.length) continue;\n\n for (const j in parentParams) {\n if (inheritList.indexOf(parentParams[j]) >= 0) continue;\n inheritList.push(parentParams[j]);\n inherited[parentParams[j]] = this[parentParams[j]];\n }\n }\n return extend({}, inherited, newParams);\n }\n}\n", "/** @module path */ /** for typedoc */\nexport * from './pathNode';\nexport * from './pathUtils';\n", "/** @module resolve */ /** for typedoc */\nexport * from './interface';\nexport * from './resolvable';\nexport * from './resolveContext';\n", - "/** @module state */ /** for typedoc */\nimport { Obj, omit, noop, extend, inherit, values, applyPairs, tail, mapObj, identity } from '../common/common';\nimport { isDefined, isFunction, isString, isArray } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { prop, pattern, is, pipe, val } from '../common/hof';\nimport { StateDeclaration } from './interface';\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { Param } from '../params/param';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { services } from '../common/coreservices';\nimport { ResolvePolicy } from '../resolve/interface';\nimport { ParamFactory } from '../url/interface';\n\nconst parseUrl = (url: string): any => {\n if (!isString(url)) return false;\n const root = url.charAt(0) === '^';\n return { val: root ? url.substring(1) : url, root };\n};\n\nexport type BuilderFunction = (state: StateObject, parent?: BuilderFunction) => any;\n\ninterface Builders {\n [key: string]: BuilderFunction[];\n\n name: BuilderFunction[];\n parent: BuilderFunction[];\n data: BuilderFunction[];\n url: BuilderFunction[];\n navigable: BuilderFunction[];\n params: BuilderFunction[];\n views: BuilderFunction[];\n path: BuilderFunction[];\n includes: BuilderFunction[];\n resolvables: BuilderFunction[];\n}\n\n\nfunction nameBuilder(state: StateObject) {\n return state.name;\n}\n\nfunction selfBuilder(state: StateObject) {\n state.self.$$state = () => state;\n return state.self;\n}\n\nfunction dataBuilder(state: StateObject) {\n if (state.parent && state.parent.data) {\n state.data = state.self.data = inherit(state.parent.data, state.data);\n }\n return state.data;\n}\n\nconst getUrlBuilder = ($urlMatcherFactoryProvider: UrlMatcherFactory, root: () => StateObject) =>\nfunction urlBuilder(state: StateObject) {\n const stateDec: StateDeclaration = state;\n\n // For future states, i.e., states whose name ends with `.**`,\n // match anything that starts with the url prefix\n if (stateDec && stateDec.url && stateDec.name && stateDec.name.match(/\\.\\*\\*$/)) {\n stateDec.url += '{remainder:any}'; // match any path (.*)\n }\n\n const parsed = parseUrl(stateDec.url), parent = state.parent;\n const url = !parsed ? stateDec.url : $urlMatcherFactoryProvider.compile(parsed.val, {\n params: state.params || {},\n paramMap: function (paramConfig: any, isSearch: boolean) {\n if (stateDec.reloadOnSearch === false && isSearch) paramConfig = extend(paramConfig || {}, { dynamic: true });\n return paramConfig;\n },\n });\n\n if (!url) return null;\n if (!$urlMatcherFactoryProvider.isMatcher(url)) throw new Error(`Invalid url '${url}' in state '${state}'`);\n return (parsed && parsed.root) ? url : ((parent && parent.navigable) || root()).url.append( url);\n};\n\nconst getNavigableBuilder = (isRoot: (state: StateObject) => boolean) =>\nfunction navigableBuilder(state: StateObject) {\n return !isRoot(state) && state.url ? state : (state.parent ? state.parent.navigable : null);\n};\n\nconst getParamsBuilder = (paramFactory: ParamFactory) =>\nfunction paramsBuilder(state: StateObject): { [key: string]: Param } {\n const makeConfigParam = (config: any, id: string) => paramFactory.fromConfig(id, null, config);\n const urlParams: Param[] = (state.url && state.url.parameters({ inherit: false })) || [];\n const nonUrlParams: Param[] = values(mapObj(omit(state.params || {}, urlParams.map(prop('id'))), makeConfigParam));\n return urlParams.concat(nonUrlParams).map(p => [p.id, p]).reduce(applyPairs, {});\n};\n\nfunction pathBuilder(state: StateObject) {\n return state.parent ? state.parent.path.concat(state) : /*root*/ [state];\n}\n\nfunction includesBuilder(state: StateObject) {\n const includes = state.parent ? extend({}, state.parent.includes) : {};\n includes[state.name] = true;\n return includes;\n}\n\n/**\n * This is a [[StateBuilder.builder]] function for the `resolve:` block on a [[StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * validates the `resolve` property and converts it to a [[Resolvable]] array.\n *\n * resolve: input value can be:\n *\n * {\n * // analyzed but not injected\n * myFooResolve: function() { return \"myFooData\"; },\n *\n * // function.toString() parsed, \"DependencyName\" dep as string (not min-safe)\n * myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },\n *\n * // Array split; \"DependencyName\" dep as string\n * myBazResolve: [ \"DependencyName\", function(dep) { return dep.fetchSomethingAsPromise() },\n *\n * // Array split; DependencyType dep as token (compared using ===)\n * myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },\n *\n * // val.$inject used as deps\n * // where:\n * // corgeResolve.$inject = [\"DependencyName\"];\n * // function corgeResolve(dep) { dep.fetchSometingAsPromise() }\n * // then \"DependencyName\" dep as string\n * myCorgeResolve: corgeResolve,\n *\n * // inject service by name\n * // When a string is found, desugar creating a resolve that injects the named service\n * myGraultResolve: \"SomeService\"\n * }\n *\n * or:\n *\n * [\n * new Resolvable(\"myFooResolve\", function() { return \"myFooData\" }),\n * new Resolvable(\"myBarResolve\", function(dep) { return dep.fetchSomethingAsPromise() }, [ \"DependencyName\" ]),\n * { provide: \"myBazResolve\", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ \"DependencyName\" ] }\n * ]\n */\nexport function resolvablesBuilder(state: StateObject): Resolvable[] {\n interface Tuple { token: any, val: any, deps: any[], policy: ResolvePolicy }\n\n /** convert resolve: {} and resolvePolicy: {} objects to an array of tuples */\n const objects2Tuples = (resolveObj: Obj, resolvePolicies: { [key: string]: ResolvePolicy }) =>\n Object.keys(resolveObj || {}).map(token => ({ token, val: resolveObj[token], deps: undefined, policy: resolvePolicies[token] }));\n\n /** fetch DI annotations from a function or ng1-style array */\n const annotate = (fn: Function) => {\n const $injector = services.$injector;\n // ng1 doesn't have an $injector until runtime.\n // If the $injector doesn't exist, use \"deferred\" literal as a\n // marker indicating they should be annotated when runtime starts\n return fn['$inject'] || ($injector && $injector.annotate(fn, $injector.strictDi)) || 'deferred';\n };\n\n /** true if the object has both `token` and `resolveFn`, and is probably a [[ResolveLiteral]] */\n const isResolveLiteral = (obj: any) => !!(obj.token && obj.resolveFn);\n\n /** true if the object looks like a provide literal, or a ng2 Provider */\n const isLikeNg2Provider = (obj: any) => !!((obj.provide || obj.token) && (obj.useValue || obj.useFactory || obj.useExisting || obj.useClass));\n\n /** true if the object looks like a tuple from obj2Tuples */\n const isTupleFromObj = (obj: any) => !!(obj && obj.val && (isString(obj.val) || isArray(obj.val) || isFunction(obj.val)));\n\n /** extracts the token from a Provider or provide literal */\n const getToken = (p: any) => p.provide || p.token;\n\n /** Given a literal resolve or provider object, returns a Resolvable */\n const literal2Resolvable = pattern([\n [prop('resolveFn'), p => new Resolvable(getToken(p), p.resolveFn, p.deps, p.policy)],\n [prop('useFactory'), p => new Resolvable(getToken(p), p.useFactory, (p.deps || p.dependencies), p.policy)],\n [prop('useClass'), p => new Resolvable(getToken(p), () => new (p.useClass)(), [], p.policy)],\n [prop('useValue'), p => new Resolvable(getToken(p), () => p.useValue, [], p.policy, p.useValue)],\n [prop('useExisting'), p => new Resolvable(getToken(p), identity, [p.useExisting], p.policy)],\n ]);\n\n const tuple2Resolvable = pattern([\n [pipe(prop('val'), isString), (tuple: Tuple) => new Resolvable(tuple.token, identity, [ tuple.val ], tuple.policy)],\n [pipe(prop('val'), isArray), (tuple: Tuple) => new Resolvable(tuple.token, tail( tuple.val), tuple.val.slice(0, -1), tuple.policy)],\n [pipe(prop('val'), isFunction), (tuple: Tuple) => new Resolvable(tuple.token, tuple.val, annotate(tuple.val), tuple.policy)],\n ]);\n\n const item2Resolvable = <(obj: any) => Resolvable> pattern([\n [is(Resolvable), (r: Resolvable) => r],\n [isResolveLiteral, literal2Resolvable],\n [isLikeNg2Provider, literal2Resolvable],\n [isTupleFromObj, tuple2Resolvable],\n [val(true), (obj: any) => { throw new Error('Invalid resolve value: ' + stringify(obj)); }],\n ]);\n\n // If resolveBlock is already an array, use it as-is.\n // Otherwise, assume it's an object and convert to an Array of tuples\n const decl = state.resolve;\n const items: any[] = isArray(decl) ? decl : objects2Tuples(decl, state.resolvePolicy || {});\n return items.map(item2Resolvable);\n}\n\n/**\n * @internalapi A internal global service\n *\n * StateBuilder is a factory for the internal [[StateObject]] objects.\n *\n * When you register a state with the [[StateRegistry]], you register a plain old javascript object which\n * conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding\n * [[StateObject]] object, which has an API and is used internally.\n *\n * Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function\n * using the [[builder]] method.\n */\nexport class StateBuilder {\n /** An object that contains all the BuilderFunctions registered, key'd by the name of the State property they build */\n private builders: Builders;\n\n constructor(private matcher: StateMatcher, urlMatcherFactory: UrlMatcherFactory) {\n const self = this;\n\n const root = () => matcher.find('');\n const isRoot = (state: StateObject) => state.name === '';\n\n function parentBuilder(state: StateObject) {\n if (isRoot(state)) return null;\n return matcher.find(self.parentName(state)) || root();\n }\n\n this.builders = {\n name: [ nameBuilder ],\n self: [ selfBuilder ],\n parent: [ parentBuilder ],\n data: [ dataBuilder ],\n // Build a URLMatcher if necessary, either via a relative or absolute URL\n url: [ getUrlBuilder(urlMatcherFactory, root) ],\n // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n navigable: [ getNavigableBuilder(isRoot) ],\n params: [ getParamsBuilder(urlMatcherFactory.paramFactory) ],\n // Each framework-specific ui-router implementation should define its own `views` builder\n // e.g., src/ng1/statebuilders/views.ts\n views: [],\n // Keep a full path from the root down to this state as this is needed for state activation.\n path: [ pathBuilder ],\n // Speed up $state.includes() as it's used a lot\n includes: [ includesBuilder ],\n resolvables: [ resolvablesBuilder ],\n };\n }\n\n /**\n * Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g., `parent`, `url`, or `path`).\n * More than one BuilderFunction can be registered for a given property.\n *\n * The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.\n *\n * @param name The name of the State property being registered for.\n * @param fn The BuilderFunction which will be used to build the State property\n * @returns a function which deregisters the BuilderFunction\n */\n builder(name: string, fn: BuilderFunction): (BuilderFunction|BuilderFunction[]|Function) {\n const builders = this.builders;\n const array = builders[name] || [];\n // Backwards compat: if only one builder exists, return it, else return whole arary.\n if (isString(name) && !isDefined(fn)) return array.length > 1 ? array : array[0];\n if (!isString(name) || !isFunction(fn)) return;\n\n builders[name] = array;\n builders[name].push(fn);\n return () => builders[name].splice(builders[name].indexOf(fn, 1)) && null;\n }\n\n /**\n * Builds all of the properties on an essentially blank State object, returning a State object which has all its\n * properties and API built.\n *\n * @param state an uninitialized State object\n * @returns the built State object\n */\n build(state: StateObject): StateObject {\n const { matcher, builders } = this;\n const parent = this.parentName(state);\n\n if (parent && !matcher.find(parent, undefined, false)) {\n return null;\n }\n\n for (const key in builders) {\n if (!builders.hasOwnProperty(key)) continue;\n const chain = builders[key].reduce((parentFn: BuilderFunction, step: BuilderFunction) => (_state) => step(_state, parentFn), noop);\n state[key] = chain(state);\n }\n return state;\n }\n\n parentName(state: StateObject) {\n // name = 'foo.bar.baz.**'\n const name = state.name || '';\n // segments = ['foo', 'bar', 'baz', '.**']\n const segments = name.split('.');\n // segments = ['foo', 'bar', 'baz']\n const lastSegment = segments.pop();\n // segments = ['foo', 'bar'] (ignore .** segment for future states)\n if (lastSegment === '**') segments.pop();\n\n if (segments.length) {\n if (state.parent) {\n throw new Error(`States that specify the 'parent:' property should not have a '.' in their name (${name})`);\n }\n\n // 'foo.bar'\n return segments.join('.');\n }\n\n if (!state.parent) return '';\n return isString(state.parent) ? state.parent : state.parent.name;\n }\n\n name(state: StateObject) {\n const name = state.name;\n if (name.indexOf('.') !== -1 || !state.parent) return name;\n\n const parentName = isString(state.parent) ? state.parent : state.parent.name;\n return parentName ? parentName + '.' + name : name;\n }\n}\n", - "/** @module state */ /** for typedoc */\nimport { isString } from '../common/predicates';\nimport { StateOrName } from './interface';\nimport { StateObject } from './stateObject';\nimport { values } from '../common/common';\n\nexport class StateMatcher {\n constructor (private _states: { [key: string]: StateObject }) { }\n\n isRelative(stateName: string) {\n stateName = stateName || '';\n return stateName.indexOf('.') === 0 || stateName.indexOf('^') === 0;\n }\n\n\n find(stateOrName: StateOrName, base?: StateOrName, matchGlob = true): StateObject {\n if (!stateOrName && stateOrName !== '') return undefined;\n const isStr = isString(stateOrName);\n let name: string = isStr ? stateOrName : (stateOrName).name;\n\n if (this.isRelative(name)) name = this.resolvePath(name, base);\n const state = this._states[name];\n\n if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n return state;\n } else if (isStr && matchGlob) {\n const _states = values(this._states);\n const matches = _states.filter(_state =>\n _state.__stateObjectCache.nameGlob &&\n _state.__stateObjectCache.nameGlob.matches(name),\n );\n\n if (matches.length > 1) {\n // tslint:disable-next-line:no-console\n console.log(`stateMatcher.find: Found multiple matches for ${name} using glob: `, matches.map(match => match.name));\n }\n return matches[0];\n }\n return undefined;\n }\n\n resolvePath(name: string, base: StateOrName) {\n if (!base) throw new Error(`No reference point given for path '${name}'`);\n\n const baseState: StateObject = this.find(base);\n\n const splitName = name.split('.');\n const pathLength = splitName.length;\n let i = 0, current = baseState;\n\n for (; i < pathLength; i++) {\n if (splitName[i] === '' && i === 0) {\n current = baseState;\n continue;\n }\n if (splitName[i] === '^') {\n if (!current.parent) throw new Error(`Path '${name}' not valid for state '${baseState.name}'`);\n current = current.parent;\n continue;\n }\n break;\n }\n const relName = splitName.slice(i).join('.');\n return current.name + (current.name && relName ? '.' : '') + relName;\n }\n}\n", - "/** @module state */ /** for typedoc */\nimport { inArray } from '../common/common';\nimport { isString } from '../common/predicates';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { StateObject } from './stateObject';\nimport { StateBuilder } from './stateBuilder';\nimport { StateRegistryListener, StateRegistry } from './stateRegistry';\nimport { Disposable } from '../interface';\nimport { UrlRouter } from '../url/urlRouter';\nimport { prop } from '../common/hof';\nimport { StateMatcher } from './stateMatcher';\n\n/** @internalapi */\nexport class StateQueueManager implements Disposable {\n queue: StateObject[];\n matcher: StateMatcher;\n\n constructor(\n private $registry: StateRegistry,\n private $urlRouter: UrlRouter,\n public states: { [key: string]: StateObject; },\n public builder: StateBuilder,\n public listeners: StateRegistryListener[]) {\n this.queue = [];\n this.matcher = $registry.matcher;\n }\n\n /** @internalapi */\n dispose() {\n this.queue = [];\n }\n\n register(stateDecl: _StateDeclaration) {\n const queue = this.queue;\n const state = StateObject.create(stateDecl);\n const name = state.name;\n\n if (!isString(name)) throw new Error('State must have a valid name');\n if (this.states.hasOwnProperty(name) || inArray(queue.map(prop('name')), name))\n throw new Error(`State '${name}' is already defined`);\n\n queue.push(state);\n this.flush();\n\n return state;\n }\n\n flush() {\n const { queue, states, builder } = this;\n const registered: StateObject[] = [], // states that got registered\n orphans: StateObject[] = [], // states that don't yet have a parent registered\n previousQueueLength = {}; // keep track of how long the queue when an orphan was first encountered\n const getState = (name) =>\n this.states.hasOwnProperty(name) && this.states[name];\n\n while (queue.length > 0) {\n const state: StateObject = queue.shift();\n const name = state.name;\n const result: StateObject = builder.build(state);\n const orphanIdx: number = orphans.indexOf(state);\n\n if (result) {\n const existingState = getState(name);\n if (existingState && existingState.name === name) {\n throw new Error(`State '${name}' is already defined`);\n }\n\n const existingFutureState = getState(name + '.**');\n if (existingFutureState) {\n // Remove future state of the same name\n this.$registry.deregister(existingFutureState);\n }\n\n states[name] = state;\n this.attachRoute(state);\n if (orphanIdx >= 0) orphans.splice(orphanIdx, 1);\n registered.push(state);\n continue;\n }\n\n const prev = previousQueueLength[name];\n previousQueueLength[name] = queue.length;\n if (orphanIdx >= 0 && prev === queue.length) {\n // Wait until two consecutive iterations where no additional states were dequeued successfully.\n // throw new Error(`Cannot register orphaned state '${name}'`);\n queue.push(state);\n return states;\n } else if (orphanIdx < 0) {\n orphans.push(state);\n }\n\n queue.push(state);\n }\n\n if (registered.length) {\n this.listeners.forEach(listener => listener('registered', registered.map(s => s.self)));\n }\n\n return states;\n }\n\n attachRoute(state: StateObject) {\n if (state.abstract || !state.url) return;\n\n this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(state));\n }\n}\n", - "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { StateBuilder } from './stateBuilder';\nimport { StateQueueManager } from './stateQueueManager';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { BuilderFunction } from './stateBuilder';\nimport { StateOrName } from './interface';\nimport { removeFrom } from '../common/common';\nimport { UIRouter } from '../router';\nimport { propEq } from '../common/hof';\n\n/**\n * The signature for the callback function provided to [[StateRegistry.onStatesChanged]].\n *\n * This callback receives two parameters:\n *\n * @param event a string; either \"registered\" or \"deregistered\"\n * @param states the list of [[StateDeclaration]]s that were registered (or deregistered).\n */\nexport type StateRegistryListener = (event: 'registered'|'deregistered', states: StateDeclaration[]) => void;\n\nexport class StateRegistry {\n private _root: StateObject;\n private states: { [key: string]: StateObject } = {};\n\n matcher: StateMatcher;\n private builder: StateBuilder;\n stateQueue: StateQueueManager;\n\n listeners: StateRegistryListener[] = [];\n\n /** @internalapi */\n constructor(private _router: UIRouter) {\n this.matcher = new StateMatcher(this.states);\n this.builder = new StateBuilder(this.matcher, _router.urlMatcherFactory);\n this.stateQueue = new StateQueueManager(this, _router.urlRouter, this.states, this.builder, this.listeners);\n this._registerRoot();\n }\n\n /** @internalapi */\n private _registerRoot() {\n const rootStateDef: StateDeclaration = {\n name: '',\n url: '^',\n views: null,\n params: {\n '#': { value: null, type: 'hash', dynamic: true },\n },\n abstract: true,\n };\n\n const _root = this._root = this.stateQueue.register(rootStateDef);\n _root.navigable = null;\n }\n\n /** @internalapi */\n dispose() {\n this.stateQueue.dispose();\n this.listeners = [];\n this.get().forEach(state => this.get(state) && this.deregister(state));\n }\n\n /**\n * Listen for a State Registry events\n *\n * Adds a callback that is invoked when states are registered or deregistered with the StateRegistry.\n *\n * #### Example:\n * ```js\n * let allStates = registry.get();\n *\n * // Later, invoke deregisterFn() to remove the listener\n * let deregisterFn = registry.onStatesChanged((event, states) => {\n * switch(event) {\n * case: 'registered':\n * states.forEach(state => allStates.push(state));\n * break;\n * case: 'deregistered':\n * states.forEach(state => {\n * let idx = allStates.indexOf(state);\n * if (idx !== -1) allStates.splice(idx, 1);\n * });\n * break;\n * }\n * });\n * ```\n *\n * @param listener a callback function invoked when the registered states changes.\n * The function receives two parameters, `event` and `state`.\n * See [[StateRegistryListener]]\n * @return a function that deregisters the listener\n */\n onStatesChanged(listener: StateRegistryListener): () => void {\n this.listeners.push(listener);\n return function deregisterListener() {\n removeFrom(this.listeners)(listener);\n }.bind(this);\n }\n\n /**\n * Gets the implicit root state\n *\n * Gets the root of the state tree.\n * The root state is implicitly created by UI-Router.\n * Note: this returns the internal [[StateObject]] representation, not a [[StateDeclaration]]\n *\n * @return the root [[StateObject]]\n */\n root() {\n return this._root;\n }\n\n /**\n * Adds a state to the registry\n *\n * Registers a [[StateDeclaration]] or queues it for registration.\n *\n * Note: a state will be queued if the state's parent isn't yet registered.\n *\n * @param stateDefinition the definition of the state to register.\n * @returns the internal [[StateObject]] object.\n * If the state was successfully registered, then the object is fully built (See: [[StateBuilder]]).\n * If the state was only queued, then the object is not fully built.\n */\n register(stateDefinition: _StateDeclaration): StateObject {\n return this.stateQueue.register(stateDefinition);\n }\n\n /** @hidden */\n private _deregisterTree(state: StateObject) {\n const all = this.get().map(s => s.$$state());\n const getChildren = (states: StateObject[]) => {\n const _children = all.filter(s => states.indexOf(s.parent) !== -1);\n return _children.length === 0 ? _children : _children.concat(getChildren(_children));\n };\n\n const children = getChildren([state]);\n const deregistered: StateObject[] = [state].concat(children).reverse();\n\n deregistered.forEach(_state => {\n const $ur = this._router.urlRouter;\n // Remove URL rule\n $ur.rules().filter(propEq('state', _state)).forEach($ur.removeRule.bind($ur));\n // Remove state from registry\n delete this.states[_state.name];\n });\n\n return deregistered;\n }\n\n /**\n * Removes a state from the registry\n *\n * This removes a state from the registry.\n * If the state has children, they are are also removed from the registry.\n *\n * @param stateOrName the state's name or object representation\n * @returns {StateObject[]} a list of removed states\n */\n deregister(stateOrName: StateOrName) {\n const _state = this.get(stateOrName);\n if (!_state) throw new Error(\"Can't deregister state; not found: \" + stateOrName);\n const deregisteredStates = this._deregisterTree(_state.$$state());\n\n this.listeners.forEach(listener => listener('deregistered', deregisteredStates.map(s => s.self)));\n return deregisteredStates;\n }\n\n /**\n * Gets all registered states\n *\n * Calling this method with no arguments will return a list of all the states that are currently registered.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @return a list of [[StateDeclaration]]s\n */\n get(): StateDeclaration[];\n\n /**\n * Gets a registered state\n *\n * Given a state or a name, finds and returns the [[StateDeclaration]] from the registry.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @param stateOrName either the name of a state, or a state object.\n * @param base the base state to use when stateOrName is relative.\n * @return a registered [[StateDeclaration]] that matched the `stateOrName`, or null if the state isn't registered.\n */\n get(stateOrName: StateOrName, base?: StateOrName): StateDeclaration;\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n if (arguments.length === 0)\n return Object.keys(this.states).map(name => this.states[name].self);\n const found = this.matcher.find(stateOrName, base);\n return found && found.self || null;\n }\n\n decorator(name: string, func: BuilderFunction) {\n return this.builder.builder(name, func);\n }\n}\n", - "/**\n * @coreapi\n * @module url\n */\n/** for typedoc */\nimport {\n map, defaults, inherit, identity, unnest, tail, find, Obj, pairs, allTrueR, unnestR, arrayTuples,\n} from '../common/common';\nimport { prop, propEq } from '../common/hof';\nimport { isArray, isString, isDefined } from '../common/predicates';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { RawParams } from '../params/interface';\nimport { ParamFactory } from './interface';\nimport { joinNeighborsR, splitOnDelim } from '../common/strings';\n\n/** @hidden */\nfunction quoteRegExp(str: any, param?: any) {\n let surroundPattern = ['', ''], result = str.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, '\\\\$&');\n if (!param) return result;\n\n switch (param.squash) {\n case false:\n surroundPattern = ['(', ')' + (param.isOptional ? '?' : '')]; break;\n case true:\n result = result.replace(/\\/$/, '');\n surroundPattern = ['(?:\\/(', ')|\\/)?'];\n break;\n default:\n surroundPattern = [`(${param.squash}|`, ')?']; break;\n }\n return result + surroundPattern[0] + param.type.pattern.source + surroundPattern[1];\n}\n\n/** @hidden */\nconst memoizeTo = (obj: Obj, _prop: string, fn: Function) =>\n obj[_prop] = obj[_prop] || fn();\n\n/** @hidden */\nconst splitOnSlash = splitOnDelim('/');\n\n/** @hidden */\ninterface UrlMatcherCache {\n segments?: any[];\n weights?: number[];\n path?: UrlMatcher[];\n parent?: UrlMatcher;\n pattern?: RegExp;\n}\n\n/**\n * Matches URLs against patterns.\n *\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL.\n *\n * A URL pattern consists of a path pattern, optionally followed by '?' and a list of search (query)\n * parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by [[UrlMatcher.exec]].\n *\n * - *Path parameters* are defined using curly brace placeholders (`/somepath/{param}`)\n * or colon placeholders (`/somePath/:param`).\n *\n * - *A parameter RegExp* may be defined for a param after a colon\n * (`/somePath/{param:[a-zA-Z0-9]+}`) in a curly brace placeholder.\n * The regexp must match for the url to be matched.\n * Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Note: a RegExp parameter will encode its value using either [[ParamTypes.path]] or [[ParamTypes.query]].\n *\n * - *Custom parameter types* may also be specified after a colon (`/somePath/{param:int}`) in curly brace parameters.\n * See [[UrlMatcherFactory.type]] for more information.\n *\n * - *Catch-all parameters* are defined using an asterisk placeholder (`/somepath/*catchallparam`).\n * A catch-all * parameter value will contain the remainder of the URL.\n *\n * ---\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters).\n * A path parameter matches any number of characters other than '/'. For catch-all\n * placeholders the path parameter matches any number of characters.\n *\n * Examples:\n *\n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n * trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n * parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n * path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n * in the built-in `date` ParamType matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n */\nexport class UrlMatcher {\n /** @hidden */\n static nameValidator: RegExp = /^\\w+([-.]+\\w+)*(?:\\[\\])?$/;\n\n /** @hidden */\n private _cache: UrlMatcherCache = { path: [this] };\n /** @hidden */\n private _children: UrlMatcher[] = [];\n /** @hidden */\n private _params: Param[] = [];\n /** @hidden */\n private _segments: string[] = [];\n /** @hidden */\n private _compiled: string[] = [];\n\n /** The pattern that was passed into the constructor */\n public pattern: string;\n\n /** @hidden */\n static encodeDashes(str: string) { // Replace dashes with encoded \"\\-\"\n return encodeURIComponent(str).replace(/-/g, c => `%5C%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n }\n\n /** @hidden Given a matcher, return an array with the matcher's path segments and path params, in order */\n static pathSegmentsAndParams(matcher: UrlMatcher) {\n const staticSegments = matcher._segments;\n const pathParams = matcher._params.filter(p => p.location === DefType.PATH);\n return arrayTuples(staticSegments, pathParams.concat(undefined))\n .reduce(unnestR, [])\n .filter(x => x !== '' && isDefined(x));\n }\n\n /** @hidden Given a matcher, return an array with the matcher's query params */\n static queryParams(matcher: UrlMatcher): Param[] {\n return matcher._params.filter(p => p.location === DefType.SEARCH);\n }\n\n /**\n * Compare two UrlMatchers\n *\n * This comparison function converts a UrlMatcher into static and dynamic path segments.\n * Each static path segment is a static string between a path separator (slash character).\n * Each dynamic segment is a path parameter.\n *\n * The comparison function sorts static segments before dynamic ones.\n */\n static compare(a: UrlMatcher, b: UrlMatcher): number {\n /**\n * Turn a UrlMatcher and all its parent matchers into an array\n * of slash literals '/', string literals, and Param objects\n *\n * This example matcher matches strings like \"/foo/:param/tail\":\n * var matcher = $umf.compile(\"/foo\").append($umf.compile(\"/:param\")).append($umf.compile(\"/\")).append($umf.compile(\"tail\"));\n * var result = segments(matcher); // [ '/', 'foo', '/', Param, '/', 'tail' ]\n *\n * Caches the result as `matcher._cache.segments`\n */\n const segments = (matcher: UrlMatcher) =>\n matcher._cache.segments = matcher._cache.segments ||\n matcher._cache.path.map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .reduce(joinNeighborsR, [])\n .map(x => isString(x) ? splitOnSlash(x) : x)\n .reduce(unnestR, []);\n\n /**\n * Gets the sort weight for each segment of a UrlMatcher\n *\n * Caches the result as `matcher._cache.weights`\n */\n const weights = (matcher: UrlMatcher) =>\n matcher._cache.weights = matcher._cache.weights ||\n segments(matcher).map(segment => {\n // Sort slashes first, then static strings, the Params\n if (segment === '/') return 1;\n if (isString(segment)) return 2;\n if (segment instanceof Param) return 3;\n });\n\n /**\n * Pads shorter array in-place (mutates)\n */\n const padArrays = (l: any[], r: any[], padVal: any) => {\n const len = Math.max(l.length, r.length);\n while (l.length < len) l.push(padVal);\n while (r.length < len) r.push(padVal);\n };\n\n const weightsA = weights(a), weightsB = weights(b);\n padArrays(weightsA, weightsB, 0);\n\n const _pairs = arrayTuples(weightsA, weightsB);\n let cmp, i;\n\n for (i = 0; i < _pairs.length; i++) {\n cmp = _pairs[i][0] - _pairs[i][1];\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n }\n\n /**\n * @param pattern The pattern to compile into a matcher.\n * @param paramTypes The [[ParamTypes]] registry\n * @param config A configuration object\n * - `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * - `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n */\n constructor(pattern: string, paramTypes: ParamTypes, paramFactory: ParamFactory, public config?: any) {\n this.pattern = pattern;\n this.config = defaults(this.config, {\n params: {},\n strict: true,\n caseInsensitive: false,\n paramMap: identity,\n });\n\n // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n // '*' name\n // ':' name\n // '{' name '}'\n // '{' name ':' regexp '}'\n // The regular expression is somewhat complicated due to the need to allow curly braces\n // inside the regular expression. The placeholder regexp breaks down as follows:\n // ([:*])([\\w\\[\\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)\n // \\{([\\w\\[\\]]+)(?:\\:\\s*( ... ))?\\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either\n // [^{}\\\\]+ - anything other than curly braces or backslash\n // \\\\. - a backslash escape\n // \\{(?:[^{}\\\\]+|\\\\.)*\\} - a matched set of curly braces containing other atoms\n const placeholder = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const searchPlaceholder = /([:]?)([\\w\\[\\].-]+)|\\{([\\w\\[\\].-]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const patterns: any[][] = [];\n let last = 0, matchArray: RegExpExecArray;\n\n const checkParamErrors = (id: string) => {\n if (!UrlMatcher.nameValidator.test(id)) throw new Error(`Invalid parameter name '${id}' in pattern '${pattern}'`);\n if (find(this._params, propEq('id', id))) throw new Error(`Duplicate parameter name '${id}' in pattern '${pattern}'`);\n };\n\n // Split into static segments separated by path parameter placeholders.\n // The number of segments is always 1 more than the number of parameters.\n const matchDetails = (m: RegExpExecArray, isSearch: boolean) => {\n // IE[78] returns '' for unmatched groups instead of null\n const id: string = m[2] || m[3];\n const regexp: string = isSearch ? m[4] : m[4] || (m[1] === '*' ? '[\\\\s\\\\S]*' : null);\n\n const makeRegexpType = (str) => inherit(paramTypes.type(isSearch ? 'query' : 'path'), {\n pattern: new RegExp(str, this.config.caseInsensitive ? 'i' : undefined),\n });\n\n return {\n id,\n regexp,\n cfg: this.config.params[id],\n segment: pattern.substring(last, m.index),\n type: !regexp ? null : paramTypes.type(regexp) || makeRegexpType(regexp),\n };\n };\n\n let p: any, segment: string;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = placeholder.exec(pattern))) {\n p = matchDetails(matchArray, false);\n if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromPath(p.id, p.type, this.config.paramMap(p.cfg, false)));\n this._segments.push(p.segment);\n patterns.push([p.segment, tail(this._params)]);\n last = placeholder.lastIndex;\n }\n segment = pattern.substring(last);\n\n // Find any search parameter names and remove them from the last segment\n const i = segment.indexOf('?');\n\n if (i >= 0) {\n const search = segment.substring(i);\n segment = segment.substring(0, i);\n\n if (search.length > 0) {\n last = 0;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = searchPlaceholder.exec(search))) {\n p = matchDetails(matchArray, true);\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromSearch(p.id, p.type, this.config.paramMap(p.cfg, true)));\n last = placeholder.lastIndex;\n // check if ?&\n }\n }\n }\n\n this._segments.push(segment);\n this._compiled = patterns.map(_pattern => quoteRegExp.apply(null, _pattern)).concat(quoteRegExp(segment));\n }\n\n /**\n * Creates a new concatenated UrlMatcher\n *\n * Builds a new UrlMatcher by appending another UrlMatcher to this one.\n *\n * @param url A `UrlMatcher` instance to append as a child of the current `UrlMatcher`.\n */\n append(url: UrlMatcher): UrlMatcher {\n this._children.push(url);\n url._cache = {\n path: this._cache.path.concat(url),\n parent: this,\n pattern: null,\n };\n return url;\n }\n\n /** @hidden */\n isRoot(): boolean {\n return this._cache.path[0] === this;\n }\n\n /** Returns the input pattern string */\n toString(): string {\n return this.pattern;\n }\n\n /**\n * Tests the specified url/path against this matcher.\n *\n * Tests if the given url matches this matcher's pattern, and returns an object containing the captured\n * parameter values. Returns null if the path does not match.\n *\n * The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `search`. This means that search parameters are always treated\n * as optional.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n * x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * ```\n *\n * @param path The URL path to match, e.g. `$location.path()`.\n * @param search URL search parameters, e.g. `$location.search()`.\n * @param hash URL hash e.g. `$location.hash()`.\n * @param options\n *\n * @returns The captured parameter values.\n */\n exec(path: string, search: any = {}, hash?: string, options: any = {}): RawParams {\n const match = memoizeTo(this._cache, 'pattern', () => {\n return new RegExp([\n '^',\n unnest(this._cache.path.map(prop('_compiled'))).join(''),\n this.config.strict === false ? '\\/?' : '',\n '$',\n ].join(''), this.config.caseInsensitive ? 'i' : undefined);\n }).exec(path);\n\n if (!match) return null;\n\n // options = defaults(options, { isolate: false });\n\n const allParams: Param[] = this.parameters(),\n pathParams: Param[] = allParams.filter(param => !param.isSearch()),\n searchParams: Param[] = allParams.filter(param => param.isSearch()),\n nPathSegments = this._cache.path.map(urlm => urlm._segments.length - 1).reduce((a, x) => a + x),\n values: RawParams = {};\n\n if (nPathSegments !== match.length - 1)\n throw new Error(`Unbalanced capture group in route '${this.pattern}'`);\n\n function decodePathArray(paramVal: string) {\n const reverseString = (str: string) => str.split('').reverse().join('');\n const unquoteDashes = (str: string) => str.replace(/\\\\-/g, '-');\n\n const split = reverseString(paramVal).split(/-(?!\\\\)/);\n const allReversed = map(split, reverseString);\n return map(allReversed, unquoteDashes).reverse();\n }\n\n for (let i = 0; i < nPathSegments; i++) {\n const param: Param = pathParams[i];\n let value: (any|any[]) = match[i + 1];\n\n // if the param value matches a pre-replace pair, replace the value before decoding.\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (value && param.array === true) value = decodePathArray(value);\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n }\n searchParams.forEach(param => {\n let value = search[param.id];\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n });\n\n if (hash) values['#'] = hash;\n\n return values;\n }\n\n /**\n * @hidden\n * Returns all the [[Param]] objects of all path and search parameters of this pattern in order of appearance.\n *\n * @returns {Array.} An array of [[Param]] objects. Must be treated as read-only. If the\n * pattern has no parameters, an empty array is returned.\n */\n parameters(opts: any = {}): Param[] {\n if (opts.inherit === false) return this._params;\n return unnest(this._cache.path.map(matcher => matcher._params));\n }\n\n /**\n * @hidden\n * Returns a single parameter from this UrlMatcher by id\n *\n * @param id\n * @param opts\n * @returns {T|Param|any|boolean|UrlMatcher|null}\n */\n parameter(id: string, opts: any = {}): Param {\n const findParam = () => {\n for (const param of this._params) {\n if (param.id === id) return param;\n }\n };\n\n const parent = this._cache.parent;\n return findParam() || (opts.inherit !== false && parent && parent.parameter(id, opts)) || null;\n }\n\n /**\n * Validates the input parameter values against this UrlMatcher\n *\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param params The object hash of parameters to validate.\n * @returns Returns `true` if `params` validates, otherwise `false`.\n */\n validates(params: RawParams): boolean {\n const validParamVal = (param: Param, val: any) =>\n !param || param.validates(val);\n\n params = params || {};\n\n // I'm not sure why this checks only the param keys passed in, and not all the params known to the matcher\n const paramSchema = this.parameters().filter(paramDef => params.hasOwnProperty(paramDef.id));\n return paramSchema.map(paramDef => validParamVal(paramDef, params[paramDef.id])).reduce(allTrueR, true);\n }\n\n /**\n * Given a set of parameter values, creates a URL from this UrlMatcher.\n *\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * ```\n *\n * @param values the values to substitute for the parameters in this pattern.\n * @returns the formatted URL (path and optionally search part).\n */\n format(values: RawParams = {}) {\n // Build the full path of UrlMatchers (including all parent UrlMatchers)\n const urlMatchers = this._cache.path;\n\n // Extract all the static segments and Params (processed as ParamDetails)\n // into an ordered array\n const pathSegmentsAndParams: Array = urlMatchers.map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .map(x => isString(x) ? x : getDetails(x));\n\n // Extract the query params into a separate array\n const queryParams: Array = urlMatchers.map(UrlMatcher.queryParams)\n .reduce(unnestR, [])\n .map(getDetails);\n\n const isInvalid = (param: ParamDetails) => param.isValid === false;\n if (pathSegmentsAndParams.concat(queryParams).filter(isInvalid).length) {\n return null;\n }\n\n /**\n * Given a Param, applies the parameter value, then returns detailed information about it\n */\n function getDetails(param: Param): ParamDetails {\n // Normalize to typed value\n const value = param.value(values[param.id]);\n const isValid = param.validates(value);\n const isDefaultValue = param.isDefaultValue(value);\n // Check if we're in squash mode for the parameter\n const squash = isDefaultValue ? param.squash : false;\n // Allow the Parameter's Type to encode the value\n const encoded = param.type.encode(value);\n\n return { param, value, isValid, isDefaultValue, squash, encoded };\n }\n\n // Build up the path-portion from the list of static segments and parameters\n const pathString = pathSegmentsAndParams.reduce((acc: string, x: string|ParamDetails) => {\n // The element is a static segment (a raw string); just append it\n if (isString(x)) return acc + x;\n\n // Otherwise, it's a ParamDetails.\n const { squash, encoded, param } = x;\n\n // If squash is === true, try to remove a slash from the path\n if (squash === true) return (acc.match(/\\/$/)) ? acc.slice(0, -1) : acc;\n // If squash is a string, use the string for the param value\n if (isString(squash)) return acc + squash;\n if (squash !== false) return acc; // ?\n if (encoded == null) return acc;\n // If this parameter value is an array, encode the value using encodeDashes\n if (isArray(encoded)) return acc + map( encoded, UrlMatcher.encodeDashes).join('-');\n // If the parameter type is \"raw\", then do not encodeURIComponent\n if (param.raw) return acc + encoded;\n // Encode the value\n return acc + encodeURIComponent( encoded);\n }, '');\n\n // Build the query string by applying parameter values (array or regular)\n // then mapping to key=value, then flattening and joining using \"&\"\n const queryString = queryParams.map((paramDetails: ParamDetails) => {\n let { param, squash, encoded, isDefaultValue } = paramDetails;\n if (encoded == null || (isDefaultValue && squash !== false)) return;\n if (!isArray(encoded)) encoded = [ encoded];\n if (encoded.length === 0) return;\n if (!param.raw) encoded = map( encoded, encodeURIComponent);\n\n return ( encoded).map(val => `${param.id}=${val}`);\n }).filter(identity).reduce(unnestR, []).join('&');\n\n // Concat the pathstring with the queryString (if exists) and the hashString (if exists)\n return pathString + (queryString ? `?${queryString}` : '') + (values['#'] ? '#' + values['#'] : '');\n }\n}\n\n/** @hidden */\ninterface ParamDetails {\n param: Param;\n value: any;\n isValid: boolean;\n isDefaultValue: boolean;\n squash: (boolean|string);\n encoded: (string|string[]);\n}\n", - "/**\n * @internalapi\n * @module url\n */ /** for typedoc */\nimport { forEach, extend } from '../common/common';\nimport { isObject, isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { ParamTypeDefinition } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { ParamType } from '../params/paramType';\nimport { ParamFactory, UrlMatcherConfig } from './interface';\n\n/**\n * Factory for [[UrlMatcher]] instances.\n *\n * The factory is available to ng1 services as\n * `$urlMatcherFactory` or ng1 providers as `$urlMatcherFactoryProvider`.\n */\nexport class UrlMatcherFactory implements Disposable, UrlMatcherConfig {\n /** @hidden */ paramTypes = new ParamTypes();\n /** @hidden */ _isCaseInsensitive = false;\n /** @hidden */ _isStrictMode = true;\n /** @hidden */ _defaultSquashPolicy: (boolean|string) = false;\n\n /** @internalapi Creates a new [[Param]] for a given location (DefType) */\n paramFactory: ParamFactory = {\n /** Creates a new [[Param]] from a CONFIG block */\n fromConfig: (id: string, type: ParamType, config: any) =>\n new Param(id, type, config, DefType.CONFIG, this),\n\n /** Creates a new [[Param]] from a url PATH */\n fromPath: (id: string, type: ParamType, config: any) =>\n new Param(id, type, config, DefType.PATH, this),\n\n /** Creates a new [[Param]] from a url SEARCH */\n fromSearch: (id: string, type: ParamType, config: any) =>\n new Param(id, type, config, DefType.SEARCH, this),\n };\n\n constructor() {\n extend(this, { UrlMatcher, Param });\n }\n\n /** @inheritdoc */\n caseInsensitive(value?: boolean): boolean {\n return this._isCaseInsensitive = isDefined(value) ? value : this._isCaseInsensitive;\n }\n\n /** @inheritdoc */\n strictMode(value?: boolean): boolean {\n return this._isStrictMode = isDefined(value) ? value : this._isStrictMode;\n }\n\n /** @inheritdoc */\n defaultSquashPolicy(value?: (boolean|string)) {\n if (isDefined(value) && value !== true && value !== false && !isString(value))\n throw new Error(`Invalid squash policy: ${value}. Valid policies: false, true, arbitrary-string`);\n return this._defaultSquashPolicy = isDefined(value) ? value : this._defaultSquashPolicy;\n }\n\n /** @hidden */\n private _getConfig = (config) =>\n extend({ strict: this._isStrictMode, caseInsensitive: this._isCaseInsensitive }, config);\n\n /**\n * Creates a [[UrlMatcher]] for the specified pattern.\n *\n * @param pattern The URL pattern.\n * @param config The config object hash.\n * @returns The UrlMatcher.\n */\n compile(pattern: string, config?: { [key: string]: any }) {\n return new UrlMatcher(pattern, this.paramTypes, this.paramFactory, this._getConfig(config));\n }\n\n /**\n * Returns true if the specified object is a [[UrlMatcher]], or false otherwise.\n *\n * @param object The object to perform the type check against.\n * @returns `true` if the object matches the `UrlMatcher` interface, by\n * implementing all the same methods.\n */\n isMatcher(object: any): boolean {\n // TODO: typeof?\n if (!isObject(object)) return false;\n let result = true;\n\n forEach(UrlMatcher.prototype, (val, name) => {\n if (isFunction(val)) result = result && (isDefined(object[name]) && isFunction(object[name]));\n });\n return result;\n }\n\n /**\n * Creates and registers a custom [[ParamType]] object\n *\n * A [[ParamType]] can be used to generate URLs with typed parameters.\n *\n * @param name The type name.\n * @param definition The type definition. See [[ParamTypeDefinition]] for information on the values accepted.\n * @param definitionFn A function that is injected before the app runtime starts.\n * The result of this function should be a [[ParamTypeDefinition]].\n * The result is merged into the existing `definition`.\n * See [[ParamType]] for information on the values accepted.\n *\n * @returns - if a type was registered: the [[UrlMatcherFactory]]\n * - if only the `name` parameter was specified: the currently registered [[ParamType]] object, or undefined\n *\n * Note: Register custom types *before using them* in a state definition.\n *\n * See [[ParamTypeDefinition]] for examples\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n const type = this.paramTypes.type(name, definition, definitionFn);\n return !isDefined(definition) ? type : this;\n }\n\n /** @hidden */\n $get() {\n this.paramTypes.enqueue = false;\n this.paramTypes._flushTypeQueue();\n return this;\n }\n\n /** @internalapi */\n dispose() {\n this.paramTypes.dispose();\n }\n}\n", - "/**\n * @coreapi\n * @module url\n */ /** */\nimport { UrlMatcher } from './urlMatcher';\nimport { isString, isDefined, isFunction, isState } from '../common/predicates';\nimport { UIRouter } from '../router';\nimport { identity, extend } from '../common/common';\nimport { is, pattern } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport {\n UrlRule, UrlRuleMatchFn, UrlRuleHandlerFn, UrlRuleType, UrlParts, MatcherUrlRule, StateRule, RegExpRule,\n} from './interface';\n\n/**\n * Creates a [[UrlRule]]\n *\n * Creates a [[UrlRule]] from a:\n *\n * - `string`\n * - [[UrlMatcher]]\n * - `RegExp`\n * - [[StateObject]]\n * @internalapi\n */\nexport class UrlRuleFactory {\n static isUrlRule = obj =>\n obj && ['type', 'match', 'handler'].every(key => isDefined(obj[key]));\n\n constructor(public router: UIRouter) { }\n\n compile(str: string) {\n return this.router.urlMatcherFactory.compile(str);\n }\n\n create(what: string|UrlMatcher|StateObject|RegExp|UrlRuleMatchFn, handler?: string|UrlRuleHandlerFn): UrlRule {\n const makeRule = pattern([\n [isString, (_what: string) => makeRule(this.compile(_what))],\n [is(UrlMatcher), (_what: UrlMatcher) => this.fromUrlMatcher(_what, handler)],\n [isState, (_what: StateObject) => this.fromState(_what, this.router)],\n [is(RegExp), (_what: RegExp) => this.fromRegExp(_what, handler)],\n [isFunction, (_what: UrlRuleMatchFn) => new BaseUrlRule(_what, handler as UrlRuleHandlerFn)],\n ]);\n\n const rule = makeRule(what);\n if (!rule) throw new Error(\"invalid 'what' in when()\");\n return rule;\n }\n\n /**\n * A UrlRule which matches based on a UrlMatcher\n *\n * The `handler` may be either a `string`, a [[UrlRuleHandlerFn]] or another [[UrlMatcher]]\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - matched parameter values ([[RawParams]] from [[UrlMatcher.exec]])\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, match => \"/home/\" + match.fooId + \"/\" + match.barId);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n *\n * ## Handler as UrlMatcher\n *\n * If `handler` is a UrlMatcher, the handler matcher is used to create the new url.\n * The `handler` UrlMatcher is formatted using the matched param from the first matcher.\n * The url is replaced with the result.\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var handler = $umf.compile(\"/home/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, handler);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n */\n fromUrlMatcher(urlMatcher: UrlMatcher, handler: string|UrlMatcher|UrlRuleHandlerFn): MatcherUrlRule {\n let _handler: UrlRuleHandlerFn = handler as any;\n if (isString(handler)) handler = this.router.urlMatcherFactory.compile(handler);\n if (is(UrlMatcher)(handler)) _handler = (match: RawParams) => (handler as UrlMatcher).format(match);\n\n function matchUrlParamters(url: UrlParts): RawParams {\n const params = urlMatcher.exec(url.path, url.search, url.hash);\n return urlMatcher.validates(params) && params;\n }\n\n // Prioritize URLs, lowest to highest:\n // - Some optional URL parameters, but none matched\n // - No optional parameters in URL\n // - Some optional parameters, some matched\n // - Some optional parameters, all matched\n function matchPriority(params: RawParams): number {\n const optional = urlMatcher.parameters().filter(param => param.isOptional);\n if (!optional.length) return 0.000001;\n const matched = optional.filter(param => params[param.id]);\n return matched.length / optional.length;\n }\n\n const details = { urlMatcher, matchPriority, type: 'URLMATCHER' };\n return extend(new BaseUrlRule(matchUrlParamters, _handler), details) as MatcherUrlRule;\n }\n\n\n /**\n * A UrlRule which matches a state by its url\n *\n * #### Example:\n * ```js\n * var rule = factory.fromState($state.get('foo'), router);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match);\n * // Starts a transition to 'foo' with params: { fooId: '123', barId: '456' }\n * ```\n */\n fromState(state: StateObject, router: UIRouter): StateRule {\n /**\n * Handles match by transitioning to matched state\n *\n * First checks if the router should start a new transition.\n * A new transition is not required if the current state's URL\n * and the new URL are already identical\n */\n const handler = (match: RawParams) => {\n const $state = router.stateService;\n const globals = router.globals;\n if ($state.href(state, match) !== $state.href(globals.current, globals.params)) {\n $state.transitionTo(state, match, { inherit: true, source: 'url' });\n }\n };\n\n const details = { state, type: 'STATE' };\n return extend(this.fromUrlMatcher(state.url, handler), details) as StateRule;\n }\n\n /**\n * A UrlRule which matches based on a regular expression\n *\n * The `handler` may be either a [[UrlRuleHandlerFn]] or a string.\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - regexp match array (from `regexp`)\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, match => \"/home/\" + match[1])\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n *\n * ## Handler as string\n *\n * If `handler` is a string, the url is *replaced by the string* when the Rule is invoked.\n * The string is first interpolated using `string.replace()` style pattern.\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, \"/home/$1\")\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n */\n fromRegExp(regexp: RegExp, handler: string|UrlRuleHandlerFn): RegExpRule {\n if (regexp.global || regexp.sticky) throw new Error('Rule RegExp must not be global or sticky');\n\n /**\n * If handler is a string, the url will be replaced by the string.\n * If the string has any String.replace() style variables in it (like `$2`),\n * they will be replaced by the captures from [[match]]\n */\n const redirectUrlTo = (match: RegExpExecArray) =>\n // Interpolates matched values into $1 $2, etc using a String.replace()-style pattern\n (handler as string).replace(/\\$(\\$|\\d{1,2})/, (m, what) =>\n match[what === '$' ? 0 : Number(what)]);\n\n const _handler = isString(handler) ? redirectUrlTo : handler;\n\n const matchParamsFromRegexp = (url: UrlParts): RegExpExecArray =>\n regexp.exec(url.path);\n\n const details = { regexp, type: 'REGEXP' };\n return extend(new BaseUrlRule(matchParamsFromRegexp, _handler), details) as RegExpRule;\n }\n}\n\n/**\n * A base rule which calls `match`\n *\n * The value from the `match` function is passed through to the `handler`.\n * @internalapi\n */\nexport class BaseUrlRule implements UrlRule {\n $id: number;\n priority: number;\n type: UrlRuleType = 'RAW';\n handler: UrlRuleHandlerFn;\n matchPriority = (match) => 0 - this.$id;\n\n constructor(public match: UrlRuleMatchFn, handler?: UrlRuleHandlerFn) {\n this.handler = handler || identity;\n }\n}\n", - "/**\n * @internalapi\n * @module url\n */\n/** for typedoc */\nimport { createProxyFunctions, extend, removeFrom } from '../common/common';\nimport { isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { RawParams } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { is, pattern, val } from '../common/hof';\nimport { UrlRuleFactory } from './urlRule';\nimport { TargetState } from '../state/targetState';\nimport { MatcherUrlRule, MatchResult, UrlParts, UrlRule, UrlRuleHandlerFn, UrlRuleMatchFn, UrlRulesApi, UrlSyncApi } from './interface';\nimport { TargetStateDef } from '../state/interface';\nimport { stripLastPathElement } from '../common';\n\n/** @hidden */\nfunction appendBasePath(url: string, isHtml5: boolean, absolute: boolean, baseHref: string): string {\n if (baseHref === '/') return url;\n if (isHtml5) return stripLastPathElement(baseHref) + url;\n if (absolute) return baseHref.slice(1) + url;\n return url;\n}\n\n/** @hidden */\nconst prioritySort = (a: UrlRule, b: UrlRule) =>\n (b.priority || 0) - (a.priority || 0);\n\n/** @hidden */\nconst typeSort = (a: UrlRule, b: UrlRule) => {\n const weights = { 'STATE': 4, 'URLMATCHER': 4, 'REGEXP': 3, 'RAW': 2, 'OTHER': 1 };\n return (weights[a.type] || 0) - (weights[b.type] || 0);\n};\n\n/** @hidden */\nconst urlMatcherSort = (a: MatcherUrlRule, b: MatcherUrlRule) =>\n !a.urlMatcher || !b.urlMatcher ? 0 : UrlMatcher.compare(a.urlMatcher, b.urlMatcher);\n\n/** @hidden */\nconst idSort = (a: UrlRule, b: UrlRule) => {\n // Identically sorted STATE and URLMATCHER best rule will be chosen by `matchPriority` after each rule matches the URL\n const useMatchPriority = { STATE: true, URLMATCHER: true };\n const equal = useMatchPriority[a.type] && useMatchPriority[b.type];\n return equal ? 0 : (a.$id || 0) - (b.$id || 0);\n};\n\n/**\n * Default rule priority sorting function.\n *\n * Sorts rules by:\n *\n * - Explicit priority (set rule priority using [[UrlRulesApi.when]])\n * - Rule type (STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1)\n * - `UrlMatcher` specificity ([[UrlMatcher.compare]]): works for STATE and URLMATCHER types to pick the most specific rule.\n * - Rule registration order (for rule types other than STATE and URLMATCHER)\n * - Equally sorted State and UrlMatcher rules will each match the URL.\n * Then, the *best* match is chosen based on how many parameter values were matched.\n *\n * @coreapi\n */\nlet defaultRuleSortFn: (a: UrlRule, b: UrlRule) => number;\ndefaultRuleSortFn = (a, b) => {\n let cmp = prioritySort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = typeSort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = urlMatcherSort(a as MatcherUrlRule, b as MatcherUrlRule);\n if (cmp !== 0) return cmp;\n\n return idSort(a, b);\n};\n\n/**\n * Updates URL and responds to URL changes\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class updates the URL when the state changes.\n * It also responds to changes in the URL.\n */\nexport class UrlRouter implements UrlRulesApi, UrlSyncApi, Disposable {\n /** used to create [[UrlRule]] objects for common cases */\n public urlRuleFactory: UrlRuleFactory;\n\n /** @hidden */ private _router: UIRouter;\n /** @hidden */ private location: string;\n /** @hidden */ private _sortFn = defaultRuleSortFn;\n /** @hidden */ private _stopFn: Function;\n /** @hidden */ _rules: UrlRule[] = [];\n /** @hidden */ private _otherwiseFn: UrlRule;\n /** @hidden */ interceptDeferred = false;\n /** @hidden */ private _id = 0;\n /** @hidden */ private _sorted = false;\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this.urlRuleFactory = new UrlRuleFactory(router);\n createProxyFunctions(val(UrlRouter.prototype), this, val(this));\n }\n\n /** @internalapi */\n dispose() {\n this.listen(false);\n this._rules = [];\n delete this._otherwiseFn;\n }\n\n /** @inheritdoc */\n sort(compareFn?: (a: UrlRule, b: UrlRule) => number) {\n this._rules = this.stableSort(this._rules, this._sortFn = compareFn || this._sortFn);\n this._sorted = true;\n }\n\n private ensureSorted() {\n this._sorted || this.sort();\n }\n\n private stableSort(arr, compareFn) {\n const arrOfWrapper = arr.map((elem, idx) => ({ elem, idx }));\n\n arrOfWrapper.sort((wrapperA, wrapperB) => {\n const cmpDiff = compareFn(wrapperA.elem, wrapperB.elem);\n return cmpDiff === 0\n ? wrapperA.idx - wrapperB.idx\n : cmpDiff;\n });\n\n return arrOfWrapper.map(wrapper => wrapper.elem);\n }\n\n /**\n * Given a URL, check all rules and return the best [[MatchResult]]\n * @param url\n * @returns {MatchResult}\n */\n match(url: UrlParts): MatchResult {\n this.ensureSorted();\n\n url = extend({ path: '', search: {}, hash: '' }, url);\n const rules = this.rules();\n if (this._otherwiseFn) rules.push(this._otherwiseFn);\n\n // Checks a single rule. Returns { rule: rule, match: match, weight: weight } if it matched, or undefined\n\n const checkRule = (rule: UrlRule): MatchResult => {\n const match = rule.match(url, this._router);\n return match && { match, rule, weight: rule.matchPriority(match) };\n };\n\n // The rules are pre-sorted.\n // - Find the first matching rule.\n // - Find any other matching rule that sorted *exactly the same*, according to `.sort()`.\n // - Choose the rule with the highest match weight.\n let best: MatchResult;\n for (let i = 0; i < rules.length; i++) {\n // Stop when there is a 'best' rule and the next rule sorts differently than it.\n if (best && this._sortFn(rules[i], best.rule) !== 0) break;\n\n const current = checkRule(rules[i]);\n // Pick the best MatchResult\n best = (!best || current && current.weight > best.weight) ? current : best;\n }\n\n return best;\n }\n\n /** @inheritdoc */\n sync(evt?) {\n if (evt && evt.defaultPrevented) return;\n\n const router = this._router,\n $url = router.urlService,\n $state = router.stateService;\n\n const url: UrlParts = {\n path: $url.path(), search: $url.search(), hash: $url.hash(),\n };\n\n const best = this.match(url);\n\n const applyResult = pattern([\n [isString, (newurl: string) => $url.url(newurl, true)],\n [TargetState.isDef, (def: TargetStateDef) => $state.go(def.state, def.params, def.options)],\n [is(TargetState), (target: TargetState) => $state.go(target.state(), target.params(), target.options())],\n ]);\n\n applyResult(best && best.rule.handler(best.match, url, router));\n }\n\n /** @inheritdoc */\n listen(enabled?: boolean): Function {\n if (enabled === false) {\n this._stopFn && this._stopFn();\n delete this._stopFn;\n } else {\n return this._stopFn = this._stopFn || this._router.urlService.onChange(evt => this.sync(evt));\n }\n }\n\n /**\n * Internal API.\n * @internalapi\n */\n update(read?: boolean) {\n const $url = this._router.locationService;\n if (read) {\n this.location = $url.url();\n return;\n }\n if ($url.url() === this.location) return;\n\n $url.url(this.location, true);\n }\n\n /**\n * Internal API.\n *\n * Pushes a new location to the browser history.\n *\n * @internalapi\n * @param urlMatcher\n * @param params\n * @param options\n */\n push(urlMatcher: UrlMatcher, params?: RawParams, options?: { replace?: (string|boolean) }) {\n const replace = options && !!options.replace;\n this._router.urlService.url(urlMatcher.format(params || {}), replace);\n }\n\n /**\n * Builds and returns a URL with interpolated parameters\n *\n * #### Example:\n * ```js\n * matcher = $umf.compile(\"/about/:person\");\n * params = { person: \"bob\" };\n * $bob = $urlRouter.href(matcher, params);\n * // $bob == \"/about/bob\";\n * ```\n *\n * @param urlMatcher The [[UrlMatcher]] object which is used as the template of the URL to generate.\n * @param params An object of parameter values to fill the matcher's required parameters.\n * @param options Options object. The options are:\n *\n * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n *\n * @returns Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n */\n href(urlMatcher: UrlMatcher, params?: any, options?: { absolute: boolean }): string {\n let url = urlMatcher.format(params);\n if (url == null) return null;\n\n options = options || { absolute: false };\n\n const cfg = this._router.urlService.config;\n const isHtml5 = cfg.html5Mode();\n if (!isHtml5 && url !== null) {\n url = '#' + cfg.hashPrefix() + url;\n }\n url = appendBasePath(url, isHtml5, options.absolute, cfg.baseHref());\n\n if (!options.absolute || !url) {\n return url;\n }\n\n const slash = (!isHtml5 && url ? '/' : '');\n const cfgPort = cfg.port();\n const port = (cfgPort === 80 || cfgPort === 443 ? '' : ':' + cfgPort);\n\n return [cfg.protocol(), '://', cfg.host(), port, slash, url].join('');\n }\n\n\n /**\n * Manually adds a URL Rule.\n *\n * Usually, a url rule is added using [[StateDeclaration.url]] or [[when]].\n * This api can be used directly for more control (to register a [[BaseUrlRule]], for example).\n * Rules can be created using [[UrlRouter.urlRuleFactory]], or create manually as simple objects.\n *\n * A rule should have a `match` function which returns truthy if the rule matched.\n * It should also have a `handler` function which is invoked if the rule is the best match.\n *\n * @return a function that deregisters the rule\n */\n rule(rule: UrlRule): Function {\n if (!UrlRuleFactory.isUrlRule(rule)) throw new Error('invalid rule');\n rule.$id = this._id++;\n rule.priority = rule.priority || 0;\n\n this._rules.push(rule);\n this._sorted = false;\n\n return () => this.removeRule(rule);\n }\n\n /** @inheritdoc */\n removeRule(rule): void {\n removeFrom(this._rules, rule);\n }\n\n /** @inheritdoc */\n rules(): UrlRule[] {\n this.ensureSorted();\n return this._rules.slice();\n }\n\n /** @inheritdoc */\n otherwise(handler: string|UrlRuleHandlerFn|TargetState|TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n this._otherwiseFn = this.urlRuleFactory.create(val(true), handlerFn);\n this._sorted = false;\n }\n\n /** @inheritdoc */\n initial(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n const matchFn: UrlRuleMatchFn = (urlParts, router) =>\n router.globals.transitionHistory.size() === 0 && !!/^\\/?$/.exec(urlParts.path);\n\n this.rule(this.urlRuleFactory.create(matchFn, handlerFn));\n }\n\n /** @inheritdoc */\n when(matcher: (RegExp|UrlMatcher|string), handler: string|UrlRuleHandlerFn, options?: { priority: number }): UrlRule {\n const rule = this.urlRuleFactory.create(matcher, handler);\n if (isDefined(options && options.priority)) rule.priority = options.priority;\n this.rule(rule);\n return rule;\n }\n\n /** @inheritdoc */\n deferIntercept(defer?: boolean) {\n if (defer === undefined) defer = true;\n this.interceptDeferred = defer;\n }\n}\n\nfunction getHandlerFn(handler: string|UrlRuleHandlerFn|TargetState|TargetStateDef): UrlRuleHandlerFn {\n if (!isFunction(handler) && !isString(handler) && !is(TargetState)(handler) && !TargetState.isDef(handler)) {\n throw new Error(\"'handler' must be a string, function, TargetState, or have a state: 'newtarget' property\");\n }\n return isFunction(handler) ? handler as UrlRuleHandlerFn : val(handler);\n}\n", - "/**\n * @coreapi\n * @module view\n */ /** for typedoc */\nimport { equals, applyPairs, removeFrom, TypedMap, inArray } from '../common/common';\nimport { curry, prop } from '../common/hof';\nimport { isString, isArray } from '../common/predicates';\nimport { trace } from '../common/trace';\nimport { PathNode } from '../path/pathNode';\nimport { ActiveUIView, ViewContext, ViewConfig } from './interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nexport type ViewConfigFactory = (path: PathNode[], decl: _ViewDeclaration) => ViewConfig|ViewConfig[];\n\nexport interface ViewServicePluginAPI {\n _rootViewContext(context?: ViewContext): ViewContext;\n _viewConfigFactory(viewType: string, factory: ViewConfigFactory);\n _registeredUIViews(): ActiveUIView[];\n _activeViewConfigs(): ViewConfig[];\n _onSync(listener: ViewSyncListener): Function;\n}\n\n// A uiView and its matching viewConfig\nexport interface ViewTuple {\n uiView: ActiveUIView;\n viewConfig: ViewConfig;\n}\n\nexport interface ViewSyncListener {\n (viewTuples: ViewTuple[]): void;\n}\n\n/**\n * The View service\n *\n * This service pairs existing `ui-view` components (which live in the DOM)\n * with view configs (from the state declaration objects: [[StateDeclaration.views]]).\n *\n * - After a successful Transition, the views from the newly entered states are activated via [[activateViewConfig]].\n * The views from exited states are deactivated via [[deactivateViewConfig]].\n * (See: the [[registerActivateViews]] Transition Hook)\n *\n * - As `ui-view` components pop in and out of existence, they register themselves using [[registerUIView]].\n *\n * - When the [[sync]] function is called, the registered `ui-view`(s) ([[ActiveUIView]])\n * are configured with the matching [[ViewConfig]](s)\n *\n */\nexport class ViewService {\n private _uiViews: ActiveUIView[] = [];\n private _viewConfigs: ViewConfig[] = [];\n private _rootContext: ViewContext;\n private _viewConfigFactories: { [key: string]: ViewConfigFactory } = {};\n private _listeners: ViewSyncListener[] = [];\n\n public _pluginapi: ViewServicePluginAPI = {\n _rootViewContext: this._rootViewContext.bind(this),\n _viewConfigFactory: this._viewConfigFactory.bind(this),\n _registeredUIViews: () => this._uiViews,\n _activeViewConfigs: () => this._viewConfigs,\n _onSync: (listener: ViewSyncListener) => {\n this._listeners.push(listener);\n return () => removeFrom(this._listeners, listener);\n },\n };\n\n /**\n * Given a ui-view and a ViewConfig, determines if they \"match\".\n *\n * A ui-view has a fully qualified name (fqn) and a context object. The fqn is built from its overall location in\n * the DOM, describing its nesting relationship to any parent ui-view tags it is nested inside of.\n *\n * A ViewConfig has a target ui-view name and a context anchor. The ui-view name can be a simple name, or\n * can be a segmented ui-view path, describing a portion of a ui-view fqn.\n *\n * In order for a ui-view to match ViewConfig, ui-view's $type must match the ViewConfig's $type\n *\n * If the ViewConfig's target ui-view name is a simple name (no dots), then a ui-view matches if:\n * - the ui-view's name matches the ViewConfig's target name\n * - the ui-view's context matches the ViewConfig's anchor\n *\n * If the ViewConfig's target ui-view name is a segmented name (with dots), then a ui-view matches if:\n * - There exists a parent ui-view where:\n * - the parent ui-view's name matches the first segment (index 0) of the ViewConfig's target name\n * - the parent ui-view's context matches the ViewConfig's anchor\n * - And the remaining segments (index 1..n) of the ViewConfig's target name match the tail of the ui-view's fqn\n *\n * Example:\n *\n * DOM:\n * \n * \n * \n * \n * \n * \n * \n * \n *\n * uiViews: [\n * { fqn: \"$default\", creationContext: { name: \"\" } },\n * { fqn: \"$default.foo\", creationContext: { name: \"A\" } },\n * { fqn: \"$default.foo.$default\", creationContext: { name: \"A.B\" } }\n * { fqn: \"$default.foo.$default.bar\", creationContext: { name: \"A.B.C\" } }\n * ]\n *\n * These four view configs all match the ui-view with the fqn: \"$default.foo.$default.bar\":\n *\n * - ViewConfig1: { uiViewName: \"bar\", uiViewContextAnchor: \"A.B.C\" }\n * - ViewConfig2: { uiViewName: \"$default.bar\", uiViewContextAnchor: \"A.B\" }\n * - ViewConfig3: { uiViewName: \"foo.$default.bar\", uiViewContextAnchor: \"A\" }\n * - ViewConfig4: { uiViewName: \"$default.foo.$default.bar\", uiViewContextAnchor: \"\" }\n *\n * Using ViewConfig3 as an example, it matches the ui-view with fqn \"$default.foo.$default.bar\" because:\n * - The ViewConfig's segmented target name is: [ \"foo\", \"$default\", \"bar\" ]\n * - There exists a parent ui-view (which has fqn: \"$default.foo\") where:\n * - the parent ui-view's name \"foo\" matches the first segment \"foo\" of the ViewConfig's target name\n * - the parent ui-view's context \"A\" matches the ViewConfig's anchor context \"A\"\n * - And the remaining segments [ \"$default\", \"bar\" ].join(\".\"_ of the ViewConfig's target name match\n * the tail of the ui-view's fqn \"default.bar\"\n *\n * @internalapi\n */\n static matches = (uiViewsByFqn: TypedMap, uiView: ActiveUIView) => (viewConfig: ViewConfig) => {\n // Don't supply an ng1 ui-view with an ng2 ViewConfig, etc\n if (uiView.$type !== viewConfig.viewDecl.$type) return false;\n\n // Split names apart from both viewConfig and uiView into segments\n const vc = viewConfig.viewDecl;\n const vcSegments = vc.$uiViewName.split('.');\n const uivSegments = uiView.fqn.split('.');\n\n // Check if the tails of the segment arrays match. ex, these arrays' tails match:\n // vc: [\"foo\", \"bar\"], uiv fqn: [\"$default\", \"foo\", \"bar\"]\n if (!equals(vcSegments, uivSegments.slice(0 - vcSegments.length)))\n return false;\n\n // Now check if the fqn ending at the first segment of the viewConfig matches the context:\n // [\"$default\", \"foo\"].join(\".\") == \"$default.foo\", does the ui-view $default.foo context match?\n const negOffset = (1 - vcSegments.length) || undefined;\n const fqnToFirstSegment = uivSegments.slice(0, negOffset).join('.');\n const uiViewContext = uiViewsByFqn[fqnToFirstSegment].creationContext;\n return vc.$uiViewContextAnchor === (uiViewContext && uiViewContext.name);\n }\n\n /**\n * Normalizes a view's name from a state.views configuration block.\n *\n * This should be used by a framework implementation to calculate the values for\n * [[_ViewDeclaration.$uiViewName]] and [[_ViewDeclaration.$uiViewContextAnchor]].\n *\n * @param context the context object (state declaration) that the view belongs to\n * @param rawViewName the name of the view, as declared in the [[StateDeclaration.views]]\n *\n * @returns the normalized uiViewName and uiViewContextAnchor that the view targets\n */\n static normalizeUIViewTarget(context: ViewContext, rawViewName = '') {\n // TODO: Validate incoming view name with a regexp to allow:\n // ex: \"view.name@foo.bar\" , \"^.^.view.name\" , \"view.name@^.^\" , \"\" ,\n // \"@\" , \"$default@^\" , \"!$default.$default\" , \"!foo.bar\"\n const viewAtContext: string[] = rawViewName.split('@');\n let uiViewName = viewAtContext[0] || '$default'; // default to unnamed view\n let uiViewContextAnchor = isString(viewAtContext[1]) ? viewAtContext[1] : '^'; // default to parent context\n\n // Handle relative view-name sugar syntax.\n // Matches rawViewName \"^.^.^.foo.bar\" into array: [\"^.^.^.foo.bar\", \"^.^.^\", \"foo.bar\"],\n const relativeViewNameSugar = /^(\\^(?:\\.\\^)*)\\.(.*$)/.exec(uiViewName);\n if (relativeViewNameSugar) {\n // Clobbers existing contextAnchor (rawViewName validation will fix this)\n uiViewContextAnchor = relativeViewNameSugar[1]; // set anchor to \"^.^.^\"\n uiViewName = relativeViewNameSugar[2]; // set view-name to \"foo.bar\"\n }\n\n if (uiViewName.charAt(0) === '!') {\n uiViewName = uiViewName.substr(1);\n uiViewContextAnchor = ''; // target absolutely from root\n }\n\n // handle parent relative targeting \"^.^.^\"\n const relativeMatch = /^(\\^(?:\\.\\^)*)$/;\n if (relativeMatch.exec(uiViewContextAnchor)) {\n const anchorState = uiViewContextAnchor.split('.')\n .reduce(((anchor, x) => anchor.parent), context);\n uiViewContextAnchor = anchorState.name;\n } else if (uiViewContextAnchor === '.') {\n uiViewContextAnchor = context.name;\n }\n\n return { uiViewName, uiViewContextAnchor };\n }\n\n constructor() { }\n\n private _rootViewContext(context?: ViewContext): ViewContext {\n return this._rootContext = context || this._rootContext;\n }\n\n private _viewConfigFactory(viewType: string, factory: ViewConfigFactory) {\n this._viewConfigFactories[viewType] = factory;\n }\n\n createViewConfig(path: PathNode[], decl: _ViewDeclaration): ViewConfig[] {\n const cfgFactory = this._viewConfigFactories[decl.$type];\n if (!cfgFactory) throw new Error('ViewService: No view config factory registered for type ' + decl.$type);\n const cfgs = cfgFactory(path, decl);\n return isArray(cfgs) ? cfgs : [cfgs];\n }\n\n /**\n * Deactivates a ViewConfig.\n *\n * This function deactivates a `ViewConfig`.\n * After calling [[sync]], it will un-pair from any `ui-view` with which it is currently paired.\n *\n * @param viewConfig The ViewConfig view to deregister.\n */\n deactivateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('<- Removing', viewConfig);\n removeFrom(this._viewConfigs, viewConfig);\n }\n\n activateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('-> Registering', viewConfig);\n this._viewConfigs.push(viewConfig);\n }\n\n\n sync() {\n const uiViewsByFqn: TypedMap =\n this._uiViews.map(uiv => [uiv.fqn, uiv]).reduce(applyPairs, {});\n\n // Return a weighted depth value for a uiView.\n // The depth is the nesting depth of ui-views (based on FQN; times 10,000)\n // plus the depth of the state that is populating the uiView\n function uiViewDepth(uiView: ActiveUIView) {\n const stateDepth = (context: ViewContext) =>\n context && context.parent ? stateDepth(context.parent) + 1 : 1;\n return (uiView.fqn.split('.').length * 10000) + stateDepth(uiView.creationContext);\n }\n\n // Return the ViewConfig's context's depth in the context tree.\n function viewConfigDepth(config: ViewConfig) {\n let context: ViewContext = config.viewDecl.$context, count = 0;\n while (++count && context.parent) context = context.parent;\n return count;\n }\n\n // Given a depth function, returns a compare function which can return either ascending or descending order\n const depthCompare = curry((depthFn, posNeg, left, right) => posNeg * (depthFn(left) - depthFn(right)));\n\n const matchingConfigPair = (uiView: ActiveUIView): ViewTuple => {\n const matchingConfigs = this._viewConfigs.filter(ViewService.matches(uiViewsByFqn, uiView));\n if (matchingConfigs.length > 1) {\n // This is OK. Child states can target a ui-view that the parent state also targets (the child wins)\n // Sort by depth and return the match from the deepest child\n // console.log(`Multiple matching view configs for ${uiView.fqn}`, matchingConfigs);\n matchingConfigs.sort(depthCompare(viewConfigDepth, -1)); // descending\n }\n return { uiView, viewConfig: matchingConfigs[0] };\n };\n\n const configureUIView = (tuple: ViewTuple) => {\n // If a parent ui-view is reconfigured, it could destroy child ui-views.\n // Before configuring a child ui-view, make sure it's still in the active uiViews array.\n if (this._uiViews.indexOf(tuple.uiView) !== -1)\n tuple.uiView.configUpdated(tuple.viewConfig);\n };\n\n // Sort views by FQN and state depth. Process uiviews nearest the root first.\n const uiViewTuples = this._uiViews.sort(depthCompare(uiViewDepth, 1)).map(matchingConfigPair);\n const matchedViewConfigs = uiViewTuples.map(tuple => tuple.viewConfig);\n const unmatchedConfigTuples = this._viewConfigs\n .filter(config => !inArray(matchedViewConfigs, config))\n .map(viewConfig => ({ uiView: undefined, viewConfig }));\n\n uiViewTuples.forEach(configureUIView);\n\n const allTuples: ViewTuple[] = uiViewTuples.concat(unmatchedConfigTuples);\n this._listeners.forEach(cb => cb(allTuples));\n trace.traceViewSync(allTuples);\n }\n\n /**\n * Registers a `ui-view` component\n *\n * When a `ui-view` component is created, it uses this method to register itself.\n * After registration the [[sync]] method is used to ensure all `ui-view` are configured with the proper [[ViewConfig]].\n *\n * Note: the `ui-view` component uses the `ViewConfig` to determine what view should be loaded inside the `ui-view`,\n * and what the view's state context is.\n *\n * Note: There is no corresponding `deregisterUIView`.\n * A `ui-view` should hang on to the return value of `registerUIView` and invoke it to deregister itself.\n *\n * @param uiView The metadata for a UIView\n * @return a de-registration function used when the view is destroyed.\n */\n registerUIView(uiView: ActiveUIView) {\n trace.traceViewServiceUIViewEvent('-> Registering', uiView);\n const uiViews = this._uiViews;\n const fqnAndTypeMatches = (uiv: ActiveUIView) => uiv.fqn === uiView.fqn && uiv.$type === uiView.$type;\n if (uiViews.filter(fqnAndTypeMatches).length)\n trace.traceViewServiceUIViewEvent('!!!! duplicate uiView named:', uiView);\n\n uiViews.push(uiView);\n this.sync();\n\n return () => {\n const idx = uiViews.indexOf(uiView);\n if (idx === -1) {\n trace.traceViewServiceUIViewEvent('Tried removing non-registered uiView', uiView);\n return;\n }\n trace.traceViewServiceUIViewEvent('<- Deregistering', uiView);\n removeFrom(uiViews)(uiView);\n };\n }\n\n /**\n * Returns the list of views currently available on the page, by fully-qualified name.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n available() {\n return this._uiViews.map(prop('fqn'));\n }\n\n /**\n * Returns the list of views on the page containing loaded content.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n active() {\n return this._uiViews.filter(prop('$config')).map(prop('name'));\n }\n\n}\n", + "/** @module state */ /** for typedoc */\nimport { Obj, omit, noop, extend, inherit, values, applyPairs, tail, mapObj, identity } from '../common/common';\nimport { isDefined, isFunction, isString, isArray } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { prop, pattern, is, pipe, val } from '../common/hof';\nimport { StateDeclaration } from './interface';\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { Param } from '../params/param';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { services } from '../common/coreservices';\nimport { ResolvePolicy } from '../resolve/interface';\nimport { ParamFactory } from '../url/interface';\n\nconst parseUrl = (url: string): any => {\n if (!isString(url)) return false;\n const root = url.charAt(0) === '^';\n return { val: root ? url.substring(1) : url, root };\n};\n\nexport type BuilderFunction = (state: StateObject, parent?: BuilderFunction) => any;\n\ninterface Builders {\n [key: string]: BuilderFunction[];\n\n name: BuilderFunction[];\n parent: BuilderFunction[];\n data: BuilderFunction[];\n url: BuilderFunction[];\n navigable: BuilderFunction[];\n params: BuilderFunction[];\n views: BuilderFunction[];\n path: BuilderFunction[];\n includes: BuilderFunction[];\n resolvables: BuilderFunction[];\n}\n\nfunction nameBuilder(state: StateObject) {\n return state.name;\n}\n\nfunction selfBuilder(state: StateObject) {\n state.self.$$state = () => state;\n return state.self;\n}\n\nfunction dataBuilder(state: StateObject) {\n if (state.parent && state.parent.data) {\n state.data = state.self.data = inherit(state.parent.data, state.data);\n }\n return state.data;\n}\n\nconst getUrlBuilder = ($urlMatcherFactoryProvider: UrlMatcherFactory, root: () => StateObject) =>\n function urlBuilder(state: StateObject) {\n const stateDec: StateDeclaration = state;\n\n // For future states, i.e., states whose name ends with `.**`,\n // match anything that starts with the url prefix\n if (stateDec && stateDec.url && stateDec.name && stateDec.name.match(/\\.\\*\\*$/)) {\n stateDec.url += '{remainder:any}'; // match any path (.*)\n }\n\n const parsed = parseUrl(stateDec.url),\n parent = state.parent;\n const url = !parsed\n ? stateDec.url\n : $urlMatcherFactoryProvider.compile(parsed.val, {\n params: state.params || {},\n paramMap: function(paramConfig: any, isSearch: boolean) {\n if (stateDec.reloadOnSearch === false && isSearch)\n paramConfig = extend(paramConfig || {}, { dynamic: true });\n return paramConfig;\n },\n });\n\n if (!url) return null;\n if (!$urlMatcherFactoryProvider.isMatcher(url)) throw new Error(`Invalid url '${url}' in state '${state}'`);\n return parsed && parsed.root ? url : ((parent && parent.navigable) || root()).url.append(url);\n };\n\nconst getNavigableBuilder = (isRoot: (state: StateObject) => boolean) =>\n function navigableBuilder(state: StateObject) {\n return !isRoot(state) && state.url ? state : state.parent ? state.parent.navigable : null;\n };\n\nconst getParamsBuilder = (paramFactory: ParamFactory) =>\n function paramsBuilder(state: StateObject): { [key: string]: Param } {\n const makeConfigParam = (config: any, id: string) => paramFactory.fromConfig(id, null, config);\n const urlParams: Param[] = (state.url && state.url.parameters({ inherit: false })) || [];\n const nonUrlParams: Param[] = values(mapObj(omit(state.params || {}, urlParams.map(prop('id'))), makeConfigParam));\n return urlParams\n .concat(nonUrlParams)\n .map(p => [p.id, p])\n .reduce(applyPairs, {});\n };\n\nfunction pathBuilder(state: StateObject) {\n return state.parent ? state.parent.path.concat(state) : /*root*/ [state];\n}\n\nfunction includesBuilder(state: StateObject) {\n const includes = state.parent ? extend({}, state.parent.includes) : {};\n includes[state.name] = true;\n return includes;\n}\n\n/**\n * This is a [[StateBuilder.builder]] function for the `resolve:` block on a [[StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * validates the `resolve` property and converts it to a [[Resolvable]] array.\n *\n * resolve: input value can be:\n *\n * {\n * // analyzed but not injected\n * myFooResolve: function() { return \"myFooData\"; },\n *\n * // function.toString() parsed, \"DependencyName\" dep as string (not min-safe)\n * myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },\n *\n * // Array split; \"DependencyName\" dep as string\n * myBazResolve: [ \"DependencyName\", function(dep) { return dep.fetchSomethingAsPromise() },\n *\n * // Array split; DependencyType dep as token (compared using ===)\n * myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },\n *\n * // val.$inject used as deps\n * // where:\n * // corgeResolve.$inject = [\"DependencyName\"];\n * // function corgeResolve(dep) { dep.fetchSometingAsPromise() }\n * // then \"DependencyName\" dep as string\n * myCorgeResolve: corgeResolve,\n *\n * // inject service by name\n * // When a string is found, desugar creating a resolve that injects the named service\n * myGraultResolve: \"SomeService\"\n * }\n *\n * or:\n *\n * [\n * new Resolvable(\"myFooResolve\", function() { return \"myFooData\" }),\n * new Resolvable(\"myBarResolve\", function(dep) { return dep.fetchSomethingAsPromise() }, [ \"DependencyName\" ]),\n * { provide: \"myBazResolve\", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ \"DependencyName\" ] }\n * ]\n */\nexport function resolvablesBuilder(state: StateObject): Resolvable[] {\n interface Tuple {\n token: any;\n val: any;\n deps: any[];\n policy: ResolvePolicy;\n }\n\n /** convert resolve: {} and resolvePolicy: {} objects to an array of tuples */\n const objects2Tuples = (resolveObj: Obj, resolvePolicies: { [key: string]: ResolvePolicy }) =>\n Object.keys(resolveObj || {}).map(token => ({\n token,\n val: resolveObj[token],\n deps: undefined,\n policy: resolvePolicies[token],\n }));\n\n /** fetch DI annotations from a function or ng1-style array */\n const annotate = (fn: Function) => {\n const $injector = services.$injector;\n // ng1 doesn't have an $injector until runtime.\n // If the $injector doesn't exist, use \"deferred\" literal as a\n // marker indicating they should be annotated when runtime starts\n return fn['$inject'] || ($injector && $injector.annotate(fn, $injector.strictDi)) || 'deferred';\n };\n\n /** true if the object has both `token` and `resolveFn`, and is probably a [[ResolveLiteral]] */\n const isResolveLiteral = (obj: any) => !!(obj.token && obj.resolveFn);\n\n /** true if the object looks like a provide literal, or a ng2 Provider */\n const isLikeNg2Provider = (obj: any) =>\n !!((obj.provide || obj.token) && (obj.useValue || obj.useFactory || obj.useExisting || obj.useClass));\n\n /** true if the object looks like a tuple from obj2Tuples */\n const isTupleFromObj = (obj: any) =>\n !!(obj && obj.val && (isString(obj.val) || isArray(obj.val) || isFunction(obj.val)));\n\n /** extracts the token from a Provider or provide literal */\n const getToken = (p: any) => p.provide || p.token;\n\n /** Given a literal resolve or provider object, returns a Resolvable */\n const literal2Resolvable = pattern([\n [prop('resolveFn'), p => new Resolvable(getToken(p), p.resolveFn, p.deps, p.policy)],\n [prop('useFactory'), p => new Resolvable(getToken(p), p.useFactory, p.deps || p.dependencies, p.policy)],\n [prop('useClass'), p => new Resolvable(getToken(p), () => new (p.useClass)(), [], p.policy)],\n [prop('useValue'), p => new Resolvable(getToken(p), () => p.useValue, [], p.policy, p.useValue)],\n [prop('useExisting'), p => new Resolvable(getToken(p), identity, [p.useExisting], p.policy)],\n ]);\n\n const tuple2Resolvable = pattern([\n [pipe(prop('val'), isString), (tuple: Tuple) => new Resolvable(tuple.token, identity, [tuple.val], tuple.policy)],\n [\n pipe(prop('val'), isArray),\n (tuple: Tuple) => new Resolvable(tuple.token, tail(tuple.val), tuple.val.slice(0, -1), tuple.policy),\n ],\n [\n pipe(prop('val'), isFunction),\n (tuple: Tuple) => new Resolvable(tuple.token, tuple.val, annotate(tuple.val), tuple.policy),\n ],\n ]);\n\n const item2Resolvable = <(obj: any) => Resolvable>pattern([\n [is(Resolvable), (r: Resolvable) => r],\n [isResolveLiteral, literal2Resolvable],\n [isLikeNg2Provider, literal2Resolvable],\n [isTupleFromObj, tuple2Resolvable],\n [\n val(true),\n (obj: any) => {\n throw new Error('Invalid resolve value: ' + stringify(obj));\n },\n ],\n ]);\n\n // If resolveBlock is already an array, use it as-is.\n // Otherwise, assume it's an object and convert to an Array of tuples\n const decl = state.resolve;\n const items: any[] = isArray(decl) ? decl : objects2Tuples(decl, state.resolvePolicy || {});\n return items.map(item2Resolvable);\n}\n\n/**\n * @internalapi A internal global service\n *\n * StateBuilder is a factory for the internal [[StateObject]] objects.\n *\n * When you register a state with the [[StateRegistry]], you register a plain old javascript object which\n * conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding\n * [[StateObject]] object, which has an API and is used internally.\n *\n * Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function\n * using the [[builder]] method.\n */\nexport class StateBuilder {\n /** An object that contains all the BuilderFunctions registered, key'd by the name of the State property they build */\n private builders: Builders;\n\n constructor(private matcher: StateMatcher, urlMatcherFactory: UrlMatcherFactory) {\n const self = this;\n\n const root = () => matcher.find('');\n const isRoot = (state: StateObject) => state.name === '';\n\n function parentBuilder(state: StateObject) {\n if (isRoot(state)) return null;\n return matcher.find(self.parentName(state)) || root();\n }\n\n this.builders = {\n name: [nameBuilder],\n self: [selfBuilder],\n parent: [parentBuilder],\n data: [dataBuilder],\n // Build a URLMatcher if necessary, either via a relative or absolute URL\n url: [getUrlBuilder(urlMatcherFactory, root)],\n // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n navigable: [getNavigableBuilder(isRoot)],\n params: [getParamsBuilder(urlMatcherFactory.paramFactory)],\n // Each framework-specific ui-router implementation should define its own `views` builder\n // e.g., src/ng1/statebuilders/views.ts\n views: [],\n // Keep a full path from the root down to this state as this is needed for state activation.\n path: [pathBuilder],\n // Speed up $state.includes() as it's used a lot\n includes: [includesBuilder],\n resolvables: [resolvablesBuilder],\n };\n }\n\n /**\n * Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g., `parent`, `url`, or `path`).\n * More than one BuilderFunction can be registered for a given property.\n *\n * The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.\n *\n * @param name The name of the State property being registered for.\n * @param fn The BuilderFunction which will be used to build the State property\n * @returns a function which deregisters the BuilderFunction\n */\n builder(name: string, fn: BuilderFunction): BuilderFunction | BuilderFunction[] | Function {\n const builders = this.builders;\n const array = builders[name] || [];\n // Backwards compat: if only one builder exists, return it, else return whole arary.\n if (isString(name) && !isDefined(fn)) return array.length > 1 ? array : array[0];\n if (!isString(name) || !isFunction(fn)) return;\n\n builders[name] = array;\n builders[name].push(fn);\n return () => builders[name].splice(builders[name].indexOf(fn, 1)) && null;\n }\n\n /**\n * Builds all of the properties on an essentially blank State object, returning a State object which has all its\n * properties and API built.\n *\n * @param state an uninitialized State object\n * @returns the built State object\n */\n build(state: StateObject): StateObject {\n const { matcher, builders } = this;\n const parent = this.parentName(state);\n\n if (parent && !matcher.find(parent, undefined, false)) {\n return null;\n }\n\n for (const key in builders) {\n if (!builders.hasOwnProperty(key)) continue;\n const chain = builders[key].reduce(\n (parentFn: BuilderFunction, step: BuilderFunction) => _state => step(_state, parentFn),\n noop,\n );\n state[key] = chain(state);\n }\n return state;\n }\n\n parentName(state: StateObject) {\n // name = 'foo.bar.baz.**'\n const name = state.name || '';\n // segments = ['foo', 'bar', 'baz', '.**']\n const segments = name.split('.');\n // segments = ['foo', 'bar', 'baz']\n const lastSegment = segments.pop();\n // segments = ['foo', 'bar'] (ignore .** segment for future states)\n if (lastSegment === '**') segments.pop();\n\n if (segments.length) {\n if (state.parent) {\n throw new Error(`States that specify the 'parent:' property should not have a '.' in their name (${name})`);\n }\n\n // 'foo.bar'\n return segments.join('.');\n }\n\n if (!state.parent) return '';\n return isString(state.parent) ? state.parent : state.parent.name;\n }\n\n name(state: StateObject) {\n const name = state.name;\n if (name.indexOf('.') !== -1 || !state.parent) return name;\n\n const parentName = isString(state.parent) ? state.parent : state.parent.name;\n return parentName ? parentName + '.' + name : name;\n }\n}\n", + "/** @module state */ /** for typedoc */\nimport { isString } from '../common/predicates';\nimport { StateOrName } from './interface';\nimport { StateObject } from './stateObject';\nimport { values } from '../common/common';\n\nexport class StateMatcher {\n constructor(private _states: { [key: string]: StateObject }) {}\n\n isRelative(stateName: string) {\n stateName = stateName || '';\n return stateName.indexOf('.') === 0 || stateName.indexOf('^') === 0;\n }\n\n find(stateOrName: StateOrName, base?: StateOrName, matchGlob = true): StateObject {\n if (!stateOrName && stateOrName !== '') return undefined;\n const isStr = isString(stateOrName);\n let name: string = isStr ? stateOrName : (stateOrName).name;\n\n if (this.isRelative(name)) name = this.resolvePath(name, base);\n const state = this._states[name];\n\n if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n return state;\n } else if (isStr && matchGlob) {\n const _states = values(this._states);\n const matches = _states.filter(\n _state => _state.__stateObjectCache.nameGlob && _state.__stateObjectCache.nameGlob.matches(name),\n );\n\n if (matches.length > 1) {\n // tslint:disable-next-line:no-console\n console.log(\n `stateMatcher.find: Found multiple matches for ${name} using glob: `,\n matches.map(match => match.name),\n );\n }\n return matches[0];\n }\n return undefined;\n }\n\n resolvePath(name: string, base: StateOrName) {\n if (!base) throw new Error(`No reference point given for path '${name}'`);\n\n const baseState: StateObject = this.find(base);\n\n const splitName = name.split('.');\n const pathLength = splitName.length;\n let i = 0,\n current = baseState;\n\n for (; i < pathLength; i++) {\n if (splitName[i] === '' && i === 0) {\n current = baseState;\n continue;\n }\n if (splitName[i] === '^') {\n if (!current.parent) throw new Error(`Path '${name}' not valid for state '${baseState.name}'`);\n current = current.parent;\n continue;\n }\n break;\n }\n const relName = splitName.slice(i).join('.');\n return current.name + (current.name && relName ? '.' : '') + relName;\n }\n}\n", + "/** @module state */ /** for typedoc */\nimport { inArray } from '../common/common';\nimport { isString } from '../common/predicates';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { StateObject } from './stateObject';\nimport { StateBuilder } from './stateBuilder';\nimport { StateRegistryListener, StateRegistry } from './stateRegistry';\nimport { Disposable } from '../interface';\nimport { UrlRouter } from '../url/urlRouter';\nimport { prop } from '../common/hof';\nimport { StateMatcher } from './stateMatcher';\n\n/** @internalapi */\nexport class StateQueueManager implements Disposable {\n queue: StateObject[];\n matcher: StateMatcher;\n\n constructor(\n private $registry: StateRegistry,\n private $urlRouter: UrlRouter,\n public states: { [key: string]: StateObject },\n public builder: StateBuilder,\n public listeners: StateRegistryListener[],\n ) {\n this.queue = [];\n this.matcher = $registry.matcher;\n }\n\n /** @internalapi */\n dispose() {\n this.queue = [];\n }\n\n register(stateDecl: _StateDeclaration) {\n const queue = this.queue;\n const state = StateObject.create(stateDecl);\n const name = state.name;\n\n if (!isString(name)) throw new Error('State must have a valid name');\n if (this.states.hasOwnProperty(name) || inArray(queue.map(prop('name')), name))\n throw new Error(`State '${name}' is already defined`);\n\n queue.push(state);\n this.flush();\n\n return state;\n }\n\n flush() {\n const { queue, states, builder } = this;\n const registered: StateObject[] = [], // states that got registered\n orphans: StateObject[] = [], // states that don't yet have a parent registered\n previousQueueLength = {}; // keep track of how long the queue when an orphan was first encountered\n const getState = name => this.states.hasOwnProperty(name) && this.states[name];\n const notifyListeners = () => {\n if (registered.length) {\n this.listeners.forEach(listener => listener('registered', registered.map(s => s.self)));\n }\n };\n\n while (queue.length > 0) {\n const state: StateObject = queue.shift();\n const name = state.name;\n const result: StateObject = builder.build(state);\n const orphanIdx: number = orphans.indexOf(state);\n\n if (result) {\n const existingState = getState(name);\n if (existingState && existingState.name === name) {\n throw new Error(`State '${name}' is already defined`);\n }\n\n const existingFutureState = getState(name + '.**');\n if (existingFutureState) {\n // Remove future state of the same name\n this.$registry.deregister(existingFutureState);\n }\n\n states[name] = state;\n this.attachRoute(state);\n if (orphanIdx >= 0) orphans.splice(orphanIdx, 1);\n registered.push(state);\n continue;\n }\n\n const prev = previousQueueLength[name];\n previousQueueLength[name] = queue.length;\n if (orphanIdx >= 0 && prev === queue.length) {\n // Wait until two consecutive iterations where no additional states were dequeued successfully.\n // throw new Error(`Cannot register orphaned state '${name}'`);\n queue.push(state);\n notifyListeners();\n return states;\n } else if (orphanIdx < 0) {\n orphans.push(state);\n }\n\n queue.push(state);\n }\n\n notifyListeners();\n return states;\n }\n\n attachRoute(state: StateObject) {\n if (state.abstract || !state.url) return;\n\n this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(state));\n }\n}\n", + "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { StateBuilder } from './stateBuilder';\nimport { StateQueueManager } from './stateQueueManager';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { BuilderFunction } from './stateBuilder';\nimport { StateOrName } from './interface';\nimport { removeFrom } from '../common/common';\nimport { UIRouter } from '../router';\nimport { propEq } from '../common/hof';\n\n/**\n * The signature for the callback function provided to [[StateRegistry.onStatesChanged]].\n *\n * This callback receives two parameters:\n *\n * @param event a string; either \"registered\" or \"deregistered\"\n * @param states the list of [[StateDeclaration]]s that were registered (or deregistered).\n */\nexport type StateRegistryListener = (event: 'registered' | 'deregistered', states: StateDeclaration[]) => void;\n\nexport class StateRegistry {\n private _root: StateObject;\n private states: { [key: string]: StateObject } = {};\n\n matcher: StateMatcher;\n private builder: StateBuilder;\n stateQueue: StateQueueManager;\n\n listeners: StateRegistryListener[] = [];\n\n /** @internalapi */\n constructor(private _router: UIRouter) {\n this.matcher = new StateMatcher(this.states);\n this.builder = new StateBuilder(this.matcher, _router.urlMatcherFactory);\n this.stateQueue = new StateQueueManager(this, _router.urlRouter, this.states, this.builder, this.listeners);\n this._registerRoot();\n }\n\n /** @internalapi */\n private _registerRoot() {\n const rootStateDef: StateDeclaration = {\n name: '',\n url: '^',\n views: null,\n params: {\n '#': { value: null, type: 'hash', dynamic: true },\n },\n abstract: true,\n };\n\n const _root = (this._root = this.stateQueue.register(rootStateDef));\n _root.navigable = null;\n }\n\n /** @internalapi */\n dispose() {\n this.stateQueue.dispose();\n this.listeners = [];\n this.get().forEach(state => this.get(state) && this.deregister(state));\n }\n\n /**\n * Listen for a State Registry events\n *\n * Adds a callback that is invoked when states are registered or deregistered with the StateRegistry.\n *\n * #### Example:\n * ```js\n * let allStates = registry.get();\n *\n * // Later, invoke deregisterFn() to remove the listener\n * let deregisterFn = registry.onStatesChanged((event, states) => {\n * switch(event) {\n * case: 'registered':\n * states.forEach(state => allStates.push(state));\n * break;\n * case: 'deregistered':\n * states.forEach(state => {\n * let idx = allStates.indexOf(state);\n * if (idx !== -1) allStates.splice(idx, 1);\n * });\n * break;\n * }\n * });\n * ```\n *\n * @param listener a callback function invoked when the registered states changes.\n * The function receives two parameters, `event` and `state`.\n * See [[StateRegistryListener]]\n * @return a function that deregisters the listener\n */\n onStatesChanged(listener: StateRegistryListener): () => void {\n this.listeners.push(listener);\n return function deregisterListener() {\n removeFrom(this.listeners)(listener);\n }.bind(this);\n }\n\n /**\n * Gets the implicit root state\n *\n * Gets the root of the state tree.\n * The root state is implicitly created by UI-Router.\n * Note: this returns the internal [[StateObject]] representation, not a [[StateDeclaration]]\n *\n * @return the root [[StateObject]]\n */\n root() {\n return this._root;\n }\n\n /**\n * Adds a state to the registry\n *\n * Registers a [[StateDeclaration]] or queues it for registration.\n *\n * Note: a state will be queued if the state's parent isn't yet registered.\n *\n * @param stateDefinition the definition of the state to register.\n * @returns the internal [[StateObject]] object.\n * If the state was successfully registered, then the object is fully built (See: [[StateBuilder]]).\n * If the state was only queued, then the object is not fully built.\n */\n register(stateDefinition: _StateDeclaration): StateObject {\n return this.stateQueue.register(stateDefinition);\n }\n\n /** @hidden */\n private _deregisterTree(state: StateObject) {\n const all = this.get().map(s => s.$$state());\n const getChildren = (states: StateObject[]) => {\n const _children = all.filter(s => states.indexOf(s.parent) !== -1);\n return _children.length === 0 ? _children : _children.concat(getChildren(_children));\n };\n\n const children = getChildren([state]);\n const deregistered: StateObject[] = [state].concat(children).reverse();\n\n deregistered.forEach(_state => {\n const $ur = this._router.urlRouter;\n // Remove URL rule\n $ur\n .rules()\n .filter(propEq('state', _state))\n .forEach($ur.removeRule.bind($ur));\n // Remove state from registry\n delete this.states[_state.name];\n });\n\n return deregistered;\n }\n\n /**\n * Removes a state from the registry\n *\n * This removes a state from the registry.\n * If the state has children, they are are also removed from the registry.\n *\n * @param stateOrName the state's name or object representation\n * @returns {StateObject[]} a list of removed states\n */\n deregister(stateOrName: StateOrName) {\n const _state = this.get(stateOrName);\n if (!_state) throw new Error(\"Can't deregister state; not found: \" + stateOrName);\n const deregisteredStates = this._deregisterTree(_state.$$state());\n\n this.listeners.forEach(listener => listener('deregistered', deregisteredStates.map(s => s.self)));\n return deregisteredStates;\n }\n\n /**\n * Gets all registered states\n *\n * Calling this method with no arguments will return a list of all the states that are currently registered.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @return a list of [[StateDeclaration]]s\n */\n get(): StateDeclaration[];\n\n /**\n * Gets a registered state\n *\n * Given a state or a name, finds and returns the [[StateDeclaration]] from the registry.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @param stateOrName either the name of a state, or a state object.\n * @param base the base state to use when stateOrName is relative.\n * @return a registered [[StateDeclaration]] that matched the `stateOrName`, or null if the state isn't registered.\n */\n get(stateOrName: StateOrName, base?: StateOrName): StateDeclaration;\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n if (arguments.length === 0) return Object.keys(this.states).map(name => this.states[name].self);\n const found = this.matcher.find(stateOrName, base);\n return (found && found.self) || null;\n }\n\n decorator(name: string, func: BuilderFunction) {\n return this.builder.builder(name, func);\n }\n}\n", + "/**\n * @coreapi\n * @module url\n */\n/** for typedoc */\nimport {\n map,\n defaults,\n inherit,\n identity,\n unnest,\n tail,\n find,\n Obj,\n pairs,\n allTrueR,\n unnestR,\n arrayTuples,\n} from '../common/common';\nimport { prop, propEq } from '../common/hof';\nimport { isArray, isString, isDefined } from '../common/predicates';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { RawParams } from '../params/interface';\nimport { ParamFactory } from './interface';\nimport { joinNeighborsR, splitOnDelim } from '../common/strings';\n\n/** @hidden */\nfunction quoteRegExp(str: any, param?: any) {\n let surroundPattern = ['', ''],\n result = str.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, '\\\\$&');\n if (!param) return result;\n\n switch (param.squash) {\n case false:\n surroundPattern = ['(', ')' + (param.isOptional ? '?' : '')];\n break;\n case true:\n result = result.replace(/\\/$/, '');\n surroundPattern = ['(?:/(', ')|/)?'];\n break;\n default:\n surroundPattern = [`(${param.squash}|`, ')?'];\n break;\n }\n return result + surroundPattern[0] + param.type.pattern.source + surroundPattern[1];\n}\n\n/** @hidden */\nconst memoizeTo = (obj: Obj, _prop: string, fn: Function) => (obj[_prop] = obj[_prop] || fn());\n\n/** @hidden */\nconst splitOnSlash = splitOnDelim('/');\n\n/** @hidden */\ninterface UrlMatcherCache {\n segments?: any[];\n weights?: number[];\n path?: UrlMatcher[];\n parent?: UrlMatcher;\n pattern?: RegExp;\n}\n\n/**\n * Matches URLs against patterns.\n *\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL.\n *\n * A URL pattern consists of a path pattern, optionally followed by '?' and a list of search (query)\n * parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by [[UrlMatcher.exec]].\n *\n * - *Path parameters* are defined using curly brace placeholders (`/somepath/{param}`)\n * or colon placeholders (`/somePath/:param`).\n *\n * - *A parameter RegExp* may be defined for a param after a colon\n * (`/somePath/{param:[a-zA-Z0-9]+}`) in a curly brace placeholder.\n * The regexp must match for the url to be matched.\n * Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Note: a RegExp parameter will encode its value using either [[ParamTypes.path]] or [[ParamTypes.query]].\n *\n * - *Custom parameter types* may also be specified after a colon (`/somePath/{param:int}`) in curly brace parameters.\n * See [[UrlMatcherFactory.type]] for more information.\n *\n * - *Catch-all parameters* are defined using an asterisk placeholder (`/somepath/*catchallparam`).\n * A catch-all * parameter value will contain the remainder of the URL.\n *\n * ---\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters).\n * A path parameter matches any number of characters other than '/'. For catch-all\n * placeholders the path parameter matches any number of characters.\n *\n * Examples:\n *\n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n * trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n * parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n * path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n * in the built-in `date` ParamType matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n */\nexport class UrlMatcher {\n /** @hidden */\n static nameValidator: RegExp = /^\\w+([-.]+\\w+)*(?:\\[\\])?$/;\n\n /** @hidden */\n private _cache: UrlMatcherCache = { path: [this] };\n /** @hidden */\n private _children: UrlMatcher[] = [];\n /** @hidden */\n private _params: Param[] = [];\n /** @hidden */\n private _segments: string[] = [];\n /** @hidden */\n private _compiled: string[] = [];\n\n /** The pattern that was passed into the constructor */\n public pattern: string;\n\n /** @hidden */\n static encodeDashes(str: string) {\n // Replace dashes with encoded \"\\-\"\n return encodeURIComponent(str).replace(\n /-/g,\n c =>\n `%5C%${c\n .charCodeAt(0)\n .toString(16)\n .toUpperCase()}`,\n );\n }\n\n /** @hidden Given a matcher, return an array with the matcher's path segments and path params, in order */\n static pathSegmentsAndParams(matcher: UrlMatcher) {\n const staticSegments = matcher._segments;\n const pathParams = matcher._params.filter(p => p.location === DefType.PATH);\n return arrayTuples(staticSegments, pathParams.concat(undefined))\n .reduce(unnestR, [])\n .filter(x => x !== '' && isDefined(x));\n }\n\n /** @hidden Given a matcher, return an array with the matcher's query params */\n static queryParams(matcher: UrlMatcher): Param[] {\n return matcher._params.filter(p => p.location === DefType.SEARCH);\n }\n\n /**\n * Compare two UrlMatchers\n *\n * This comparison function converts a UrlMatcher into static and dynamic path segments.\n * Each static path segment is a static string between a path separator (slash character).\n * Each dynamic segment is a path parameter.\n *\n * The comparison function sorts static segments before dynamic ones.\n */\n static compare(a: UrlMatcher, b: UrlMatcher): number {\n /**\n * Turn a UrlMatcher and all its parent matchers into an array\n * of slash literals '/', string literals, and Param objects\n *\n * This example matcher matches strings like \"/foo/:param/tail\":\n * var matcher = $umf.compile(\"/foo\").append($umf.compile(\"/:param\")).append($umf.compile(\"/\")).append($umf.compile(\"tail\"));\n * var result = segments(matcher); // [ '/', 'foo', '/', Param, '/', 'tail' ]\n *\n * Caches the result as `matcher._cache.segments`\n */\n const segments = (matcher: UrlMatcher) =>\n (matcher._cache.segments =\n matcher._cache.segments ||\n matcher._cache.path\n .map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .reduce(joinNeighborsR, [])\n .map(x => (isString(x) ? splitOnSlash(x) : x))\n .reduce(unnestR, []));\n\n /**\n * Gets the sort weight for each segment of a UrlMatcher\n *\n * Caches the result as `matcher._cache.weights`\n */\n const weights = (matcher: UrlMatcher) =>\n (matcher._cache.weights =\n matcher._cache.weights ||\n segments(matcher).map(segment => {\n // Sort slashes first, then static strings, the Params\n if (segment === '/') return 1;\n if (isString(segment)) return 2;\n if (segment instanceof Param) return 3;\n }));\n\n /**\n * Pads shorter array in-place (mutates)\n */\n const padArrays = (l: any[], r: any[], padVal: any) => {\n const len = Math.max(l.length, r.length);\n while (l.length < len) l.push(padVal);\n while (r.length < len) r.push(padVal);\n };\n\n const weightsA = weights(a),\n weightsB = weights(b);\n padArrays(weightsA, weightsB, 0);\n\n const _pairs = arrayTuples(weightsA, weightsB);\n let cmp, i;\n\n for (i = 0; i < _pairs.length; i++) {\n cmp = _pairs[i][0] - _pairs[i][1];\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n }\n\n /**\n * @param pattern The pattern to compile into a matcher.\n * @param paramTypes The [[ParamTypes]] registry\n * @param config A configuration object\n * - `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * - `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n */\n constructor(pattern: string, paramTypes: ParamTypes, paramFactory: ParamFactory, public config?: any) {\n this.pattern = pattern;\n this.config = defaults(this.config, {\n params: {},\n strict: true,\n caseInsensitive: false,\n paramMap: identity,\n });\n\n // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n // '*' name\n // ':' name\n // '{' name '}'\n // '{' name ':' regexp '}'\n // The regular expression is somewhat complicated due to the need to allow curly braces\n // inside the regular expression. The placeholder regexp breaks down as follows:\n // ([:*])([\\w\\[\\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)\n // \\{([\\w\\[\\]]+)(?:\\:\\s*( ... ))?\\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either\n // [^{}\\\\]+ - anything other than curly braces or backslash\n // \\\\. - a backslash escape\n // \\{(?:[^{}\\\\]+|\\\\.)*\\} - a matched set of curly braces containing other atoms\n const placeholder = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const searchPlaceholder = /([:]?)([\\w\\[\\].-]+)|\\{([\\w\\[\\].-]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const patterns: any[][] = [];\n let last = 0,\n matchArray: RegExpExecArray;\n\n const checkParamErrors = (id: string) => {\n if (!UrlMatcher.nameValidator.test(id)) throw new Error(`Invalid parameter name '${id}' in pattern '${pattern}'`);\n if (find(this._params, propEq('id', id)))\n throw new Error(`Duplicate parameter name '${id}' in pattern '${pattern}'`);\n };\n\n // Split into static segments separated by path parameter placeholders.\n // The number of segments is always 1 more than the number of parameters.\n const matchDetails = (m: RegExpExecArray, isSearch: boolean) => {\n // IE[78] returns '' for unmatched groups instead of null\n const id: string = m[2] || m[3];\n const regexp: string = isSearch ? m[4] : m[4] || (m[1] === '*' ? '[\\\\s\\\\S]*' : null);\n\n const makeRegexpType = str =>\n inherit(paramTypes.type(isSearch ? 'query' : 'path'), {\n pattern: new RegExp(str, this.config.caseInsensitive ? 'i' : undefined),\n });\n\n return {\n id,\n regexp,\n cfg: this.config.params[id],\n segment: pattern.substring(last, m.index),\n type: !regexp ? null : paramTypes.type(regexp) || makeRegexpType(regexp),\n };\n };\n\n let p: any, segment: string;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = placeholder.exec(pattern))) {\n p = matchDetails(matchArray, false);\n if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromPath(p.id, p.type, this.config.paramMap(p.cfg, false)));\n this._segments.push(p.segment);\n patterns.push([p.segment, tail(this._params)]);\n last = placeholder.lastIndex;\n }\n segment = pattern.substring(last);\n\n // Find any search parameter names and remove them from the last segment\n const i = segment.indexOf('?');\n\n if (i >= 0) {\n const search = segment.substring(i);\n segment = segment.substring(0, i);\n\n if (search.length > 0) {\n last = 0;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = searchPlaceholder.exec(search))) {\n p = matchDetails(matchArray, true);\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromSearch(p.id, p.type, this.config.paramMap(p.cfg, true)));\n last = placeholder.lastIndex;\n // check if ?&\n }\n }\n }\n\n this._segments.push(segment);\n this._compiled = patterns.map(_pattern => quoteRegExp.apply(null, _pattern)).concat(quoteRegExp(segment));\n }\n\n /**\n * Creates a new concatenated UrlMatcher\n *\n * Builds a new UrlMatcher by appending another UrlMatcher to this one.\n *\n * @param url A `UrlMatcher` instance to append as a child of the current `UrlMatcher`.\n */\n append(url: UrlMatcher): UrlMatcher {\n this._children.push(url);\n url._cache = {\n path: this._cache.path.concat(url),\n parent: this,\n pattern: null,\n };\n return url;\n }\n\n /** @hidden */\n isRoot(): boolean {\n return this._cache.path[0] === this;\n }\n\n /** Returns the input pattern string */\n toString(): string {\n return this.pattern;\n }\n\n /**\n * Tests the specified url/path against this matcher.\n *\n * Tests if the given url matches this matcher's pattern, and returns an object containing the captured\n * parameter values. Returns null if the path does not match.\n *\n * The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `search`. This means that search parameters are always treated\n * as optional.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n * x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * ```\n *\n * @param path The URL path to match, e.g. `$location.path()`.\n * @param search URL search parameters, e.g. `$location.search()`.\n * @param hash URL hash e.g. `$location.hash()`.\n * @param options\n *\n * @returns The captured parameter values.\n */\n exec(path: string, search: any = {}, hash?: string, options: any = {}): RawParams {\n const match = memoizeTo(this._cache, 'pattern', () => {\n return new RegExp(\n [\n '^',\n unnest(this._cache.path.map(prop('_compiled'))).join(''),\n this.config.strict === false ? '/?' : '',\n '$',\n ].join(''),\n this.config.caseInsensitive ? 'i' : undefined,\n );\n }).exec(path);\n\n if (!match) return null;\n\n // options = defaults(options, { isolate: false });\n\n const allParams: Param[] = this.parameters(),\n pathParams: Param[] = allParams.filter(param => !param.isSearch()),\n searchParams: Param[] = allParams.filter(param => param.isSearch()),\n nPathSegments = this._cache.path.map(urlm => urlm._segments.length - 1).reduce((a, x) => a + x),\n values: RawParams = {};\n\n if (nPathSegments !== match.length - 1) throw new Error(`Unbalanced capture group in route '${this.pattern}'`);\n\n function decodePathArray(paramVal: string) {\n const reverseString = (str: string) =>\n str\n .split('')\n .reverse()\n .join('');\n const unquoteDashes = (str: string) => str.replace(/\\\\-/g, '-');\n\n const split = reverseString(paramVal).split(/-(?!\\\\)/);\n const allReversed = map(split, reverseString);\n return map(allReversed, unquoteDashes).reverse();\n }\n\n for (let i = 0; i < nPathSegments; i++) {\n const param: Param = pathParams[i];\n let value: any | any[] = match[i + 1];\n\n // if the param value matches a pre-replace pair, replace the value before decoding.\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (value && param.array === true) value = decodePathArray(value);\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n }\n searchParams.forEach(param => {\n let value = search[param.id];\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n });\n\n if (hash) values['#'] = hash;\n\n return values;\n }\n\n /**\n * @hidden\n * Returns all the [[Param]] objects of all path and search parameters of this pattern in order of appearance.\n *\n * @returns {Array.} An array of [[Param]] objects. Must be treated as read-only. If the\n * pattern has no parameters, an empty array is returned.\n */\n parameters(opts: any = {}): Param[] {\n if (opts.inherit === false) return this._params;\n return unnest(this._cache.path.map(matcher => matcher._params));\n }\n\n /**\n * @hidden\n * Returns a single parameter from this UrlMatcher by id\n *\n * @param id\n * @param opts\n * @returns {T|Param|any|boolean|UrlMatcher|null}\n */\n parameter(id: string, opts: any = {}): Param {\n const findParam = () => {\n for (const param of this._params) {\n if (param.id === id) return param;\n }\n };\n\n const parent = this._cache.parent;\n return findParam() || (opts.inherit !== false && parent && parent.parameter(id, opts)) || null;\n }\n\n /**\n * Validates the input parameter values against this UrlMatcher\n *\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param params The object hash of parameters to validate.\n * @returns Returns `true` if `params` validates, otherwise `false`.\n */\n validates(params: RawParams): boolean {\n const validParamVal = (param: Param, val: any) => !param || param.validates(val);\n\n params = params || {};\n\n // I'm not sure why this checks only the param keys passed in, and not all the params known to the matcher\n const paramSchema = this.parameters().filter(paramDef => params.hasOwnProperty(paramDef.id));\n return paramSchema.map(paramDef => validParamVal(paramDef, params[paramDef.id])).reduce(allTrueR, true);\n }\n\n /**\n * Given a set of parameter values, creates a URL from this UrlMatcher.\n *\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * ```\n *\n * @param values the values to substitute for the parameters in this pattern.\n * @returns the formatted URL (path and optionally search part).\n */\n format(values: RawParams = {}) {\n // Build the full path of UrlMatchers (including all parent UrlMatchers)\n const urlMatchers = this._cache.path;\n\n // Extract all the static segments and Params (processed as ParamDetails)\n // into an ordered array\n const pathSegmentsAndParams: Array = urlMatchers\n .map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .map(x => (isString(x) ? x : getDetails(x)));\n\n // Extract the query params into a separate array\n const queryParams: Array = urlMatchers\n .map(UrlMatcher.queryParams)\n .reduce(unnestR, [])\n .map(getDetails);\n\n const isInvalid = (param: ParamDetails) => param.isValid === false;\n if (pathSegmentsAndParams.concat(queryParams).filter(isInvalid).length) {\n return null;\n }\n\n /**\n * Given a Param, applies the parameter value, then returns detailed information about it\n */\n function getDetails(param: Param): ParamDetails {\n // Normalize to typed value\n const value = param.value(values[param.id]);\n const isValid = param.validates(value);\n const isDefaultValue = param.isDefaultValue(value);\n // Check if we're in squash mode for the parameter\n const squash = isDefaultValue ? param.squash : false;\n // Allow the Parameter's Type to encode the value\n const encoded = param.type.encode(value);\n\n return { param, value, isValid, isDefaultValue, squash, encoded };\n }\n\n // Build up the path-portion from the list of static segments and parameters\n const pathString = pathSegmentsAndParams.reduce((acc: string, x: string | ParamDetails) => {\n // The element is a static segment (a raw string); just append it\n if (isString(x)) return acc + x;\n\n // Otherwise, it's a ParamDetails.\n const { squash, encoded, param } = x;\n\n // If squash is === true, try to remove a slash from the path\n if (squash === true) return acc.match(/\\/$/) ? acc.slice(0, -1) : acc;\n // If squash is a string, use the string for the param value\n if (isString(squash)) return acc + squash;\n if (squash !== false) return acc; // ?\n if (encoded == null) return acc;\n // If this parameter value is an array, encode the value using encodeDashes\n if (isArray(encoded)) return acc + map(encoded, UrlMatcher.encodeDashes).join('-');\n // If the parameter type is \"raw\", then do not encodeURIComponent\n if (param.raw) return acc + encoded;\n // Encode the value\n return acc + encodeURIComponent(encoded);\n }, '');\n\n // Build the query string by applying parameter values (array or regular)\n // then mapping to key=value, then flattening and joining using \"&\"\n const queryString = queryParams\n .map((paramDetails: ParamDetails) => {\n let { param, squash, encoded, isDefaultValue } = paramDetails;\n if (encoded == null || (isDefaultValue && squash !== false)) return;\n if (!isArray(encoded)) encoded = [encoded];\n if (encoded.length === 0) return;\n if (!param.raw) encoded = map(encoded, encodeURIComponent);\n\n return (encoded).map(val => `${param.id}=${val}`);\n })\n .filter(identity)\n .reduce(unnestR, [])\n .join('&');\n\n // Concat the pathstring with the queryString (if exists) and the hashString (if exists)\n return pathString + (queryString ? `?${queryString}` : '') + (values['#'] ? '#' + values['#'] : '');\n }\n}\n\n/** @hidden */\ninterface ParamDetails {\n param: Param;\n value: any;\n isValid: boolean;\n isDefaultValue: boolean;\n squash: boolean | string;\n encoded: string | string[];\n}\n", + "/**\n * @internalapi\n * @module url\n */ /** for typedoc */\nimport { forEach, extend } from '../common/common';\nimport { isObject, isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { ParamTypeDefinition } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { ParamType } from '../params/paramType';\nimport { ParamFactory, UrlMatcherConfig } from './interface';\n\n/**\n * Factory for [[UrlMatcher]] instances.\n *\n * The factory is available to ng1 services as\n * `$urlMatcherFactory` or ng1 providers as `$urlMatcherFactoryProvider`.\n */\nexport class UrlMatcherFactory implements Disposable, UrlMatcherConfig {\n /** @hidden */ paramTypes = new ParamTypes();\n /** @hidden */ _isCaseInsensitive = false;\n /** @hidden */ _isStrictMode = true;\n /** @hidden */ _defaultSquashPolicy: boolean | string = false;\n\n /** @internalapi Creates a new [[Param]] for a given location (DefType) */\n paramFactory: ParamFactory = {\n /** Creates a new [[Param]] from a CONFIG block */\n fromConfig: (id: string, type: ParamType, config: any) => new Param(id, type, config, DefType.CONFIG, this),\n\n /** Creates a new [[Param]] from a url PATH */\n fromPath: (id: string, type: ParamType, config: any) => new Param(id, type, config, DefType.PATH, this),\n\n /** Creates a new [[Param]] from a url SEARCH */\n fromSearch: (id: string, type: ParamType, config: any) => new Param(id, type, config, DefType.SEARCH, this),\n };\n\n constructor() {\n extend(this, { UrlMatcher, Param });\n }\n\n /** @inheritdoc */\n caseInsensitive(value?: boolean): boolean {\n return (this._isCaseInsensitive = isDefined(value) ? value : this._isCaseInsensitive);\n }\n\n /** @inheritdoc */\n strictMode(value?: boolean): boolean {\n return (this._isStrictMode = isDefined(value) ? value : this._isStrictMode);\n }\n\n /** @inheritdoc */\n defaultSquashPolicy(value?: boolean | string) {\n if (isDefined(value) && value !== true && value !== false && !isString(value))\n throw new Error(`Invalid squash policy: ${value}. Valid policies: false, true, arbitrary-string`);\n return (this._defaultSquashPolicy = isDefined(value) ? value : this._defaultSquashPolicy);\n }\n\n /** @hidden */\n private _getConfig = config =>\n extend({ strict: this._isStrictMode, caseInsensitive: this._isCaseInsensitive }, config);\n\n /**\n * Creates a [[UrlMatcher]] for the specified pattern.\n *\n * @param pattern The URL pattern.\n * @param config The config object hash.\n * @returns The UrlMatcher.\n */\n compile(pattern: string, config?: { [key: string]: any }) {\n return new UrlMatcher(pattern, this.paramTypes, this.paramFactory, this._getConfig(config));\n }\n\n /**\n * Returns true if the specified object is a [[UrlMatcher]], or false otherwise.\n *\n * @param object The object to perform the type check against.\n * @returns `true` if the object matches the `UrlMatcher` interface, by\n * implementing all the same methods.\n */\n isMatcher(object: any): boolean {\n // TODO: typeof?\n if (!isObject(object)) return false;\n let result = true;\n\n forEach(UrlMatcher.prototype, (val, name) => {\n if (isFunction(val)) result = result && (isDefined(object[name]) && isFunction(object[name]));\n });\n return result;\n }\n\n /**\n * Creates and registers a custom [[ParamType]] object\n *\n * A [[ParamType]] can be used to generate URLs with typed parameters.\n *\n * @param name The type name.\n * @param definition The type definition. See [[ParamTypeDefinition]] for information on the values accepted.\n * @param definitionFn A function that is injected before the app runtime starts.\n * The result of this function should be a [[ParamTypeDefinition]].\n * The result is merged into the existing `definition`.\n * See [[ParamType]] for information on the values accepted.\n *\n * @returns - if a type was registered: the [[UrlMatcherFactory]]\n * - if only the `name` parameter was specified: the currently registered [[ParamType]] object, or undefined\n *\n * Note: Register custom types *before using them* in a state definition.\n *\n * See [[ParamTypeDefinition]] for examples\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n const type = this.paramTypes.type(name, definition, definitionFn);\n return !isDefined(definition) ? type : this;\n }\n\n /** @hidden */\n $get() {\n this.paramTypes.enqueue = false;\n this.paramTypes._flushTypeQueue();\n return this;\n }\n\n /** @internalapi */\n dispose() {\n this.paramTypes.dispose();\n }\n}\n", + "/**\n * @coreapi\n * @module url\n */ /** */\nimport { UrlMatcher } from './urlMatcher';\nimport { isString, isDefined, isFunction, isState } from '../common/predicates';\nimport { UIRouter } from '../router';\nimport { identity, extend } from '../common/common';\nimport { is, pattern } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport {\n UrlRule,\n UrlRuleMatchFn,\n UrlRuleHandlerFn,\n UrlRuleType,\n UrlParts,\n MatcherUrlRule,\n StateRule,\n RegExpRule,\n} from './interface';\n\n/**\n * Creates a [[UrlRule]]\n *\n * Creates a [[UrlRule]] from a:\n *\n * - `string`\n * - [[UrlMatcher]]\n * - `RegExp`\n * - [[StateObject]]\n * @internalapi\n */\nexport class UrlRuleFactory {\n static isUrlRule = obj => obj && ['type', 'match', 'handler'].every(key => isDefined(obj[key]));\n\n constructor(public router: UIRouter) {}\n\n compile(str: string) {\n return this.router.urlMatcherFactory.compile(str);\n }\n\n create(\n what: string | UrlMatcher | StateObject | RegExp | UrlRuleMatchFn,\n handler?: string | UrlRuleHandlerFn,\n ): UrlRule {\n const makeRule = pattern([\n [isString, (_what: string) => makeRule(this.compile(_what))],\n [is(UrlMatcher), (_what: UrlMatcher) => this.fromUrlMatcher(_what, handler)],\n [isState, (_what: StateObject) => this.fromState(_what, this.router)],\n [is(RegExp), (_what: RegExp) => this.fromRegExp(_what, handler)],\n [isFunction, (_what: UrlRuleMatchFn) => new BaseUrlRule(_what, handler as UrlRuleHandlerFn)],\n ]);\n\n const rule = makeRule(what);\n if (!rule) throw new Error(\"invalid 'what' in when()\");\n return rule;\n }\n\n /**\n * A UrlRule which matches based on a UrlMatcher\n *\n * The `handler` may be either a `string`, a [[UrlRuleHandlerFn]] or another [[UrlMatcher]]\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - matched parameter values ([[RawParams]] from [[UrlMatcher.exec]])\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, match => \"/home/\" + match.fooId + \"/\" + match.barId);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n *\n * ## Handler as UrlMatcher\n *\n * If `handler` is a UrlMatcher, the handler matcher is used to create the new url.\n * The `handler` UrlMatcher is formatted using the matched param from the first matcher.\n * The url is replaced with the result.\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var handler = $umf.compile(\"/home/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, handler);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n */\n fromUrlMatcher(urlMatcher: UrlMatcher, handler: string | UrlMatcher | UrlRuleHandlerFn): MatcherUrlRule {\n let _handler: UrlRuleHandlerFn = handler as any;\n if (isString(handler)) handler = this.router.urlMatcherFactory.compile(handler);\n if (is(UrlMatcher)(handler)) _handler = (match: RawParams) => (handler as UrlMatcher).format(match);\n\n function matchUrlParamters(url: UrlParts): RawParams {\n const params = urlMatcher.exec(url.path, url.search, url.hash);\n return urlMatcher.validates(params) && params;\n }\n\n // Prioritize URLs, lowest to highest:\n // - Some optional URL parameters, but none matched\n // - No optional parameters in URL\n // - Some optional parameters, some matched\n // - Some optional parameters, all matched\n function matchPriority(params: RawParams): number {\n const optional = urlMatcher.parameters().filter(param => param.isOptional);\n if (!optional.length) return 0.000001;\n const matched = optional.filter(param => params[param.id]);\n return matched.length / optional.length;\n }\n\n const details = { urlMatcher, matchPriority, type: 'URLMATCHER' };\n return extend(new BaseUrlRule(matchUrlParamters, _handler), details) as MatcherUrlRule;\n }\n\n /**\n * A UrlRule which matches a state by its url\n *\n * #### Example:\n * ```js\n * var rule = factory.fromState($state.get('foo'), router);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match);\n * // Starts a transition to 'foo' with params: { fooId: '123', barId: '456' }\n * ```\n */\n fromState(state: StateObject, router: UIRouter): StateRule {\n /**\n * Handles match by transitioning to matched state\n *\n * First checks if the router should start a new transition.\n * A new transition is not required if the current state's URL\n * and the new URL are already identical\n */\n const handler = (match: RawParams) => {\n const $state = router.stateService;\n const globals = router.globals;\n if ($state.href(state, match) !== $state.href(globals.current, globals.params)) {\n $state.transitionTo(state, match, { inherit: true, source: 'url' });\n }\n };\n\n const details = { state, type: 'STATE' };\n return extend(this.fromUrlMatcher(state.url, handler), details) as StateRule;\n }\n\n /**\n * A UrlRule which matches based on a regular expression\n *\n * The `handler` may be either a [[UrlRuleHandlerFn]] or a string.\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - regexp match array (from `regexp`)\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, match => \"/home/\" + match[1])\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n *\n * ## Handler as string\n *\n * If `handler` is a string, the url is *replaced by the string* when the Rule is invoked.\n * The string is first interpolated using `string.replace()` style pattern.\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, \"/home/$1\")\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n */\n fromRegExp(regexp: RegExp, handler: string | UrlRuleHandlerFn): RegExpRule {\n if (regexp.global || regexp.sticky) throw new Error('Rule RegExp must not be global or sticky');\n\n /**\n * If handler is a string, the url will be replaced by the string.\n * If the string has any String.replace() style variables in it (like `$2`),\n * they will be replaced by the captures from [[match]]\n */\n const redirectUrlTo = (match: RegExpExecArray) =>\n // Interpolates matched values into $1 $2, etc using a String.replace()-style pattern\n (handler as string).replace(/\\$(\\$|\\d{1,2})/, (m, what) => match[what === '$' ? 0 : Number(what)]);\n\n const _handler = isString(handler) ? redirectUrlTo : handler;\n\n const matchParamsFromRegexp = (url: UrlParts): RegExpExecArray => regexp.exec(url.path);\n\n const details = { regexp, type: 'REGEXP' };\n return extend(new BaseUrlRule(matchParamsFromRegexp, _handler), details) as RegExpRule;\n }\n}\n\n/**\n * A base rule which calls `match`\n *\n * The value from the `match` function is passed through to the `handler`.\n * @internalapi\n */\nexport class BaseUrlRule implements UrlRule {\n $id: number;\n priority: number;\n type: UrlRuleType = 'RAW';\n handler: UrlRuleHandlerFn;\n matchPriority = match => 0 - this.$id;\n\n constructor(public match: UrlRuleMatchFn, handler?: UrlRuleHandlerFn) {\n this.handler = handler || identity;\n }\n}\n", + "/**\n * @internalapi\n * @module url\n */\n/** for typedoc */\nimport { createProxyFunctions, extend, removeFrom } from '../common/common';\nimport { isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { RawParams } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { is, pattern, val } from '../common/hof';\nimport { UrlRuleFactory } from './urlRule';\nimport { TargetState } from '../state/targetState';\nimport {\n MatcherUrlRule,\n MatchResult,\n UrlParts,\n UrlRule,\n UrlRuleHandlerFn,\n UrlRuleMatchFn,\n UrlRulesApi,\n UrlSyncApi,\n} from './interface';\nimport { TargetStateDef } from '../state/interface';\nimport { stripLastPathElement } from '../common';\n\n/** @hidden */\nfunction appendBasePath(url: string, isHtml5: boolean, absolute: boolean, baseHref: string): string {\n if (baseHref === '/') return url;\n if (isHtml5) return stripLastPathElement(baseHref) + url;\n if (absolute) return baseHref.slice(1) + url;\n return url;\n}\n\n/** @hidden */\nconst prioritySort = (a: UrlRule, b: UrlRule) => (b.priority || 0) - (a.priority || 0);\n\n/** @hidden */\nconst typeSort = (a: UrlRule, b: UrlRule) => {\n const weights = { STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1 };\n return (weights[a.type] || 0) - (weights[b.type] || 0);\n};\n\n/** @hidden */\nconst urlMatcherSort = (a: MatcherUrlRule, b: MatcherUrlRule) =>\n !a.urlMatcher || !b.urlMatcher ? 0 : UrlMatcher.compare(a.urlMatcher, b.urlMatcher);\n\n/** @hidden */\nconst idSort = (a: UrlRule, b: UrlRule) => {\n // Identically sorted STATE and URLMATCHER best rule will be chosen by `matchPriority` after each rule matches the URL\n const useMatchPriority = { STATE: true, URLMATCHER: true };\n const equal = useMatchPriority[a.type] && useMatchPriority[b.type];\n return equal ? 0 : (a.$id || 0) - (b.$id || 0);\n};\n\n/**\n * Default rule priority sorting function.\n *\n * Sorts rules by:\n *\n * - Explicit priority (set rule priority using [[UrlRulesApi.when]])\n * - Rule type (STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1)\n * - `UrlMatcher` specificity ([[UrlMatcher.compare]]): works for STATE and URLMATCHER types to pick the most specific rule.\n * - Rule registration order (for rule types other than STATE and URLMATCHER)\n * - Equally sorted State and UrlMatcher rules will each match the URL.\n * Then, the *best* match is chosen based on how many parameter values were matched.\n *\n * @coreapi\n */\nlet defaultRuleSortFn: (a: UrlRule, b: UrlRule) => number;\ndefaultRuleSortFn = (a, b) => {\n let cmp = prioritySort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = typeSort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = urlMatcherSort(a as MatcherUrlRule, b as MatcherUrlRule);\n if (cmp !== 0) return cmp;\n\n return idSort(a, b);\n};\n\n/**\n * Updates URL and responds to URL changes\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class updates the URL when the state changes.\n * It also responds to changes in the URL.\n */\nexport class UrlRouter implements UrlRulesApi, UrlSyncApi, Disposable {\n /** used to create [[UrlRule]] objects for common cases */\n public urlRuleFactory: UrlRuleFactory;\n\n /** @hidden */ private _router: UIRouter;\n /** @hidden */ private location: string;\n /** @hidden */ private _sortFn = defaultRuleSortFn;\n /** @hidden */ private _stopFn: Function;\n /** @hidden */ _rules: UrlRule[] = [];\n /** @hidden */ private _otherwiseFn: UrlRule;\n /** @hidden */ interceptDeferred = false;\n /** @hidden */ private _id = 0;\n /** @hidden */ private _sorted = false;\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this.urlRuleFactory = new UrlRuleFactory(router);\n createProxyFunctions(val(UrlRouter.prototype), this, val(this));\n }\n\n /** @internalapi */\n dispose() {\n this.listen(false);\n this._rules = [];\n delete this._otherwiseFn;\n }\n\n /** @inheritdoc */\n sort(compareFn?: (a: UrlRule, b: UrlRule) => number) {\n this._rules = this.stableSort(this._rules, (this._sortFn = compareFn || this._sortFn));\n this._sorted = true;\n }\n\n private ensureSorted() {\n this._sorted || this.sort();\n }\n\n private stableSort(arr, compareFn) {\n const arrOfWrapper = arr.map((elem, idx) => ({ elem, idx }));\n\n arrOfWrapper.sort((wrapperA, wrapperB) => {\n const cmpDiff = compareFn(wrapperA.elem, wrapperB.elem);\n return cmpDiff === 0 ? wrapperA.idx - wrapperB.idx : cmpDiff;\n });\n\n return arrOfWrapper.map(wrapper => wrapper.elem);\n }\n\n /**\n * Given a URL, check all rules and return the best [[MatchResult]]\n * @param url\n * @returns {MatchResult}\n */\n match(url: UrlParts): MatchResult {\n this.ensureSorted();\n\n url = extend({ path: '', search: {}, hash: '' }, url);\n const rules = this.rules();\n if (this._otherwiseFn) rules.push(this._otherwiseFn);\n\n // Checks a single rule. Returns { rule: rule, match: match, weight: weight } if it matched, or undefined\n\n const checkRule = (rule: UrlRule): MatchResult => {\n const match = rule.match(url, this._router);\n return match && { match, rule, weight: rule.matchPriority(match) };\n };\n\n // The rules are pre-sorted.\n // - Find the first matching rule.\n // - Find any other matching rule that sorted *exactly the same*, according to `.sort()`.\n // - Choose the rule with the highest match weight.\n let best: MatchResult;\n for (let i = 0; i < rules.length; i++) {\n // Stop when there is a 'best' rule and the next rule sorts differently than it.\n if (best && this._sortFn(rules[i], best.rule) !== 0) break;\n\n const current = checkRule(rules[i]);\n // Pick the best MatchResult\n best = !best || (current && current.weight > best.weight) ? current : best;\n }\n\n return best;\n }\n\n /** @inheritdoc */\n sync(evt?) {\n if (evt && evt.defaultPrevented) return;\n\n const router = this._router,\n $url = router.urlService,\n $state = router.stateService;\n\n const url: UrlParts = {\n path: $url.path(),\n search: $url.search(),\n hash: $url.hash(),\n };\n\n const best = this.match(url);\n\n const applyResult = pattern([\n [isString, (newurl: string) => $url.url(newurl, true)],\n [TargetState.isDef, (def: TargetStateDef) => $state.go(def.state, def.params, def.options)],\n [is(TargetState), (target: TargetState) => $state.go(target.state(), target.params(), target.options())],\n ]);\n\n applyResult(best && best.rule.handler(best.match, url, router));\n }\n\n /** @inheritdoc */\n listen(enabled?: boolean): Function {\n if (enabled === false) {\n this._stopFn && this._stopFn();\n delete this._stopFn;\n } else {\n return (this._stopFn = this._stopFn || this._router.urlService.onChange(evt => this.sync(evt)));\n }\n }\n\n /**\n * Internal API.\n * @internalapi\n */\n update(read?: boolean) {\n const $url = this._router.locationService;\n if (read) {\n this.location = $url.url();\n return;\n }\n if ($url.url() === this.location) return;\n\n $url.url(this.location, true);\n }\n\n /**\n * Internal API.\n *\n * Pushes a new location to the browser history.\n *\n * @internalapi\n * @param urlMatcher\n * @param params\n * @param options\n */\n push(urlMatcher: UrlMatcher, params?: RawParams, options?: { replace?: string | boolean }) {\n const replace = options && !!options.replace;\n this._router.urlService.url(urlMatcher.format(params || {}), replace);\n }\n\n /**\n * Builds and returns a URL with interpolated parameters\n *\n * #### Example:\n * ```js\n * matcher = $umf.compile(\"/about/:person\");\n * params = { person: \"bob\" };\n * $bob = $urlRouter.href(matcher, params);\n * // $bob == \"/about/bob\";\n * ```\n *\n * @param urlMatcher The [[UrlMatcher]] object which is used as the template of the URL to generate.\n * @param params An object of parameter values to fill the matcher's required parameters.\n * @param options Options object. The options are:\n *\n * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n *\n * @returns Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n */\n href(urlMatcher: UrlMatcher, params?: any, options?: { absolute: boolean }): string {\n let url = urlMatcher.format(params);\n if (url == null) return null;\n\n options = options || { absolute: false };\n\n const cfg = this._router.urlService.config;\n const isHtml5 = cfg.html5Mode();\n if (!isHtml5 && url !== null) {\n url = '#' + cfg.hashPrefix() + url;\n }\n url = appendBasePath(url, isHtml5, options.absolute, cfg.baseHref());\n\n if (!options.absolute || !url) {\n return url;\n }\n\n const slash = !isHtml5 && url ? '/' : '';\n const cfgPort = cfg.port();\n const port = (cfgPort === 80 || cfgPort === 443 ? '' : ':' + cfgPort);\n\n return [cfg.protocol(), '://', cfg.host(), port, slash, url].join('');\n }\n\n /**\n * Manually adds a URL Rule.\n *\n * Usually, a url rule is added using [[StateDeclaration.url]] or [[when]].\n * This api can be used directly for more control (to register a [[BaseUrlRule]], for example).\n * Rules can be created using [[UrlRouter.urlRuleFactory]], or create manually as simple objects.\n *\n * A rule should have a `match` function which returns truthy if the rule matched.\n * It should also have a `handler` function which is invoked if the rule is the best match.\n *\n * @return a function that deregisters the rule\n */\n rule(rule: UrlRule): Function {\n if (!UrlRuleFactory.isUrlRule(rule)) throw new Error('invalid rule');\n rule.$id = this._id++;\n rule.priority = rule.priority || 0;\n\n this._rules.push(rule);\n this._sorted = false;\n\n return () => this.removeRule(rule);\n }\n\n /** @inheritdoc */\n removeRule(rule): void {\n removeFrom(this._rules, rule);\n }\n\n /** @inheritdoc */\n rules(): UrlRule[] {\n this.ensureSorted();\n return this._rules.slice();\n }\n\n /** @inheritdoc */\n otherwise(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n this._otherwiseFn = this.urlRuleFactory.create(val(true), handlerFn);\n this._sorted = false;\n }\n\n /** @inheritdoc */\n initial(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n const matchFn: UrlRuleMatchFn = (urlParts, router) =>\n router.globals.transitionHistory.size() === 0 && !!/^\\/?$/.exec(urlParts.path);\n\n this.rule(this.urlRuleFactory.create(matchFn, handlerFn));\n }\n\n /** @inheritdoc */\n when(\n matcher: RegExp | UrlMatcher | string,\n handler: string | UrlRuleHandlerFn,\n options?: { priority: number },\n ): UrlRule {\n const rule = this.urlRuleFactory.create(matcher, handler);\n if (isDefined(options && options.priority)) rule.priority = options.priority;\n this.rule(rule);\n return rule;\n }\n\n /** @inheritdoc */\n deferIntercept(defer?: boolean) {\n if (defer === undefined) defer = true;\n this.interceptDeferred = defer;\n }\n}\n\nfunction getHandlerFn(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef): UrlRuleHandlerFn {\n if (!isFunction(handler) && !isString(handler) && !is(TargetState)(handler) && !TargetState.isDef(handler)) {\n throw new Error(\"'handler' must be a string, function, TargetState, or have a state: 'newtarget' property\");\n }\n return isFunction(handler) ? (handler as UrlRuleHandlerFn) : val(handler);\n}\n", + "/**\n * @coreapi\n * @module view\n */ /** for typedoc */\nimport { equals, applyPairs, removeFrom, TypedMap, inArray } from '../common/common';\nimport { curry, prop } from '../common/hof';\nimport { isString, isArray } from '../common/predicates';\nimport { trace } from '../common/trace';\nimport { PathNode } from '../path/pathNode';\nimport { ActiveUIView, ViewContext, ViewConfig } from './interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nexport type ViewConfigFactory = (path: PathNode[], decl: _ViewDeclaration) => ViewConfig | ViewConfig[];\n\nexport interface ViewServicePluginAPI {\n _rootViewContext(context?: ViewContext): ViewContext;\n _viewConfigFactory(viewType: string, factory: ViewConfigFactory);\n _registeredUIViews(): ActiveUIView[];\n _activeViewConfigs(): ViewConfig[];\n _onSync(listener: ViewSyncListener): Function;\n}\n\n// A uiView and its matching viewConfig\nexport interface ViewTuple {\n uiView: ActiveUIView;\n viewConfig: ViewConfig;\n}\n\nexport interface ViewSyncListener {\n (viewTuples: ViewTuple[]): void;\n}\n\n/**\n * The View service\n *\n * This service pairs existing `ui-view` components (which live in the DOM)\n * with view configs (from the state declaration objects: [[StateDeclaration.views]]).\n *\n * - After a successful Transition, the views from the newly entered states are activated via [[activateViewConfig]].\n * The views from exited states are deactivated via [[deactivateViewConfig]].\n * (See: the [[registerActivateViews]] Transition Hook)\n *\n * - As `ui-view` components pop in and out of existence, they register themselves using [[registerUIView]].\n *\n * - When the [[sync]] function is called, the registered `ui-view`(s) ([[ActiveUIView]])\n * are configured with the matching [[ViewConfig]](s)\n *\n */\nexport class ViewService {\n private _uiViews: ActiveUIView[] = [];\n private _viewConfigs: ViewConfig[] = [];\n private _rootContext: ViewContext;\n private _viewConfigFactories: { [key: string]: ViewConfigFactory } = {};\n private _listeners: ViewSyncListener[] = [];\n\n public _pluginapi: ViewServicePluginAPI = {\n _rootViewContext: this._rootViewContext.bind(this),\n _viewConfigFactory: this._viewConfigFactory.bind(this),\n _registeredUIViews: () => this._uiViews,\n _activeViewConfigs: () => this._viewConfigs,\n _onSync: (listener: ViewSyncListener) => {\n this._listeners.push(listener);\n return () => removeFrom(this._listeners, listener);\n },\n };\n\n /**\n * Given a ui-view and a ViewConfig, determines if they \"match\".\n *\n * A ui-view has a fully qualified name (fqn) and a context object. The fqn is built from its overall location in\n * the DOM, describing its nesting relationship to any parent ui-view tags it is nested inside of.\n *\n * A ViewConfig has a target ui-view name and a context anchor. The ui-view name can be a simple name, or\n * can be a segmented ui-view path, describing a portion of a ui-view fqn.\n *\n * In order for a ui-view to match ViewConfig, ui-view's $type must match the ViewConfig's $type\n *\n * If the ViewConfig's target ui-view name is a simple name (no dots), then a ui-view matches if:\n * - the ui-view's name matches the ViewConfig's target name\n * - the ui-view's context matches the ViewConfig's anchor\n *\n * If the ViewConfig's target ui-view name is a segmented name (with dots), then a ui-view matches if:\n * - There exists a parent ui-view where:\n * - the parent ui-view's name matches the first segment (index 0) of the ViewConfig's target name\n * - the parent ui-view's context matches the ViewConfig's anchor\n * - And the remaining segments (index 1..n) of the ViewConfig's target name match the tail of the ui-view's fqn\n *\n * Example:\n *\n * DOM:\n * \n * \n * \n * \n * \n * \n * \n * \n *\n * uiViews: [\n * { fqn: \"$default\", creationContext: { name: \"\" } },\n * { fqn: \"$default.foo\", creationContext: { name: \"A\" } },\n * { fqn: \"$default.foo.$default\", creationContext: { name: \"A.B\" } }\n * { fqn: \"$default.foo.$default.bar\", creationContext: { name: \"A.B.C\" } }\n * ]\n *\n * These four view configs all match the ui-view with the fqn: \"$default.foo.$default.bar\":\n *\n * - ViewConfig1: { uiViewName: \"bar\", uiViewContextAnchor: \"A.B.C\" }\n * - ViewConfig2: { uiViewName: \"$default.bar\", uiViewContextAnchor: \"A.B\" }\n * - ViewConfig3: { uiViewName: \"foo.$default.bar\", uiViewContextAnchor: \"A\" }\n * - ViewConfig4: { uiViewName: \"$default.foo.$default.bar\", uiViewContextAnchor: \"\" }\n *\n * Using ViewConfig3 as an example, it matches the ui-view with fqn \"$default.foo.$default.bar\" because:\n * - The ViewConfig's segmented target name is: [ \"foo\", \"$default\", \"bar\" ]\n * - There exists a parent ui-view (which has fqn: \"$default.foo\") where:\n * - the parent ui-view's name \"foo\" matches the first segment \"foo\" of the ViewConfig's target name\n * - the parent ui-view's context \"A\" matches the ViewConfig's anchor context \"A\"\n * - And the remaining segments [ \"$default\", \"bar\" ].join(\".\"_ of the ViewConfig's target name match\n * the tail of the ui-view's fqn \"default.bar\"\n *\n * @internalapi\n */\n static matches = (uiViewsByFqn: TypedMap, uiView: ActiveUIView) => (viewConfig: ViewConfig) => {\n // Don't supply an ng1 ui-view with an ng2 ViewConfig, etc\n if (uiView.$type !== viewConfig.viewDecl.$type) return false;\n\n // Split names apart from both viewConfig and uiView into segments\n const vc = viewConfig.viewDecl;\n const vcSegments = vc.$uiViewName.split('.');\n const uivSegments = uiView.fqn.split('.');\n\n // Check if the tails of the segment arrays match. ex, these arrays' tails match:\n // vc: [\"foo\", \"bar\"], uiv fqn: [\"$default\", \"foo\", \"bar\"]\n if (!equals(vcSegments, uivSegments.slice(0 - vcSegments.length))) return false;\n\n // Now check if the fqn ending at the first segment of the viewConfig matches the context:\n // [\"$default\", \"foo\"].join(\".\") == \"$default.foo\", does the ui-view $default.foo context match?\n const negOffset = 1 - vcSegments.length || undefined;\n const fqnToFirstSegment = uivSegments.slice(0, negOffset).join('.');\n const uiViewContext = uiViewsByFqn[fqnToFirstSegment].creationContext;\n return vc.$uiViewContextAnchor === (uiViewContext && uiViewContext.name);\n };\n\n /**\n * Normalizes a view's name from a state.views configuration block.\n *\n * This should be used by a framework implementation to calculate the values for\n * [[_ViewDeclaration.$uiViewName]] and [[_ViewDeclaration.$uiViewContextAnchor]].\n *\n * @param context the context object (state declaration) that the view belongs to\n * @param rawViewName the name of the view, as declared in the [[StateDeclaration.views]]\n *\n * @returns the normalized uiViewName and uiViewContextAnchor that the view targets\n */\n static normalizeUIViewTarget(context: ViewContext, rawViewName = '') {\n // TODO: Validate incoming view name with a regexp to allow:\n // ex: \"view.name@foo.bar\" , \"^.^.view.name\" , \"view.name@^.^\" , \"\" ,\n // \"@\" , \"$default@^\" , \"!$default.$default\" , \"!foo.bar\"\n const viewAtContext: string[] = rawViewName.split('@');\n let uiViewName = viewAtContext[0] || '$default'; // default to unnamed view\n let uiViewContextAnchor = isString(viewAtContext[1]) ? viewAtContext[1] : '^'; // default to parent context\n\n // Handle relative view-name sugar syntax.\n // Matches rawViewName \"^.^.^.foo.bar\" into array: [\"^.^.^.foo.bar\", \"^.^.^\", \"foo.bar\"],\n const relativeViewNameSugar = /^(\\^(?:\\.\\^)*)\\.(.*$)/.exec(uiViewName);\n if (relativeViewNameSugar) {\n // Clobbers existing contextAnchor (rawViewName validation will fix this)\n uiViewContextAnchor = relativeViewNameSugar[1]; // set anchor to \"^.^.^\"\n uiViewName = relativeViewNameSugar[2]; // set view-name to \"foo.bar\"\n }\n\n if (uiViewName.charAt(0) === '!') {\n uiViewName = uiViewName.substr(1);\n uiViewContextAnchor = ''; // target absolutely from root\n }\n\n // handle parent relative targeting \"^.^.^\"\n const relativeMatch = /^(\\^(?:\\.\\^)*)$/;\n if (relativeMatch.exec(uiViewContextAnchor)) {\n const anchorState = uiViewContextAnchor.split('.').reduce((anchor, x) => anchor.parent, context);\n uiViewContextAnchor = anchorState.name;\n } else if (uiViewContextAnchor === '.') {\n uiViewContextAnchor = context.name;\n }\n\n return { uiViewName, uiViewContextAnchor };\n }\n\n constructor() {}\n\n private _rootViewContext(context?: ViewContext): ViewContext {\n return (this._rootContext = context || this._rootContext);\n }\n\n private _viewConfigFactory(viewType: string, factory: ViewConfigFactory) {\n this._viewConfigFactories[viewType] = factory;\n }\n\n createViewConfig(path: PathNode[], decl: _ViewDeclaration): ViewConfig[] {\n const cfgFactory = this._viewConfigFactories[decl.$type];\n if (!cfgFactory) throw new Error('ViewService: No view config factory registered for type ' + decl.$type);\n const cfgs = cfgFactory(path, decl);\n return isArray(cfgs) ? cfgs : [cfgs];\n }\n\n /**\n * Deactivates a ViewConfig.\n *\n * This function deactivates a `ViewConfig`.\n * After calling [[sync]], it will un-pair from any `ui-view` with which it is currently paired.\n *\n * @param viewConfig The ViewConfig view to deregister.\n */\n deactivateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('<- Removing', viewConfig);\n removeFrom(this._viewConfigs, viewConfig);\n }\n\n activateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('-> Registering', viewConfig);\n this._viewConfigs.push(viewConfig);\n }\n\n sync() {\n const uiViewsByFqn: TypedMap = this._uiViews.map(uiv => [uiv.fqn, uiv]).reduce(applyPairs, {});\n\n // Return a weighted depth value for a uiView.\n // The depth is the nesting depth of ui-views (based on FQN; times 10,000)\n // plus the depth of the state that is populating the uiView\n function uiViewDepth(uiView: ActiveUIView) {\n const stateDepth = (context: ViewContext) => (context && context.parent ? stateDepth(context.parent) + 1 : 1);\n return uiView.fqn.split('.').length * 10000 + stateDepth(uiView.creationContext);\n }\n\n // Return the ViewConfig's context's depth in the context tree.\n function viewConfigDepth(config: ViewConfig) {\n let context: ViewContext = config.viewDecl.$context,\n count = 0;\n while (++count && context.parent) context = context.parent;\n return count;\n }\n\n // Given a depth function, returns a compare function which can return either ascending or descending order\n const depthCompare = curry((depthFn, posNeg, left, right) => posNeg * (depthFn(left) - depthFn(right)));\n\n const matchingConfigPair = (uiView: ActiveUIView): ViewTuple => {\n const matchingConfigs = this._viewConfigs.filter(ViewService.matches(uiViewsByFqn, uiView));\n if (matchingConfigs.length > 1) {\n // This is OK. Child states can target a ui-view that the parent state also targets (the child wins)\n // Sort by depth and return the match from the deepest child\n // console.log(`Multiple matching view configs for ${uiView.fqn}`, matchingConfigs);\n matchingConfigs.sort(depthCompare(viewConfigDepth, -1)); // descending\n }\n return { uiView, viewConfig: matchingConfigs[0] };\n };\n\n const configureUIView = (tuple: ViewTuple) => {\n // If a parent ui-view is reconfigured, it could destroy child ui-views.\n // Before configuring a child ui-view, make sure it's still in the active uiViews array.\n if (this._uiViews.indexOf(tuple.uiView) !== -1) tuple.uiView.configUpdated(tuple.viewConfig);\n };\n\n // Sort views by FQN and state depth. Process uiviews nearest the root first.\n const uiViewTuples = this._uiViews.sort(depthCompare(uiViewDepth, 1)).map(matchingConfigPair);\n const matchedViewConfigs = uiViewTuples.map(tuple => tuple.viewConfig);\n const unmatchedConfigTuples = this._viewConfigs\n .filter(config => !inArray(matchedViewConfigs, config))\n .map(viewConfig => ({ uiView: undefined, viewConfig }));\n\n uiViewTuples.forEach(configureUIView);\n\n const allTuples: ViewTuple[] = uiViewTuples.concat(unmatchedConfigTuples);\n this._listeners.forEach(cb => cb(allTuples));\n trace.traceViewSync(allTuples);\n }\n\n /**\n * Registers a `ui-view` component\n *\n * When a `ui-view` component is created, it uses this method to register itself.\n * After registration the [[sync]] method is used to ensure all `ui-view` are configured with the proper [[ViewConfig]].\n *\n * Note: the `ui-view` component uses the `ViewConfig` to determine what view should be loaded inside the `ui-view`,\n * and what the view's state context is.\n *\n * Note: There is no corresponding `deregisterUIView`.\n * A `ui-view` should hang on to the return value of `registerUIView` and invoke it to deregister itself.\n *\n * @param uiView The metadata for a UIView\n * @return a de-registration function used when the view is destroyed.\n */\n registerUIView(uiView: ActiveUIView) {\n trace.traceViewServiceUIViewEvent('-> Registering', uiView);\n const uiViews = this._uiViews;\n const fqnAndTypeMatches = (uiv: ActiveUIView) => uiv.fqn === uiView.fqn && uiv.$type === uiView.$type;\n if (uiViews.filter(fqnAndTypeMatches).length)\n trace.traceViewServiceUIViewEvent('!!!! duplicate uiView named:', uiView);\n\n uiViews.push(uiView);\n this.sync();\n\n return () => {\n const idx = uiViews.indexOf(uiView);\n if (idx === -1) {\n trace.traceViewServiceUIViewEvent('Tried removing non-registered uiView', uiView);\n return;\n }\n trace.traceViewServiceUIViewEvent('<- Deregistering', uiView);\n removeFrom(uiViews)(uiView);\n };\n }\n\n /**\n * Returns the list of views currently available on the page, by fully-qualified name.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n available() {\n return this._uiViews.map(prop('fqn'));\n }\n\n /**\n * Returns the list of views on the page containing loaded content.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n active() {\n return this._uiViews.filter(prop('$config')).map(prop('name'));\n }\n}\n", "/**\n * @coreapi\n * @module core\n */ /** */\nimport { StateParams } from './params/stateParams';\nimport { StateDeclaration } from './state/interface';\nimport { StateObject } from './state/stateObject';\nimport { Transition } from './transition/transition';\nimport { Queue } from './common/queue';\nimport { Disposable } from './interface';\n\n/**\n * Global router state\n *\n * This is where we hold the global mutable state such as current state, current\n * params, current transition, etc.\n */\nexport class UIRouterGlobals implements Disposable {\n /**\n * Current parameter values\n *\n * The parameter values from the latest successful transition\n */\n params: StateParams = new StateParams();\n\n /**\n * Current state\n *\n * The to-state from the latest successful transition\n */\n current: StateDeclaration;\n\n /**\n * Current state (internal object)\n *\n * The to-state from the latest successful transition\n * @internalapi\n */\n $current: StateObject;\n\n /**\n * The current started/running transition.\n * This transition has reached at least the onStart phase, but is not yet complete\n */\n transition: Transition;\n\n /** @internalapi */\n lastStartedTransitionId = -1;\n\n /** @internalapi */\n transitionHistory = new Queue([], 1);\n\n /** @internalapi */\n successfulTransitions = new Queue([], 1);\n\n dispose() {\n this.transitionHistory.clear();\n this.successfulTransitions.clear();\n this.transition = null;\n }\n}\n", - "/**\n * @coreapi\n * @module url\n */ /** */\n\nimport { UIRouter } from '../router';\nimport { LocationServices, notImplemented, LocationConfig } from '../common/coreservices';\nimport { noop, createProxyFunctions } from '../common/common';\nimport { UrlConfigApi, UrlSyncApi, UrlRulesApi, UrlParts, MatchResult } from './interface';\n\n/** @hidden */\nconst makeStub = (keys: string[]): any =>\n keys.reduce((acc, key) => (acc[key] = notImplemented(key), acc), { dispose: noop });\n\n/* tslint:disable:align */\n/** @hidden */ const locationServicesFns = ['url', 'path', 'search', 'hash', 'onChange'];\n/** @hidden */ const locationConfigFns = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix'];\n/** @hidden */ const umfFns = ['type', 'caseInsensitive', 'strictMode', 'defaultSquashPolicy'];\n/** @hidden */ const rulesFns = ['sort', 'when', 'initial', 'otherwise', 'rules', 'rule', 'removeRule'];\n/** @hidden */ const syncFns = ['deferIntercept', 'listen', 'sync', 'match'];\n/* tslint:enable:align */\n\n/**\n * API for URL management\n */\nexport class UrlService implements LocationServices, UrlSyncApi {\n /** @hidden */\n static locationServiceStub: LocationServices = makeStub(locationServicesFns);\n /** @hidden */\n static locationConfigStub: LocationConfig = makeStub(locationConfigFns);\n\n /**\n * A nested API for managing URL rules and rewrites\n *\n * See: [[UrlRulesApi]] for details\n */\n rules: UrlRulesApi;\n\n /**\n * A nested API to configure the URL and retrieve URL information\n *\n * See: [[UrlConfigApi]] for details\n */\n config: UrlConfigApi;\n\n /** @hidden */\n private router: UIRouter;\n\n /** @hidden */\n constructor(router: UIRouter, lateBind = true) {\n this.router = router;\n this.rules = {} as any;\n this.config = {} as any;\n\n // proxy function calls from UrlService to the LocationService/LocationConfig\n const locationServices = () => router.locationService;\n createProxyFunctions(locationServices, this, locationServices, locationServicesFns, lateBind);\n\n const locationConfig = () => router.locationConfig;\n createProxyFunctions(locationConfig, this.config, locationConfig, locationConfigFns, lateBind);\n\n const umf = () => router.urlMatcherFactory;\n createProxyFunctions(umf, this.config, umf, umfFns);\n\n const urlRouter = () => router.urlRouter;\n createProxyFunctions(urlRouter, this.rules, urlRouter, rulesFns);\n createProxyFunctions(urlRouter, this, urlRouter, syncFns);\n }\n\n /** @inheritdoc */\n url(): string;\n /** @inheritdoc */\n url(newurl: string, replace?: boolean, state?): void;\n url(newurl?, replace?, state?): any { return; }\n /** @inheritdoc */\n path(): string { return; }\n /** @inheritdoc */\n search(): { [key: string]: any } { return; }\n /** @inheritdoc */\n hash(): string { return; }\n /** @inheritdoc */\n onChange(callback: Function): Function { return; }\n\n\n /**\n * Returns the current URL parts\n *\n * This method returns the current URL components as a [[UrlParts]] object.\n *\n * @returns the current url parts\n */\n parts(): UrlParts {\n return { path: this.path(), search: this.search(), hash: this.hash() };\n }\n\n dispose() { }\n\n /** @inheritdoc */\n sync(evt?) { return; }\n /** @inheritdoc */\n listen(enabled?: boolean): Function { return; }\n /** @inheritdoc */\n deferIntercept(defer?: boolean) { return; }\n /** @inheritdoc */\n match(urlParts: UrlParts): MatchResult { return; }\n\n}\n", - "/**\n * @coreapi\n * @module core\n */ /** */\nimport { UrlMatcherFactory } from './url/urlMatcherFactory';\nimport { UrlRouter } from './url/urlRouter';\nimport { TransitionService } from './transition/transitionService';\nimport { ViewService } from './view/view';\nimport { StateRegistry } from './state/stateRegistry';\nimport { StateService } from './state/stateService';\nimport { UIRouterGlobals } from './globals';\nimport { UIRouterPlugin, Disposable } from './interface';\nimport { values, removeFrom } from './common/common';\nimport { isFunction } from './common/predicates';\nimport { UrlService } from './url/urlService';\nimport { LocationServices, LocationConfig } from './common/coreservices';\nimport { Trace, trace } from './common/trace';\n\n/** @hidden */\nlet _routerInstance = 0;\n\n/**\n * The master class used to instantiate an instance of UI-Router.\n *\n * UI-Router (for each specific framework) will create an instance of this class during bootstrap.\n * This class instantiates and wires the UI-Router services together.\n *\n * After a new instance of the UIRouter class is created, it should be configured for your app.\n * For instance, app states should be registered with the [[UIRouter.stateRegistry]].\n *\n * ---\n *\n * Normally the framework code will bootstrap UI-Router.\n * If you are bootstrapping UIRouter manually, tell it to monitor the URL by calling\n * [[UrlService.listen]] then [[UrlService.sync]].\n */\nexport class UIRouter {\n /** @hidden */ $id = _routerInstance++;\n /** @hidden */ _disposed = false;\n /** @hidden */ private _disposables: Disposable[] = [];\n\n /** Provides trace information to the console */\n trace: Trace = trace;\n\n /** Provides services related to ui-view synchronization */\n viewService = new ViewService();\n\n /** Global router state */\n globals: UIRouterGlobals = new UIRouterGlobals();\n\n /** Provides services related to Transitions */\n transitionService: TransitionService = new TransitionService(this);\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlMatcherFactory: UrlMatcherFactory = new UrlMatcherFactory();\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlRouter: UrlRouter = new UrlRouter(this);\n\n /** Provides a registry for states, and related registration services */\n stateRegistry: StateRegistry = new StateRegistry(this);\n\n /** Provides services related to states */\n stateService = new StateService(this);\n\n /** Provides services related to the URL */\n urlService: UrlService = new UrlService(this);\n\n /** @hidden plugin instances are registered here */\n private _plugins: { [key: string]: UIRouterPlugin } = {};\n\n\n /** Registers an object to be notified when the router is disposed */\n disposable(disposable: Disposable) {\n this._disposables.push(disposable);\n }\n\n /**\n * Disposes this router instance\n *\n * When called, clears resources retained by the router by calling `dispose(this)` on all\n * registered [[disposable]] objects.\n *\n * Or, if a `disposable` object is provided, calls `dispose(this)` on that object only.\n *\n * @param disposable (optional) the disposable to dispose\n */\n dispose(disposable?: any): void {\n if (disposable && isFunction(disposable.dispose)) {\n disposable.dispose(this);\n return undefined;\n }\n\n this._disposed = true;\n this._disposables.slice().forEach(d => {\n try {\n typeof d.dispose === 'function' && d.dispose(this);\n removeFrom(this._disposables, d);\n } catch (ignored) {}\n });\n }\n\n /**\n * Creates a new `UIRouter` object\n *\n * @param locationService a [[LocationServices]] implementation\n * @param locationConfig a [[LocationConfig]] implementation\n * @internalapi\n */\n constructor(\n public locationService: LocationServices = UrlService.locationServiceStub,\n public locationConfig: LocationConfig = UrlService.locationConfigStub,\n ) {\n\n this.viewService._pluginapi._rootViewContext(this.stateRegistry.root());\n this.globals.$current = this.stateRegistry.root();\n this.globals.current = this.globals.$current.self;\n\n this.disposable(this.globals);\n this.disposable(this.stateService);\n this.disposable(this.stateRegistry);\n this.disposable(this.transitionService);\n this.disposable(this.urlRouter);\n this.disposable(locationService);\n this.disposable(locationConfig);\n }\n\n /** Add plugin (as ES6 class) */\n plugin(plugin: { new(router: UIRouter, options?: any): T }, options?: any): T;\n /** Add plugin (as javascript constructor function) */\n plugin(plugin: { (router: UIRouter, options?: any): void }, options?: any): T;\n /** Add plugin (as javascript factory function) */\n plugin(plugin: PluginFactory, options?: any): T;\n /**\n * Adds a plugin to UI-Router\n *\n * This method adds a UI-Router Plugin.\n * A plugin can enhance or change UI-Router behavior using any public API.\n *\n * #### Example:\n * ```js\n * import { MyCoolPlugin } from \"ui-router-cool-plugin\";\n *\n * var plugin = router.addPlugin(MyCoolPlugin);\n * ```\n *\n * ### Plugin authoring\n *\n * A plugin is simply a class (or constructor function) which accepts a [[UIRouter]] instance and (optionally) an options object.\n *\n * The plugin can implement its functionality using any of the public APIs of [[UIRouter]].\n * For example, it may configure router options or add a Transition Hook.\n *\n * The plugin can then be published as a separate module.\n *\n * #### Example:\n * ```js\n * export class MyAuthPlugin implements UIRouterPlugin {\n * constructor(router: UIRouter, options: any) {\n * this.name = \"MyAuthPlugin\";\n * let $transitions = router.transitionService;\n * let $state = router.stateService;\n *\n * let authCriteria = {\n * to: (state) => state.data && state.data.requiresAuth\n * };\n *\n * function authHook(transition: Transition) {\n * let authService = transition.injector().get('AuthService');\n * if (!authService.isAuthenticated()) {\n * return $state.target('login');\n * }\n * }\n *\n * $transitions.onStart(authCriteria, authHook);\n * }\n * }\n * ```\n *\n * @param plugin one of:\n * - a plugin class which implements [[UIRouterPlugin]]\n * - a constructor function for a [[UIRouterPlugin]] which accepts a [[UIRouter]] instance\n * - a factory function which accepts a [[UIRouter]] instance and returns a [[UIRouterPlugin]] instance\n * @param options options to pass to the plugin class/factory\n * @returns the registered plugin instance\n */\n plugin(plugin: any, options: any = {}): T {\n const pluginInstance = new plugin(this, options);\n if (!pluginInstance.name) throw new Error('Required property `name` missing on plugin: ' + pluginInstance);\n this._disposables.push(pluginInstance);\n return this._plugins[pluginInstance.name] = pluginInstance;\n }\n\n /**\n * Returns registered plugins\n *\n * Returns the registered plugin of the given `pluginName`.\n * If no `pluginName` is given, returns all registered plugins\n *\n * @param pluginName (optional) the name of the plugin to get\n * @return the named plugin (undefined if not found), or all plugins (if `pluginName` is omitted)\n */\n getPlugin(pluginName: string): UIRouterPlugin;\n getPlugin(): UIRouterPlugin[];\n getPlugin(pluginName?: string): UIRouterPlugin|UIRouterPlugin[] {\n return pluginName ? this._plugins[pluginName] : values(this._plugins);\n }\n}\n\n/** @internalapi */\nexport type PluginFactory = (router: UIRouter, options?: any) => T;\n", - "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { UIRouter } from '../router';\nimport { TransitionService } from '../transition/transitionService';\nimport { Resolvable } from '../resolve';\nimport { extend, inArray, map, mapObj, uniqR, unnestR, values } from '../common';\nimport { PathNode } from '../path';\nimport { TreeChanges } from \"../transition\";\n\nfunction addCoreResolvables(trans: Transition) {\n trans.addResolvable(Resolvable.fromData(UIRouter, trans.router), '');\n trans.addResolvable(Resolvable.fromData(Transition, trans), '');\n trans.addResolvable(Resolvable.fromData('$transition$', trans), '');\n trans.addResolvable(Resolvable.fromData('$stateParams', trans.params()), '');\n\n trans.entering().forEach(state => {\n trans.addResolvable(Resolvable.fromData('$state$', state), state);\n });\n}\n\nexport const registerAddCoreResolvables = (transitionService: TransitionService) =>\n transitionService.onCreate({}, addCoreResolvables);\n\nconst TRANSITION_TOKENS = ['$transition$', Transition];\nconst isTransition = inArray(TRANSITION_TOKENS);\n\n// References to Transition in the treeChanges pathnodes makes all\n// previous Transitions reachable in memory, causing a memory leak\n// This function removes resolves for '$transition$' and `Transition` from the treeChanges.\n// Do not use this on current transitions, only on old ones.\nexport const treeChangesCleanup = (trans: Transition) => {\n const nodes = values(trans.treeChanges()).reduce(unnestR, []).reduce(uniqR, []);\n\n // If the resolvable is a Transition, return a new resolvable with null data\n const replaceTransitionWithNull = (r: Resolvable): Resolvable => {\n return isTransition(r.token) ? Resolvable.fromData(r.token, null) : r;\n };\n\n nodes.forEach((node: PathNode) => {\n node.resolvables = node.resolvables.map(replaceTransitionWithNull);\n });\n};\n", - "/** @module hooks */ /** */\nimport { isString, isFunction } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { services } from '../common/coreservices';\nimport { TargetState } from '../state/targetState';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\n\n/**\n * A [[TransitionHookFn]] that redirects to a different state or params\n *\n * Registered using `transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectHook);`\n *\n * See [[StateDeclaration.redirectTo]]\n */\nconst redirectToHook: TransitionHookFn = (trans: Transition) => {\n const redirect = trans.to().redirectTo;\n if (!redirect) return;\n\n const $state = trans.router.stateService;\n\n function handleResult(result: any) {\n if (!result) return;\n if (result instanceof TargetState) return result;\n if (isString(result)) return $state.target( result, trans.params(), trans.options());\n if (result['state'] || result['params'])\n return $state.target(result['state'] || trans.to(), result['params'] || trans.params(), trans.options());\n }\n\n if (isFunction(redirect)) {\n return services.$q.when(redirect(trans)).then(handleResult);\n }\n return handleResult(redirect);\n};\n\nexport const registerRedirectToHook = (transitionService: TransitionService) =>\n transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectToHook);\n", - "/** @module hooks */\n/** for typedoc */\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { StateDeclaration } from '../state/interface';\nimport { StateObject } from '../state/stateObject';\n\n/**\n * A factory which creates an onEnter, onExit or onRetain transition hook function\n *\n * The returned function invokes the (for instance) state.onEnter hook when the\n * state is being entered.\n *\n * @hidden\n */\nfunction makeEnterExitRetainHook(hookName: string): TransitionStateHookFn {\n return (transition: Transition, state: StateDeclaration) => {\n const _state: StateObject = state.$$state();\n const hookFn: TransitionStateHookFn = _state[hookName];\n return hookFn(transition, state);\n };\n}\n\n/**\n * The [[TransitionStateHookFn]] for onExit\n *\n * When the state is being exited, the state's .onExit function is invoked.\n *\n * Registered using `transitionService.onExit({ exiting: (state) => !!state.onExit }, onExitHook);`\n *\n * See: [[IHookRegistry.onExit]]\n */\nconst onExitHook: TransitionStateHookFn = makeEnterExitRetainHook('onExit');\nexport const registerOnExitHook = (transitionService: TransitionService) =>\n transitionService.onExit({ exiting: state => !!state.onExit }, onExitHook);\n\n/**\n * The [[TransitionStateHookFn]] for onRetain\n *\n * When the state was already entered, and is not being exited or re-entered, the state's .onRetain function is invoked.\n *\n * Registered using `transitionService.onRetain({ retained: (state) => !!state.onRetain }, onRetainHook);`\n *\n * See: [[IHookRegistry.onRetain]]\n */\nconst onRetainHook: TransitionStateHookFn = makeEnterExitRetainHook('onRetain');\nexport const registerOnRetainHook = (transitionService: TransitionService) =>\n transitionService.onRetain({ retained: state => !!state.onRetain }, onRetainHook);\n\n/**\n * The [[TransitionStateHookFn]] for onEnter\n *\n * When the state is being entered, the state's .onEnter function is invoked.\n *\n * Registered using `transitionService.onEnter({ entering: (state) => !!state.onEnter }, onEnterHook);`\n *\n * See: [[IHookRegistry.onEnter]]\n */\nconst onEnterHook: TransitionStateHookFn = makeEnterExitRetainHook('onEnter');\nexport const registerOnEnterHook = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: state => !!state.onEnter }, onEnterHook);\n\n", - "/** @module hooks */\n/** for typedoc */\nimport { noop } from '../common/common';\nimport { Transition } from '../transition/transition';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { TransitionStateHookFn, TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\nimport { val } from '../common/hof';\nimport { StateDeclaration } from '../state/interface';\n\nexport const RESOLVE_HOOK_PRIORITY = 1000;\n\n/**\n * A [[TransitionHookFn]] which resolves all EAGER Resolvables in the To Path\n *\n * Registered using `transitionService.onStart({}, eagerResolvePath, { priority: 1000 });`\n *\n * When a Transition starts, this hook resolves all the EAGER Resolvables, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst eagerResolvePath: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to)\n .resolvePath('EAGER', trans)\n .then(noop);\n\nexport const registerEagerResolvePath = (transitionService: TransitionService) =>\n transitionService.onStart({}, eagerResolvePath, { priority: RESOLVE_HOOK_PRIORITY });\n\n/**\n * A [[TransitionHookFn]] which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path\n *\n * Registered using `transitionService.onEnter({ entering: () => true }, lazyResolveState, { priority: 1000 });`\n *\n * When a State is being entered, this hook resolves all the Resolvables for this state, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst lazyResolveState: TransitionStateHookFn = (trans: Transition, state: StateDeclaration) =>\n new ResolveContext(trans.treeChanges().to)\n .subContext(state.$$state())\n .resolvePath('LAZY', trans)\n .then(noop);\n\nexport const registerLazyResolveState = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: val(true) }, lazyResolveState, { priority: RESOLVE_HOOK_PRIORITY });\n\n\n/**\n * A [[TransitionHookFn]] which resolves any dynamically added (LAZY or EAGER) Resolvables.\n *\n * Registered using `transitionService.onFinish({}, eagerResolvePath, { priority: 1000 });`\n *\n * After all entering states have been entered, this hook resolves any remaining Resolvables.\n * These are typically dynamic resolves which were added by some Transition Hook using [[Transition.addResolvable]].\n *\n * See [[StateDeclaration.resolve]]\n */\nconst resolveRemaining: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to)\n .resolvePath('LAZY', trans)\n .then(noop);\n\nexport const registerResolveRemaining = (transitionService: TransitionService) =>\n transitionService.onFinish({}, resolveRemaining, { priority: RESOLVE_HOOK_PRIORITY });\n", - "/** @module hooks */ /** for typedoc */\nimport { noop } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { Transition } from '../transition/transition';\nimport { ViewService } from '../view/view';\nimport { ViewConfig } from '../view/interface';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n\n/**\n * A [[TransitionHookFn]] which waits for the views to load\n *\n * Registered using `transitionService.onStart({}, loadEnteringViews);`\n *\n * Allows the views to do async work in [[ViewConfig.load]] before the transition continues.\n * In angular 1, this includes loading the templates.\n */\nconst loadEnteringViews: TransitionHookFn = (transition: Transition) => {\n const $q = services.$q;\n const enteringViews = transition.views('entering');\n if (!enteringViews.length) return;\n return $q.all(enteringViews.map(view => $q.when(view.load()))).then(noop);\n};\n\nexport const registerLoadEnteringViews = (transitionService: TransitionService) =>\n transitionService.onFinish({}, loadEnteringViews);\n\n/**\n * A [[TransitionHookFn]] which activates the new views when a transition is successful.\n *\n * Registered using `transitionService.onSuccess({}, activateViews);`\n *\n * After a transition is complete, this hook deactivates the old views from the previous state,\n * and activates the new views from the destination state.\n *\n * See [[ViewService]]\n */\nconst activateViews: TransitionHookFn = (transition: Transition) => {\n const enteringViews = transition.views('entering');\n const exitingViews = transition.views('exiting');\n if (!enteringViews.length && !exitingViews.length) return;\n\n const $view: ViewService = transition.router.viewService;\n\n exitingViews.forEach((vc: ViewConfig) => $view.deactivateViewConfig(vc));\n enteringViews.forEach((vc: ViewConfig) => $view.activateViewConfig(vc));\n\n $view.sync();\n};\n\nexport const registerActivateViews = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, activateViews);\n", - "/** @module hooks */\n/** for typedoc */\nimport { Transition } from '../transition/transition';\nimport { copy } from '../common/common';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates global UI-Router state\n *\n * Registered using `transitionService.onBefore({}, updateGlobalState);`\n *\n * Before a [[Transition]] starts, updates the global value of \"the current transition\" ([[Globals.transition]]).\n * After a successful [[Transition]], updates the global values of \"the current state\"\n * ([[Globals.current]] and [[Globals.$current]]) and \"the current param values\" ([[Globals.params]]).\n *\n * See also the deprecated properties:\n * [[StateService.transition]], [[StateService.current]], [[StateService.params]]\n */\nconst updateGlobalState = (trans: Transition) => {\n const globals = trans.router.globals;\n\n const transitionSuccessful = () => {\n globals.successfulTransitions.enqueue(trans);\n globals.$current = trans.$to();\n globals.current = globals.$current.self;\n\n copy(trans.params(), globals.params);\n };\n\n const clearCurrentTransition = () => {\n // Do not clear globals.transition if a different transition has started in the meantime\n if (globals.transition === trans) globals.transition = null;\n };\n\n trans.onSuccess({}, transitionSuccessful, { priority: 10000 });\n trans.promise.then(clearCurrentTransition, clearCurrentTransition);\n};\n\nexport const registerUpdateGlobalState = (transitionService: TransitionService) =>\n transitionService.onCreate({}, updateGlobalState);\n", - "/** @module hooks */ /** */\nimport { UrlRouter } from '../url/urlRouter';\nimport { StateService } from '../state/stateService';\nimport { Transition } from '../transition/transition';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates the URL after a successful transition\n *\n * Registered using `transitionService.onSuccess({}, updateUrl);`\n */\nconst updateUrl: TransitionHookFn = (transition: Transition) => {\n const options = transition.options();\n const $state: StateService = transition.router.stateService;\n const $urlRouter: UrlRouter = transition.router.urlRouter;\n\n // Dont update the url in these situations:\n // The transition was triggered by a URL sync (options.source === 'url')\n // The user doesn't want the url to update (options.location === false)\n // The destination state, and all parents have no navigable url\n if (options.source !== 'url' && options.location && $state.$current.navigable) {\n const urlOptions = { replace: options.location === 'replace' };\n $urlRouter.push($state.$current.navigable.url, $state.params, urlOptions);\n }\n\n $urlRouter.update(true);\n};\n\nexport const registerUpdateUrl = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, updateUrl, { priority: 9999 });\n", - "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\nimport { StateDeclaration, LazyLoadResult } from '../state/interface';\nimport { services } from '../common/coreservices';\nimport { StateRule } from '../url/interface';\n\n/**\n * A [[TransitionHookFn]] that performs lazy loading\n *\n * When entering a state \"abc\" which has a `lazyLoad` function defined:\n * - Invoke the `lazyLoad` function (unless it is already in process)\n * - Flag the hook function as \"in process\"\n * - The function should return a promise (that resolves when lazy loading is complete)\n * - Wait for the promise to settle\n * - If the promise resolves to a [[LazyLoadResult]], then register those states\n * - Flag the hook function as \"not in process\"\n * - If the hook was successful\n * - Remove the `lazyLoad` function from the state declaration\n * - If all the hooks were successful\n * - Retry the transition (by returning a TargetState)\n *\n * ```\n * .state('abc', {\n * component: 'fooComponent',\n * lazyLoad: () => System.import('./fooComponent')\n * });\n * ```\n *\n * See [[StateDeclaration.lazyLoad]]\n */\nconst lazyLoadHook: TransitionHookFn = (transition: Transition) => {\n const router = transition.router;\n\n function retryTransition() {\n if (transition.originalTransition().options().source !== 'url') {\n // The original transition was not triggered via url sync\n // The lazy state should be loaded now, so re-try the original transition\n const orig = transition.targetState();\n return router.stateService.target(orig.identifier(), orig.params(), orig.options());\n }\n\n // The original transition was triggered via url sync\n // Run the URL rules and find the best match\n const $url = router.urlService;\n const result = $url.match($url.parts());\n const rule = result && result.rule;\n\n // If the best match is a state, redirect the transition (instead\n // of calling sync() which supersedes the current transition)\n if (rule && rule.type === 'STATE') {\n const state = (rule as StateRule).state;\n const params = result.match;\n return router.stateService.target(state, params, transition.options());\n }\n\n // No matching state found, so let .sync() choose the best non-state match/otherwise\n router.urlService.sync();\n }\n\n const promises = transition.entering()\n .filter(state => !!state.$$state().lazyLoad)\n .map(state => lazyLoadState(transition, state));\n\n return services.$q.all(promises).then(retryTransition);\n};\n\nexport const registerLazyLoadHook = (transitionService: TransitionService) =>\n transitionService.onBefore({ entering: (state) => !!state.lazyLoad }, lazyLoadHook);\n\n\n/**\n * Invokes a state's lazy load function\n *\n * @param transition a Transition context\n * @param state the state to lazy load\n * @returns A promise for the lazy load result\n */\nexport function lazyLoadState(transition: Transition, state: StateDeclaration): Promise {\n const lazyLoadFn = state.$$state().lazyLoad;\n\n // Store/get the lazy load promise on/from the hookfn so it doesn't get re-invoked\n let promise = lazyLoadFn['_promise'];\n if (!promise) {\n const success = (result) => {\n delete state.lazyLoad;\n delete state.$$state().lazyLoad;\n delete lazyLoadFn['_promise'];\n return result;\n };\n\n const error = (err) => {\n delete lazyLoadFn['_promise'];\n return services.$q.reject(err);\n };\n\n promise = lazyLoadFn['_promise'] =\n services.$q.when(lazyLoadFn(transition, state))\n .then(updateStateRegistry)\n .then(success, error);\n }\n\n /** Register any lazy loaded state definitions */\n function updateStateRegistry(result: LazyLoadResult) {\n if (result && Array.isArray(result.states)) {\n result.states.forEach(_state => transition.router.stateRegistry.register(_state));\n }\n return result;\n }\n\n return promise;\n}\n", - "/** @module transition */ /** */\nimport { TransitionHookPhase, PathType } from './interface';\nimport { GetErrorHandler, GetResultHandler, TransitionHook } from './transitionHook';\n/**\n * This class defines a type of hook, such as `onBefore` or `onEnter`.\n * Plugins can define custom hook types, such as sticky states does for `onInactive`.\n *\n * @interalapi\n */\nexport class TransitionEventType {\n /* tslint:disable:no-inferrable-types */\n constructor(public name: string,\n public hookPhase: TransitionHookPhase,\n public hookOrder: number,\n public criteriaMatchPath: PathType,\n public reverseSort: boolean = false,\n public getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n public getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n public synchronous: boolean = false,\n ) { }\n}\n", - "/** @module hooks */ /** */\n\nimport { trace } from '../common/trace';\nimport { Rejection } from '../transition/rejectFactory';\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that skips a transition if it should be ignored\n *\n * This hook is invoked at the end of the onBefore phase.\n *\n * If the transition should be ignored (because no parameter or states changed)\n * then the transition is ignored and not processed.\n */\nfunction ignoredHook(trans: Transition) {\n const ignoredReason = trans._ignoredReason();\n if (!ignoredReason) return;\n\n trace.traceTransitionIgnored(trans);\n\n const pending = trans.router.globals.transition;\n\n // The user clicked a link going back to the *current state* ('A')\n // However, there is also a pending transition in flight (to 'B')\n // Abort the transition to 'B' because the user now wants to be back at 'A'.\n if (ignoredReason === 'SameAsCurrent' && pending) {\n pending.abort();\n }\n\n return Rejection.ignored().toPromise();\n}\n\nexport const registerIgnoredTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, ignoredHook, { priority: -9999 });\n", - "/** @module hooks */ /** */\n\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that rejects the Transition if it is invalid\n *\n * This hook is invoked at the end of the onBefore phase.\n * If the transition is invalid (for example, param values do not validate)\n * then the transition is rejected.\n */\nfunction invalidTransitionHook(trans: Transition) {\n if (!trans.valid()) {\n throw new Error(trans.error());\n }\n}\n\nexport const registerInvalidTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, invalidTransitionHook, { priority: -10000 });\n", - "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport {\n IHookRegistry, TransitionOptions, TransitionHookScope, TransitionHookPhase, TransitionCreateHookFn, HookMatchCriteria,\n HookRegOptions, PathTypes, PathType, RegisteredHooks, TransitionHookFn, TransitionStateHookFn,\n} from './interface';\nimport { Transition } from './transition';\nimport { makeEvent, RegisteredHook } from './hookRegistry';\nimport { TargetState } from '../state/targetState';\nimport { PathNode } from '../path/pathNode';\nimport { ViewService } from '../view/view';\nimport { UIRouter } from '../router';\nimport { registerAddCoreResolvables, treeChangesCleanup } from '../hooks/coreResolvables';\nimport { registerRedirectToHook } from '../hooks/redirectTo';\nimport { registerOnExitHook, registerOnRetainHook, registerOnEnterHook } from '../hooks/onEnterExitRetain';\nimport { registerEagerResolvePath, registerLazyResolveState, registerResolveRemaining } from '../hooks/resolve';\nimport { registerLoadEnteringViews, registerActivateViews } from '../hooks/views';\nimport { registerUpdateGlobalState } from '../hooks/updateGlobals';\nimport { registerUpdateUrl } from '../hooks/url';\nimport { registerLazyLoadHook } from '../hooks/lazyLoad';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionHook, GetResultHandler, GetErrorHandler } from './transitionHook';\nimport { isDefined } from '../common/predicates';\nimport { removeFrom, values, createProxyFunctions } from '../common/common';\nimport { Disposable } from '../interface'; // has or is using\nimport { val } from '../common/hof';\nimport { registerIgnoredTransitionHook } from '../hooks/ignoredTransition';\nimport { registerInvalidTransitionHook } from '../hooks/invalidTransition';\n\n/**\n * The default [[Transition]] options.\n *\n * Include this object when applying custom defaults:\n * let reloadOpts = { reload: true, notify: true }\n * let options = defaults(theirOpts, customDefaults, defaultOptions);\n */\nexport let defaultTransOpts: TransitionOptions = {\n location : true,\n relative : null,\n inherit : false,\n notify : true,\n reload : false,\n custom : {},\n current : () => null,\n source : 'unknown',\n};\n\n\n/**\n * Plugin API for Transition Service\n * @internalapi\n */\nexport interface TransitionServicePluginAPI {\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n */\n _definePathType(name: string, hookScope: TransitionHookScope);\n\n /**\n * Gets a Path definition used as a criterion against a TreeChanges path\n */\n _getPathTypes(): PathTypes;\n\n /**\n * Defines a transition hook type and returns a transition hook registration\n * function (which can then be used to register hooks of this type).\n */\n _defineEvent(name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort?: boolean,\n getResultHandler?: GetResultHandler,\n getErrorHandler?: GetErrorHandler,\n rejectIfSuperseded?: boolean);\n\n /**\n * Returns the known event types, such as `onBefore`\n * If a phase argument is provided, returns only events for the given phase.\n */\n _getEvents(phase?: TransitionHookPhase): TransitionEventType[];\n\n /** Returns the hooks registered for the given hook name */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/**\n * This class provides services related to Transitions.\n *\n * - Most importantly, it allows global Transition Hooks to be registered.\n * - It allows the default transition error handler to be set.\n * - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]).\n *\n * At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class.\n */\nexport class TransitionService implements IHookRegistry, Disposable {\n /** @hidden */\n _transitionCount = 0;\n\n /** @hidden */\n public $view: ViewService;\n\n /** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */\n private _eventTypes: TransitionEventType[] = [];\n /** @hidden The registered transition hooks */\n _registeredHooks = { } as RegisteredHooks;\n /** @hidden The paths on a criteria object */\n private _criteriaPaths = { } as PathTypes;\n /** @hidden */\n private _router: UIRouter;\n\n /** @internalapi */\n _pluginapi: TransitionServicePluginAPI;\n\n /**\n * This object has hook de-registration functions for the built-in hooks.\n * This can be used by third parties libraries that wish to customize the behaviors\n *\n * @hidden\n */\n _deregisterHookFns: {\n addCoreResolves: Function;\n ignored: Function;\n invalid: Function;\n redirectTo: Function;\n onExit: Function;\n onRetain: Function;\n onEnter: Function;\n eagerResolve: Function;\n lazyResolve: Function;\n resolveAll: Function;\n loadViews: Function;\n activateViews: Function;\n updateGlobals: Function;\n updateUrl: Function;\n lazyLoad: Function;\n };\n\n /** @hidden */\n constructor(_router: UIRouter) {\n this._router = _router;\n this.$view = _router.viewService;\n this._deregisterHookFns = {};\n this._pluginapi = createProxyFunctions(val(this), {}, val(this), [\n '_definePathType',\n '_defineEvent',\n '_getPathTypes',\n '_getEvents',\n 'getHooks',\n ]);\n\n this._defineCorePaths();\n this._defineCoreEvents();\n this._registerCoreTransitionHooks();\n _router.globals.successfulTransitions.onEvict(treeChangesCleanup);\n }\n\n /**\n * Registers a [[TransitionHookFn]], called *while a transition is being constructed*.\n *\n * Registers a transition lifecycle hook, which is invoked during transition construction.\n *\n * This low level hook should only be used by plugins.\n * This can be a useful time for plugins to add resolves or mutate the transition as needed.\n * The Sticky States plugin uses this hook to modify the treechanges.\n *\n * ### Lifecycle\n *\n * `onCreate` hooks are invoked *while a transition is being constructed*.\n *\n * ### Return value\n *\n * The hook's return value is ignored\n *\n * @internalapi\n * @param criteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @param options the registration options\n * @returns a function which deregisters the hook.\n */\n onCreate(criteria: HookMatchCriteria, callback: TransitionCreateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n\n /**\n * dispose\n * @internalapi\n */\n dispose(router: UIRouter) {\n values(this._registeredHooks).forEach((hooksArray: RegisteredHook[]) => hooksArray.forEach(hook => {\n hook._deregistered = true;\n removeFrom(hooksArray, hook);\n }));\n }\n\n /**\n * Creates a new [[Transition]] object\n *\n * This is a factory function for creating new Transition objects.\n * It is used internally by the [[StateService]] and should generally not be called by application code.\n *\n * @param fromPath the path to the current state (the from state)\n * @param targetState the target state (destination)\n * @returns a Transition\n */\n create(fromPath: PathNode[], targetState: TargetState): Transition {\n return new Transition(fromPath, targetState, this._router);\n }\n\n /** @hidden */\n private _defineCoreEvents() {\n const Phase = TransitionHookPhase;\n const TH = TransitionHook;\n const paths = this._criteriaPaths;\n const NORMAL_SORT = false, REVERSE_SORT = true;\n const SYNCHRONOUS = true;\n\n this._defineEvent('onCreate', Phase.CREATE, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.THROW_ERROR, SYNCHRONOUS);\n\n this._defineEvent('onBefore', Phase.BEFORE, 0, paths.to);\n\n this._defineEvent('onStart', Phase.RUN, 0, paths.to);\n this._defineEvent('onExit', Phase.RUN, 100, paths.exiting, REVERSE_SORT);\n this._defineEvent('onRetain', Phase.RUN, 200, paths.retained);\n this._defineEvent('onEnter', Phase.RUN, 300, paths.entering);\n this._defineEvent('onFinish', Phase.RUN, 400, paths.to);\n\n this._defineEvent('onSuccess', Phase.SUCCESS, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.LOG_ERROR, SYNCHRONOUS);\n this._defineEvent('onError', Phase.ERROR, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.LOG_ERROR, SYNCHRONOUS);\n }\n\n /** @hidden */\n private _defineCorePaths() {\n const { STATE, TRANSITION } = TransitionHookScope;\n\n this._definePathType('to', TRANSITION);\n this._definePathType('from', TRANSITION);\n this._definePathType('exiting', STATE);\n this._definePathType('retained', STATE);\n this._definePathType('entering', STATE);\n }\n\n /** @hidden */\n _defineEvent(name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort = false,\n getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n synchronous = false) {\n const eventType = new TransitionEventType(name, hookPhase, hookOrder, criteriaMatchPath, reverseSort, getResultHandler, getErrorHandler, synchronous);\n\n this._eventTypes.push(eventType);\n makeEvent(this, this, eventType);\n }\n\n /** @hidden */ // tslint:disable-next-line\n private _getEvents(phase?: TransitionHookPhase): TransitionEventType[] {\n const transitionHookTypes = isDefined(phase) ?\n this._eventTypes.filter(type => type.hookPhase === phase) :\n this._eventTypes.slice();\n\n return transitionHookTypes.sort((l, r) => {\n const cmpByPhase = l.hookPhase - r.hookPhase;\n return cmpByPhase === 0 ? l.hookOrder - r.hookOrder : cmpByPhase;\n });\n }\n\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n *\n * @hidden\n */\n private _definePathType(name: string, hookScope: TransitionHookScope) {\n this._criteriaPaths[name] = { name, scope: hookScope };\n }\n\n /** * @hidden */ // tslint:disable-next-line\n private _getPathTypes(): PathTypes {\n return this._criteriaPaths;\n }\n\n /** @hidden */\n public getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /** @hidden */\n private _registerCoreTransitionHooks() {\n const fns = this._deregisterHookFns;\n\n fns.addCoreResolves = registerAddCoreResolvables(this);\n fns.ignored = registerIgnoredTransitionHook(this);\n fns.invalid = registerInvalidTransitionHook(this);\n\n // Wire up redirectTo hook\n fns.redirectTo = registerRedirectToHook(this);\n\n // Wire up onExit/Retain/Enter state hooks\n fns.onExit = registerOnExitHook(this);\n fns.onRetain = registerOnRetainHook(this);\n fns.onEnter = registerOnEnterHook(this);\n\n // Wire up Resolve hooks\n fns.eagerResolve = registerEagerResolvePath(this);\n fns.lazyResolve = registerLazyResolveState(this);\n fns.resolveAll = registerResolveRemaining(this);\n\n // Wire up the View management hooks\n fns.loadViews = registerLoadEnteringViews(this);\n fns.activateViews = registerActivateViews(this);\n\n // Updates global state after a transition\n fns.updateGlobals = registerUpdateGlobalState(this);\n\n // After globals.current is updated at priority: 10000\n fns.updateUrl = registerUpdateUrl(this);\n\n // Lazy load state trees\n fns.lazyLoad = registerLazyLoadHook(this);\n }\n}\n", - "/**\n * @coreapi\n * @module state\n */\n/** */\nimport { createProxyFunctions, defaults, extend, inArray, noop, removeFrom, silenceUncaughtInPromise, silentRejection } from '../common/common';\nimport { isDefined, isObject, isString } from '../common/predicates';\nimport { Queue } from '../common/queue';\nimport { services } from '../common/coreservices';\n\nimport { PathUtils } from '../path/pathUtils';\nimport { PathNode } from '../path/pathNode';\n\nimport { HookResult, TransitionOptions } from '../transition/interface';\nimport { defaultTransOpts } from '../transition/transitionService';\nimport { Rejection, RejectType } from '../transition/rejectFactory';\nimport { Transition } from '../transition/transition';\n\nimport { HrefOptions, LazyLoadResult, StateDeclaration, StateOrName, TransitionPromise } from './interface';\nimport { StateObject } from './stateObject';\nimport { TargetState } from './targetState';\n\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Glob } from '../common/glob';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { lazyLoadState } from '../hooks/lazyLoad';\nimport { not, val } from '../common/hof';\nimport { StateParams } from '../params/stateParams';\n\nexport type OnInvalidCallback =\n (toState?: TargetState, fromState?: TargetState, injector?: UIInjector) => HookResult;\n\n/**\n * Provides state related service functions\n *\n * This class provides services related to ui-router states.\n * An instance of this class is located on the global [[UIRouter]] object.\n */\nexport class StateService {\n /** @internalapi */\n invalidCallbacks: OnInvalidCallback[] = [];\n\n /**\n * The [[Transition]] currently in progress (or null)\n *\n * This is a passthrough through to [[UIRouterGlobals.transition]]\n */\n get transition() { return this.router.globals.transition; }\n /**\n * The latest successful state parameters\n *\n * This is a passthrough through to [[UIRouterGlobals.params]]\n */\n get params(): StateParams { return this.router.globals.params; }\n /**\n * The current [[StateDeclaration]]\n *\n * This is a passthrough through to [[UIRouterGlobals.current]]\n */\n get current() { return this.router.globals.current; }\n /**\n * The current [[StateObject]]\n *\n * This is a passthrough through to [[UIRouterGlobals.$current]]\n */\n get $current() { return this.router.globals.$current; }\n\n /** @internalapi */\n constructor(private router: UIRouter) {\n const getters = ['current', '$current', 'params', 'transition'];\n const boundFns = Object.keys(StateService.prototype).filter(not(inArray(getters)));\n createProxyFunctions(val(StateService.prototype), this, val(this), boundFns);\n }\n\n /** @internalapi */\n dispose() {\n this.defaultErrorHandler(noop);\n this.invalidCallbacks = [];\n }\n\n /**\n * Handler for when [[transitionTo]] is called with an invalid state.\n *\n * Invokes the [[onInvalid]] callbacks, in natural order.\n * Each callback's return value is checked in sequence until one of them returns an instance of TargetState.\n * The results of the callbacks are wrapped in $q.when(), so the callbacks may return promises.\n *\n * If a callback returns an TargetState, then it is used as arguments to $state.transitionTo() and the result returned.\n *\n * @internalapi\n */\n private _handleInvalidTargetState(fromPath: PathNode[], toState: TargetState) {\n const fromState = PathUtils.makeTargetState(this.router.stateRegistry, fromPath);\n const globals = this.router.globals;\n const latestThing = () => globals.transitionHistory.peekTail();\n const latest = latestThing();\n const callbackQueue = new Queue(this.invalidCallbacks.slice());\n const injector = new ResolveContext(fromPath).injector();\n\n const checkForRedirect = (result: HookResult) => {\n if (!(result instanceof TargetState)) {\n return;\n }\n\n let target = result;\n // Recreate the TargetState, in case the state is now defined.\n target = this.target(target.identifier(), target.params(), target.options());\n\n if (!target.valid()) {\n return Rejection.invalid(target.error()).toPromise();\n }\n\n if (latestThing() !== latest) {\n return Rejection.superseded().toPromise();\n }\n\n return this.transitionTo(target.identifier(), target.params(), target.options());\n };\n\n function invokeNextCallback() {\n const nextCallback = callbackQueue.dequeue();\n if (nextCallback === undefined) return Rejection.invalid(toState.error()).toPromise();\n\n const callbackResult = services.$q.when(nextCallback(toState, fromState, injector));\n return callbackResult.then(checkForRedirect).then(result => result || invokeNextCallback());\n }\n\n return invokeNextCallback();\n }\n\n /**\n * Registers an Invalid State handler\n *\n * Registers a [[OnInvalidCallback]] function to be invoked when [[StateService.transitionTo]]\n * has been called with an invalid state reference parameter\n *\n * Example:\n * ```js\n * stateService.onInvalid(function(to, from, injector) {\n * if (to.name() === 'foo') {\n * let lazyLoader = injector.get('LazyLoadService');\n * return lazyLoader.load('foo')\n * .then(() => stateService.target('foo'));\n * }\n * });\n * ```\n *\n * @param {function} callback invoked when the toState is invalid\n * This function receives the (invalid) toState, the fromState, and an injector.\n * The function may optionally return a [[TargetState]] or a Promise for a TargetState.\n * If one is returned, it is treated as a redirect.\n *\n * @returns a function which deregisters the callback\n */\n onInvalid(callback: OnInvalidCallback): Function {\n this.invalidCallbacks.push(callback);\n return function deregisterListener() {\n removeFrom(this.invalidCallbacks)(callback);\n }.bind(this);\n }\n\n\n /**\n * Reloads the current state\n *\n * A method that force reloads the current state, or a partial state hierarchy.\n * All resolves are re-resolved, and components reinstantiated.\n *\n * #### Example:\n * ```js\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * $state.reload();\n * }\n * });\n * ```\n *\n * Note: `reload()` is just an alias for:\n *\n * ```js\n * $state.transitionTo($state.current, $state.params, {\n * reload: true, inherit: false\n * });\n * ```\n *\n * @param reloadState A state name or a state object.\n * If present, this state and all its children will be reloaded, but ancestors will not reload.\n *\n * #### Example:\n * ```js\n * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'\n * //and current state is 'contacts.detail.item'\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * //will reload 'contact.detail' and nested 'contact.detail.item' states\n * $state.reload('contact.detail');\n * }\n * });\n * ```\n *\n * @returns A promise representing the state of the new transition. See [[StateService.go]]\n */\n reload(reloadState?: StateOrName): Promise {\n return this.transitionTo(this.current, this.params, {\n reload: isDefined(reloadState) ? reloadState : true,\n inherit: false,\n notify: false,\n });\n }\n\n /**\n * Transition to a different state and/or parameters\n *\n * Convenience method for transitioning to a new state.\n *\n * `$state.go` calls `$state.transitionTo` internally but automatically sets options to\n * `{ location: true, inherit: true, relative: router.globals.$current, notify: true }`.\n * This allows you to use either an absolute or relative `to` argument (because of `relative: router.globals.$current`).\n * It also allows you to specify * only the parameters you'd like to update, while letting unspecified parameters\n * inherit from the current parameter values (because of `inherit: true`).\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.go('contact.detail');\n * };\n * });\n * ```\n *\n * @param to Absolute state name, state object, or relative state path (relative to current state).\n *\n * Some examples:\n *\n * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n * - `$state.go('^')` - will go to the parent state\n * - `$state.go('^.sibling')` - if current state is `home.child`, will go to the `home.sibling` state\n * - `$state.go('.child.grandchild')` - if current state is home, will go to the `home.child.grandchild` state\n *\n * @param params A map of the parameters that will be sent to the state, will populate $stateParams.\n *\n * Any parameters that are not specified will be inherited from current parameter values (because of `inherit: true`).\n * This allows, for example, going to a sibling state that shares parameters defined by a parent state.\n *\n * @param options Transition options\n *\n * @returns {promise} A promise representing the state of the new transition.\n */\n go(to: StateOrName, params?: RawParams, options?: TransitionOptions): TransitionPromise {\n const defautGoOpts = { relative: this.$current, inherit: true };\n const transOpts = defaults(options, defautGoOpts, defaultTransOpts);\n return this.transitionTo(to, params, transOpts);\n }\n\n /**\n * Creates a [[TargetState]]\n *\n * This is a factory method for creating a TargetState\n *\n * This may be returned from a Transition Hook to redirect a transition, for example.\n */\n target(identifier: StateOrName, params?: RawParams, options: TransitionOptions = {}): TargetState {\n // If we're reloading, find the state object to reload from\n if (isObject(options.reload) && !(options.reload).name)\n throw new Error('Invalid reload state object');\n const reg = this.router.stateRegistry;\n options.reloadState = options.reload === true ? reg.root() : reg.matcher.find( options.reload, options.relative);\n\n if (options.reload && !options.reloadState)\n throw new Error(`No such reload state '${(isString(options.reload) ? options.reload : (options.reload).name)}'`);\n\n return new TargetState(this.router.stateRegistry, identifier, params, options);\n }\n\n private getCurrentPath(): PathNode[] {\n const globals = this.router.globals;\n const latestSuccess: Transition = globals.successfulTransitions.peekTail();\n const rootPath = () => [ new PathNode(this.router.stateRegistry.root()) ];\n return latestSuccess ? latestSuccess.treeChanges().to : rootPath();\n }\n\n /**\n * Low-level method for transitioning to a new state.\n *\n * The [[go]] method (which uses `transitionTo` internally) is recommended in most situations.\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.transitionTo('contact.detail');\n * };\n * });\n * ```\n *\n * @param to State name or state object.\n * @param toParams A map of the parameters that will be sent to the state,\n * will populate $stateParams.\n * @param options Transition options\n *\n * @returns A promise representing the state of the new transition. See [[go]]\n */\n transitionTo(to: StateOrName, toParams: RawParams = {}, options: TransitionOptions = {}): TransitionPromise {\n const router = this.router;\n const globals = router.globals;\n options = defaults(options, defaultTransOpts);\n const getCurrent = () =>\n globals.transition;\n options = extend(options, { current: getCurrent });\n\n const ref: TargetState = this.target(to, toParams, options);\n const currentPath = this.getCurrentPath();\n\n if (!ref.exists())\n return this._handleInvalidTargetState(currentPath, ref);\n\n if (!ref.valid())\n return silentRejection(ref.error());\n\n /**\n * Special handling for Ignored, Aborted, and Redirected transitions\n *\n * The semantics for the transition.run() promise and the StateService.transitionTo()\n * promise differ. For instance, the run() promise may be rejected because it was\n * IGNORED, but the transitionTo() promise is resolved because from the user perspective\n * no error occurred. Likewise, the transition.run() promise may be rejected because of\n * a Redirect, but the transitionTo() promise is chained to the new Transition's promise.\n */\n const rejectedTransitionHandler = (trans: Transition) => (error: any): Promise => {\n if (error instanceof Rejection) {\n const isLatest = router.globals.lastStartedTransitionId === trans.$id;\n\n if (error.type === RejectType.IGNORED) {\n isLatest && router.urlRouter.update();\n // Consider ignored `Transition.run()` as a successful `transitionTo`\n return services.$q.when(globals.current);\n }\n\n const detail: any = error.detail;\n if (error.type === RejectType.SUPERSEDED && error.redirected && detail instanceof TargetState) {\n // If `Transition.run()` was redirected, allow the `transitionTo()` promise to resolve successfully\n // by returning the promise for the new (redirect) `Transition.run()`.\n const redirect: Transition = trans.redirect(detail);\n return redirect.run().catch(rejectedTransitionHandler(redirect));\n }\n\n if (error.type === RejectType.ABORTED) {\n isLatest && router.urlRouter.update();\n return services.$q.reject(error);\n }\n }\n\n const errorHandler = this.defaultErrorHandler();\n errorHandler(error);\n\n return services.$q.reject(error);\n };\n\n const transition = this.router.transitionService.create(currentPath, ref);\n const transitionToPromise = transition.run().catch(rejectedTransitionHandler(transition));\n silenceUncaughtInPromise(transitionToPromise); // issue #2676\n\n // Return a promise for the transition, which also has the transition object on it.\n return extend(transitionToPromise, { transition });\n }\n\n /**\n * Checks if the current state *is* the provided state\n *\n * Similar to [[includes]] but only checks for the full state name.\n * If params is supplied then it will be tested for strict equality against the current\n * active params object, so all params must match with none missing and no extras.\n *\n * #### Example:\n * ```js\n * $state.$current.name = 'contacts.details.item';\n *\n * // absolute name\n * $state.is('contact.details.item'); // returns true\n * $state.is(contactDetailItemStateObject); // returns true\n * ```\n *\n * // relative name (. and ^), typically from a template\n * // E.g. from the 'contacts.details' template\n * ```html\n *
    Item
    \n * ```\n *\n * @param stateOrName The state name (absolute or relative) or state object you'd like to check.\n * @param params A param object, e.g. `{sectionId: section.id}`, that you'd like\n * to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns Returns true if it is the state.\n */\n is(stateOrName: StateOrName, params?: RawParams, options?: { relative?: StateOrName }): boolean {\n options = defaults(options, { relative: this.$current });\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n if (!isDefined(state)) return undefined;\n if (this.$current !== state) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n /**\n * Checks if the current state *includes* the provided state\n *\n * A method to determine if the current active state is equal to or is the child of the\n * state stateName. If any params are passed then they will be tested for a match as well.\n * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n *\n * #### Example when `$state.$current.name === 'contacts.details.item'`\n * ```js\n * // Using partial names\n * $state.includes(\"contacts\"); // returns true\n * $state.includes(\"contacts.details\"); // returns true\n * $state.includes(\"contacts.details.item\"); // returns true\n * $state.includes(\"contacts.list\"); // returns false\n * $state.includes(\"about\"); // returns false\n * ```\n *\n * #### Glob Examples when `* $state.$current.name === 'contacts.details.item.url'`:\n * ```js\n * $state.includes(\"*.details.*.*\"); // returns true\n * $state.includes(\"*.details.**\"); // returns true\n * $state.includes(\"**.item.**\"); // returns true\n * $state.includes(\"*.details.item.url\"); // returns true\n * $state.includes(\"*.details.*.url\"); // returns true\n * $state.includes(\"*.details.*\"); // returns false\n * $state.includes(\"item.**\"); // returns false\n * ```\n *\n * @param stateOrName A partial name, relative name, glob pattern,\n * or state object to be searched for within the current state name.\n * @param params A param object, e.g. `{sectionId: section.id}`,\n * that you'd like to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns {boolean} Returns true if it does include the state\n */\n includes(stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions): boolean {\n options = defaults(options, { relative: this.$current });\n const glob = isString(stateOrName) && Glob.fromString( stateOrName);\n\n if (glob) {\n if (!glob.matches(this.$current.name)) return false;\n stateOrName = this.$current.name;\n }\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative), include = this.$current.includes;\n\n if (!isDefined(state)) return undefined;\n if (!isDefined(include[state.name])) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n\n /**\n * Generates a URL for a state and parameters\n *\n * Returns the url for the given state populated with the given params.\n *\n * #### Example:\n * ```js\n * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n * ```\n *\n * @param stateOrName The state name or state object you'd like to generate a url from.\n * @param params An object of parameter values to fill the state's required parameters.\n * @param options Options object. The options are:\n *\n * @returns {string} compiled state url\n */\n href(stateOrName: StateOrName, params: RawParams, options?: HrefOptions): string {\n const defaultHrefOpts = {\n lossy: true,\n inherit: true,\n absolute: false,\n relative: this.$current,\n };\n options = defaults(options, defaultHrefOpts);\n params = params || {};\n\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n\n if (!isDefined(state)) return null;\n if (options.inherit) params = this.params.$inherit(params, this.$current, state);\n\n const nav = (state && options.lossy) ? state.navigable : state;\n\n if (!nav || nav.url === undefined || nav.url === null) {\n return null;\n }\n return this.router.urlRouter.href(nav.url, params, {\n absolute: options.absolute,\n });\n }\n\n /** @hidden */\n private _defaultErrorHandler: ((_error: any) => void) = function $defaultErrorHandler($error$) {\n if ($error$ instanceof Error && $error$.stack) {\n console.error($error$);\n console.error($error$.stack);\n } else if ($error$ instanceof Rejection) {\n console.error($error$.toString());\n if ($error$.detail && $error$.detail.stack)\n console.error($error$.detail.stack);\n } else {\n console.error($error$);\n }\n };\n\n /**\n * Sets or gets the default [[transitionTo]] error handler.\n *\n * The error handler is called when a [[Transition]] is rejected or when any error occurred during the Transition.\n * This includes errors caused by resolves and transition hooks.\n *\n * Note:\n * This handler does not receive certain Transition rejections.\n * Redirected and Ignored Transitions are not considered to be errors by [[StateService.transitionTo]].\n *\n * The built-in default error handler logs the error to the console.\n *\n * You can provide your own custom handler.\n *\n * #### Example:\n * ```js\n * stateService.defaultErrorHandler(function() {\n * // Do not log transitionTo errors\n * });\n * ```\n *\n * @param handler a global error handler function\n * @returns the current global error handler\n */\n defaultErrorHandler(handler?: (error: any) => void): (error: any) => void {\n return this._defaultErrorHandler = handler || this._defaultErrorHandler;\n }\n\n /**\n * Gets a registered [[StateDeclaration]] object\n *\n * Returns the state declaration object for any specific state, or for all registered states.\n *\n * @param stateOrName (absolute or relative) If provided, will only get the declaration object for the requested state.\n * If not provided, returns an array of ALL states.\n * @param base When `stateOrName` is a relative state reference (such as `.bar.baz`), the state will be retrieved relative to this state.\n *\n * @returns a [[StateDeclaration]] object (or array of all registered [[StateDeclaration]] objects.)\n */\n get(stateOrName: StateOrName, base: StateOrName): StateDeclaration;\n get(stateOrName: StateOrName): StateDeclaration;\n get(): StateDeclaration[];\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n const reg = this.router.stateRegistry;\n if (arguments.length === 0) return reg.get();\n return reg.get(stateOrName, base || this.$current);\n }\n\n /**\n * Lazy loads a state\n *\n * Explicitly runs a state's [[StateDeclaration.lazyLoad]] function.\n *\n * @param stateOrName the state that should be lazy loaded\n * @param transition the optional Transition context to use (if the lazyLoad function requires an injector, etc)\n * Note: If no transition is provided, a noop transition is created using the from the current state to the current state.\n * This noop transition is not actually run.\n *\n * @returns a promise to lazy load\n */\n lazyLoad(stateOrName: StateOrName, transition?: Transition): Promise {\n const state: StateDeclaration = this.get(stateOrName);\n if (!state || !state.lazyLoad) throw new Error('Can not lazy load ' + stateOrName);\n\n const currentPath = this.getCurrentPath();\n const target = PathUtils.makeTargetState(this.router.stateRegistry, currentPath);\n transition = transition || this.router.transitionService.create(currentPath, target);\n\n return lazyLoadState(transition, state);\n }\n}\n", - "/**\n * # Transition subsystem\n *\n * This module contains APIs related to a Transition.\n *\n * See:\n * - [[TransitionService]]\n * - [[Transition]]\n * - [[HookFn]], [[TransitionHookFn]], [[TransitionStateHookFn]], [[HookMatchCriteria]], [[HookResult]]\n *\n * @coreapi\n * @preferred\n * @module transition\n */ /** for typedoc */\nexport * from './interface';\nexport * from './hookBuilder';\nexport * from './hookRegistry';\nexport * from './rejectFactory';\nexport * from './transition';\nexport * from './transitionHook';\nexport * from './transitionEventType';\nexport * from './transitionService';\n\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isArray, isObject, $QLike } from '../common/index';\n\n/**\n * An angular1-like promise api\n *\n * This object implements four methods similar to the\n * [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This API provides native ES6 promise support wrapped as a $q-like API.\n * Internally, UI-Router uses this $q object to perform promise operations.\n * The `angular-ui-router` (ui-router for angular 1) uses the $q API provided by angular.\n *\n * $q-like promise api\n */\nexport const $q = {\n /** Normalizes a value as a promise */\n when: (val) => new Promise((resolve, reject) => resolve(val)),\n\n /** Normalizes a value as a promise rejection */\n reject: (val) => new Promise((resolve, reject) => { reject(val); }),\n\n /** @returns a deferred object, which has `resolve` and `reject` functions */\n defer: () => {\n const deferred: any = {};\n deferred.promise = new Promise((resolve, reject) => {\n deferred.resolve = resolve;\n deferred.reject = reject;\n });\n return deferred;\n },\n\n /** Like Promise.all(), but also supports object key/promise notation like $q */\n all: (promises: { [key: string]: Promise } | Promise[]) => {\n if (isArray(promises)) {\n return Promise.all(promises);\n }\n\n if (isObject(promises)) {\n // Convert promises map to promises array.\n // When each promise resolves, map it to a tuple { key: key, val: val }\n const chain = Object.keys(promises)\n .map(key => promises[key].then(val => ({ key, val })));\n\n // Then wait for all promises to resolve, and convert them back to an object\n return $q.all(chain).then(values =>\n values.reduce((acc, tuple) => { acc[tuple.key] = tuple.val; return acc; }, {}));\n }\n },\n} as $QLike;\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n extend, assertPredicate, isFunction, isArray, isInjectable, $InjectorLike, IInjectable,\n} from '../common/index';\n\n// globally available injectables\nconst globals = {};\nconst STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nconst ARGUMENT_NAMES = /([^\\s,]+)/g;\n\n/**\n * A basic angular1-like injector api\n *\n * This object implements four methods similar to the\n * [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This object provides a naive implementation of a globally scoped dependency injection system.\n * It supports the following DI approaches:\n *\n * ### Function parameter names\n *\n * A function's `.toString()` is called, and the parameter names are parsed.\n * This only works when the parameter names aren't \"mangled\" by a minifier such as UglifyJS.\n *\n * ```js\n * function injectedFunction(FooService, BarService) {\n * // FooService and BarService are injected\n * }\n * ```\n *\n * ### Function annotation\n *\n * A function may be annotated with an array of dependency names as the `$inject` property.\n *\n * ```js\n * injectedFunction.$inject = [ 'FooService', 'BarService' ];\n * function injectedFunction(fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }\n * ```\n *\n * ### Array notation\n *\n * An array provides the names of the dependencies to inject (as strings).\n * The function is the last element of the array.\n *\n * ```js\n * [ 'FooService', 'BarService', function (fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }]\n * ```\n *\n * @type {$InjectorLike}\n */\nexport const $injector = {\n /** Gets an object from DI based on a string token */\n get: name => globals[name],\n\n /** Returns true if an object named `name` exists in global DI */\n has: (name) => $injector.get(name) != null,\n\n /**\n * Injects a function\n *\n * @param fn the function to inject\n * @param context the function's `this` binding\n * @param locals An object with additional DI tokens and values, such as `{ someToken: { foo: 1 } }`\n */\n invoke: (fn: IInjectable, context?, locals?) => {\n const all = extend({}, globals, locals || {});\n const params = $injector.annotate(fn);\n const ensureExist = assertPredicate((key: string) => all.hasOwnProperty(key), key => `DI can't find injectable: '${key}'`);\n const args = params.filter(ensureExist).map(x => all[x]);\n if (isFunction(fn)) return fn.apply(context, args);\n else return (fn as any[]).slice(-1)[0].apply(context, args);\n },\n\n /**\n * Returns a function's dependencies\n *\n * Analyzes a function (or array) and returns an array of DI tokens that the function requires.\n * @return an array of `string`s\n */\n annotate: (fn: IInjectable): any[] => {\n if (!isInjectable(fn)) throw new Error(`Not an injectable function: ${fn}`);\n if (fn && (fn as any).$inject) return (fn as any).$inject;\n if (isArray(fn)) return fn.slice(0, -1);\n const fnStr = fn.toString().replace(STRIP_COMMENTS, '');\n const result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);\n return result || [];\n },\n} as $InjectorLike;\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n LocationConfig, LocationServices, identity, unnestR, isArray, splitEqual, splitHash, splitQuery,\n} from '../common';\nimport { UIRouter } from '../router';\n\nexport const keyValsToObjectR = (accum, [key, val]) => {\n if (!accum.hasOwnProperty(key)) {\n accum[key] = val;\n } else if (isArray(accum[key])) {\n accum[key].push(val);\n } else {\n accum[key] = [accum[key], val];\n }\n return accum;\n};\n\nexport const getParams = (queryString: string): any =>\n queryString.split('&').filter(identity).map(splitEqual).reduce(keyValsToObjectR, {});\n\nexport function parseUrl(url: string) {\n const orEmptyString = x => x || '';\n const [beforehash, hash] = splitHash(url).map(orEmptyString);\n const [path, search] = splitQuery(beforehash).map(orEmptyString);\n\n return { path, search, hash, url };\n}\n\nexport const buildUrl = (loc: LocationServices) => {\n const path = loc.path();\n const searchObject = loc.search();\n const hash = loc.hash();\n\n const search = Object.keys(searchObject).map(key => {\n const param = searchObject[key];\n const vals = isArray(param) ? param : [param];\n return vals.map(val => key + '=' + val);\n }).reduce(unnestR, []).join('&');\n\n return path + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n};\n\nexport function locationPluginFactory(\n name: string,\n isHtml5: boolean,\n serviceClass: { new(uiRouter?: UIRouter): LocationServices },\n configurationClass: { new(uiRouter?: UIRouter, isHtml5?: boolean): LocationConfig },\n) {\n return function(uiRouter: UIRouter) {\n const service = uiRouter.locationService = new serviceClass(uiRouter);\n const configuration = uiRouter.locationConfig = new configurationClass(uiRouter, isHtml5);\n\n function dispose(router: UIRouter) {\n router.dispose(service);\n router.dispose(configuration);\n }\n\n return { name, service, configuration, dispose };\n };\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */ /** */\n\nimport { deregAll, isDefined, LocationServices, removeFrom, root } from '../common';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { HistoryLike, LocationLike } from './interface';\nimport { buildUrl, getParams, parseUrl } from './utils';\n\n/** A base `LocationServices` */\nexport abstract class BaseLocationServices implements LocationServices, Disposable {\n private _listeners: Function[] = [];\n _location: LocationLike;\n _history: HistoryLike;\n\n _listener = evt => this._listeners.forEach(cb => cb(evt));\n\n constructor(router: UIRouter, public fireAfterUpdate: boolean) {\n this._location = root.location;\n this._history = root.history;\n }\n\n /**\n * This should return the current internal URL representation.\n *\n * The internal URL includes only the portion that UI-Router matches.\n * It does not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n */\n protected abstract _get(): string;\n\n /**\n * This should set the current URL.\n *\n * The `url` param should include only the portion that UI-Router matches on.\n * It should not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n *\n * However, after this function completes, the browser URL should reflect the entire (fully qualified)\n * HREF including those data.\n */\n protected abstract _set(state: any, title: string, url: string, replace: boolean);\n\n hash = () => parseUrl(this._get()).hash;\n path = () => parseUrl(this._get()).path;\n search = () => getParams(parseUrl(this._get()).search);\n\n url(url?: string, replace = true): string {\n if (isDefined(url) && url !== this._get()) {\n this._set(null, null, url, replace);\n\n if (this.fireAfterUpdate) {\n this._listeners.forEach(cb => cb({ url }));\n }\n }\n\n return buildUrl(this);\n }\n\n onChange(cb: EventListener) {\n this._listeners.push(cb);\n return () => removeFrom(this._listeners, cb);\n }\n\n dispose(router: UIRouter) {\n deregAll(this._listeners);\n }\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { root, trimHashVal } from '../common';\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\n\n/** A `LocationServices` that uses the browser hash \"#\" to get/set the current location */\nexport class HashLocationService extends BaseLocationServices {\n constructor(router: UIRouter) {\n super(router, false);\n root.addEventListener('hashchange', this._listener, false);\n }\n\n _get() {\n return trimHashVal(this._location.hash);\n }\n _set(state: any, title: string, url: string, replace: boolean) {\n this._location.hash = url;\n }\n\n dispose (router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('hashchange', this._listener);\n }\n}\n\n", + "/**\n * @coreapi\n * @module url\n */ /** */\n\nimport { UIRouter } from '../router';\nimport { LocationServices, notImplemented, LocationConfig } from '../common/coreservices';\nimport { noop, createProxyFunctions } from '../common/common';\nimport { UrlConfigApi, UrlSyncApi, UrlRulesApi, UrlParts, MatchResult } from './interface';\n\n/** @hidden */\nconst makeStub = (keys: string[]): any =>\n keys.reduce((acc, key) => ((acc[key] = notImplemented(key)), acc), { dispose: noop });\n\n/** @hidden */\nconst locationServicesFns = ['url', 'path', 'search', 'hash', 'onChange'];\n/** @hidden */\nconst locationConfigFns = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix'];\n/** @hidden */\nconst umfFns = ['type', 'caseInsensitive', 'strictMode', 'defaultSquashPolicy'];\n/** @hidden */\nconst rulesFns = ['sort', 'when', 'initial', 'otherwise', 'rules', 'rule', 'removeRule'];\n/** @hidden */\nconst syncFns = ['deferIntercept', 'listen', 'sync', 'match'];\n\n/**\n * API for URL management\n */\nexport class UrlService implements LocationServices, UrlSyncApi {\n /** @hidden */\n static locationServiceStub: LocationServices = makeStub(locationServicesFns);\n /** @hidden */\n static locationConfigStub: LocationConfig = makeStub(locationConfigFns);\n\n /**\n * A nested API for managing URL rules and rewrites\n *\n * See: [[UrlRulesApi]] for details\n */\n rules: UrlRulesApi;\n\n /**\n * A nested API to configure the URL and retrieve URL information\n *\n * See: [[UrlConfigApi]] for details\n */\n config: UrlConfigApi;\n\n /** @hidden */\n private router: UIRouter;\n\n /** @hidden */\n constructor(router: UIRouter, lateBind = true) {\n this.router = router;\n this.rules = {} as any;\n this.config = {} as any;\n\n // proxy function calls from UrlService to the LocationService/LocationConfig\n const locationServices = () => router.locationService;\n createProxyFunctions(locationServices, this, locationServices, locationServicesFns, lateBind);\n\n const locationConfig = () => router.locationConfig;\n createProxyFunctions(locationConfig, this.config, locationConfig, locationConfigFns, lateBind);\n\n const umf = () => router.urlMatcherFactory;\n createProxyFunctions(umf, this.config, umf, umfFns);\n\n const urlRouter = () => router.urlRouter;\n createProxyFunctions(urlRouter, this.rules, urlRouter, rulesFns);\n createProxyFunctions(urlRouter, this, urlRouter, syncFns);\n }\n\n /** @inheritdoc */\n url(): string;\n /** @inheritdoc */\n url(newurl: string, replace?: boolean, state?): void;\n url(newurl?, replace?, state?): any {\n return;\n }\n /** @inheritdoc */\n path(): string {\n return;\n }\n /** @inheritdoc */\n search(): { [key: string]: any } {\n return;\n }\n /** @inheritdoc */\n hash(): string {\n return;\n }\n /** @inheritdoc */\n onChange(callback: Function): Function {\n return;\n }\n\n /**\n * Returns the current URL parts\n *\n * This method returns the current URL components as a [[UrlParts]] object.\n *\n * @returns the current url parts\n */\n parts(): UrlParts {\n return { path: this.path(), search: this.search(), hash: this.hash() };\n }\n\n dispose() {}\n\n /** @inheritdoc */\n sync(evt?) {\n return;\n }\n /** @inheritdoc */\n listen(enabled?: boolean): Function {\n return;\n }\n /** @inheritdoc */\n deferIntercept(defer?: boolean) {\n return;\n }\n /** @inheritdoc */\n match(urlParts: UrlParts): MatchResult {\n return;\n }\n}\n", + "/**\n * @coreapi\n * @module core\n */ /** */\nimport { UrlMatcherFactory } from './url/urlMatcherFactory';\nimport { UrlRouter } from './url/urlRouter';\nimport { TransitionService } from './transition/transitionService';\nimport { ViewService } from './view/view';\nimport { StateRegistry } from './state/stateRegistry';\nimport { StateService } from './state/stateService';\nimport { UIRouterGlobals } from './globals';\nimport { UIRouterPlugin, Disposable } from './interface';\nimport { values, removeFrom } from './common/common';\nimport { isFunction } from './common/predicates';\nimport { UrlService } from './url/urlService';\nimport { LocationServices, LocationConfig } from './common/coreservices';\nimport { Trace, trace } from './common/trace';\n\n/** @hidden */\nlet _routerInstance = 0;\n\n/**\n * The master class used to instantiate an instance of UI-Router.\n *\n * UI-Router (for each specific framework) will create an instance of this class during bootstrap.\n * This class instantiates and wires the UI-Router services together.\n *\n * After a new instance of the UIRouter class is created, it should be configured for your app.\n * For instance, app states should be registered with the [[UIRouter.stateRegistry]].\n *\n * ---\n *\n * Normally the framework code will bootstrap UI-Router.\n * If you are bootstrapping UIRouter manually, tell it to monitor the URL by calling\n * [[UrlService.listen]] then [[UrlService.sync]].\n */\nexport class UIRouter {\n /** @hidden */ $id = _routerInstance++;\n /** @hidden */ _disposed = false;\n /** @hidden */ private _disposables: Disposable[] = [];\n\n /** Provides trace information to the console */\n trace: Trace = trace;\n\n /** Provides services related to ui-view synchronization */\n viewService = new ViewService();\n\n /** Global router state */\n globals: UIRouterGlobals = new UIRouterGlobals();\n\n /** Provides services related to Transitions */\n transitionService: TransitionService = new TransitionService(this);\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlMatcherFactory: UrlMatcherFactory = new UrlMatcherFactory();\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlRouter: UrlRouter = new UrlRouter(this);\n\n /** Provides a registry for states, and related registration services */\n stateRegistry: StateRegistry = new StateRegistry(this);\n\n /** Provides services related to states */\n stateService = new StateService(this);\n\n /** Provides services related to the URL */\n urlService: UrlService = new UrlService(this);\n\n /** @hidden plugin instances are registered here */\n private _plugins: { [key: string]: UIRouterPlugin } = {};\n\n /** Registers an object to be notified when the router is disposed */\n disposable(disposable: Disposable) {\n this._disposables.push(disposable);\n }\n\n /**\n * Disposes this router instance\n *\n * When called, clears resources retained by the router by calling `dispose(this)` on all\n * registered [[disposable]] objects.\n *\n * Or, if a `disposable` object is provided, calls `dispose(this)` on that object only.\n *\n * @param disposable (optional) the disposable to dispose\n */\n dispose(disposable?: any): void {\n if (disposable && isFunction(disposable.dispose)) {\n disposable.dispose(this);\n return undefined;\n }\n\n this._disposed = true;\n this._disposables.slice().forEach(d => {\n try {\n typeof d.dispose === 'function' && d.dispose(this);\n removeFrom(this._disposables, d);\n } catch (ignored) {}\n });\n }\n\n /**\n * Creates a new `UIRouter` object\n *\n * @param locationService a [[LocationServices]] implementation\n * @param locationConfig a [[LocationConfig]] implementation\n * @internalapi\n */\n constructor(\n public locationService: LocationServices = UrlService.locationServiceStub,\n public locationConfig: LocationConfig = UrlService.locationConfigStub,\n ) {\n this.viewService._pluginapi._rootViewContext(this.stateRegistry.root());\n this.globals.$current = this.stateRegistry.root();\n this.globals.current = this.globals.$current.self;\n\n this.disposable(this.globals);\n this.disposable(this.stateService);\n this.disposable(this.stateRegistry);\n this.disposable(this.transitionService);\n this.disposable(this.urlRouter);\n this.disposable(locationService);\n this.disposable(locationConfig);\n }\n\n /** Add plugin (as ES6 class) */\n plugin(plugin: { new (router: UIRouter, options?: any): T }, options?: any): T;\n /** Add plugin (as javascript constructor function) */\n plugin(plugin: { (router: UIRouter, options?: any): void }, options?: any): T;\n /** Add plugin (as javascript factory function) */\n plugin(plugin: PluginFactory, options?: any): T;\n /**\n * Adds a plugin to UI-Router\n *\n * This method adds a UI-Router Plugin.\n * A plugin can enhance or change UI-Router behavior using any public API.\n *\n * #### Example:\n * ```js\n * import { MyCoolPlugin } from \"ui-router-cool-plugin\";\n *\n * var plugin = router.addPlugin(MyCoolPlugin);\n * ```\n *\n * ### Plugin authoring\n *\n * A plugin is simply a class (or constructor function) which accepts a [[UIRouter]] instance and (optionally) an options object.\n *\n * The plugin can implement its functionality using any of the public APIs of [[UIRouter]].\n * For example, it may configure router options or add a Transition Hook.\n *\n * The plugin can then be published as a separate module.\n *\n * #### Example:\n * ```js\n * export class MyAuthPlugin implements UIRouterPlugin {\n * constructor(router: UIRouter, options: any) {\n * this.name = \"MyAuthPlugin\";\n * let $transitions = router.transitionService;\n * let $state = router.stateService;\n *\n * let authCriteria = {\n * to: (state) => state.data && state.data.requiresAuth\n * };\n *\n * function authHook(transition: Transition) {\n * let authService = transition.injector().get('AuthService');\n * if (!authService.isAuthenticated()) {\n * return $state.target('login');\n * }\n * }\n *\n * $transitions.onStart(authCriteria, authHook);\n * }\n * }\n * ```\n *\n * @param plugin one of:\n * - a plugin class which implements [[UIRouterPlugin]]\n * - a constructor function for a [[UIRouterPlugin]] which accepts a [[UIRouter]] instance\n * - a factory function which accepts a [[UIRouter]] instance and returns a [[UIRouterPlugin]] instance\n * @param options options to pass to the plugin class/factory\n * @returns the registered plugin instance\n */\n plugin(plugin: any, options: any = {}): T {\n const pluginInstance = new plugin(this, options);\n if (!pluginInstance.name) throw new Error('Required property `name` missing on plugin: ' + pluginInstance);\n this._disposables.push(pluginInstance);\n return (this._plugins[pluginInstance.name] = pluginInstance);\n }\n\n /**\n * Returns registered plugins\n *\n * Returns the registered plugin of the given `pluginName`.\n * If no `pluginName` is given, returns all registered plugins\n *\n * @param pluginName (optional) the name of the plugin to get\n * @return the named plugin (undefined if not found), or all plugins (if `pluginName` is omitted)\n */\n getPlugin(pluginName: string): UIRouterPlugin;\n getPlugin(): UIRouterPlugin[];\n getPlugin(pluginName?: string): UIRouterPlugin | UIRouterPlugin[] {\n return pluginName ? this._plugins[pluginName] : values(this._plugins);\n }\n}\n\n/** @internalapi */\nexport type PluginFactory = (router: UIRouter, options?: any) => T;\n", + "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { UIRouter } from '../router';\nimport { TransitionService } from '../transition/transitionService';\nimport { Resolvable } from '../resolve';\nimport { extend, inArray, map, mapObj, uniqR, unnestR, values } from '../common';\nimport { PathNode } from '../path';\nimport { TreeChanges } from '../transition';\n\nfunction addCoreResolvables(trans: Transition) {\n trans.addResolvable(Resolvable.fromData(UIRouter, trans.router), '');\n trans.addResolvable(Resolvable.fromData(Transition, trans), '');\n trans.addResolvable(Resolvable.fromData('$transition$', trans), '');\n trans.addResolvable(Resolvable.fromData('$stateParams', trans.params()), '');\n\n trans.entering().forEach(state => {\n trans.addResolvable(Resolvable.fromData('$state$', state), state);\n });\n}\n\nexport const registerAddCoreResolvables = (transitionService: TransitionService) =>\n transitionService.onCreate({}, addCoreResolvables);\n\nconst TRANSITION_TOKENS = ['$transition$', Transition];\nconst isTransition = inArray(TRANSITION_TOKENS);\n\n// References to Transition in the treeChanges pathnodes makes all\n// previous Transitions reachable in memory, causing a memory leak\n// This function removes resolves for '$transition$' and `Transition` from the treeChanges.\n// Do not use this on current transitions, only on old ones.\nexport const treeChangesCleanup = (trans: Transition) => {\n const nodes = values(trans.treeChanges())\n .reduce(unnestR, [])\n .reduce(uniqR, []);\n\n // If the resolvable is a Transition, return a new resolvable with null data\n const replaceTransitionWithNull = (r: Resolvable): Resolvable => {\n return isTransition(r.token) ? Resolvable.fromData(r.token, null) : r;\n };\n\n nodes.forEach((node: PathNode) => {\n node.resolvables = node.resolvables.map(replaceTransitionWithNull);\n });\n};\n", + "/** @module hooks */ /** */\nimport { isString, isFunction } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { services } from '../common/coreservices';\nimport { TargetState } from '../state/targetState';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\n\n/**\n * A [[TransitionHookFn]] that redirects to a different state or params\n *\n * Registered using `transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectHook);`\n *\n * See [[StateDeclaration.redirectTo]]\n */\nconst redirectToHook: TransitionHookFn = (trans: Transition) => {\n const redirect = trans.to().redirectTo;\n if (!redirect) return;\n\n const $state = trans.router.stateService;\n\n function handleResult(result: any) {\n if (!result) return;\n if (result instanceof TargetState) return result;\n if (isString(result)) return $state.target(result, trans.params(), trans.options());\n if (result['state'] || result['params'])\n return $state.target(result['state'] || trans.to(), result['params'] || trans.params(), trans.options());\n }\n\n if (isFunction(redirect)) {\n return services.$q.when(redirect(trans)).then(handleResult);\n }\n return handleResult(redirect);\n};\n\nexport const registerRedirectToHook = (transitionService: TransitionService) =>\n transitionService.onStart({ to: state => !!state.redirectTo }, redirectToHook);\n", + "/** @module hooks */\n/** for typedoc */\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { StateDeclaration } from '../state/interface';\nimport { StateObject } from '../state/stateObject';\n\n/**\n * A factory which creates an onEnter, onExit or onRetain transition hook function\n *\n * The returned function invokes the (for instance) state.onEnter hook when the\n * state is being entered.\n *\n * @hidden\n */\nfunction makeEnterExitRetainHook(hookName: string): TransitionStateHookFn {\n return (transition: Transition, state: StateDeclaration) => {\n const _state: StateObject = state.$$state();\n const hookFn: TransitionStateHookFn = _state[hookName];\n return hookFn(transition, state);\n };\n}\n\n/**\n * The [[TransitionStateHookFn]] for onExit\n *\n * When the state is being exited, the state's .onExit function is invoked.\n *\n * Registered using `transitionService.onExit({ exiting: (state) => !!state.onExit }, onExitHook);`\n *\n * See: [[IHookRegistry.onExit]]\n */\nconst onExitHook: TransitionStateHookFn = makeEnterExitRetainHook('onExit');\nexport const registerOnExitHook = (transitionService: TransitionService) =>\n transitionService.onExit({ exiting: state => !!state.onExit }, onExitHook);\n\n/**\n * The [[TransitionStateHookFn]] for onRetain\n *\n * When the state was already entered, and is not being exited or re-entered, the state's .onRetain function is invoked.\n *\n * Registered using `transitionService.onRetain({ retained: (state) => !!state.onRetain }, onRetainHook);`\n *\n * See: [[IHookRegistry.onRetain]]\n */\nconst onRetainHook: TransitionStateHookFn = makeEnterExitRetainHook('onRetain');\nexport const registerOnRetainHook = (transitionService: TransitionService) =>\n transitionService.onRetain({ retained: state => !!state.onRetain }, onRetainHook);\n\n/**\n * The [[TransitionStateHookFn]] for onEnter\n *\n * When the state is being entered, the state's .onEnter function is invoked.\n *\n * Registered using `transitionService.onEnter({ entering: (state) => !!state.onEnter }, onEnterHook);`\n *\n * See: [[IHookRegistry.onEnter]]\n */\nconst onEnterHook: TransitionStateHookFn = makeEnterExitRetainHook('onEnter');\nexport const registerOnEnterHook = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: state => !!state.onEnter }, onEnterHook);\n", + "/** @module hooks */\n/** for typedoc */\nimport { noop } from '../common/common';\nimport { Transition } from '../transition/transition';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { TransitionStateHookFn, TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\nimport { val } from '../common/hof';\nimport { StateDeclaration } from '../state/interface';\n\nexport const RESOLVE_HOOK_PRIORITY = 1000;\n\n/**\n * A [[TransitionHookFn]] which resolves all EAGER Resolvables in the To Path\n *\n * Registered using `transitionService.onStart({}, eagerResolvePath, { priority: 1000 });`\n *\n * When a Transition starts, this hook resolves all the EAGER Resolvables, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst eagerResolvePath: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to).resolvePath('EAGER', trans).then(noop);\n\nexport const registerEagerResolvePath = (transitionService: TransitionService) =>\n transitionService.onStart({}, eagerResolvePath, { priority: RESOLVE_HOOK_PRIORITY });\n\n/**\n * A [[TransitionHookFn]] which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path\n *\n * Registered using `transitionService.onEnter({ entering: () => true }, lazyResolveState, { priority: 1000 });`\n *\n * When a State is being entered, this hook resolves all the Resolvables for this state, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst lazyResolveState: TransitionStateHookFn = (trans: Transition, state: StateDeclaration) =>\n new ResolveContext(trans.treeChanges().to)\n .subContext(state.$$state())\n .resolvePath('LAZY', trans)\n .then(noop);\n\nexport const registerLazyResolveState = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: val(true) }, lazyResolveState, { priority: RESOLVE_HOOK_PRIORITY });\n\n/**\n * A [[TransitionHookFn]] which resolves any dynamically added (LAZY or EAGER) Resolvables.\n *\n * Registered using `transitionService.onFinish({}, eagerResolvePath, { priority: 1000 });`\n *\n * After all entering states have been entered, this hook resolves any remaining Resolvables.\n * These are typically dynamic resolves which were added by some Transition Hook using [[Transition.addResolvable]].\n *\n * See [[StateDeclaration.resolve]]\n */\nconst resolveRemaining: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to).resolvePath('LAZY', trans).then(noop);\n\nexport const registerResolveRemaining = (transitionService: TransitionService) =>\n transitionService.onFinish({}, resolveRemaining, { priority: RESOLVE_HOOK_PRIORITY });\n", + "/** @module hooks */ /** for typedoc */\nimport { noop } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { Transition } from '../transition/transition';\nimport { ViewService } from '../view/view';\nimport { ViewConfig } from '../view/interface';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which waits for the views to load\n *\n * Registered using `transitionService.onStart({}, loadEnteringViews);`\n *\n * Allows the views to do async work in [[ViewConfig.load]] before the transition continues.\n * In angular 1, this includes loading the templates.\n */\nconst loadEnteringViews: TransitionHookFn = (transition: Transition) => {\n const $q = services.$q;\n const enteringViews = transition.views('entering');\n if (!enteringViews.length) return;\n return $q.all(enteringViews.map(view => $q.when(view.load()))).then(noop);\n};\n\nexport const registerLoadEnteringViews = (transitionService: TransitionService) =>\n transitionService.onFinish({}, loadEnteringViews);\n\n/**\n * A [[TransitionHookFn]] which activates the new views when a transition is successful.\n *\n * Registered using `transitionService.onSuccess({}, activateViews);`\n *\n * After a transition is complete, this hook deactivates the old views from the previous state,\n * and activates the new views from the destination state.\n *\n * See [[ViewService]]\n */\nconst activateViews: TransitionHookFn = (transition: Transition) => {\n const enteringViews = transition.views('entering');\n const exitingViews = transition.views('exiting');\n if (!enteringViews.length && !exitingViews.length) return;\n\n const $view: ViewService = transition.router.viewService;\n\n exitingViews.forEach((vc: ViewConfig) => $view.deactivateViewConfig(vc));\n enteringViews.forEach((vc: ViewConfig) => $view.activateViewConfig(vc));\n\n $view.sync();\n};\n\nexport const registerActivateViews = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, activateViews);\n", + "/** @module hooks */\n/** for typedoc */\nimport { Transition } from '../transition/transition';\nimport { copy } from '../common/common';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates global UI-Router state\n *\n * Registered using `transitionService.onBefore({}, updateGlobalState);`\n *\n * Before a [[Transition]] starts, updates the global value of \"the current transition\" ([[Globals.transition]]).\n * After a successful [[Transition]], updates the global values of \"the current state\"\n * ([[Globals.current]] and [[Globals.$current]]) and \"the current param values\" ([[Globals.params]]).\n *\n * See also the deprecated properties:\n * [[StateService.transition]], [[StateService.current]], [[StateService.params]]\n */\nconst updateGlobalState = (trans: Transition) => {\n const globals = trans.router.globals;\n\n const transitionSuccessful = () => {\n globals.successfulTransitions.enqueue(trans);\n globals.$current = trans.$to();\n globals.current = globals.$current.self;\n\n copy(trans.params(), globals.params);\n };\n\n const clearCurrentTransition = () => {\n // Do not clear globals.transition if a different transition has started in the meantime\n if (globals.transition === trans) globals.transition = null;\n };\n\n trans.onSuccess({}, transitionSuccessful, { priority: 10000 });\n trans.promise.then(clearCurrentTransition, clearCurrentTransition);\n};\n\nexport const registerUpdateGlobalState = (transitionService: TransitionService) =>\n transitionService.onCreate({}, updateGlobalState);\n", + "/** @module hooks */ /** */\nimport { UrlRouter } from '../url/urlRouter';\nimport { StateService } from '../state/stateService';\nimport { Transition } from '../transition/transition';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates the URL after a successful transition\n *\n * Registered using `transitionService.onSuccess({}, updateUrl);`\n */\nconst updateUrl: TransitionHookFn = (transition: Transition) => {\n const options = transition.options();\n const $state: StateService = transition.router.stateService;\n const $urlRouter: UrlRouter = transition.router.urlRouter;\n\n // Dont update the url in these situations:\n // The transition was triggered by a URL sync (options.source === 'url')\n // The user doesn't want the url to update (options.location === false)\n // The destination state, and all parents have no navigable url\n if (options.source !== 'url' && options.location && $state.$current.navigable) {\n const urlOptions = { replace: options.location === 'replace' };\n $urlRouter.push($state.$current.navigable.url, $state.params, urlOptions);\n }\n\n $urlRouter.update(true);\n};\n\nexport const registerUpdateUrl = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, updateUrl, { priority: 9999 });\n", + "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\nimport { StateDeclaration, LazyLoadResult } from '../state/interface';\nimport { services } from '../common/coreservices';\nimport { StateRule } from '../url/interface';\n\n/**\n * A [[TransitionHookFn]] that performs lazy loading\n *\n * When entering a state \"abc\" which has a `lazyLoad` function defined:\n * - Invoke the `lazyLoad` function (unless it is already in process)\n * - Flag the hook function as \"in process\"\n * - The function should return a promise (that resolves when lazy loading is complete)\n * - Wait for the promise to settle\n * - If the promise resolves to a [[LazyLoadResult]], then register those states\n * - Flag the hook function as \"not in process\"\n * - If the hook was successful\n * - Remove the `lazyLoad` function from the state declaration\n * - If all the hooks were successful\n * - Retry the transition (by returning a TargetState)\n *\n * ```\n * .state('abc', {\n * component: 'fooComponent',\n * lazyLoad: () => System.import('./fooComponent')\n * });\n * ```\n *\n * See [[StateDeclaration.lazyLoad]]\n */\nconst lazyLoadHook: TransitionHookFn = (transition: Transition) => {\n const router = transition.router;\n\n function retryTransition() {\n if (transition.originalTransition().options().source !== 'url') {\n // The original transition was not triggered via url sync\n // The lazy state should be loaded now, so re-try the original transition\n const orig = transition.targetState();\n return router.stateService.target(orig.identifier(), orig.params(), orig.options());\n }\n\n // The original transition was triggered via url sync\n // Run the URL rules and find the best match\n const $url = router.urlService;\n const result = $url.match($url.parts());\n const rule = result && result.rule;\n\n // If the best match is a state, redirect the transition (instead\n // of calling sync() which supersedes the current transition)\n if (rule && rule.type === 'STATE') {\n const state = (rule as StateRule).state;\n const params = result.match;\n return router.stateService.target(state, params, transition.options());\n }\n\n // No matching state found, so let .sync() choose the best non-state match/otherwise\n router.urlService.sync();\n }\n\n const promises = transition\n .entering()\n .filter(state => !!state.$$state().lazyLoad)\n .map(state => lazyLoadState(transition, state));\n\n return services.$q.all(promises).then(retryTransition);\n};\n\nexport const registerLazyLoadHook = (transitionService: TransitionService) =>\n transitionService.onBefore({ entering: state => !!state.lazyLoad }, lazyLoadHook);\n\n/**\n * Invokes a state's lazy load function\n *\n * @param transition a Transition context\n * @param state the state to lazy load\n * @returns A promise for the lazy load result\n */\nexport function lazyLoadState(transition: Transition, state: StateDeclaration): Promise {\n const lazyLoadFn = state.$$state().lazyLoad;\n\n // Store/get the lazy load promise on/from the hookfn so it doesn't get re-invoked\n let promise = lazyLoadFn['_promise'];\n if (!promise) {\n const success = result => {\n delete state.lazyLoad;\n delete state.$$state().lazyLoad;\n delete lazyLoadFn['_promise'];\n return result;\n };\n\n const error = err => {\n delete lazyLoadFn['_promise'];\n return services.$q.reject(err);\n };\n\n promise = lazyLoadFn['_promise'] = services.$q\n .when(lazyLoadFn(transition, state))\n .then(updateStateRegistry)\n .then(success, error);\n }\n\n /** Register any lazy loaded state definitions */\n function updateStateRegistry(result: LazyLoadResult) {\n if (result && Array.isArray(result.states)) {\n result.states.forEach(_state => transition.router.stateRegistry.register(_state));\n }\n return result;\n }\n\n return promise;\n}\n", + "/** @module transition */ /** */\nimport { TransitionHookPhase, PathType } from './interface';\nimport { GetErrorHandler, GetResultHandler, TransitionHook } from './transitionHook';\n/**\n * This class defines a type of hook, such as `onBefore` or `onEnter`.\n * Plugins can define custom hook types, such as sticky states does for `onInactive`.\n *\n * @interalapi\n */\nexport class TransitionEventType {\n /* tslint:disable:no-inferrable-types */\n constructor(\n public name: string,\n public hookPhase: TransitionHookPhase,\n public hookOrder: number,\n public criteriaMatchPath: PathType,\n public reverseSort: boolean = false,\n public getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n public getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n public synchronous: boolean = false,\n ) {}\n}\n", + "/** @module hooks */ /** */\n\nimport { trace } from '../common/trace';\nimport { Rejection } from '../transition/rejectFactory';\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that skips a transition if it should be ignored\n *\n * This hook is invoked at the end of the onBefore phase.\n *\n * If the transition should be ignored (because no parameter or states changed)\n * then the transition is ignored and not processed.\n */\nfunction ignoredHook(trans: Transition) {\n const ignoredReason = trans._ignoredReason();\n if (!ignoredReason) return;\n\n trace.traceTransitionIgnored(trans);\n\n const pending = trans.router.globals.transition;\n\n // The user clicked a link going back to the *current state* ('A')\n // However, there is also a pending transition in flight (to 'B')\n // Abort the transition to 'B' because the user now wants to be back at 'A'.\n if (ignoredReason === 'SameAsCurrent' && pending) {\n pending.abort();\n }\n\n return Rejection.ignored().toPromise();\n}\n\nexport const registerIgnoredTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, ignoredHook, { priority: -9999 });\n", + "/** @module hooks */ /** */\n\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that rejects the Transition if it is invalid\n *\n * This hook is invoked at the end of the onBefore phase.\n * If the transition is invalid (for example, param values do not validate)\n * then the transition is rejected.\n */\nfunction invalidTransitionHook(trans: Transition) {\n if (!trans.valid()) {\n throw new Error(trans.error().toString());\n }\n}\n\nexport const registerInvalidTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, invalidTransitionHook, { priority: -10000 });\n", + "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport {\n IHookRegistry,\n TransitionOptions,\n TransitionHookScope,\n TransitionHookPhase,\n TransitionCreateHookFn,\n HookMatchCriteria,\n HookRegOptions,\n PathTypes,\n PathType,\n RegisteredHooks,\n TransitionHookFn,\n TransitionStateHookFn,\n} from './interface';\nimport { Transition } from './transition';\nimport { makeEvent, RegisteredHook } from './hookRegistry';\nimport { TargetState } from '../state/targetState';\nimport { PathNode } from '../path/pathNode';\nimport { ViewService } from '../view/view';\nimport { UIRouter } from '../router';\nimport { registerAddCoreResolvables, treeChangesCleanup } from '../hooks/coreResolvables';\nimport { registerRedirectToHook } from '../hooks/redirectTo';\nimport { registerOnExitHook, registerOnRetainHook, registerOnEnterHook } from '../hooks/onEnterExitRetain';\nimport { registerEagerResolvePath, registerLazyResolveState, registerResolveRemaining } from '../hooks/resolve';\nimport { registerLoadEnteringViews, registerActivateViews } from '../hooks/views';\nimport { registerUpdateGlobalState } from '../hooks/updateGlobals';\nimport { registerUpdateUrl } from '../hooks/url';\nimport { registerLazyLoadHook } from '../hooks/lazyLoad';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionHook, GetResultHandler, GetErrorHandler } from './transitionHook';\nimport { isDefined } from '../common/predicates';\nimport { removeFrom, values, createProxyFunctions } from '../common/common';\nimport { Disposable } from '../interface'; // has or is using\nimport { val } from '../common/hof';\nimport { registerIgnoredTransitionHook } from '../hooks/ignoredTransition';\nimport { registerInvalidTransitionHook } from '../hooks/invalidTransition';\n\n/**\n * The default [[Transition]] options.\n *\n * Include this object when applying custom defaults:\n * let reloadOpts = { reload: true, notify: true }\n * let options = defaults(theirOpts, customDefaults, defaultOptions);\n */\nexport let defaultTransOpts: TransitionOptions = {\n location: true,\n relative: null,\n inherit: false,\n notify: true,\n reload: false,\n custom: {},\n current: () => null,\n source: 'unknown',\n};\n\n/**\n * Plugin API for Transition Service\n * @internalapi\n */\nexport interface TransitionServicePluginAPI {\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n */\n _definePathType(name: string, hookScope: TransitionHookScope);\n\n /**\n * Gets a Path definition used as a criterion against a TreeChanges path\n */\n _getPathTypes(): PathTypes;\n\n /**\n * Defines a transition hook type and returns a transition hook registration\n * function (which can then be used to register hooks of this type).\n */\n _defineEvent(\n name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort?: boolean,\n getResultHandler?: GetResultHandler,\n getErrorHandler?: GetErrorHandler,\n rejectIfSuperseded?: boolean,\n );\n\n /**\n * Returns the known event types, such as `onBefore`\n * If a phase argument is provided, returns only events for the given phase.\n */\n _getEvents(phase?: TransitionHookPhase): TransitionEventType[];\n\n /** Returns the hooks registered for the given hook name */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/**\n * This class provides services related to Transitions.\n *\n * - Most importantly, it allows global Transition Hooks to be registered.\n * - It allows the default transition error handler to be set.\n * - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]).\n *\n * At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class.\n */\nexport class TransitionService implements IHookRegistry, Disposable {\n /** @hidden */\n _transitionCount = 0;\n\n /** @hidden */\n public $view: ViewService;\n\n /** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */\n private _eventTypes: TransitionEventType[] = [];\n /** @hidden The registered transition hooks */\n _registeredHooks = {} as RegisteredHooks;\n /** @hidden The paths on a criteria object */\n private _criteriaPaths = {} as PathTypes;\n /** @hidden */\n private _router: UIRouter;\n\n /** @internalapi */\n _pluginapi: TransitionServicePluginAPI;\n\n /**\n * This object has hook de-registration functions for the built-in hooks.\n * This can be used by third parties libraries that wish to customize the behaviors\n *\n * @hidden\n */\n _deregisterHookFns: {\n addCoreResolves: Function;\n ignored: Function;\n invalid: Function;\n redirectTo: Function;\n onExit: Function;\n onRetain: Function;\n onEnter: Function;\n eagerResolve: Function;\n lazyResolve: Function;\n resolveAll: Function;\n loadViews: Function;\n activateViews: Function;\n updateGlobals: Function;\n updateUrl: Function;\n lazyLoad: Function;\n };\n\n /** @hidden */\n constructor(_router: UIRouter) {\n this._router = _router;\n this.$view = _router.viewService;\n this._deregisterHookFns = {};\n this._pluginapi = createProxyFunctions(val(this), {}, val(this), [\n '_definePathType',\n '_defineEvent',\n '_getPathTypes',\n '_getEvents',\n 'getHooks',\n ]);\n\n this._defineCorePaths();\n this._defineCoreEvents();\n this._registerCoreTransitionHooks();\n _router.globals.successfulTransitions.onEvict(treeChangesCleanup);\n }\n\n /**\n * Registers a [[TransitionHookFn]], called *while a transition is being constructed*.\n *\n * Registers a transition lifecycle hook, which is invoked during transition construction.\n *\n * This low level hook should only be used by plugins.\n * This can be a useful time for plugins to add resolves or mutate the transition as needed.\n * The Sticky States plugin uses this hook to modify the treechanges.\n *\n * ### Lifecycle\n *\n * `onCreate` hooks are invoked *while a transition is being constructed*.\n *\n * ### Return value\n *\n * The hook's return value is ignored\n *\n * @internalapi\n * @param criteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @param options the registration options\n * @returns a function which deregisters the hook.\n */\n onCreate(criteria: HookMatchCriteria, callback: TransitionCreateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n\n /**\n * dispose\n * @internalapi\n */\n dispose(router: UIRouter) {\n values(this._registeredHooks).forEach((hooksArray: RegisteredHook[]) =>\n hooksArray.forEach(hook => {\n hook._deregistered = true;\n removeFrom(hooksArray, hook);\n }),\n );\n }\n\n /**\n * Creates a new [[Transition]] object\n *\n * This is a factory function for creating new Transition objects.\n * It is used internally by the [[StateService]] and should generally not be called by application code.\n *\n * @param fromPath the path to the current state (the from state)\n * @param targetState the target state (destination)\n * @returns a Transition\n */\n create(fromPath: PathNode[], targetState: TargetState): Transition {\n return new Transition(fromPath, targetState, this._router);\n }\n\n /** @hidden */\n private _defineCoreEvents() {\n const Phase = TransitionHookPhase;\n const TH = TransitionHook;\n const paths = this._criteriaPaths;\n const NORMAL_SORT = false,\n REVERSE_SORT = true;\n const SYNCHRONOUS = true;\n\n this._defineEvent(\n 'onCreate',\n Phase.CREATE,\n 0,\n paths.to,\n NORMAL_SORT,\n TH.LOG_REJECTED_RESULT,\n TH.THROW_ERROR,\n SYNCHRONOUS,\n );\n\n this._defineEvent('onBefore', Phase.BEFORE, 0, paths.to);\n\n this._defineEvent('onStart', Phase.RUN, 0, paths.to);\n this._defineEvent('onExit', Phase.RUN, 100, paths.exiting, REVERSE_SORT);\n this._defineEvent('onRetain', Phase.RUN, 200, paths.retained);\n this._defineEvent('onEnter', Phase.RUN, 300, paths.entering);\n this._defineEvent('onFinish', Phase.RUN, 400, paths.to);\n\n this._defineEvent(\n 'onSuccess',\n Phase.SUCCESS,\n 0,\n paths.to,\n NORMAL_SORT,\n TH.LOG_REJECTED_RESULT,\n TH.LOG_ERROR,\n SYNCHRONOUS,\n );\n this._defineEvent(\n 'onError',\n Phase.ERROR,\n 0,\n paths.to,\n NORMAL_SORT,\n TH.LOG_REJECTED_RESULT,\n TH.LOG_ERROR,\n SYNCHRONOUS,\n );\n }\n\n /** @hidden */\n private _defineCorePaths() {\n const { STATE, TRANSITION } = TransitionHookScope;\n\n this._definePathType('to', TRANSITION);\n this._definePathType('from', TRANSITION);\n this._definePathType('exiting', STATE);\n this._definePathType('retained', STATE);\n this._definePathType('entering', STATE);\n }\n\n /** @hidden */\n _defineEvent(\n name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort = false,\n getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n synchronous = false,\n ) {\n const eventType = new TransitionEventType(\n name,\n hookPhase,\n hookOrder,\n criteriaMatchPath,\n reverseSort,\n getResultHandler,\n getErrorHandler,\n synchronous,\n );\n\n this._eventTypes.push(eventType);\n makeEvent(this, this, eventType);\n }\n\n /** @hidden */\n // tslint:disable-next-line\n private _getEvents(phase?: TransitionHookPhase): TransitionEventType[] {\n const transitionHookTypes = isDefined(phase)\n ? this._eventTypes.filter(type => type.hookPhase === phase)\n : this._eventTypes.slice();\n\n return transitionHookTypes.sort((l, r) => {\n const cmpByPhase = l.hookPhase - r.hookPhase;\n return cmpByPhase === 0 ? l.hookOrder - r.hookOrder : cmpByPhase;\n });\n }\n\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n *\n * @hidden\n */\n private _definePathType(name: string, hookScope: TransitionHookScope) {\n this._criteriaPaths[name] = { name, scope: hookScope };\n }\n\n /** * @hidden */\n // tslint:disable-next-line\n private _getPathTypes(): PathTypes {\n return this._criteriaPaths;\n }\n\n /** @hidden */\n public getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /** @hidden */\n private _registerCoreTransitionHooks() {\n const fns = this._deregisterHookFns;\n\n fns.addCoreResolves = registerAddCoreResolvables(this);\n fns.ignored = registerIgnoredTransitionHook(this);\n fns.invalid = registerInvalidTransitionHook(this);\n\n // Wire up redirectTo hook\n fns.redirectTo = registerRedirectToHook(this);\n\n // Wire up onExit/Retain/Enter state hooks\n fns.onExit = registerOnExitHook(this);\n fns.onRetain = registerOnRetainHook(this);\n fns.onEnter = registerOnEnterHook(this);\n\n // Wire up Resolve hooks\n fns.eagerResolve = registerEagerResolvePath(this);\n fns.lazyResolve = registerLazyResolveState(this);\n fns.resolveAll = registerResolveRemaining(this);\n\n // Wire up the View management hooks\n fns.loadViews = registerLoadEnteringViews(this);\n fns.activateViews = registerActivateViews(this);\n\n // Updates global state after a transition\n fns.updateGlobals = registerUpdateGlobalState(this);\n\n // After globals.current is updated at priority: 10000\n fns.updateUrl = registerUpdateUrl(this);\n\n // Lazy load state trees\n fns.lazyLoad = registerLazyLoadHook(this);\n }\n}\n", + "/**\n * @coreapi\n * @module state\n */\n/** */\nimport {\n createProxyFunctions,\n defaults,\n extend,\n inArray,\n noop,\n removeFrom,\n silenceUncaughtInPromise,\n silentRejection,\n} from '../common/common';\nimport { isDefined, isObject, isString } from '../common/predicates';\nimport { Queue } from '../common/queue';\nimport { services } from '../common/coreservices';\n\nimport { PathUtils } from '../path/pathUtils';\nimport { PathNode } from '../path/pathNode';\n\nimport { HookResult, TransitionOptions } from '../transition/interface';\nimport { defaultTransOpts } from '../transition/transitionService';\nimport { Rejection, RejectType } from '../transition/rejectFactory';\nimport { Transition } from '../transition/transition';\n\nimport { HrefOptions, LazyLoadResult, StateDeclaration, StateOrName, TransitionPromise } from './interface';\nimport { StateObject } from './stateObject';\nimport { TargetState } from './targetState';\n\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Glob } from '../common/glob';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { lazyLoadState } from '../hooks/lazyLoad';\nimport { not, val } from '../common/hof';\nimport { StateParams } from '../params/stateParams';\n\nexport type OnInvalidCallback = (toState?: TargetState, fromState?: TargetState, injector?: UIInjector) => HookResult;\n\n/**\n * Provides state related service functions\n *\n * This class provides services related to ui-router states.\n * An instance of this class is located on the global [[UIRouter]] object.\n */\nexport class StateService {\n /** @internalapi */\n invalidCallbacks: OnInvalidCallback[] = [];\n\n /**\n * The [[Transition]] currently in progress (or null)\n *\n * This is a passthrough through to [[UIRouterGlobals.transition]]\n */\n get transition() {\n return this.router.globals.transition;\n }\n /**\n * The latest successful state parameters\n *\n * This is a passthrough through to [[UIRouterGlobals.params]]\n */\n get params(): StateParams {\n return this.router.globals.params;\n }\n /**\n * The current [[StateDeclaration]]\n *\n * This is a passthrough through to [[UIRouterGlobals.current]]\n */\n get current() {\n return this.router.globals.current;\n }\n /**\n * The current [[StateObject]]\n *\n * This is a passthrough through to [[UIRouterGlobals.$current]]\n */\n get $current() {\n return this.router.globals.$current;\n }\n\n /** @internalapi */\n constructor(private router: UIRouter) {\n const getters = ['current', '$current', 'params', 'transition'];\n const boundFns = Object.keys(StateService.prototype).filter(not(inArray(getters)));\n createProxyFunctions(val(StateService.prototype), this, val(this), boundFns);\n }\n\n /** @internalapi */\n dispose() {\n this.defaultErrorHandler(noop);\n this.invalidCallbacks = [];\n }\n\n /**\n * Handler for when [[transitionTo]] is called with an invalid state.\n *\n * Invokes the [[onInvalid]] callbacks, in natural order.\n * Each callback's return value is checked in sequence until one of them returns an instance of TargetState.\n * The results of the callbacks are wrapped in $q.when(), so the callbacks may return promises.\n *\n * If a callback returns an TargetState, then it is used as arguments to $state.transitionTo() and the result returned.\n *\n * @internalapi\n */\n private _handleInvalidTargetState(fromPath: PathNode[], toState: TargetState) {\n const fromState = PathUtils.makeTargetState(this.router.stateRegistry, fromPath);\n const globals = this.router.globals;\n const latestThing = () => globals.transitionHistory.peekTail();\n const latest = latestThing();\n const callbackQueue = new Queue(this.invalidCallbacks.slice());\n const injector = new ResolveContext(fromPath).injector();\n\n const checkForRedirect = (result: HookResult) => {\n if (!(result instanceof TargetState)) {\n return;\n }\n\n let target = result;\n // Recreate the TargetState, in case the state is now defined.\n target = this.target(target.identifier(), target.params(), target.options());\n\n if (!target.valid()) {\n return Rejection.invalid(target.error()).toPromise();\n }\n\n if (latestThing() !== latest) {\n return Rejection.superseded().toPromise();\n }\n\n return this.transitionTo(target.identifier(), target.params(), target.options());\n };\n\n function invokeNextCallback() {\n const nextCallback = callbackQueue.dequeue();\n if (nextCallback === undefined) return Rejection.invalid(toState.error()).toPromise();\n\n const callbackResult = services.$q.when(nextCallback(toState, fromState, injector));\n return callbackResult.then(checkForRedirect).then(result => result || invokeNextCallback());\n }\n\n return invokeNextCallback();\n }\n\n /**\n * Registers an Invalid State handler\n *\n * Registers a [[OnInvalidCallback]] function to be invoked when [[StateService.transitionTo]]\n * has been called with an invalid state reference parameter\n *\n * Example:\n * ```js\n * stateService.onInvalid(function(to, from, injector) {\n * if (to.name() === 'foo') {\n * let lazyLoader = injector.get('LazyLoadService');\n * return lazyLoader.load('foo')\n * .then(() => stateService.target('foo'));\n * }\n * });\n * ```\n *\n * @param {function} callback invoked when the toState is invalid\n * This function receives the (invalid) toState, the fromState, and an injector.\n * The function may optionally return a [[TargetState]] or a Promise for a TargetState.\n * If one is returned, it is treated as a redirect.\n *\n * @returns a function which deregisters the callback\n */\n onInvalid(callback: OnInvalidCallback): Function {\n this.invalidCallbacks.push(callback);\n return function deregisterListener() {\n removeFrom(this.invalidCallbacks)(callback);\n }.bind(this);\n }\n\n /**\n * Reloads the current state\n *\n * A method that force reloads the current state, or a partial state hierarchy.\n * All resolves are re-resolved, and components reinstantiated.\n *\n * #### Example:\n * ```js\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * $state.reload();\n * }\n * });\n * ```\n *\n * Note: `reload()` is just an alias for:\n *\n * ```js\n * $state.transitionTo($state.current, $state.params, {\n * reload: true, inherit: false\n * });\n * ```\n *\n * @param reloadState A state name or a state object.\n * If present, this state and all its children will be reloaded, but ancestors will not reload.\n *\n * #### Example:\n * ```js\n * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'\n * //and current state is 'contacts.detail.item'\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * //will reload 'contact.detail' and nested 'contact.detail.item' states\n * $state.reload('contact.detail');\n * }\n * });\n * ```\n *\n * @returns A promise representing the state of the new transition. See [[StateService.go]]\n */\n reload(reloadState?: StateOrName): Promise {\n return this.transitionTo(this.current, this.params, {\n reload: isDefined(reloadState) ? reloadState : true,\n inherit: false,\n notify: false,\n });\n }\n\n /**\n * Transition to a different state and/or parameters\n *\n * Convenience method for transitioning to a new state.\n *\n * `$state.go` calls `$state.transitionTo` internally but automatically sets options to\n * `{ location: true, inherit: true, relative: router.globals.$current, notify: true }`.\n * This allows you to use either an absolute or relative `to` argument (because of `relative: router.globals.$current`).\n * It also allows you to specify * only the parameters you'd like to update, while letting unspecified parameters\n * inherit from the current parameter values (because of `inherit: true`).\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.go('contact.detail');\n * };\n * });\n * ```\n *\n * @param to Absolute state name, state object, or relative state path (relative to current state).\n *\n * Some examples:\n *\n * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n * - `$state.go('^')` - will go to the parent state\n * - `$state.go('^.sibling')` - if current state is `home.child`, will go to the `home.sibling` state\n * - `$state.go('.child.grandchild')` - if current state is home, will go to the `home.child.grandchild` state\n *\n * @param params A map of the parameters that will be sent to the state, will populate $stateParams.\n *\n * Any parameters that are not specified will be inherited from current parameter values (because of `inherit: true`).\n * This allows, for example, going to a sibling state that shares parameters defined by a parent state.\n *\n * @param options Transition options\n *\n * @returns {promise} A promise representing the state of the new transition.\n */\n go(to: StateOrName, params?: RawParams, options?: TransitionOptions): TransitionPromise {\n const defautGoOpts = { relative: this.$current, inherit: true };\n const transOpts = defaults(options, defautGoOpts, defaultTransOpts);\n return this.transitionTo(to, params, transOpts);\n }\n\n /**\n * Creates a [[TargetState]]\n *\n * This is a factory method for creating a TargetState\n *\n * This may be returned from a Transition Hook to redirect a transition, for example.\n */\n target(identifier: StateOrName, params?: RawParams, options: TransitionOptions = {}): TargetState {\n // If we're reloading, find the state object to reload from\n if (isObject(options.reload) && !(options.reload).name) throw new Error('Invalid reload state object');\n const reg = this.router.stateRegistry;\n options.reloadState =\n options.reload === true ? reg.root() : reg.matcher.find(options.reload, options.relative);\n\n if (options.reload && !options.reloadState)\n throw new Error(\n `No such reload state '${isString(options.reload) ? options.reload : (options.reload).name}'`,\n );\n\n return new TargetState(this.router.stateRegistry, identifier, params, options);\n }\n\n private getCurrentPath(): PathNode[] {\n const globals = this.router.globals;\n const latestSuccess: Transition = globals.successfulTransitions.peekTail();\n const rootPath = () => [new PathNode(this.router.stateRegistry.root())];\n return latestSuccess ? latestSuccess.treeChanges().to : rootPath();\n }\n\n /**\n * Low-level method for transitioning to a new state.\n *\n * The [[go]] method (which uses `transitionTo` internally) is recommended in most situations.\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.transitionTo('contact.detail');\n * };\n * });\n * ```\n *\n * @param to State name or state object.\n * @param toParams A map of the parameters that will be sent to the state,\n * will populate $stateParams.\n * @param options Transition options\n *\n * @returns A promise representing the state of the new transition. See [[go]]\n */\n transitionTo(to: StateOrName, toParams: RawParams = {}, options: TransitionOptions = {}): TransitionPromise {\n const router = this.router;\n const globals = router.globals;\n options = defaults(options, defaultTransOpts);\n const getCurrent = () => globals.transition;\n options = extend(options, { current: getCurrent });\n\n const ref: TargetState = this.target(to, toParams, options);\n const currentPath = this.getCurrentPath();\n\n if (!ref.exists()) return this._handleInvalidTargetState(currentPath, ref);\n\n if (!ref.valid()) return silentRejection(ref.error());\n\n /**\n * Special handling for Ignored, Aborted, and Redirected transitions\n *\n * The semantics for the transition.run() promise and the StateService.transitionTo()\n * promise differ. For instance, the run() promise may be rejected because it was\n * IGNORED, but the transitionTo() promise is resolved because from the user perspective\n * no error occurred. Likewise, the transition.run() promise may be rejected because of\n * a Redirect, but the transitionTo() promise is chained to the new Transition's promise.\n */\n const rejectedTransitionHandler = (trans: Transition) => (error: any): Promise => {\n if (error instanceof Rejection) {\n const isLatest = router.globals.lastStartedTransitionId === trans.$id;\n\n if (error.type === RejectType.IGNORED) {\n isLatest && router.urlRouter.update();\n // Consider ignored `Transition.run()` as a successful `transitionTo`\n return services.$q.when(globals.current);\n }\n\n const detail: any = error.detail;\n if (error.type === RejectType.SUPERSEDED && error.redirected && detail instanceof TargetState) {\n // If `Transition.run()` was redirected, allow the `transitionTo()` promise to resolve successfully\n // by returning the promise for the new (redirect) `Transition.run()`.\n const redirect: Transition = trans.redirect(detail);\n return redirect.run().catch(rejectedTransitionHandler(redirect));\n }\n\n if (error.type === RejectType.ABORTED) {\n isLatest && router.urlRouter.update();\n return services.$q.reject(error);\n }\n }\n\n const errorHandler = this.defaultErrorHandler();\n errorHandler(error);\n\n return services.$q.reject(error);\n };\n\n const transition = this.router.transitionService.create(currentPath, ref);\n const transitionToPromise = transition.run().catch(rejectedTransitionHandler(transition));\n silenceUncaughtInPromise(transitionToPromise); // issue #2676\n\n // Return a promise for the transition, which also has the transition object on it.\n return extend(transitionToPromise, { transition });\n }\n\n /**\n * Checks if the current state *is* the provided state\n *\n * Similar to [[includes]] but only checks for the full state name.\n * If params is supplied then it will be tested for strict equality against the current\n * active params object, so all params must match with none missing and no extras.\n *\n * #### Example:\n * ```js\n * $state.$current.name = 'contacts.details.item';\n *\n * // absolute name\n * $state.is('contact.details.item'); // returns true\n * $state.is(contactDetailItemStateObject); // returns true\n * ```\n *\n * // relative name (. and ^), typically from a template\n * // E.g. from the 'contacts.details' template\n * ```html\n *
    Item
    \n * ```\n *\n * @param stateOrName The state name (absolute or relative) or state object you'd like to check.\n * @param params A param object, e.g. `{sectionId: section.id}`, that you'd like\n * to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns Returns true if it is the state.\n */\n is(stateOrName: StateOrName, params?: RawParams, options?: { relative?: StateOrName }): boolean {\n options = defaults(options, { relative: this.$current });\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n if (!isDefined(state)) return undefined;\n if (this.$current !== state) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n /**\n * Checks if the current state *includes* the provided state\n *\n * A method to determine if the current active state is equal to or is the child of the\n * state stateName. If any params are passed then they will be tested for a match as well.\n * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n *\n * #### Example when `$state.$current.name === 'contacts.details.item'`\n * ```js\n * // Using partial names\n * $state.includes(\"contacts\"); // returns true\n * $state.includes(\"contacts.details\"); // returns true\n * $state.includes(\"contacts.details.item\"); // returns true\n * $state.includes(\"contacts.list\"); // returns false\n * $state.includes(\"about\"); // returns false\n * ```\n *\n * #### Glob Examples when `* $state.$current.name === 'contacts.details.item.url'`:\n * ```js\n * $state.includes(\"*.details.*.*\"); // returns true\n * $state.includes(\"*.details.**\"); // returns true\n * $state.includes(\"**.item.**\"); // returns true\n * $state.includes(\"*.details.item.url\"); // returns true\n * $state.includes(\"*.details.*.url\"); // returns true\n * $state.includes(\"*.details.*\"); // returns false\n * $state.includes(\"item.**\"); // returns false\n * ```\n *\n * @param stateOrName A partial name, relative name, glob pattern,\n * or state object to be searched for within the current state name.\n * @param params A param object, e.g. `{sectionId: section.id}`,\n * that you'd like to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns {boolean} Returns true if it does include the state\n */\n includes(stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions): boolean {\n options = defaults(options, { relative: this.$current });\n const glob = isString(stateOrName) && Glob.fromString(stateOrName);\n\n if (glob) {\n if (!glob.matches(this.$current.name)) return false;\n stateOrName = this.$current.name;\n }\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative),\n include = this.$current.includes;\n\n if (!isDefined(state)) return undefined;\n if (!isDefined(include[state.name])) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n /**\n * Generates a URL for a state and parameters\n *\n * Returns the url for the given state populated with the given params.\n *\n * #### Example:\n * ```js\n * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n * ```\n *\n * @param stateOrName The state name or state object you'd like to generate a url from.\n * @param params An object of parameter values to fill the state's required parameters.\n * @param options Options object. The options are:\n *\n * @returns {string} compiled state url\n */\n href(stateOrName: StateOrName, params: RawParams, options?: HrefOptions): string {\n const defaultHrefOpts = {\n lossy: true,\n inherit: true,\n absolute: false,\n relative: this.$current,\n };\n options = defaults(options, defaultHrefOpts);\n params = params || {};\n\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n\n if (!isDefined(state)) return null;\n if (options.inherit) params = this.params.$inherit(params, this.$current, state);\n\n const nav = state && options.lossy ? state.navigable : state;\n\n if (!nav || nav.url === undefined || nav.url === null) {\n return null;\n }\n return this.router.urlRouter.href(nav.url, params, {\n absolute: options.absolute,\n });\n }\n\n /** @hidden */\n private _defaultErrorHandler: ((_error: any) => void) = function $defaultErrorHandler($error$) {\n if ($error$ instanceof Error && $error$.stack) {\n console.error($error$);\n console.error($error$.stack);\n } else if ($error$ instanceof Rejection) {\n console.error($error$.toString());\n if ($error$.detail && $error$.detail.stack) console.error($error$.detail.stack);\n } else {\n console.error($error$);\n }\n };\n\n /**\n * Sets or gets the default [[transitionTo]] error handler.\n *\n * The error handler is called when a [[Transition]] is rejected or when any error occurred during the Transition.\n * This includes errors caused by resolves and transition hooks.\n *\n * Note:\n * This handler does not receive certain Transition rejections.\n * Redirected and Ignored Transitions are not considered to be errors by [[StateService.transitionTo]].\n *\n * The built-in default error handler logs the error to the console.\n *\n * You can provide your own custom handler.\n *\n * #### Example:\n * ```js\n * stateService.defaultErrorHandler(function() {\n * // Do not log transitionTo errors\n * });\n * ```\n *\n * @param handler a global error handler function\n * @returns the current global error handler\n */\n defaultErrorHandler(handler?: (error: any) => void): (error: any) => void {\n return (this._defaultErrorHandler = handler || this._defaultErrorHandler);\n }\n\n /**\n * Gets a registered [[StateDeclaration]] object\n *\n * Returns the state declaration object for any specific state, or for all registered states.\n *\n * @param stateOrName (absolute or relative) If provided, will only get the declaration object for the requested state.\n * If not provided, returns an array of ALL states.\n * @param base When `stateOrName` is a relative state reference (such as `.bar.baz`), the state will be retrieved relative to this state.\n *\n * @returns a [[StateDeclaration]] object (or array of all registered [[StateDeclaration]] objects.)\n */\n get(stateOrName: StateOrName, base: StateOrName): StateDeclaration;\n get(stateOrName: StateOrName): StateDeclaration;\n get(): StateDeclaration[];\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n const reg = this.router.stateRegistry;\n if (arguments.length === 0) return reg.get();\n return reg.get(stateOrName, base || this.$current);\n }\n\n /**\n * Lazy loads a state\n *\n * Explicitly runs a state's [[StateDeclaration.lazyLoad]] function.\n *\n * @param stateOrName the state that should be lazy loaded\n * @param transition the optional Transition context to use (if the lazyLoad function requires an injector, etc)\n * Note: If no transition is provided, a noop transition is created using the from the current state to the current state.\n * This noop transition is not actually run.\n *\n * @returns a promise to lazy load\n */\n lazyLoad(stateOrName: StateOrName, transition?: Transition): Promise {\n const state: StateDeclaration = this.get(stateOrName);\n if (!state || !state.lazyLoad) throw new Error('Can not lazy load ' + stateOrName);\n\n const currentPath = this.getCurrentPath();\n const target = PathUtils.makeTargetState(this.router.stateRegistry, currentPath);\n transition = transition || this.router.transitionService.create(currentPath, target);\n\n return lazyLoadState(transition, state);\n }\n}\n", + "/**\n * # Transition subsystem\n *\n * This module contains APIs related to a Transition.\n *\n * See:\n * - [[TransitionService]]\n * - [[Transition]]\n * - [[HookFn]], [[TransitionHookFn]], [[TransitionStateHookFn]], [[HookMatchCriteria]], [[HookResult]]\n *\n * @coreapi\n * @preferred\n * @module transition\n */ /** for typedoc */\nexport * from './interface';\nexport * from './hookBuilder';\nexport * from './hookRegistry';\nexport * from './rejectFactory';\nexport * from './transition';\nexport * from './transitionHook';\nexport * from './transitionEventType';\nexport * from './transitionService';\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isArray, isObject, $QLike } from '../common/index';\n\n/**\n * An angular1-like promise api\n *\n * This object implements four methods similar to the\n * [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This API provides native ES6 promise support wrapped as a $q-like API.\n * Internally, UI-Router uses this $q object to perform promise operations.\n * The `angular-ui-router` (ui-router for angular 1) uses the $q API provided by angular.\n *\n * $q-like promise api\n */\nexport const $q = {\n /** Normalizes a value as a promise */\n when: val => new Promise((resolve, reject) => resolve(val)),\n\n /** Normalizes a value as a promise rejection */\n reject: val =>\n new Promise((resolve, reject) => {\n reject(val);\n }),\n\n /** @returns a deferred object, which has `resolve` and `reject` functions */\n defer: () => {\n const deferred: any = {};\n deferred.promise = new Promise((resolve, reject) => {\n deferred.resolve = resolve;\n deferred.reject = reject;\n });\n return deferred;\n },\n\n /** Like Promise.all(), but also supports object key/promise notation like $q */\n all: (promises: { [key: string]: Promise } | Promise[]) => {\n if (isArray(promises)) {\n return Promise.all(promises);\n }\n\n if (isObject(promises)) {\n // Convert promises map to promises array.\n // When each promise resolves, map it to a tuple { key: key, val: val }\n const chain = Object.keys(promises).map(key => promises[key].then(val => ({ key, val })));\n\n // Then wait for all promises to resolve, and convert them back to an object\n return $q.all(chain).then(values =>\n values.reduce((acc, tuple) => {\n acc[tuple.key] = tuple.val;\n return acc;\n }, {}),\n );\n }\n },\n} as $QLike;\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n extend,\n assertPredicate,\n isFunction,\n isArray,\n isInjectable,\n $InjectorLike,\n IInjectable,\n} from '../common/index';\n\n// globally available injectables\nconst globals = {};\nconst STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/gm;\nconst ARGUMENT_NAMES = /([^\\s,]+)/g;\n\n/**\n * A basic angular1-like injector api\n *\n * This object implements four methods similar to the\n * [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This object provides a naive implementation of a globally scoped dependency injection system.\n * It supports the following DI approaches:\n *\n * ### Function parameter names\n *\n * A function's `.toString()` is called, and the parameter names are parsed.\n * This only works when the parameter names aren't \"mangled\" by a minifier such as UglifyJS.\n *\n * ```js\n * function injectedFunction(FooService, BarService) {\n * // FooService and BarService are injected\n * }\n * ```\n *\n * ### Function annotation\n *\n * A function may be annotated with an array of dependency names as the `$inject` property.\n *\n * ```js\n * injectedFunction.$inject = [ 'FooService', 'BarService' ];\n * function injectedFunction(fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }\n * ```\n *\n * ### Array notation\n *\n * An array provides the names of the dependencies to inject (as strings).\n * The function is the last element of the array.\n *\n * ```js\n * [ 'FooService', 'BarService', function (fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }]\n * ```\n *\n * @type {$InjectorLike}\n */\nexport const $injector = {\n /** Gets an object from DI based on a string token */\n get: name => globals[name],\n\n /** Returns true if an object named `name` exists in global DI */\n has: name => $injector.get(name) != null,\n\n /**\n * Injects a function\n *\n * @param fn the function to inject\n * @param context the function's `this` binding\n * @param locals An object with additional DI tokens and values, such as `{ someToken: { foo: 1 } }`\n */\n invoke: (fn: IInjectable, context?, locals?) => {\n const all = extend({}, globals, locals || {});\n const params = $injector.annotate(fn);\n const ensureExist = assertPredicate(\n (key: string) => all.hasOwnProperty(key),\n key => `DI can't find injectable: '${key}'`,\n );\n const args = params.filter(ensureExist).map(x => all[x]);\n if (isFunction(fn)) return fn.apply(context, args);\n else return (fn as any[]).slice(-1)[0].apply(context, args);\n },\n\n /**\n * Returns a function's dependencies\n *\n * Analyzes a function (or array) and returns an array of DI tokens that the function requires.\n * @return an array of `string`s\n */\n annotate: (fn: IInjectable): any[] => {\n if (!isInjectable(fn)) throw new Error(`Not an injectable function: ${fn}`);\n if (fn && (fn as any).$inject) return (fn as any).$inject;\n if (isArray(fn)) return fn.slice(0, -1);\n const fnStr = fn.toString().replace(STRIP_COMMENTS, '');\n const result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);\n return result || [];\n },\n} as $InjectorLike;\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n LocationConfig,\n LocationServices,\n identity,\n unnestR,\n isArray,\n splitEqual,\n splitHash,\n splitQuery,\n} from '../common';\nimport { UIRouter } from '../router';\n\nexport const keyValsToObjectR = (accum, [key, val]) => {\n if (!accum.hasOwnProperty(key)) {\n accum[key] = val;\n } else if (isArray(accum[key])) {\n accum[key].push(val);\n } else {\n accum[key] = [accum[key], val];\n }\n return accum;\n};\n\nexport const getParams = (queryString: string): any =>\n queryString\n .split('&')\n .filter(identity)\n .map(splitEqual)\n .reduce(keyValsToObjectR, {});\n\nexport function parseUrl(url: string) {\n const orEmptyString = x => x || '';\n const [beforehash, hash] = splitHash(url).map(orEmptyString);\n const [path, search] = splitQuery(beforehash).map(orEmptyString);\n\n return { path, search, hash, url };\n}\n\nexport const buildUrl = (loc: LocationServices) => {\n const path = loc.path();\n const searchObject = loc.search();\n const hash = loc.hash();\n\n const search = Object.keys(searchObject)\n .map(key => {\n const param = searchObject[key];\n const vals = isArray(param) ? param : [param];\n return vals.map(val => key + '=' + val);\n })\n .reduce(unnestR, [])\n .join('&');\n\n return path + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n};\n\nexport function locationPluginFactory(\n name: string,\n isHtml5: boolean,\n serviceClass: { new (uiRouter?: UIRouter): LocationServices },\n configurationClass: { new (uiRouter?: UIRouter, isHtml5?: boolean): LocationConfig },\n) {\n return function(uiRouter: UIRouter) {\n const service = (uiRouter.locationService = new serviceClass(uiRouter));\n const configuration = (uiRouter.locationConfig = new configurationClass(uiRouter, isHtml5));\n\n function dispose(router: UIRouter) {\n router.dispose(service);\n router.dispose(configuration);\n }\n\n return { name, service, configuration, dispose };\n };\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */ /** */\n\nimport { deregAll, isDefined, LocationServices, removeFrom, root } from '../common';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { HistoryLike, LocationLike } from './interface';\nimport { buildUrl, getParams, parseUrl } from './utils';\n\n/** A base `LocationServices` */\nexport abstract class BaseLocationServices implements LocationServices, Disposable {\n private _listeners: Function[] = [];\n _location: LocationLike;\n _history: HistoryLike;\n\n _listener = evt => this._listeners.forEach(cb => cb(evt));\n\n constructor(router: UIRouter, public fireAfterUpdate: boolean) {\n this._location = root.location;\n this._history = root.history;\n }\n\n /**\n * This should return the current internal URL representation.\n *\n * The internal URL includes only the portion that UI-Router matches.\n * It does not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n */\n protected abstract _get(): string;\n\n /**\n * This should set the current URL.\n *\n * The `url` param should include only the portion that UI-Router matches on.\n * It should not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n *\n * However, after this function completes, the browser URL should reflect the entire (fully qualified)\n * HREF including those data.\n */\n protected abstract _set(state: any, title: string, url: string, replace: boolean);\n\n hash = () => parseUrl(this._get()).hash;\n path = () => parseUrl(this._get()).path;\n search = () => getParams(parseUrl(this._get()).search);\n\n url(url?: string, replace = true): string {\n if (isDefined(url) && url !== this._get()) {\n this._set(null, null, url, replace);\n\n if (this.fireAfterUpdate) {\n this._listeners.forEach(cb => cb({ url }));\n }\n }\n\n return buildUrl(this);\n }\n\n onChange(cb: EventListener) {\n this._listeners.push(cb);\n return () => removeFrom(this._listeners, cb);\n }\n\n dispose(router: UIRouter) {\n deregAll(this._listeners);\n }\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { root, trimHashVal } from '../common';\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\n\n/** A `LocationServices` that uses the browser hash \"#\" to get/set the current location */\nexport class HashLocationService extends BaseLocationServices {\n constructor(router: UIRouter) {\n super(router, false);\n root.addEventListener('hashchange', this._listener, false);\n }\n\n _get() {\n return trimHashVal(this._location.hash);\n }\n _set(state: any, title: string, url: string, replace: boolean) {\n this._location.hash = url;\n }\n\n dispose(router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('hashchange', this._listener);\n }\n}\n", "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { BaseLocationServices } from './baseLocationService';\nimport { UIRouter } from '../router';\n\n/** A `LocationServices` that gets/sets the current location from an in-memory object */\nexport class MemoryLocationService extends BaseLocationServices {\n _url: string;\n\n constructor(router: UIRouter) {\n super(router, true);\n }\n\n _get() {\n return this._url;\n }\n\n _set(state: any, title: string, url: string, replace: boolean) {\n this._url = url;\n }\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\nimport { LocationConfig, root, splitHash, splitQuery, stripLastPathElement } from '../common';\n\n/**\n * A `LocationServices` that gets/sets the current location using the browser's `location` and `history` apis\n *\n * Uses `history.pushState` and `history.replaceState`\n */\nexport class PushStateLocationService extends BaseLocationServices {\n _config: LocationConfig;\n\n constructor(router: UIRouter) {\n super(router, true);\n this._config = router.urlService.config;\n root.addEventListener('popstate', this._listener, false);\n }\n\n /**\n * Gets the base prefix without:\n * - trailing slash\n * - trailing filename\n * - protocol and hostname\n *\n * If , this returns '/base'.\n * If , this returns '/foo/base'.\n * If , this returns '/base'.\n * If , this returns '/base'.\n * If , this returns ''.\n * If , this returns ''.\n * If , this returns ''.\n *\n * See: https://html.spec.whatwg.org/dev/semantics.html#the-base-element\n */\n private _getBasePrefix() {\n return stripLastPathElement(this._config.baseHref());\n }\n\n protected _get() {\n let { pathname, hash, search } = this._location;\n search = splitQuery(search)[1]; // strip ? if found\n hash = splitHash(hash)[1]; // strip # if found\n\n const basePrefix = this._getBasePrefix();\n const exactBaseHrefMatch = pathname === this._config.baseHref();\n const startsWithBase = pathname.substr(0, basePrefix.length) === basePrefix;\n pathname = exactBaseHrefMatch ? '/' : startsWithBase ? pathname.substring(basePrefix.length) : pathname;\n\n return pathname + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n }\n\n protected _set(state: any, title: string, url: string, replace: boolean) {\n const basePrefix = this._getBasePrefix();\n const slash = url && url[0] !== '/' ? '/' : '';\n const fullUrl = (url === '' || url === '/') ? this._config.baseHref() : basePrefix + slash + url;\n\n if (replace) {\n this._history.replaceState(state, title, fullUrl);\n } else {\n this._history.pushState(state, title, fullUrl);\n }\n }\n\n public dispose(router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('popstate', this._listener);\n }\n}\n\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { LocationConfig } from '../common/coreservices';\nimport { isDefined } from '../common/predicates';\nimport { noop } from '../common/common';\n\n/** A `LocationConfig` mock that gets/sets all config from an in-memory object */\nexport class MemoryLocationConfig implements LocationConfig {\n dispose = noop;\n\n _baseHref = '';\n _port = 80;\n _protocol = 'http';\n _host = 'localhost';\n _hashPrefix = '';\n\n port = () => this._port;\n protocol = () => this._protocol;\n host = () => this._host;\n baseHref = () => this._baseHref;\n html5Mode = () => false;\n hashPrefix = (newval?) => isDefined(newval) ? this._hashPrefix = newval : this._hashPrefix;\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isDefined } from '../common/predicates';\nimport { LocationConfig } from '../common/coreservices';\n\n/** A `LocationConfig` that delegates to the browser's `location` object */\nexport class BrowserLocationConfig implements LocationConfig {\n private _baseHref = undefined;\n private _hashPrefix = '';\n\n constructor(router?, private _isHtml5 = false) { }\n\n port(): number {\n if (location.port) {\n return Number(location.port);\n }\n\n return this.protocol() === 'https' ? 443 : 80;\n }\n\n protocol(): string {\n return location.protocol.replace(/:/g, '');\n }\n\n host(): string {\n return location.hostname;\n }\n\n html5Mode(): boolean {\n return this._isHtml5;\n }\n\n hashPrefix(): string;\n hashPrefix(newprefix?: string): string {\n return isDefined(newprefix) ? this._hashPrefix = newprefix : this._hashPrefix;\n }\n\n baseHref(href?: string): string {\n return isDefined(href) ? this._baseHref = href :\n isDefined(this._baseHref) ? this._baseHref : this.applyDocumentBaseHref();\n }\n\n applyDocumentBaseHref() {\n const baseTag: HTMLBaseElement = document.getElementsByTagName('base')[0];\n return this._baseHref = baseTag ? baseTag.href.substr(location.origin.length) : location.pathname || '/';\n }\n\n dispose() {}\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { BrowserLocationConfig } from './browserLocationConfig';\nimport { HashLocationService } from './hashLocationService';\nimport { locationPluginFactory } from './utils';\nimport { LocationPlugin, ServicesPlugin } from './interface';\nimport { UIRouter } from '../router';\nimport { PushStateLocationService } from './pushStateLocationService';\nimport { MemoryLocationService } from './memoryLocationService';\nimport { MemoryLocationConfig } from './memoryLocationConfig';\nimport { $injector } from './injector';\nimport { $q } from './q';\nimport { services } from '../common/coreservices';\n\nexport function servicesPlugin(router: UIRouter): ServicesPlugin {\n services.$injector = $injector;\n services.$q = $q;\n\n return { name: 'vanilla.services', $q, $injector, dispose: () => null };\n}\n\n/** A `UIRouterPlugin` uses the browser hash to get/set the current location */\nexport const hashLocationPlugin: (router: UIRouter) => LocationPlugin =\n locationPluginFactory('vanilla.hashBangLocation', false, HashLocationService, BrowserLocationConfig);\n\n/** A `UIRouterPlugin` that gets/sets the current location using the browser's `location` and `history` apis */\nexport const pushStateLocationPlugin: (router: UIRouter) => LocationPlugin =\n locationPluginFactory('vanilla.pushStateLocation', true, PushStateLocationService, BrowserLocationConfig);\n\n/** A `UIRouterPlugin` that gets/sets the current location from an in-memory object */\nexport const memoryLocationPlugin: (router: UIRouter) => LocationPlugin =\n locationPluginFactory('vanilla.memoryLocation', false, MemoryLocationService, MemoryLocationConfig);\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\nimport { LocationConfig, root, splitHash, splitQuery, stripLastPathElement } from '../common';\n\n/**\n * A `LocationServices` that gets/sets the current location using the browser's `location` and `history` apis\n *\n * Uses `history.pushState` and `history.replaceState`\n */\nexport class PushStateLocationService extends BaseLocationServices {\n _config: LocationConfig;\n\n constructor(router: UIRouter) {\n super(router, true);\n this._config = router.urlService.config;\n root.addEventListener('popstate', this._listener, false);\n }\n\n /**\n * Gets the base prefix without:\n * - trailing slash\n * - trailing filename\n * - protocol and hostname\n *\n * If , this returns '/base'.\n * If , this returns '/foo/base'.\n * If , this returns '/base'.\n * If , this returns '/base'.\n * If , this returns ''.\n * If , this returns ''.\n * If , this returns ''.\n *\n * See: https://html.spec.whatwg.org/dev/semantics.html#the-base-element\n */\n private _getBasePrefix() {\n return stripLastPathElement(this._config.baseHref());\n }\n\n protected _get() {\n let { pathname, hash, search } = this._location;\n search = splitQuery(search)[1]; // strip ? if found\n hash = splitHash(hash)[1]; // strip # if found\n\n const basePrefix = this._getBasePrefix();\n const exactBaseHrefMatch = pathname === this._config.baseHref();\n const startsWithBase = pathname.substr(0, basePrefix.length) === basePrefix;\n pathname = exactBaseHrefMatch ? '/' : startsWithBase ? pathname.substring(basePrefix.length) : pathname;\n\n return pathname + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n }\n\n protected _set(state: any, title: string, url: string, replace: boolean) {\n const basePrefix = this._getBasePrefix();\n const slash = url && url[0] !== '/' ? '/' : '';\n const fullUrl = url === '' || url === '/' ? this._config.baseHref() : basePrefix + slash + url;\n\n if (replace) {\n this._history.replaceState(state, title, fullUrl);\n } else {\n this._history.pushState(state, title, fullUrl);\n }\n }\n\n public dispose(router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('popstate', this._listener);\n }\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { LocationConfig } from '../common/coreservices';\nimport { isDefined } from '../common/predicates';\nimport { noop } from '../common/common';\n\n/** A `LocationConfig` mock that gets/sets all config from an in-memory object */\nexport class MemoryLocationConfig implements LocationConfig {\n dispose = noop;\n\n _baseHref = '';\n _port = 80;\n _protocol = 'http';\n _host = 'localhost';\n _hashPrefix = '';\n\n port = () => this._port;\n protocol = () => this._protocol;\n host = () => this._host;\n baseHref = () => this._baseHref;\n html5Mode = () => false;\n hashPrefix = (newval?) => (isDefined(newval) ? (this._hashPrefix = newval) : this._hashPrefix);\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isDefined } from '../common/predicates';\nimport { LocationConfig } from '../common/coreservices';\n\n/** A `LocationConfig` that delegates to the browser's `location` object */\nexport class BrowserLocationConfig implements LocationConfig {\n private _baseHref = undefined;\n private _hashPrefix = '';\n\n constructor(router?, private _isHtml5 = false) {}\n\n port(): number {\n if (location.port) {\n return Number(location.port);\n }\n\n return this.protocol() === 'https' ? 443 : 80;\n }\n\n protocol(): string {\n return location.protocol.replace(/:/g, '');\n }\n\n host(): string {\n return location.hostname;\n }\n\n html5Mode(): boolean {\n return this._isHtml5;\n }\n\n hashPrefix(): string;\n hashPrefix(newprefix?: string): string {\n return isDefined(newprefix) ? (this._hashPrefix = newprefix) : this._hashPrefix;\n }\n\n baseHref(href?: string): string {\n return isDefined(href)\n ? (this._baseHref = href)\n : isDefined(this._baseHref) ? this._baseHref : this.applyDocumentBaseHref();\n }\n\n applyDocumentBaseHref() {\n const baseTag: HTMLBaseElement = document.getElementsByTagName('base')[0];\n return (this._baseHref = baseTag ? baseTag.href.substr(location.origin.length) : location.pathname || '/');\n }\n\n dispose() {}\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { BrowserLocationConfig } from './browserLocationConfig';\nimport { HashLocationService } from './hashLocationService';\nimport { locationPluginFactory } from './utils';\nimport { LocationPlugin, ServicesPlugin } from './interface';\nimport { UIRouter } from '../router';\nimport { PushStateLocationService } from './pushStateLocationService';\nimport { MemoryLocationService } from './memoryLocationService';\nimport { MemoryLocationConfig } from './memoryLocationConfig';\nimport { $injector } from './injector';\nimport { $q } from './q';\nimport { services } from '../common/coreservices';\n\nexport function servicesPlugin(router: UIRouter): ServicesPlugin {\n services.$injector = $injector;\n services.$q = $q;\n\n return { name: 'vanilla.services', $q, $injector, dispose: () => null };\n}\n\n/** A `UIRouterPlugin` uses the browser hash to get/set the current location */\nexport const hashLocationPlugin: (router: UIRouter) => LocationPlugin = locationPluginFactory(\n 'vanilla.hashBangLocation',\n false,\n HashLocationService,\n BrowserLocationConfig,\n);\n\n/** A `UIRouterPlugin` that gets/sets the current location using the browser's `location` and `history` apis */\nexport const pushStateLocationPlugin: (router: UIRouter) => LocationPlugin = locationPluginFactory(\n 'vanilla.pushStateLocation',\n true,\n PushStateLocationService,\n BrowserLocationConfig,\n);\n\n/** A `UIRouterPlugin` that gets/sets the current location from an in-memory object */\nexport const memoryLocationPlugin: (router: UIRouter) => LocationPlugin = locationPluginFactory(\n 'vanilla.memoryLocation',\n false,\n MemoryLocationService,\n MemoryLocationConfig,\n);\n", "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nexport * from './vanilla/index';\n", - "/**\n * # Core classes and interfaces\n *\n * The classes and interfaces that are core to ui-router and do not belong\n * to a more specific subsystem (such as resolve).\n *\n * @coreapi\n * @preferred\n * @module core\n */ /** for typedoc */\n\n// Need to import or export at least one concrete something\nimport { noop } from './common/common';\nimport { UIRouter } from './router';\n\n/**\n * An interface for getting values from dependency injection.\n *\n * This is primarily used to get resolve values for a given token.\n * An instance of the `UIInjector` can be retrieved from the current transition using [[Transition.injector]].\n *\n * ---\n *\n * If no resolve is found for a token, then it will delegate to the native injector.\n * The native injector may be Angular 1 `$injector`, Angular 2 `Injector`, or a simple polyfill.\n *\n * In Angular 2, the native injector might be the root Injector,\n * or it might be a lazy loaded `NgModule` injector scoped to a lazy load state tree.\n */\nexport interface UIInjector {\n /**\n * Gets a value from the injector.\n *\n * For a given token, returns the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this throws an error.\n *\n * #### Example:\n * ```js\n * var myResolve = injector.get('myResolve');\n * ```\n *\n * #### ng1 Example:\n * ```js\n * // Fetch StateService\n * injector.get('$state').go('home');\n * ```\n *\n * #### ng2 Example:\n * ```js\n * import {StateService} from \"ui-router-ng2\";\n * // Fetch StateService\n * injector.get(StateService).go('home');\n * ```\n *\n * #### Typescript Example:\n * ```js\n * var stringArray = injector.get('myStringArray');\n * ```\n *\n * ### `NOWAIT` policy\n *\n * When using [[ResolvePolicy.async]] === `NOWAIT`, the value returned from `get()` is a promise for the result.\n * The promise is not automatically unwrapped.\n *\n * @param token the key for the value to get. May be a string, a class, or any arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n get(token: any): any;\n /** Gets a value as type `T` (generics parameter) */\n get(token: any): T;\n\n /**\n * Asynchronously gets a value from the injector\n *\n * For a given token, returns a promise for the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this triggers the resolve to load.\n *\n * #### Example:\n * ```js\n * return injector.getAsync('myResolve').then(value => {\n * if (value === 'declined') return false;\n * });\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return a Promise for the Dependency Injection value that matches the token\n */\n getAsync(token: any): Promise;\n /** Asynchronously gets a value as type `T` (generics parameter) */\n getAsync(token: any): Promise;\n\n /**\n * Gets a value from the native injector\n *\n * Returns a value from the native injector, bypassing anything in the [[ResolveContext]].\n *\n * Example:\n * ```js\n * let someThing = injector.getNative(SomeToken);\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n getNative(token: any): any;\n getNative(token: any): T;\n}\n\n/** @internalapi */\nexport interface UIRouterPlugin extends Disposable {\n name: string;\n}\n\n/** @internalapi */\nexport abstract class UIRouterPluginBase implements UIRouterPlugin, Disposable {\n abstract name: string;\n dispose(router: UIRouter) { }\n}\n\n/** @internalapi */\nexport interface Disposable {\n /** Instructs the Disposable to clean up any resources */\n dispose(router?: UIRouter);\n}\n", + "/**\n * # Core classes and interfaces\n *\n * The classes and interfaces that are core to ui-router and do not belong\n * to a more specific subsystem (such as resolve).\n *\n * @coreapi\n * @preferred\n * @module core\n */ /** for typedoc */\n\n// Need to import or export at least one concrete something\nimport { noop } from './common/common';\nimport { UIRouter } from './router';\n\n/**\n * An interface for getting values from dependency injection.\n *\n * This is primarily used to get resolve values for a given token.\n * An instance of the `UIInjector` can be retrieved from the current transition using [[Transition.injector]].\n *\n * ---\n *\n * If no resolve is found for a token, then it will delegate to the native injector.\n * The native injector may be Angular 1 `$injector`, Angular 2 `Injector`, or a simple polyfill.\n *\n * In Angular 2, the native injector might be the root Injector,\n * or it might be a lazy loaded `NgModule` injector scoped to a lazy load state tree.\n */\nexport interface UIInjector {\n /**\n * Gets a value from the injector.\n *\n * For a given token, returns the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this throws an error.\n *\n * #### Example:\n * ```js\n * var myResolve = injector.get('myResolve');\n * ```\n *\n * #### ng1 Example:\n * ```js\n * // Fetch StateService\n * injector.get('$state').go('home');\n * ```\n *\n * #### ng2 Example:\n * ```js\n * import {StateService} from \"ui-router-ng2\";\n * // Fetch StateService\n * injector.get(StateService).go('home');\n * ```\n *\n * #### Typescript Example:\n * ```js\n * var stringArray = injector.get('myStringArray');\n * ```\n *\n * ### `NOWAIT` policy\n *\n * When using [[ResolvePolicy.async]] === `NOWAIT`, the value returned from `get()` is a promise for the result.\n * The promise is not automatically unwrapped.\n *\n * @param token the key for the value to get. May be a string, a class, or any arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n get(token: any): any;\n /** Gets a value as type `T` (generics parameter) */\n get(token: any): T;\n\n /**\n * Asynchronously gets a value from the injector\n *\n * For a given token, returns a promise for the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this triggers the resolve to load.\n *\n * #### Example:\n * ```js\n * return injector.getAsync('myResolve').then(value => {\n * if (value === 'declined') return false;\n * });\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return a Promise for the Dependency Injection value that matches the token\n */\n getAsync(token: any): Promise;\n /** Asynchronously gets a value as type `T` (generics parameter) */\n getAsync(token: any): Promise;\n\n /**\n * Gets a value from the native injector\n *\n * Returns a value from the native injector, bypassing anything in the [[ResolveContext]].\n *\n * Example:\n * ```js\n * let someThing = injector.getNative(SomeToken);\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n getNative(token: any): any;\n getNative(token: any): T;\n}\n\n/** @internalapi */\nexport interface UIRouterPlugin extends Disposable {\n name: string;\n}\n\n/** @internalapi */\nexport abstract class UIRouterPluginBase implements UIRouterPlugin, Disposable {\n abstract name: string;\n dispose(router: UIRouter) {}\n}\n\n/** @internalapi */\nexport interface Disposable {\n /** Instructs the Disposable to clean up any resources */\n dispose(router?: UIRouter);\n}\n", "/**\n * @coreapi\n * @module common\n */ /** */\n\nexport * from './common/index';\nexport * from './params/index';\nexport * from './path/index';\nexport * from './resolve/index';\nexport * from './state/index';\nexport * from './transition/index';\nexport * from './url/index';\nexport * from './view/index';\nexport * from './globals';\n\nexport * from './router';\nexport * from './vanilla';\nexport * from './interface';\n", - "/** @module ng1 */ /** */\nimport { ng as angular } from '../angular';\nimport {\n StateObject, pick, forEach, tail, extend,\n isArray, isInjectable, isDefined, isString, services, trace,\n ViewConfig, ViewService, ViewConfigFactory, PathNode, ResolveContext, Resolvable, IInjectable,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration } from '../interface';\nimport { TemplateFactory } from '../templateFactory';\nimport IInjectorService = angular.auto.IInjectorService;\n\nexport function getNg1ViewConfigFactory(): ViewConfigFactory {\n let templateFactory: TemplateFactory = null;\n return (path, view) => {\n templateFactory = templateFactory || services.$injector.get('$templateFactory');\n return [new Ng1ViewConfig(path, view, templateFactory)];\n };\n}\n\nconst hasAnyKey = (keys, obj) =>\n keys.reduce((acc, key) => acc || isDefined(obj[key]), false);\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `views`.\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * handles the `views` property with logic specific to @uirouter/angularjs (ng1).\n *\n * If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object\n * and applies the state-level configuration to a view named `$default`.\n */\nexport function ng1ViewsBuilder(state: StateObject) {\n // Do not process root state\n if (!state.parent) return {};\n\n const tplKeys = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'],\n ctrlKeys = ['controller', 'controllerProvider', 'controllerAs', 'resolveAs'],\n compKeys = ['component', 'bindings', 'componentProvider'],\n nonCompKeys = tplKeys.concat(ctrlKeys),\n allViewKeys = compKeys.concat(nonCompKeys);\n\n // Do not allow a state to have both state-level props and also a `views: {}` property.\n // A state without a `views: {}` property can declare properties for the `$default` view as properties of the state.\n // However, the `$default` approach should not be mixed with a separate `views: ` block.\n if (isDefined(state.views) && hasAnyKey(allViewKeys, state)) {\n throw new Error(`State '${state.name}' has a 'views' object. ` +\n `It cannot also have \"view properties\" at the state level. ` +\n `Move the following properties into a view (in the 'views' object): ` +\n ` ${allViewKeys.filter(key => isDefined(state[key])).join(', ')}`);\n }\n\n const views: { [key: string]: Ng1ViewDeclaration } = {},\n viewsObject = state.views || { '$default': pick(state, allViewKeys) };\n\n forEach(viewsObject, function (config: Ng1ViewDeclaration, name: string) {\n // Account for views: { \"\": { template... } }\n name = name || '$default';\n // Account for views: { header: \"headerComponent\" }\n if (isString(config)) config = { component: config };\n\n // Make a shallow copy of the config object\n config = extend({}, config);\n\n // Do not allow a view to mix props for component-style view with props for template/controller-style view\n if (hasAnyKey(compKeys, config) && hasAnyKey(nonCompKeys, config)) {\n throw new Error(`Cannot combine: ${compKeys.join('|')} with: ${nonCompKeys.join('|')} in stateview: '${name}@${state.name}'`);\n }\n\n config.resolveAs = config.resolveAs || '$resolve';\n config.$type = 'ng1';\n config.$context = state;\n config.$name = name;\n\n const normalized = ViewService.normalizeUIViewTarget(config.$context, config.$name);\n config.$uiViewName = normalized.uiViewName;\n config.$uiViewContextAnchor = normalized.uiViewContextAnchor;\n\n views[name] = config;\n });\n return views;\n}\n\nlet id = 0;\nexport class Ng1ViewConfig implements ViewConfig {\n $id = id++;\n loaded = false;\n controller: Function; // actually IInjectable|string\n template: string;\n component: string;\n locals: any; // TODO: delete me\n\n constructor(public path: PathNode[], public viewDecl: Ng1ViewDeclaration, public factory: TemplateFactory) { }\n\n load() {\n const $q = services.$q;\n const context = new ResolveContext(this.path);\n const params = this.path.reduce((acc, node) => extend(acc, node.paramValues), {});\n\n const promises: any = {\n template: $q.when(this.factory.fromConfig(this.viewDecl, params, context)),\n controller: $q.when(this.getController(context)),\n };\n\n return $q.all(promises).then((results) => {\n trace.traceViewServiceEvent('Loaded', this);\n this.controller = results.controller;\n extend(this, results.template); // Either { template: \"tpl\" } or { component: \"cmpName\" }\n return this;\n });\n }\n\n getTemplate = (uiView, context: ResolveContext) =>\n this.component ? this.factory.makeComponentTemplate(uiView, context, this.component, this.viewDecl.bindings) : this.template;\n\n /**\n * Gets the controller for a view configuration.\n *\n * @returns {Function|Promise.} Returns a controller, or a promise that resolves to a controller.\n */\n getController(context: ResolveContext): (IInjectable|string|Promise) {\n const provider = this.viewDecl.controllerProvider;\n if (!isInjectable(provider)) return this.viewDecl.controller;\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail( provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n}\n", - "/** @module view */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport { IAugmentedJQuery } from 'angular';\nimport {\n isArray, isDefined, isFunction, isObject, services, Obj, IInjectable, tail, kebobString, unnestR, ResolveContext,\n Resolvable, RawParams,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration, TemplateFactoryProvider } from './interface';\n\n/**\n * Service which manages loading of templates from a ViewConfig.\n */\nexport class TemplateFactory implements TemplateFactoryProvider {\n /** @hidden */ private _useHttp = angular.version.minor < 3;\n /** @hidden */ private $templateRequest;\n /** @hidden */ private $templateCache;\n /** @hidden */ private $http;\n\n /** @hidden */ $get = ['$http', '$templateCache', '$injector', ($http, $templateCache, $injector) => {\n this.$templateRequest = $injector.has && $injector.has('$templateRequest') && $injector.get('$templateRequest');\n this.$http = $http;\n this.$templateCache = $templateCache;\n return this;\n }];\n\n /** @hidden */\n useHttpService(value: boolean) {\n this._useHttp = value;\n }\n\n /**\n * Creates a template from a configuration object.\n *\n * @param config Configuration object for which to load a template.\n * The following properties are search in the specified order, and the first one\n * that is defined is used to create the template:\n *\n * @param params Parameters to pass to the template function.\n * @param context The resolve context associated with the template's view\n *\n * @return {string|object} The template html as a string, or a promise for\n * that string,or `null` if no template is configured.\n */\n fromConfig(config: Ng1ViewDeclaration, params: any, context: ResolveContext): Promise<{ template?: string, component?: string }> {\n const defaultTemplate = '';\n\n const asTemplate = (result) => services.$q.when(result).then(str => ({ template: str }));\n const asComponent = (result) => services.$q.when(result).then(str => ({ component: str }));\n\n return (\n isDefined(config.template) ? asTemplate(this.fromString(config.template, params)) :\n isDefined(config.templateUrl) ? asTemplate(this.fromUrl(config.templateUrl, params)) :\n isDefined(config.templateProvider) ? asTemplate(this.fromProvider(config.templateProvider, params, context)) :\n isDefined(config.component) ? asComponent(config.component) :\n isDefined(config.componentProvider) ? asComponent(this.fromComponentProvider(config.componentProvider, params, context)) :\n asTemplate(defaultTemplate)\n );\n }\n\n /**\n * Creates a template from a string or a function returning a string.\n *\n * @param template html template as a string or function that returns an html template as a string.\n * @param params Parameters to pass to the template function.\n *\n * @return {string|object} The template html as a string, or a promise for that\n * string.\n */\n fromString(template: (string | Function), params?: RawParams) {\n return isFunction(template) ? ( template)(params) : template;\n }\n\n /**\n * Loads a template from the a URL via `$http` and `$templateCache`.\n *\n * @param {string|Function} url url of the template to load, or a function\n * that returns a url.\n * @param {Object} params Parameters to pass to the url function.\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromUrl(url: (string | Function), params: any) {\n if (isFunction(url)) url = ( url)(params);\n if (url == null) return null;\n\n if (this._useHttp) {\n return this.$http.get(url, { cache: this.$templateCache, headers: { Accept: 'text/html' } })\n .then(function (response) {\n return response.data;\n });\n }\n\n return this.$templateRequest(url);\n }\n\n /**\n * Creates a template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail( provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a component's template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string} The template html as a string: \"\".\n */\n fromComponentProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail( provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a template from a component's name\n *\n * This implements route-to-component.\n * It works by retrieving the component (directive) metadata from the injector.\n * It analyses the component's bindings, then constructs a template that instantiates the component.\n * The template wires input and output bindings to resolves or from the parent component.\n *\n * @param uiView {object} The parent ui-view (for binding outputs to callbacks)\n * @param context The ResolveContext (for binding outputs to callbacks returned from resolves)\n * @param component {string} Component's name in camel case.\n * @param bindings An object defining the component's bindings: {foo: '<'}\n * @return {string} The template as a string: \"\".\n */\n makeComponentTemplate(uiView: IAugmentedJQuery, context: ResolveContext, component: string, bindings?: any) {\n bindings = bindings || {};\n\n // Bind once prefix\n const prefix = angular.version.minor >= 3 ? '::' : '';\n // Convert to kebob name. Add x- prefix if the string starts with `x-` or `data-`\n const kebob = (camelCase: string) => {\n const kebobed = kebobString(camelCase);\n return /^(x|data)-/.exec(kebobed) ? `x-${kebobed}` : kebobed;\n };\n\n\n const attributeTpl = (input: BindingTuple) => {\n const { name, type } = input;\n const attrName = kebob(name);\n // If the ui-view has an attribute which matches a binding on the routed component\n // then pass that attribute through to the routed component template.\n // Prefer ui-view wired mappings to resolve data, unless the resolve was explicitly bound using `bindings:`\n if (uiView.attr(attrName) && !bindings[name])\n return `${attrName}='${uiView.attr(attrName)}'`;\n\n const resolveName = bindings[name] || name;\n // Pre-evaluate the expression for \"@\" bindings by enclosing in {{ }}\n // some-attr=\"{{ ::$resolve.someResolveName }}\"\n if (type === '@')\n return `${attrName}='{{${prefix}$resolve.${resolveName}}}'`;\n\n // Wire \"&\" callbacks to resolves that return a callback function\n // Get the result of the resolve (should be a function) and annotate it to get its arguments.\n // some-attr=\"$resolve.someResolveResultName(foo, bar)\"\n if (type === '&') {\n const res = context.getResolvable(resolveName);\n const fn = res && res.data;\n const args = fn && services.$injector.annotate(fn) || [];\n // account for array style injection, i.e., ['foo', function(foo) {}]\n const arrayIdxStr = isArray(fn) ? `[${fn.length - 1}]` : '';\n return `${attrName}='$resolve.${resolveName}${arrayIdxStr}(${args.join(',')})'`;\n }\n\n // some-attr=\"::$resolve.someResolveName\"\n return `${attrName}='${prefix}$resolve.${resolveName}'`;\n };\n\n const attrs = getComponentBindings(component).map(attributeTpl).join(' ');\n const kebobName = kebob(component);\n return `<${kebobName} ${attrs}>`;\n }\n}\n\n// Gets all the directive(s)' inputs ('@', '=', and '<') and outputs ('&')\nfunction getComponentBindings(name: string) {\n const cmpDefs = services.$injector.get(name + 'Directive'); // could be multiple\n if (!cmpDefs || !cmpDefs.length) throw new Error(`Unable to find component named '${name}'`);\n return cmpDefs.map(getBindings).reduce(unnestR, []);\n}\n\n// Given a directive definition, find its object input attributes\n// Use different properties, depending on the type of directive (component, bindToController, normal)\nconst getBindings = (def: any) => {\n if (isObject(def.bindToController)) return scopeBindings(def.bindToController);\n return scopeBindings(def.scope);\n};\n\ninterface BindingTuple {\n name: string;\n type: string;\n}\n\n// for ng 1.2 style, process the scope: { input: \"=foo\" }\n// for ng 1.3 through ng 1.5, process the component's bindToController: { input: \"=foo\" } object\nconst scopeBindings = (bindingsObj: Obj) => Object.keys(bindingsObj || {})\n // [ 'input', [ '=foo', '=', 'foo' ] ]\n .map(key => [key, /^([=<@&])[?]?(.*)/.exec(bindingsObj[key])])\n // skip malformed values\n .filter(tuple => isDefined(tuple) && isArray(tuple[1]))\n // { name: ('foo' || 'input'), type: '=' }\n .map(tuple => ({ name: tuple[1][2] || tuple[0], type: tuple[1][1] } as BindingTuple));\n\n", - "/** @module ng1 */ /** for typedoc */\nimport {\n val, isObject, createProxyFunctions, BuilderFunction, StateRegistry, StateService, OnInvalidCallback,\n} from '@uirouter/core';\nimport { Ng1StateDeclaration } from './interface';\n\n/**\n * The Angular 1 `StateProvider`\n *\n * The `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\nexport class StateProvider {\n constructor(private stateRegistry: StateRegistry, private stateService: StateService) {\n createProxyFunctions(val(StateProvider.prototype), this, val(this));\n }\n\n /**\n * Decorates states when they are registered\n *\n * Allows you to extend (carefully) or override (at your own peril) the\n * `stateBuilder` object used internally by [[StateRegistry]].\n * This can be used to add custom functionality to ui-router,\n * for example inferring templateUrl based on the state name.\n *\n * When passing only a name, it returns the current (original or decorated) builder\n * function that matches `name`.\n *\n * The builder functions that can be decorated are listed below. Though not all\n * necessarily have a good use case for decoration, that is up to you to decide.\n *\n * In addition, users can attach custom decorators, which will generate new\n * properties within the state's internal definition. There is currently no clear\n * use-case for this beyond accessing internal states (i.e. $state.$current),\n * however, expect this to become increasingly relevant as we introduce additional\n * meta-programming features.\n *\n * **Warning**: Decorators should not be interdependent because the order of\n * execution of the builder functions in non-deterministic. Builder functions\n * should only be dependent on the state definition object and super function.\n *\n *\n * Existing builder functions and current return values:\n *\n * - **parent** `{object}` - returns the parent state object.\n * - **data** `{object}` - returns state data, including any inherited data that is not\n * overridden by own values (if any).\n * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n * or `null`.\n * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is\n * navigable).\n * - **params** `{object}` - returns an array of state params that are ensured to\n * be a super-set of parent's params.\n * - **views** `{object}` - returns a views object where each key is an absolute view\n * name (i.e. \"viewName@stateName\") and each value is the config object\n * (template, controller) for the view. Even when you don't use the views object\n * explicitly on a state config, one is still created for you internally.\n * So by decorating this builder function you have access to decorating template\n * and controller properties.\n * - **ownParams** `{object}` - returns an array of params that belong to the state,\n * not including any params defined by ancestor states.\n * - **path** `{string}` - returns the full path from the root down to this state.\n * Needed for state activation.\n * - **includes** `{object}` - returns an object that includes every state that\n * would pass a `$state.includes()` test.\n *\n * #### Example:\n * Override the internal 'views' builder with a function that takes the state\n * definition, and a reference to the internal function being overridden:\n * ```js\n * $stateProvider.decorator('views', function (state, parent) {\n * let result = {},\n * views = parent(state);\n *\n * angular.forEach(views, function (config, name) {\n * let autoName = (state.name + '.' + name).replace('.', '/');\n * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n * result[name] = config;\n * });\n * return result;\n * });\n *\n * $stateProvider.state('home', {\n * views: {\n * 'contact.list': { controller: 'ListController' },\n * 'contact.item': { controller: 'ItemController' }\n * }\n * });\n * ```\n *\n *\n * ```js\n * // Auto-populates list and item views with /partials/home/contact/list.html,\n * // and /partials/home/contact/item.html, respectively.\n * $state.go('home');\n * ```\n *\n * @param {string} name The name of the builder function to decorate.\n * @param {object} func A function that is responsible for decorating the original\n * builder function. The function receives two parameters:\n *\n * - `{object}` - state - The state config object.\n * - `{object}` - super - The original builder function.\n *\n * @return {object} $stateProvider - $stateProvider instance\n */\n decorator(name: string, func: BuilderFunction) {\n return this.stateRegistry.decorator(name, func) || this;\n }\n\n /**\n * Registers a state\n *\n * ### This is a passthrough to [[StateRegistry.register]].\n *\n * Registers a state configuration under a given state name.\n * The stateConfig object has the following acceptable properties.\n *\n *
    \n *\n * - **`template`** - {string|function=} - html template as a string or a function that returns\n * an html template as a string which should be used by the uiView directives. This property\n * takes precedence over templateUrl.\n *\n * If `template` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateUrl`** - {string|function=} - path or function that returns a path to an html\n * template that should be used by uiView.\n *\n * If `templateUrl` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateProvider`** - {function=} - Provider function that returns HTML content\n * string.\n *\n * \n *\n * - **`controller`** - {string|function=} - Controller fn that should be associated with newly\n * related scope or the name of a registered controller if passed as a string.\n *\n * \n *\n * - **`controllerProvider`** - {function=} - Injectable provider function that returns\n * the actual controller or string.\n *\n * \n *\n * - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be\n * published to scope under the controllerAs name.\n *\n * \n *\n * - **`resolve`** - {object.<string, function>=} - An optional map of dependencies which\n * should be injected into the controller. If any of these dependencies are promises,\n * the router will wait for them all to be resolved or one to be rejected before the\n * controller is instantiated. If all the promises are resolved successfully, the values\n * of the resolved promises are injected and $stateChangeSuccess event is fired. If any\n * of the promises are rejected the $stateChangeError event is fired. The map object is:\n *\n * - key - {string}: name of dependency to be injected into controller\n * - factory - {string|function}: If string then it is alias for service. Otherwise if function,\n * it is injected and return value it treated as dependency. If result is a promise, it is\n * resolved before its value is injected into controller.\n *\n * \n *\n * - **`url`** - {string=} - A url with optional parameters. When a state is navigated or\n * transitioned to, the `$stateParams` service will be populated with any\n * parameters that were passed.\n *\n * \n *\n * - **`params`** - {object=} - An array of parameter names or regular expressions. Only\n * use this within a state if you are not using url. Otherwise you can specify your\n * parameters within the url. When a state is navigated or transitioned to, the\n * $stateParams service will be populated with any parameters that were passed.\n *\n * \n *\n * - **`views`** - {object=} - Use the views property to set up multiple views or to target views\n * manually/explicitly.\n *\n * \n *\n * - **`abstract`** - {boolean=} - An abstract state will never be directly activated,\n * but can provide inherited properties to its common children states.\n *\n * \n *\n * - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way\n * to trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to\n * trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state\n * just because a search/query parameter has changed (via $location.search() or $location.hash()).\n * Useful for when you'd like to modify $location.search() without triggering a reload.\n *\n * \n *\n * - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.\n *\n * #### Example:\n * Some state name examples\n * ```js\n * // stateName can be a single top-level name (must be unique).\n * $stateProvider.state(\"home\", {});\n *\n * // Or it can be a nested state name. This state is a child of the\n * // above \"home\" state.\n * $stateProvider.state(\"home.newest\", {});\n *\n * // Nest states as deeply as needed.\n * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n *\n * // state() returns $stateProvider, so you can chain state declarations.\n * $stateProvider\n * .state(\"home\", {})\n * .state(\"about\", {})\n * .state(\"contacts\", {});\n * ```\n *\n * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n * @param {object} definition State configuration object.\n */\n state(name: string, definition: Ng1StateDeclaration): StateProvider;\n state(definition: Ng1StateDeclaration): StateProvider;\n state(name: any, definition?: any) {\n if (isObject(name)) {\n definition = name;\n } else {\n definition.name = name;\n }\n this.stateRegistry.register(definition);\n return this;\n }\n\n /**\n * Registers an invalid state handler\n *\n * This is a passthrough to [[StateService.onInvalid]] for ng1.\n */\n\n onInvalid(callback: OnInvalidCallback): Function {\n return this.stateService.onInvalid(callback);\n }\n}\n", - "/** @module ng1 */ /** */\nimport {\n StateObject, TransitionStateHookFn, HookResult, Transition, services, ResolveContext, extend, BuilderFunction,\n} from '@uirouter/core';\nimport { getLocals } from '../services';\nimport { Ng1StateDeclaration } from '../interface';\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,\n * `onRetain` callback hooks on a [[Ng1StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * ensures that those hooks are injectable for @uirouter/angularjs (ng1).\n */\nexport const getStateHookBuilder = (hookName: 'onEnter'|'onExit'|'onRetain') =>\nfunction stateHookBuilder(stateObject: StateObject, parentFn: BuilderFunction): TransitionStateHookFn {\n const hook = stateObject[hookName];\n const pathname = hookName === 'onExit' ? 'from' : 'to';\n\n function decoratedNg1Hook(trans: Transition, state: Ng1StateDeclaration): HookResult {\n const resolveContext = new ResolveContext(trans.treeChanges(pathname));\n const subContext = resolveContext.subContext(state.$$state());\n const locals = extend(getLocals(subContext), { $state$: state, $transition$: trans });\n return services.$injector.invoke(hook, this, locals);\n }\n\n return hook ? decoratedNg1Hook : undefined;\n};\n", - "/**\n * @internalapi\n * @module ng1\n */ /** */\nimport { LocationConfig, LocationServices, UIRouter, ParamType, isDefined } from '@uirouter/core';\nimport { val, createProxyFunctions, removeFrom, isObject } from '@uirouter/core';\nimport { ILocationService, ILocationProvider } from 'angular';\n\n/**\n * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service\n */\nexport class Ng1LocationServices implements LocationConfig, LocationServices {\n private $locationProvider: ILocationProvider;\n private $location: ILocationService;\n private $sniffer;\n\n path;\n search;\n hash;\n hashPrefix;\n port;\n protocol;\n host;\n baseHref;\n\n // .onChange() registry\n private _urlListeners: Function[] = [];\n\n /**\n * Applys ng1-specific path parameter encoding\n *\n * The Angular 1 `$location` service is a bit weird.\n * It doesn't allow slashes to be encoded/decoded bi-directionally.\n *\n * See the writeup at https://github.com/angular-ui/ui-router/issues/2598\n *\n * This code patches the `path` parameter type so it encoded/decodes slashes as ~2F\n *\n * @param router\n */\n static monkeyPatchPathParameterType(router: UIRouter) {\n const pathType: ParamType = router.urlMatcherFactory.type('path');\n\n pathType.encode = (x: any) =>\n x != null ? x.toString().replace(/(~|\\/)/g, m => ({ '~': '~~', '/': '~2F' }[m])) : x;\n\n pathType.decode = (x: string) =>\n x != null ? x.toString().replace(/(~~|~2F)/g, m => ({ '~~': '~', '~2F': '/' }[m])) : x;\n\n }\n\n dispose() { }\n\n constructor($locationProvider: ILocationProvider) {\n this.$locationProvider = $locationProvider;\n const _lp = val($locationProvider);\n createProxyFunctions(_lp, this, _lp, ['hashPrefix']);\n }\n\n onChange(callback: Function) {\n this._urlListeners.push(callback);\n return () => removeFrom(this._urlListeners)(callback);\n }\n\n html5Mode() {\n let html5Mode: any = this.$locationProvider.html5Mode();\n html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode;\n return html5Mode && this.$sniffer.history;\n }\n\n url(newUrl?: string, replace = false, state?) {\n if (isDefined(newUrl)) this.$location.url(newUrl);\n if (replace) this.$location.replace();\n if (state) this.$location.state(state);\n return this.$location.url();\n }\n\n _runtimeServices($rootScope, $location: ILocationService, $sniffer, $browser) {\n this.$location = $location;\n this.$sniffer = $sniffer;\n\n // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange\n $rootScope.$on('$locationChangeSuccess', evt => this._urlListeners.forEach(fn => fn(evt)));\n const _loc = val($location);\n const _browser = val($browser);\n\n // Bind these LocationService functions to $location\n createProxyFunctions(_loc, this, _loc, ['replace', 'path', 'search', 'hash']);\n // Bind these LocationConfig functions to $location\n createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);\n // Bind these LocationConfig functions to $browser\n createProxyFunctions(_browser, this, _browser, ['baseHref']);\n }\n}\n", - "/** @module url */ /** */\nimport {\n UIRouter, UrlRouter, LocationServices, $InjectorLike, BaseUrlRule, UrlRuleHandlerFn, UrlMatcher,\n IInjectable,\n} from '@uirouter/core';\nimport { services, isString, isFunction, isArray, identity } from '@uirouter/core';\n\nexport interface RawNg1RuleFunction {\n ($injector: $InjectorLike, $location: LocationServices): string|void;\n}\n\n/**\n * Manages rules for client-side URL\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class manages the router rules for what to do when the URL changes.\n *\n * This provider remains for backwards compatibility.\n *\n * @deprecated\n */\nexport class UrlRouterProvider {\n /** @hidden */ _router: UIRouter;\n /** @hidden */ _urlRouter: UrlRouter;\n\n static injectableHandler(router: UIRouter, handler): UrlRuleHandlerFn {\n return match =>\n services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params });\n }\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this._urlRouter = router.urlRouter;\n }\n\n /** @hidden */\n $get() {\n const urlRouter = this._urlRouter;\n urlRouter.update(true);\n if (!urlRouter.interceptDeferred) urlRouter.listen();\n return urlRouter;\n }\n\n /**\n * Registers a url handler function.\n *\n * Registers a low level url handler (a `rule`).\n * A rule detects specific URL patterns and returns a redirect, or performs some action.\n *\n * If a rule returns a string, the URL is replaced with the string, and all rules are fired again.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Here's an example of how you might allow case insensitive urls\n * $urlRouterProvider.rule(function ($injector, $location) {\n * var path = $location.path(),\n * normalized = path.toLowerCase();\n *\n * if (path !== normalized) {\n * return normalized;\n * }\n * });\n * });\n * ```\n *\n * @param ruleFn\n * Handler function that takes `$injector` and `$location` services as arguments.\n * You can use them to detect a url and return a different url as a string.\n *\n * @return [[UrlRouterProvider]] (`this`)\n */\n rule(ruleFn: RawNg1RuleFunction): UrlRouterProvider {\n if (!isFunction(ruleFn)) throw new Error(\"'rule' must be a function\");\n\n const match = () =>\n ruleFn(services.$injector, this._router.locationService);\n\n const rule = new BaseUrlRule(match, identity);\n this._urlRouter.rule(rule);\n return this;\n }\n\n /**\n * Defines the path or behavior to use when no url can be matched.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // if the path doesn't match any of the urls you configured\n * // otherwise will take care of routing the user to the\n * // specified url\n * $urlRouterProvider.otherwise('/index');\n *\n * // Example of using function rule as param\n * $urlRouterProvider.otherwise(function ($injector, $location) {\n * return '/a/valid/url';\n * });\n * });\n * ```\n *\n * @param rule\n * The url path you want to redirect to or a function rule that returns the url path or performs a `$state.go()`.\n * The function version is passed two params: `$injector` and `$location` services, and should return a url string.\n *\n * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n */\n otherwise(rule: string | RawNg1RuleFunction): UrlRouterProvider {\n const urlRouter = this._urlRouter;\n\n if (isString(rule)) {\n urlRouter.otherwise(rule);\n } else if (isFunction(rule)) {\n urlRouter.otherwise(() => rule(services.$injector, this._router.locationService));\n } else {\n throw new Error(\"'rule' must be a string or function\");\n }\n\n return this;\n }\n\n /**\n * Registers a handler for a given url matching.\n *\n * If the handler is a string, it is\n * treated as a redirect, and is interpolated according to the syntax of match\n * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n *\n * If the handler is a function, it is injectable.\n * It gets invoked if `$location` matches.\n * You have the option of inject the match object as `$match`.\n *\n * The handler can return\n *\n * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n * will continue trying to find another one that matches.\n * - **string** which is treated as a redirect and passed to `$location.url()`\n * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n * if ($state.$current.navigable !== state ||\n * !equalForKeys($match, $stateParams) {\n * $state.transitionTo(state, $match, false);\n * }\n * });\n * });\n * ```\n *\n * @param what A pattern string to match, compiled as a [[UrlMatcher]].\n * @param handler The path (or function that returns a path) that you want to redirect your user to.\n * @param ruleCallback [optional] A callback that receives the `rule` registered with [[UrlMatcher.rule]]\n *\n * Note: the handler may also invoke arbitrary code, such as `$state.go()`\n */\n when(what: (RegExp|UrlMatcher|string), handler: string|IInjectable) {\n if (isArray(handler) || isFunction(handler)) {\n handler = UrlRouterProvider.injectableHandler(this._router, handler);\n }\n\n this._urlRouter.when(what, handler as any);\n return this;\n }\n\n /**\n * Disables monitoring of the URL.\n *\n * Call this method before UI-Router has bootstrapped.\n * It will stop UI-Router from performing the initial url sync.\n *\n * This can be useful to perform some asynchronous initialization before the router starts.\n * Once the initialization is complete, call [[listen]] to tell UI-Router to start watching and synchronizing the URL.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Prevent $urlRouter from automatically intercepting URL changes;\n * $urlRouterProvider.deferIntercept();\n * })\n *\n * app.run(function (MyService, $urlRouter, $http) {\n * $http.get(\"/stuff\").then(function(resp) {\n * MyService.doStuff(resp.data);\n * $urlRouter.listen();\n * $urlRouter.sync();\n * });\n * });\n * ```\n *\n * @param defer Indicates whether to defer location change interception.\n * Passing no parameter is equivalent to `true`.\n */\n deferIntercept(defer?: boolean) {\n this._urlRouter.deferIntercept(defer);\n }\n}\n", - "/**\n * # Angular 1 types\n *\n * UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc.\n * The customizations to the core types for Angular UI-Router are documented here.\n *\n * The optional [[$resolve]] service is also documented here.\n *\n * @module ng1\n * @preferred\n */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport {\n IRootScopeService, IQService, ILocationService, ILocationProvider, IHttpService, ITemplateCacheService,\n} from 'angular';\nimport {\n services, applyPairs, isString, trace, extend, UIRouter, StateService, UrlRouter, UrlMatcherFactory, ResolveContext,\n unnestR, TypedMap,\n} from '@uirouter/core';\nimport { ng1ViewsBuilder, getNg1ViewConfigFactory } from './statebuilders/views';\nimport { TemplateFactory } from './templateFactory';\nimport { StateProvider } from './stateProvider';\nimport { getStateHookBuilder } from './statebuilders/onEnterExitRetain';\nimport { Ng1LocationServices } from './locationServices';\nimport { UrlRouterProvider } from './urlRouterProvider';\nimport IInjectorService = angular.auto.IInjectorService; // tslint:disable-line\n\nangular.module('ui.router.angular1', []);\nconst mod_init = angular.module('ui.router.init', []);\nconst mod_util = angular.module('ui.router.util', ['ng', 'ui.router.init']);\nconst mod_rtr = angular.module('ui.router.router', ['ui.router.util']);\nconst mod_state = angular.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']);\nconst mod_main = angular.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']);\nlet mod_cmpt = angular.module('ui.router.compat', ['ui.router']); // tslint:disable-line\n\ndeclare module '@uirouter/core/lib/router' {\n interface UIRouter { // tslint:disable-line:no-shadowed-variable\n /** @hidden */\n stateProvider: StateProvider;\n /** @hidden */\n urlRouterProvider: UrlRouterProvider;\n }\n}\n\nlet router: UIRouter = null;\n\n$uiRouterProvider.$inject = ['$locationProvider'];\n/** This angular 1 provider instantiates a Router and exposes its services via the angular injector */\nfunction $uiRouterProvider($locationProvider: ILocationProvider) {\n\n // Create a new instance of the Router when the $uiRouterProvider is initialized\n router = this.router = new UIRouter();\n router.stateProvider = new StateProvider(router.stateRegistry, router.stateService);\n\n // Apply ng1 specific StateBuilder code for `views`, `resolve`, and `onExit/Retain/Enter` properties\n router.stateRegistry.decorator('views', ng1ViewsBuilder);\n router.stateRegistry.decorator('onExit', getStateHookBuilder('onExit'));\n router.stateRegistry.decorator('onRetain', getStateHookBuilder('onRetain'));\n router.stateRegistry.decorator('onEnter', getStateHookBuilder('onEnter'));\n\n router.viewService._pluginapi._viewConfigFactory('ng1', getNg1ViewConfigFactory());\n\n const ng1LocationService = router.locationService = router.locationConfig = new Ng1LocationServices($locationProvider);\n\n Ng1LocationServices.monkeyPatchPathParameterType(router);\n\n // backwards compat: also expose router instance as $uiRouterProvider.router\n router['router'] = router;\n router['$get'] = $get;\n $get.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache'];\n function $get($location: ILocationService, $browser: any, $sniffer: any, $rootScope: ng.IScope, $http: IHttpService, $templateCache: ITemplateCacheService) {\n ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser);\n delete router['router'];\n delete router['$get'];\n return router;\n }\n return router;\n}\n\nconst getProviderFor = (serviceName) => [ '$uiRouterProvider', ($urp) => {\n const service = $urp.router[serviceName];\n service['$get'] = () => service;\n return service;\n}];\n\n// This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime)\nrunBlock.$inject = ['$injector', '$q', '$uiRouter'];\nfunction runBlock($injector: IInjectorService, $q: IQService, $uiRouter: UIRouter) {\n services.$injector = $injector;\n services.$q = $q;\n\n // The $injector is now available.\n // Find any resolvables that had dependency annotation deferred\n $uiRouter.stateRegistry.get()\n .map(x => x.$$state().resolvables)\n .reduce(unnestR, [])\n .filter(x => x.deps === 'deferred')\n .forEach(resolvable => resolvable.deps = $injector.annotate(resolvable.resolveFn, $injector.strictDi));\n}\n\n// $urlRouter service and $urlRouterProvider\nconst getUrlRouterProvider = (uiRouter: UIRouter) =>\n uiRouter.urlRouterProvider = new UrlRouterProvider(uiRouter);\n\n// $state service and $stateProvider\n// $urlRouter service and $urlRouterProvider\nconst getStateProvider = () =>\n extend(router.stateProvider, { $get: () => router.stateService });\n\nwatchDigests.$inject = ['$rootScope'];\nexport function watchDigests($rootScope: IRootScopeService) {\n $rootScope.$watch(function() { trace.approximateDigests++; });\n}\n\nmod_init .provider('$uiRouter', $uiRouterProvider);\nmod_rtr .provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]);\nmod_util .provider('$urlService', getProviderFor('urlService'));\nmod_util .provider('$urlMatcherFactory', ['$uiRouterProvider', () => router.urlMatcherFactory]);\nmod_util .provider('$templateFactory', () => new TemplateFactory());\nmod_state.provider('$stateRegistry', getProviderFor('stateRegistry'));\nmod_state.provider('$uiRouterGlobals', getProviderFor('globals'));\nmod_state.provider('$transitions', getProviderFor('transitionService'));\nmod_state.provider('$state', ['$uiRouterProvider', getStateProvider]);\n\nmod_state.factory ('$stateParams', ['$uiRouter', ($uiRouter: UIRouter) => $uiRouter.globals.params]);\nmod_main .factory ('$view', () => router.viewService);\nmod_main .service ('$trace', () => trace);\n\nmod_main .run (watchDigests);\nmod_util .run (['$urlMatcherFactory', function ($urlMatcherFactory: UrlMatcherFactory) { }]);\nmod_state.run (['$state', function ($state: StateService) { }]);\nmod_rtr .run (['$urlRouter', function ($urlRouter: UrlRouter) { }]);\nmod_init .run (runBlock);\n\n/** @hidden TODO: find a place to move this */\nexport const getLocals = (ctx: ResolveContext): TypedMap => {\n const tokens = ctx.getTokens().filter(isString);\n\n const tuples = tokens .map(key => {\n const resolvable = ctx.getResolvable(key);\n const waitPolicy = ctx.getPolicy(resolvable).async;\n return [ key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data ];\n });\n\n return tuples.reduce(applyPairs, {});\n};\n\n", - "/**\n * # Angular 1 injectable services\n *\n * This is a list of the objects which can be injected using angular's injector.\n *\n * There are three different kind of injectable objects:\n *\n * ## **Provider** objects\n * #### injectable into a `.config()` block during configtime\n *\n * - [[$uiRouterProvider]]: The UI-Router instance\n * - [[$stateProvider]]: State registration\n * - [[$transitionsProvider]]: Transition hooks\n * - [[$urlServiceProvider]]: All URL related public APIs\n *\n * - [[$uiViewScrollProvider]]: Disable ui-router view scrolling\n * - [[$urlRouterProvider]]: (deprecated) Url matching rules\n * - [[$urlMatcherFactoryProvider]]: (deprecated) Url parsing config\n *\n * ## **Service** objects\n * #### injectable globally during runtime\n *\n * - [[$uiRouter]]: The UI-Router instance\n * - [[$trace]]: Enable transition trace/debug\n * - [[$transitions]]: Transition hooks\n * - [[$state]]: Imperative state related APIs\n * - [[$stateRegistry]]: State registration\n * - [[$urlService]]: All URL related public APIs\n * - [[$uiRouterGlobals]]: Global variables\n * - [[$uiViewScroll]]: Scroll an element into view\n *\n * - [[$stateParams]]: (deprecated) Global state param values\n * - [[$urlRouter]]: (deprecated) URL synchronization\n * - [[$urlMatcherFactory]]: (deprecated) URL parsing config\n *\n * ## **Per-Transition** objects\n *\n * - These kind of objects are injectable into:\n * - Resolves ([[Ng1StateDeclaration.resolve]]),\n * - Transition Hooks ([[TransitionService.onStart]], etc),\n * - Routed Controllers ([[Ng1ViewDeclaration.controller]])\n *\n * #### Different instances are injected based on the [[Transition]]\n *\n * - [[$transition$]]: The current Transition object\n * - [[$stateParams]]: State param values for pending Transition (deprecated)\n * - Any resolve data defined using [[Ng1StateDeclaration.resolve]]\n *\n * @ng1api\n * @preferred\n * @module injectables\n */ /** */\n/* tslint:disable:prefer-const */\nimport { StateProvider } from './stateProvider';\nimport {\n StateService, TransitionService, Transition, UrlRouter, UrlMatcherFactory,\n StateParams, StateRegistry, UIRouterGlobals, UIRouter, Trace, UrlService,\n} from '@uirouter/core';\nimport { UIViewScrollProvider } from './viewScroll';\nimport { UrlRouterProvider } from './urlRouterProvider';\n\n/**\n * The current (or pending) State Parameters\n *\n * An injectable global **Service Object** which holds the state parameters for the latest **SUCCESSFUL** transition.\n *\n * The values are not updated until *after* a `Transition` successfully completes.\n *\n * **Also:** an injectable **Per-Transition Object** object which holds the pending state parameters for the pending `Transition` currently running.\n *\n * ### Deprecation warning:\n *\n * The value injected for `$stateParams` is different depending on where it is injected.\n *\n * - When injected into an angular service, the object injected is the global **Service Object** with the parameter values for the latest successful `Transition`.\n * - When injected into transition hooks, resolves, or view controllers, the object is the **Per-Transition Object** with the parameter values for the running `Transition`.\n *\n * Because of these confusing details, this service is deprecated.\n *\n * ### Instead of using the global `$stateParams` service object,\n * inject [[$uiRouterGlobals]] and use [[UIRouterGlobals.params]]\n *\n * ```js\n * MyService.$inject = ['$uiRouterGlobals'];\n * function MyService($uiRouterGlobals) {\n * return {\n * paramValues: function () {\n * return $uiRouterGlobals.params;\n * }\n * }\n * }\n * ```\n *\n * ### Instead of using the per-transition `$stateParams` object,\n * inject the current `Transition` (as [[$transition$]]) and use [[Transition.params]]\n *\n * ```js\n * MyController.$inject = ['$transition$'];\n * function MyController($transition$) {\n * var username = $transition$.params().username;\n * // .. do something with username\n * }\n * ```\n *\n * ---\n *\n * This object can be injected into other services.\n *\n * #### Deprecated Example:\n * ```js\n * SomeService.$inject = ['$http', '$stateParams'];\n * function SomeService($http, $stateParams) {\n * return {\n * getUser: function() {\n * return $http.get('/api/users/' + $stateParams.username);\n * }\n * }\n * };\n * angular.service('SomeService', SomeService);\n * ```\n * @deprecated\n */\nlet $stateParams: StateParams;\n\n/**\n * Global UI-Router variables\n *\n * The router global state as a **Service Object** (injectable during runtime).\n *\n * This object contains globals such as the current state and current parameter values.\n */\nlet $uiRouterGlobals: UIRouterGlobals;\n\n/**\n * The UI-Router instance\n *\n * The [[UIRouter]] singleton (the router instance) as a **Service Object** (injectable during runtime).\n *\n * This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.\n * It has references to the other UI-Router services\n *\n * #### Note: This object is also exposed as [[$uiRouterProvider]] for injection during angular config time.\n */\nlet $uiRouter: UIRouter ;\n\n/**\n * The UI-Router instance\n *\n * The [[UIRouter]] singleton (the router instance) as a **Provider Object** (injectable during config phase).\n *\n * This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.\n * It has references to the other UI-Router services\n *\n * #### Note: This object is also exposed as [[$uiRouter]] for injection during runtime.\n */\nlet $uiRouterProvider: UIRouter;\n\n/**\n * Transition debug/tracing\n *\n * The [[Trace]] singleton as a **Service Object** (injectable during runtime).\n *\n * Enables or disables Transition tracing which can help to debug issues.\n */\nlet $trace: Trace;\n\n/**\n * The Transition Service\n *\n * The [[TransitionService]] singleton as a **Service Object** (injectable during runtime).\n *\n * This angular service exposes the [[TransitionService]] singleton, which is primarily\n * used to register global transition hooks.\n *\n * #### Note: This object is also exposed as [[$transitionsProvider]] for injection during the config phase.\n */\nlet $transitions: TransitionService;\n\n/**\n * The Transition Service\n *\n * The [[TransitionService]] singleton as a **Provider Object** (injectable during config phase)\n *\n * This angular service exposes the [[TransitionService]] singleton, which is primarily\n * used to register global transition hooks.\n *\n * #### Note: This object is also exposed as [[$transitions]] for injection during runtime.\n */\nlet $transitionsProvider: TransitionService;\n\n/**\n * The current [[Transition]] object\n *\n * The current [[Transition]] object as a **Per-Transition Object** (injectable into Resolve, Hooks, Controllers)\n *\n * This object returns information about the current transition, including:\n *\n * - To/from states\n * - To/from parameters\n * - Transition options\n * - States being entered, exited, and retained\n * - Resolve data\n * - A Promise for the transition\n * - Any transition failure information\n * - An injector for both Service and Per-Transition Objects\n */\nlet $transition$: Transition;\n\n/**\n * The State Service\n *\n * The [[StateService]] singleton as a **Service Object** (injectable during runtime).\n *\n * This service used to manage and query information on registered states.\n * It exposes state related APIs including:\n *\n * - Start a [[Transition]]\n * - Imperatively lazy load states\n * - Check if a state is currently active\n * - Look up states by name\n * - Build URLs for a state+parameters\n * - Configure the global Transition error handler\n *\n * This angular service exposes the [[StateService]] singleton.\n */\nlet $state: StateService;\n\n/**\n * The State Registry\n *\n * The [[StateRegistry]] singleton as a **Service Object** (injectable during runtime).\n *\n * This service is used to register/deregister states.\n * It has state registration related APIs including:\n *\n * - Register/deregister states\n * - Listen for state registration/deregistration\n * - Get states by name\n * - Add state decorators (to customize the state creation process)\n *\n * #### Note: This object is also exposed as [[$stateRegistryProvider]] for injection during the config phase.\n */\nlet $stateRegistry: StateRegistry;\n\n/**\n * The State Registry\n *\n * The [[StateRegistry]] singleton as a **Provider Object** (injectable during config time).\n *\n * This service is used to register/deregister states.\n * It has state registration related APIs including:\n *\n * - Register/deregister states\n * - Listen for state registration/deregistration\n * - Get states by name\n * - Add state decorators (to customize the state creation process)\n *\n * #### Note: This object is also exposed as [[$stateRegistry]] for injection during runtime.\n */\nlet $stateRegistryProvider: StateRegistry;\n\n/**\n * The View Scroll provider\n *\n * The [[UIViewScrollProvider]] as a **Provider Object** (injectable during config time).\n *\n * This angular service exposes the [[UIViewScrollProvider]] singleton and is\n * used to disable UI-Router's scroll behavior.\n */\nlet $uiViewScrollProvider: UIViewScrollProvider;\n\n/**\n * The View Scroll function\n *\n * The View Scroll function as a **Service Object** (injectable during runtime).\n *\n * This is a function that scrolls an element into view.\n * The element is scrolled after a `$timeout` so the DOM has time to refresh.\n *\n * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,\n * this can be enabled by calling [[UIViewScrollProvider.useAnchorScroll]].\n *\n * Note: this function is used by the [[directives.uiView]] when the `autoscroll` expression evaluates to true.\n */\nlet $uiViewScroll: ($element: JQuery) => void;\n\n/**\n * The StateProvider\n *\n * An angular1-only [[StateProvider]] as a **Provider Object** (injectable during config time).\n *\n * This angular service exposes the [[StateProvider]] singleton.\n *\n * The `StateProvider` is primarily used to register states or add custom state decorators.\n *\n * ##### Note: This provider is a ng1 vestige.\n * It is a passthrough to [[$stateRegistry]] and [[$state]].\n */\nlet $stateProvider: StateProvider;\n\n/**\n * The URL Service Provider\n *\n * The [[UrlService]] singleton as a **Provider Object** (injectable during the angular config phase).\n *\n * A service used to configure and interact with the URL.\n * It has URL related APIs including:\n *\n * - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])\n * - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])\n * - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])\n * - delay initial URL synchronization [[UrlService.deferIntercept]].\n * - get or set the current url: [[UrlService.url]]\n *\n * ##### Note: This service can also be injected during runtime as [[$urlService]].\n */\nlet $urlServiceProvider: UrlService;\n\n/**\n * The URL Service\n *\n * The [[UrlService]] singleton as a **Service Object** (injectable during runtime).\n *\n * Note: This service can also be injected during the config phase as [[$urlServiceProvider]].\n *\n * Used to configure the URL.\n * It has URL related APIs including:\n *\n * - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])\n * - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])\n * - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])\n * - delay initial URL synchronization [[UrlService.deferIntercept]].\n * - get or set the current url: [[UrlService.url]]\n *\n * ##### Note: This service can also be injected during the config phase as [[$urlServiceProvider]].\n */\nlet $urlService: UrlService;\n\n/**\n * The URL Router Provider\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlServiceProvider]] instead.\n *\n * The [[UrlRouter]] singleton as a **Provider Object** (injectable during config time).\n *\n * #### Note: This object is also exposed as [[$urlRouter]] for injection during runtime.\n *\n * @deprecated\n */\nlet $urlRouterProvider: UrlRouterProvider;\n\n/**\n * The Url Router\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.\n *\n * The [[UrlRouter]] singleton as a **Service Object** (injectable during runtime).\n *\n * #### Note: This object is also exposed as [[$urlRouterProvider]] for injection during angular config time.\n *\n * @deprecated\n */\nlet $urlRouter: UrlRouter;\n\n/**\n * The URL Matcher Factory\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.\n *\n * The [[UrlMatcherFactory]] singleton as a **Service Object** (injectable during runtime).\n *\n * This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.\n *\n * #### Note: This object is also exposed as [[$urlMatcherFactoryProvider]] for injection during angular config time.\n *\n * @deprecated\n */\nlet $urlMatcherFactory: UrlMatcherFactory;\n\n/**\n * The URL Matcher Factory\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.\n *\n * The [[UrlMatcherFactory]] singleton as a **Provider Object** (injectable during config time).\n *\n * This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.\n *\n * #### Note: This object is also exposed as [[$urlMatcherFactory]] for injection during runtime.\n *\n * @deprecated\n */\nlet $urlMatcherFactoryProvider: UrlMatcherFactory;\n\n\n\n", - "/**\n * # Angular 1 Directives\n *\n * These are the directives included in UI-Router for Angular 1.\n * These directives are used in templates to create viewports and link/navigate to states.\n *\n * @ng1api\n * @preferred\n * @module directives\n */ /** for typedoc */\nimport { ng as angular } from '../angular';\nimport { IAugmentedJQuery, ITimeoutService, IScope, IInterpolateService } from 'angular';\n\nimport {\n Obj, extend, forEach, tail, isString, isObject, isArray, parse, noop, unnestR, identity, uniqR, inArray, removeFrom,\n RawParams, PathNode, StateOrName, StateService, StateDeclaration, UIRouter,\n} from '@uirouter/core';\nimport { UIViewData } from './viewDirective';\nimport EventHandler = JQuery.EventHandler;\n\n/** @hidden Used for typedoc */\nexport interface ng1_directive {} // tslint:disable-line:class-name\n\n/** @hidden */\nfunction parseStateRef(ref: string) {\n let parsed;\n const paramsOnly = ref.match(/^\\s*({[^}]*})\\s*$/);\n if (paramsOnly) ref = '(' + paramsOnly[1] + ')';\n\n parsed = ref.replace(/\\n/g, ' ').match(/^\\s*([^(]*?)\\s*(\\((.*)\\))?\\s*$/);\n if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n return { state: parsed[1] || null, paramExpr: parsed[3] || null };\n}\n\n/** @hidden */\nfunction stateContext(el: IAugmentedJQuery) {\n const $uiView: UIViewData = (el.parent() as IAugmentedJQuery).inheritedData('$uiView');\n const path: PathNode[] = parse('$cfg.path')($uiView);\n return path ? tail(path).state.name : undefined;\n}\n\n/** @hidden */\nfunction processedDef($state: StateService, $element: IAugmentedJQuery, def: Def): Def {\n const uiState = def.uiState || $state.current.name;\n const uiStateOpts = extend(defaultOpts($element, $state), def.uiStateOpts || {});\n const href = $state.href(uiState, def.uiStateParams, uiStateOpts);\n return { uiState, uiStateParams: def.uiStateParams, uiStateOpts, href };\n}\n\n/** @hidden */\ninterface TypeInfo {\n attr: string;\n isAnchor: boolean;\n clickable: boolean;\n}\n\n/** @hidden */\nfunction getTypeInfo(el: IAugmentedJQuery): TypeInfo {\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n const isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';\n const isForm = el[0].nodeName === 'FORM';\n\n return {\n attr: isForm ? 'action' : (isSvg ? 'xlink:href' : 'href'),\n isAnchor: el.prop('tagName').toUpperCase() === 'A',\n clickable: !isForm,\n };\n}\n\n/** @hidden */\nfunction clickHook(el: IAugmentedJQuery, $state: StateService, $timeout: ITimeoutService, type: TypeInfo, getDef: () => Def) {\n return function (e: JQueryMouseEventObject) {\n const button = e.which || e.button, target = getDef();\n\n if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {\n // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n const transition = $timeout(function () {\n $state.go(target.uiState, target.uiStateParams, target.uiStateOpts);\n });\n e.preventDefault();\n\n // if the state has no URL, ignore one preventDefault from the directive.\n let ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;\n\n e.preventDefault = function () {\n if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);\n };\n }\n };\n}\n\n/** @hidden */\nfunction defaultOpts(el: IAugmentedJQuery, $state: StateService) {\n return {\n relative: stateContext(el) || $state.$current,\n inherit: true,\n source: 'sref',\n };\n}\n\n/** @hidden */\nfunction bindEvents(element: IAugmentedJQuery, scope: IScope, hookFn: EventHandler, uiStateOpts: any): void {\n let events;\n\n if (uiStateOpts) {\n events = uiStateOpts.events;\n }\n\n if (!isArray(events)) {\n events = ['click'];\n }\n\n const on = element.on ? 'on' : 'bind';\n for (const event of events) {\n element[on](event, hookFn);\n }\n\n scope.$on('$destroy', function() {\n const off = element.off ? 'off' : 'unbind';\n for (const event of events) {\n element[off](event, hookFn);\n }\n });\n}\n\n/**\n * `ui-sref`: A directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of the `ui-sref` is the name of the state to link to.\n *\n * #### Example:\n * This will activate the `home` state when the link is clicked.\n * ```html\n * Home\n * ```\n *\n * ### Relative Links\n * You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]).\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create a relative `ui-sref` which always targets the same destination.\n *\n * #### Example:\n * Both these links are relative to the parent state, even when a child state is currently active.\n * ```html\n * child 1 state\n * child 2 state\n * ```\n *\n * This link activates the parent state.\n * ```html\n * Return\n * ```\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * #### Example:\n * Assuming the `users` state has a url of `/users/`\n * ```html\n * Users\n * ```\n *\n * ### Parameter Values\n * In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state.\n * Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses.\n * The content inside the parentheses is an expression, evaluated to the parameter values.\n *\n * #### Example:\n * This example renders a list of links to users.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ user.displayName }}\n *
  • \n * ```\n *\n * Note:\n * The parameter values expression is `$watch`ed for updates.\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-sref-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Examples\n * If you have the following template:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n * \n * ```\n *\n * Then (assuming the current state is `contacts`) the rendered html including hrefs would be:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n *
      \n *
    • \n * Joe\n *
    • \n *
    • \n * Alice\n *
    • \n *
    • \n * Bob\n *
    • \n *
    \n *\n * Home\n * ```\n *\n * ### Notes\n *\n * - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses.\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n *\n * - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons).\n * If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive.\n */\nlet uiSrefDirective: ng1_directive;\nuiSrefDirective = ['$uiRouter', '$timeout',\n function $StateRefDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function (scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const ref = parseStateRef(attrs.uiSref);\n rawDef.uiState = ref.state;\n rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {};\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n if (ref.paramExpr) {\n scope.$watch(ref.paramExpr, function (val) {\n rawDef.uiStateParams = extend({}, val);\n update();\n }, true);\n rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr));\n }\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n }];\n\n/**\n * `ui-state`: A fully dynamic directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.**\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to.\n * **This is in contrast with `ui-sref`, which takes a state name as a string literal.**\n *\n * #### Example:\n * Create a list of links.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Relative Links\n * If the expression evaluates to a relative path, it is processed like [[uiSref]].\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create relative `ui-state` which always targets the same destination.\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * ### Parameter Values\n * In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state.\n * Param values should be provided using the `ui-state-params` attribute.\n * The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * This example renders a list of links with param values.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n * The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-state-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Notes\n *\n * - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`.\n * However, it might be simpler to use [[uiSref]] parameter-only links.\n *\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n * ```\n */\nlet uiStateDirective: ng1_directive;\nuiStateDirective = ['$uiRouter', '$timeout',\n function $StateRefDynamicDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function (scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts'];\n const watchDeregFns = inputAttrs.reduce((acc, attr) => (acc[attr] = noop, acc), {});\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n inputAttrs.forEach((field) => {\n rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null;\n\n attrs.$observe(field, (expr) => {\n watchDeregFns[field]();\n watchDeregFns[field] = scope.$watch(expr, (newval) => {\n rawDef[field] = newval;\n update();\n }, true);\n });\n });\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n }];\n\n\n/**\n * `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active\n *\n * A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the\n * related directive's state is active (and remove them when it is inactive).\n *\n * The primary use-case is to highlight the active link in navigation menus,\n * distinguishing it from the inactive menu items.\n *\n * ### Linking to a `ui-sref` or `ui-state`\n * `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element.\n * If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**.\n *\n * ### Matching\n *\n * The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**.\n * This is a \"fuzzy match\" which uses [[StateService.includes]].\n *\n * The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active).\n * This is an \"exact match\" which uses [[StateService.is]].\n *\n * ### Parameter values\n * If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted.\n * This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted.\n *\n * #### Example:\n * ```html\n *
  • \n * {{ user.lastName }}\n *
  • \n * ```\n *\n * ### Examples\n *\n * Given the following template:\n * #### Example:\n * ```html\n * \n * ```\n *\n * When the app state is `app.user` (or any child state),\n * and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n *\n * ```html\n * \n * ```\n *\n * ### Glob mode\n *\n * It is possible to pass `ui-sref-active` an expression that evaluates to an object.\n * The objects keys represent active class names and values represent the respective state names/globs.\n * `ui-sref-active` will match if the current active state **includes** any of\n * the specified state names/globs, even the abstract ones.\n *\n * #### Example:\n * Given the following template, with \"admin\" being an abstract state:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * Arrays are also supported as values in the `ngClass`-like interface.\n * This allows multiple states to add `active` class.\n *\n * #### Example:\n * Given the following template, with \"admin.roles\" being the current state, the class will be added too:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * When the current state is \"admin.roles\" the \"active\" class will be applied to both the `
    ` and `` elements.\n * It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`.\n *\n * ### Notes:\n *\n * - The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'`\n */\nlet uiSrefActiveDirective: ng1_directive;\nuiSrefActiveDirective = ['$state', '$stateParams', '$interpolate', '$uiRouter',\n function $StateRefActiveDirective($state: StateService, $stateParams: Obj, $interpolate: IInterpolateService, $uiRouter: UIRouter) {\n return {\n restrict: 'A',\n controller: ['$scope', '$element', '$attrs',\n function ($scope: IScope, $element: IAugmentedJQuery, $attrs: any) {\n let states: StateData[] = [];\n let activeEqClass: string;\n let uiSrefActive: any;\n\n // There probably isn't much point in $observing this\n // uiSrefActive and uiSrefActiveEq share the same directive object with some\n // slight difference in logic routing\n activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);\n\n try {\n uiSrefActive = $scope.$eval($attrs.uiSrefActive);\n } catch (e) {\n // Do nothing. uiSrefActive is not a valid expression.\n // Fall back to using $interpolate below\n }\n uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);\n setStatesFromDefinitionObject(uiSrefActive);\n\n // Allow uiSref to communicate with uiSrefActive[Equals]\n this.$$addStateInfo = function (newState: string, newParams: Obj) {\n // we already got an explicit state provided by ui-sref-active, so we\n // shadow the one that comes from ui-sref\n if (isObject(uiSrefActive) && states.length > 0) {\n return;\n }\n const deregister = addState(newState, newParams, uiSrefActive);\n update();\n return deregister;\n };\n\n function updateAfterTransition(trans) {\n trans.promise.then(update, noop);\n }\n $scope.$on('$destroy', setupEventListeners());\n if ($uiRouter.globals.transition) {\n updateAfterTransition($uiRouter.globals.transition);\n }\n\n function setupEventListeners () {\n const deregisterStatesChangedListener = $uiRouter.stateRegistry.onStatesChanged(handleStatesChanged);\n const deregisterOnStartListener = $uiRouter.transitionService.onStart({}, updateAfterTransition);\n const deregisterStateChangeSuccessListener = $scope.$on('$stateChangeSuccess', update);\n return function cleanUp () {\n deregisterStatesChangedListener();\n deregisterOnStartListener();\n deregisterStateChangeSuccessListener();\n };\n }\n\n function handleStatesChanged () {\n setStatesFromDefinitionObject(uiSrefActive);\n }\n\n function setStatesFromDefinitionObject (statesDefinition: object) {\n if (isObject(statesDefinition)) {\n states = [];\n forEach(statesDefinition, function (stateOrName: StateOrName | Array, activeClass: string) {\n // Helper function to abstract adding state.\n const addStateForClass = function (stateOrName: string, activeClass: string) {\n const ref = parseStateRef(stateOrName);\n addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);\n };\n\n if (isString(stateOrName)) {\n // If state is string, just add it.\n addStateForClass(stateOrName as string, activeClass)\n } else if (isArray(stateOrName)) {\n // If state is an array, iterate over it and add each array item individually.\n forEach(stateOrName, function (stateOrName: string) {\n addStateForClass(stateOrName, activeClass)\n });\n }\n });\n }\n }\n\n function addState(stateName: string, stateParams: Obj, activeClass: string) {\n const state = $state.get(stateName, stateContext($element));\n\n const stateInfo = {\n state: state || { name: stateName },\n params: stateParams,\n activeClass: activeClass,\n };\n\n states.push(stateInfo);\n\n return function removeState() {\n removeFrom(states)(stateInfo);\n };\n }\n\n // Update route state\n function update() {\n const splitClasses = str =>\n str.split(/\\s/).filter(identity);\n const getClasses = (stateList: StateData[]) =>\n stateList.map(x => x.activeClass).map(splitClasses).reduce(unnestR, []);\n\n const allClasses = getClasses(states).concat(splitClasses(activeEqClass)).reduce(uniqR, []);\n const fuzzyClasses = getClasses(states.filter(x => $state.includes(x.state.name, x.params)));\n const exactlyMatchesAny = !!states.filter(x => $state.is(x.state.name, x.params)).length;\n const exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : [];\n\n const addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []);\n const removeClasses = allClasses.filter(cls => !inArray(addClasses, cls));\n\n $scope.$evalAsync(() => {\n addClasses.forEach(className => $element.addClass(className));\n removeClasses.forEach(className => $element.removeClass(className));\n });\n }\n\n update();\n }],\n };\n }];\n\n/** @hidden */\ninterface Def { uiState: string; href: string; uiStateParams: Obj; uiStateOpts: any; }\n/** @hidden */\ninterface StateData { state: StateDeclaration; params: RawParams; activeClass: string; }\n\nangular.module('ui.router.state')\n .directive('uiSref', uiSrefDirective)\n .directive('uiSrefActive', uiSrefActiveDirective)\n .directive('uiSrefActiveEq', uiSrefActiveDirective)\n .directive('uiState', uiStateDirective);\n", - "/** @module ng1 */ /** for typedoc */\n\nimport { ng as angular } from './angular';\nimport { Obj, StateService, StateOrName } from '@uirouter/core';\n\n/**\n * `isState` Filter: truthy if the current state is the parameter\n *\n * Translates to [[StateService.is]] `$state.is(\"stateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state is 'stateName'
    \n * ```\n */\n$IsStateFilter.$inject = ['$state'];\nexport function $IsStateFilter($state: StateService) {\n const isFilter: any = function(state: StateOrName, params: Obj, options?: { relative?: StateOrName }) {\n return $state.is(state, params, options);\n };\n isFilter.$stateful = true;\n return isFilter;\n}\n\n/**\n * `includedByState` Filter: truthy if the current state includes the parameter\n *\n * Translates to [[StateService.includes]]` $state.is(\"fullOrPartialStateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state includes 'fullOrPartialStateName'
    \n * ```\n */\n$IncludedByStateFilter.$inject = ['$state'];\nexport function $IncludedByStateFilter($state: StateService) {\n const includesFilter: any = function(state: StateOrName, params: Obj, options: { relative?: StateOrName }) {\n return $state.includes(state, params, options);\n };\n includesFilter.$stateful = true;\n return includesFilter;\n}\n\nangular.module('ui.router.state')\n .filter('isState', $IsStateFilter)\n .filter('includedByState', $IncludedByStateFilter);\n", - "/**\n * @ng1api\n * @module directives\n */ /** for typedoc */\nimport { ng as angular } from '../angular';\nimport { IInterpolateService, IScope, ITranscludeFunction, IAugmentedJQuery, ITimeoutService } from 'angular';\n\nimport {\n extend, unnestR, filter, tail, isDefined, isFunction, isString, trace, parse,\n ActiveUIView, TransitionService, ResolveContext, Transition, PathNode, StateDeclaration,\n Param, kebobString, HookRegOptions, ViewService, $QLike, Obj, TypedMap, noop,\n} from '@uirouter/core';\nimport { Ng1ViewConfig } from '../statebuilders/views';\nimport { Ng1Controller, Ng1StateDeclaration } from '../interface';\nimport { getLocals } from '../services';\nimport { ng1_directive } from './stateDirectives';\n\n/** @hidden */\nexport type UIViewData = {\n $cfg: Ng1ViewConfig;\n $uiView: ActiveUIView;\n};\n\n/** @hidden */\nexport type UIViewAnimData = {\n $animEnter: Promise;\n $animLeave: Promise;\n $$animLeave: { resolve: () => any; } // \"deferred\"\n};\n\n/**\n * `ui-view`: A viewport directive which is filled in by a view from the active state.\n *\n * ### Attributes\n *\n * - `name`: (Optional) A view name.\n * The name should be unique amongst the other views in the same state.\n * You can have views of the same name that live in different states.\n * The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]).\n *\n * - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated.\n * Uses [[$uiViewScroll]] to do the scrolling.\n *\n * - `onload`: Expression to evaluate whenever the view updates.\n *\n * #### Example:\n * A view can be unnamed or named.\n * ```html\n * \n *
    \n *\n * \n *
    \n *\n * \n * \n * ```\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a\n * single view and it is unnamed then you can populate it like so:\n *\n * ```html\n *
    \n * $stateProvider.state(\"home\", {\n * template: \"

    HELLO!

    \"\n * })\n * ```\n *\n * The above is a convenient shortcut equivalent to specifying your view explicitly with the\n * [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name:\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * But typically you'll only use the views property if you name your view or have more than one view\n * in the same template. There's not really a compelling reason to name a view if its the only one,\n * but you could if you wanted, like so:\n *\n * ```html\n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"main\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * Really though, you'll use views to set up multiple views:\n *\n * ```html\n *
    \n *
    \n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * },\n * \"chart\": {\n * template: \"\"\n * },\n * \"data\": {\n * template: \"\"\n * }\n * }\n * })\n * ```\n *\n * #### Examples for `autoscroll`:\n * ```html\n * \n * \n *\n * \n * \n * \n * \n * ```\n *\n * Resolve data:\n *\n * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this\n * can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template.\n *\n * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the\n * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which\n * depends on `$resolve` data.\n *\n * #### Example:\n * ```js\n * $stateProvider.state('home', {\n * template: '',\n * resolve: {\n * user: function(UserService) { return UserService.fetchUser(); }\n * }\n * });\n * ```\n */\nexport let uiView: ng1_directive;\nuiView = ['$view', '$animate', '$uiViewScroll', '$interpolate', '$q',\nfunction $ViewDirective($view: ViewService, $animate: any, $uiViewScroll: any, $interpolate: IInterpolateService, $q: $QLike) {\n\n function getRenderer(attrs: Obj, scope: IScope) {\n return {\n enter: function(element: JQuery, target: any, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.enter(element, null, target).then(cb);\n } else {\n $animate.enter(element, null, target, cb);\n }\n },\n leave: function(element: JQuery, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.leave(element).then(cb);\n } else {\n $animate.leave(element, cb);\n }\n },\n };\n }\n\n function configsEqual(config1: Ng1ViewConfig, config2: Ng1ViewConfig) {\n return config1 === config2;\n }\n\n const rootData = {\n $cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } },\n $uiView: { },\n };\n\n const directive = {\n count: 0,\n restrict: 'ECA',\n terminal: true,\n priority: 400,\n transclude: 'element',\n compile: function (tElement: JQuery, tAttrs: Obj, $transclude: ITranscludeFunction) {\n\n return function (scope: IScope, $element: IAugmentedJQuery, attrs: Obj) {\n const onloadExp = attrs['onload'] || '',\n autoScrollExp = attrs['autoscroll'],\n renderer = getRenderer(attrs, scope),\n inherited = $element.inheritedData('$uiView') || rootData,\n name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default';\n\n let previousEl: JQuery,\n currentEl: JQuery,\n currentScope: IScope,\n viewConfig: Ng1ViewConfig,\n unregister: Function;\n\n const activeUIView: ActiveUIView = {\n $type: 'ng1',\n id: directive.count++, // Global sequential ID for ui-view tags added to DOM\n name: name, // ui-view name (
    \n fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + '.' + name : name, // fully qualified name, describes location in DOM\n config: null, // The ViewConfig loaded (from a state.views definition)\n configUpdated: configUpdatedCallback, // Called when the matching ViewConfig changes\n get creationContext() { // The context in which this ui-view \"tag\" was created\n const fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited);\n // Allow \n // See https://github.com/angular-ui/ui-router/issues/3355\n const fromParentTag = parse('$uiView.creationContext')(inherited);\n return fromParentTagConfig || fromParentTag;\n },\n };\n\n trace.traceUIViewEvent('Linking', activeUIView);\n\n function configUpdatedCallback(config?: Ng1ViewConfig) {\n if (config && !(config instanceof Ng1ViewConfig)) return;\n if (configsEqual(viewConfig, config)) return;\n trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context);\n\n viewConfig = config;\n updateView(config);\n }\n\n $element.data('$uiView', { $uiView: activeUIView });\n\n updateView();\n\n unregister = $view.registerUIView(activeUIView);\n scope.$on('$destroy', function() {\n trace.traceUIViewEvent('Destroying/Unregistering', activeUIView);\n unregister();\n });\n\n function cleanupLastView() {\n if (previousEl) {\n trace.traceUIViewEvent('Removing (previous) el', previousEl.data('$uiView'));\n previousEl.remove();\n previousEl = null;\n }\n\n if (currentScope) {\n trace.traceUIViewEvent('Destroying scope', activeUIView);\n currentScope.$destroy();\n currentScope = null;\n }\n\n if (currentEl) {\n const _viewData = currentEl.data('$uiViewAnim');\n trace.traceUIViewEvent('Animate out', _viewData);\n renderer.leave(currentEl, function() {\n _viewData.$$animLeave.resolve();\n previousEl = null;\n });\n\n previousEl = currentEl;\n currentEl = null;\n }\n }\n\n function updateView(config?: Ng1ViewConfig) {\n const newScope = scope.$new();\n const animEnter = $q.defer(), animLeave = $q.defer();\n\n const $uiViewData: UIViewData = {\n $cfg: config,\n $uiView: activeUIView,\n };\n\n const $uiViewAnim: UIViewAnimData = {\n $animEnter: animEnter.promise,\n $animLeave: animLeave.promise,\n $$animLeave: animLeave,\n };\n\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoading\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description\n *\n * Fired once the view **begins loading**, *before* the DOM is rendered.\n *\n * @param {Object} event Event object.\n * @param {string} viewName Name of the view.\n */\n newScope.$emit('$viewContentLoading', name);\n\n const cloned = $transclude(newScope, function(clone) {\n clone.data('$uiViewAnim', $uiViewAnim);\n clone.data('$uiView', $uiViewData);\n renderer.enter(clone, $element, function onUIViewEnter() {\n animEnter.resolve();\n if (currentScope) currentScope.$emit('$viewContentAnimationEnded');\n\n if (isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {\n $uiViewScroll(clone);\n }\n });\n\n cleanupLastView();\n });\n\n currentEl = cloned;\n currentScope = newScope;\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoaded\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description *\n * Fired once the view is **loaded**, *after* the DOM is rendered.\n *\n * @param {Object} event Event object.\n */\n currentScope.$emit('$viewContentLoaded', config || viewConfig);\n currentScope.$eval(onloadExp);\n }\n };\n },\n };\n\n return directive;\n}];\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout'];\n/** @hidden */\nfunction $ViewDirectiveFill($compile: angular.ICompileService,\n $controller: angular.IControllerService,\n $transitions: TransitionService,\n $view: ViewService,\n $q: angular.IQService,\n $timeout: ITimeoutService) {\n const getControllerAs = parse('viewDecl.controllerAs');\n const getResolveAs = parse('viewDecl.resolveAs');\n\n return {\n restrict: 'ECA',\n priority: -400,\n compile: function (tElement: JQuery) {\n const initial = tElement.html();\n tElement.empty();\n\n return function (scope: IScope, $element: JQuery) {\n const data: UIViewData = $element.data('$uiView');\n if (!data) {\n $element.html(initial);\n $compile($element.contents() as any)(scope);\n return;\n }\n\n const cfg: Ng1ViewConfig = data.$cfg || { viewDecl: {}, getTemplate: noop };\n const resolveCtx: ResolveContext = cfg.path && new ResolveContext(cfg.path);\n $element.html(cfg.getTemplate($element, resolveCtx) || initial);\n trace.traceUIViewFill(data.$uiView, $element.html());\n\n const link = $compile($element.contents() as any);\n const controller = cfg.controller;\n const controllerAs: string = getControllerAs(cfg);\n const resolveAs: string = getResolveAs(cfg);\n const locals = resolveCtx && getLocals(resolveCtx);\n\n scope[resolveAs] = locals;\n\n if (controller) {\n const controllerInstance = $controller(controller, extend({}, locals, { $scope: scope, $element: $element }));\n if (controllerAs) {\n scope[controllerAs] = controllerInstance;\n scope[controllerAs][resolveAs] = locals;\n }\n\n // TODO: Use $view service as a central point for registering component-level hooks\n // Then, when a component is created, tell the $view service, so it can invoke hooks\n // $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element });\n // scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element }));\n\n $element.data('$ngControllerController', controllerInstance);\n $element.children().data('$ngControllerController', controllerInstance);\n\n registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg);\n }\n\n // Wait for the component to appear in the DOM\n if (isString(cfg.viewDecl.component)) {\n const cmp = cfg.viewDecl.component;\n const kebobName = kebobString(cmp);\n const tagRegexp = new RegExp(`^(x-|data-)?${kebobName}$`, 'i');\n\n const getComponentController = () => {\n const directiveEl = [].slice.call($element[0].children)\n .filter((el: Element) => el && el.tagName && tagRegexp.exec(el.tagName)) ;\n\n return directiveEl && angular.element(directiveEl).data(`$${cmp}Controller`);\n };\n\n const deregisterWatch = scope.$watch(getComponentController, function(ctrlInstance) {\n if (!ctrlInstance) return;\n registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg);\n deregisterWatch();\n });\n }\n\n link(scope);\n };\n },\n };\n}\n\n/** @hidden */\nconst hasComponentImpl = typeof (angular as any).module('ui.router')['component'] === 'function';\n/** @hidden incrementing id */\nlet _uiCanExitId = 0;\n\n/** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */\nfunction registerControllerCallbacks($q: angular.IQService,\n $transitions: TransitionService,\n controllerInstance: Ng1Controller,\n $scope: IScope,\n cfg: Ng1ViewConfig) {\n // Call $onInit() ASAP\n if (isFunction(controllerInstance.$onInit) && !(cfg.viewDecl.component && hasComponentImpl)) {\n controllerInstance.$onInit();\n }\n\n const viewState: Ng1StateDeclaration = tail(cfg.path).state.self;\n\n const hookOptions: HookRegOptions = { bind: controllerInstance };\n // Add component-level hook for onParamsChange\n if (isFunction(controllerInstance.uiOnParamsChanged)) {\n const resolveContext: ResolveContext = new ResolveContext(cfg.path);\n const viewCreationTrans = resolveContext.getResolvable('$transition$').data;\n\n // Fire callback on any successful transition\n const paramsUpdated = ($transition$: Transition) => {\n // Exit early if the $transition$ is the same as the view was created within.\n // Exit early if the $transition$ will exit the state the view is for.\n if ($transition$ === viewCreationTrans || $transition$.exiting().indexOf(viewState as StateDeclaration) !== -1) return;\n\n const toParams = $transition$.params('to') as TypedMap;\n const fromParams = $transition$.params>('from') as TypedMap;\n const toSchema: Param[] = $transition$.treeChanges().to.map((node: PathNode) => node.paramSchema).reduce(unnestR, []);\n const fromSchema: Param[] = $transition$.treeChanges().from.map((node: PathNode) => node.paramSchema).reduce(unnestR, []);\n\n // Find the to params that have different values than the from params\n const changedToParams = toSchema.filter((param: Param) => {\n const idx = fromSchema.indexOf(param);\n return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]);\n });\n\n // Only trigger callback if a to param has changed or is new\n if (changedToParams.length) {\n const changedKeys: string[] = changedToParams.map(x => x.id);\n // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params.\n const newValues = filter(toParams, (val, key) => changedKeys.indexOf(key) !== -1);\n controllerInstance.uiOnParamsChanged(newValues, $transition$);\n }\n };\n $scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions));\n }\n\n // Add component-level hook for uiCanExit\n if (isFunction(controllerInstance.uiCanExit)) {\n const id = _uiCanExitId++;\n const cacheProp = '_uiCanExitIds';\n\n // Returns true if a redirect transition already answered truthy\n const prevTruthyAnswer = (trans: Transition) =>\n !!trans && (trans[cacheProp] && trans[cacheProp][id] === true || prevTruthyAnswer(trans.redirectedFrom()));\n\n // If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition\n const wrappedHook = (trans: Transition) => {\n let promise;\n const ids = trans[cacheProp] = trans[cacheProp] || {};\n\n if (!prevTruthyAnswer(trans)) {\n promise = $q.when(controllerInstance.uiCanExit(trans));\n promise.then(val => ids[id] = (val !== false));\n }\n return promise;\n };\n\n const criteria = { exiting: viewState.name };\n $scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions));\n }\n}\n\nangular.module('ui.router.state').directive('uiView', uiView);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n", - "/** @module ng1 */ /** */\nimport { ng as angular } from './angular';\nimport { IServiceProviderFactory } from 'angular';\nimport IAnchorScrollService = angular.IAnchorScrollService;\nimport ITimeoutService = angular.ITimeoutService;\n\nexport interface UIViewScrollProvider {\n /**\n * Uses standard anchorScroll behavior\n *\n * Reverts [[$uiViewScroll]] back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * service for scrolling based on the url anchor.\n */\n useAnchorScroll(): void;\n}\n\n\n/** @hidden */\nfunction $ViewScrollProvider() {\n\n let useAnchorScroll = false;\n\n this.useAnchorScroll = function () {\n useAnchorScroll = true;\n };\n\n this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll: IAnchorScrollService, $timeout: ITimeoutService): Function {\n if (useAnchorScroll) {\n return $anchorScroll;\n }\n\n return function ($element: JQuery) {\n return $timeout(function () {\n $element[0].scrollIntoView();\n }, 0, false);\n };\n }];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n", - "/**\n * Main entry point for angular 1.x build\n * @module ng1\n */ /** */\n\nexport * from './interface';\nexport * from './services';\nexport * from './statebuilders/views';\nexport * from './stateProvider';\nexport * from './urlRouterProvider';\n\nimport './injectables';\nimport './directives/stateDirectives';\nimport './stateFilters';\nimport './directives/viewDirective';\nimport './viewScroll';\n\nexport default 'ui.router';\n\nimport * as core from '@uirouter/core';\nexport { core };\nexport * from '@uirouter/core';\n\n" + "/** @module ng1 */ /** */\nimport { ng as angular } from '../angular';\nimport {\n StateObject,\n pick,\n forEach,\n tail,\n extend,\n isArray,\n isInjectable,\n isDefined,\n isString,\n services,\n trace,\n ViewConfig,\n ViewService,\n ViewConfigFactory,\n PathNode,\n ResolveContext,\n Resolvable,\n IInjectable,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration } from '../interface';\nimport { TemplateFactory } from '../templateFactory';\nimport IInjectorService = angular.auto.IInjectorService;\n\nexport function getNg1ViewConfigFactory(): ViewConfigFactory {\n let templateFactory: TemplateFactory = null;\n return (path, view) => {\n templateFactory = templateFactory || services.$injector.get('$templateFactory');\n return [new Ng1ViewConfig(path, view, templateFactory)];\n };\n}\n\nconst hasAnyKey = (keys, obj) => keys.reduce((acc, key) => acc || isDefined(obj[key]), false);\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `views`.\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * handles the `views` property with logic specific to @uirouter/angularjs (ng1).\n *\n * If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object\n * and applies the state-level configuration to a view named `$default`.\n */\nexport function ng1ViewsBuilder(state: StateObject) {\n // Do not process root state\n if (!state.parent) return {};\n\n const tplKeys = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'],\n ctrlKeys = ['controller', 'controllerProvider', 'controllerAs', 'resolveAs'],\n compKeys = ['component', 'bindings', 'componentProvider'],\n nonCompKeys = tplKeys.concat(ctrlKeys),\n allViewKeys = compKeys.concat(nonCompKeys);\n\n // Do not allow a state to have both state-level props and also a `views: {}` property.\n // A state without a `views: {}` property can declare properties for the `$default` view as properties of the state.\n // However, the `$default` approach should not be mixed with a separate `views: ` block.\n if (isDefined(state.views) && hasAnyKey(allViewKeys, state)) {\n throw new Error(\n `State '${state.name}' has a 'views' object. ` +\n `It cannot also have \"view properties\" at the state level. ` +\n `Move the following properties into a view (in the 'views' object): ` +\n ` ${allViewKeys.filter(key => isDefined(state[key])).join(', ')}`,\n );\n }\n\n const views: { [key: string]: Ng1ViewDeclaration } = {},\n viewsObject = state.views || { $default: pick(state, allViewKeys) };\n\n forEach(viewsObject, function(config: Ng1ViewDeclaration, name: string) {\n // Account for views: { \"\": { template... } }\n name = name || '$default';\n // Account for views: { header: \"headerComponent\" }\n if (isString(config)) config = { component: config };\n\n // Make a shallow copy of the config object\n config = extend({}, config);\n\n // Do not allow a view to mix props for component-style view with props for template/controller-style view\n if (hasAnyKey(compKeys, config) && hasAnyKey(nonCompKeys, config)) {\n throw new Error(\n `Cannot combine: ${compKeys.join('|')} with: ${nonCompKeys.join('|')} in stateview: '${name}@${state.name}'`,\n );\n }\n\n config.resolveAs = config.resolveAs || '$resolve';\n config.$type = 'ng1';\n config.$context = state;\n config.$name = name;\n\n const normalized = ViewService.normalizeUIViewTarget(config.$context, config.$name);\n config.$uiViewName = normalized.uiViewName;\n config.$uiViewContextAnchor = normalized.uiViewContextAnchor;\n\n views[name] = config;\n });\n return views;\n}\n\nlet id = 0;\nexport class Ng1ViewConfig implements ViewConfig {\n $id = id++;\n loaded = false;\n controller: Function; // actually IInjectable|string\n template: string;\n component: string;\n locals: any; // TODO: delete me\n\n constructor(public path: PathNode[], public viewDecl: Ng1ViewDeclaration, public factory: TemplateFactory) {}\n\n load() {\n const $q = services.$q;\n const context = new ResolveContext(this.path);\n const params = this.path.reduce((acc, node) => extend(acc, node.paramValues), {});\n\n const promises: any = {\n template: $q.when(this.factory.fromConfig(this.viewDecl, params, context)),\n controller: $q.when(this.getController(context)),\n };\n\n return $q.all(promises).then(results => {\n trace.traceViewServiceEvent('Loaded', this);\n this.controller = results.controller;\n extend(this, results.template); // Either { template: \"tpl\" } or { component: \"cmpName\" }\n return this;\n });\n }\n\n getTemplate = (uiView, context: ResolveContext) =>\n this.component\n ? this.factory.makeComponentTemplate(uiView, context, this.component, this.viewDecl.bindings)\n : this.template;\n\n /**\n * Gets the controller for a view configuration.\n *\n * @returns {Function|Promise.} Returns a controller, or a promise that resolves to a controller.\n */\n getController(context: ResolveContext): IInjectable | string | Promise {\n const provider = this.viewDecl.controllerProvider;\n if (!isInjectable(provider)) return this.viewDecl.controller;\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail(provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n}\n", + "/** @module view */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport { IAugmentedJQuery } from 'angular';\nimport {\n isArray,\n isDefined,\n isFunction,\n isObject,\n services,\n Obj,\n IInjectable,\n tail,\n kebobString,\n unnestR,\n ResolveContext,\n Resolvable,\n RawParams,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration, TemplateFactoryProvider } from './interface';\n\n/**\n * Service which manages loading of templates from a ViewConfig.\n */\nexport class TemplateFactory implements TemplateFactoryProvider {\n /** @hidden */ private _useHttp = angular.version.minor < 3;\n /** @hidden */ private $templateRequest;\n /** @hidden */ private $templateCache;\n /** @hidden */ private $http;\n\n /** @hidden */ $get = [\n '$http',\n '$templateCache',\n '$injector',\n ($http, $templateCache, $injector) => {\n this.$templateRequest = $injector.has && $injector.has('$templateRequest') && $injector.get('$templateRequest');\n this.$http = $http;\n this.$templateCache = $templateCache;\n return this;\n },\n ];\n\n /** @hidden */\n useHttpService(value: boolean) {\n this._useHttp = value;\n }\n\n /**\n * Creates a template from a configuration object.\n *\n * @param config Configuration object for which to load a template.\n * The following properties are search in the specified order, and the first one\n * that is defined is used to create the template:\n *\n * @param params Parameters to pass to the template function.\n * @param context The resolve context associated with the template's view\n *\n * @return {string|object} The template html as a string, or a promise for\n * that string,or `null` if no template is configured.\n */\n fromConfig(\n config: Ng1ViewDeclaration,\n params: any,\n context: ResolveContext,\n ): Promise<{ template?: string; component?: string }> {\n const defaultTemplate = '';\n\n const asTemplate = result => services.$q.when(result).then(str => ({ template: str }));\n const asComponent = result => services.$q.when(result).then(str => ({ component: str }));\n\n return isDefined(config.template)\n ? asTemplate(this.fromString(config.template, params))\n : isDefined(config.templateUrl)\n ? asTemplate(this.fromUrl(config.templateUrl, params))\n : isDefined(config.templateProvider)\n ? asTemplate(this.fromProvider(config.templateProvider, params, context))\n : isDefined(config.component)\n ? asComponent(config.component)\n : isDefined(config.componentProvider)\n ? asComponent(this.fromComponentProvider(config.componentProvider, params, context))\n : asTemplate(defaultTemplate);\n }\n\n /**\n * Creates a template from a string or a function returning a string.\n *\n * @param template html template as a string or function that returns an html template as a string.\n * @param params Parameters to pass to the template function.\n *\n * @return {string|object} The template html as a string, or a promise for that\n * string.\n */\n fromString(template: string | Function, params?: RawParams) {\n return isFunction(template) ? (template)(params) : template;\n }\n\n /**\n * Loads a template from the a URL via `$http` and `$templateCache`.\n *\n * @param {string|Function} url url of the template to load, or a function\n * that returns a url.\n * @param {Object} params Parameters to pass to the url function.\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromUrl(url: string | Function, params: any) {\n if (isFunction(url)) url = (url)(params);\n if (url == null) return null;\n\n if (this._useHttp) {\n return this.$http\n .get(url, { cache: this.$templateCache, headers: { Accept: 'text/html' } })\n .then(function(response) {\n return response.data;\n });\n }\n\n return this.$templateRequest(url);\n }\n\n /**\n * Creates a template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail(provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a component's template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string} The template html as a string: \"\".\n */\n fromComponentProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail(provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a template from a component's name\n *\n * This implements route-to-component.\n * It works by retrieving the component (directive) metadata from the injector.\n * It analyses the component's bindings, then constructs a template that instantiates the component.\n * The template wires input and output bindings to resolves or from the parent component.\n *\n * @param uiView {object} The parent ui-view (for binding outputs to callbacks)\n * @param context The ResolveContext (for binding outputs to callbacks returned from resolves)\n * @param component {string} Component's name in camel case.\n * @param bindings An object defining the component's bindings: {foo: '<'}\n * @return {string} The template as a string: \"\".\n */\n makeComponentTemplate(uiView: IAugmentedJQuery, context: ResolveContext, component: string, bindings?: any) {\n bindings = bindings || {};\n\n // Bind once prefix\n const prefix = angular.version.minor >= 3 ? '::' : '';\n // Convert to kebob name. Add x- prefix if the string starts with `x-` or `data-`\n const kebob = (camelCase: string) => {\n const kebobed = kebobString(camelCase);\n return /^(x|data)-/.exec(kebobed) ? `x-${kebobed}` : kebobed;\n };\n\n const attributeTpl = (input: BindingTuple) => {\n const { name, type } = input;\n const attrName = kebob(name);\n // If the ui-view has an attribute which matches a binding on the routed component\n // then pass that attribute through to the routed component template.\n // Prefer ui-view wired mappings to resolve data, unless the resolve was explicitly bound using `bindings:`\n if (uiView.attr(attrName) && !bindings[name]) return `${attrName}='${uiView.attr(attrName)}'`;\n\n const resolveName = bindings[name] || name;\n // Pre-evaluate the expression for \"@\" bindings by enclosing in {{ }}\n // some-attr=\"{{ ::$resolve.someResolveName }}\"\n if (type === '@') return `${attrName}='{{${prefix}$resolve.${resolveName}}}'`;\n\n // Wire \"&\" callbacks to resolves that return a callback function\n // Get the result of the resolve (should be a function) and annotate it to get its arguments.\n // some-attr=\"$resolve.someResolveResultName(foo, bar)\"\n if (type === '&') {\n const res = context.getResolvable(resolveName);\n const fn = res && res.data;\n const args = (fn && services.$injector.annotate(fn)) || [];\n // account for array style injection, i.e., ['foo', function(foo) {}]\n const arrayIdxStr = isArray(fn) ? `[${fn.length - 1}]` : '';\n return `${attrName}='$resolve.${resolveName}${arrayIdxStr}(${args.join(',')})'`;\n }\n\n // some-attr=\"::$resolve.someResolveName\"\n return `${attrName}='${prefix}$resolve.${resolveName}'`;\n };\n\n const attrs = getComponentBindings(component)\n .map(attributeTpl)\n .join(' ');\n const kebobName = kebob(component);\n return `<${kebobName} ${attrs}>`;\n }\n}\n\n// Gets all the directive(s)' inputs ('@', '=', and '<') and outputs ('&')\nfunction getComponentBindings(name: string) {\n const cmpDefs = services.$injector.get(name + 'Directive'); // could be multiple\n if (!cmpDefs || !cmpDefs.length) throw new Error(`Unable to find component named '${name}'`);\n return cmpDefs.map(getBindings).reduce(unnestR, []);\n}\n\n// Given a directive definition, find its object input attributes\n// Use different properties, depending on the type of directive (component, bindToController, normal)\nconst getBindings = (def: any) => {\n if (isObject(def.bindToController)) return scopeBindings(def.bindToController);\n return scopeBindings(def.scope);\n};\n\ninterface BindingTuple {\n name: string;\n type: string;\n}\n\n// for ng 1.2 style, process the scope: { input: \"=foo\" }\n// for ng 1.3 through ng 1.5, process the component's bindToController: { input: \"=foo\" } object\nconst scopeBindings = (bindingsObj: Obj) =>\n Object.keys(bindingsObj || {})\n // [ 'input', [ '=foo', '=', 'foo' ] ]\n .map(key => [key, /^([=<@&])[?]?(.*)/.exec(bindingsObj[key])])\n // skip malformed values\n .filter(tuple => isDefined(tuple) && isArray(tuple[1]))\n // { name: ('foo' || 'input'), type: '=' }\n .map(tuple => ({ name: tuple[1][2] || tuple[0], type: tuple[1][1] } as BindingTuple));\n", + "/** @module ng1 */ /** for typedoc */\nimport {\n val,\n isObject,\n createProxyFunctions,\n BuilderFunction,\n StateRegistry,\n StateService,\n OnInvalidCallback,\n} from '@uirouter/core';\nimport { Ng1StateDeclaration } from './interface';\n\n/**\n * The Angular 1 `StateProvider`\n *\n * The `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\nexport class StateProvider {\n constructor(private stateRegistry: StateRegistry, private stateService: StateService) {\n createProxyFunctions(val(StateProvider.prototype), this, val(this));\n }\n\n /**\n * Decorates states when they are registered\n *\n * Allows you to extend (carefully) or override (at your own peril) the\n * `stateBuilder` object used internally by [[StateRegistry]].\n * This can be used to add custom functionality to ui-router,\n * for example inferring templateUrl based on the state name.\n *\n * When passing only a name, it returns the current (original or decorated) builder\n * function that matches `name`.\n *\n * The builder functions that can be decorated are listed below. Though not all\n * necessarily have a good use case for decoration, that is up to you to decide.\n *\n * In addition, users can attach custom decorators, which will generate new\n * properties within the state's internal definition. There is currently no clear\n * use-case for this beyond accessing internal states (i.e. $state.$current),\n * however, expect this to become increasingly relevant as we introduce additional\n * meta-programming features.\n *\n * **Warning**: Decorators should not be interdependent because the order of\n * execution of the builder functions in non-deterministic. Builder functions\n * should only be dependent on the state definition object and super function.\n *\n *\n * Existing builder functions and current return values:\n *\n * - **parent** `{object}` - returns the parent state object.\n * - **data** `{object}` - returns state data, including any inherited data that is not\n * overridden by own values (if any).\n * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n * or `null`.\n * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is\n * navigable).\n * - **params** `{object}` - returns an array of state params that are ensured to\n * be a super-set of parent's params.\n * - **views** `{object}` - returns a views object where each key is an absolute view\n * name (i.e. \"viewName@stateName\") and each value is the config object\n * (template, controller) for the view. Even when you don't use the views object\n * explicitly on a state config, one is still created for you internally.\n * So by decorating this builder function you have access to decorating template\n * and controller properties.\n * - **ownParams** `{object}` - returns an array of params that belong to the state,\n * not including any params defined by ancestor states.\n * - **path** `{string}` - returns the full path from the root down to this state.\n * Needed for state activation.\n * - **includes** `{object}` - returns an object that includes every state that\n * would pass a `$state.includes()` test.\n *\n * #### Example:\n * Override the internal 'views' builder with a function that takes the state\n * definition, and a reference to the internal function being overridden:\n * ```js\n * $stateProvider.decorator('views', function (state, parent) {\n * let result = {},\n * views = parent(state);\n *\n * angular.forEach(views, function (config, name) {\n * let autoName = (state.name + '.' + name).replace('.', '/');\n * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n * result[name] = config;\n * });\n * return result;\n * });\n *\n * $stateProvider.state('home', {\n * views: {\n * 'contact.list': { controller: 'ListController' },\n * 'contact.item': { controller: 'ItemController' }\n * }\n * });\n * ```\n *\n *\n * ```js\n * // Auto-populates list and item views with /partials/home/contact/list.html,\n * // and /partials/home/contact/item.html, respectively.\n * $state.go('home');\n * ```\n *\n * @param {string} name The name of the builder function to decorate.\n * @param {object} func A function that is responsible for decorating the original\n * builder function. The function receives two parameters:\n *\n * - `{object}` - state - The state config object.\n * - `{object}` - super - The original builder function.\n *\n * @return {object} $stateProvider - $stateProvider instance\n */\n decorator(name: string, func: BuilderFunction) {\n return this.stateRegistry.decorator(name, func) || this;\n }\n\n /**\n * Registers a state\n *\n * ### This is a passthrough to [[StateRegistry.register]].\n *\n * Registers a state configuration under a given state name.\n * The stateConfig object has the following acceptable properties.\n *\n *
    \n *\n * - **`template`** - {string|function=} - html template as a string or a function that returns\n * an html template as a string which should be used by the uiView directives. This property\n * takes precedence over templateUrl.\n *\n * If `template` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateUrl`** - {string|function=} - path or function that returns a path to an html\n * template that should be used by uiView.\n *\n * If `templateUrl` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateProvider`** - {function=} - Provider function that returns HTML content\n * string.\n *\n * \n *\n * - **`controller`** - {string|function=} - Controller fn that should be associated with newly\n * related scope or the name of a registered controller if passed as a string.\n *\n * \n *\n * - **`controllerProvider`** - {function=} - Injectable provider function that returns\n * the actual controller or string.\n *\n * \n *\n * - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be\n * published to scope under the controllerAs name.\n *\n * \n *\n * - **`resolve`** - {object.<string, function>=} - An optional map of dependencies which\n * should be injected into the controller. If any of these dependencies are promises,\n * the router will wait for them all to be resolved or one to be rejected before the\n * controller is instantiated. If all the promises are resolved successfully, the values\n * of the resolved promises are injected and $stateChangeSuccess event is fired. If any\n * of the promises are rejected the $stateChangeError event is fired. The map object is:\n *\n * - key - {string}: name of dependency to be injected into controller\n * - factory - {string|function}: If string then it is alias for service. Otherwise if function,\n * it is injected and return value it treated as dependency. If result is a promise, it is\n * resolved before its value is injected into controller.\n *\n * \n *\n * - **`url`** - {string=} - A url with optional parameters. When a state is navigated or\n * transitioned to, the `$stateParams` service will be populated with any\n * parameters that were passed.\n *\n * \n *\n * - **`params`** - {object=} - An array of parameter names or regular expressions. Only\n * use this within a state if you are not using url. Otherwise you can specify your\n * parameters within the url. When a state is navigated or transitioned to, the\n * $stateParams service will be populated with any parameters that were passed.\n *\n * \n *\n * - **`views`** - {object=} - Use the views property to set up multiple views or to target views\n * manually/explicitly.\n *\n * \n *\n * - **`abstract`** - {boolean=} - An abstract state will never be directly activated,\n * but can provide inherited properties to its common children states.\n *\n * \n *\n * - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way\n * to trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to\n * trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state\n * just because a search/query parameter has changed (via $location.search() or $location.hash()).\n * Useful for when you'd like to modify $location.search() without triggering a reload.\n *\n * \n *\n * - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.\n *\n * #### Example:\n * Some state name examples\n * ```js\n * // stateName can be a single top-level name (must be unique).\n * $stateProvider.state(\"home\", {});\n *\n * // Or it can be a nested state name. This state is a child of the\n * // above \"home\" state.\n * $stateProvider.state(\"home.newest\", {});\n *\n * // Nest states as deeply as needed.\n * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n *\n * // state() returns $stateProvider, so you can chain state declarations.\n * $stateProvider\n * .state(\"home\", {})\n * .state(\"about\", {})\n * .state(\"contacts\", {});\n * ```\n *\n * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n * @param {object} definition State configuration object.\n */\n state(name: string, definition: Ng1StateDeclaration): StateProvider;\n state(definition: Ng1StateDeclaration): StateProvider;\n state(name: any, definition?: any) {\n if (isObject(name)) {\n definition = name;\n } else {\n definition.name = name;\n }\n this.stateRegistry.register(definition);\n return this;\n }\n\n /**\n * Registers an invalid state handler\n *\n * This is a passthrough to [[StateService.onInvalid]] for ng1.\n */\n\n onInvalid(callback: OnInvalidCallback): Function {\n return this.stateService.onInvalid(callback);\n }\n}\n", + "/** @module ng1 */ /** */\nimport {\n StateObject,\n TransitionStateHookFn,\n HookResult,\n Transition,\n services,\n ResolveContext,\n extend,\n BuilderFunction,\n} from '@uirouter/core';\nimport { getLocals } from '../services';\nimport { Ng1StateDeclaration } from '../interface';\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,\n * `onRetain` callback hooks on a [[Ng1StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * ensures that those hooks are injectable for @uirouter/angularjs (ng1).\n */\nexport const getStateHookBuilder = (hookName: 'onEnter' | 'onExit' | 'onRetain') =>\n function stateHookBuilder(stateObject: StateObject, parentFn: BuilderFunction): TransitionStateHookFn {\n const hook = stateObject[hookName];\n const pathname = hookName === 'onExit' ? 'from' : 'to';\n\n function decoratedNg1Hook(trans: Transition, state: Ng1StateDeclaration): HookResult {\n const resolveContext = new ResolveContext(trans.treeChanges(pathname));\n const subContext = resolveContext.subContext(state.$$state());\n const locals = extend(getLocals(subContext), { $state$: state, $transition$: trans });\n return services.$injector.invoke(hook, this, locals);\n }\n\n return hook ? decoratedNg1Hook : undefined;\n };\n", + "/**\n * @internalapi\n * @module ng1\n */ /** */\nimport { LocationConfig, LocationServices, UIRouter, ParamType, isDefined } from '@uirouter/core';\nimport { val, createProxyFunctions, removeFrom, isObject } from '@uirouter/core';\nimport { ILocationService, ILocationProvider } from 'angular';\n\n/**\n * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service\n */\nexport class Ng1LocationServices implements LocationConfig, LocationServices {\n private $locationProvider: ILocationProvider;\n private $location: ILocationService;\n private $sniffer;\n\n path;\n search;\n hash;\n hashPrefix;\n port;\n protocol;\n host;\n baseHref;\n\n // .onChange() registry\n private _urlListeners: Function[] = [];\n\n /**\n * Applys ng1-specific path parameter encoding\n *\n * The Angular 1 `$location` service is a bit weird.\n * It doesn't allow slashes to be encoded/decoded bi-directionally.\n *\n * See the writeup at https://github.com/angular-ui/ui-router/issues/2598\n *\n * This code patches the `path` parameter type so it encoded/decodes slashes as ~2F\n *\n * @param router\n */\n static monkeyPatchPathParameterType(router: UIRouter) {\n const pathType: ParamType = router.urlMatcherFactory.type('path');\n\n pathType.encode = (x: any) =>\n x != null ? x.toString().replace(/(~|\\/)/g, m => ({ '~': '~~', '/': '~2F' }[m])) : x;\n\n pathType.decode = (x: string) =>\n x != null ? x.toString().replace(/(~~|~2F)/g, m => ({ '~~': '~', '~2F': '/' }[m])) : x;\n }\n\n dispose() {}\n\n constructor($locationProvider: ILocationProvider) {\n this.$locationProvider = $locationProvider;\n const _lp = val($locationProvider);\n createProxyFunctions(_lp, this, _lp, ['hashPrefix']);\n }\n\n onChange(callback: Function) {\n this._urlListeners.push(callback);\n return () => removeFrom(this._urlListeners)(callback);\n }\n\n html5Mode() {\n let html5Mode: any = this.$locationProvider.html5Mode();\n html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode;\n return html5Mode && this.$sniffer.history;\n }\n\n url(newUrl?: string, replace = false, state?) {\n if (isDefined(newUrl)) this.$location.url(newUrl);\n if (replace) this.$location.replace();\n if (state) this.$location.state(state);\n return this.$location.url();\n }\n\n _runtimeServices($rootScope, $location: ILocationService, $sniffer, $browser) {\n this.$location = $location;\n this.$sniffer = $sniffer;\n\n // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange\n $rootScope.$on('$locationChangeSuccess', evt => this._urlListeners.forEach(fn => fn(evt)));\n const _loc = val($location);\n const _browser = val($browser);\n\n // Bind these LocationService functions to $location\n createProxyFunctions(_loc, this, _loc, ['replace', 'path', 'search', 'hash']);\n // Bind these LocationConfig functions to $location\n createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);\n // Bind these LocationConfig functions to $browser\n createProxyFunctions(_browser, this, _browser, ['baseHref']);\n }\n}\n", + "/** @module url */ /** */\nimport {\n UIRouter,\n UrlRouter,\n LocationServices,\n $InjectorLike,\n BaseUrlRule,\n UrlRuleHandlerFn,\n UrlMatcher,\n IInjectable,\n} from '@uirouter/core';\nimport { services, isString, isFunction, isArray, identity } from '@uirouter/core';\n\nexport interface RawNg1RuleFunction {\n ($injector: $InjectorLike, $location: LocationServices): string | void;\n}\n\n/**\n * Manages rules for client-side URL\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class manages the router rules for what to do when the URL changes.\n *\n * This provider remains for backwards compatibility.\n *\n * @deprecated\n */\nexport class UrlRouterProvider {\n /** @hidden */ _router: UIRouter;\n /** @hidden */ _urlRouter: UrlRouter;\n\n static injectableHandler(router: UIRouter, handler): UrlRuleHandlerFn {\n return match => services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params });\n }\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this._urlRouter = router.urlRouter;\n }\n\n /** @hidden */\n $get() {\n const urlRouter = this._urlRouter;\n urlRouter.update(true);\n if (!urlRouter.interceptDeferred) urlRouter.listen();\n return urlRouter;\n }\n\n /**\n * Registers a url handler function.\n *\n * Registers a low level url handler (a `rule`).\n * A rule detects specific URL patterns and returns a redirect, or performs some action.\n *\n * If a rule returns a string, the URL is replaced with the string, and all rules are fired again.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Here's an example of how you might allow case insensitive urls\n * $urlRouterProvider.rule(function ($injector, $location) {\n * var path = $location.path(),\n * normalized = path.toLowerCase();\n *\n * if (path !== normalized) {\n * return normalized;\n * }\n * });\n * });\n * ```\n *\n * @param ruleFn\n * Handler function that takes `$injector` and `$location` services as arguments.\n * You can use them to detect a url and return a different url as a string.\n *\n * @return [[UrlRouterProvider]] (`this`)\n */\n rule(ruleFn: RawNg1RuleFunction): UrlRouterProvider {\n if (!isFunction(ruleFn)) throw new Error(\"'rule' must be a function\");\n\n const match = () => ruleFn(services.$injector, this._router.locationService);\n\n const rule = new BaseUrlRule(match, identity);\n this._urlRouter.rule(rule);\n return this;\n }\n\n /**\n * Defines the path or behavior to use when no url can be matched.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // if the path doesn't match any of the urls you configured\n * // otherwise will take care of routing the user to the\n * // specified url\n * $urlRouterProvider.otherwise('/index');\n *\n * // Example of using function rule as param\n * $urlRouterProvider.otherwise(function ($injector, $location) {\n * return '/a/valid/url';\n * });\n * });\n * ```\n *\n * @param rule\n * The url path you want to redirect to or a function rule that returns the url path or performs a `$state.go()`.\n * The function version is passed two params: `$injector` and `$location` services, and should return a url string.\n *\n * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n */\n otherwise(rule: string | RawNg1RuleFunction): UrlRouterProvider {\n const urlRouter = this._urlRouter;\n\n if (isString(rule)) {\n urlRouter.otherwise(rule);\n } else if (isFunction(rule)) {\n urlRouter.otherwise(() => rule(services.$injector, this._router.locationService));\n } else {\n throw new Error(\"'rule' must be a string or function\");\n }\n\n return this;\n }\n\n /**\n * Registers a handler for a given url matching.\n *\n * If the handler is a string, it is\n * treated as a redirect, and is interpolated according to the syntax of match\n * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n *\n * If the handler is a function, it is injectable.\n * It gets invoked if `$location` matches.\n * You have the option of inject the match object as `$match`.\n *\n * The handler can return\n *\n * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n * will continue trying to find another one that matches.\n * - **string** which is treated as a redirect and passed to `$location.url()`\n * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n * if ($state.$current.navigable !== state ||\n * !equalForKeys($match, $stateParams) {\n * $state.transitionTo(state, $match, false);\n * }\n * });\n * });\n * ```\n *\n * @param what A pattern string to match, compiled as a [[UrlMatcher]].\n * @param handler The path (or function that returns a path) that you want to redirect your user to.\n * @param ruleCallback [optional] A callback that receives the `rule` registered with [[UrlMatcher.rule]]\n *\n * Note: the handler may also invoke arbitrary code, such as `$state.go()`\n */\n when(what: RegExp | UrlMatcher | string, handler: string | IInjectable) {\n if (isArray(handler) || isFunction(handler)) {\n handler = UrlRouterProvider.injectableHandler(this._router, handler);\n }\n\n this._urlRouter.when(what, handler as any);\n return this;\n }\n\n /**\n * Disables monitoring of the URL.\n *\n * Call this method before UI-Router has bootstrapped.\n * It will stop UI-Router from performing the initial url sync.\n *\n * This can be useful to perform some asynchronous initialization before the router starts.\n * Once the initialization is complete, call [[listen]] to tell UI-Router to start watching and synchronizing the URL.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Prevent $urlRouter from automatically intercepting URL changes;\n * $urlRouterProvider.deferIntercept();\n * })\n *\n * app.run(function (MyService, $urlRouter, $http) {\n * $http.get(\"/stuff\").then(function(resp) {\n * MyService.doStuff(resp.data);\n * $urlRouter.listen();\n * $urlRouter.sync();\n * });\n * });\n * ```\n *\n * @param defer Indicates whether to defer location change interception.\n * Passing no parameter is equivalent to `true`.\n */\n deferIntercept(defer?: boolean) {\n this._urlRouter.deferIntercept(defer);\n }\n}\n", + "/**\n * # Angular 1 types\n *\n * UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc.\n * The customizations to the core types for Angular UI-Router are documented here.\n *\n * The optional [[$resolve]] service is also documented here.\n *\n * @module ng1\n * @preferred\n */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport {\n IRootScopeService,\n IQService,\n ILocationService,\n ILocationProvider,\n IHttpService,\n ITemplateCacheService,\n} from 'angular';\nimport {\n services,\n applyPairs,\n isString,\n trace,\n extend,\n UIRouter,\n StateService,\n UrlRouter,\n UrlMatcherFactory,\n ResolveContext,\n unnestR,\n TypedMap,\n} from '@uirouter/core';\nimport { ng1ViewsBuilder, getNg1ViewConfigFactory } from './statebuilders/views';\nimport { TemplateFactory } from './templateFactory';\nimport { StateProvider } from './stateProvider';\nimport { getStateHookBuilder } from './statebuilders/onEnterExitRetain';\nimport { Ng1LocationServices } from './locationServices';\nimport { UrlRouterProvider } from './urlRouterProvider';\nimport IInjectorService = angular.auto.IInjectorService; // tslint:disable-line\n\nangular.module('ui.router.angular1', []);\nconst mod_init = angular.module('ui.router.init', []);\nconst mod_util = angular.module('ui.router.util', ['ng', 'ui.router.init']);\nconst mod_rtr = angular.module('ui.router.router', ['ui.router.util']);\nconst mod_state = angular.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']);\nconst mod_main = angular.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']);\nlet mod_cmpt = angular.module('ui.router.compat', ['ui.router']); // tslint:disable-line\n\ndeclare module '@uirouter/core/lib/router' {\n interface UIRouter {\n // tslint:disable-line:no-shadowed-variable\n /** @hidden */\n stateProvider: StateProvider;\n /** @hidden */\n urlRouterProvider: UrlRouterProvider;\n }\n}\n\nlet router: UIRouter = null;\n\n$uiRouterProvider.$inject = ['$locationProvider'];\n/** This angular 1 provider instantiates a Router and exposes its services via the angular injector */\nfunction $uiRouterProvider($locationProvider: ILocationProvider) {\n // Create a new instance of the Router when the $uiRouterProvider is initialized\n router = this.router = new UIRouter();\n router.stateProvider = new StateProvider(router.stateRegistry, router.stateService);\n\n // Apply ng1 specific StateBuilder code for `views`, `resolve`, and `onExit/Retain/Enter` properties\n router.stateRegistry.decorator('views', ng1ViewsBuilder);\n router.stateRegistry.decorator('onExit', getStateHookBuilder('onExit'));\n router.stateRegistry.decorator('onRetain', getStateHookBuilder('onRetain'));\n router.stateRegistry.decorator('onEnter', getStateHookBuilder('onEnter'));\n\n router.viewService._pluginapi._viewConfigFactory('ng1', getNg1ViewConfigFactory());\n\n const ng1LocationService = (router.locationService = router.locationConfig = new Ng1LocationServices(\n $locationProvider,\n ));\n\n Ng1LocationServices.monkeyPatchPathParameterType(router);\n\n // backwards compat: also expose router instance as $uiRouterProvider.router\n router['router'] = router;\n router['$get'] = $get;\n $get.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache'];\n function $get(\n $location: ILocationService,\n $browser: any,\n $sniffer: any,\n $rootScope: ng.IScope,\n $http: IHttpService,\n $templateCache: ITemplateCacheService,\n ) {\n ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser);\n delete router['router'];\n delete router['$get'];\n return router;\n }\n return router;\n}\n\nconst getProviderFor = serviceName => [\n '$uiRouterProvider',\n $urp => {\n const service = $urp.router[serviceName];\n service['$get'] = () => service;\n return service;\n },\n];\n\n// This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime)\nrunBlock.$inject = ['$injector', '$q', '$uiRouter'];\nfunction runBlock($injector: IInjectorService, $q: IQService, $uiRouter: UIRouter) {\n services.$injector = $injector;\n services.$q = $q;\n\n // The $injector is now available.\n // Find any resolvables that had dependency annotation deferred\n $uiRouter.stateRegistry\n .get()\n .map(x => x.$$state().resolvables)\n .reduce(unnestR, [])\n .filter(x => x.deps === 'deferred')\n .forEach(resolvable => (resolvable.deps = $injector.annotate(resolvable.resolveFn, $injector.strictDi)));\n}\n\n// $urlRouter service and $urlRouterProvider\nconst getUrlRouterProvider = (uiRouter: UIRouter) => (uiRouter.urlRouterProvider = new UrlRouterProvider(uiRouter));\n\n// $state service and $stateProvider\n// $urlRouter service and $urlRouterProvider\nconst getStateProvider = () => extend(router.stateProvider, { $get: () => router.stateService });\n\nwatchDigests.$inject = ['$rootScope'];\nexport function watchDigests($rootScope: IRootScopeService) {\n $rootScope.$watch(function() {\n trace.approximateDigests++;\n });\n}\n\nmod_init.provider('$uiRouter', $uiRouterProvider);\nmod_rtr.provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]);\nmod_util.provider('$urlService', getProviderFor('urlService'));\nmod_util.provider('$urlMatcherFactory', ['$uiRouterProvider', () => router.urlMatcherFactory]);\nmod_util.provider('$templateFactory', () => new TemplateFactory());\nmod_state.provider('$stateRegistry', getProviderFor('stateRegistry'));\nmod_state.provider('$uiRouterGlobals', getProviderFor('globals'));\nmod_state.provider('$transitions', getProviderFor('transitionService'));\nmod_state.provider('$state', ['$uiRouterProvider', getStateProvider]);\n\nmod_state.factory('$stateParams', ['$uiRouter', ($uiRouter: UIRouter) => $uiRouter.globals.params]);\nmod_main.factory('$view', () => router.viewService);\nmod_main.service('$trace', () => trace);\n\nmod_main.run(watchDigests);\nmod_util.run(['$urlMatcherFactory', function($urlMatcherFactory: UrlMatcherFactory) {}]);\nmod_state.run(['$state', function($state: StateService) {}]);\nmod_rtr.run(['$urlRouter', function($urlRouter: UrlRouter) {}]);\nmod_init.run(runBlock);\n\n/** @hidden TODO: find a place to move this */\nexport const getLocals = (ctx: ResolveContext): TypedMap => {\n const tokens = ctx.getTokens().filter(isString);\n\n const tuples = tokens.map(key => {\n const resolvable = ctx.getResolvable(key);\n const waitPolicy = ctx.getPolicy(resolvable).async;\n return [key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data];\n });\n\n return tuples.reduce(applyPairs, {});\n};\n", + "/**\n * # Angular 1 injectable services\n *\n * This is a list of the objects which can be injected using angular's injector.\n *\n * There are three different kind of injectable objects:\n *\n * ## **Provider** objects\n * #### injectable into a `.config()` block during configtime\n *\n * - [[$uiRouterProvider]]: The UI-Router instance\n * - [[$stateProvider]]: State registration\n * - [[$transitionsProvider]]: Transition hooks\n * - [[$urlServiceProvider]]: All URL related public APIs\n *\n * - [[$uiViewScrollProvider]]: Disable ui-router view scrolling\n * - [[$urlRouterProvider]]: (deprecated) Url matching rules\n * - [[$urlMatcherFactoryProvider]]: (deprecated) Url parsing config\n *\n * ## **Service** objects\n * #### injectable globally during runtime\n *\n * - [[$uiRouter]]: The UI-Router instance\n * - [[$trace]]: Enable transition trace/debug\n * - [[$transitions]]: Transition hooks\n * - [[$state]]: Imperative state related APIs\n * - [[$stateRegistry]]: State registration\n * - [[$urlService]]: All URL related public APIs\n * - [[$uiRouterGlobals]]: Global variables\n * - [[$uiViewScroll]]: Scroll an element into view\n *\n * - [[$stateParams]]: (deprecated) Global state param values\n * - [[$urlRouter]]: (deprecated) URL synchronization\n * - [[$urlMatcherFactory]]: (deprecated) URL parsing config\n *\n * ## **Per-Transition** objects\n *\n * - These kind of objects are injectable into:\n * - Resolves ([[Ng1StateDeclaration.resolve]]),\n * - Transition Hooks ([[TransitionService.onStart]], etc),\n * - Routed Controllers ([[Ng1ViewDeclaration.controller]])\n *\n * #### Different instances are injected based on the [[Transition]]\n *\n * - [[$transition$]]: The current Transition object\n * - [[$stateParams]]: State param values for pending Transition (deprecated)\n * - Any resolve data defined using [[Ng1StateDeclaration.resolve]]\n *\n * @ng1api\n * @preferred\n * @module injectables\n */ /** */\n/* tslint:disable:prefer-const */\nimport { StateProvider } from './stateProvider';\nimport {\n StateService,\n TransitionService,\n Transition,\n UrlRouter,\n UrlMatcherFactory,\n StateParams,\n StateRegistry,\n UIRouterGlobals,\n UIRouter,\n Trace,\n UrlService,\n} from '@uirouter/core';\nimport { UIViewScrollProvider } from './viewScroll';\nimport { UrlRouterProvider } from './urlRouterProvider';\n\n/**\n * The current (or pending) State Parameters\n *\n * An injectable global **Service Object** which holds the state parameters for the latest **SUCCESSFUL** transition.\n *\n * The values are not updated until *after* a `Transition` successfully completes.\n *\n * **Also:** an injectable **Per-Transition Object** object which holds the pending state parameters for the pending `Transition` currently running.\n *\n * ### Deprecation warning:\n *\n * The value injected for `$stateParams` is different depending on where it is injected.\n *\n * - When injected into an angular service, the object injected is the global **Service Object** with the parameter values for the latest successful `Transition`.\n * - When injected into transition hooks, resolves, or view controllers, the object is the **Per-Transition Object** with the parameter values for the running `Transition`.\n *\n * Because of these confusing details, this service is deprecated.\n *\n * ### Instead of using the global `$stateParams` service object,\n * inject [[$uiRouterGlobals]] and use [[UIRouterGlobals.params]]\n *\n * ```js\n * MyService.$inject = ['$uiRouterGlobals'];\n * function MyService($uiRouterGlobals) {\n * return {\n * paramValues: function () {\n * return $uiRouterGlobals.params;\n * }\n * }\n * }\n * ```\n *\n * ### Instead of using the per-transition `$stateParams` object,\n * inject the current `Transition` (as [[$transition$]]) and use [[Transition.params]]\n *\n * ```js\n * MyController.$inject = ['$transition$'];\n * function MyController($transition$) {\n * var username = $transition$.params().username;\n * // .. do something with username\n * }\n * ```\n *\n * ---\n *\n * This object can be injected into other services.\n *\n * #### Deprecated Example:\n * ```js\n * SomeService.$inject = ['$http', '$stateParams'];\n * function SomeService($http, $stateParams) {\n * return {\n * getUser: function() {\n * return $http.get('/api/users/' + $stateParams.username);\n * }\n * }\n * };\n * angular.service('SomeService', SomeService);\n * ```\n * @deprecated\n */\nlet $stateParams: StateParams;\n\n/**\n * Global UI-Router variables\n *\n * The router global state as a **Service Object** (injectable during runtime).\n *\n * This object contains globals such as the current state and current parameter values.\n */\nlet $uiRouterGlobals: UIRouterGlobals;\n\n/**\n * The UI-Router instance\n *\n * The [[UIRouter]] singleton (the router instance) as a **Service Object** (injectable during runtime).\n *\n * This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.\n * It has references to the other UI-Router services\n *\n * #### Note: This object is also exposed as [[$uiRouterProvider]] for injection during angular config time.\n */\nlet $uiRouter: UIRouter;\n\n/**\n * The UI-Router instance\n *\n * The [[UIRouter]] singleton (the router instance) as a **Provider Object** (injectable during config phase).\n *\n * This object is the UI-Router singleton instance, created by angular dependency injection during application bootstrap.\n * It has references to the other UI-Router services\n *\n * #### Note: This object is also exposed as [[$uiRouter]] for injection during runtime.\n */\nlet $uiRouterProvider: UIRouter;\n\n/**\n * Transition debug/tracing\n *\n * The [[Trace]] singleton as a **Service Object** (injectable during runtime).\n *\n * Enables or disables Transition tracing which can help to debug issues.\n */\nlet $trace: Trace;\n\n/**\n * The Transition Service\n *\n * The [[TransitionService]] singleton as a **Service Object** (injectable during runtime).\n *\n * This angular service exposes the [[TransitionService]] singleton, which is primarily\n * used to register global transition hooks.\n *\n * #### Note: This object is also exposed as [[$transitionsProvider]] for injection during the config phase.\n */\nlet $transitions: TransitionService;\n\n/**\n * The Transition Service\n *\n * The [[TransitionService]] singleton as a **Provider Object** (injectable during config phase)\n *\n * This angular service exposes the [[TransitionService]] singleton, which is primarily\n * used to register global transition hooks.\n *\n * #### Note: This object is also exposed as [[$transitions]] for injection during runtime.\n */\nlet $transitionsProvider: TransitionService;\n\n/**\n * The current [[Transition]] object\n *\n * The current [[Transition]] object as a **Per-Transition Object** (injectable into Resolve, Hooks, Controllers)\n *\n * This object returns information about the current transition, including:\n *\n * - To/from states\n * - To/from parameters\n * - Transition options\n * - States being entered, exited, and retained\n * - Resolve data\n * - A Promise for the transition\n * - Any transition failure information\n * - An injector for both Service and Per-Transition Objects\n */\nlet $transition$: Transition;\n\n/**\n * The State Service\n *\n * The [[StateService]] singleton as a **Service Object** (injectable during runtime).\n *\n * This service used to manage and query information on registered states.\n * It exposes state related APIs including:\n *\n * - Start a [[Transition]]\n * - Imperatively lazy load states\n * - Check if a state is currently active\n * - Look up states by name\n * - Build URLs for a state+parameters\n * - Configure the global Transition error handler\n *\n * This angular service exposes the [[StateService]] singleton.\n */\nlet $state: StateService;\n\n/**\n * The State Registry\n *\n * The [[StateRegistry]] singleton as a **Service Object** (injectable during runtime).\n *\n * This service is used to register/deregister states.\n * It has state registration related APIs including:\n *\n * - Register/deregister states\n * - Listen for state registration/deregistration\n * - Get states by name\n * - Add state decorators (to customize the state creation process)\n *\n * #### Note: This object is also exposed as [[$stateRegistryProvider]] for injection during the config phase.\n */\nlet $stateRegistry: StateRegistry;\n\n/**\n * The State Registry\n *\n * The [[StateRegistry]] singleton as a **Provider Object** (injectable during config time).\n *\n * This service is used to register/deregister states.\n * It has state registration related APIs including:\n *\n * - Register/deregister states\n * - Listen for state registration/deregistration\n * - Get states by name\n * - Add state decorators (to customize the state creation process)\n *\n * #### Note: This object is also exposed as [[$stateRegistry]] for injection during runtime.\n */\nlet $stateRegistryProvider: StateRegistry;\n\n/**\n * The View Scroll provider\n *\n * The [[UIViewScrollProvider]] as a **Provider Object** (injectable during config time).\n *\n * This angular service exposes the [[UIViewScrollProvider]] singleton and is\n * used to disable UI-Router's scroll behavior.\n */\nlet $uiViewScrollProvider: UIViewScrollProvider;\n\n/**\n * The View Scroll function\n *\n * The View Scroll function as a **Service Object** (injectable during runtime).\n *\n * This is a function that scrolls an element into view.\n * The element is scrolled after a `$timeout` so the DOM has time to refresh.\n *\n * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,\n * this can be enabled by calling [[UIViewScrollProvider.useAnchorScroll]].\n *\n * Note: this function is used by the [[directives.uiView]] when the `autoscroll` expression evaluates to true.\n */\nlet $uiViewScroll: ($element: JQuery) => void;\n\n/**\n * The StateProvider\n *\n * An angular1-only [[StateProvider]] as a **Provider Object** (injectable during config time).\n *\n * This angular service exposes the [[StateProvider]] singleton.\n *\n * The `StateProvider` is primarily used to register states or add custom state decorators.\n *\n * ##### Note: This provider is a ng1 vestige.\n * It is a passthrough to [[$stateRegistry]] and [[$state]].\n */\nlet $stateProvider: StateProvider;\n\n/**\n * The URL Service Provider\n *\n * The [[UrlService]] singleton as a **Provider Object** (injectable during the angular config phase).\n *\n * A service used to configure and interact with the URL.\n * It has URL related APIs including:\n *\n * - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])\n * - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])\n * - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])\n * - delay initial URL synchronization [[UrlService.deferIntercept]].\n * - get or set the current url: [[UrlService.url]]\n *\n * ##### Note: This service can also be injected during runtime as [[$urlService]].\n */\nlet $urlServiceProvider: UrlService;\n\n/**\n * The URL Service\n *\n * The [[UrlService]] singleton as a **Service Object** (injectable during runtime).\n *\n * Note: This service can also be injected during the config phase as [[$urlServiceProvider]].\n *\n * Used to configure the URL.\n * It has URL related APIs including:\n *\n * - register custom Parameter types `UrlService.config.type` ([[UrlConfigApi.type]])\n * - add URL rules: `UrlService.rules.when` ([[UrlRulesApi.when]])\n * - configure behavior when no url matches: `UrlService.rules.otherwise` ([[UrlRulesApi.otherwise]])\n * - delay initial URL synchronization [[UrlService.deferIntercept]].\n * - get or set the current url: [[UrlService.url]]\n *\n * ##### Note: This service can also be injected during the config phase as [[$urlServiceProvider]].\n */\nlet $urlService: UrlService;\n\n/**\n * The URL Router Provider\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlServiceProvider]] instead.\n *\n * The [[UrlRouter]] singleton as a **Provider Object** (injectable during config time).\n *\n * #### Note: This object is also exposed as [[$urlRouter]] for injection during runtime.\n *\n * @deprecated\n */\nlet $urlRouterProvider: UrlRouterProvider;\n\n/**\n * The Url Router\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.\n *\n * The [[UrlRouter]] singleton as a **Service Object** (injectable during runtime).\n *\n * #### Note: This object is also exposed as [[$urlRouterProvider]] for injection during angular config time.\n *\n * @deprecated\n */\nlet $urlRouter: UrlRouter;\n\n/**\n * The URL Matcher Factory\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.\n *\n * The [[UrlMatcherFactory]] singleton as a **Service Object** (injectable during runtime).\n *\n * This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.\n *\n * #### Note: This object is also exposed as [[$urlMatcherFactoryProvider]] for injection during angular config time.\n *\n * @deprecated\n */\nlet $urlMatcherFactory: UrlMatcherFactory;\n\n/**\n * The URL Matcher Factory\n *\n * ### Deprecation warning: This object is now considered internal. Use [[$urlService]] instead.\n *\n * The [[UrlMatcherFactory]] singleton as a **Provider Object** (injectable during config time).\n *\n * This service is used to set url mapping options, define custom parameter types, and create [[UrlMatcher]] objects.\n *\n * #### Note: This object is also exposed as [[$urlMatcherFactory]] for injection during runtime.\n *\n * @deprecated\n */\nlet $urlMatcherFactoryProvider: UrlMatcherFactory;\n", + "/**\n * # Angular 1 Directives\n *\n * These are the directives included in UI-Router for Angular 1.\n * These directives are used in templates to create viewports and link/navigate to states.\n *\n * @ng1api\n * @preferred\n * @module directives\n */ /** for typedoc */\nimport { ng as angular } from '../angular';\nimport { IAugmentedJQuery, ITimeoutService, IScope, IInterpolateService } from 'angular';\n\nimport {\n Obj,\n extend,\n forEach,\n tail,\n isString,\n isObject,\n isArray,\n parse,\n noop,\n unnestR,\n identity,\n uniqR,\n inArray,\n removeFrom,\n RawParams,\n PathNode,\n StateOrName,\n StateService,\n StateDeclaration,\n UIRouter,\n} from '@uirouter/core';\nimport { UIViewData } from './viewDirective';\nimport EventHandler = JQuery.EventHandler;\n\n/** @hidden Used for typedoc */\nexport interface ng1_directive {} // tslint:disable-line:class-name\n\n/** @hidden */\nfunction parseStateRef(ref: string) {\n let parsed;\n const paramsOnly = ref.match(/^\\s*({[^}]*})\\s*$/);\n if (paramsOnly) ref = '(' + paramsOnly[1] + ')';\n\n parsed = ref.replace(/\\n/g, ' ').match(/^\\s*([^(]*?)\\s*(\\((.*)\\))?\\s*$/);\n if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n return { state: parsed[1] || null, paramExpr: parsed[3] || null };\n}\n\n/** @hidden */\nfunction stateContext(el: IAugmentedJQuery) {\n const $uiView: UIViewData = (el.parent() as IAugmentedJQuery).inheritedData('$uiView');\n const path: PathNode[] = parse('$cfg.path')($uiView);\n return path ? tail(path).state.name : undefined;\n}\n\n/** @hidden */\nfunction processedDef($state: StateService, $element: IAugmentedJQuery, def: Def): Def {\n const uiState = def.uiState || $state.current.name;\n const uiStateOpts = extend(defaultOpts($element, $state), def.uiStateOpts || {});\n const href = $state.href(uiState, def.uiStateParams, uiStateOpts);\n return { uiState, uiStateParams: def.uiStateParams, uiStateOpts, href };\n}\n\n/** @hidden */\ninterface TypeInfo {\n attr: string;\n isAnchor: boolean;\n clickable: boolean;\n}\n\n/** @hidden */\nfunction getTypeInfo(el: IAugmentedJQuery): TypeInfo {\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n const isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';\n const isForm = el[0].nodeName === 'FORM';\n\n return {\n attr: isForm ? 'action' : isSvg ? 'xlink:href' : 'href',\n isAnchor: el.prop('tagName').toUpperCase() === 'A',\n clickable: !isForm,\n };\n}\n\n/** @hidden */\nfunction clickHook(\n el: IAugmentedJQuery,\n $state: StateService,\n $timeout: ITimeoutService,\n type: TypeInfo,\n getDef: () => Def,\n) {\n return function(e: JQueryMouseEventObject) {\n const button = e.which || e.button,\n target = getDef();\n\n if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {\n // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n const transition = $timeout(function() {\n $state.go(target.uiState, target.uiStateParams, target.uiStateOpts);\n });\n e.preventDefault();\n\n // if the state has no URL, ignore one preventDefault from the directive.\n let ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;\n\n e.preventDefault = function() {\n if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);\n };\n }\n };\n}\n\n/** @hidden */\nfunction defaultOpts(el: IAugmentedJQuery, $state: StateService) {\n return {\n relative: stateContext(el) || $state.$current,\n inherit: true,\n source: 'sref',\n };\n}\n\n/** @hidden */\nfunction bindEvents(element: IAugmentedJQuery, scope: IScope, hookFn: EventHandler, uiStateOpts: any): void {\n let events;\n\n if (uiStateOpts) {\n events = uiStateOpts.events;\n }\n\n if (!isArray(events)) {\n events = ['click'];\n }\n\n const on = element.on ? 'on' : 'bind';\n for (const event of events) {\n element[on](event, hookFn);\n }\n\n scope.$on('$destroy', function() {\n const off = element.off ? 'off' : 'unbind';\n for (const event of events) {\n element[off](event, hookFn);\n }\n });\n}\n\n/**\n * `ui-sref`: A directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of the `ui-sref` is the name of the state to link to.\n *\n * #### Example:\n * This will activate the `home` state when the link is clicked.\n * ```html\n * Home\n * ```\n *\n * ### Relative Links\n * You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]).\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create a relative `ui-sref` which always targets the same destination.\n *\n * #### Example:\n * Both these links are relative to the parent state, even when a child state is currently active.\n * ```html\n * child 1 state\n * child 2 state\n * ```\n *\n * This link activates the parent state.\n * ```html\n * Return\n * ```\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * #### Example:\n * Assuming the `users` state has a url of `/users/`\n * ```html\n * Users\n * ```\n *\n * ### Parameter Values\n * In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state.\n * Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses.\n * The content inside the parentheses is an expression, evaluated to the parameter values.\n *\n * #### Example:\n * This example renders a list of links to users.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ user.displayName }}\n *
  • \n * ```\n *\n * Note:\n * The parameter values expression is `$watch`ed for updates.\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-sref-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Examples\n * If you have the following template:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n * \n * ```\n *\n * Then (assuming the current state is `contacts`) the rendered html including hrefs would be:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n *
      \n *
    • \n * Joe\n *
    • \n *
    • \n * Alice\n *
    • \n *
    • \n * Bob\n *
    • \n *
    \n *\n * Home\n * ```\n *\n * ### Notes\n *\n * - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses.\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n *\n * - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons).\n * If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive.\n */\nlet uiSrefDirective: ng1_directive;\nuiSrefDirective = [\n '$uiRouter',\n '$timeout',\n function $StateRefDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function(scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const ref = parseStateRef(attrs.uiSref);\n rawDef.uiState = ref.state;\n rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {};\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n if (ref.paramExpr) {\n scope.$watch(\n ref.paramExpr,\n function(val) {\n rawDef.uiStateParams = extend({}, val);\n update();\n },\n true,\n );\n rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr));\n }\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n },\n];\n\n/**\n * `ui-state`: A fully dynamic directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.**\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to.\n * **This is in contrast with `ui-sref`, which takes a state name as a string literal.**\n *\n * #### Example:\n * Create a list of links.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Relative Links\n * If the expression evaluates to a relative path, it is processed like [[uiSref]].\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create relative `ui-state` which always targets the same destination.\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * ### Parameter Values\n * In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state.\n * Param values should be provided using the `ui-state-params` attribute.\n * The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * This example renders a list of links with param values.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n * The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-state-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Notes\n *\n * - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`.\n * However, it might be simpler to use [[uiSref]] parameter-only links.\n *\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n * ```\n */\nlet uiStateDirective: ng1_directive;\nuiStateDirective = [\n '$uiRouter',\n '$timeout',\n function $StateRefDynamicDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function(scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts'];\n const watchDeregFns = inputAttrs.reduce((acc, attr) => ((acc[attr] = noop), acc), {});\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n inputAttrs.forEach(field => {\n rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null;\n\n attrs.$observe(field, expr => {\n watchDeregFns[field]();\n watchDeregFns[field] = scope.$watch(\n expr,\n newval => {\n rawDef[field] = newval;\n update();\n },\n true,\n );\n });\n });\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n },\n];\n\n/**\n * `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active\n *\n * A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the\n * related directive's state is active (and remove them when it is inactive).\n *\n * The primary use-case is to highlight the active link in navigation menus,\n * distinguishing it from the inactive menu items.\n *\n * ### Linking to a `ui-sref` or `ui-state`\n * `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element.\n * If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**.\n *\n * ### Matching\n *\n * The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**.\n * This is a \"fuzzy match\" which uses [[StateService.includes]].\n *\n * The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active).\n * This is an \"exact match\" which uses [[StateService.is]].\n *\n * ### Parameter values\n * If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted.\n * This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted.\n *\n * #### Example:\n * ```html\n *
  • \n * {{ user.lastName }}\n *
  • \n * ```\n *\n * ### Examples\n *\n * Given the following template:\n * #### Example:\n * ```html\n * \n * ```\n *\n * When the app state is `app.user` (or any child state),\n * and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n *\n * ```html\n * \n * ```\n *\n * ### Glob mode\n *\n * It is possible to pass `ui-sref-active` an expression that evaluates to an object.\n * The objects keys represent active class names and values represent the respective state names/globs.\n * `ui-sref-active` will match if the current active state **includes** any of\n * the specified state names/globs, even the abstract ones.\n *\n * #### Example:\n * Given the following template, with \"admin\" being an abstract state:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * Arrays are also supported as values in the `ngClass`-like interface.\n * This allows multiple states to add `active` class.\n *\n * #### Example:\n * Given the following template, with \"admin.roles\" being the current state, the class will be added too:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * When the current state is \"admin.roles\" the \"active\" class will be applied to both the `
    ` and `` elements.\n * It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`.\n *\n * ### Notes:\n *\n * - The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'`\n */\nlet uiSrefActiveDirective: ng1_directive;\nuiSrefActiveDirective = [\n '$state',\n '$stateParams',\n '$interpolate',\n '$uiRouter',\n function $StateRefActiveDirective(\n $state: StateService,\n $stateParams: Obj,\n $interpolate: IInterpolateService,\n $uiRouter: UIRouter,\n ) {\n return {\n restrict: 'A',\n controller: [\n '$scope',\n '$element',\n '$attrs',\n function($scope: IScope, $element: IAugmentedJQuery, $attrs: any) {\n let states: StateData[] = [];\n let activeEqClass: string;\n let uiSrefActive: any;\n\n // There probably isn't much point in $observing this\n // uiSrefActive and uiSrefActiveEq share the same directive object with some\n // slight difference in logic routing\n activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);\n\n try {\n uiSrefActive = $scope.$eval($attrs.uiSrefActive);\n } catch (e) {\n // Do nothing. uiSrefActive is not a valid expression.\n // Fall back to using $interpolate below\n }\n uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);\n setStatesFromDefinitionObject(uiSrefActive);\n\n // Allow uiSref to communicate with uiSrefActive[Equals]\n this.$$addStateInfo = function(newState: string, newParams: Obj) {\n // we already got an explicit state provided by ui-sref-active, so we\n // shadow the one that comes from ui-sref\n if (isObject(uiSrefActive) && states.length > 0) {\n return;\n }\n const deregister = addState(newState, newParams, uiSrefActive);\n update();\n return deregister;\n };\n\n function updateAfterTransition(trans) {\n trans.promise.then(update, noop);\n }\n $scope.$on('$destroy', setupEventListeners());\n if ($uiRouter.globals.transition) {\n updateAfterTransition($uiRouter.globals.transition);\n }\n\n function setupEventListeners() {\n const deregisterStatesChangedListener = $uiRouter.stateRegistry.onStatesChanged(handleStatesChanged);\n const deregisterOnStartListener = $uiRouter.transitionService.onStart({}, updateAfterTransition);\n const deregisterStateChangeSuccessListener = $scope.$on('$stateChangeSuccess', update);\n return function cleanUp() {\n deregisterStatesChangedListener();\n deregisterOnStartListener();\n deregisterStateChangeSuccessListener();\n };\n }\n\n function handleStatesChanged() {\n setStatesFromDefinitionObject(uiSrefActive);\n }\n\n function setStatesFromDefinitionObject(statesDefinition: object) {\n if (isObject(statesDefinition)) {\n states = [];\n forEach(statesDefinition, function(stateOrName: StateOrName | Array, activeClass: string) {\n // Helper function to abstract adding state.\n const addStateForClass = function(stateOrName: string, activeClass: string) {\n const ref = parseStateRef(stateOrName);\n addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);\n };\n\n if (isString(stateOrName)) {\n // If state is string, just add it.\n addStateForClass(stateOrName as string, activeClass);\n } else if (isArray(stateOrName)) {\n // If state is an array, iterate over it and add each array item individually.\n forEach(stateOrName, function(stateOrName: string) {\n addStateForClass(stateOrName, activeClass);\n });\n }\n });\n }\n }\n\n function addState(stateName: string, stateParams: Obj, activeClass: string) {\n const state = $state.get(stateName, stateContext($element));\n\n const stateInfo = {\n state: state || { name: stateName },\n params: stateParams,\n activeClass: activeClass,\n };\n\n states.push(stateInfo);\n\n return function removeState() {\n removeFrom(states)(stateInfo);\n };\n }\n\n // Update route state\n function update() {\n const splitClasses = str => str.split(/\\s/).filter(identity);\n const getClasses = (stateList: StateData[]) =>\n stateList\n .map(x => x.activeClass)\n .map(splitClasses)\n .reduce(unnestR, []);\n\n const allClasses = getClasses(states)\n .concat(splitClasses(activeEqClass))\n .reduce(uniqR, []);\n const fuzzyClasses = getClasses(states.filter(x => $state.includes(x.state.name, x.params)));\n const exactlyMatchesAny = !!states.filter(x => $state.is(x.state.name, x.params)).length;\n const exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : [];\n\n const addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []);\n const removeClasses = allClasses.filter(cls => !inArray(addClasses, cls));\n\n $scope.$evalAsync(() => {\n addClasses.forEach(className => $element.addClass(className));\n removeClasses.forEach(className => $element.removeClass(className));\n });\n }\n\n update();\n },\n ],\n };\n },\n];\n\n/** @hidden */\ninterface Def {\n uiState: string;\n href: string;\n uiStateParams: Obj;\n uiStateOpts: any;\n}\n/** @hidden */\ninterface StateData {\n state: StateDeclaration;\n params: RawParams;\n activeClass: string;\n}\n\nangular\n .module('ui.router.state')\n .directive('uiSref', uiSrefDirective)\n .directive('uiSrefActive', uiSrefActiveDirective)\n .directive('uiSrefActiveEq', uiSrefActiveDirective)\n .directive('uiState', uiStateDirective);\n", + "/** @module ng1 */ /** for typedoc */\n\nimport { ng as angular } from './angular';\nimport { Obj, StateService, StateOrName } from '@uirouter/core';\n\n/**\n * `isState` Filter: truthy if the current state is the parameter\n *\n * Translates to [[StateService.is]] `$state.is(\"stateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state is 'stateName'
    \n * ```\n */\n$IsStateFilter.$inject = ['$state'];\nexport function $IsStateFilter($state: StateService) {\n const isFilter: any = function(state: StateOrName, params: Obj, options?: { relative?: StateOrName }) {\n return $state.is(state, params, options);\n };\n isFilter.$stateful = true;\n return isFilter;\n}\n\n/**\n * `includedByState` Filter: truthy if the current state includes the parameter\n *\n * Translates to [[StateService.includes]]` $state.is(\"fullOrPartialStateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state includes 'fullOrPartialStateName'
    \n * ```\n */\n$IncludedByStateFilter.$inject = ['$state'];\nexport function $IncludedByStateFilter($state: StateService) {\n const includesFilter: any = function(state: StateOrName, params: Obj, options: { relative?: StateOrName }) {\n return $state.includes(state, params, options);\n };\n includesFilter.$stateful = true;\n return includesFilter;\n}\n\nangular\n .module('ui.router.state')\n .filter('isState', $IsStateFilter)\n .filter('includedByState', $IncludedByStateFilter);\n", + "/**\n * @ng1api\n * @module directives\n */\n\nimport {\n $QLike,\n ActiveUIView,\n extend,\n filter,\n HookRegOptions,\n isDefined,\n isFunction,\n isString,\n kebobString,\n noop,\n Obj,\n Param,\n parse,\n PathNode,\n ResolveContext,\n StateDeclaration,\n tail,\n trace,\n Transition,\n TransitionService,\n TypedMap,\n unnestR,\n ViewService,\n} from '@uirouter/core';\nimport { IAugmentedJQuery, IInterpolateService, IScope, ITimeoutService, ITranscludeFunction } from 'angular';\nimport { ng as angular } from '../angular';\nimport { Ng1Controller, Ng1StateDeclaration } from '../interface';\nimport { getLocals } from '../services';\nimport { Ng1ViewConfig } from '../statebuilders/views';\nimport { ng1_directive } from './stateDirectives';\n\n/** @hidden */\nexport type UIViewData = {\n $cfg: Ng1ViewConfig;\n $uiView: ActiveUIView;\n};\n\n/** @hidden */\nexport type UIViewAnimData = {\n $animEnter: Promise;\n $animLeave: Promise;\n $$animLeave: { resolve: () => any }; // \"deferred\"\n};\n\n/**\n * `ui-view`: A viewport directive which is filled in by a view from the active state.\n *\n * ### Attributes\n *\n * - `name`: (Optional) A view name.\n * The name should be unique amongst the other views in the same state.\n * You can have views of the same name that live in different states.\n * The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]).\n *\n * - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated.\n * Uses [[$uiViewScroll]] to do the scrolling.\n *\n * - `onload`: Expression to evaluate whenever the view updates.\n *\n * #### Example:\n * A view can be unnamed or named.\n * ```html\n * \n *
    \n *\n * \n *
    \n *\n * \n * \n * ```\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a\n * single view and it is unnamed then you can populate it like so:\n *\n * ```html\n *
    \n * $stateProvider.state(\"home\", {\n * template: \"

    HELLO!

    \"\n * })\n * ```\n *\n * The above is a convenient shortcut equivalent to specifying your view explicitly with the\n * [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name:\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * But typically you'll only use the views property if you name your view or have more than one view\n * in the same template. There's not really a compelling reason to name a view if its the only one,\n * but you could if you wanted, like so:\n *\n * ```html\n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"main\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * Really though, you'll use views to set up multiple views:\n *\n * ```html\n *
    \n *
    \n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * },\n * \"chart\": {\n * template: \"\"\n * },\n * \"data\": {\n * template: \"\"\n * }\n * }\n * })\n * ```\n *\n * #### Examples for `autoscroll`:\n * ```html\n * \n * \n *\n * \n * \n * \n * \n * ```\n *\n * Resolve data:\n *\n * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this\n * can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template.\n *\n * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the\n * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which\n * depends on `$resolve` data.\n *\n * #### Example:\n * ```js\n * $stateProvider.state('home', {\n * template: '',\n * resolve: {\n * user: function(UserService) { return UserService.fetchUser(); }\n * }\n * });\n * ```\n */\nexport let uiView: ng1_directive;\nuiView = [\n '$view',\n '$animate',\n '$uiViewScroll',\n '$interpolate',\n '$q',\n function $ViewDirective(\n $view: ViewService,\n $animate: any,\n $uiViewScroll: any,\n $interpolate: IInterpolateService,\n $q: $QLike,\n ) {\n function getRenderer(attrs: Obj, scope: IScope) {\n return {\n enter: function(element: JQuery, target: any, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.enter(element, null, target).then(cb);\n } else {\n $animate.enter(element, null, target, cb);\n }\n },\n leave: function(element: JQuery, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.leave(element).then(cb);\n } else {\n $animate.leave(element, cb);\n }\n },\n };\n }\n\n function configsEqual(config1: Ng1ViewConfig, config2: Ng1ViewConfig) {\n return config1 === config2;\n }\n\n const rootData = {\n $cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } },\n $uiView: {},\n };\n\n const directive = {\n count: 0,\n restrict: 'ECA',\n terminal: true,\n priority: 400,\n transclude: 'element',\n compile: function(tElement: JQuery, tAttrs: Obj, $transclude: ITranscludeFunction) {\n return function(scope: IScope, $element: IAugmentedJQuery, attrs: Obj) {\n const onloadExp = attrs['onload'] || '',\n autoScrollExp = attrs['autoscroll'],\n renderer = getRenderer(attrs, scope),\n inherited = $element.inheritedData('$uiView') || rootData,\n name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default';\n\n let previousEl: JQuery,\n currentEl: JQuery,\n currentScope: IScope,\n viewConfig: Ng1ViewConfig,\n unregister: Function;\n\n const activeUIView: ActiveUIView = {\n $type: 'ng1',\n id: directive.count++, // Global sequential ID for ui-view tags added to DOM\n name: name, // ui-view name (
    \n fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + '.' + name : name, // fully qualified name, describes location in DOM\n config: null, // The ViewConfig loaded (from a state.views definition)\n configUpdated: configUpdatedCallback, // Called when the matching ViewConfig changes\n get creationContext() {\n // The context in which this ui-view \"tag\" was created\n const fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited);\n // Allow \n // See https://github.com/angular-ui/ui-router/issues/3355\n const fromParentTag = parse('$uiView.creationContext')(inherited);\n return fromParentTagConfig || fromParentTag;\n },\n };\n\n trace.traceUIViewEvent('Linking', activeUIView);\n\n function configUpdatedCallback(config?: Ng1ViewConfig) {\n if (config && !(config instanceof Ng1ViewConfig)) return;\n if (configsEqual(viewConfig, config)) return;\n trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context);\n\n viewConfig = config;\n updateView(config);\n }\n\n $element.data('$uiView', { $uiView: activeUIView });\n\n updateView();\n\n unregister = $view.registerUIView(activeUIView);\n scope.$on('$destroy', function() {\n trace.traceUIViewEvent('Destroying/Unregistering', activeUIView);\n unregister();\n });\n\n function cleanupLastView() {\n if (previousEl) {\n trace.traceUIViewEvent('Removing (previous) el', previousEl.data('$uiView'));\n previousEl.remove();\n previousEl = null;\n }\n\n if (currentScope) {\n trace.traceUIViewEvent('Destroying scope', activeUIView);\n currentScope.$destroy();\n currentScope = null;\n }\n\n if (currentEl) {\n const _viewData = currentEl.data('$uiViewAnim');\n trace.traceUIViewEvent('Animate out', _viewData);\n renderer.leave(currentEl, function() {\n _viewData.$$animLeave.resolve();\n previousEl = null;\n });\n\n previousEl = currentEl;\n currentEl = null;\n }\n }\n\n function updateView(config?: Ng1ViewConfig) {\n const newScope = scope.$new();\n const animEnter = $q.defer(),\n animLeave = $q.defer();\n\n const $uiViewData: UIViewData = {\n $cfg: config,\n $uiView: activeUIView,\n };\n\n const $uiViewAnim: UIViewAnimData = {\n $animEnter: animEnter.promise,\n $animLeave: animLeave.promise,\n $$animLeave: animLeave,\n };\n\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoading\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description\n *\n * Fired once the view **begins loading**, *before* the DOM is rendered.\n *\n * @param {Object} event Event object.\n * @param {string} viewName Name of the view.\n */\n newScope.$emit('$viewContentLoading', name);\n\n const cloned = $transclude(newScope, function(clone) {\n clone.data('$uiViewAnim', $uiViewAnim);\n clone.data('$uiView', $uiViewData);\n renderer.enter(clone, $element, function onUIViewEnter() {\n animEnter.resolve();\n if (currentScope) currentScope.$emit('$viewContentAnimationEnded');\n\n if ((isDefined(autoScrollExp) && !autoScrollExp) || scope.$eval(autoScrollExp)) {\n $uiViewScroll(clone);\n }\n });\n\n cleanupLastView();\n });\n\n currentEl = cloned;\n currentScope = newScope;\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoaded\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description *\n * Fired once the view is **loaded**, *after* the DOM is rendered.\n *\n * @param {Object} event Event object.\n */\n currentScope.$emit('$viewContentLoaded', config || viewConfig);\n currentScope.$eval(onloadExp);\n }\n };\n },\n };\n\n return directive;\n },\n];\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout'];\n\n/** @hidden */\nfunction $ViewDirectiveFill(\n $compile: angular.ICompileService,\n $controller: angular.IControllerService,\n $transitions: TransitionService,\n $view: ViewService,\n $q: angular.IQService,\n $timeout: ITimeoutService,\n) {\n const getControllerAs = parse('viewDecl.controllerAs');\n const getResolveAs = parse('viewDecl.resolveAs');\n\n return {\n restrict: 'ECA',\n priority: -400,\n compile: function(tElement: JQuery) {\n const initial = tElement.html();\n tElement.empty();\n\n return function(scope: IScope, $element: JQuery) {\n const data: UIViewData = $element.data('$uiView');\n if (!data) {\n $element.html(initial);\n $compile($element.contents() as any)(scope);\n return;\n }\n\n const cfg: Ng1ViewConfig = data.$cfg || { viewDecl: {}, getTemplate: noop };\n const resolveCtx: ResolveContext = cfg.path && new ResolveContext(cfg.path);\n $element.html(cfg.getTemplate($element, resolveCtx) || initial);\n trace.traceUIViewFill(data.$uiView, $element.html());\n\n const link = $compile($element.contents() as any);\n const controller = cfg.controller;\n const controllerAs: string = getControllerAs(cfg);\n const resolveAs: string = getResolveAs(cfg);\n const locals = resolveCtx && getLocals(resolveCtx);\n\n scope[resolveAs] = locals;\n\n if (controller) {\n const controllerInstance = $controller(\n controller,\n extend({}, locals, { $scope: scope, $element: $element }),\n );\n if (controllerAs) {\n scope[controllerAs] = controllerInstance;\n scope[controllerAs][resolveAs] = locals;\n }\n\n // TODO: Use $view service as a central point for registering component-level hooks\n // Then, when a component is created, tell the $view service, so it can invoke hooks\n // $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element });\n // scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element }));\n\n $element.data('$ngControllerController', controllerInstance);\n $element.children().data('$ngControllerController', controllerInstance);\n\n registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg);\n }\n\n // Wait for the component to appear in the DOM\n if (isString(cfg.viewDecl.component)) {\n const cmp = cfg.viewDecl.component;\n const kebobName = kebobString(cmp);\n const tagRegexp = new RegExp(`^(x-|data-)?${kebobName}$`, 'i');\n\n const getComponentController = () => {\n const directiveEl = [].slice\n .call($element[0].children)\n .filter((el: Element) => el && el.tagName && tagRegexp.exec(el.tagName));\n\n return directiveEl && angular.element(directiveEl).data(`$${cmp}Controller`);\n };\n\n const deregisterWatch = scope.$watch(getComponentController, function(ctrlInstance) {\n if (!ctrlInstance) return;\n registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg);\n deregisterWatch();\n });\n }\n\n link(scope);\n };\n },\n };\n}\n\n/** @hidden */\nconst hasComponentImpl = typeof (angular as any).module('ui.router')['component'] === 'function';\n/** @hidden incrementing id */\nlet _uiCanExitId = 0;\n\n/** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */\nfunction registerControllerCallbacks(\n $q: angular.IQService,\n $transitions: TransitionService,\n controllerInstance: Ng1Controller,\n $scope: IScope,\n cfg: Ng1ViewConfig,\n) {\n // Call $onInit() ASAP\n if (isFunction(controllerInstance.$onInit) && !(cfg.viewDecl.component && hasComponentImpl)) {\n controllerInstance.$onInit();\n }\n\n const viewState: Ng1StateDeclaration = tail(cfg.path).state.self;\n\n const hookOptions: HookRegOptions = { bind: controllerInstance };\n // Add component-level hook for onUiParamsChanged\n if (isFunction(controllerInstance.uiOnParamsChanged)) {\n const resolveContext: ResolveContext = new ResolveContext(cfg.path);\n const viewCreationTrans = resolveContext.getResolvable('$transition$').data;\n\n // Fire callback on any successful transition\n const paramsUpdated = ($transition$: Transition) => {\n // Exit early if the $transition$ is the same as the view was created within.\n // Exit early if the $transition$ will exit the state the view is for.\n if ($transition$ === viewCreationTrans || $transition$.exiting().indexOf(viewState as StateDeclaration) !== -1)\n return;\n\n const toParams = $transition$.params('to') as TypedMap;\n const fromParams = $transition$.params>('from') as TypedMap;\n const getNodeSchema = (node: PathNode) => node.paramSchema;\n const toSchema: Param[] = $transition$\n .treeChanges('to')\n .map(getNodeSchema)\n .reduce(unnestR, []);\n const fromSchema: Param[] = $transition$\n .treeChanges('from')\n .map(getNodeSchema)\n .reduce(unnestR, []);\n\n // Find the to params that have different values than the from params\n const changedToParams = toSchema.filter((param: Param) => {\n const idx = fromSchema.indexOf(param);\n return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]);\n });\n\n // Only trigger callback if a to param has changed or is new\n if (changedToParams.length) {\n const changedKeys: string[] = changedToParams.map(x => x.id);\n // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params.\n const newValues = filter(toParams, (val, key) => changedKeys.indexOf(key) !== -1);\n controllerInstance.uiOnParamsChanged(newValues, $transition$);\n }\n };\n $scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions));\n }\n\n // Add component-level hook for uiCanExit\n if (isFunction(controllerInstance.uiCanExit)) {\n const id = _uiCanExitId++;\n const cacheProp = '_uiCanExitIds';\n\n // Returns true if a redirect transition already answered truthy\n const prevTruthyAnswer = (trans: Transition) =>\n !!trans && ((trans[cacheProp] && trans[cacheProp][id] === true) || prevTruthyAnswer(trans.redirectedFrom()));\n\n // If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition\n const wrappedHook = (trans: Transition) => {\n let promise;\n const ids = (trans[cacheProp] = trans[cacheProp] || {});\n\n if (!prevTruthyAnswer(trans)) {\n promise = $q.when(controllerInstance.uiCanExit(trans));\n promise.then(val => (ids[id] = val !== false));\n }\n return promise;\n };\n\n const criteria = { exiting: viewState.name };\n $scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions));\n }\n}\n\nangular.module('ui.router.state').directive('uiView', uiView);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n", + "/** @module ng1 */ /** */\nimport { ng as angular } from './angular';\nimport { IServiceProviderFactory } from 'angular';\nimport IAnchorScrollService = angular.IAnchorScrollService;\nimport ITimeoutService = angular.ITimeoutService;\n\nexport interface UIViewScrollProvider {\n /**\n * Uses standard anchorScroll behavior\n *\n * Reverts [[$uiViewScroll]] back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * service for scrolling based on the url anchor.\n */\n useAnchorScroll(): void;\n}\n\n/** @hidden */\nfunction $ViewScrollProvider() {\n let useAnchorScroll = false;\n\n this.useAnchorScroll = function() {\n useAnchorScroll = true;\n };\n\n this.$get = [\n '$anchorScroll',\n '$timeout',\n function($anchorScroll: IAnchorScrollService, $timeout: ITimeoutService): Function {\n if (useAnchorScroll) {\n return $anchorScroll;\n }\n\n return function($element: JQuery) {\n return $timeout(\n function() {\n $element[0].scrollIntoView();\n },\n 0,\n false,\n );\n };\n },\n ];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n", + "/**\n * Main entry point for angular 1.x build\n * @module ng1\n */ /** */\n\nexport * from './interface';\nexport * from './services';\nexport * from './statebuilders/views';\nexport * from './stateProvider';\nexport * from './urlRouterProvider';\n\nimport './injectables';\nimport './directives/stateDirectives';\nimport './stateFilters';\nimport './directives/viewDirective';\nimport './viewScroll';\n\nexport default 'ui.router';\n\nimport * as core from '@uirouter/core';\nexport { core };\nexport * from '@uirouter/core';\n" ], "names": [ "ng_from_import.module", @@ -184,7 +184,9 @@ "pattern", "parseUrl", "__extends", - "id" + "id", + "$q", + "$injector" ], - "mappings": ";;;;;;;;;;;;;;;;AAMA,IAAM,cAAc,GAAG,OAAO,CAAC;AAE/B,AAAO,IAAM,EAAE,GAAG,CAAC,cAAc,IAAIA,qBAAqB,IAAI,cAAc,GAAG,cAAc;;ACR7F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,eAAsB,EAAY;IAChC,IAAM,YAAY,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACpD,IAAM,gBAAgB,GAAG,EAAE,CAAC,MAAM,CAAC;IAEnC,iBAAiB,IAAW;QAC1B,IAAI,IAAI,CAAC,MAAM,IAAI,gBAAgB;YAC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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;" } \ No newline at end of file diff --git a/UI/WebServerResources/js/vendor/angular-ui-router.min.js b/UI/WebServerResources/js/vendor/angular-ui-router.min.js index 344525805..ef31434d2 100644 --- a/UI/WebServerResources/js/vendor/angular-ui-router.min.js +++ b/UI/WebServerResources/js/vendor/angular-ui-router.min.js @@ -4,9 +4,6011 @@ * This causes it to be incompatible with plugins that depend on @uirouter/core. * We recommend switching to the ui-router-core.js and ui-router-angularjs.js bundles instead. * For more information, see https://ui-router.github.io/blog/uirouter-for-angularjs-umd-bundles - * @version v1.0.15 + * @version v1.0.17 * @link https://ui-router.github.io * @license MIT License, http://www.opensource.org/licenses/MIT */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("angular")):"function"==typeof define&&define.amd?define(["exports","angular"],e):e(t["@uirouter/angularjs"]={},t.angular)}(this,function(t,e){"use strict";var r=angular,n=e&&e.module?e:r;function i(t){var e=[].slice.apply(arguments,[1]),r=t.length;return function e(n){return n.length>=r?t.apply(null,n):function(){return e(n.concat([].slice.apply(arguments)))}}(e)}function o(){var t=arguments,e=t.length-1;return function(){for(var r=e,n=t[e].apply(this,arguments);r--;)n=t[r].call(this,n);return n}}function a(){for(var t=[],e=0;e=0&&t.splice(r,1),t}var et=i(rt);function rt(t,e){return t.push(e),e}var nt=function(t){return t.slice().forEach(function(e){"function"==typeof e&&e(),X(t,e)})};function it(t){for(var e=[],r=1;rthis._limit&&this.evict(),t},t.prototype.evict=function(){var t=this._items.shift();return this._evictListeners.forEach(function(e){return e(t)}),t},t.prototype.dequeue=function(){if(this.size())return this._items.splice(0,1)[0]},t.prototype.clear=function(){var t=this._items;return this._items=[],t},t.prototype.size=function(){return this._items.length},t.prototype.remove=function(t){var e=this._items.indexOf(t);return e>-1&&this._items.splice(e,1)[0]},t.prototype.peekTail=function(){return this._items[this._items.length-1]},t.prototype.peekHead=function(){if(this.size())return this._items[0]},t}();(Vt=t.RejectType||(t.RejectType={}))[Vt.SUPERSEDED=2]="SUPERSEDED",Vt[Vt.ABORTED=3]="ABORTED",Vt[Vt.INVALID=4]="INVALID",Vt[Vt.IGNORED=5]="IGNORED",Vt[Vt.ERROR=6]="ERROR";var Dt=0,qt=function(){function e(t,e,r){this.$id=Dt++,this.type=t,this.message=e,this.detail=r}return e.isRejectionPromise=function(t){return t&&"function"==typeof t.then&&d(e)(t._transitionRejection)},e.superseded=function(r,n){var i=new e(t.RejectType.SUPERSEDED,"The transition has been superseded by a different transition",r);return n&&n.redirected&&(i.redirected=!0),i},e.redirected=function(t){return e.superseded(t,{redirected:!0})},e.invalid=function(r){return new e(t.RejectType.INVALID,"This transition is invalid",r)},e.ignored=function(r){return new e(t.RejectType.IGNORED,"The transition was ignored",r)},e.aborted=function(r){return new e(t.RejectType.ABORTED,"The transition has been aborted",r)},e.errored=function(r){return new e(t.RejectType.ERROR,"The transition errored",r)},e.normalize=function(t){return d(e)(t)?t:e.errored(t)},e.prototype.toString=function(){var t,e=(t=this.detail)&&t.toString!==Object.prototype.toString?t.toString():ke(t);return"Transition Rejection($id: "+this.$id+" type: "+this.type+", message: "+this.message+", detail: "+e+")"},e.prototype.toPromise=function(){return G(At(this),{_transitionRejection:this})},e}();function Nt(t){if(!t)return"ui-view (defunct)";var e=t.creationContext?t.creationContext.name||"(root)":"(none)";return"[ui-view#"+t.id+" "+t.$type+":"+t.fqn+" ("+t.name+"@"+e+")]"}function Ft(e){return k(e)?t.Category[e]:t.Category[t.Category[e]]}var Ut,Lt=Function.prototype.bind.call(console.log,console),Mt=P(console.table)?console.table.bind(console):Lt.bind(console);(Ut=t.Category||(t.Category={}))[Ut.RESOLVE=0]="RESOLVE",Ut[Ut.TRANSITION=1]="TRANSITION",Ut[Ut.HOOK=2]="HOOK",Ut[Ut.UIVIEW=3]="UIVIEW",Ut[Ut.VIEWCONFIG=4]="VIEWCONFIG";var Bt,Gt,Wt=c("$id"),zt=c("router.$id"),Jt=function(t){return"Transition #"+Wt(t)+"-"+zt(t)},Qt=function(){function e(){this._enabled={},this.approximateDigests=0}return e.prototype._set=function(e,r){var n=this;r.length||(r=Object.keys(t.Category).map(function(t){return parseInt(t,10)}).filter(function(t){return!isNaN(t)}).map(function(e){return t.Category[e]})),r.map(Ft).forEach(function(t){return n._enabled[t]=e})},e.prototype.enable=function(){for(var t=[],e=0;e "+ke(e))},e.prototype.traceTransitionIgnored=function(e){this.enabled(t.Category.TRANSITION)&&console.log(Jt(e)+": Ignored <> "+ke(e))},e.prototype.traceHookInvocation=function(e,r,n){if(this.enabled(t.Category.HOOK)){var i=c("traceData.hookType")(n)||"internal",o=c("traceData.context.state.name")(n)||c("traceData.context")(n)||"unknown",a=Ee(e.registeredHook.callback);console.log(Jt(r)+": Hook -> "+i+" context: "+o+", "+Se(200,a))}},e.prototype.traceHookResult=function(e,r,n){this.enabled(t.Category.HOOK)&&console.log(Jt(r)+": <- Hook returned: "+Se(200,ke(e)))},e.prototype.traceResolvePath=function(e,r,n){this.enabled(t.Category.RESOLVE)&&console.log(Jt(n)+": Resolving "+e+" ("+r+")")},e.prototype.traceResolvableResolved=function(e,r){this.enabled(t.Category.RESOLVE)&&console.log(Jt(r)+": <- Resolved "+e+" to: "+Se(200,ke(e.data)))},e.prototype.traceError=function(e,r){this.enabled(t.Category.TRANSITION)&&console.log(Jt(r)+": <- Rejected "+ke(r)+", reason: "+e)},e.prototype.traceSuccess=function(e,r){this.enabled(t.Category.TRANSITION)&&console.log(Jt(r)+": <- Success "+ke(r)+", final state: "+e.name)},e.prototype.traceUIViewEvent=function(e,r,n){void 0===n&&(n=""),this.enabled(t.Category.UIVIEW)&&console.log("ui-view: "+be(30,e)+" "+Nt(r)+n)},e.prototype.traceUIViewConfigUpdated=function(e,r){this.enabled(t.Category.UIVIEW)&&this.traceUIViewEvent("Updating",e," with ViewConfig from context='"+r+"'")},e.prototype.traceUIViewFill=function(e,r){this.enabled(t.Category.UIVIEW)&&this.traceUIViewEvent("Fill",e," with: "+Se(200,r))},e.prototype.traceViewSync=function(e){if(this.enabled(t.Category.VIEWCONFIG)){var r="uiview component fqn",n=e.map(function(t){var e,n=t.uiView,i=t.viewConfig,o=n&&n.fqn,a=i&&i.viewDecl.$context.name+": ("+i.viewDecl.$name+")";return(e={})[r]=o,e["view config state (view name)"]=a,e}).sort(function(t,e){return(t[r]||"").localeCompare(e[r]||"")});Mt(n)}},e.prototype.traceViewServiceEvent=function(e,r){this.enabled(t.Category.VIEWCONFIG)&&console.log("VIEWCONFIG: "+e+" "+function(t){var e=t.viewDecl,r=e.$context.name||"(root)";return"[View#"+t.$id+" from '"+r+"' state]: target ui-view: '"+e.$uiViewName+"@"+e.$uiViewContextAnchor+"'"}(r))},e.prototype.traceViewServiceUIViewEvent=function(e,r){this.enabled(t.Category.VIEWCONFIG)&&console.log("VIEWCONFIG: "+e+" "+Nt(r))},e}(),Kt=new Qt;(Bt=t.TransitionHookPhase||(t.TransitionHookPhase={}))[Bt.CREATE=0]="CREATE",Bt[Bt.BEFORE=1]="BEFORE",Bt[Bt.RUN=2]="RUN",Bt[Bt.SUCCESS=3]="SUCCESS",Bt[Bt.ERROR=4]="ERROR",(Gt=t.TransitionHookScope||(t.TransitionHookScope={}))[Gt.TRANSITION=0]="TRANSITION",Gt[Gt.STATE=1]="STATE";var Yt=function(){function t(t,e,r,n){this._stateRegistry=t,this._identifier=e,this._identifier=e,this._params=G({},r||{}),this._options=G({},n||{}),this._definition=t.matcher.find(e,this._options.relative)}return t.prototype.name=function(){return this._definition&&this._definition.name||this._identifier},t.prototype.identifier=function(){return this._identifier},t.prototype.params=function(){return this._params},t.prototype.$state=function(){return this._definition},t.prototype.state=function(){return this._definition&&this._definition.self},t.prototype.options=function(){return this._options},t.prototype.exists=function(){return!(!this._definition||!this._definition.self)},t.prototype.valid=function(){return!this.error()},t.prototype.error=function(){var t=this.options().relative;if(!this._definition&&t){var e=t.name?t.name:t;return"Could not resolve '"+this.name()+"' from state '"+e+"'"}return this._definition?this._definition.self?void 0:"State '"+this.name()+"' has an invalid definition":"No such state '"+this.name()+"'"},t.prototype.toString=function(){return"'"+this.name()+"'"+ke(this.params())},t.prototype.withState=function(e){return new t(this._stateRegistry,e,this._params,this._options)},t.prototype.withParams=function(e,r){void 0===r&&(r=!1);var n=r?e:G({},this._params,e);return new t(this._stateRegistry,this._identifier,n,this._options)},t.prototype.withOptions=function(e,r){void 0===r&&(r=!1);var n=r?e:G({},this._options,e);return new t(this._stateRegistry,this._identifier,this._params,n)},t.isDef=function(t){return t&&t.state&&(O(t.state)||O(t.state.name))},t}(),Zt={current:J,transition:null,traceData:{},bind:null},Xt=function(){function e(e,r,n,i){var o=this;this.transition=e,this.stateContext=r,this.registeredHook=n,this.options=i,this.isSuperseded=function(){return o.type.hookPhase===t.TransitionHookPhase.RUN&&!o.options.transition.isActive()},this.options=it(i,Zt),this.type=n.eventType}return e.chain=function(t,e){return t.reduce(function(t,e){return t.then(function(){return e.invokeHook()})},e||N.$q.when())},e.invokeHooks=function(t,r){for(var n=0;n=e.invokeLimit&&e.deregister()}}},e.prototype.handleHookResult=function(t){var e=this,r=this.getNotCurrentRejection();return r||(D(t)?t.then(function(t){return e.handleHookResult(t)}):(Kt.traceHookResult(t,this.transition,this.options),!1===t?qt.aborted("Hook aborted transition").toPromise():d(Yt)(t)?qt.redirected(t).toPromise():void 0))},e.prototype.getNotCurrentRejection=function(){var t=this.transition.router;return t._disposed?qt.aborted("UIRouter instance #"+t.$id+" has been stopped (disposed)").toPromise():this.transition._aborted?qt.aborted().toPromise():this.isSuperseded()?qt.superseded(this.options.current()).toPromise():void 0},e.prototype.toString=function(){var t=this.options,e=this.registeredHook;return(c("traceData.hookType")(t)||"internal")+" context: "+(c("traceData.context.state.name")(t)||c("traceData.context")(t)||"unknown")+", "+Se(200,Ce(e.callback))},e.HANDLE_RESULT=function(t){return function(e){return t.handleHookResult(e)}},e.LOG_REJECTED_RESULT=function(t){return function(e){D(e)&&e.catch(function(e){return t.logError(qt.normalize(e))})}},e.LOG_ERROR=function(t){return function(e){return t.logError(e)}},e.REJECT_ERROR=function(t){return function(t){return At(t)}},e.THROW_ERROR=function(t){return function(t){throw t}},e}();function te(t,e){var r=O(e)?[e]:e;return!!(P(r)?r:function(t){for(var e=r,n=0;n20)throw new Error("Too many consecutive Transition redirects (20+)");var n={redirectedFrom:this,source:"redirect"};"url"===this.options().source&&!1!==t.options().location&&(n.location="replace");var i=G({},this.options(),t.options(),n);t=t.withOptions(i,!0);var o,a=this.router.transitionService.create(this._treeChanges.from,t),u=this._treeChanges.entering,s=a._treeChanges.entering;return fe.matching(s,u,fe.nonDynamicParams).filter(f((o=t.options().reloadState,function(t){return o&&t.state.includes[o.name]}))).forEach(function(t,e){t.resolvables=u[e].resolvables}),a},e.prototype._changedParams=function(){var t=this._treeChanges;if(!this._options.reload&&(!t.exiting.length&&!t.entering.length&&t.to.length===t.from.length&&!Tt(t.to,t.from).map(function(t){return t[0].state!==t[1].state}).reduce(mt,!1))){var e=t.to.map(function(t){return t.paramSchema}),r=[t.to,t.from].map(function(t){return t.map(function(t){return t.paramValues})});return Tt(e,r[0],r[1]).map(function(t){var e=t[0],r=t[1],n=t[2];return se.changed(e,r,n)}).reduce(yt,[])}},e.prototype.dynamic=function(){var t=this._changedParams();return!!t&&t.map(function(t){return t.dynamic}).reduce(mt,!1)},e.prototype.ignored=function(){return!!this._ignoredReason()},e.prototype._ignoredReason=function(){var t=this.router.globals.transition,e=this._options.reloadState,r=function(t,r){if(t.length!==r.length)return!1;var n=fe.matching(t,r);return t.length===n.filter(function(t){return!e||!t.state.includes[e.name]}).length},n=this.treeChanges(),i=t&&t.treeChanges();return i&&r(i.to,n.to)&&r(i.exiting,n.exiting)?"SameAsPending":0===n.exiting.length&&0===n.entering.length&&r(n.from,n.to)?"SameAsCurrent":void 0},e.prototype.run=function(){var e=this,r=Xt.runAllHooks,n=function(t){return e._hookBuilder.buildHooksForPhase(t)},i=n(t.TransitionHookPhase.BEFORE);return Xt.invokeHooks(i,function(){var t=e.router.globals;return t.lastStartedTransitionId=e.$id,t.transition=e,t.transitionHistory.enqueue(e),Kt.traceTransitionStart(e),N.$q.when(void 0)}).then(function(){var e=n(t.TransitionHookPhase.RUN);return Xt.invokeHooks(e,function(){return N.$q.when(void 0)})}).then(function(){Kt.traceSuccess(e.$to(),e),e.success=!0,e._deferred.resolve(e.to()),r(n(t.TransitionHookPhase.SUCCESS))},function(i){Kt.traceError(i,e),e.success=!1,e._deferred.reject(i),e._error=i,r(n(t.TransitionHookPhase.ERROR))}),this.promise},e.prototype.valid=function(){return!this.error()||void 0!==this.success},e.prototype.abort=function(){R(this.success)&&(this._aborted=!0)},e.prototype.error=function(){var t=this.$to();if(t.self.abstract)return"Cannot transition to abstract state '"+t.name+"'";var e=t.parameters(),r=this.params(),n=e.filter(function(t){return!t.validates(r[t.id])});return n.length?"Param values not valid for state '"+t.name+"'. Invalid params: [ "+n.map(function(t){return t.id}).join(", ")+" ]":!1===this.success?this._error:void 0},e.prototype.toString=function(){var t=this.from(),e=this.to(),r=function(t){return null!==t["#"]&&void 0!==t["#"]?t:st(t,["#"])};return"Transition#"+this.$id+"( '"+(x(t)?t.name:t)+"'"+ke(r(this._treeChanges.from.map(u("paramValues")).reduce(ot,{})))+" -> "+(this.valid()?"":"(X) ")+"'"+(x(e)?e.name:e)+"'"+ke(r(this.params()))+" )"},e.diToken=e,e}();function Se(t,e){return e.length<=t?e:e.substr(0,t-3)+"..."}function be(t,e){for(;e.length=0||(a.push(n[s]),o[n[s]]=this[n[s]]);return G({},o,t)},t}();function Le(t){return t.name}function Me(t){return t.self.$$state=function(){return t},t.self}function Be(t){return t.parent&&t.parent.data&&(t.data=t.self.data=K(t.parent.data,t.data)),t.data}var Ge=function(t,e){return function(r){var n=r;n&&n.url&&n.name&&n.name.match(/\.\*\*$/)&&(n.url+="{remainder:any}");var i=function(t){if(!O(t))return!1;var e="^"===t.charAt(0);return{val:e?t.substring(1):t,root:e}}(n.url),o=r.parent,a=i?t.compile(i.val,{params:r.params||{},paramMap:function(t,e){return!1===n.reloadOnSearch&&e&&(t=G(t||{},{dynamic:!0})),t}}):n.url;if(!a)return null;if(!t.isMatcher(a))throw new Error("Invalid url '"+a+"' in state '"+r+"'");return i&&i.root?a:(o&&o.navigable||e()).url.append(a)}},We=function(t){return function(e){return!t(e)&&e.url?e:e.parent?e.parent.navigable:null}},ze=function(t){return function(e){var r=e.url&&e.url.parameters({inherit:!1})||[],n=vt(ht(st(e.params||{},r.map(u("id"))),function(e,r){return t.fromConfig(r,null,e)}));return r.concat(n).map(function(t){return[t.id,t]}).reduce(Pt,{})}};function Je(t){return t.parent?t.parent.path.concat(t):[t]}function Qe(t){var e=t.parent?G({},t.parent.includes):{};return e[t.name]=!0,e}function Ke(t){var e,r,n=function(t){return t.provide||t.token},i=_([[u("resolveFn"),function(t){return new he(n(t),t.resolveFn,t.deps,t.policy)}],[u("useFactory"),function(t){return new he(n(t),t.useFactory,t.deps||t.dependencies,t.policy)}],[u("useClass"),function(t){return new he(n(t),function(){return new t.useClass},[],t.policy)}],[u("useValue"),function(t){return new he(n(t),function(){return t.useValue},[],t.policy,t.useValue)}],[u("useExisting"),function(t){return new he(n(t),z,[t.useExisting],t.policy)}]]),o=_([[a(u("val"),O),function(t){return new he(t.token,z,[t.val],t.policy)}],[a(u("val"),I),function(t){return new he(t.token,kt(t.val),t.val.slice(0,-1),t.policy)}],[a(u("val"),P),function(t){return new he(t.token,t.val,(e=t.val,r=N.$injector,e.$inject||r&&r.annotate(e,r.strictDi)||"deferred"),t.policy);var e,r}]]),s=_([[d(he),function(t){return t}],[function(t){return!(!t.token||!t.resolveFn)},i],[function(t){return!(!t.provide&&!t.token||!(t.useValue||t.useFactory||t.useExisting||t.useClass))},i],[function(t){return!!(t&&t.val&&(O(t.val)||I(t.val)||P(t.val)))},o],[y(!0),function(t){throw new Error("Invalid resolve value: "+ke(t))}]]),c=t.resolve;return(I(c)?c:(e=c,r=t.resolvePolicy||{},Object.keys(e||{}).map(function(t){return{token:t,val:e[t],deps:void 0,policy:r[t]}}))).map(s)}var Ye=function(){function t(t,e){this.matcher=t;var r=this,n=function(){return t.find("")},i=function(t){return""===t.name};this.builders={name:[Le],self:[Me],parent:[function(e){return i(e)?null:t.find(r.parentName(e))||n()}],data:[Be],url:[Ge(e,n)],navigable:[We(i)],params:[ze(e.paramFactory)],views:[],path:[Je],includes:[Qe],resolvables:[Ke]}}return t.prototype.builder=function(t,e){var r=this.builders,n=r[t]||[];return O(t)&&!E(e)?n.length>1?n:n[0]:O(t)&&P(e)?(r[t]=n,r[t].push(e),function(){return r[t].splice(r[t].indexOf(e,1))&&null}):void 0},t.prototype.build=function(t){var e=this.matcher,r=this.builders,n=this.parentName(t);if(n&&!e.find(n,void 0,!1))return null;for(var i in r)if(r.hasOwnProperty(i)){var o=r[i].reduce(function(t,e){return function(r){return e(r,t)}},J);t[i]=o(t)}return t},t.prototype.parentName=function(t){var e=t.name||"",r=e.split(".");if("**"===r.pop()&&r.pop(),r.length){if(t.parent)throw new Error("States that specify the 'parent:' property should not have a '.' in their name ("+e+")");return r.join(".")}return t.parent?O(t.parent)?t.parent:t.parent.name:""},t.prototype.name=function(t){var e=t.name;if(-1!==e.indexOf(".")||!t.parent)return e;var r=O(t.parent)?t.parent:t.parent.name;return r?r+"."+e:e},t}(),Ze=function(){function t(t){this._states=t}return t.prototype.isRelative=function(t){return 0===(t=t||"").indexOf(".")||0===t.indexOf("^")},t.prototype.find=function(t,e,r){if(void 0===r&&(r=!0),t||""===t){var n=O(t),i=n?t:t.name;this.isRelative(i)&&(i=this.resolvePath(i,e));var o=this._states[i];if(o&&(n||!(n||o!==t&&o.self!==t)))return o;if(n&&r){var a=vt(this._states).filter(function(t){return t.__stateObjectCache.nameGlob&&t.__stateObjectCache.nameGlob.matches(i)});return a.length>1&&console.log("stateMatcher.find: Found multiple matches for "+i+" using glob: ",a.map(function(t){return t.name})),a[0]}}},t.prototype.resolvePath=function(t,e){if(!e)throw new Error("No reference point given for path '"+t+"'");for(var r=this.find(e),n=t.split("."),i=n.length,o=0,a=r;o0;){var s=e.shift(),c=s.name,f=n.build(s),l=o.indexOf(s);if(f){var h=u(c);if(h&&h.name===c)throw new Error("State '"+c+"' is already defined");var p=u(c+".**");p&&this.$registry.deregister(p),r[c]=s,this.attachRoute(s),l>=0&&o.splice(l,1),i.push(s)}else{var v=a[c];if(a[c]=e.length,l>=0&&v===e.length)return e.push(s),r;l<0&&o.push(s),e.push(s)}}return i.length&&this.listeners.forEach(function(t){return t("registered",i.map(function(t){return t.self}))}),r},t.prototype.attachRoute=function(t){!t.abstract&&t.url&&this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(t))},t}(),tr=function(){function t(t){this._router=t,this.states={},this.listeners=[],this.matcher=new Ze(this.states),this.builder=new Ye(this.matcher,t.urlMatcherFactory),this.stateQueue=new Xe(this,t.urlRouter,this.states,this.builder,this.listeners),this._registerRoot()}return t.prototype._registerRoot=function(){(this._root=this.stateQueue.register({name:"",url:"^",views:null,params:{"#":{value:null,type:"hash",dynamic:!0}},abstract:!0})).navigable=null},t.prototype.dispose=function(){var t=this;this.stateQueue.dispose(),this.listeners=[],this.get().forEach(function(e){return t.get(e)&&t.deregister(e)})},t.prototype.onStatesChanged=function(t){return this.listeners.push(t),function(){X(this.listeners)(t)}.bind(this)},t.prototype.root=function(){return this._root},t.prototype.register=function(t){return this.stateQueue.register(t)},t.prototype._deregisterTree=function(t){var e=this,r=this.get().map(function(t){return t.$$state()}),n=function(t){var e=r.filter(function(e){return-1!==t.indexOf(e.parent)});return 0===e.length?e:e.concat(n(e))},i=n([t]),o=[t].concat(i).reverse();return o.forEach(function(t){var r=e._router.urlRouter;r.rules().filter(s("state",t)).forEach(r.removeRule.bind(r)),delete e.states[t.name]}),o},t.prototype.deregister=function(t){var e=this.get(t);if(!e)throw new Error("Can't deregister state; not found: "+t);var r=this._deregisterTree(e.$$state());return this.listeners.forEach(function(t){return t("deregistered",r.map(function(t){return t.self}))}),r},t.prototype.get=function(t,e){var r=this;if(0===arguments.length)return Object.keys(this.states).map(function(t){return r.states[t].self});var n=this.matcher.find(t,e);return n&&n.self||null},t.prototype.decorator=function(t,e){return this.builder.builder(t,e)},t}();function er(t,e){var r=["",""],n=t.replace(/[\\\[\]\^$*+?.()|{}]/g,"\\$&");if(!e)return n;switch(e.squash){case!1:r=["(",")"+(e.isOptional?"?":"")];break;case!0:n=n.replace(/\/$/,""),r=["(?:/(",")|/)?"];break;default:r=["("+e.squash+"|",")?"]}return n+r[0]+e.type.pattern.source+r[1]}var rr=De("/"),nr=function(){function e(t,r,n,i){var o=this;this.config=i,this._cache={path:[this]},this._children=[],this._params=[],this._segments=[],this._compiled=[],this.pattern=t,this.config=it(this.config,{params:{},strict:!0,caseInsensitive:!1,paramMap:z});for(var a,u,c,f=/([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,l=/([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,h=[],p=0,v=function(r){if(!e.nameValidator.test(r))throw new Error("Invalid parameter name '"+r+"' in pattern '"+t+"'");if(lt(o._params,s("id",r)))throw new Error("Duplicate parameter name '"+r+"' in pattern '"+t+"'")},d=function(e,n){var i,a=e[2]||e[3],u=n?e[4]:e[4]||("*"===e[1]?"[\\s\\S]*":null);return{id:a,regexp:u,cfg:o.config.params[a],segment:t.substring(p,e.index),type:u?r.type(u)||(i=u,K(r.type(n?"query":"path"),{pattern:new RegExp(i,o.config.caseInsensitive?"i":void 0)})):null}};(a=f.exec(t))&&!((u=d(a,!1)).segment.indexOf("?")>=0);)v(u.id),this._params.push(n.fromPath(u.id,u.type,this.config.paramMap(u.cfg,!1))),this._segments.push(u.segment),h.push([u.segment,kt(this._params)]),p=f.lastIndex;var m=(c=t.substring(p)).indexOf("?");if(m>=0){var y=c.substring(m);if(c=c.substring(0,m),y.length>0)for(p=0;a=l.exec(y);)v((u=d(a,!0)).id),this._params.push(n.fromSearch(u.id,u.type,this.config.paramMap(u.cfg,!0))),p=f.lastIndex}this._segments.push(c),this._compiled=h.map(function(t){return er.apply(null,t)}).concat(er(c))}return e.encodeDashes=function(t){return encodeURIComponent(t).replace(/-/g,function(t){return"%5C%"+t.charCodeAt(0).toString(16).toUpperCase()})},e.pathSegmentsAndParams=function(e){return Tt(e._segments,e._params.filter(function(e){return e.location===t.DefType.PATH}).concat(void 0)).reduce(yt,[]).filter(function(t){return""!==t&&E(t)})},e.queryParams=function(e){return e._params.filter(function(e){return e.location===t.DefType.SEARCH})},e.compare=function(t,r){var n=function(t){return t._cache.weights=t._cache.weights||function(t){return t._cache.segments=t._cache.segments||t._cache.path.map(e.pathSegmentsAndParams).reduce(yt,[]).reduce(qe,[]).map(function(t){return O(t)?rr(t):t}).reduce(yt,[])}(t).map(function(t){return"/"===t?1:O(t)?2:t instanceof se?3:void 0})},i=n(t),o=n(r);!function(t,e,r){for(var n=Math.max(t.length,e.length);t.lengthn.weight?u:n}return n},t.prototype.sync=function(t){if(!t||!t.defaultPrevented){var e=this._router,r=e.urlService,n=e.stateService,i={path:r.path(),search:r.search(),hash:r.hash()},o=this.match(i);_([[O,function(t){return r.url(t,!0)}],[Yt.isDef,function(t){return n.go(t.state,t.params,t.options)}],[d(Yt),function(t){return n.go(t.state(),t.params(),t.options())}]])(o&&o.rule.handler(o.match,i,e))}},t.prototype.listen=function(t){var e=this;if(!1!==t)return this._stopFn=this._stopFn||this._router.urlService.onChange(function(t){return e.sync(t)});this._stopFn&&this._stopFn(),delete this._stopFn},t.prototype.update=function(t){var e=this._router.locationService;t?this.location=e.url():e.url()!==this.location&&e.url(this.location,!0)},t.prototype.push=function(t,e,r){var n=r&&!!r.replace;this._router.urlService.url(t.format(e||{}),n)},t.prototype.href=function(t,e,r){var n=t.format(e);if(null==n)return null;r=r||{absolute:!1};var i=this._router.urlService.config,o=i.html5Mode();if(o||null===n||(n="#"+i.hashPrefix()+n),n=function(t,e,r,n){return"/"===n?t:e?Ie(n)+t:r?n.slice(1)+t:t}(n,o,r.absolute,i.baseHref()),!r.absolute||!n)return n;var a=!o&&n?"/":"",u=i.port(),s=80===u||443===u?"":":"+u;return[i.protocol(),"://",i.host(),s,a,n].join("")},t.prototype.rule=function(t){var e=this;if(!or.isUrlRule(t))throw new Error("invalid rule");return t.$id=this._id++,t.priority=t.priority||0,this._rules.push(t),this._sorted=!1,function(){return e.removeRule(t)}},t.prototype.removeRule=function(t){X(this._rules,t)},t.prototype.rules=function(){return this.ensureSorted(),this._rules.slice()},t.prototype.otherwise=function(t){var e=cr(t);this._otherwiseFn=this.urlRuleFactory.create(y(!0),e),this._sorted=!1},t.prototype.initial=function(t){var e=cr(t);this.rule(this.urlRuleFactory.create(function(t,e){return 0===e.globals.transitionHistory.size()&&!!/^\/?$/.exec(t.path)},e))},t.prototype.when=function(t,e,r){var n=this.urlRuleFactory.create(t,e);return E(r&&r.priority)&&(n.priority=r.priority),this.rule(n),n},t.prototype.deferIntercept=function(t){void 0===t&&(t=!0),this.interceptDeferred=t},t}();function cr(t){if(!(P(t)||O(t)||d(Yt)(t)||Yt.isDef(t)))throw new Error("'handler' must be a string, function, TargetState, or have a state: 'newtarget' property");return P(t)?t:y(t)}var fr=function(){function t(){var t=this;this._uiViews=[],this._viewConfigs=[],this._viewConfigFactories={},this._listeners=[],this._pluginapi={_rootViewContext:this._rootViewContext.bind(this),_viewConfigFactory:this._viewConfigFactory.bind(this),_registeredUIViews:function(){return t._uiViews},_activeViewConfigs:function(){return t._viewConfigs},_onSync:function(e){return t._listeners.push(e),function(){return X(t._listeners,e)}}}}return t.normalizeUIViewTarget=function(t,e){void 0===e&&(e="");var r=e.split("@"),n=r[0]||"$default",i=O(r[1])?r[1]:"^",o=/^(\^(?:\.\^)*)\.(.*$)/.exec(n);o&&(i=o[1],n=o[2]),"!"===n.charAt(0)&&(n=n.substr(1),i="");/^(\^(?:\.\^)*)$/.exec(i)?i=i.split(".").reduce(function(t,e){return t.parent},t).name:"."===i&&(i=t.name);return{uiViewName:n,uiViewContextAnchor:i}},t.prototype._rootViewContext=function(t){return this._rootContext=t||this._rootContext},t.prototype._viewConfigFactory=function(t,e){this._viewConfigFactories[t]=e},t.prototype.createViewConfig=function(t,e){var r=this._viewConfigFactories[e.$type];if(!r)throw new Error("ViewService: No view config factory registered for type "+e.$type);var n=r(t,e);return I(n)?n:[n]},t.prototype.deactivateViewConfig=function(t){Kt.traceViewServiceEvent("<- Removing",t),X(this._viewConfigs,t)},t.prototype.activateViewConfig=function(t){Kt.traceViewServiceEvent("-> Registering",t),this._viewConfigs.push(t)},t.prototype.sync=function(){var e=this,r=this._uiViews.map(function(t){return[t.fqn,t]}).reduce(Pt,{});function n(t){for(var e=t.viewDecl.$context,r=0;++r&&e.parent;)e=e.parent;return r}var o=i(function(t,e,r,n){return e*(t(r)-t(n))}),a=this._uiViews.sort(o(function(t){var e=function(t){return t&&t.parent?e(t.parent)+1:1};return 1e4*t.fqn.split(".").length+e(t.creationContext)},1)).map(function(i){var a=e._viewConfigs.filter(t.matches(r,i));return a.length>1&&a.sort(o(n,-1)),{uiView:i,viewConfig:a[0]}}),u=a.map(function(t){return t.viewConfig}),s=this._viewConfigs.filter(function(t){return!Y(u,t)}).map(function(t){return{uiView:void 0,viewConfig:t}});a.forEach(function(t){-1!==e._uiViews.indexOf(t.uiView)&&t.uiView.configUpdated(t.viewConfig)});var c=a.concat(s);this._listeners.forEach(function(t){return t(c)}),Kt.traceViewSync(c)},t.prototype.registerUIView=function(t){Kt.traceViewServiceUIViewEvent("-> Registering",t);var e=this._uiViews;return e.filter(function(e){return e.fqn===t.fqn&&e.$type===t.$type}).length&&Kt.traceViewServiceUIViewEvent("!!!! duplicate uiView named:",t),e.push(t),this.sync(),function(){-1!==e.indexOf(t)?(Kt.traceViewServiceUIViewEvent("<- Deregistering",t),X(e)(t)):Kt.traceViewServiceUIViewEvent("Tried removing non-registered uiView",t)}},t.prototype.available=function(){return this._uiViews.map(u("fqn"))},t.prototype.active=function(){return this._uiViews.filter(u("$config")).map(u("name"))},t.matches=function(t,e){return function(r){if(e.$type!==r.viewDecl.$type)return!1;var n=r.viewDecl,i=n.$uiViewName.split("."),o=e.fqn.split(".");if(!W(i,o.slice(0-i.length)))return!1;var a=1-i.length||void 0,u=o.slice(0,a).join("."),s=t[u].creationContext;return n.$uiViewContextAnchor===(s&&s.name)}},t}(),lr=function(){function t(){this.params=new Ue,this.lastStartedTransitionId=-1,this.transitionHistory=new Ht([],1),this.successfulTransitions=new Ht([],1)}return t.prototype.dispose=function(){this.transitionHistory.clear(),this.successfulTransitions.clear(),this.transition=null},t}(),hr=function(t){return t.reduce(function(t,e){return t[e]=q(e),t},{dispose:J})},pr=["url","path","search","hash","onChange"],vr=["port","protocol","host","baseHref","html5Mode","hashPrefix"],dr=["type","caseInsensitive","strictMode","defaultSquashPolicy"],mr=["sort","when","initial","otherwise","rules","rule","removeRule"],yr=["deferIntercept","listen","sync","match"],gr=function(){function t(t,e){void 0===e&&(e=!0),this.router=t,this.rules={},this.config={};var r=function(){return t.locationService};Q(r,this,r,pr,e);var n=function(){return t.locationConfig};Q(n,this.config,n,vr,e);var i=function(){return t.urlMatcherFactory};Q(i,this.config,i,dr);var o=function(){return t.urlRouter};Q(o,this.rules,o,mr),Q(o,this,o,yr)}return t.prototype.url=function(t,e,r){},t.prototype.path=function(){},t.prototype.search=function(){},t.prototype.hash=function(){},t.prototype.onChange=function(t){},t.prototype.parts=function(){return{path:this.path(),search:this.search(),hash:this.hash()}},t.prototype.dispose=function(){},t.prototype.sync=function(t){},t.prototype.listen=function(t){},t.prototype.deferIntercept=function(t){},t.prototype.match=function(t){},t.locationServiceStub=hr(pr),t.locationConfigStub=hr(vr),t}(),_r=0,wr=function(){function t(t,e){void 0===t&&(t=gr.locationServiceStub),void 0===e&&(e=gr.locationConfigStub),this.locationService=t,this.locationConfig=e,this.$id=_r++,this._disposed=!1,this._disposables=[],this.trace=Kt,this.viewService=new fr,this.globals=new lr,this.transitionService=new Lr(this),this.urlMatcherFactory=new ir,this.urlRouter=new sr(this),this.stateRegistry=new tr(this),this.stateService=new Mr(this),this.urlService=new gr(this),this._plugins={},this.viewService._pluginapi._rootViewContext(this.stateRegistry.root()),this.globals.$current=this.stateRegistry.root(),this.globals.current=this.globals.$current.self,this.disposable(this.globals),this.disposable(this.stateService),this.disposable(this.stateRegistry),this.disposable(this.transitionService),this.disposable(this.urlRouter),this.disposable(t),this.disposable(e)}return t.prototype.disposable=function(t){this._disposables.push(t)},t.prototype.dispose=function(t){var e=this;t&&P(t.dispose)?t.dispose(this):(this._disposed=!0,this._disposables.slice().forEach(function(t){try{"function"==typeof t.dispose&&t.dispose(e),X(e._disposables,t)}catch(t){}}))},t.prototype.plugin=function(t,e){void 0===e&&(e={});var r=new t(this,e);if(!r.name)throw new Error("Required property `name` missing on plugin: "+r);return this._disposables.push(r),this._plugins[r.name]=r},t.prototype.getPlugin=function(t){return t?this._plugins[t]:vt(this._plugins)},t}();function $r(t){t.addResolvable(he.fromData(wr,t.router),""),t.addResolvable(he.fromData($e,t),""),t.addResolvable(he.fromData("$transition$",t),""),t.addResolvable(he.fromData("$stateParams",t.params()),""),t.entering().forEach(function(e){t.addResolvable(he.fromData("$state$",e),e)})}var Sr=Y(["$transition$",$e]),br=function(t){var e=function(t){return Sr(t.token)?he.fromData(t.token,null):t};vt(t.treeChanges()).reduce(yt,[]).reduce(wt,[]).forEach(function(t){t.resolvables=t.resolvables.map(e)})},Rr=function(t){var e=t.to().redirectTo;if(e){var r=t.router.stateService;return P(e)?N.$q.when(e(t)).then(n):n(e)}function n(e){if(e)return e instanceof Yt?e:O(e)?r.target(e,t.params(),t.options()):e.state||e.params?r.target(e.state||t.to(),e.params||t.params(),t.options()):void 0}};function Er(t){return function(e,r){return(0,r.$$state()[t])(e,r)}}var Cr=Er("onExit"),Tr=Er("onRetain"),Pr=Er("onEnter"),kr=function(t){return new ge(t.treeChanges().to).resolvePath("EAGER",t).then(J)},Or=function(t,e){return new ge(t.treeChanges().to).subContext(e.$$state()).resolvePath("LAZY",t).then(J)},xr=function(t){return new ge(t.treeChanges().to).resolvePath("LAZY",t).then(J)},Ir=function(t){var e=N.$q,r=t.views("entering");if(r.length)return e.all(r.map(function(t){return e.when(t.load())})).then(J)},Vr=function(t){var e=t.views("entering"),r=t.views("exiting");if(e.length||r.length){var n=t.router.viewService;r.forEach(function(t){return n.deactivateViewConfig(t)}),e.forEach(function(t){return n.activateViewConfig(t)}),n.sync()}},jr=function(t){var e=t.router.globals,r=function(){e.transition===t&&(e.transition=null)};t.onSuccess({},function(){e.successfulTransitions.enqueue(t),e.$current=t.$to(),e.current=e.$current.self,Ot(t.params(),e.params)},{priority:1e4}),t.promise.then(r,r)},Ar=function(t){var e=t.options(),r=t.router.stateService,n=t.router.urlRouter;if("url"!==e.source&&e.location&&r.$current.navigable){var i={replace:"replace"===e.location};n.push(r.$current.navigable.url,r.params,i)}n.update(!0)},Hr=function(t){var e=t.router;var r=t.entering().filter(function(t){return!!t.$$state().lazyLoad}).map(function(e){return Dr(t,e)});return N.$q.all(r).then(function(){if("url"!==t.originalTransition().options().source){var r=t.targetState();return e.stateService.target(r.identifier(),r.params(),r.options())}var n=e.urlService,i=n.match(n.parts()),o=i&&i.rule;if(o&&"STATE"===o.type){var a=o.state,u=i.match;return e.stateService.target(a,u,t.options())}e.urlService.sync()})};function Dr(t,e){var r=e.$$state().lazyLoad,n=r._promise;if(!n){n=r._promise=N.$q.when(r(t,e)).then(function(e){e&&Array.isArray(e.states)&&e.states.forEach(function(e){return t.router.stateRegistry.register(e)});return e}).then(function(t){return delete e.lazyLoad,delete e.$$state().lazyLoad,delete r._promise,t},function(t){return delete r._promise,N.$q.reject(t)})}return n}var qr=function(){return function(t,e,r,n,i,o,a,u){void 0===i&&(i=!1),void 0===o&&(o=Xt.HANDLE_RESULT),void 0===a&&(a=Xt.REJECT_ERROR),void 0===u&&(u=!1),this.name=t,this.hookPhase=e,this.hookOrder=r,this.criteriaMatchPath=n,this.reverseSort=i,this.getResultHandler=o,this.getErrorHandler=a,this.synchronous=u}}();function Nr(t){var e=t._ignoredReason();if(e){Kt.traceTransitionIgnored(t);var r=t.router.globals.transition;return"SameAsCurrent"===e&&r&&r.abort(),qt.ignored().toPromise()}}function Fr(t){if(!t.valid())throw new Error(t.error())}var Ur={location:!0,relative:null,inherit:!1,notify:!0,reload:!1,custom:{},current:function(){return null},source:"unknown"},Lr=function(){function e(t){this._transitionCount=0,this._eventTypes=[],this._registeredHooks={},this._criteriaPaths={},this._router=t,this.$view=t.viewService,this._deregisterHookFns={},this._pluginapi=Q(y(this),{},y(this),["_definePathType","_defineEvent","_getPathTypes","_getEvents","getHooks"]),this._defineCorePaths(),this._defineCoreEvents(),this._registerCoreTransitionHooks(),t.globals.successfulTransitions.onEvict(br)}return e.prototype.onCreate=function(t,e,r){},e.prototype.onBefore=function(t,e,r){},e.prototype.onStart=function(t,e,r){},e.prototype.onExit=function(t,e,r){},e.prototype.onRetain=function(t,e,r){},e.prototype.onEnter=function(t,e,r){},e.prototype.onFinish=function(t,e,r){},e.prototype.onSuccess=function(t,e,r){},e.prototype.onError=function(t,e,r){},e.prototype.dispose=function(t){vt(this._registeredHooks).forEach(function(t){return t.forEach(function(e){e._deregistered=!0,X(t,e)})})},e.prototype.create=function(t,e){return new $e(t,e,this._router)},e.prototype._defineCoreEvents=function(){var e=t.TransitionHookPhase,r=Xt,n=this._criteriaPaths;this._defineEvent("onCreate",e.CREATE,0,n.to,!1,r.LOG_REJECTED_RESULT,r.THROW_ERROR,!0),this._defineEvent("onBefore",e.BEFORE,0,n.to),this._defineEvent("onStart",e.RUN,0,n.to),this._defineEvent("onExit",e.RUN,100,n.exiting,!0),this._defineEvent("onRetain",e.RUN,200,n.retained),this._defineEvent("onEnter",e.RUN,300,n.entering),this._defineEvent("onFinish",e.RUN,400,n.to),this._defineEvent("onSuccess",e.SUCCESS,0,n.to,!1,r.LOG_REJECTED_RESULT,r.LOG_ERROR,!0),this._defineEvent("onError",e.ERROR,0,n.to,!1,r.LOG_REJECTED_RESULT,r.LOG_ERROR,!0)},e.prototype._defineCorePaths=function(){var e=t.TransitionHookScope.STATE,r=t.TransitionHookScope.TRANSITION;this._definePathType("to",r),this._definePathType("from",r),this._definePathType("exiting",e),this._definePathType("retained",e),this._definePathType("entering",e)},e.prototype._defineEvent=function(t,e,r,n,i,o,a,u){void 0===i&&(i=!1),void 0===o&&(o=Xt.HANDLE_RESULT),void 0===a&&(a=Xt.REJECT_ERROR),void 0===u&&(u=!1);var s=new qr(t,e,r,n,i,o,a,u);this._eventTypes.push(s),re(this,this,s)},e.prototype._getEvents=function(t){return(E(t)?this._eventTypes.filter(function(e){return e.hookPhase===t}):this._eventTypes.slice()).sort(function(t,e){var r=t.hookPhase-e.hookPhase;return 0===r?t.hookOrder-e.hookOrder:r})},e.prototype._definePathType=function(t,e){this._criteriaPaths[t]={name:t,scope:e}},e.prototype._getPathTypes=function(){return this._criteriaPaths},e.prototype.getHooks=function(t){return this._registeredHooks[t]},e.prototype._registerCoreTransitionHooks=function(){var t=this._deregisterHookFns;t.addCoreResolves=this.onCreate({},$r),t.ignored=function(t){return t.onBefore({},Nr,{priority:-9999})}(this),t.invalid=function(t){return t.onBefore({},Fr,{priority:-1e4})}(this),t.redirectTo=function(t){return t.onStart({to:function(t){return!!t.redirectTo}},Rr)}(this),t.onExit=function(t){return t.onExit({exiting:function(t){return!!t.onExit}},Cr)}(this),t.onRetain=function(t){return t.onRetain({retained:function(t){return!!t.onRetain}},Tr)}(this),t.onEnter=function(t){return t.onEnter({entering:function(t){return!!t.onEnter}},Pr)}(this),t.eagerResolve=function(t){return t.onStart({},kr,{priority:1e3})}(this),t.lazyResolve=function(t){return t.onEnter({entering:y(!0)},Or,{priority:1e3})}(this),t.resolveAll=function(t){return t.onFinish({},xr,{priority:1e3})}(this),t.loadViews=function(t){return t.onFinish({},Ir)}(this),t.activateViews=function(t){return t.onSuccess({},Vr)}(this),t.updateGlobals=function(t){return t.onCreate({},jr)}(this),t.updateUrl=function(t){return t.onSuccess({},Ar,{priority:9999})}(this),t.lazyLoad=function(t){return t.onBefore({entering:function(t){return!!t.lazyLoad}},Hr)}(this)},e}(),Mr=function(){function e(t){this.router=t,this.invalidCallbacks=[],this._defaultErrorHandler=function(t){t instanceof Error&&t.stack?(console.error(t),console.error(t.stack)):t instanceof qt?(console.error(t.toString()),t.detail&&t.detail.stack&&console.error(t.detail.stack)):console.error(t)};var r=Object.keys(e.prototype).filter(f(Y(["current","$current","params","transition"])));Q(y(e.prototype),this,y(this),r)}return Object.defineProperty(e.prototype,"transition",{get:function(){return this.router.globals.transition},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"params",{get:function(){return this.router.globals.params},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this.router.globals.current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"$current",{get:function(){return this.router.globals.$current},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.defaultErrorHandler(J),this.invalidCallbacks=[]},e.prototype._handleInvalidTargetState=function(t,e){var r=this,n=fe.makeTargetState(this.router.stateRegistry,t),i=this.router.globals,o=function(){return i.transitionHistory.peekTail()},a=o(),u=new Ht(this.invalidCallbacks.slice()),s=new ge(t).injector(),c=function(t){if(t instanceof Yt){var e=t;return(e=r.target(e.identifier(),e.params(),e.options())).valid()?o()!==a?qt.superseded().toPromise():r.transitionTo(e.identifier(),e.params(),e.options()):qt.invalid(e.error()).toPromise()}};return function t(){var r=u.dequeue();return void 0===r?qt.invalid(e.error()).toPromise():N.$q.when(r(e,n,s)).then(c).then(function(e){return e||t()})}()},e.prototype.onInvalid=function(t){return this.invalidCallbacks.push(t),function(){X(this.invalidCallbacks)(t)}.bind(this)},e.prototype.reload=function(t){return this.transitionTo(this.current,this.params,{reload:!E(t)||t,inherit:!1,notify:!1})},e.prototype.go=function(t,e,r){var n=it(r,{relative:this.$current,inherit:!0},Ur);return this.transitionTo(t,e,n)},e.prototype.target=function(t,e,r){if(void 0===r&&(r={}),x(r.reload)&&!r.reload.name)throw new Error("Invalid reload state object");var n=this.router.stateRegistry;if(r.reloadState=!0===r.reload?n.root():n.matcher.find(r.reload,r.relative),r.reload&&!r.reloadState)throw new Error("No such reload state '"+(O(r.reload)?r.reload:r.reload.name)+"'");return new Yt(this.router.stateRegistry,t,e,r)},e.prototype.getCurrentPath=function(){var t=this,e=this.router.globals.successfulTransitions.peekTail();return e?e.treeChanges().to:[new ce(t.router.stateRegistry.root())]},e.prototype.transitionTo=function(e,r,n){var i=this;void 0===r&&(r={}),void 0===n&&(n={});var o=this.router,a=o.globals;n=it(n,Ur);n=G(n,{current:function(){return a.transition}});var u=this.target(e,r,n),s=this.getCurrentPath();if(!u.exists())return this._handleInvalidTargetState(s,u);if(!u.valid())return At(u.error());var c=function(e){return function(r){if(r instanceof qt){var n=o.globals.lastStartedTransitionId===e.$id;if(r.type===t.RejectType.IGNORED)return n&&o.urlRouter.update(),N.$q.when(a.current);var u=r.detail;if(r.type===t.RejectType.SUPERSEDED&&r.redirected&&u instanceof Yt){var s=e.redirect(u);return s.run().catch(c(s))}if(r.type===t.RejectType.ABORTED)return n&&o.urlRouter.update(),N.$q.reject(r)}return i.defaultErrorHandler()(r),N.$q.reject(r)}},f=this.router.transitionService.create(s,u),l=f.run().catch(c(f));return jt(l),G(l,{transition:f})},e.prototype.is=function(t,e,r){r=it(r,{relative:this.$current});var n=this.router.stateRegistry.matcher.find(t,r.relative);if(E(n)){if(this.$current!==n)return!1;if(!e)return!0;var i=n.parameters({inherit:!0,matchingKeys:e});return se.equals(i,se.values(i,e),this.params)}},e.prototype.includes=function(t,e,r){r=it(r,{relative:this.$current});var n=O(t)&&w.fromString(t);if(n){if(!n.matches(this.$current.name))return!1;t=this.$current.name}var i=this.router.stateRegistry.matcher.find(t,r.relative),o=this.$current.includes;if(E(i)){if(!E(o[i.name]))return!1;if(!e)return!0;var a=i.parameters({inherit:!0,matchingKeys:e});return se.equals(a,se.values(a,e),this.params)}},e.prototype.href=function(t,e,r){r=it(r,{lossy:!0,inherit:!0,absolute:!1,relative:this.$current}),e=e||{};var n=this.router.stateRegistry.matcher.find(t,r.relative);if(!E(n))return null;r.inherit&&(e=this.params.$inherit(e,this.$current,n));var i=n&&r.lossy?n.navigable:n;return i&&void 0!==i.url&&null!==i.url?this.router.urlRouter.href(i.url,e,{absolute:r.absolute}):null},e.prototype.defaultErrorHandler=function(t){return this._defaultErrorHandler=t||this._defaultErrorHandler},e.prototype.get=function(t,e){var r=this.router.stateRegistry;return 0===arguments.length?r.get():r.get(t,e||this.$current)},e.prototype.lazyLoad=function(t,e){var r=this.get(t);if(!r||!r.lazyLoad)throw new Error("Can not lazy load "+t);var n=this.getCurrentPath(),i=fe.makeTargetState(this.router.stateRegistry,n);return Dr(e=e||this.router.transitionService.create(n,i),r)},e}(),Br={when:function(t){return new Promise(function(e,r){return e(t)})},reject:function(t){return new Promise(function(e,r){r(t)})},defer:function(){var t={};return t.promise=new Promise(function(e,r){t.resolve=e,t.reject=r}),t},all:function(t){if(I(t))return Promise.all(t);if(x(t)){var e=Object.keys(t).map(function(e){return t[e].then(function(t){return{key:e,val:t}})});return Br.all(e).then(function(t){return t.reduce(function(t,e){return t[e.key]=e.val,t},{})})}}},Gr={},Wr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,zr=/([^\s,]+)/g,Jr={get:function(t){return Gr[t]},has:function(t){return null!=Jr.get(t)},invoke:function(t,e,r){var n=G({},Gr,r||{}),i=Jr.annotate(t),o=bt(function(t){return n.hasOwnProperty(t)},function(t){return"DI can't find injectable: '"+t+"'"}),a=i.filter(o).map(function(t){return n[t]});return P(t)?t.apply(e,a):t.slice(-1)[0].apply(e,a)},annotate:function(t){if(!H(t))throw new Error("Not an injectable function: "+t);if(t&&t.$inject)return t.$inject;if(I(t))return t.slice(0,-1);var e=t.toString().replace(Wr,"");return e.slice(e.indexOf("(")+1,e.indexOf(")")).match(zr)||[]}},Qr=function(t,e){var r=e[0],n=e[1];return t.hasOwnProperty(r)?I(t[r])?t[r].push(n):t[r]=[t[r],n]:t[r]=n,t},Kr=function(t){return t.split("&").filter(z).map(Ae).reduce(Qr,{})};function Yr(t){var e=function(t){return t||""},r=Ve(t).map(e),n=r[0],i=r[1],o=je(n).map(e);return{path:o[0],search:o[1],hash:i,url:t}}var Zr=function(t){var e=t.path(),r=t.search(),n=t.hash(),i=Object.keys(r).map(function(t){var e=r[t];return(I(e)?e:[e]).map(function(e){return t+"="+e})}).reduce(yt,[]).join("&");return e+(i?"?"+i:"")+(n?"#"+n:"")};function Xr(t,e,r,n){return function(i){var o=i.locationService=new r(i),a=i.locationConfig=new n(i,e);return{name:t,service:o,configuration:a,dispose:function(t){t.dispose(o),t.dispose(a)}}}}var tn,en=function(){function t(t,e){var r=this;this.fireAfterUpdate=e,this._listeners=[],this._listener=function(t){return r._listeners.forEach(function(e){return e(t)})},this.hash=function(){return Yr(r._get()).hash},this.path=function(){return Yr(r._get()).path},this.search=function(){return Kr(Yr(r._get()).search)},this._location=F.location,this._history=F.history}return t.prototype.url=function(t,e){return void 0===e&&(e=!0),E(t)&&t!==this._get()&&(this._set(null,null,t,e),this.fireAfterUpdate&&this._listeners.forEach(function(e){return e({url:t})})),Zr(this)},t.prototype.onChange=function(t){var e=this;return this._listeners.push(t),function(){return X(e._listeners,t)}},t.prototype.dispose=function(t){nt(this._listeners)},t}(),rn=(tn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}tn(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),nn=function(t){function e(e){var r=t.call(this,e,!1)||this;return F.addEventListener("hashchange",r._listener,!1),r}return rn(e,t),e.prototype._get=function(){return He(this._location.hash)},e.prototype._set=function(t,e,r,n){this._location.hash=r},e.prototype.dispose=function(e){t.prototype.dispose.call(this,e),F.removeEventListener("hashchange",this._listener)},e}(en),on=function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])};return function(e,r){function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),an=function(t){function e(e){return t.call(this,e,!0)||this}return on(e,t),e.prototype._get=function(){return this._url},e.prototype._set=function(t,e,r,n){this._url=r},e}(en),un=function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])};return function(e,r){function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),sn=function(t){function e(e){var r=t.call(this,e,!0)||this;return r._config=e.urlService.config,F.addEventListener("popstate",r._listener,!1),r}return un(e,t),e.prototype._getBasePrefix=function(){return Ie(this._config.baseHref())},e.prototype._get=function(){var t=this._location,e=t.pathname,r=t.hash,n=t.search;n=je(n)[1],r=Ve(r)[1];var i=this._getBasePrefix(),o=e===this._config.baseHref(),a=e.substr(0,i.length)===i;return(e=o?"/":a?e.substring(i.length):e)+(n?"?"+n:"")+(r?"#"+r:"")},e.prototype._set=function(t,e,r,n){var i=this._getBasePrefix(),o=r&&"/"!==r[0]?"/":"",a=""===r||"/"===r?this._config.baseHref():i+o+r;n?this._history.replaceState(t,e,a):this._history.pushState(t,e,a)},e.prototype.dispose=function(e){t.prototype.dispose.call(this,e),F.removeEventListener("popstate",this._listener)},e}(en),cn=function(){return function(){var t=this;this.dispose=J,this._baseHref="",this._port=80,this._protocol="http",this._host="localhost",this._hashPrefix="",this.port=function(){return t._port},this.protocol=function(){return t._protocol},this.host=function(){return t._host},this.baseHref=function(){return t._baseHref},this.html5Mode=function(){return!1},this.hashPrefix=function(e){return E(e)?t._hashPrefix=e:t._hashPrefix}}}(),fn=function(){function t(t,e){void 0===e&&(e=!1),this._isHtml5=e,this._baseHref=void 0,this._hashPrefix=""}return t.prototype.port=function(){return location.port?Number(location.port):"https"===this.protocol()?443:80},t.prototype.protocol=function(){return location.protocol.replace(/:/g,"")},t.prototype.host=function(){return location.hostname},t.prototype.html5Mode=function(){return this._isHtml5},t.prototype.hashPrefix=function(t){return E(t)?this._hashPrefix=t:this._hashPrefix},t.prototype.baseHref=function(t){return E(t)?this._baseHref=t:E(this._baseHref)?this._baseHref:this.applyDocumentBaseHref()},t.prototype.applyDocumentBaseHref=function(){var t=document.getElementsByTagName("base")[0];return this._baseHref=t?t.href.substr(location.origin.length):location.pathname||"/"},t.prototype.dispose=function(){},t}();function ln(t){return N.$injector=Jr,N.$q=Br,{name:"vanilla.services",$q:Br,$injector:Jr,dispose:function(){return null}}}var hn=Xr("vanilla.hashBangLocation",!1,nn,fn),pn=Xr("vanilla.pushStateLocation",!0,sn,fn),vn=Xr("vanilla.memoryLocation",!1,an,cn),dn=function(){function t(){}return t.prototype.dispose=function(t){},t}(),mn=Object.freeze({root:F,fromJson:L,toJson:M,forEach:B,extend:G,equals:W,identity:z,noop:J,createProxyFunctions:Q,inherit:K,inArray:Y,_inArray:Z,removeFrom:X,_removeFrom:tt,pushTo:et,_pushTo:rt,deregAll:nt,defaults:it,mergeR:ot,ancestors:at,pick:ut,omit:st,pluck:ct,filter:ft,find:lt,mapObj:ht,map:pt,values:vt,allTrueR:dt,anyTrueR:mt,unnestR:yt,flattenR:gt,pushR:_t,uniqR:wt,unnest:$t,flatten:St,assertPredicate:bt,assertMap:Rt,assertFn:Et,pairs:Ct,arrayTuples:Tt,applyPairs:Pt,tail:kt,copy:Ot,_extend:xt,silenceUncaughtInPromise:jt,silentRejection:At,notImplemented:q,services:N,Glob:w,curry:i,compose:o,pipe:a,prop:u,propEq:s,parse:c,not:f,and:l,or:h,all:p,any:v,is:d,eq:m,val:y,invoke:g,pattern:_,isUndefined:R,isDefined:E,isNull:C,isNullOrUndefined:T,isFunction:P,isNumber:k,isString:O,isObject:x,isArray:I,isDate:V,isRegExp:j,isState:A,isInjectable:H,isPromise:D,Queue:Ht,maxLength:Se,padString:be,kebobString:Re,functionToString:Ee,fnToString:Ce,stringify:ke,beforeAfterSubstr:Oe,hostRegex:xe,stripLastPathElement:Ie,splitHash:Ve,splitQuery:je,splitEqual:Ae,trimHashVal:He,splitOnDelim:De,joinNeighborsR:qe,get Category(){return t.Category},Trace:Qt,trace:Kt,get DefType(){return t.DefType},Param:se,ParamTypes:Fe,StateParams:Ue,ParamType:ie,PathNode:ce,PathUtils:fe,resolvePolicies:pe,defaultResolvePolicy:le,Resolvable:he,NATIVE_INJECTOR_TOKEN:ye,ResolveContext:ge,resolvablesBuilder:Ke,StateBuilder:Ye,StateObject:$,StateMatcher:Ze,StateQueueManager:Xe,StateRegistry:tr,StateService:Mr,TargetState:Yt,get TransitionHookPhase(){return t.TransitionHookPhase},get TransitionHookScope(){return t.TransitionHookScope},HookBuilder:ne,matchState:te,RegisteredHook:ee,makeEvent:re,get RejectType(){return t.RejectType},Rejection:qt,Transition:$e,TransitionHook:Xt,TransitionEventType:qr,defaultTransOpts:Ur,TransitionService:Lr,UrlMatcher:nr,UrlMatcherFactory:ir,UrlRouter:sr,UrlRuleFactory:or,BaseUrlRule:ar,UrlService:gr,ViewService:fr,UIRouterGlobals:lr,UIRouter:wr,$q:Br,$injector:Jr,BaseLocationServices:en,HashLocationService:nn,MemoryLocationService:an,PushStateLocationService:sn,MemoryLocationConfig:cn,BrowserLocationConfig:fn,keyValsToObjectR:Qr,getParams:Kr,parseUrl:Yr,buildUrl:Zr,locationPluginFactory:Xr,servicesPlugin:ln,hashLocationPlugin:hn,pushStateLocationPlugin:pn,memoryLocationPlugin:vn,UIRouterPluginBase:dn});function yn(){var t=null;return function(e,r){return t=t||N.$injector.get("$templateFactory"),[new $n(e,r,t)]}}var gn=function(t,e){return t.reduce(function(t,r){return t||E(e[r])},!1)};function _n(t){if(!t.parent)return{};var e=["component","bindings","componentProvider"],r=["templateProvider","templateUrl","template","notify","async"].concat(["controller","controllerProvider","controllerAs","resolveAs"]),n=e.concat(r);if(E(t.views)&&gn(n,t))throw new Error("State '"+t.name+"' has a 'views' object. It cannot also have \"view properties\" at the state level. Move the following properties into a view (in the 'views' object): "+n.filter(function(e){return E(t[e])}).join(", "));var i={},o=t.views||{$default:ut(t,n)};return B(o,function(n,o){if(o=o||"$default",O(n)&&(n={component:n}),n=G({},n),gn(e,n)&&gn(r,n))throw new Error("Cannot combine: "+e.join("|")+" with: "+r.join("|")+" in stateview: '"+o+"@"+t.name+"'");n.resolveAs=n.resolveAs||"$resolve",n.$type="ng1",n.$context=t,n.$name=o;var a=fr.normalizeUIViewTarget(n.$context,n.$name);n.$uiViewName=a.uiViewName,n.$uiViewContextAnchor=a.uiViewContextAnchor,i[o]=n}),i}var wn=0,$n=function(){function t(t,e,r){var n=this;this.path=t,this.viewDecl=e,this.factory=r,this.$id=wn++,this.loaded=!1,this.getTemplate=function(t,e){return n.component?n.factory.makeComponentTemplate(t,e,n.component,n.viewDecl.bindings):n.template}}return t.prototype.load=function(){var t=this,e=N.$q,r=new ge(this.path),n=this.path.reduce(function(t,e){return G(t,e.paramValues)},{}),i={template:e.when(this.factory.fromConfig(this.viewDecl,n,r)),controller:e.when(this.getController(r))};return e.all(i).then(function(e){return Kt.traceViewServiceEvent("Loaded",t),t.controller=e.controller,G(t,e.template),t})},t.prototype.getController=function(t){var e=this.viewDecl.controllerProvider;if(!H(e))return this.viewDecl.controller;var r=N.$injector.annotate(e),n=I(e)?kt(e):e;return new he("",n,r).get(t)},t}(),Sn=function(){function t(){var t=this;this._useHttp=n.version.minor<3,this.$get=["$http","$templateCache","$injector",function(e,r,n){return t.$templateRequest=n.has&&n.has("$templateRequest")&&n.get("$templateRequest"),t.$http=e,t.$templateCache=r,t}]}return t.prototype.useHttpService=function(t){this._useHttp=t},t.prototype.fromConfig=function(t,e,r){var n=function(t){return N.$q.when(t).then(function(t){return{template:t}})},i=function(t){return N.$q.when(t).then(function(t){return{component:t}})};return E(t.template)?n(this.fromString(t.template,e)):E(t.templateUrl)?n(this.fromUrl(t.templateUrl,e)):E(t.templateProvider)?n(this.fromProvider(t.templateProvider,e,r)):E(t.component)?i(t.component):E(t.componentProvider)?i(this.fromComponentProvider(t.componentProvider,e,r)):n("")},t.prototype.fromString=function(t,e){return P(t)?t(e):t},t.prototype.fromUrl=function(t,e){return P(t)&&(t=t(e)),null==t?null:this._useHttp?this.$http.get(t,{cache:this.$templateCache,headers:{Accept:"text/html"}}).then(function(t){return t.data}):this.$templateRequest(t)},t.prototype.fromProvider=function(t,e,r){var n=N.$injector.annotate(t),i=I(t)?kt(t):t;return new he("",i,n).get(r)},t.prototype.fromComponentProvider=function(t,e,r){var n=N.$injector.annotate(t),i=I(t)?kt(t):t;return new he("",i,n).get(r)},t.prototype.makeComponentTemplate=function(t,e,r,i){i=i||{};var o=n.version.minor>=3?"::":"",a=function(t){var e=Re(t);return/^(x|data)-/.exec(e)?"x-"+e:e},u=function(t){var e=N.$injector.get(t+"Directive");if(!e||!e.length)throw new Error("Unable to find component named '"+t+"'");return e.map(bn).reduce(yt,[])}(r).map(function(r){var n=r.name,u=r.type,s=a(n);if(t.attr(s)&&!i[n])return s+"='"+t.attr(s)+"'";var c=i[n]||n;if("@"===u)return s+"='{{"+o+"$resolve."+c+"}}'";if("&"===u){var f=e.getResolvable(c),l=f&&f.data,h=l&&N.$injector.annotate(l)||[];return s+"='$resolve."+c+(I(l)?"["+(l.length-1)+"]":"")+"("+h.join(",")+")'"}return s+"='"+o+"$resolve."+c+"'"}).join(" "),s=a(r);return"<"+s+" "+u+">"},t}();var bn=function(t){return x(t.bindToController)?Rn(t.bindToController):Rn(t.scope)},Rn=function(t){return Object.keys(t||{}).map(function(e){return[e,/^([=<@&])[?]?(.*)/.exec(t[e])]}).filter(function(t){return E(t)&&I(t[1])}).map(function(t){return{name:t[1][2]||t[0],type:t[1][1]}})},En=function(){function t(e,r){this.stateRegistry=e,this.stateService=r,Q(y(t.prototype),this,y(this))}return t.prototype.decorator=function(t,e){return this.stateRegistry.decorator(t,e)||this},t.prototype.state=function(t,e){return x(t)?e=t:e.name=t,this.stateRegistry.register(e),this},t.prototype.onInvalid=function(t){return this.stateService.onInvalid(t)},t}(),Cn=function(t){return function(e,r){var n=e[t],i="onExit"===t?"from":"to";return n?function(t,e){var r=new ge(t.treeChanges(i)).subContext(e.$$state()),o=G(Mn(r),{$state$:e,$transition$:t});return N.$injector.invoke(n,this,o)}:void 0}},Tn=function(){function t(t){this._urlListeners=[],this.$locationProvider=t;var e=y(t);Q(e,this,e,["hashPrefix"])}return t.monkeyPatchPathParameterType=function(t){var e=t.urlMatcherFactory.type("path");e.encode=function(t){return null!=t?t.toString().replace(/(~|\/)/g,function(t){return{"~":"~~","/":"~2F"}[t]}):t},e.decode=function(t){return null!=t?t.toString().replace(/(~~|~2F)/g,function(t){return{"~~":"~","~2F":"/"}[t]}):t}},t.prototype.dispose=function(){},t.prototype.onChange=function(t){var e=this;return this._urlListeners.push(t),function(){return X(e._urlListeners)(t)}},t.prototype.html5Mode=function(){var t=this.$locationProvider.html5Mode();return(t=x(t)?t.enabled:t)&&this.$sniffer.history},t.prototype.url=function(t,e,r){return void 0===e&&(e=!1),E(t)&&this.$location.url(t),e&&this.$location.replace(),r&&this.$location.state(r),this.$location.url()},t.prototype._runtimeServices=function(t,e,r,n){var i=this;this.$location=e,this.$sniffer=r,t.$on("$locationChangeSuccess",function(t){return i._urlListeners.forEach(function(e){return e(t)})});var o=y(e),a=y(n);Q(o,this,o,["replace","path","search","hash"]),Q(o,this,o,["port","protocol","host"]),Q(a,this,a,["baseHref"])},t}(),Pn=function(){function t(t){this._router=t,this._urlRouter=t.urlRouter}return t.injectableHandler=function(t,e){return function(r){return N.$injector.invoke(e,null,{$match:r,$stateParams:t.globals.params})}},t.prototype.$get=function(){var t=this._urlRouter;return t.update(!0),t.interceptDeferred||t.listen(),t},t.prototype.rule=function(t){var e=this;if(!P(t))throw new Error("'rule' must be a function");var r=new ar(function(){return t(N.$injector,e._router.locationService)},z);return this._urlRouter.rule(r),this},t.prototype.otherwise=function(t){var e=this,r=this._urlRouter;if(O(t))r.otherwise(t);else{if(!P(t))throw new Error("'rule' must be a string or function");r.otherwise(function(){return t(N.$injector,e._router.locationService)})}return this},t.prototype.when=function(e,r){return(I(r)||P(r))&&(r=t.injectableHandler(this._router,r)),this._urlRouter.when(e,r),this},t.prototype.deferIntercept=function(t){this._urlRouter.deferIntercept(t)},t}();n.module("ui.router.angular1",[]);var kn=n.module("ui.router.init",[]),On=n.module("ui.router.util",["ng","ui.router.init"]),xn=n.module("ui.router.router",["ui.router.util"]),In=n.module("ui.router.state",["ui.router.router","ui.router.util","ui.router.angular1"]),Vn=n.module("ui.router",["ui.router.init","ui.router.state","ui.router.angular1"]),jn=(n.module("ui.router.compat",["ui.router"]),null);function An(t){(jn=this.router=new wr).stateProvider=new En(jn.stateRegistry,jn.stateService),jn.stateRegistry.decorator("views",_n),jn.stateRegistry.decorator("onExit",Cn("onExit")),jn.stateRegistry.decorator("onRetain",Cn("onRetain")),jn.stateRegistry.decorator("onEnter",Cn("onEnter")),jn.viewService._pluginapi._viewConfigFactory("ng1",yn());var e=jn.locationService=jn.locationConfig=new Tn(t);function r(t,r,n,i,o,a){return e._runtimeServices(i,t,n,r),delete jn.router,delete jn.$get,jn}return Tn.monkeyPatchPathParameterType(jn),jn.router=jn,jn.$get=r,r.$inject=["$location","$browser","$sniffer","$rootScope","$http","$templateCache"],jn}An.$inject=["$locationProvider"];var Hn=function(t){return["$uiRouterProvider",function(e){var r=e.router[t];return r.$get=function(){return r},r}]};function Dn(t,e,r){N.$injector=t,N.$q=e,r.stateRegistry.get().map(function(t){return t.$$state().resolvables}).reduce(yt,[]).filter(function(t){return"deferred"===t.deps}).forEach(function(e){return e.deps=t.annotate(e.resolveFn,t.strictDi)})}Dn.$inject=["$injector","$q","$uiRouter"];function qn(t){t.$watch(function(){Kt.approximateDigests++})}qn.$inject=["$rootScope"],kn.provider("$uiRouter",An),xn.provider("$urlRouter",["$uiRouterProvider",function(t){return t.urlRouterProvider=new Pn(t)}]),On.provider("$urlService",Hn("urlService")),On.provider("$urlMatcherFactory",["$uiRouterProvider",function(){return jn.urlMatcherFactory}]),On.provider("$templateFactory",function(){return new Sn}),In.provider("$stateRegistry",Hn("stateRegistry")),In.provider("$uiRouterGlobals",Hn("globals")),In.provider("$transitions",Hn("transitionService")),In.provider("$state",["$uiRouterProvider",function(){return G(jn.stateProvider,{$get:function(){return jn.stateService}})}]),In.factory("$stateParams",["$uiRouter",function(t){return t.globals.params}]),Vn.factory("$view",function(){return jn.viewService}),Vn.service("$trace",function(){return Kt}),Vn.run(qn),On.run(["$urlMatcherFactory",function(t){}]),In.run(["$state",function(t){}]),xn.run(["$urlRouter",function(t){}]),kn.run(Dn);var Nn,Fn,Un,Ln,Mn=function(t){return t.getTokens().filter(O).map(function(e){var r=t.getResolvable(e);return[e,"NOWAIT"===t.getPolicy(r).async?r.promise:r.data]}).reduce(Pt,{})};function Bn(t){var e,r=t.match(/^\s*({[^}]*})\s*$/);if(r&&(t="("+r[1]+")"),!(e=t.replace(/\n/g," ").match(/^\s*([^(]*?)\s*(\((.*)\))?\s*$/))||4!==e.length)throw new Error("Invalid state ref '"+t+"'");return{state:e[1]||null,paramExpr:e[3]||null}}function Gn(t){var e=t.parent().inheritedData("$uiView"),r=c("$cfg.path")(e);return r?kt(r).state.name:void 0}function Wn(t,e,r){var n=r.uiState||t.current.name,i=G(function(t,e){return{relative:Gn(t)||e.$current,inherit:!0,source:"sref"}}(e,t),r.uiStateOpts||{}),o=t.href(n,r.uiStateParams,i);return{uiState:n,uiStateParams:r.uiStateParams,uiStateOpts:i,href:o}}function zn(t){var e="[object SVGAnimatedString]"===Object.prototype.toString.call(t.prop("href")),r="FORM"===t[0].nodeName;return{attr:r?"action":e?"xlink:href":"href",isAnchor:"A"===t.prop("tagName").toUpperCase(),clickable:!r}}function Jn(t,e,r,n,i){return function(o){var a=o.which||o.button,u=i();if(!(a>1||o.ctrlKey||o.metaKey||o.shiftKey||t.attr("target"))){var s=r(function(){e.go(u.uiState,u.uiStateParams,u.uiStateOpts)});o.preventDefault();var c=n.isAnchor&&!u.href?1:0;o.preventDefault=function(){c--<=0&&r.cancel(s)}}}}function Qn(t,e,r,n){var i;n&&(i=n.events),I(i)||(i=["click"]);for(var o=t.on?"on":"bind",a=0,u=i;a0)){var r=d(t,e,u);return m(),r}},e.$on("$destroy",(s=n.stateRegistry.onStatesChanged(p),c=n.transitionService.onStart({},h),f=e.$on("$stateChangeSuccess",m),function(){s(),c(),f()})),n.globals.transition&&h(n.globals.transition),m()}]}}],n.module("ui.router.state").directive("uiSref",Nn).directive("uiSrefActive",Un).directive("uiSrefActiveEq",Un).directive("uiState",Fn),Kn.$inject=["$state"],Yn.$inject=["$state"],n.module("ui.router.state").filter("isState",Kn).filter("includedByState",Yn),Ln=["$view","$animate","$uiViewScroll","$interpolate","$q",function(t,e,r,i,o){var a={$cfg:{viewDecl:{$context:t._pluginapi._rootViewContext()}},$uiView:{}},u={count:0,restrict:"ECA",terminal:!0,priority:400,transclude:"element",compile:function(s,f,l){return function(s,f,h){var p,v,d,m,y,g=h.onload||"",_=h.autoscroll,w={enter:function(t,r,i){n.version.minor>2?e.enter(t,null,r).then(i):e.enter(t,null,r,i)},leave:function(t,r){n.version.minor>2?e.leave(t).then(r):e.leave(t,r)}},$=f.inheritedData("$uiView")||a,S=i(h.uiView||h.name||"")(s)||"$default",b={$type:"ng1",id:u.count++,name:S,fqn:$.$uiView.fqn?$.$uiView.fqn+"."+S:S,config:null,configUpdated:function(t){if(t&&!(t instanceof $n))return;if(e=m,r=t,e===r)return;var e,r;Kt.traceUIViewConfigUpdated(b,t&&t.viewDecl&&t.viewDecl.$context),m=t,R(t)},get creationContext(){var t=c("$cfg.viewDecl.$context")($),e=c("$uiView.creationContext")($);return t||e}};function R(t){var e=s.$new(),n=o.defer(),i=o.defer(),a={$cfg:t,$uiView:b},u={$animEnter:n.promise,$animLeave:i.promise,$$animLeave:i};e.$emit("$viewContentLoading",S);var c=l(e,function(t){t.data("$uiViewAnim",u),t.data("$uiView",a),w.enter(t,f,function(){n.resolve(),d&&d.$emit("$viewContentAnimationEnded"),(E(_)&&!_||s.$eval(_))&&r(t)}),function(){if(p&&(Kt.traceUIViewEvent("Removing (previous) el",p.data("$uiView")),p.remove(),p=null),d&&(Kt.traceUIViewEvent("Destroying scope",b),d.$destroy(),d=null),v){var t=v.data("$uiViewAnim");Kt.traceUIViewEvent("Animate out",t),w.leave(v,function(){t.$$animLeave.resolve(),p=null}),p=v,v=null}}()});v=c,(d=e).$emit("$viewContentLoaded",t||m),d.$eval(g)}Kt.traceUIViewEvent("Linking",b),f.data("$uiView",{$uiView:b}),R(),y=t.registerUIView(b),s.$on("$destroy",function(){Kt.traceUIViewEvent("Destroying/Unregistering",b),y()})}}};return u}],Zn.$inject=["$compile","$controller","$transitions","$view","$q","$timeout"];var Xn="function"==typeof n.module("ui.router").component,ti=0;function ei(t,e,r,n,i){!P(r.$onInit)||i.viewDecl.component&&Xn||r.$onInit();var o=kt(i.path).state.self,a={bind:r};if(P(r.uiOnParamsChanged)){var u=new ge(i.path).getResolvable("$transition$").data;n.$on("$destroy",e.onSuccess({},function(t){if(t!==u&&-1===t.exiting().indexOf(o)){var e=t.params("to"),n=t.params("from"),i=t.treeChanges().to.map(function(t){return t.paramSchema}).reduce(yt,[]),a=t.treeChanges().from.map(function(t){return t.paramSchema}).reduce(yt,[]),s=i.filter(function(t){var r=a.indexOf(t);return-1===r||!a[r].type.equals(e[t.id],n[t.id])});if(s.length){var c=s.map(function(t){return t.id}),f=ft(e,function(t,e){return-1!==c.indexOf(e)});r.uiOnParamsChanged(f,t)}}},a))}if(P(r.uiCanExit)){var s=ti++,c=function(t){return!!t&&(t._uiCanExitIds&&!0===t._uiCanExitIds[s]||c(t.redirectedFrom()))},f={exiting:o.name};n.$on("$destroy",e.onBefore(f,function(e){var n,i=e._uiCanExitIds=e._uiCanExitIds||{};return c(e)||(n=t.when(r.uiCanExit(e))).then(function(t){return i[s]=!1!==t}),n},a))}}n.module("ui.router.state").directive("uiView",Ln),n.module("ui.router.state").directive("uiView",Zn),n.module("ui.router.state").provider("$uiViewScroll",function(){var t=!1;this.useAnchorScroll=function(){t=!0},this.$get=["$anchorScroll","$timeout",function(e,r){return t?e:function(t){return r(function(){t[0].scrollIntoView()},0,!1)}}]});t.default="ui.router",t.core=mn,t.watchDigests=qn,t.getLocals=Mn,t.getNg1ViewConfigFactory=yn,t.ng1ViewsBuilder=_n,t.Ng1ViewConfig=$n,t.StateProvider=En,t.UrlRouterProvider=Pn,t.root=F,t.fromJson=L,t.toJson=M,t.forEach=B,t.extend=G,t.equals=W,t.identity=z,t.noop=J,t.createProxyFunctions=Q,t.inherit=K,t.inArray=Y,t._inArray=Z,t.removeFrom=X,t._removeFrom=tt,t.pushTo=et,t._pushTo=rt,t.deregAll=nt,t.defaults=it,t.mergeR=ot,t.ancestors=at,t.pick=ut,t.omit=st,t.pluck=ct,t.filter=ft,t.find=lt,t.mapObj=ht,t.map=pt,t.values=vt,t.allTrueR=dt,t.anyTrueR=mt,t.unnestR=yt,t.flattenR=gt,t.pushR=_t,t.uniqR=wt,t.unnest=$t,t.flatten=St,t.assertPredicate=bt,t.assertMap=Rt,t.assertFn=Et,t.pairs=Ct,t.arrayTuples=Tt,t.applyPairs=Pt,t.tail=kt,t.copy=Ot,t._extend=xt,t.silenceUncaughtInPromise=jt,t.silentRejection=At,t.notImplemented=q,t.services=N,t.Glob=w,t.curry=i,t.compose=o,t.pipe=a,t.prop=u,t.propEq=s,t.parse=c,t.not=f,t.and=l,t.or=h,t.all=p,t.any=v,t.is=d,t.eq=m,t.val=y,t.invoke=g,t.pattern=_,t.isUndefined=R,t.isDefined=E,t.isNull=C,t.isNullOrUndefined=T,t.isFunction=P,t.isNumber=k,t.isString=O,t.isObject=x,t.isArray=I,t.isDate=V,t.isRegExp=j,t.isState=A,t.isInjectable=H,t.isPromise=D,t.Queue=Ht,t.maxLength=Se,t.padString=be,t.kebobString=Re,t.functionToString=Ee,t.fnToString=Ce,t.stringify=ke,t.beforeAfterSubstr=Oe,t.hostRegex=xe,t.stripLastPathElement=Ie,t.splitHash=Ve,t.splitQuery=je,t.splitEqual=Ae,t.trimHashVal=He,t.splitOnDelim=De,t.joinNeighborsR=qe,t.Trace=Qt,t.trace=Kt,t.Param=se,t.ParamTypes=Fe,t.StateParams=Ue,t.ParamType=ie,t.PathNode=ce,t.PathUtils=fe,t.resolvePolicies=pe,t.defaultResolvePolicy=le,t.Resolvable=he,t.NATIVE_INJECTOR_TOKEN=ye,t.ResolveContext=ge,t.resolvablesBuilder=Ke,t.StateBuilder=Ye,t.StateObject=$,t.StateMatcher=Ze,t.StateQueueManager=Xe,t.StateRegistry=tr,t.StateService=Mr,t.TargetState=Yt,t.HookBuilder=ne,t.matchState=te,t.RegisteredHook=ee,t.makeEvent=re,t.Rejection=qt,t.Transition=$e,t.TransitionHook=Xt,t.TransitionEventType=qr,t.defaultTransOpts=Ur,t.TransitionService=Lr,t.UrlMatcher=nr,t.UrlMatcherFactory=ir,t.UrlRouter=sr,t.UrlRuleFactory=or,t.BaseUrlRule=ar,t.UrlService=gr,t.ViewService=fr,t.UIRouterGlobals=lr,t.UIRouter=wr,t.$q=Br,t.$injector=Jr,t.BaseLocationServices=en,t.HashLocationService=nn,t.MemoryLocationService=an,t.PushStateLocationService=sn,t.MemoryLocationConfig=cn,t.BrowserLocationConfig=fn,t.keyValsToObjectR=Qr,t.getParams=Kr,t.parseUrl=Yr,t.buildUrl=Zr,t.locationPluginFactory=Xr,t.servicesPlugin=ln,t.hashLocationPlugin=hn,t.pushStateLocationPlugin=pn,t.memoryLocationPlugin=vn,t.UIRouterPluginBase=dn,Object.defineProperty(t,"__esModule",{value:!0})}); +!(function(t, e) { + 'object' == typeof exports && 'undefined' != typeof module + ? e(exports, require('angular')) + : 'function' == typeof define && define.amd + ? define(['exports', 'angular'], e) + : e((t['@uirouter/angularjs'] = {}), t.angular); +})(this, function(t, e) { + 'use strict'; + var r = angular, + n = e && e.module ? e : r; + function i(t) { + var e = [].slice.apply(arguments, [1]), + r = t.length; + return (function e(n) { + return n.length >= r + ? t.apply(null, n) + : function() { + return e(n.concat([].slice.apply(arguments))); + }; + })(e); + } + function o() { + var t = arguments, + e = t.length - 1; + return function() { + for (var r = e, n = t[e].apply(this, arguments); r--; ) n = t[r].call(this, n); + return n; + }; + } + function a() { + for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e]; + return o.apply(null, [].slice.call(arguments).reverse()); + } + var u = function(t) { + return function(e) { + return e && e[t]; + }; + }, + s = i(function(t, e, r) { + return r && r[t] === e; + }), + c = function(t) { + return a.apply(null, t.split('.').map(u)); + }, + f = function(t) { + return function() { + for (var e = [], r = 0; r < arguments.length; r++) e[r] = arguments[r]; + return !t.apply(null, e); + }; + }; + function l(t, e) { + return function() { + for (var r = [], n = 0; n < arguments.length; n++) r[n] = arguments[n]; + return t.apply(null, r) && e.apply(null, r); + }; + } + function h(t, e) { + return function() { + for (var r = [], n = 0; n < arguments.length; n++) r[n] = arguments[n]; + return t.apply(null, r) || e.apply(null, r); + }; + } + var p = function(t) { + return function(e) { + return e.reduce(function(e, r) { + return e && !!t(r); + }, !0); + }; + }, + v = function(t) { + return function(e) { + return e.reduce(function(e, r) { + return e || !!t(r); + }, !1); + }; + }, + d = function(t) { + return function(e) { + return (null != e && e.constructor === t) || e instanceof t; + }; + }, + m = function(t) { + return function(e) { + return t === e; + }; + }, + y = function(t) { + return function() { + return t; + }; + }; + function g(t, e) { + return function(r) { + return r[t].apply(r, e); + }; + } + function _(t) { + return function(e) { + for (var r = 0; r < t.length; r++) if (t[r][0](e)) return t[r][1](e); + }; + } + var w = (function() { + function t(t) { + (this.text = t), (this.glob = t.split('.')); + var e = this.text + .split('.') + .map(function(t) { + return '**' === t ? '(?:|(?:\\.[^.]*)*)' : '*' === t ? '\\.[^.]*' : '\\.' + t; + }) + .join(''); + this.regexp = new RegExp('^' + e + '$'); + } + return ( + (t.is = function(t) { + return !!/[!,*]+/.exec(t); + }), + (t.fromString = function(e) { + return t.is(e) ? new t(e) : null; + }), + (t.prototype.matches = function(t) { + return this.regexp.test('.' + t); + }), + t + ); + })(), + $ = (function() { + function t(e) { + return t.create(e || {}); + } + return ( + (t.create = function(e) { + e = t.isStateClass(e) ? new e() : e; + var r = K(K(e, t.prototype)); + return ( + (e.$$state = function() { + return r; + }), + (r.self = e), + (r.__stateObjectCache = { nameGlob: w.fromString(r.name) }), + r + ); + }), + (t.prototype.is = function(t) { + return this === t || this.self === t || this.fqn() === t; + }), + (t.prototype.fqn = function() { + if (!(this.parent && this.parent instanceof this.constructor)) return this.name; + var t = this.parent.fqn(); + return t ? t + '.' + this.name : this.name; + }), + (t.prototype.root = function() { + return (this.parent && this.parent.root()) || this; + }), + (t.prototype.parameters = function(t) { + return ( + ((t = it(t, { inherit: !0, matchingKeys: null })).inherit && this.parent && this.parent.parameters()) || + [] + ) + .concat(vt(this.params)) + .filter(function(e) { + return !t.matchingKeys || t.matchingKeys.hasOwnProperty(e.id); + }); + }), + (t.prototype.parameter = function(t, e) { + return ( + void 0 === e && (e = {}), + (this.url && this.url.parameter(t, e)) || + lt(vt(this.params), s('id', t)) || + (e.inherit && this.parent && this.parent.parameter(t)) + ); + }), + (t.prototype.toString = function() { + return this.fqn(); + }), + (t.isStateClass = function(t) { + return P(t) && !0 === t.__uiRouterState; + }), + (t.isState = function(t) { + return x(t.__stateObjectCache); + }), + t + ); + })(), + S = Object.prototype.toString, + b = function(t) { + return function(e) { + return typeof e === t; + }; + }, + R = b('undefined'), + E = f(R), + C = function(t) { + return null === t; + }, + T = h(C, R), + P = b('function'), + k = b('number'), + O = b('string'), + x = function(t) { + return null !== t && 'object' == typeof t; + }, + V = Array.isArray, + I = function(t) { + return '[object Date]' === S.call(t); + }, + j = function(t) { + return '[object RegExp]' === S.call(t); + }, + A = $.isState; + function H(t) { + if (V(t) && t.length) { + var e = t.slice(0, -1), + r = t.slice(-1); + return !(e.filter(f(O)).length || r.filter(f(P)).length); + } + return P(t); + } + var D = l(x, a(u('then'), P)), + q = function(t) { + return function() { + throw new Error(t + '(): No coreservices implementation for UI-Router is loaded.'); + }; + }, + N = { $q: void 0, $injector: void 0 }, + F = + ('object' == typeof self && self.self === self && self) || + ('object' == typeof global && global.global === global && global) || + void 0, + U = F.angular || {}, + L = U.fromJson || JSON.parse.bind(JSON), + M = U.toJson || JSON.stringify.bind(JSON), + B = + U.forEach || + function(t, e, r) { + if (V(t)) return t.forEach(e, r); + Object.keys(t).forEach(function(r) { + return e(t[r], r); + }); + }, + G = Object.assign || xt, + W = U.equals || Vt; + function z(t) { + return t; + } + function J() {} + function Q(t, e, r, n, i) { + void 0 === i && (i = !1); + var o = function(e) { + return t()[e].bind(r()); + }; + return (n = n || Object.keys(t())).reduce(function(t, r) { + var n; + return ( + (t[r] = i + ? ((n = r), + function() { + return (e[n] = o(n)), e[n].apply(null, arguments); + }) + : o(r)), + t + ); + }, e); + } + var K = function(t, e) { + return G(Object.create(t), e); + }, + Y = i(Z); + function Z(t, e) { + return -1 !== t.indexOf(e); + } + var X = i(tt); + function tt(t, e) { + var r = t.indexOf(e); + return r >= 0 && t.splice(r, 1), t; + } + var et = i(rt); + function rt(t, e) { + return t.push(e), e; + } + var nt = function(t) { + return t.slice().forEach(function(e) { + 'function' == typeof e && e(), X(t, e); + }); + }; + function it(t) { + for (var e = [], r = 1; r < arguments.length; r++) e[r - 1] = arguments[r]; + var n = e.concat({}).reverse(), + i = G.apply(null, n); + return G({}, i, ut(t || {}, Object.keys(i))); + } + var ot = function(t, e) { + return G(t, e); + }; + function at(t, e) { + var r = []; + for (var n in t.path) { + if (t.path[n] !== e.path[n]) break; + r.push(t.path[n]); + } + return r; + } + function ut(t, e) { + var r = {}; + for (var n in t) -1 !== e.indexOf(n) && (r[n] = t[n]); + return r; + } + function st(t, e) { + return Object.keys(t) + .filter(f(Y(e))) + .reduce(function(e, r) { + return (e[r] = t[r]), e; + }, {}); + } + function ct(t, e) { + return pt(t, u(e)); + } + function ft(t, e) { + var r = V(t), + n = r ? [] : {}, + i = r + ? function(t) { + return n.push(t); + } + : function(t, e) { + return (n[e] = t); + }; + return ( + B(t, function(t, r) { + e(t, r) && i(t, r); + }), + n + ); + } + function lt(t, e) { + var r; + return ( + B(t, function(t, n) { + r || (e(t, n) && (r = t)); + }), + r + ); + } + var ht = pt; + function pt(t, e, r) { + return ( + (r = r || (V(t) ? [] : {})), + B(t, function(t, n) { + return (r[n] = e(t, n)); + }), + r + ); + } + var vt = function(t) { + return Object.keys(t).map(function(e) { + return t[e]; + }); + }, + dt = function(t, e) { + return t && e; + }, + mt = function(t, e) { + return t || e; + }, + yt = function(t, e) { + return t.concat(e); + }, + gt = function(t, e) { + return V(e) ? t.concat(e.reduce(gt, [])) : _t(t, e); + }; + function _t(t, e) { + return t.push(e), t; + } + var wt = function(t, e) { + return Y(t, e) ? t : _t(t, e); + }, + $t = function(t) { + return t.reduce(yt, []); + }, + St = function(t) { + return t.reduce(gt, []); + }, + bt = Et, + Rt = Et; + function Et(t, e) { + return ( + void 0 === e && (e = 'assert failure'), + function(r) { + var n = t(r); + if (!n) throw new Error(P(e) ? e(r) : e); + return n; + } + ); + } + var Ct = function(t) { + return Object.keys(t).map(function(e) { + return [e, t[e]]; + }); + }; + function Tt() { + for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e]; + if (0 === t.length) return []; + for ( + var r = t.reduce(function(t, e) { + return Math.min(e.length, t); + }, 9007199254740991), + n = [], + i = function(e) { + switch (t.length) { + case 1: + n.push([t[0][e]]); + break; + case 2: + n.push([t[0][e], t[1][e]]); + break; + case 3: + n.push([t[0][e], t[1][e], t[2][e]]); + break; + case 4: + n.push([t[0][e], t[1][e], t[2][e], t[3][e]]); + break; + default: + n.push( + t.map(function(t) { + return t[e]; + }), + ); + } + }, + o = 0; + o < r; + o++ + ) + i(o); + return n; + } + function Pt(t, e) { + var r, n; + if ((V(e) && ((r = e[0]), (n = e[1])), !O(r))) throw new Error('invalid parameters to applyPairs'); + return (t[r] = n), t; + } + function kt(t) { + return (t.length && t[t.length - 1]) || void 0; + } + function Ot(t, e) { + return ( + e && + Object.keys(e).forEach(function(t) { + return delete e[t]; + }), + e || (e = {}), + G(e, t) + ); + } + function xt(t) { + for (var e = 1; e < arguments.length; e++) { + var r = arguments[e]; + if (r) for (var n = Object.keys(r), i = 0; i < n.length; i++) t[n[i]] = r[n[i]]; + } + return t; + } + function Vt(t, e) { + if (t === e) return !0; + if (null === t || null === e) return !1; + if (t != t && e != e) return !0; + var r = typeof t; + if (r !== typeof e || 'object' !== r) return !1; + var n, + i, + o = [t, e]; + if (p(V)(o)) + return ( + (i = e), + (n = t).length === i.length && + Tt(n, i).reduce(function(t, e) { + return t && Vt(e[0], e[1]); + }, !0) + ); + if (p(I)(o)) return t.getTime() === e.getTime(); + if (p(j)(o)) return t.toString() === e.toString(); + if (p(P)(o)) return !0; + if ( + [P, V, I, j].map(v).reduce(function(t, e) { + return t || !!e(o); + }, !1) + ) + return !1; + var a = {}; + for (var u in t) { + if (!Vt(t[u], e[u])) return !1; + a[u] = !0; + } + for (var u in e) if (!a[u]) return !1; + return !0; + } + var It, + jt = function(t) { + return ( + t.catch(function(t) { + return 0; + }) && t + ); + }, + At = function(t) { + return jt(N.$q.reject(t)); + }, + Ht = (function() { + function t(t, e) { + void 0 === t && (t = []), + void 0 === e && (e = null), + (this._items = t), + (this._limit = e), + (this._evictListeners = []), + (this.onEvict = et(this._evictListeners)); + } + return ( + (t.prototype.enqueue = function(t) { + var e = this._items; + return e.push(t), this._limit && e.length > this._limit && this.evict(), t; + }), + (t.prototype.evict = function() { + var t = this._items.shift(); + return ( + this._evictListeners.forEach(function(e) { + return e(t); + }), + t + ); + }), + (t.prototype.dequeue = function() { + if (this.size()) return this._items.splice(0, 1)[0]; + }), + (t.prototype.clear = function() { + var t = this._items; + return (this._items = []), t; + }), + (t.prototype.size = function() { + return this._items.length; + }), + (t.prototype.remove = function(t) { + var e = this._items.indexOf(t); + return e > -1 && this._items.splice(e, 1)[0]; + }), + (t.prototype.peekTail = function() { + return this._items[this._items.length - 1]; + }), + (t.prototype.peekHead = function() { + if (this.size()) return this._items[0]; + }), + t + ); + })(); + ((It = t.RejectType || (t.RejectType = {}))[(It.SUPERSEDED = 2)] = 'SUPERSEDED'), + (It[(It.ABORTED = 3)] = 'ABORTED'), + (It[(It.INVALID = 4)] = 'INVALID'), + (It[(It.IGNORED = 5)] = 'IGNORED'), + (It[(It.ERROR = 6)] = 'ERROR'); + var Dt = 0, + qt = (function() { + function e(t, e, r) { + (this.$id = Dt++), (this.type = t), (this.message = e), (this.detail = r); + } + return ( + (e.isRejectionPromise = function(t) { + return t && 'function' == typeof t.then && d(e)(t._transitionRejection); + }), + (e.superseded = function(r, n) { + var i = new e(t.RejectType.SUPERSEDED, 'The transition has been superseded by a different transition', r); + return n && n.redirected && (i.redirected = !0), i; + }), + (e.redirected = function(t) { + return e.superseded(t, { redirected: !0 }); + }), + (e.invalid = function(r) { + return new e(t.RejectType.INVALID, 'This transition is invalid', r); + }), + (e.ignored = function(r) { + return new e(t.RejectType.IGNORED, 'The transition was ignored', r); + }), + (e.aborted = function(r) { + return new e(t.RejectType.ABORTED, 'The transition has been aborted', r); + }), + (e.errored = function(r) { + return new e(t.RejectType.ERROR, 'The transition errored', r); + }), + (e.normalize = function(t) { + return d(e)(t) ? t : e.errored(t); + }), + (e.prototype.toString = function() { + var t, + e = (t = this.detail) && t.toString !== Object.prototype.toString ? t.toString() : ke(t); + return ( + 'Transition Rejection($id: ' + + this.$id + + ' type: ' + + this.type + + ', message: ' + + this.message + + ', detail: ' + + e + + ')' + ); + }), + (e.prototype.toPromise = function() { + return G(At(this), { _transitionRejection: this }); + }), + e + ); + })(); + function Nt(t) { + if (!t) return 'ui-view (defunct)'; + var e = t.creationContext ? t.creationContext.name || '(root)' : '(none)'; + return '[ui-view#' + t.id + ' ' + t.$type + ':' + t.fqn + ' (' + t.name + '@' + e + ')]'; + } + function Ft(e) { + return k(e) ? t.Category[e] : t.Category[t.Category[e]]; + } + var Ut, + Lt = Function.prototype.bind.call(console.log, console), + Mt = P(console.table) ? console.table.bind(console) : Lt.bind(console); + ((Ut = t.Category || (t.Category = {}))[(Ut.RESOLVE = 0)] = 'RESOLVE'), + (Ut[(Ut.TRANSITION = 1)] = 'TRANSITION'), + (Ut[(Ut.HOOK = 2)] = 'HOOK'), + (Ut[(Ut.UIVIEW = 3)] = 'UIVIEW'), + (Ut[(Ut.VIEWCONFIG = 4)] = 'VIEWCONFIG'); + var Bt, + Gt, + Wt = c('$id'), + zt = c('router.$id'), + Jt = function(t) { + return 'Transition #' + Wt(t) + '-' + zt(t); + }, + Qt = (function() { + function e() { + (this._enabled = {}), (this.approximateDigests = 0); + } + return ( + (e.prototype._set = function(e, r) { + var n = this; + r.length || + (r = Object.keys(t.Category) + .map(function(t) { + return parseInt(t, 10); + }) + .filter(function(t) { + return !isNaN(t); + }) + .map(function(e) { + return t.Category[e]; + })), + r.map(Ft).forEach(function(t) { + return (n._enabled[t] = e); + }); + }), + (e.prototype.enable = function() { + for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e]; + this._set(!0, t); + }), + (e.prototype.disable = function() { + for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e]; + this._set(!1, t); + }), + (e.prototype.enabled = function(t) { + return !!this._enabled[Ft(t)]; + }), + (e.prototype.traceTransitionStart = function(e) { + this.enabled(t.Category.TRANSITION) && console.log(Jt(e) + ': Started -> ' + ke(e)); + }), + (e.prototype.traceTransitionIgnored = function(e) { + this.enabled(t.Category.TRANSITION) && console.log(Jt(e) + ': Ignored <> ' + ke(e)); + }), + (e.prototype.traceHookInvocation = function(e, r, n) { + if (this.enabled(t.Category.HOOK)) { + var i = c('traceData.hookType')(n) || 'internal', + o = c('traceData.context.state.name')(n) || c('traceData.context')(n) || 'unknown', + a = Ee(e.registeredHook.callback); + console.log(Jt(r) + ': Hook -> ' + i + ' context: ' + o + ', ' + Se(200, a)); + } + }), + (e.prototype.traceHookResult = function(e, r, n) { + this.enabled(t.Category.HOOK) && console.log(Jt(r) + ': <- Hook returned: ' + Se(200, ke(e))); + }), + (e.prototype.traceResolvePath = function(e, r, n) { + this.enabled(t.Category.RESOLVE) && console.log(Jt(n) + ': Resolving ' + e + ' (' + r + ')'); + }), + (e.prototype.traceResolvableResolved = function(e, r) { + this.enabled(t.Category.RESOLVE) && + console.log(Jt(r) + ': <- Resolved ' + e + ' to: ' + Se(200, ke(e.data))); + }), + (e.prototype.traceError = function(e, r) { + this.enabled(t.Category.TRANSITION) && console.log(Jt(r) + ': <- Rejected ' + ke(r) + ', reason: ' + e); + }), + (e.prototype.traceSuccess = function(e, r) { + this.enabled(t.Category.TRANSITION) && + console.log(Jt(r) + ': <- Success ' + ke(r) + ', final state: ' + e.name); + }), + (e.prototype.traceUIViewEvent = function(e, r, n) { + void 0 === n && (n = ''), + this.enabled(t.Category.UIVIEW) && console.log('ui-view: ' + be(30, e) + ' ' + Nt(r) + n); + }), + (e.prototype.traceUIViewConfigUpdated = function(e, r) { + this.enabled(t.Category.UIVIEW) && + this.traceUIViewEvent('Updating', e, " with ViewConfig from context='" + r + "'"); + }), + (e.prototype.traceUIViewFill = function(e, r) { + this.enabled(t.Category.UIVIEW) && this.traceUIViewEvent('Fill', e, ' with: ' + Se(200, r)); + }), + (e.prototype.traceViewSync = function(e) { + if (this.enabled(t.Category.VIEWCONFIG)) { + var r = 'uiview component fqn', + n = e + .map(function(t) { + var e, + n = t.uiView, + i = t.viewConfig, + o = n && n.fqn, + a = i && i.viewDecl.$context.name + ': (' + i.viewDecl.$name + ')'; + return ((e = {})[r] = o), (e['view config state (view name)'] = a), e; + }) + .sort(function(t, e) { + return (t[r] || '').localeCompare(e[r] || ''); + }); + Mt(n); + } + }), + (e.prototype.traceViewServiceEvent = function(e, r) { + this.enabled(t.Category.VIEWCONFIG) && + console.log( + 'VIEWCONFIG: ' + + e + + ' ' + + (function(t) { + var e = t.viewDecl, + r = e.$context.name || '(root)'; + return ( + '[View#' + + t.$id + + " from '" + + r + + "' state]: target ui-view: '" + + e.$uiViewName + + '@' + + e.$uiViewContextAnchor + + "'" + ); + })(r), + ); + }), + (e.prototype.traceViewServiceUIViewEvent = function(e, r) { + this.enabled(t.Category.VIEWCONFIG) && console.log('VIEWCONFIG: ' + e + ' ' + Nt(r)); + }), + e + ); + })(), + Kt = new Qt(); + ((Bt = t.TransitionHookPhase || (t.TransitionHookPhase = {}))[(Bt.CREATE = 0)] = 'CREATE'), + (Bt[(Bt.BEFORE = 1)] = 'BEFORE'), + (Bt[(Bt.RUN = 2)] = 'RUN'), + (Bt[(Bt.SUCCESS = 3)] = 'SUCCESS'), + (Bt[(Bt.ERROR = 4)] = 'ERROR'), + ((Gt = t.TransitionHookScope || (t.TransitionHookScope = {}))[(Gt.TRANSITION = 0)] = 'TRANSITION'), + (Gt[(Gt.STATE = 1)] = 'STATE'); + var Yt = (function() { + function t(t, e, r, n) { + (this._stateRegistry = t), + (this._identifier = e), + (this._identifier = e), + (this._params = G({}, r || {})), + (this._options = G({}, n || {})), + (this._definition = t.matcher.find(e, this._options.relative)); + } + return ( + (t.prototype.name = function() { + return (this._definition && this._definition.name) || this._identifier; + }), + (t.prototype.identifier = function() { + return this._identifier; + }), + (t.prototype.params = function() { + return this._params; + }), + (t.prototype.$state = function() { + return this._definition; + }), + (t.prototype.state = function() { + return this._definition && this._definition.self; + }), + (t.prototype.options = function() { + return this._options; + }), + (t.prototype.exists = function() { + return !(!this._definition || !this._definition.self); + }), + (t.prototype.valid = function() { + return !this.error(); + }), + (t.prototype.error = function() { + var t = this.options().relative; + if (!this._definition && t) { + var e = t.name ? t.name : t; + return "Could not resolve '" + this.name() + "' from state '" + e + "'"; + } + return this._definition + ? this._definition.self + ? void 0 + : "State '" + this.name() + "' has an invalid definition" + : "No such state '" + this.name() + "'"; + }), + (t.prototype.toString = function() { + return "'" + this.name() + "'" + ke(this.params()); + }), + (t.prototype.withState = function(e) { + return new t(this._stateRegistry, e, this._params, this._options); + }), + (t.prototype.withParams = function(e, r) { + void 0 === r && (r = !1); + var n = r ? e : G({}, this._params, e); + return new t(this._stateRegistry, this._identifier, n, this._options); + }), + (t.prototype.withOptions = function(e, r) { + void 0 === r && (r = !1); + var n = r ? e : G({}, this._options, e); + return new t(this._stateRegistry, this._identifier, this._params, n); + }), + (t.isDef = function(t) { + return t && t.state && (O(t.state) || O(t.state.name)); + }), + t + ); + })(), + Zt = { current: J, transition: null, traceData: {}, bind: null }, + Xt = (function() { + function e(e, r, n, i) { + var o = this; + (this.transition = e), + (this.stateContext = r), + (this.registeredHook = n), + (this.options = i), + (this.isSuperseded = function() { + return o.type.hookPhase === t.TransitionHookPhase.RUN && !o.options.transition.isActive(); + }), + (this.options = it(i, Zt)), + (this.type = n.eventType); + } + return ( + (e.chain = function(t, e) { + return t.reduce(function(t, e) { + return t.then(function() { + return e.invokeHook(); + }); + }, e || N.$q.when()); + }), + (e.invokeHooks = function(t, r) { + for (var n = 0; n < t.length; n++) { + var i = t[n].invokeHook(); + if (D(i)) { + var o = t.slice(n + 1); + return e.chain(o, i).then(r); + } + } + return r(); + }), + (e.runAllHooks = function(t) { + t.forEach(function(t) { + return t.invokeHook(); + }); + }), + (e.prototype.logError = function(t) { + this.transition.router.stateService.defaultErrorHandler()(t); + }), + (e.prototype.invokeHook = function() { + var t = this, + e = this.registeredHook; + if (!e._deregistered) { + var r = this.getNotCurrentRejection(); + if (r) return r; + var n = this.options; + Kt.traceHookInvocation(this, this.transition, n); + var i = function(r) { + return e.eventType.getErrorHandler(t)(r); + }, + o = function(r) { + return e.eventType.getResultHandler(t)(r); + }; + try { + var a = e.callback.call(n.bind, t.transition, t.stateContext); + return !this.type.synchronous && D(a) + ? a + .catch(function(t) { + return qt.normalize(t).toPromise(); + }) + .then(o, i) + : o(a); + } catch (t) { + return i(qt.normalize(t)); + } finally { + e.invokeLimit && ++e.invokeCount >= e.invokeLimit && e.deregister(); + } + } + }), + (e.prototype.handleHookResult = function(t) { + var e = this, + r = this.getNotCurrentRejection(); + return ( + r || + (D(t) + ? t.then(function(t) { + return e.handleHookResult(t); + }) + : (Kt.traceHookResult(t, this.transition, this.options), + !1 === t + ? qt.aborted('Hook aborted transition').toPromise() + : d(Yt)(t) + ? qt.redirected(t).toPromise() + : void 0)) + ); + }), + (e.prototype.getNotCurrentRejection = function() { + var t = this.transition.router; + return t._disposed + ? qt.aborted('UIRouter instance #' + t.$id + ' has been stopped (disposed)').toPromise() + : this.transition._aborted + ? qt.aborted().toPromise() + : this.isSuperseded() + ? qt.superseded(this.options.current()).toPromise() + : void 0; + }), + (e.prototype.toString = function() { + var t = this.options, + e = this.registeredHook; + return ( + (c('traceData.hookType')(t) || 'internal') + + ' context: ' + + (c('traceData.context.state.name')(t) || c('traceData.context')(t) || 'unknown') + + ', ' + + Se(200, Ce(e.callback)) + ); + }), + (e.HANDLE_RESULT = function(t) { + return function(e) { + return t.handleHookResult(e); + }; + }), + (e.LOG_REJECTED_RESULT = function(t) { + return function(e) { + D(e) && + e.catch(function(e) { + return t.logError(qt.normalize(e)); + }); + }; + }), + (e.LOG_ERROR = function(t) { + return function(e) { + return t.logError(e); + }; + }), + (e.REJECT_ERROR = function(t) { + return function(t) { + return At(t); + }; + }), + (e.THROW_ERROR = function(t) { + return function(t) { + throw t; + }; + }), + e + ); + })(); + function te(t, e) { + var r = O(e) ? [e] : e; + return !!(P(r) + ? r + : function(t) { + for (var e = r, n = 0; n < e.length; n++) { + var i = new w(e[n]); + if ((i && i.matches(t.name)) || (!i && e[n] === t.name)) return !0; + } + return !1; + })(t); + } + var ee = (function() { + function e(t, e, r, n, i, o) { + void 0 === o && (o = {}), + (this.tranSvc = t), + (this.eventType = e), + (this.callback = r), + (this.matchCriteria = n), + (this.removeHookFromRegistry = i), + (this.invokeCount = 0), + (this._deregistered = !1), + (this.priority = o.priority || 0), + (this.bind = o.bind || null), + (this.invokeLimit = o.invokeLimit); + } + return ( + (e.prototype._matchingNodes = function(t, e) { + if (!0 === e) return t; + var r = t.filter(function(t) { + return te(t.state, e); + }); + return r.length ? r : null; + }), + (e.prototype._getDefaultMatchCriteria = function() { + return ht(this.tranSvc._pluginapi._getPathTypes(), function() { + return !0; + }); + }), + (e.prototype._getMatchingNodes = function(e) { + var r = this, + n = G(this._getDefaultMatchCriteria(), this.matchCriteria); + return vt(this.tranSvc._pluginapi._getPathTypes()).reduce(function(i, o) { + var a = o.scope === t.TransitionHookScope.STATE, + u = e[o.name] || [], + s = a ? u : [kt(u)]; + return (i[o.name] = r._matchingNodes(s, n[o.name])), i; + }, {}); + }), + (e.prototype.matches = function(t) { + var e = this._getMatchingNodes(t); + return vt(e).every(z) ? e : null; + }), + (e.prototype.deregister = function() { + this.removeHookFromRegistry(this), (this._deregistered = !0); + }), + e + ); + })(); + function re(t, e, r) { + var n = ((t._registeredHooks = t._registeredHooks || {})[r.name] = []), + i = X(n); + function o(t, o, a) { + void 0 === a && (a = {}); + var u = new ee(e, r, o, t, i, a); + return n.push(u), u.deregister.bind(u); + } + return (t[r.name] = o), o; + } + var ne = (function() { + function e(t) { + this.transition = t; + } + return ( + (e.prototype.buildHooksForPhase = function(t) { + var e = this; + return this.transition.router.transitionService._pluginapi + ._getEvents(t) + .map(function(t) { + return e.buildHooks(t); + }) + .reduce(yt, []) + .filter(z); + }), + (e.prototype.buildHooks = function(e) { + var r = this.transition, + n = r.treeChanges(), + i = this.getMatchingHooks(e, n); + if (!i) return []; + var o = { transition: r, current: r.options().current }; + return i + .map(function(i) { + return i.matches(n)[e.criteriaMatchPath.name].map(function(n) { + var a = G({ bind: i.bind, traceData: { hookType: e.name, context: n } }, o), + u = e.criteriaMatchPath.scope === t.TransitionHookScope.STATE ? n.state.self : null, + s = new Xt(r, u, i, a); + return { hook: i, node: n, transitionHook: s }; + }); + }) + .reduce(yt, []) + .sort( + (function(t) { + void 0 === t && (t = !1); + return function(e, r) { + var n = t ? -1 : 1, + i = (e.node.state.path.length - r.node.state.path.length) * n; + return 0 !== i ? i : r.hook.priority - e.hook.priority; + }; + })(e.reverseSort), + ) + .map(function(t) { + return t.transitionHook; + }); + }), + (e.prototype.getMatchingHooks = function(e, r) { + var n = e.hookPhase === t.TransitionHookPhase.CREATE, + i = this.transition.router.transitionService; + return (n ? [i] : [this.transition, i]) + .map(function(t) { + return t.getHooks(e.name); + }) + .filter(bt(V, 'broken event named: ' + e.name)) + .reduce(yt, []) + .filter(function(t) { + return t.matches(r); + }); + }), + e + ); + })(); + var ie = (function() { + function t(t) { + (this.pattern = /.*/), (this.inherit = !0), G(this, t); + } + return ( + (t.prototype.is = function(t, e) { + return !0; + }), + (t.prototype.encode = function(t, e) { + return t; + }), + (t.prototype.decode = function(t, e) { + return t; + }), + (t.prototype.equals = function(t, e) { + return t == e; + }), + (t.prototype.$subPattern = function() { + var t = this.pattern.toString(); + return t.substr(1, t.length - 2); + }), + (t.prototype.toString = function() { + return '{ParamType:' + this.name + '}'; + }), + (t.prototype.$normalize = function(t) { + return this.is(t) ? t : this.decode(t); + }), + (t.prototype.$asArray = function(t, e) { + if (!t) return this; + if ('auto' === t && !e) throw new Error("'auto' array mode is for query parameters only"); + return new function(t, e) { + var r = this; + function n(t) { + return V(t) ? t : E(t) ? [t] : []; + } + function i(t, r) { + return function(i) { + if (V(i) && 0 === i.length) return i; + var o = n(i), + a = pt(o, t); + return !0 === r + ? 0 === + ft(a, function(t) { + return !t; + }).length + : (function(t) { + switch (t.length) { + case 0: + return; + case 1: + return 'auto' === e ? t[0] : t; + default: + return t; + } + })(a); + }; + } + function o(t) { + return function(e, r) { + var i = n(e), + o = n(r); + if (i.length !== o.length) return !1; + for (var a = 0; a < i.length; a++) if (!t(i[a], o[a])) return !1; + return !0; + }; + } + ['encode', 'decode', 'equals', '$normalize'].forEach(function(e) { + var n = t[e].bind(t), + a = 'equals' === e ? o : i; + r[e] = a(n); + }), + G(this, { + dynamic: t.dynamic, + name: t.name, + pattern: t.pattern, + inherit: t.inherit, + is: i(t.is.bind(t), !0), + $arrayMode: e, + }); + }(this, t); + }), + t + ); + })(); + var oe, + ae = Object.prototype.hasOwnProperty, + ue = function(t) { + return 0 === ['value', 'type', 'squash', 'array', 'dynamic'].filter(ae.bind(t || {})).length; + }; + ((oe = t.DefType || (t.DefType = {}))[(oe.PATH = 0)] = 'PATH'), + (oe[(oe.SEARCH = 1)] = 'SEARCH'), + (oe[(oe.CONFIG = 2)] = 'CONFIG'); + var se = (function() { + function e(e, r, n, i, o) { + r = (function(e, r, n, i, o) { + if (e.type && r && 'string' !== r.name) throw new Error("Param '" + i + "' has two type configurations."); + if (e.type && r && 'string' === r.name && o.type(e.type)) return o.type(e.type); + if (r) return r; + if (!e.type) { + var a = + n === t.DefType.CONFIG + ? 'any' + : n === t.DefType.PATH + ? 'path' + : n === t.DefType.SEARCH + ? 'query' + : 'string'; + return o.type(a); + } + return e.type instanceof ie ? e.type : o.type(e.type); + })( + (n = (function(t) { + function e() { + return t.value; + } + return (t = (ue(t) && { value: t }) || t), (e.__cacheable = !0), G(t, { $$fn: H(t.value) ? t.value : e }); + })(n)), + r, + i, + e, + o.paramTypes, + ); + var a, + s, + c = ((a = { array: i === t.DefType.SEARCH && 'auto' }), + (s = e.match(/\[\]$/) ? { array: !0 } : {}), + G(a, s, n).array); + r = c ? r.$asArray(c, i === t.DefType.SEARCH) : r; + var f = void 0 !== n.value || i === t.DefType.SEARCH, + l = E(n.dynamic) ? !!n.dynamic : !!r.dynamic, + h = E(n.raw) ? !!n.raw : !!r.raw, + p = (function(t, e, r) { + var n = t.squash; + if (!e || !1 === n) return !1; + if (!E(n) || null == n) return r; + if (!0 === n || O(n)) return n; + throw new Error("Invalid squash policy: '" + n + "'. Valid policies: false, true, or arbitrary string"); + })(n, f, o.defaultSquashPolicy()), + v = (function(t, e, r, n) { + var i = [{ from: '', to: r || e ? void 0 : '' }, { from: null, to: r || e ? void 0 : '' }], + o = V(t.replace) ? t.replace : []; + O(n) && o.push({ from: n, to: void 0 }); + var a = pt(o, u('from')); + return ft(i, function(t) { + return -1 === a.indexOf(t.from); + }).concat(o); + })(n, c, f, p), + d = E(n.inherit) ? !!n.inherit : !!r.inherit; + G(this, { + id: e, + type: r, + location: i, + isOptional: f, + dynamic: l, + raw: h, + squash: p, + replace: v, + inherit: d, + array: c, + config: n, + }); + } + return ( + (e.values = function(t, e) { + void 0 === e && (e = {}); + for (var r = {}, n = 0, i = t; n < i.length; n++) { + var o = i[n]; + r[o.id] = o.value(e[o.id]); + } + return r; + }), + (e.changed = function(t, e, r) { + return ( + void 0 === e && (e = {}), + void 0 === r && (r = {}), + t.filter(function(t) { + return !t.type.equals(e[t.id], r[t.id]); + }) + ); + }), + (e.equals = function(t, r, n) { + return void 0 === r && (r = {}), void 0 === n && (n = {}), 0 === e.changed(t, r, n).length; + }), + (e.validates = function(t, e) { + return ( + void 0 === e && (e = {}), + t + .map(function(t) { + return t.validates(e[t.id]); + }) + .reduce(dt, !0) + ); + }), + (e.prototype.isDefaultValue = function(t) { + return this.isOptional && this.type.equals(this.value(), t); + }), + (e.prototype.value = function(t) { + var e = this; + return ( + (t = (function(t) { + for (var r = 0, n = e.replace; r < n.length; r++) { + var i = n[r]; + if (i.from === t) return i.to; + } + return t; + })(t)), + R(t) + ? (function() { + if (e._defaultValueCache) return e._defaultValueCache.defaultValue; + if (!N.$injector) throw new Error('Injectable functions cannot be called at configuration time'); + var t = N.$injector.invoke(e.config.$$fn); + if (null !== t && void 0 !== t && !e.type.is(t)) + throw new Error( + 'Default value (' + + t + + ") for parameter '" + + e.id + + "' is not an instance of ParamType (" + + e.type.name + + ')', + ); + return e.config.$$fn.__cacheable && (e._defaultValueCache = { defaultValue: t }), t; + })() + : this.type.$normalize(t) + ); + }), + (e.prototype.isSearch = function() { + return this.location === t.DefType.SEARCH; + }), + (e.prototype.validates = function(t) { + if ((R(t) || null === t) && this.isOptional) return !0; + var e = this.type.$normalize(t); + if (!this.type.is(e)) return !1; + var r = this.type.encode(e); + return !(O(r) && !this.type.pattern.exec(r)); + }), + (e.prototype.toString = function() { + return ( + '{Param:' + this.id + ' ' + this.type + " squash: '" + this.squash + "' optional: " + this.isOptional + '}' + ); + }), + e + ); + })(), + ce = (function() { + function t(e) { + if (e instanceof t) { + var r = e; + (this.state = r.state), + (this.paramSchema = r.paramSchema.slice()), + (this.paramValues = G({}, r.paramValues)), + (this.resolvables = r.resolvables.slice()), + (this.views = r.views && r.views.slice()); + } else { + var n = e; + (this.state = n), + (this.paramSchema = n.parameters({ inherit: !1 })), + (this.paramValues = {}), + (this.resolvables = n.resolvables.map(function(t) { + return t.clone(); + })); + } + } + return ( + (t.prototype.clone = function() { + return new t(this); + }), + (t.prototype.applyRawParams = function(t) { + return ( + (this.paramValues = this.paramSchema.reduce(function(e, r) { + return Pt(e, [(n = r).id, n.value(t[n.id])]); + var n; + }, {})), + this + ); + }), + (t.prototype.parameter = function(t) { + return lt(this.paramSchema, s('id', t)); + }), + (t.prototype.equals = function(t, e) { + var r = this.diff(t, e); + return r && 0 === r.length; + }), + (t.prototype.diff = function(t, e) { + if (this.state !== t.state) return !1; + var r = e ? e(this) : this.paramSchema; + return se.changed(r, this.paramValues, t.paramValues); + }), + (t.clone = function(t) { + return t.clone(); + }), + t + ); + })(), + fe = (function() { + function t() {} + return ( + (t.makeTargetState = function(t, e) { + var r = kt(e).state; + return new Yt(t, r, e.map(u('paramValues')).reduce(ot, {}), {}); + }), + (t.buildPath = function(t) { + var e = t.params(); + return t.$state().path.map(function(t) { + return new ce(t).applyRawParams(e); + }); + }), + (t.buildToPath = function(e, r) { + var n = t.buildPath(r); + return r.options().inherit ? t.inheritParams(e, n, Object.keys(r.params())) : n; + }), + (t.applyViewConfigs = function(e, r, n) { + r + .filter(function(t) { + return Y(n, t.state); + }) + .forEach(function(n) { + var i = vt(n.state.views || {}), + o = t.subPath(r, function(t) { + return t === n; + }), + a = i.map(function(t) { + return e.createViewConfig(o, t); + }); + n.views = a.reduce(yt, []); + }); + }), + (t.inheritParams = function(t, e, r) { + void 0 === r && (r = []); + var n = t + .map(function(t) { + return t.paramSchema; + }) + .reduce(yt, []) + .filter(function(t) { + return !t.inherit; + }) + .map(u('id')); + return e.map(function(e) { + var i = G({}, e && e.paramValues), + o = ut(i, r); + i = st(i, r); + var a, + u, + c, + f = st(((a = t), (u = e.state), (c = lt(a, s('state', u))), G({}, c && c.paramValues) || {}), n), + l = G(i, f, o); + return new ce(e.state).applyRawParams(l); + }); + }), + (t.treeChanges = function(e, r, n) { + for ( + var i, o, a, u, s, c, f = Math.min(e.length, r.length), l = 0; + l < f && e[l].state !== n && ((i = e[l]), (o = r[l]), i.equals(o, t.nonDynamicParams)); + + ) + l++; + (u = (a = e).slice(0, l)), (s = a.slice(l)); + var h = u.map(function(t, e) { + var n = t.clone(); + return (n.paramValues = r[e].paramValues), n; + }); + return ( + (c = r.slice(l)), + { from: a, to: h.concat(c), retained: u, retainedWithToParams: h, exiting: s, entering: c } + ); + }), + (t.matching = function(t, e, r) { + var n = !1; + return Tt(t, e).reduce(function(t, e) { + var i = e[0], + o = e[1]; + return (n = n || !i.equals(o, r)) ? t : t.concat(i); + }, []); + }), + (t.equals = function(e, r, n) { + return e.length === r.length && t.matching(e, r, n).length === e.length; + }), + (t.subPath = function(t, e) { + var r = lt(t, e), + n = t.indexOf(r); + return -1 === n ? void 0 : t.slice(0, n + 1); + }), + (t.nonDynamicParams = function(t) { + return t.state.parameters({ inherit: !1 }).filter(function(t) { + return !t.dynamic; + }); + }), + (t.paramValues = function(t) { + return t.reduce(function(t, e) { + return G(t, e.paramValues); + }, {}); + }), + t + ); + })(), + le = { when: 'LAZY', async: 'WAIT' }, + he = (function() { + function t(e, r, n, i, o) { + if (((this.resolved = !1), (this.promise = void 0), e instanceof t)) G(this, e); + else if (P(r)) { + if (T(e)) throw new Error('new Resolvable(): token argument is required'); + if (!P(r)) throw new Error('new Resolvable(): resolveFn argument must be a function'); + (this.token = e), + (this.policy = i), + (this.resolveFn = r), + (this.deps = n || []), + (this.data = o), + (this.resolved = void 0 !== o), + (this.promise = this.resolved ? N.$q.when(this.data) : void 0); + } else if (x(e) && e.token && (e.hasOwnProperty('resolveFn') || e.hasOwnProperty('data'))) { + var a = e; + return new t(a.token, a.resolveFn, a.deps, a.policy, a.data); + } + } + return ( + (t.prototype.getPolicy = function(t) { + var e = this.policy || {}, + r = (t && t.resolvePolicy) || {}; + return { when: e.when || r.when || le.when, async: e.async || r.async || le.async }; + }), + (t.prototype.resolve = function(t, e) { + var r = this, + n = N.$q, + i = t.findNode(this), + o = i && i.state, + a = + 'RXWAIT' === this.getPolicy(o).async + ? function(t) { + var e = t.cache(1); + return e + .take(1) + .toPromise() + .then(function() { + return e; + }); + } + : z; + return (this.promise = n + .when() + .then(function() { + return n.all( + t.getDependencies(r).map(function(r) { + return r.get(t, e); + }), + ); + }) + .then(function(t) { + return r.resolveFn.apply(null, t); + }) + .then(a) + .then(function(t) { + return (r.data = t), (r.resolved = !0), (r.resolveFn = null), Kt.traceResolvableResolved(r, e), r.data; + })); + }), + (t.prototype.get = function(t, e) { + return this.promise || this.resolve(t, e); + }), + (t.prototype.toString = function() { + return 'Resolvable(token: ' + ke(this.token) + ', requires: [' + this.deps.map(ke) + '])'; + }), + (t.prototype.clone = function() { + return new t(this); + }), + (t.fromData = function(e, r) { + return new t( + e, + function() { + return r; + }, + null, + null, + r, + ); + }), + t + ); + })(), + pe = { when: { LAZY: 'LAZY', EAGER: 'EAGER' }, async: { WAIT: 'WAIT', NOWAIT: 'NOWAIT', RXWAIT: 'RXWAIT' } }, + ve = pe.when, + de = [ve.EAGER, ve.LAZY], + me = [ve.EAGER], + ye = 'Native Injector', + ge = (function() { + function t(t) { + this._path = t; + } + return ( + (t.prototype.getTokens = function() { + return this._path + .reduce(function(t, e) { + return t.concat( + e.resolvables.map(function(t) { + return t.token; + }), + ); + }, []) + .reduce(wt, []); + }), + (t.prototype.getResolvable = function(t) { + return kt( + this._path + .map(function(t) { + return t.resolvables; + }) + .reduce(yt, []) + .filter(function(e) { + return e.token === t; + }), + ); + }), + (t.prototype.getPolicy = function(t) { + var e = this.findNode(t); + return t.getPolicy(e.state); + }), + (t.prototype.subContext = function(e) { + return new t( + fe.subPath(this._path, function(t) { + return t.state === e; + }), + ); + }), + (t.prototype.addResolvables = function(t, e) { + var r = lt(this._path, s('state', e)), + n = t.map(function(t) { + return t.token; + }); + r.resolvables = r.resolvables + .filter(function(t) { + return -1 === n.indexOf(t.token); + }) + .concat(t); + }), + (t.prototype.resolvePath = function(t, e) { + var r = this; + void 0 === t && (t = 'LAZY'); + var n = (Y(de, t) ? t : 'LAZY') === pe.when.EAGER ? me : de; + Kt.traceResolvePath(this._path, t, e); + var i = function(t, e) { + return function(n) { + return Y(t, r.getPolicy(n)[e]); + }; + }, + o = this._path.reduce(function(t, o) { + var a = o.resolvables.filter(i(n, 'when')), + u = a.filter(i(['NOWAIT'], 'async')), + s = a.filter(f(i(['NOWAIT'], 'async'))), + c = r.subContext(o.state), + l = function(t) { + return t.get(c, e).then(function(e) { + return { token: t.token, value: e }; + }); + }; + return u.forEach(l), t.concat(s.map(l)); + }, []); + return N.$q.all(o); + }), + (t.prototype.injector = function() { + return this._injector || (this._injector = new _e(this)); + }), + (t.prototype.findNode = function(t) { + return lt(this._path, function(e) { + return Y(e.resolvables, t); + }); + }), + (t.prototype.getDependencies = function(t) { + var e = this, + r = this.findNode(t), + n = ( + fe.subPath(this._path, function(t) { + return t === r; + }) || this._path + ) + .reduce(function(t, e) { + return t.concat(e.resolvables); + }, []) + .filter(function(e) { + return e !== t; + }); + return t.deps.map(function(t) { + var r = n.filter(function(e) { + return e.token === t; + }); + if (r.length) return kt(r); + var i = e.injector().getNative(t); + if (R(i)) throw new Error('Could not find Dependency Injection token: ' + ke(t)); + return new he( + t, + function() { + return i; + }, + [], + i, + ); + }); + }), + t + ); + })(), + _e = (function() { + function t(t) { + (this.context = t), (this.native = this.get(ye) || N.$injector); + } + return ( + (t.prototype.get = function(t) { + var e = this.context.getResolvable(t); + if (e) { + if ('NOWAIT' === this.context.getPolicy(e).async) return e.get(this.context); + if (!e.resolved) throw new Error('Resolvable async .get() not complete:' + ke(e.token)); + return e.data; + } + return this.getNative(t); + }), + (t.prototype.getAsync = function(t) { + var e = this.context.getResolvable(t); + return e ? e.get(this.context) : N.$q.when(this.native.get(t)); + }), + (t.prototype.getNative = function(t) { + return this.native && this.native.get(t); + }), + t + ); + })(), + we = u('self'), + $e = (function() { + function e(e, r, n) { + var i = this; + if ( + ((this._deferred = N.$q.defer()), + (this.promise = this._deferred.promise), + (this._registeredHooks = {}), + (this._hookBuilder = new ne(this)), + (this.isActive = function() { + return i.router.globals.transition === i; + }), + (this.router = n), + (this._targetState = r), + !r.valid()) + ) + throw new Error(r.error()); + (this._options = G({ current: y(this) }, r.options())), (this.$id = n.transitionService._transitionCount++); + var o = fe.buildToPath(e, r); + (this._treeChanges = fe.treeChanges(e, o, this._options.reloadState)), this.createTransitionHookRegFns(); + var a = this._hookBuilder.buildHooksForPhase(t.TransitionHookPhase.CREATE); + Xt.invokeHooks(a, function() { + return null; + }), + this.applyViewConfigs(n); + } + return ( + (e.prototype.onBefore = function(t, e, r) {}), + (e.prototype.onStart = function(t, e, r) {}), + (e.prototype.onExit = function(t, e, r) {}), + (e.prototype.onRetain = function(t, e, r) {}), + (e.prototype.onEnter = function(t, e, r) {}), + (e.prototype.onFinish = function(t, e, r) {}), + (e.prototype.onSuccess = function(t, e, r) {}), + (e.prototype.onError = function(t, e, r) {}), + (e.prototype.createTransitionHookRegFns = function() { + var e = this; + this.router.transitionService._pluginapi + ._getEvents() + .filter(function(e) { + return e.hookPhase !== t.TransitionHookPhase.CREATE; + }) + .forEach(function(t) { + return re(e, e.router.transitionService, t); + }); + }), + (e.prototype.getHooks = function(t) { + return this._registeredHooks[t]; + }), + (e.prototype.applyViewConfigs = function(t) { + var e = this._treeChanges.entering.map(function(t) { + return t.state; + }); + fe.applyViewConfigs(t.transitionService.$view, this._treeChanges.to, e); + }), + (e.prototype.$from = function() { + return kt(this._treeChanges.from).state; + }), + (e.prototype.$to = function() { + return kt(this._treeChanges.to).state; + }), + (e.prototype.from = function() { + return this.$from().self; + }), + (e.prototype.to = function() { + return this.$to().self; + }), + (e.prototype.targetState = function() { + return this._targetState; + }), + (e.prototype.is = function(t) { + return t instanceof e + ? this.is({ to: t.$to().name, from: t.$from().name }) + : !((t.to && !te(this.$to(), t.to)) || (t.from && !te(this.$from(), t.from))); + }), + (e.prototype.params = function(t) { + return void 0 === t && (t = 'to'), Object.freeze(this._treeChanges[t].map(u('paramValues')).reduce(ot, {})); + }), + (e.prototype.injector = function(t, e) { + void 0 === e && (e = 'to'); + var r = this._treeChanges[e]; + return ( + t && + (r = fe.subPath(r, function(e) { + return e.state === t || e.state.name === t; + })), + new ge(r).injector() + ); + }), + (e.prototype.getResolveTokens = function(t) { + return void 0 === t && (t = 'to'), new ge(this._treeChanges[t]).getTokens(); + }), + (e.prototype.addResolvable = function(t, e) { + void 0 === e && (e = ''), (t = d(he)(t) ? t : new he(t)); + var r = 'string' == typeof e ? e : e.name, + n = this._treeChanges.to, + i = lt(n, function(t) { + return t.state.name === r; + }); + new ge(n).addResolvables([t], i.state); + }), + (e.prototype.redirectedFrom = function() { + return this._options.redirectedFrom || null; + }), + (e.prototype.originalTransition = function() { + var t = this.redirectedFrom(); + return (t && t.originalTransition()) || this; + }), + (e.prototype.options = function() { + return this._options; + }), + (e.prototype.entering = function() { + return pt(this._treeChanges.entering, u('state')).map(we); + }), + (e.prototype.exiting = function() { + return pt(this._treeChanges.exiting, u('state')) + .map(we) + .reverse(); + }), + (e.prototype.retained = function() { + return pt(this._treeChanges.retained, u('state')).map(we); + }), + (e.prototype.views = function(t, e) { + void 0 === t && (t = 'entering'); + var r = this._treeChanges[t]; + return (r = e ? r.filter(s('state', e)) : r) + .map(u('views')) + .filter(z) + .reduce(yt, []); + }), + (e.prototype.treeChanges = function(t) { + return t ? this._treeChanges[t] : this._treeChanges; + }), + (e.prototype.redirect = function(t) { + for (var e = 1, r = this; null != (r = r.redirectedFrom()); ) + if (++e > 20) throw new Error('Too many consecutive Transition redirects (20+)'); + var n = { redirectedFrom: this, source: 'redirect' }; + 'url' === this.options().source && !1 !== t.options().location && (n.location = 'replace'); + var i = G({}, this.options(), t.options(), n); + t = t.withOptions(i, !0); + var o, + a = this.router.transitionService.create(this._treeChanges.from, t), + u = this._treeChanges.entering, + s = a._treeChanges.entering; + return ( + fe + .matching(s, u, fe.nonDynamicParams) + .filter( + f( + ((o = t.options().reloadState), + function(t) { + return o && t.state.includes[o.name]; + }), + ), + ) + .forEach(function(t, e) { + t.resolvables = u[e].resolvables; + }), + a + ); + }), + (e.prototype._changedParams = function() { + var t = this._treeChanges; + if ( + !this._options.reload && + (!t.exiting.length && + !t.entering.length && + t.to.length === t.from.length && + !Tt(t.to, t.from) + .map(function(t) { + return t[0].state !== t[1].state; + }) + .reduce(mt, !1)) + ) { + var e = t.to.map(function(t) { + return t.paramSchema; + }), + r = [t.to, t.from].map(function(t) { + return t.map(function(t) { + return t.paramValues; + }); + }); + return Tt(e, r[0], r[1]) + .map(function(t) { + var e = t[0], + r = t[1], + n = t[2]; + return se.changed(e, r, n); + }) + .reduce(yt, []); + } + }), + (e.prototype.dynamic = function() { + var t = this._changedParams(); + return ( + !!t && + t + .map(function(t) { + return t.dynamic; + }) + .reduce(mt, !1) + ); + }), + (e.prototype.ignored = function() { + return !!this._ignoredReason(); + }), + (e.prototype._ignoredReason = function() { + var t = this.router.globals.transition, + e = this._options.reloadState, + r = function(t, r) { + if (t.length !== r.length) return !1; + var n = fe.matching(t, r); + return ( + t.length === + n.filter(function(t) { + return !e || !t.state.includes[e.name]; + }).length + ); + }, + n = this.treeChanges(), + i = t && t.treeChanges(); + return i && r(i.to, n.to) && r(i.exiting, n.exiting) + ? 'SameAsPending' + : 0 === n.exiting.length && 0 === n.entering.length && r(n.from, n.to) + ? 'SameAsCurrent' + : void 0; + }), + (e.prototype.run = function() { + var e = this, + r = Xt.runAllHooks, + n = function(t) { + return e._hookBuilder.buildHooksForPhase(t); + }, + i = n(t.TransitionHookPhase.BEFORE); + return ( + Xt.invokeHooks(i, function() { + var t = e.router.globals; + return ( + (t.lastStartedTransitionId = e.$id), + (t.transition = e), + t.transitionHistory.enqueue(e), + Kt.traceTransitionStart(e), + N.$q.when(void 0) + ); + }) + .then(function() { + var e = n(t.TransitionHookPhase.RUN); + return Xt.invokeHooks(e, function() { + return N.$q.when(void 0); + }); + }) + .then( + function() { + Kt.traceSuccess(e.$to(), e), + (e.success = !0), + e._deferred.resolve(e.to()), + r(n(t.TransitionHookPhase.SUCCESS)); + }, + function(i) { + Kt.traceError(i, e), + (e.success = !1), + e._deferred.reject(i), + (e._error = i), + r(n(t.TransitionHookPhase.ERROR)); + }, + ), + this.promise + ); + }), + (e.prototype.valid = function() { + return !this.error() || void 0 !== this.success; + }), + (e.prototype.abort = function() { + R(this.success) && (this._aborted = !0); + }), + (e.prototype.error = function() { + var t = this.$to(); + if (t.self.abstract) return qt.invalid("Cannot transition to abstract state '" + t.name + "'"); + var e = t.parameters(), + r = this.params(), + n = e.filter(function(t) { + return !t.validates(r[t.id]); + }); + if (n.length) { + var i = n + .map(function(t) { + return '[' + t.id + ':' + ke(r[t.id]) + ']'; + }) + .join(', '), + o = "The following parameter values are not valid for state '" + t.name + "': " + i; + return qt.invalid(o); + } + return !1 === this.success ? this._error : void 0; + }), + (e.prototype.toString = function() { + var t = this.from(), + e = this.to(), + r = function(t) { + return null !== t['#'] && void 0 !== t['#'] ? t : st(t, ['#']); + }; + return ( + 'Transition#' + + this.$id + + "( '" + + (x(t) ? t.name : t) + + "'" + + ke(r(this._treeChanges.from.map(u('paramValues')).reduce(ot, {}))) + + ' -> ' + + (this.valid() ? '' : '(X) ') + + "'" + + (x(e) ? e.name : e) + + "'" + + ke(r(this.params())) + + ' )' + ); + }), + (e.diToken = e), + e + ); + })(); + function Se(t, e) { + return e.length <= t ? e : e.substr(0, t - 3) + '...'; + } + function be(t, e) { + for (; e.length < t; ) e += ' '; + return e; + } + function Re(t) { + return t + .replace(/^([A-Z])/, function(t) { + return t.toLowerCase(); + }) + .replace(/([A-Z])/g, function(t) { + return '-' + t.toLowerCase(); + }); + } + function Ee(t) { + var e = Ce(t), + r = e.match(/^(function [^ ]+\([^)]*\))/), + n = r ? r[1] : e, + i = t.name || ''; + return i && n.match(/function \(/) ? 'function ' + i + n.substr(9) : n; + } + function Ce(t) { + var e = V(t) ? t.slice(-1)[0] : t; + return (e && e.toString()) || 'undefined'; + } + var Te = null, + Pe = function(t) { + var e = qt.isRejectionPromise; + return (Te = + Te || + _([ + [f(E), y('undefined')], + [C, y('null')], + [D, y('[Promise]')], + [ + e, + function(t) { + return t._transitionRejection.toString(); + }, + ], + [d(qt), g('toString')], + [d($e), g('toString')], + [d(he), g('toString')], + [H, Ee], + [y(!0), z], + ]))(t); + }; + function ke(t) { + var e = []; + return JSON.stringify(t, function(t, r) { + return (function(t) { + if (x(t)) { + if (-1 !== e.indexOf(t)) return '[circular ref]'; + e.push(t); + } + return Pe(t); + })(r); + }).replace(/\\"/g, '"'); + } + var Oe = function(t) { + return function(e) { + if (!e) return ['', '']; + var r = e.indexOf(t); + return -1 === r ? [e, ''] : [e.substr(0, r), e.substr(r + 1)]; + }; + }, + xe = new RegExp('^(?:[a-z]+:)?//[^/]+/'), + Ve = function(t) { + return t.replace(/\/[^/]*$/, ''); + }, + Ie = Oe('#'), + je = Oe('?'), + Ae = Oe('='), + He = function(t) { + return t ? t.replace(/^#/, '') : ''; + }; + function De(t) { + var e = new RegExp('(' + t + ')', 'g'); + return function(t) { + return t.split(e).filter(z); + }; + } + function qe(t, e) { + return O(kt(t)) && O(e) ? t.slice(0, -1).concat(kt(t) + e) : _t(t, e); + } + var Ne, + Fe = (function() { + function t() { + (this.enqueue = !0), + (this.typeQueue = []), + (this.defaultTypes = ut(t.prototype, [ + 'hash', + 'string', + 'query', + 'path', + 'int', + 'bool', + 'date', + 'json', + 'any', + ])); + this.types = K( + pt(this.defaultTypes, function(t, e) { + return new ie(G({ name: e }, t)); + }), + {}, + ); + } + return ( + (t.prototype.dispose = function() { + this.types = {}; + }), + (t.prototype.type = function(t, e, r) { + if (!E(e)) return this.types[t]; + if (this.types.hasOwnProperty(t)) throw new Error("A type named '" + t + "' has already been defined."); + return ( + (this.types[t] = new ie(G({ name: t }, e))), + r && (this.typeQueue.push({ name: t, def: r }), this.enqueue || this._flushTypeQueue()), + this + ); + }), + (t.prototype._flushTypeQueue = function() { + for (; this.typeQueue.length; ) { + var t = this.typeQueue.shift(); + if (t.pattern) throw new Error("You cannot override a type's .pattern at runtime."); + G(this.types[t.name], N.$injector.invoke(t.def)); + } + }), + t + ); + })(); + (Ne = function(t) { + var e = function(t) { + return null != t ? t.toString() : t; + }, + r = { + encode: e, + decode: e, + is: d(String), + pattern: /.*/, + equals: function(t, e) { + return t == e; + }, + }; + return G({}, r, t); + }), + G(Fe.prototype, { + string: Ne({}), + path: Ne({ pattern: /[^/]*/ }), + query: Ne({}), + hash: Ne({ inherit: !1 }), + int: Ne({ + decode: function(t) { + return parseInt(t, 10); + }, + is: function(t) { + return !T(t) && this.decode(t.toString()) === t; + }, + pattern: /-?\d+/, + }), + bool: Ne({ + encode: function(t) { + return t ? 1 : 0; + }, + decode: function(t) { + return 0 !== parseInt(t, 10); + }, + is: d(Boolean), + pattern: /0|1/, + }), + date: Ne({ + encode: function(t) { + return this.is(t) + ? [t.getFullYear(), ('0' + (t.getMonth() + 1)).slice(-2), ('0' + t.getDate()).slice(-2)].join('-') + : void 0; + }, + decode: function(t) { + if (this.is(t)) return t; + var e = this.capture.exec(t); + return e ? new Date(e[1], e[2] - 1, e[3]) : void 0; + }, + is: function(t) { + return t instanceof Date && !isNaN(t.valueOf()); + }, + equals: function(t, e) { + return ['getFullYear', 'getMonth', 'getDate'].reduce(function(r, n) { + return r && t[n]() === e[n](); + }, !0); + }, + pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/, + capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/, + }), + json: Ne({ encode: M, decode: L, is: d(Object), equals: W, pattern: /[^/]*/ }), + any: Ne({ + encode: z, + decode: z, + is: function() { + return !0; + }, + equals: W, + }), + }); + var Ue = (function() { + function t(t) { + void 0 === t && (t = {}), G(this, t); + } + return ( + (t.prototype.$inherit = function(t, e, r) { + var n, + i = at(e, r), + o = {}, + a = []; + for (var u in i) + if (i[u] && i[u].params && (n = Object.keys(i[u].params)).length) + for (var s in n) a.indexOf(n[s]) >= 0 || (a.push(n[s]), (o[n[s]] = this[n[s]])); + return G({}, o, t); + }), + t + ); + })(); + function Le(t) { + return t.name; + } + function Me(t) { + return ( + (t.self.$$state = function() { + return t; + }), + t.self + ); + } + function Be(t) { + return t.parent && t.parent.data && (t.data = t.self.data = K(t.parent.data, t.data)), t.data; + } + var Ge = function(t, e) { + return function(r) { + var n = r; + n && n.url && n.name && n.name.match(/\.\*\*$/) && (n.url += '{remainder:any}'); + var i = (function(t) { + if (!O(t)) return !1; + var e = '^' === t.charAt(0); + return { val: e ? t.substring(1) : t, root: e }; + })(n.url), + o = r.parent, + a = i + ? t.compile(i.val, { + params: r.params || {}, + paramMap: function(t, e) { + return !1 === n.reloadOnSearch && e && (t = G(t || {}, { dynamic: !0 })), t; + }, + }) + : n.url; + if (!a) return null; + if (!t.isMatcher(a)) throw new Error("Invalid url '" + a + "' in state '" + r + "'"); + return i && i.root ? a : ((o && o.navigable) || e()).url.append(a); + }; + }, + We = function(t) { + return function(e) { + return !t(e) && e.url ? e : e.parent ? e.parent.navigable : null; + }; + }, + ze = function(t) { + return function(e) { + var r = (e.url && e.url.parameters({ inherit: !1 })) || [], + n = vt( + ht(st(e.params || {}, r.map(u('id'))), function(e, r) { + return t.fromConfig(r, null, e); + }), + ); + return r + .concat(n) + .map(function(t) { + return [t.id, t]; + }) + .reduce(Pt, {}); + }; + }; + function Je(t) { + return t.parent ? t.parent.path.concat(t) : [t]; + } + function Qe(t) { + var e = t.parent ? G({}, t.parent.includes) : {}; + return (e[t.name] = !0), e; + } + function Ke(t) { + var e, + r, + n = function(t) { + return t.provide || t.token; + }, + i = _([ + [ + u('resolveFn'), + function(t) { + return new he(n(t), t.resolveFn, t.deps, t.policy); + }, + ], + [ + u('useFactory'), + function(t) { + return new he(n(t), t.useFactory, t.deps || t.dependencies, t.policy); + }, + ], + [ + u('useClass'), + function(t) { + return new he( + n(t), + function() { + return new t.useClass(); + }, + [], + t.policy, + ); + }, + ], + [ + u('useValue'), + function(t) { + return new he( + n(t), + function() { + return t.useValue; + }, + [], + t.policy, + t.useValue, + ); + }, + ], + [ + u('useExisting'), + function(t) { + return new he(n(t), z, [t.useExisting], t.policy); + }, + ], + ]), + o = _([ + [ + a(u('val'), O), + function(t) { + return new he(t.token, z, [t.val], t.policy); + }, + ], + [ + a(u('val'), V), + function(t) { + return new he(t.token, kt(t.val), t.val.slice(0, -1), t.policy); + }, + ], + [ + a(u('val'), P), + function(t) { + return new he( + t.token, + t.val, + ((e = t.val), (r = N.$injector), e.$inject || (r && r.annotate(e, r.strictDi)) || 'deferred'), + t.policy, + ); + var e, r; + }, + ], + ]), + s = _([ + [ + d(he), + function(t) { + return t; + }, + ], + [ + function(t) { + return !(!t.token || !t.resolveFn); + }, + i, + ], + [ + function(t) { + return !((!t.provide && !t.token) || !(t.useValue || t.useFactory || t.useExisting || t.useClass)); + }, + i, + ], + [ + function(t) { + return !!(t && t.val && (O(t.val) || V(t.val) || P(t.val))); + }, + o, + ], + [ + y(!0), + function(t) { + throw new Error('Invalid resolve value: ' + ke(t)); + }, + ], + ]), + c = t.resolve; + return (V(c) + ? c + : ((e = c), + (r = t.resolvePolicy || {}), + Object.keys(e || {}).map(function(t) { + return { token: t, val: e[t], deps: void 0, policy: r[t] }; + })) + ).map(s); + } + var Ye = (function() { + function t(t, e) { + this.matcher = t; + var r = this, + n = function() { + return t.find(''); + }, + i = function(t) { + return '' === t.name; + }; + this.builders = { + name: [Le], + self: [Me], + parent: [ + function(e) { + return i(e) ? null : t.find(r.parentName(e)) || n(); + }, + ], + data: [Be], + url: [Ge(e, n)], + navigable: [We(i)], + params: [ze(e.paramFactory)], + views: [], + path: [Je], + includes: [Qe], + resolvables: [Ke], + }; + } + return ( + (t.prototype.builder = function(t, e) { + var r = this.builders, + n = r[t] || []; + return O(t) && !E(e) + ? n.length > 1 + ? n + : n[0] + : O(t) && P(e) + ? ((r[t] = n), + r[t].push(e), + function() { + return r[t].splice(r[t].indexOf(e, 1)) && null; + }) + : void 0; + }), + (t.prototype.build = function(t) { + var e = this.matcher, + r = this.builders, + n = this.parentName(t); + if (n && !e.find(n, void 0, !1)) return null; + for (var i in r) + if (r.hasOwnProperty(i)) { + var o = r[i].reduce(function(t, e) { + return function(r) { + return e(r, t); + }; + }, J); + t[i] = o(t); + } + return t; + }), + (t.prototype.parentName = function(t) { + var e = t.name || '', + r = e.split('.'); + if (('**' === r.pop() && r.pop(), r.length)) { + if (t.parent) + throw new Error( + "States that specify the 'parent:' property should not have a '.' in their name (" + e + ')', + ); + return r.join('.'); + } + return t.parent ? (O(t.parent) ? t.parent : t.parent.name) : ''; + }), + (t.prototype.name = function(t) { + var e = t.name; + if (-1 !== e.indexOf('.') || !t.parent) return e; + var r = O(t.parent) ? t.parent : t.parent.name; + return r ? r + '.' + e : e; + }), + t + ); + })(), + Ze = (function() { + function t(t) { + this._states = t; + } + return ( + (t.prototype.isRelative = function(t) { + return 0 === (t = t || '').indexOf('.') || 0 === t.indexOf('^'); + }), + (t.prototype.find = function(t, e, r) { + if ((void 0 === r && (r = !0), t || '' === t)) { + var n = O(t), + i = n ? t : t.name; + this.isRelative(i) && (i = this.resolvePath(i, e)); + var o = this._states[i]; + if (o && (n || !(n || (o !== t && o.self !== t)))) return o; + if (n && r) { + var a = vt(this._states).filter(function(t) { + return t.__stateObjectCache.nameGlob && t.__stateObjectCache.nameGlob.matches(i); + }); + return ( + a.length > 1 && + console.log( + 'stateMatcher.find: Found multiple matches for ' + i + ' using glob: ', + a.map(function(t) { + return t.name; + }), + ), + a[0] + ); + } + } + }), + (t.prototype.resolvePath = function(t, e) { + if (!e) throw new Error("No reference point given for path '" + t + "'"); + for (var r = this.find(e), n = t.split('.'), i = n.length, o = 0, a = r; o < i; o++) + if ('' !== n[o] || 0 !== o) { + if ('^' !== n[o]) break; + if (!a.parent) throw new Error("Path '" + t + "' not valid for state '" + r.name + "'"); + a = a.parent; + } else a = r; + var u = n.slice(o).join('.'); + return a.name + (a.name && u ? '.' : '') + u; + }), + t + ); + })(), + Xe = (function() { + function t(t, e, r, n, i) { + (this.$registry = t), + (this.$urlRouter = e), + (this.states = r), + (this.builder = n), + (this.listeners = i), + (this.queue = []), + (this.matcher = t.matcher); + } + return ( + (t.prototype.dispose = function() { + this.queue = []; + }), + (t.prototype.register = function(t) { + var e = this.queue, + r = $.create(t), + n = r.name; + if (!O(n)) throw new Error('State must have a valid name'); + if (this.states.hasOwnProperty(n) || Y(e.map(u('name')), n)) + throw new Error("State '" + n + "' is already defined"); + return e.push(r), this.flush(), r; + }), + (t.prototype.flush = function() { + for ( + var t = this, + e = this.queue, + r = this.states, + n = this.builder, + i = [], + o = [], + a = {}, + u = function(e) { + return t.states.hasOwnProperty(e) && t.states[e]; + }, + s = function() { + i.length && + t.listeners.forEach(function(t) { + return t( + 'registered', + i.map(function(t) { + return t.self; + }), + ); + }); + }; + e.length > 0; + + ) { + var c = e.shift(), + f = c.name, + l = n.build(c), + h = o.indexOf(c); + if (l) { + var p = u(f); + if (p && p.name === f) throw new Error("State '" + f + "' is already defined"); + var v = u(f + '.**'); + v && this.$registry.deregister(v), (r[f] = c), this.attachRoute(c), h >= 0 && o.splice(h, 1), i.push(c); + } else { + var d = a[f]; + if (((a[f] = e.length), h >= 0 && d === e.length)) return e.push(c), s(), r; + h < 0 && o.push(c), e.push(c); + } + } + return s(), r; + }), + (t.prototype.attachRoute = function(t) { + !t.abstract && t.url && this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(t)); + }), + t + ); + })(), + tr = (function() { + function t(t) { + (this._router = t), + (this.states = {}), + (this.listeners = []), + (this.matcher = new Ze(this.states)), + (this.builder = new Ye(this.matcher, t.urlMatcherFactory)), + (this.stateQueue = new Xe(this, t.urlRouter, this.states, this.builder, this.listeners)), + this._registerRoot(); + } + return ( + (t.prototype._registerRoot = function() { + (this._root = this.stateQueue.register({ + name: '', + url: '^', + views: null, + params: { '#': { value: null, type: 'hash', dynamic: !0 } }, + abstract: !0, + })).navigable = null; + }), + (t.prototype.dispose = function() { + var t = this; + this.stateQueue.dispose(), + (this.listeners = []), + this.get().forEach(function(e) { + return t.get(e) && t.deregister(e); + }); + }), + (t.prototype.onStatesChanged = function(t) { + return ( + this.listeners.push(t), + function() { + X(this.listeners)(t); + }.bind(this) + ); + }), + (t.prototype.root = function() { + return this._root; + }), + (t.prototype.register = function(t) { + return this.stateQueue.register(t); + }), + (t.prototype._deregisterTree = function(t) { + var e = this, + r = this.get().map(function(t) { + return t.$$state(); + }), + n = function(t) { + var e = r.filter(function(e) { + return -1 !== t.indexOf(e.parent); + }); + return 0 === e.length ? e : e.concat(n(e)); + }, + i = n([t]), + o = [t].concat(i).reverse(); + return ( + o.forEach(function(t) { + var r = e._router.urlRouter; + r + .rules() + .filter(s('state', t)) + .forEach(r.removeRule.bind(r)), + delete e.states[t.name]; + }), + o + ); + }), + (t.prototype.deregister = function(t) { + var e = this.get(t); + if (!e) throw new Error("Can't deregister state; not found: " + t); + var r = this._deregisterTree(e.$$state()); + return ( + this.listeners.forEach(function(t) { + return t( + 'deregistered', + r.map(function(t) { + return t.self; + }), + ); + }), + r + ); + }), + (t.prototype.get = function(t, e) { + var r = this; + if (0 === arguments.length) + return Object.keys(this.states).map(function(t) { + return r.states[t].self; + }); + var n = this.matcher.find(t, e); + return (n && n.self) || null; + }), + (t.prototype.decorator = function(t, e) { + return this.builder.builder(t, e); + }), + t + ); + })(); + function er(t, e) { + var r = ['', ''], + n = t.replace(/[\\\[\]\^$*+?.()|{}]/g, '\\$&'); + if (!e) return n; + switch (e.squash) { + case !1: + r = ['(', ')' + (e.isOptional ? '?' : '')]; + break; + case !0: + (n = n.replace(/\/$/, '')), (r = ['(?:/(', ')|/)?']); + break; + default: + r = ['(' + e.squash + '|', ')?']; + } + return n + r[0] + e.type.pattern.source + r[1]; + } + var rr = De('/'), + nr = (function() { + function e(t, r, n, i) { + var o = this; + (this.config = i), + (this._cache = { path: [this] }), + (this._children = []), + (this._params = []), + (this._segments = []), + (this._compiled = []), + (this.pattern = t), + (this.config = it(this.config, { params: {}, strict: !0, caseInsensitive: !1, paramMap: z })); + for ( + var a, + u, + c, + f = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, + l = /([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, + h = [], + p = 0, + v = function(r) { + if (!e.nameValidator.test(r)) + throw new Error("Invalid parameter name '" + r + "' in pattern '" + t + "'"); + if (lt(o._params, s('id', r))) + throw new Error("Duplicate parameter name '" + r + "' in pattern '" + t + "'"); + }, + d = function(e, n) { + var i, + a = e[2] || e[3], + u = n ? e[4] : e[4] || ('*' === e[1] ? '[\\s\\S]*' : null); + return { + id: a, + regexp: u, + cfg: o.config.params[a], + segment: t.substring(p, e.index), + type: u + ? r.type(u) || + ((i = u), + K(r.type(n ? 'query' : 'path'), { + pattern: new RegExp(i, o.config.caseInsensitive ? 'i' : void 0), + })) + : null, + }; + }; + (a = f.exec(t)) && !((u = d(a, !1)).segment.indexOf('?') >= 0); + + ) + v(u.id), + this._params.push(n.fromPath(u.id, u.type, this.config.paramMap(u.cfg, !1))), + this._segments.push(u.segment), + h.push([u.segment, kt(this._params)]), + (p = f.lastIndex); + var m = (c = t.substring(p)).indexOf('?'); + if (m >= 0) { + var y = c.substring(m); + if (((c = c.substring(0, m)), y.length > 0)) + for (p = 0; (a = l.exec(y)); ) + v((u = d(a, !0)).id), + this._params.push(n.fromSearch(u.id, u.type, this.config.paramMap(u.cfg, !0))), + (p = f.lastIndex); + } + this._segments.push(c), + (this._compiled = h + .map(function(t) { + return er.apply(null, t); + }) + .concat(er(c))); + } + return ( + (e.encodeDashes = function(t) { + return encodeURIComponent(t).replace(/-/g, function(t) { + return ( + '%5C%' + + t + .charCodeAt(0) + .toString(16) + .toUpperCase() + ); + }); + }), + (e.pathSegmentsAndParams = function(e) { + return Tt( + e._segments, + e._params + .filter(function(e) { + return e.location === t.DefType.PATH; + }) + .concat(void 0), + ) + .reduce(yt, []) + .filter(function(t) { + return '' !== t && E(t); + }); + }), + (e.queryParams = function(e) { + return e._params.filter(function(e) { + return e.location === t.DefType.SEARCH; + }); + }), + (e.compare = function(t, r) { + var n = function(t) { + return (t._cache.weights = + t._cache.weights || + (function(t) { + return (t._cache.segments = + t._cache.segments || + t._cache.path + .map(e.pathSegmentsAndParams) + .reduce(yt, []) + .reduce(qe, []) + .map(function(t) { + return O(t) ? rr(t) : t; + }) + .reduce(yt, [])); + })(t).map(function(t) { + return '/' === t ? 1 : O(t) ? 2 : t instanceof se ? 3 : void 0; + })); + }, + i = n(t), + o = n(r); + !(function(t, e, r) { + for (var n = Math.max(t.length, e.length); t.length < n; ) t.push(r); + for (; e.length < n; ) e.push(r); + })(i, o, 0); + var a, + u, + s = Tt(i, o); + for (u = 0; u < s.length; u++) if (0 !== (a = s[u][0] - s[u][1])) return a; + return 0; + }), + (e.prototype.append = function(t) { + return ( + this._children.push(t), (t._cache = { path: this._cache.path.concat(t), parent: this, pattern: null }), t + ); + }), + (e.prototype.isRoot = function() { + return this._cache.path[0] === this; + }), + (e.prototype.toString = function() { + return this.pattern; + }), + (e.prototype.exec = function(t, e, r, n) { + var i = this; + void 0 === e && (e = {}), void 0 === n && (n = {}); + var o, + a, + s, + c = ((o = this._cache), + (a = 'pattern'), + (s = function() { + return new RegExp( + ['^', $t(i._cache.path.map(u('_compiled'))).join(''), !1 === i.config.strict ? '/?' : '', '$'].join(''), + i.config.caseInsensitive ? 'i' : void 0, + ); + }), + (o[a] = o[a] || s())).exec(t); + if (!c) return null; + var f, + l = this.parameters(), + h = l.filter(function(t) { + return !t.isSearch(); + }), + p = l.filter(function(t) { + return t.isSearch(); + }), + v = this._cache.path + .map(function(t) { + return t._segments.length - 1; + }) + .reduce(function(t, e) { + return t + e; + }), + d = {}; + if (v !== c.length - 1) throw new Error("Unbalanced capture group in route '" + this.pattern + "'"); + for (var m = 0; m < v; m++) { + for (var y = h[m], g = c[m + 1], _ = 0; _ < y.replace.length; _++) + y.replace[_].from === g && (g = y.replace[_].to); + g && + !0 === y.array && + (void 0, + (g = pt( + pt( + (f = function(t) { + return t + .split('') + .reverse() + .join(''); + })(g).split(/-(?!\\)/), + f, + ), + function(t) { + return t.replace(/\\-/g, '-'); + }, + ).reverse())), + E(g) && (g = y.type.decode(g)), + (d[y.id] = y.value(g)); + } + return ( + p.forEach(function(t) { + for (var r = e[t.id], n = 0; n < t.replace.length; n++) t.replace[n].from === r && (r = t.replace[n].to); + E(r) && (r = t.type.decode(r)), (d[t.id] = t.value(r)); + }), + r && (d['#'] = r), + d + ); + }), + (e.prototype.parameters = function(t) { + return ( + void 0 === t && (t = {}), + !1 === t.inherit + ? this._params + : $t( + this._cache.path.map(function(t) { + return t._params; + }), + ) + ); + }), + (e.prototype.parameter = function(t, e) { + var r = this; + void 0 === e && (e = {}); + var n = this._cache.parent; + return ( + (function() { + for (var e = 0, n = r._params; e < n.length; e++) { + var i = n[e]; + if (i.id === t) return i; + } + })() || + (!1 !== e.inherit && n && n.parameter(t, e)) || + null + ); + }), + (e.prototype.validates = function(t) { + return ( + (t = t || {}), + this.parameters() + .filter(function(e) { + return t.hasOwnProperty(e.id); + }) + .map(function(e) { + return (r = e), (n = t[e.id]), !r || r.validates(n); + var r, n; + }) + .reduce(dt, !0) + ); + }), + (e.prototype.format = function(t) { + void 0 === t && (t = {}); + var r = this._cache.path, + n = r + .map(e.pathSegmentsAndParams) + .reduce(yt, []) + .map(function(t) { + return O(t) ? t : o(t); + }), + i = r + .map(e.queryParams) + .reduce(yt, []) + .map(o); + if ( + n.concat(i).filter(function(t) { + return !1 === t.isValid; + }).length + ) + return null; + function o(e) { + var r = e.value(t[e.id]), + n = e.validates(r), + i = e.isDefaultValue(r); + return { + param: e, + value: r, + isValid: n, + isDefaultValue: i, + squash: !!i && e.squash, + encoded: e.type.encode(r), + }; + } + var a = n.reduce(function(t, r) { + if (O(r)) return t + r; + var n = r.squash, + i = r.encoded, + o = r.param; + return !0 === n + ? t.match(/\/$/) + ? t.slice(0, -1) + : t + : O(n) + ? t + n + : !1 !== n + ? t + : null == i + ? t + : V(i) + ? t + pt(i, e.encodeDashes).join('-') + : o.raw + ? t + i + : t + encodeURIComponent(i); + }, ''), + u = i + .map(function(t) { + var e = t.param, + r = t.squash, + n = t.encoded, + i = t.isDefaultValue; + if (!(null == n || (i && !1 !== r)) && (V(n) || (n = [n]), 0 !== n.length)) + return ( + e.raw || (n = pt(n, encodeURIComponent)), + n.map(function(t) { + return e.id + '=' + t; + }) + ); + }) + .filter(z) + .reduce(yt, []) + .join('&'); + return a + (u ? '?' + u : '') + (t['#'] ? '#' + t['#'] : ''); + }), + (e.nameValidator = /^\w+([-.]+\w+)*(?:\[\])?$/), + e + ); + })(), + ir = (function() { + function e() { + var e = this; + (this.paramTypes = new Fe()), + (this._isCaseInsensitive = !1), + (this._isStrictMode = !0), + (this._defaultSquashPolicy = !1), + (this.paramFactory = { + fromConfig: function(r, n, i) { + return new se(r, n, i, t.DefType.CONFIG, e); + }, + fromPath: function(r, n, i) { + return new se(r, n, i, t.DefType.PATH, e); + }, + fromSearch: function(r, n, i) { + return new se(r, n, i, t.DefType.SEARCH, e); + }, + }), + (this._getConfig = function(t) { + return G({ strict: e._isStrictMode, caseInsensitive: e._isCaseInsensitive }, t); + }), + G(this, { UrlMatcher: nr, Param: se }); + } + return ( + (e.prototype.caseInsensitive = function(t) { + return (this._isCaseInsensitive = E(t) ? t : this._isCaseInsensitive); + }), + (e.prototype.strictMode = function(t) { + return (this._isStrictMode = E(t) ? t : this._isStrictMode); + }), + (e.prototype.defaultSquashPolicy = function(t) { + if (E(t) && !0 !== t && !1 !== t && !O(t)) + throw new Error('Invalid squash policy: ' + t + '. Valid policies: false, true, arbitrary-string'); + return (this._defaultSquashPolicy = E(t) ? t : this._defaultSquashPolicy); + }), + (e.prototype.compile = function(t, e) { + return new nr(t, this.paramTypes, this.paramFactory, this._getConfig(e)); + }), + (e.prototype.isMatcher = function(t) { + if (!x(t)) return !1; + var e = !0; + return ( + B(nr.prototype, function(r, n) { + P(r) && (e = e && E(t[n]) && P(t[n])); + }), + e + ); + }), + (e.prototype.type = function(t, e, r) { + var n = this.paramTypes.type(t, e, r); + return E(e) ? this : n; + }), + (e.prototype.$get = function() { + return (this.paramTypes.enqueue = !1), this.paramTypes._flushTypeQueue(), this; + }), + (e.prototype.dispose = function() { + this.paramTypes.dispose(); + }), + e + ); + })(), + or = (function() { + function t(t) { + this.router = t; + } + return ( + (t.prototype.compile = function(t) { + return this.router.urlMatcherFactory.compile(t); + }), + (t.prototype.create = function(t, e) { + var r = this, + n = _([ + [ + O, + function(t) { + return n(r.compile(t)); + }, + ], + [ + d(nr), + function(t) { + return r.fromUrlMatcher(t, e); + }, + ], + [ + A, + function(t) { + return r.fromState(t, r.router); + }, + ], + [ + d(RegExp), + function(t) { + return r.fromRegExp(t, e); + }, + ], + [ + P, + function(t) { + return new ar(t, e); + }, + ], + ]), + i = n(t); + if (!i) throw new Error("invalid 'what' in when()"); + return i; + }), + (t.prototype.fromUrlMatcher = function(t, e) { + var r = e; + O(e) && (e = this.router.urlMatcherFactory.compile(e)), + d(nr)(e) && + (r = function(t) { + return e.format(t); + }); + var n = { + urlMatcher: t, + matchPriority: function(e) { + var r = t.parameters().filter(function(t) { + return t.isOptional; + }); + return r.length + ? r.filter(function(t) { + return e[t.id]; + }).length / r.length + : 1e-6; + }, + type: 'URLMATCHER', + }; + return G( + new ar(function(e) { + var r = t.exec(e.path, e.search, e.hash); + return t.validates(r) && r; + }, r), + n, + ); + }), + (t.prototype.fromState = function(t, e) { + var r = { state: t, type: 'STATE' }; + return G( + this.fromUrlMatcher(t.url, function(r) { + var n = e.stateService, + i = e.globals; + n.href(t, r) !== n.href(i.current, i.params) && n.transitionTo(t, r, { inherit: !0, source: 'url' }); + }), + r, + ); + }), + (t.prototype.fromRegExp = function(t, e) { + if (t.global || t.sticky) throw new Error('Rule RegExp must not be global or sticky'); + var r = O(e) + ? function(t) { + return e.replace(/\$(\$|\d{1,2})/, function(e, r) { + return t['$' === r ? 0 : Number(r)]; + }); + } + : e, + n = { regexp: t, type: 'REGEXP' }; + return G( + new ar(function(e) { + return t.exec(e.path); + }, r), + n, + ); + }), + (t.isUrlRule = function(t) { + return ( + t && + ['type', 'match', 'handler'].every(function(e) { + return E(t[e]); + }) + ); + }), + t + ); + })(), + ar = (function() { + return function(t, e) { + var r = this; + (this.match = t), + (this.type = 'RAW'), + (this.matchPriority = function(t) { + return 0 - r.$id; + }), + (this.handler = e || z); + }; + })(); + var ur; + ur = function(t, e) { + var r = (function(t, e) { + return (e.priority || 0) - (t.priority || 0); + })(t, e); + return 0 !== r + ? r + : 0 !== + (r = (function(t, e) { + var r = { STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1 }; + return (r[t.type] || 0) - (r[e.type] || 0); + })(t, e)) + ? r + : 0 !== + (r = (function(t, e) { + return t.urlMatcher && e.urlMatcher ? nr.compare(t.urlMatcher, e.urlMatcher) : 0; + })(t, e)) + ? r + : (function(t, e) { + var r = { STATE: !0, URLMATCHER: !0 }; + return r[t.type] && r[e.type] ? 0 : (t.$id || 0) - (e.$id || 0); + })(t, e); + }; + var sr = (function() { + function t(e) { + (this._sortFn = ur), + (this._rules = []), + (this.interceptDeferred = !1), + (this._id = 0), + (this._sorted = !1), + (this._router = e), + (this.urlRuleFactory = new or(e)), + Q(y(t.prototype), this, y(this)); + } + return ( + (t.prototype.dispose = function() { + this.listen(!1), (this._rules = []), delete this._otherwiseFn; + }), + (t.prototype.sort = function(t) { + (this._rules = this.stableSort(this._rules, (this._sortFn = t || this._sortFn))), (this._sorted = !0); + }), + (t.prototype.ensureSorted = function() { + this._sorted || this.sort(); + }), + (t.prototype.stableSort = function(t, e) { + var r = t.map(function(t, e) { + return { elem: t, idx: e }; + }); + return ( + r.sort(function(t, r) { + var n = e(t.elem, r.elem); + return 0 === n ? t.idx - r.idx : n; + }), + r.map(function(t) { + return t.elem; + }) + ); + }), + (t.prototype.match = function(t) { + var e = this; + this.ensureSorted(), (t = G({ path: '', search: {}, hash: '' }, t)); + var r = this.rules(); + this._otherwiseFn && r.push(this._otherwiseFn); + for (var n, i, o, a = 0; a < r.length && (!n || 0 === this._sortFn(r[a], n.rule)); a++) { + var u = ((i = r[a]), + void 0, + (o = i.match(t, e._router)) && { match: o, rule: i, weight: i.matchPriority(o) }); + n = !n || (u && u.weight > n.weight) ? u : n; + } + return n; + }), + (t.prototype.sync = function(t) { + if (!t || !t.defaultPrevented) { + var e = this._router, + r = e.urlService, + n = e.stateService, + i = { path: r.path(), search: r.search(), hash: r.hash() }, + o = this.match(i); + _([ + [ + O, + function(t) { + return r.url(t, !0); + }, + ], + [ + Yt.isDef, + function(t) { + return n.go(t.state, t.params, t.options); + }, + ], + [ + d(Yt), + function(t) { + return n.go(t.state(), t.params(), t.options()); + }, + ], + ])(o && o.rule.handler(o.match, i, e)); + } + }), + (t.prototype.listen = function(t) { + var e = this; + if (!1 !== t) + return (this._stopFn = + this._stopFn || + this._router.urlService.onChange(function(t) { + return e.sync(t); + })); + this._stopFn && this._stopFn(), delete this._stopFn; + }), + (t.prototype.update = function(t) { + var e = this._router.locationService; + t ? (this.location = e.url()) : e.url() !== this.location && e.url(this.location, !0); + }), + (t.prototype.push = function(t, e, r) { + var n = r && !!r.replace; + this._router.urlService.url(t.format(e || {}), n); + }), + (t.prototype.href = function(t, e, r) { + var n = t.format(e); + if (null == n) return null; + r = r || { absolute: !1 }; + var i = this._router.urlService.config, + o = i.html5Mode(); + if ( + (o || null === n || (n = '#' + i.hashPrefix() + n), + (n = (function(t, e, r, n) { + return '/' === n ? t : e ? Ve(n) + t : r ? n.slice(1) + t : t; + })(n, o, r.absolute, i.baseHref())), + !r.absolute || !n) + ) + return n; + var a = !o && n ? '/' : '', + u = i.port(), + s = 80 === u || 443 === u ? '' : ':' + u; + return [i.protocol(), '://', i.host(), s, a, n].join(''); + }), + (t.prototype.rule = function(t) { + var e = this; + if (!or.isUrlRule(t)) throw new Error('invalid rule'); + return ( + (t.$id = this._id++), + (t.priority = t.priority || 0), + this._rules.push(t), + (this._sorted = !1), + function() { + return e.removeRule(t); + } + ); + }), + (t.prototype.removeRule = function(t) { + X(this._rules, t); + }), + (t.prototype.rules = function() { + return this.ensureSorted(), this._rules.slice(); + }), + (t.prototype.otherwise = function(t) { + var e = cr(t); + (this._otherwiseFn = this.urlRuleFactory.create(y(!0), e)), (this._sorted = !1); + }), + (t.prototype.initial = function(t) { + var e = cr(t); + this.rule( + this.urlRuleFactory.create(function(t, e) { + return 0 === e.globals.transitionHistory.size() && !!/^\/?$/.exec(t.path); + }, e), + ); + }), + (t.prototype.when = function(t, e, r) { + var n = this.urlRuleFactory.create(t, e); + return E(r && r.priority) && (n.priority = r.priority), this.rule(n), n; + }), + (t.prototype.deferIntercept = function(t) { + void 0 === t && (t = !0), (this.interceptDeferred = t); + }), + t + ); + })(); + function cr(t) { + if (!(P(t) || O(t) || d(Yt)(t) || Yt.isDef(t))) + throw new Error("'handler' must be a string, function, TargetState, or have a state: 'newtarget' property"); + return P(t) ? t : y(t); + } + var fr = (function() { + function t() { + var t = this; + (this._uiViews = []), + (this._viewConfigs = []), + (this._viewConfigFactories = {}), + (this._listeners = []), + (this._pluginapi = { + _rootViewContext: this._rootViewContext.bind(this), + _viewConfigFactory: this._viewConfigFactory.bind(this), + _registeredUIViews: function() { + return t._uiViews; + }, + _activeViewConfigs: function() { + return t._viewConfigs; + }, + _onSync: function(e) { + return ( + t._listeners.push(e), + function() { + return X(t._listeners, e); + } + ); + }, + }); + } + return ( + (t.normalizeUIViewTarget = function(t, e) { + void 0 === e && (e = ''); + var r = e.split('@'), + n = r[0] || '$default', + i = O(r[1]) ? r[1] : '^', + o = /^(\^(?:\.\^)*)\.(.*$)/.exec(n); + o && ((i = o[1]), (n = o[2])), '!' === n.charAt(0) && ((n = n.substr(1)), (i = '')); + /^(\^(?:\.\^)*)$/.exec(i) + ? (i = i.split('.').reduce(function(t, e) { + return t.parent; + }, t).name) + : '.' === i && (i = t.name); + return { uiViewName: n, uiViewContextAnchor: i }; + }), + (t.prototype._rootViewContext = function(t) { + return (this._rootContext = t || this._rootContext); + }), + (t.prototype._viewConfigFactory = function(t, e) { + this._viewConfigFactories[t] = e; + }), + (t.prototype.createViewConfig = function(t, e) { + var r = this._viewConfigFactories[e.$type]; + if (!r) throw new Error('ViewService: No view config factory registered for type ' + e.$type); + var n = r(t, e); + return V(n) ? n : [n]; + }), + (t.prototype.deactivateViewConfig = function(t) { + Kt.traceViewServiceEvent('<- Removing', t), X(this._viewConfigs, t); + }), + (t.prototype.activateViewConfig = function(t) { + Kt.traceViewServiceEvent('-> Registering', t), this._viewConfigs.push(t); + }), + (t.prototype.sync = function() { + var e = this, + r = this._uiViews + .map(function(t) { + return [t.fqn, t]; + }) + .reduce(Pt, {}); + function n(t) { + for (var e = t.viewDecl.$context, r = 0; ++r && e.parent; ) e = e.parent; + return r; + } + var o = i(function(t, e, r, n) { + return e * (t(r) - t(n)); + }), + a = this._uiViews + .sort( + o(function(t) { + var e = function(t) { + return t && t.parent ? e(t.parent) + 1 : 1; + }; + return 1e4 * t.fqn.split('.').length + e(t.creationContext); + }, 1), + ) + .map(function(i) { + var a = e._viewConfigs.filter(t.matches(r, i)); + return a.length > 1 && a.sort(o(n, -1)), { uiView: i, viewConfig: a[0] }; + }), + u = a.map(function(t) { + return t.viewConfig; + }), + s = this._viewConfigs + .filter(function(t) { + return !Y(u, t); + }) + .map(function(t) { + return { uiView: void 0, viewConfig: t }; + }); + a.forEach(function(t) { + -1 !== e._uiViews.indexOf(t.uiView) && t.uiView.configUpdated(t.viewConfig); + }); + var c = a.concat(s); + this._listeners.forEach(function(t) { + return t(c); + }), + Kt.traceViewSync(c); + }), + (t.prototype.registerUIView = function(t) { + Kt.traceViewServiceUIViewEvent('-> Registering', t); + var e = this._uiViews; + return ( + e.filter(function(e) { + return e.fqn === t.fqn && e.$type === t.$type; + }).length && Kt.traceViewServiceUIViewEvent('!!!! duplicate uiView named:', t), + e.push(t), + this.sync(), + function() { + -1 !== e.indexOf(t) + ? (Kt.traceViewServiceUIViewEvent('<- Deregistering', t), X(e)(t)) + : Kt.traceViewServiceUIViewEvent('Tried removing non-registered uiView', t); + } + ); + }), + (t.prototype.available = function() { + return this._uiViews.map(u('fqn')); + }), + (t.prototype.active = function() { + return this._uiViews.filter(u('$config')).map(u('name')); + }), + (t.matches = function(t, e) { + return function(r) { + if (e.$type !== r.viewDecl.$type) return !1; + var n = r.viewDecl, + i = n.$uiViewName.split('.'), + o = e.fqn.split('.'); + if (!W(i, o.slice(0 - i.length))) return !1; + var a = 1 - i.length || void 0, + u = o.slice(0, a).join('.'), + s = t[u].creationContext; + return n.$uiViewContextAnchor === (s && s.name); + }; + }), + t + ); + })(), + lr = (function() { + function t() { + (this.params = new Ue()), + (this.lastStartedTransitionId = -1), + (this.transitionHistory = new Ht([], 1)), + (this.successfulTransitions = new Ht([], 1)); + } + return ( + (t.prototype.dispose = function() { + this.transitionHistory.clear(), this.successfulTransitions.clear(), (this.transition = null); + }), + t + ); + })(), + hr = function(t) { + return t.reduce( + function(t, e) { + return (t[e] = q(e)), t; + }, + { dispose: J }, + ); + }, + pr = ['url', 'path', 'search', 'hash', 'onChange'], + vr = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix'], + dr = ['type', 'caseInsensitive', 'strictMode', 'defaultSquashPolicy'], + mr = ['sort', 'when', 'initial', 'otherwise', 'rules', 'rule', 'removeRule'], + yr = ['deferIntercept', 'listen', 'sync', 'match'], + gr = (function() { + function t(t, e) { + void 0 === e && (e = !0), (this.router = t), (this.rules = {}), (this.config = {}); + var r = function() { + return t.locationService; + }; + Q(r, this, r, pr, e); + var n = function() { + return t.locationConfig; + }; + Q(n, this.config, n, vr, e); + var i = function() { + return t.urlMatcherFactory; + }; + Q(i, this.config, i, dr); + var o = function() { + return t.urlRouter; + }; + Q(o, this.rules, o, mr), Q(o, this, o, yr); + } + return ( + (t.prototype.url = function(t, e, r) {}), + (t.prototype.path = function() {}), + (t.prototype.search = function() {}), + (t.prototype.hash = function() {}), + (t.prototype.onChange = function(t) {}), + (t.prototype.parts = function() { + return { path: this.path(), search: this.search(), hash: this.hash() }; + }), + (t.prototype.dispose = function() {}), + (t.prototype.sync = function(t) {}), + (t.prototype.listen = function(t) {}), + (t.prototype.deferIntercept = function(t) {}), + (t.prototype.match = function(t) {}), + (t.locationServiceStub = hr(pr)), + (t.locationConfigStub = hr(vr)), + t + ); + })(), + _r = 0, + wr = (function() { + function t(t, e) { + void 0 === t && (t = gr.locationServiceStub), + void 0 === e && (e = gr.locationConfigStub), + (this.locationService = t), + (this.locationConfig = e), + (this.$id = _r++), + (this._disposed = !1), + (this._disposables = []), + (this.trace = Kt), + (this.viewService = new fr()), + (this.globals = new lr()), + (this.transitionService = new Lr(this)), + (this.urlMatcherFactory = new ir()), + (this.urlRouter = new sr(this)), + (this.stateRegistry = new tr(this)), + (this.stateService = new Mr(this)), + (this.urlService = new gr(this)), + (this._plugins = {}), + this.viewService._pluginapi._rootViewContext(this.stateRegistry.root()), + (this.globals.$current = this.stateRegistry.root()), + (this.globals.current = this.globals.$current.self), + this.disposable(this.globals), + this.disposable(this.stateService), + this.disposable(this.stateRegistry), + this.disposable(this.transitionService), + this.disposable(this.urlRouter), + this.disposable(t), + this.disposable(e); + } + return ( + (t.prototype.disposable = function(t) { + this._disposables.push(t); + }), + (t.prototype.dispose = function(t) { + var e = this; + t && P(t.dispose) + ? t.dispose(this) + : ((this._disposed = !0), + this._disposables.slice().forEach(function(t) { + try { + 'function' == typeof t.dispose && t.dispose(e), X(e._disposables, t); + } catch (t) {} + })); + }), + (t.prototype.plugin = function(t, e) { + void 0 === e && (e = {}); + var r = new t(this, e); + if (!r.name) throw new Error('Required property `name` missing on plugin: ' + r); + return this._disposables.push(r), (this._plugins[r.name] = r); + }), + (t.prototype.getPlugin = function(t) { + return t ? this._plugins[t] : vt(this._plugins); + }), + t + ); + })(); + function $r(t) { + t.addResolvable(he.fromData(wr, t.router), ''), + t.addResolvable(he.fromData($e, t), ''), + t.addResolvable(he.fromData('$transition$', t), ''), + t.addResolvable(he.fromData('$stateParams', t.params()), ''), + t.entering().forEach(function(e) { + t.addResolvable(he.fromData('$state$', e), e); + }); + } + var Sr = Y(['$transition$', $e]), + br = function(t) { + var e = function(t) { + return Sr(t.token) ? he.fromData(t.token, null) : t; + }; + vt(t.treeChanges()) + .reduce(yt, []) + .reduce(wt, []) + .forEach(function(t) { + t.resolvables = t.resolvables.map(e); + }); + }, + Rr = function(t) { + var e = t.to().redirectTo; + if (e) { + var r = t.router.stateService; + return P(e) ? N.$q.when(e(t)).then(n) : n(e); + } + function n(e) { + if (e) + return e instanceof Yt + ? e + : O(e) + ? r.target(e, t.params(), t.options()) + : e.state || e.params + ? r.target(e.state || t.to(), e.params || t.params(), t.options()) + : void 0; + } + }; + function Er(t) { + return function(e, r) { + return (0, r.$$state()[t])(e, r); + }; + } + var Cr = Er('onExit'), + Tr = Er('onRetain'), + Pr = Er('onEnter'), + kr = function(t) { + return new ge(t.treeChanges().to).resolvePath('EAGER', t).then(J); + }, + Or = function(t, e) { + return new ge(t.treeChanges().to) + .subContext(e.$$state()) + .resolvePath('LAZY', t) + .then(J); + }, + xr = function(t) { + return new ge(t.treeChanges().to).resolvePath('LAZY', t).then(J); + }, + Vr = function(t) { + var e = N.$q, + r = t.views('entering'); + if (r.length) + return e + .all( + r.map(function(t) { + return e.when(t.load()); + }), + ) + .then(J); + }, + Ir = function(t) { + var e = t.views('entering'), + r = t.views('exiting'); + if (e.length || r.length) { + var n = t.router.viewService; + r.forEach(function(t) { + return n.deactivateViewConfig(t); + }), + e.forEach(function(t) { + return n.activateViewConfig(t); + }), + n.sync(); + } + }, + jr = function(t) { + var e = t.router.globals, + r = function() { + e.transition === t && (e.transition = null); + }; + t.onSuccess( + {}, + function() { + e.successfulTransitions.enqueue(t), + (e.$current = t.$to()), + (e.current = e.$current.self), + Ot(t.params(), e.params); + }, + { priority: 1e4 }, + ), + t.promise.then(r, r); + }, + Ar = function(t) { + var e = t.options(), + r = t.router.stateService, + n = t.router.urlRouter; + if ('url' !== e.source && e.location && r.$current.navigable) { + var i = { replace: 'replace' === e.location }; + n.push(r.$current.navigable.url, r.params, i); + } + n.update(!0); + }, + Hr = function(t) { + var e = t.router; + var r = t + .entering() + .filter(function(t) { + return !!t.$$state().lazyLoad; + }) + .map(function(e) { + return Dr(t, e); + }); + return N.$q.all(r).then(function() { + if ('url' !== t.originalTransition().options().source) { + var r = t.targetState(); + return e.stateService.target(r.identifier(), r.params(), r.options()); + } + var n = e.urlService, + i = n.match(n.parts()), + o = i && i.rule; + if (o && 'STATE' === o.type) { + var a = o.state, + u = i.match; + return e.stateService.target(a, u, t.options()); + } + e.urlService.sync(); + }); + }; + function Dr(t, e) { + var r = e.$$state().lazyLoad, + n = r._promise; + if (!n) { + n = r._promise = N.$q + .when(r(t, e)) + .then(function(e) { + e && + Array.isArray(e.states) && + e.states.forEach(function(e) { + return t.router.stateRegistry.register(e); + }); + return e; + }) + .then( + function(t) { + return delete e.lazyLoad, delete e.$$state().lazyLoad, delete r._promise, t; + }, + function(t) { + return delete r._promise, N.$q.reject(t); + }, + ); + } + return n; + } + var qr = (function() { + return function(t, e, r, n, i, o, a, u) { + void 0 === i && (i = !1), + void 0 === o && (o = Xt.HANDLE_RESULT), + void 0 === a && (a = Xt.REJECT_ERROR), + void 0 === u && (u = !1), + (this.name = t), + (this.hookPhase = e), + (this.hookOrder = r), + (this.criteriaMatchPath = n), + (this.reverseSort = i), + (this.getResultHandler = o), + (this.getErrorHandler = a), + (this.synchronous = u); + }; + })(); + function Nr(t) { + var e = t._ignoredReason(); + if (e) { + Kt.traceTransitionIgnored(t); + var r = t.router.globals.transition; + return 'SameAsCurrent' === e && r && r.abort(), qt.ignored().toPromise(); + } + } + function Fr(t) { + if (!t.valid()) throw new Error(t.error().toString()); + } + var Ur = { + location: !0, + relative: null, + inherit: !1, + notify: !0, + reload: !1, + custom: {}, + current: function() { + return null; + }, + source: 'unknown', + }, + Lr = (function() { + function e(t) { + (this._transitionCount = 0), + (this._eventTypes = []), + (this._registeredHooks = {}), + (this._criteriaPaths = {}), + (this._router = t), + (this.$view = t.viewService), + (this._deregisterHookFns = {}), + (this._pluginapi = Q(y(this), {}, y(this), [ + '_definePathType', + '_defineEvent', + '_getPathTypes', + '_getEvents', + 'getHooks', + ])), + this._defineCorePaths(), + this._defineCoreEvents(), + this._registerCoreTransitionHooks(), + t.globals.successfulTransitions.onEvict(br); + } + return ( + (e.prototype.onCreate = function(t, e, r) {}), + (e.prototype.onBefore = function(t, e, r) {}), + (e.prototype.onStart = function(t, e, r) {}), + (e.prototype.onExit = function(t, e, r) {}), + (e.prototype.onRetain = function(t, e, r) {}), + (e.prototype.onEnter = function(t, e, r) {}), + (e.prototype.onFinish = function(t, e, r) {}), + (e.prototype.onSuccess = function(t, e, r) {}), + (e.prototype.onError = function(t, e, r) {}), + (e.prototype.dispose = function(t) { + vt(this._registeredHooks).forEach(function(t) { + return t.forEach(function(e) { + (e._deregistered = !0), X(t, e); + }); + }); + }), + (e.prototype.create = function(t, e) { + return new $e(t, e, this._router); + }), + (e.prototype._defineCoreEvents = function() { + var e = t.TransitionHookPhase, + r = Xt, + n = this._criteriaPaths; + this._defineEvent('onCreate', e.CREATE, 0, n.to, !1, r.LOG_REJECTED_RESULT, r.THROW_ERROR, !0), + this._defineEvent('onBefore', e.BEFORE, 0, n.to), + this._defineEvent('onStart', e.RUN, 0, n.to), + this._defineEvent('onExit', e.RUN, 100, n.exiting, !0), + this._defineEvent('onRetain', e.RUN, 200, n.retained), + this._defineEvent('onEnter', e.RUN, 300, n.entering), + this._defineEvent('onFinish', e.RUN, 400, n.to), + this._defineEvent('onSuccess', e.SUCCESS, 0, n.to, !1, r.LOG_REJECTED_RESULT, r.LOG_ERROR, !0), + this._defineEvent('onError', e.ERROR, 0, n.to, !1, r.LOG_REJECTED_RESULT, r.LOG_ERROR, !0); + }), + (e.prototype._defineCorePaths = function() { + var e = t.TransitionHookScope.STATE, + r = t.TransitionHookScope.TRANSITION; + this._definePathType('to', r), + this._definePathType('from', r), + this._definePathType('exiting', e), + this._definePathType('retained', e), + this._definePathType('entering', e); + }), + (e.prototype._defineEvent = function(t, e, r, n, i, o, a, u) { + void 0 === i && (i = !1), + void 0 === o && (o = Xt.HANDLE_RESULT), + void 0 === a && (a = Xt.REJECT_ERROR), + void 0 === u && (u = !1); + var s = new qr(t, e, r, n, i, o, a, u); + this._eventTypes.push(s), re(this, this, s); + }), + (e.prototype._getEvents = function(t) { + return (E(t) + ? this._eventTypes.filter(function(e) { + return e.hookPhase === t; + }) + : this._eventTypes.slice() + ).sort(function(t, e) { + var r = t.hookPhase - e.hookPhase; + return 0 === r ? t.hookOrder - e.hookOrder : r; + }); + }), + (e.prototype._definePathType = function(t, e) { + this._criteriaPaths[t] = { name: t, scope: e }; + }), + (e.prototype._getPathTypes = function() { + return this._criteriaPaths; + }), + (e.prototype.getHooks = function(t) { + return this._registeredHooks[t]; + }), + (e.prototype._registerCoreTransitionHooks = function() { + var t = this._deregisterHookFns; + (t.addCoreResolves = this.onCreate({}, $r)), + (t.ignored = (function(t) { + return t.onBefore({}, Nr, { priority: -9999 }); + })(this)), + (t.invalid = (function(t) { + return t.onBefore({}, Fr, { priority: -1e4 }); + })(this)), + (t.redirectTo = (function(t) { + return t.onStart( + { + to: function(t) { + return !!t.redirectTo; + }, + }, + Rr, + ); + })(this)), + (t.onExit = (function(t) { + return t.onExit( + { + exiting: function(t) { + return !!t.onExit; + }, + }, + Cr, + ); + })(this)), + (t.onRetain = (function(t) { + return t.onRetain( + { + retained: function(t) { + return !!t.onRetain; + }, + }, + Tr, + ); + })(this)), + (t.onEnter = (function(t) { + return t.onEnter( + { + entering: function(t) { + return !!t.onEnter; + }, + }, + Pr, + ); + })(this)), + (t.eagerResolve = (function(t) { + return t.onStart({}, kr, { priority: 1e3 }); + })(this)), + (t.lazyResolve = (function(t) { + return t.onEnter({ entering: y(!0) }, Or, { priority: 1e3 }); + })(this)), + (t.resolveAll = (function(t) { + return t.onFinish({}, xr, { priority: 1e3 }); + })(this)), + (t.loadViews = (function(t) { + return t.onFinish({}, Vr); + })(this)), + (t.activateViews = (function(t) { + return t.onSuccess({}, Ir); + })(this)), + (t.updateGlobals = (function(t) { + return t.onCreate({}, jr); + })(this)), + (t.updateUrl = (function(t) { + return t.onSuccess({}, Ar, { priority: 9999 }); + })(this)), + (t.lazyLoad = (function(t) { + return t.onBefore( + { + entering: function(t) { + return !!t.lazyLoad; + }, + }, + Hr, + ); + })(this)); + }), + e + ); + })(), + Mr = (function() { + function e(t) { + (this.router = t), + (this.invalidCallbacks = []), + (this._defaultErrorHandler = function(t) { + t instanceof Error && t.stack + ? (console.error(t), console.error(t.stack)) + : t instanceof qt + ? (console.error(t.toString()), t.detail && t.detail.stack && console.error(t.detail.stack)) + : console.error(t); + }); + var r = Object.keys(e.prototype).filter(f(Y(['current', '$current', 'params', 'transition']))); + Q(y(e.prototype), this, y(this), r); + } + return ( + Object.defineProperty(e.prototype, 'transition', { + get: function() { + return this.router.globals.transition; + }, + enumerable: !0, + configurable: !0, + }), + Object.defineProperty(e.prototype, 'params', { + get: function() { + return this.router.globals.params; + }, + enumerable: !0, + configurable: !0, + }), + Object.defineProperty(e.prototype, 'current', { + get: function() { + return this.router.globals.current; + }, + enumerable: !0, + configurable: !0, + }), + Object.defineProperty(e.prototype, '$current', { + get: function() { + return this.router.globals.$current; + }, + enumerable: !0, + configurable: !0, + }), + (e.prototype.dispose = function() { + this.defaultErrorHandler(J), (this.invalidCallbacks = []); + }), + (e.prototype._handleInvalidTargetState = function(t, e) { + var r = this, + n = fe.makeTargetState(this.router.stateRegistry, t), + i = this.router.globals, + o = function() { + return i.transitionHistory.peekTail(); + }, + a = o(), + u = new Ht(this.invalidCallbacks.slice()), + s = new ge(t).injector(), + c = function(t) { + if (t instanceof Yt) { + var e = t; + return (e = r.target(e.identifier(), e.params(), e.options())).valid() + ? o() !== a + ? qt.superseded().toPromise() + : r.transitionTo(e.identifier(), e.params(), e.options()) + : qt.invalid(e.error()).toPromise(); + } + }; + return (function t() { + var r = u.dequeue(); + return void 0 === r + ? qt.invalid(e.error()).toPromise() + : N.$q + .when(r(e, n, s)) + .then(c) + .then(function(e) { + return e || t(); + }); + })(); + }), + (e.prototype.onInvalid = function(t) { + return ( + this.invalidCallbacks.push(t), + function() { + X(this.invalidCallbacks)(t); + }.bind(this) + ); + }), + (e.prototype.reload = function(t) { + return this.transitionTo(this.current, this.params, { reload: !E(t) || t, inherit: !1, notify: !1 }); + }), + (e.prototype.go = function(t, e, r) { + var n = it(r, { relative: this.$current, inherit: !0 }, Ur); + return this.transitionTo(t, e, n); + }), + (e.prototype.target = function(t, e, r) { + if ((void 0 === r && (r = {}), x(r.reload) && !r.reload.name)) throw new Error('Invalid reload state object'); + var n = this.router.stateRegistry; + if ( + ((r.reloadState = !0 === r.reload ? n.root() : n.matcher.find(r.reload, r.relative)), + r.reload && !r.reloadState) + ) + throw new Error("No such reload state '" + (O(r.reload) ? r.reload : r.reload.name) + "'"); + return new Yt(this.router.stateRegistry, t, e, r); + }), + (e.prototype.getCurrentPath = function() { + var t = this, + e = this.router.globals.successfulTransitions.peekTail(); + return e ? e.treeChanges().to : [new ce(t.router.stateRegistry.root())]; + }), + (e.prototype.transitionTo = function(e, r, n) { + var i = this; + void 0 === r && (r = {}), void 0 === n && (n = {}); + var o = this.router, + a = o.globals; + n = it(n, Ur); + n = G(n, { + current: function() { + return a.transition; + }, + }); + var u = this.target(e, r, n), + s = this.getCurrentPath(); + if (!u.exists()) return this._handleInvalidTargetState(s, u); + if (!u.valid()) return At(u.error()); + var c = function(e) { + return function(r) { + if (r instanceof qt) { + var n = o.globals.lastStartedTransitionId === e.$id; + if (r.type === t.RejectType.IGNORED) return n && o.urlRouter.update(), N.$q.when(a.current); + var u = r.detail; + if (r.type === t.RejectType.SUPERSEDED && r.redirected && u instanceof Yt) { + var s = e.redirect(u); + return s.run().catch(c(s)); + } + if (r.type === t.RejectType.ABORTED) return n && o.urlRouter.update(), N.$q.reject(r); + } + return i.defaultErrorHandler()(r), N.$q.reject(r); + }; + }, + f = this.router.transitionService.create(s, u), + l = f.run().catch(c(f)); + return jt(l), G(l, { transition: f }); + }), + (e.prototype.is = function(t, e, r) { + r = it(r, { relative: this.$current }); + var n = this.router.stateRegistry.matcher.find(t, r.relative); + if (E(n)) { + if (this.$current !== n) return !1; + if (!e) return !0; + var i = n.parameters({ inherit: !0, matchingKeys: e }); + return se.equals(i, se.values(i, e), this.params); + } + }), + (e.prototype.includes = function(t, e, r) { + r = it(r, { relative: this.$current }); + var n = O(t) && w.fromString(t); + if (n) { + if (!n.matches(this.$current.name)) return !1; + t = this.$current.name; + } + var i = this.router.stateRegistry.matcher.find(t, r.relative), + o = this.$current.includes; + if (E(i)) { + if (!E(o[i.name])) return !1; + if (!e) return !0; + var a = i.parameters({ inherit: !0, matchingKeys: e }); + return se.equals(a, se.values(a, e), this.params); + } + }), + (e.prototype.href = function(t, e, r) { + (r = it(r, { lossy: !0, inherit: !0, absolute: !1, relative: this.$current })), (e = e || {}); + var n = this.router.stateRegistry.matcher.find(t, r.relative); + if (!E(n)) return null; + r.inherit && (e = this.params.$inherit(e, this.$current, n)); + var i = n && r.lossy ? n.navigable : n; + return i && void 0 !== i.url && null !== i.url + ? this.router.urlRouter.href(i.url, e, { absolute: r.absolute }) + : null; + }), + (e.prototype.defaultErrorHandler = function(t) { + return (this._defaultErrorHandler = t || this._defaultErrorHandler); + }), + (e.prototype.get = function(t, e) { + var r = this.router.stateRegistry; + return 0 === arguments.length ? r.get() : r.get(t, e || this.$current); + }), + (e.prototype.lazyLoad = function(t, e) { + var r = this.get(t); + if (!r || !r.lazyLoad) throw new Error('Can not lazy load ' + t); + var n = this.getCurrentPath(), + i = fe.makeTargetState(this.router.stateRegistry, n); + return Dr((e = e || this.router.transitionService.create(n, i)), r); + }), + e + ); + })(), + Br = { + when: function(t) { + return new Promise(function(e, r) { + return e(t); + }); + }, + reject: function(t) { + return new Promise(function(e, r) { + r(t); + }); + }, + defer: function() { + var t = {}; + return ( + (t.promise = new Promise(function(e, r) { + (t.resolve = e), (t.reject = r); + })), + t + ); + }, + all: function(t) { + if (V(t)) return Promise.all(t); + if (x(t)) { + var e = Object.keys(t).map(function(e) { + return t[e].then(function(t) { + return { key: e, val: t }; + }); + }); + return Br.all(e).then(function(t) { + return t.reduce(function(t, e) { + return (t[e.key] = e.val), t; + }, {}); + }); + } + }, + }, + Gr = {}, + Wr = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm, + zr = /([^\s,]+)/g, + Jr = { + get: function(t) { + return Gr[t]; + }, + has: function(t) { + return null != Jr.get(t); + }, + invoke: function(t, e, r) { + var n = G({}, Gr, r || {}), + i = Jr.annotate(t), + o = bt( + function(t) { + return n.hasOwnProperty(t); + }, + function(t) { + return "DI can't find injectable: '" + t + "'"; + }, + ), + a = i.filter(o).map(function(t) { + return n[t]; + }); + return P(t) ? t.apply(e, a) : t.slice(-1)[0].apply(e, a); + }, + annotate: function(t) { + if (!H(t)) throw new Error('Not an injectable function: ' + t); + if (t && t.$inject) return t.$inject; + if (V(t)) return t.slice(0, -1); + var e = t.toString().replace(Wr, ''); + return e.slice(e.indexOf('(') + 1, e.indexOf(')')).match(zr) || []; + }, + }, + Qr = function(t, e) { + var r = e[0], + n = e[1]; + return t.hasOwnProperty(r) ? (V(t[r]) ? t[r].push(n) : (t[r] = [t[r], n])) : (t[r] = n), t; + }, + Kr = function(t) { + return t + .split('&') + .filter(z) + .map(Ae) + .reduce(Qr, {}); + }; + function Yr(t) { + var e = function(t) { + return t || ''; + }, + r = Ie(t).map(e), + n = r[0], + i = r[1], + o = je(n).map(e); + return { path: o[0], search: o[1], hash: i, url: t }; + } + var Zr = function(t) { + var e = t.path(), + r = t.search(), + n = t.hash(), + i = Object.keys(r) + .map(function(t) { + var e = r[t]; + return (V(e) ? e : [e]).map(function(e) { + return t + '=' + e; + }); + }) + .reduce(yt, []) + .join('&'); + return e + (i ? '?' + i : '') + (n ? '#' + n : ''); + }; + function Xr(t, e, r, n) { + return function(i) { + var o = (i.locationService = new r(i)), + a = (i.locationConfig = new n(i, e)); + return { + name: t, + service: o, + configuration: a, + dispose: function(t) { + t.dispose(o), t.dispose(a); + }, + }; + }; + } + var tn, + en = (function() { + function t(t, e) { + var r = this; + (this.fireAfterUpdate = e), + (this._listeners = []), + (this._listener = function(t) { + return r._listeners.forEach(function(e) { + return e(t); + }); + }), + (this.hash = function() { + return Yr(r._get()).hash; + }), + (this.path = function() { + return Yr(r._get()).path; + }), + (this.search = function() { + return Kr(Yr(r._get()).search); + }), + (this._location = F.location), + (this._history = F.history); + } + return ( + (t.prototype.url = function(t, e) { + return ( + void 0 === e && (e = !0), + E(t) && + t !== this._get() && + (this._set(null, null, t, e), + this.fireAfterUpdate && + this._listeners.forEach(function(e) { + return e({ url: t }); + })), + Zr(this) + ); + }), + (t.prototype.onChange = function(t) { + var e = this; + return ( + this._listeners.push(t), + function() { + return X(e._listeners, t); + } + ); + }), + (t.prototype.dispose = function(t) { + nt(this._listeners); + }), + t + ); + })(), + rn = ((tn = + Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && + function(t, e) { + t.__proto__ = e; + }) || + function(t, e) { + for (var r in e) e.hasOwnProperty(r) && (t[r] = e[r]); + }), + function(t, e) { + function r() { + this.constructor = t; + } + tn(t, e), (t.prototype = null === e ? Object.create(e) : ((r.prototype = e.prototype), new r())); + }), + nn = (function(t) { + function e(e) { + var r = t.call(this, e, !1) || this; + return F.addEventListener('hashchange', r._listener, !1), r; + } + return ( + rn(e, t), + (e.prototype._get = function() { + return He(this._location.hash); + }), + (e.prototype._set = function(t, e, r, n) { + this._location.hash = r; + }), + (e.prototype.dispose = function(e) { + t.prototype.dispose.call(this, e), F.removeEventListener('hashchange', this._listener); + }), + e + ); + })(en), + on = (function() { + var t = + Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && + function(t, e) { + t.__proto__ = e; + }) || + function(t, e) { + for (var r in e) e.hasOwnProperty(r) && (t[r] = e[r]); + }; + return function(e, r) { + function n() { + this.constructor = e; + } + t(e, r), (e.prototype = null === r ? Object.create(r) : ((n.prototype = r.prototype), new n())); + }; + })(), + an = (function(t) { + function e(e) { + return t.call(this, e, !0) || this; + } + return ( + on(e, t), + (e.prototype._get = function() { + return this._url; + }), + (e.prototype._set = function(t, e, r, n) { + this._url = r; + }), + e + ); + })(en), + un = (function() { + var t = + Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && + function(t, e) { + t.__proto__ = e; + }) || + function(t, e) { + for (var r in e) e.hasOwnProperty(r) && (t[r] = e[r]); + }; + return function(e, r) { + function n() { + this.constructor = e; + } + t(e, r), (e.prototype = null === r ? Object.create(r) : ((n.prototype = r.prototype), new n())); + }; + })(), + sn = (function(t) { + function e(e) { + var r = t.call(this, e, !0) || this; + return (r._config = e.urlService.config), F.addEventListener('popstate', r._listener, !1), r; + } + return ( + un(e, t), + (e.prototype._getBasePrefix = function() { + return Ve(this._config.baseHref()); + }), + (e.prototype._get = function() { + var t = this._location, + e = t.pathname, + r = t.hash, + n = t.search; + (n = je(n)[1]), (r = Ie(r)[1]); + var i = this._getBasePrefix(), + o = e === this._config.baseHref(), + a = e.substr(0, i.length) === i; + return (e = o ? '/' : a ? e.substring(i.length) : e) + (n ? '?' + n : '') + (r ? '#' + r : ''); + }), + (e.prototype._set = function(t, e, r, n) { + var i = this._getBasePrefix(), + o = r && '/' !== r[0] ? '/' : '', + a = '' === r || '/' === r ? this._config.baseHref() : i + o + r; + n ? this._history.replaceState(t, e, a) : this._history.pushState(t, e, a); + }), + (e.prototype.dispose = function(e) { + t.prototype.dispose.call(this, e), F.removeEventListener('popstate', this._listener); + }), + e + ); + })(en), + cn = (function() { + return function() { + var t = this; + (this.dispose = J), + (this._baseHref = ''), + (this._port = 80), + (this._protocol = 'http'), + (this._host = 'localhost'), + (this._hashPrefix = ''), + (this.port = function() { + return t._port; + }), + (this.protocol = function() { + return t._protocol; + }), + (this.host = function() { + return t._host; + }), + (this.baseHref = function() { + return t._baseHref; + }), + (this.html5Mode = function() { + return !1; + }), + (this.hashPrefix = function(e) { + return E(e) ? (t._hashPrefix = e) : t._hashPrefix; + }); + }; + })(), + fn = (function() { + function t(t, e) { + void 0 === e && (e = !1), (this._isHtml5 = e), (this._baseHref = void 0), (this._hashPrefix = ''); + } + return ( + (t.prototype.port = function() { + return location.port ? Number(location.port) : 'https' === this.protocol() ? 443 : 80; + }), + (t.prototype.protocol = function() { + return location.protocol.replace(/:/g, ''); + }), + (t.prototype.host = function() { + return location.hostname; + }), + (t.prototype.html5Mode = function() { + return this._isHtml5; + }), + (t.prototype.hashPrefix = function(t) { + return E(t) ? (this._hashPrefix = t) : this._hashPrefix; + }), + (t.prototype.baseHref = function(t) { + return E(t) ? (this._baseHref = t) : E(this._baseHref) ? this._baseHref : this.applyDocumentBaseHref(); + }), + (t.prototype.applyDocumentBaseHref = function() { + var t = document.getElementsByTagName('base')[0]; + return (this._baseHref = t ? t.href.substr(location.origin.length) : location.pathname || '/'); + }), + (t.prototype.dispose = function() {}), + t + ); + })(); + function ln(t) { + return ( + (N.$injector = Jr), + (N.$q = Br), + { + name: 'vanilla.services', + $q: Br, + $injector: Jr, + dispose: function() { + return null; + }, + } + ); + } + var hn = Xr('vanilla.hashBangLocation', !1, nn, fn), + pn = Xr('vanilla.pushStateLocation', !0, sn, fn), + vn = Xr('vanilla.memoryLocation', !1, an, cn), + dn = (function() { + function t() {} + return (t.prototype.dispose = function(t) {}), t; + })(), + mn = Object.freeze({ + root: F, + fromJson: L, + toJson: M, + forEach: B, + extend: G, + equals: W, + identity: z, + noop: J, + createProxyFunctions: Q, + inherit: K, + inArray: Y, + _inArray: Z, + removeFrom: X, + _removeFrom: tt, + pushTo: et, + _pushTo: rt, + deregAll: nt, + defaults: it, + mergeR: ot, + ancestors: at, + pick: ut, + omit: st, + pluck: ct, + filter: ft, + find: lt, + mapObj: ht, + map: pt, + values: vt, + allTrueR: dt, + anyTrueR: mt, + unnestR: yt, + flattenR: gt, + pushR: _t, + uniqR: wt, + unnest: $t, + flatten: St, + assertPredicate: bt, + assertMap: Rt, + assertFn: Et, + pairs: Ct, + arrayTuples: Tt, + applyPairs: Pt, + tail: kt, + copy: Ot, + _extend: xt, + silenceUncaughtInPromise: jt, + silentRejection: At, + notImplemented: q, + services: N, + Glob: w, + curry: i, + compose: o, + pipe: a, + prop: u, + propEq: s, + parse: c, + not: f, + and: l, + or: h, + all: p, + any: v, + is: d, + eq: m, + val: y, + invoke: g, + pattern: _, + isUndefined: R, + isDefined: E, + isNull: C, + isNullOrUndefined: T, + isFunction: P, + isNumber: k, + isString: O, + isObject: x, + isArray: V, + isDate: I, + isRegExp: j, + isState: A, + isInjectable: H, + isPromise: D, + Queue: Ht, + maxLength: Se, + padString: be, + kebobString: Re, + functionToString: Ee, + fnToString: Ce, + stringify: ke, + beforeAfterSubstr: Oe, + hostRegex: xe, + stripLastPathElement: Ve, + splitHash: Ie, + splitQuery: je, + splitEqual: Ae, + trimHashVal: He, + splitOnDelim: De, + joinNeighborsR: qe, + get Category() { + return t.Category; + }, + Trace: Qt, + trace: Kt, + get DefType() { + return t.DefType; + }, + Param: se, + ParamTypes: Fe, + StateParams: Ue, + ParamType: ie, + PathNode: ce, + PathUtils: fe, + resolvePolicies: pe, + defaultResolvePolicy: le, + Resolvable: he, + NATIVE_INJECTOR_TOKEN: ye, + ResolveContext: ge, + resolvablesBuilder: Ke, + StateBuilder: Ye, + StateObject: $, + StateMatcher: Ze, + StateQueueManager: Xe, + StateRegistry: tr, + StateService: Mr, + TargetState: Yt, + get TransitionHookPhase() { + return t.TransitionHookPhase; + }, + get TransitionHookScope() { + return t.TransitionHookScope; + }, + HookBuilder: ne, + matchState: te, + RegisteredHook: ee, + makeEvent: re, + get RejectType() { + return t.RejectType; + }, + Rejection: qt, + Transition: $e, + TransitionHook: Xt, + TransitionEventType: qr, + defaultTransOpts: Ur, + TransitionService: Lr, + UrlMatcher: nr, + UrlMatcherFactory: ir, + UrlRouter: sr, + UrlRuleFactory: or, + BaseUrlRule: ar, + UrlService: gr, + ViewService: fr, + UIRouterGlobals: lr, + UIRouter: wr, + $q: Br, + $injector: Jr, + BaseLocationServices: en, + HashLocationService: nn, + MemoryLocationService: an, + PushStateLocationService: sn, + MemoryLocationConfig: cn, + BrowserLocationConfig: fn, + keyValsToObjectR: Qr, + getParams: Kr, + parseUrl: Yr, + buildUrl: Zr, + locationPluginFactory: Xr, + servicesPlugin: ln, + hashLocationPlugin: hn, + pushStateLocationPlugin: pn, + memoryLocationPlugin: vn, + UIRouterPluginBase: dn, + }); + function yn() { + var t = null; + return function(e, r) { + return (t = t || N.$injector.get('$templateFactory')), [new $n(e, r, t)]; + }; + } + var gn = function(t, e) { + return t.reduce(function(t, r) { + return t || E(e[r]); + }, !1); + }; + function _n(t) { + if (!t.parent) return {}; + var e = ['component', 'bindings', 'componentProvider'], + r = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'].concat([ + 'controller', + 'controllerProvider', + 'controllerAs', + 'resolveAs', + ]), + n = e.concat(r); + if (E(t.views) && gn(n, t)) + throw new Error( + "State '" + + t.name + + "' has a 'views' object. It cannot also have \"view properties\" at the state level. Move the following properties into a view (in the 'views' object): " + + n + .filter(function(e) { + return E(t[e]); + }) + .join(', '), + ); + var i = {}, + o = t.views || { $default: ut(t, n) }; + return ( + B(o, function(n, o) { + if (((o = o || '$default'), O(n) && (n = { component: n }), (n = G({}, n)), gn(e, n) && gn(r, n))) + throw new Error( + 'Cannot combine: ' + e.join('|') + ' with: ' + r.join('|') + " in stateview: '" + o + '@' + t.name + "'", + ); + (n.resolveAs = n.resolveAs || '$resolve'), (n.$type = 'ng1'), (n.$context = t), (n.$name = o); + var a = fr.normalizeUIViewTarget(n.$context, n.$name); + (n.$uiViewName = a.uiViewName), (n.$uiViewContextAnchor = a.uiViewContextAnchor), (i[o] = n); + }), + i + ); + } + var wn = 0, + $n = (function() { + function t(t, e, r) { + var n = this; + (this.path = t), + (this.viewDecl = e), + (this.factory = r), + (this.$id = wn++), + (this.loaded = !1), + (this.getTemplate = function(t, e) { + return n.component ? n.factory.makeComponentTemplate(t, e, n.component, n.viewDecl.bindings) : n.template; + }); + } + return ( + (t.prototype.load = function() { + var t = this, + e = N.$q, + r = new ge(this.path), + n = this.path.reduce(function(t, e) { + return G(t, e.paramValues); + }, {}), + i = { + template: e.when(this.factory.fromConfig(this.viewDecl, n, r)), + controller: e.when(this.getController(r)), + }; + return e.all(i).then(function(e) { + return Kt.traceViewServiceEvent('Loaded', t), (t.controller = e.controller), G(t, e.template), t; + }); + }), + (t.prototype.getController = function(t) { + var e = this.viewDecl.controllerProvider; + if (!H(e)) return this.viewDecl.controller; + var r = N.$injector.annotate(e), + n = V(e) ? kt(e) : e; + return new he('', n, r).get(t); + }), + t + ); + })(), + Sn = (function() { + function t() { + var t = this; + (this._useHttp = n.version.minor < 3), + (this.$get = [ + '$http', + '$templateCache', + '$injector', + function(e, r, n) { + return ( + (t.$templateRequest = n.has && n.has('$templateRequest') && n.get('$templateRequest')), + (t.$http = e), + (t.$templateCache = r), + t + ); + }, + ]); + } + return ( + (t.prototype.useHttpService = function(t) { + this._useHttp = t; + }), + (t.prototype.fromConfig = function(t, e, r) { + var n = function(t) { + return N.$q.when(t).then(function(t) { + return { template: t }; + }); + }, + i = function(t) { + return N.$q.when(t).then(function(t) { + return { component: t }; + }); + }; + return E(t.template) + ? n(this.fromString(t.template, e)) + : E(t.templateUrl) + ? n(this.fromUrl(t.templateUrl, e)) + : E(t.templateProvider) + ? n(this.fromProvider(t.templateProvider, e, r)) + : E(t.component) + ? i(t.component) + : E(t.componentProvider) + ? i(this.fromComponentProvider(t.componentProvider, e, r)) + : n(''); + }), + (t.prototype.fromString = function(t, e) { + return P(t) ? t(e) : t; + }), + (t.prototype.fromUrl = function(t, e) { + return ( + P(t) && (t = t(e)), + null == t + ? null + : this._useHttp + ? this.$http.get(t, { cache: this.$templateCache, headers: { Accept: 'text/html' } }).then(function(t) { + return t.data; + }) + : this.$templateRequest(t) + ); + }), + (t.prototype.fromProvider = function(t, e, r) { + var n = N.$injector.annotate(t), + i = V(t) ? kt(t) : t; + return new he('', i, n).get(r); + }), + (t.prototype.fromComponentProvider = function(t, e, r) { + var n = N.$injector.annotate(t), + i = V(t) ? kt(t) : t; + return new he('', i, n).get(r); + }), + (t.prototype.makeComponentTemplate = function(t, e, r, i) { + i = i || {}; + var o = n.version.minor >= 3 ? '::' : '', + a = function(t) { + var e = Re(t); + return /^(x|data)-/.exec(e) ? 'x-' + e : e; + }, + u = (function(t) { + var e = N.$injector.get(t + 'Directive'); + if (!e || !e.length) throw new Error("Unable to find component named '" + t + "'"); + return e.map(bn).reduce(yt, []); + })(r) + .map(function(r) { + var n = r.name, + u = r.type, + s = a(n); + if (t.attr(s) && !i[n]) return s + "='" + t.attr(s) + "'"; + var c = i[n] || n; + if ('@' === u) return s + "='{{" + o + '$resolve.' + c + "}}'"; + if ('&' === u) { + var f = e.getResolvable(c), + l = f && f.data, + h = (l && N.$injector.annotate(l)) || []; + return s + "='$resolve." + c + (V(l) ? '[' + (l.length - 1) + ']' : '') + '(' + h.join(',') + ")'"; + } + return s + "='" + o + '$resolve.' + c + "'"; + }) + .join(' '), + s = a(r); + return '<' + s + ' ' + u + '>'; + }), + t + ); + })(); + var bn = function(t) { + return x(t.bindToController) ? Rn(t.bindToController) : Rn(t.scope); + }, + Rn = function(t) { + return Object.keys(t || {}) + .map(function(e) { + return [e, /^([=<@&])[?]?(.*)/.exec(t[e])]; + }) + .filter(function(t) { + return E(t) && V(t[1]); + }) + .map(function(t) { + return { name: t[1][2] || t[0], type: t[1][1] }; + }); + }, + En = (function() { + function t(e, r) { + (this.stateRegistry = e), (this.stateService = r), Q(y(t.prototype), this, y(this)); + } + return ( + (t.prototype.decorator = function(t, e) { + return this.stateRegistry.decorator(t, e) || this; + }), + (t.prototype.state = function(t, e) { + return x(t) ? (e = t) : (e.name = t), this.stateRegistry.register(e), this; + }), + (t.prototype.onInvalid = function(t) { + return this.stateService.onInvalid(t); + }), + t + ); + })(), + Cn = function(t) { + return function(e, r) { + var n = e[t], + i = 'onExit' === t ? 'from' : 'to'; + return n + ? function(t, e) { + var r = new ge(t.treeChanges(i)).subContext(e.$$state()), + o = G(Mn(r), { $state$: e, $transition$: t }); + return N.$injector.invoke(n, this, o); + } + : void 0; + }; + }, + Tn = (function() { + function t(t) { + (this._urlListeners = []), (this.$locationProvider = t); + var e = y(t); + Q(e, this, e, ['hashPrefix']); + } + return ( + (t.monkeyPatchPathParameterType = function(t) { + var e = t.urlMatcherFactory.type('path'); + (e.encode = function(t) { + return null != t + ? t.toString().replace(/(~|\/)/g, function(t) { + return { '~': '~~', '/': '~2F' }[t]; + }) + : t; + }), + (e.decode = function(t) { + return null != t + ? t.toString().replace(/(~~|~2F)/g, function(t) { + return { '~~': '~', '~2F': '/' }[t]; + }) + : t; + }); + }), + (t.prototype.dispose = function() {}), + (t.prototype.onChange = function(t) { + var e = this; + return ( + this._urlListeners.push(t), + function() { + return X(e._urlListeners)(t); + } + ); + }), + (t.prototype.html5Mode = function() { + var t = this.$locationProvider.html5Mode(); + return (t = x(t) ? t.enabled : t) && this.$sniffer.history; + }), + (t.prototype.url = function(t, e, r) { + return ( + void 0 === e && (e = !1), + E(t) && this.$location.url(t), + e && this.$location.replace(), + r && this.$location.state(r), + this.$location.url() + ); + }), + (t.prototype._runtimeServices = function(t, e, r, n) { + var i = this; + (this.$location = e), + (this.$sniffer = r), + t.$on('$locationChangeSuccess', function(t) { + return i._urlListeners.forEach(function(e) { + return e(t); + }); + }); + var o = y(e), + a = y(n); + Q(o, this, o, ['replace', 'path', 'search', 'hash']), + Q(o, this, o, ['port', 'protocol', 'host']), + Q(a, this, a, ['baseHref']); + }), + t + ); + })(), + Pn = (function() { + function t(t) { + (this._router = t), (this._urlRouter = t.urlRouter); + } + return ( + (t.injectableHandler = function(t, e) { + return function(r) { + return N.$injector.invoke(e, null, { $match: r, $stateParams: t.globals.params }); + }; + }), + (t.prototype.$get = function() { + var t = this._urlRouter; + return t.update(!0), t.interceptDeferred || t.listen(), t; + }), + (t.prototype.rule = function(t) { + var e = this; + if (!P(t)) throw new Error("'rule' must be a function"); + var r = new ar(function() { + return t(N.$injector, e._router.locationService); + }, z); + return this._urlRouter.rule(r), this; + }), + (t.prototype.otherwise = function(t) { + var e = this, + r = this._urlRouter; + if (O(t)) r.otherwise(t); + else { + if (!P(t)) throw new Error("'rule' must be a string or function"); + r.otherwise(function() { + return t(N.$injector, e._router.locationService); + }); + } + return this; + }), + (t.prototype.when = function(e, r) { + return (V(r) || P(r)) && (r = t.injectableHandler(this._router, r)), this._urlRouter.when(e, r), this; + }), + (t.prototype.deferIntercept = function(t) { + this._urlRouter.deferIntercept(t); + }), + t + ); + })(); + n.module('ui.router.angular1', []); + var kn = n.module('ui.router.init', []), + On = n.module('ui.router.util', ['ng', 'ui.router.init']), + xn = n.module('ui.router.router', ['ui.router.util']), + Vn = n.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']), + In = n.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']), + jn = (n.module('ui.router.compat', ['ui.router']), null); + function An(t) { + ((jn = this.router = new wr()).stateProvider = new En(jn.stateRegistry, jn.stateService)), + jn.stateRegistry.decorator('views', _n), + jn.stateRegistry.decorator('onExit', Cn('onExit')), + jn.stateRegistry.decorator('onRetain', Cn('onRetain')), + jn.stateRegistry.decorator('onEnter', Cn('onEnter')), + jn.viewService._pluginapi._viewConfigFactory('ng1', yn()); + var e = (jn.locationService = jn.locationConfig = new Tn(t)); + function r(t, r, n, i, o, a) { + return e._runtimeServices(i, t, n, r), delete jn.router, delete jn.$get, jn; + } + return ( + Tn.monkeyPatchPathParameterType(jn), + (jn.router = jn), + (jn.$get = r), + (r.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache']), + jn + ); + } + An.$inject = ['$locationProvider']; + var Hn = function(t) { + return [ + '$uiRouterProvider', + function(e) { + var r = e.router[t]; + return ( + (r.$get = function() { + return r; + }), + r + ); + }, + ]; + }; + function Dn(t, e, r) { + (N.$injector = t), + (N.$q = e), + r.stateRegistry + .get() + .map(function(t) { + return t.$$state().resolvables; + }) + .reduce(yt, []) + .filter(function(t) { + return 'deferred' === t.deps; + }) + .forEach(function(e) { + return (e.deps = t.annotate(e.resolveFn, t.strictDi)); + }); + } + Dn.$inject = ['$injector', '$q', '$uiRouter']; + function qn(t) { + t.$watch(function() { + Kt.approximateDigests++; + }); + } + (qn.$inject = ['$rootScope']), + kn.provider('$uiRouter', An), + xn.provider('$urlRouter', [ + '$uiRouterProvider', + function(t) { + return (t.urlRouterProvider = new Pn(t)); + }, + ]), + On.provider('$urlService', Hn('urlService')), + On.provider('$urlMatcherFactory', [ + '$uiRouterProvider', + function() { + return jn.urlMatcherFactory; + }, + ]), + On.provider('$templateFactory', function() { + return new Sn(); + }), + Vn.provider('$stateRegistry', Hn('stateRegistry')), + Vn.provider('$uiRouterGlobals', Hn('globals')), + Vn.provider('$transitions', Hn('transitionService')), + Vn.provider('$state', [ + '$uiRouterProvider', + function() { + return G(jn.stateProvider, { + $get: function() { + return jn.stateService; + }, + }); + }, + ]), + Vn.factory('$stateParams', [ + '$uiRouter', + function(t) { + return t.globals.params; + }, + ]), + In.factory('$view', function() { + return jn.viewService; + }), + In.service('$trace', function() { + return Kt; + }), + In.run(qn), + On.run(['$urlMatcherFactory', function(t) {}]), + Vn.run(['$state', function(t) {}]), + xn.run(['$urlRouter', function(t) {}]), + kn.run(Dn); + var Nn, + Fn, + Un, + Ln, + Mn = function(t) { + return t + .getTokens() + .filter(O) + .map(function(e) { + var r = t.getResolvable(e); + return [e, 'NOWAIT' === t.getPolicy(r).async ? r.promise : r.data]; + }) + .reduce(Pt, {}); + }; + function Bn(t) { + var e, + r = t.match(/^\s*({[^}]*})\s*$/); + if ( + (r && (t = '(' + r[1] + ')'), + !(e = t.replace(/\n/g, ' ').match(/^\s*([^(]*?)\s*(\((.*)\))?\s*$/)) || 4 !== e.length) + ) + throw new Error("Invalid state ref '" + t + "'"); + return { state: e[1] || null, paramExpr: e[3] || null }; + } + function Gn(t) { + var e = t.parent().inheritedData('$uiView'), + r = c('$cfg.path')(e); + return r ? kt(r).state.name : void 0; + } + function Wn(t, e, r) { + var n = r.uiState || t.current.name, + i = G( + (function(t, e) { + return { relative: Gn(t) || e.$current, inherit: !0, source: 'sref' }; + })(e, t), + r.uiStateOpts || {}, + ), + o = t.href(n, r.uiStateParams, i); + return { uiState: n, uiStateParams: r.uiStateParams, uiStateOpts: i, href: o }; + } + function zn(t) { + var e = '[object SVGAnimatedString]' === Object.prototype.toString.call(t.prop('href')), + r = 'FORM' === t[0].nodeName; + return { + attr: r ? 'action' : e ? 'xlink:href' : 'href', + isAnchor: 'A' === t.prop('tagName').toUpperCase(), + clickable: !r, + }; + } + function Jn(t, e, r, n, i) { + return function(o) { + var a = o.which || o.button, + u = i(); + if (!(a > 1 || o.ctrlKey || o.metaKey || o.shiftKey || t.attr('target'))) { + var s = r(function() { + e.go(u.uiState, u.uiStateParams, u.uiStateOpts); + }); + o.preventDefault(); + var c = n.isAnchor && !u.href ? 1 : 0; + o.preventDefault = function() { + c-- <= 0 && r.cancel(s); + }; + } + }; + } + function Qn(t, e, r, n) { + var i; + n && (i = n.events), V(i) || (i = ['click']); + for (var o = t.on ? 'on' : 'bind', a = 0, u = i; a < u.length; a++) { + var s = u[a]; + t[o](s, r); + } + e.$on('$destroy', function() { + for (var e = t.off ? 'off' : 'unbind', n = 0, o = i; n < o.length; n++) { + var a = o[n]; + t[e](a, r); + } + }); + } + function Kn(t) { + var e = function(e, r, n) { + return t.is(e, r, n); + }; + return (e.$stateful = !0), e; + } + function Yn(t) { + var e = function(e, r, n) { + return t.includes(e, r, n); + }; + return (e.$stateful = !0), e; + } + function Zn(t, e, r, i, o, a) { + var u = c('viewDecl.controllerAs'), + s = c('viewDecl.resolveAs'); + return { + restrict: 'ECA', + priority: -400, + compile: function(i) { + var a = i.html(); + return ( + i.empty(), + function(i, c) { + var f = c.data('$uiView'); + if (!f) return c.html(a), void t(c.contents())(i); + var l = f.$cfg || { viewDecl: {}, getTemplate: J }, + h = l.path && new ge(l.path); + c.html(l.getTemplate(c, h) || a), Kt.traceUIViewFill(f.$uiView, c.html()); + var p = t(c.contents()), + v = l.controller, + d = u(l), + m = s(l), + y = h && Mn(h); + if (((i[m] = y), v)) { + var g = e(v, G({}, y, { $scope: i, $element: c })); + d && ((i[d] = g), (i[d][m] = y)), + c.data('$ngControllerController', g), + c.children().data('$ngControllerController', g), + ei(o, r, g, i, l); + } + if (O(l.viewDecl.component)) + var _ = l.viewDecl.component, + w = Re(_), + $ = new RegExp('^(x-|data-)?' + w + '$', 'i'), + S = i.$watch( + function() { + var t = [].slice.call(c[0].children).filter(function(t) { + return t && t.tagName && $.exec(t.tagName); + }); + return t && n.element(t).data('$' + _ + 'Controller'); + }, + function(t) { + t && (ei(o, r, t, i, l), S()); + }, + ); + p(i); + } + ); + }, + }; + } + (Nn = [ + '$uiRouter', + '$timeout', + function(t, e) { + var r = t.stateService; + return { + restrict: 'A', + require: ['?^uiSrefActive', '?^uiSrefActiveEq'], + link: function(n, i, o, a) { + var u, + s = zn(i), + c = a[1] || a[0], + f = null, + l = {}, + h = function() { + return Wn(r, i, l); + }, + p = Bn(o.uiSref); + function v() { + var t = h(); + f && f(), c && (f = c.$$addStateInfo(t.uiState, t.uiStateParams)), null != t.href && o.$set(s.attr, t.href); + } + (l.uiState = p.state), + (l.uiStateOpts = o.uiSrefOpts ? n.$eval(o.uiSrefOpts) : {}), + p.paramExpr && + (n.$watch( + p.paramExpr, + function(t) { + (l.uiStateParams = G({}, t)), v(); + }, + !0, + ), + (l.uiStateParams = G({}, n.$eval(p.paramExpr)))), + v(), + n.$on('$destroy', t.stateRegistry.onStatesChanged(v)), + n.$on('$destroy', t.transitionService.onSuccess({}, v)), + s.clickable && ((u = Jn(i, r, e, s, h)), Qn(i, n, u, l.uiStateOpts)); + }, + }; + }, + ]), + (Fn = [ + '$uiRouter', + '$timeout', + function(t, e) { + var r = t.stateService; + return { + restrict: 'A', + require: ['?^uiSrefActive', '?^uiSrefActiveEq'], + link: function(n, i, o, a) { + var u, + s = zn(i), + c = a[1] || a[0], + f = null, + l = {}, + h = function() { + return Wn(r, i, l); + }, + p = ['uiState', 'uiStateParams', 'uiStateOpts'], + v = p.reduce(function(t, e) { + return (t[e] = J), t; + }, {}); + function d() { + var t = h(); + f && f(), + c && (f = c.$$addStateInfo(t.uiState, t.uiStateParams)), + null != t.href && o.$set(s.attr, t.href); + } + p.forEach(function(t) { + (l[t] = o[t] ? n.$eval(o[t]) : null), + o.$observe(t, function(e) { + v[t](), + (v[t] = n.$watch( + e, + function(e) { + (l[t] = e), d(); + }, + !0, + )); + }); + }), + d(), + n.$on('$destroy', t.stateRegistry.onStatesChanged(d)), + n.$on('$destroy', t.transitionService.onSuccess({}, d)), + s.clickable && ((u = Jn(i, r, e, s, h)), Qn(i, n, u, l.uiStateOpts)); + }, + }; + }, + ]), + (Un = [ + '$state', + '$stateParams', + '$interpolate', + '$uiRouter', + function(t, e, r, n) { + return { + restrict: 'A', + controller: [ + '$scope', + '$element', + '$attrs', + function(e, i, o) { + var a, + u, + s, + c, + f, + l = []; + a = r(o.uiSrefActiveEq || '', !1)(e); + try { + u = e.$eval(o.uiSrefActive); + } catch (t) {} + function h(t) { + t.promise.then(m, J); + } + function p() { + v(u); + } + function v(t) { + x(t) && + ((l = []), + B(t, function(t, r) { + var n = function(t, r) { + var n = Bn(t); + d(n.state, e.$eval(n.paramExpr), r); + }; + O(t) + ? n(t, r) + : V(t) && + B(t, function(t) { + n(t, r); + }); + })); + } + function d(e, r, n) { + var o = { state: t.get(e, Gn(i)) || { name: e }, params: r, activeClass: n }; + return ( + l.push(o), + function() { + X(l)(o); + } + ); + } + function m() { + var r = function(t) { + return t.split(/\s/).filter(z); + }, + n = function(t) { + return t + .map(function(t) { + return t.activeClass; + }) + .map(r) + .reduce(yt, []); + }, + o = n(l) + .concat(r(a)) + .reduce(wt, []), + u = n( + l.filter(function(e) { + return t.includes(e.state.name, e.params); + }), + ), + s = !!l.filter(function(e) { + return t.is(e.state.name, e.params); + }).length + ? r(a) + : [], + c = u.concat(s).reduce(wt, []), + f = o.filter(function(t) { + return !Y(c, t); + }); + e.$evalAsync(function() { + c.forEach(function(t) { + return i.addClass(t); + }), + f.forEach(function(t) { + return i.removeClass(t); + }); + }); + } + v((u = u || r(o.uiSrefActive || '', !1)(e))), + (this.$$addStateInfo = function(t, e) { + if (!(x(u) && l.length > 0)) { + var r = d(t, e, u); + return m(), r; + } + }), + e.$on( + '$destroy', + ((s = n.stateRegistry.onStatesChanged(p)), + (c = n.transitionService.onStart({}, h)), + (f = e.$on('$stateChangeSuccess', m)), + function() { + s(), c(), f(); + }), + ), + n.globals.transition && h(n.globals.transition), + m(); + }, + ], + }; + }, + ]), + n + .module('ui.router.state') + .directive('uiSref', Nn) + .directive('uiSrefActive', Un) + .directive('uiSrefActiveEq', Un) + .directive('uiState', Fn), + (Kn.$inject = ['$state']), + (Yn.$inject = ['$state']), + n + .module('ui.router.state') + .filter('isState', Kn) + .filter('includedByState', Yn), + (Ln = [ + '$view', + '$animate', + '$uiViewScroll', + '$interpolate', + '$q', + function(t, e, r, i, o) { + var a = { $cfg: { viewDecl: { $context: t._pluginapi._rootViewContext() } }, $uiView: {} }, + u = { + count: 0, + restrict: 'ECA', + terminal: !0, + priority: 400, + transclude: 'element', + compile: function(s, f, l) { + return function(s, f, h) { + var p, + v, + d, + m, + y, + g = h.onload || '', + _ = h.autoscroll, + w = { + enter: function(t, r, i) { + n.version.minor > 2 ? e.enter(t, null, r).then(i) : e.enter(t, null, r, i); + }, + leave: function(t, r) { + n.version.minor > 2 ? e.leave(t).then(r) : e.leave(t, r); + }, + }, + $ = f.inheritedData('$uiView') || a, + S = i(h.uiView || h.name || '')(s) || '$default', + b = { + $type: 'ng1', + id: u.count++, + name: S, + fqn: $.$uiView.fqn ? $.$uiView.fqn + '.' + S : S, + config: null, + configUpdated: function(t) { + if (t && !(t instanceof $n)) return; + if (((e = m), (r = t), e === r)) return; + var e, r; + Kt.traceUIViewConfigUpdated(b, t && t.viewDecl && t.viewDecl.$context), (m = t), R(t); + }, + get creationContext() { + var t = c('$cfg.viewDecl.$context')($), + e = c('$uiView.creationContext')($); + return t || e; + }, + }; + function R(t) { + var e = s.$new(), + n = o.defer(), + i = o.defer(), + a = { $cfg: t, $uiView: b }, + u = { $animEnter: n.promise, $animLeave: i.promise, $$animLeave: i }; + e.$emit('$viewContentLoading', S); + var c = l(e, function(t) { + t.data('$uiViewAnim', u), + t.data('$uiView', a), + w.enter(t, f, function() { + n.resolve(), d && d.$emit('$viewContentAnimationEnded'), ((E(_) && !_) || s.$eval(_)) && r(t); + }), + (function() { + if ( + (p && + (Kt.traceUIViewEvent('Removing (previous) el', p.data('$uiView')), p.remove(), (p = null)), + d && (Kt.traceUIViewEvent('Destroying scope', b), d.$destroy(), (d = null)), + v) + ) { + var t = v.data('$uiViewAnim'); + Kt.traceUIViewEvent('Animate out', t), + w.leave(v, function() { + t.$$animLeave.resolve(), (p = null); + }), + (p = v), + (v = null); + } + })(); + }); + (v = c), (d = e).$emit('$viewContentLoaded', t || m), d.$eval(g); + } + Kt.traceUIViewEvent('Linking', b), + f.data('$uiView', { $uiView: b }), + R(), + (y = t.registerUIView(b)), + s.$on('$destroy', function() { + Kt.traceUIViewEvent('Destroying/Unregistering', b), y(); + }); + }; + }, + }; + return u; + }, + ]), + (Zn.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout']); + var Xn = 'function' == typeof n.module('ui.router').component, + ti = 0; + function ei(t, e, r, n, i) { + !P(r.$onInit) || (i.viewDecl.component && Xn) || r.$onInit(); + var o = kt(i.path).state.self, + a = { bind: r }; + if (P(r.uiOnParamsChanged)) { + var u = new ge(i.path).getResolvable('$transition$').data; + n.$on( + '$destroy', + e.onSuccess( + {}, + function(t) { + if (t !== u && -1 === t.exiting().indexOf(o)) { + var e = t.params('to'), + n = t.params('from'), + i = function(t) { + return t.paramSchema; + }, + a = t + .treeChanges('to') + .map(i) + .reduce(yt, []), + s = t + .treeChanges('from') + .map(i) + .reduce(yt, []), + c = a.filter(function(t) { + var r = s.indexOf(t); + return -1 === r || !s[r].type.equals(e[t.id], n[t.id]); + }); + if (c.length) { + var f = c.map(function(t) { + return t.id; + }), + l = ft(e, function(t, e) { + return -1 !== f.indexOf(e); + }); + r.uiOnParamsChanged(l, t); + } + } + }, + a, + ), + ); + } + if (P(r.uiCanExit)) { + var s = ti++, + c = function(t) { + return !!t && ((t._uiCanExitIds && !0 === t._uiCanExitIds[s]) || c(t.redirectedFrom())); + }, + f = { exiting: o.name }; + n.$on( + '$destroy', + e.onBefore( + f, + function(e) { + var n, + i = (e._uiCanExitIds = e._uiCanExitIds || {}); + return ( + c(e) || + (n = t.when(r.uiCanExit(e))).then(function(t) { + return (i[s] = !1 !== t); + }), + n + ); + }, + a, + ), + ); + } + } + n.module('ui.router.state').directive('uiView', Ln), + n.module('ui.router.state').directive('uiView', Zn), + n.module('ui.router.state').provider('$uiViewScroll', function() { + var t = !1; + (this.useAnchorScroll = function() { + t = !0; + }), + (this.$get = [ + '$anchorScroll', + '$timeout', + function(e, r) { + return t + ? e + : function(t) { + return r( + function() { + t[0].scrollIntoView(); + }, + 0, + !1, + ); + }; + }, + ]); + }); + (t.default = 'ui.router'), + (t.core = mn), + (t.watchDigests = qn), + (t.getLocals = Mn), + (t.getNg1ViewConfigFactory = yn), + (t.ng1ViewsBuilder = _n), + (t.Ng1ViewConfig = $n), + (t.StateProvider = En), + (t.UrlRouterProvider = Pn), + (t.root = F), + (t.fromJson = L), + (t.toJson = M), + (t.forEach = B), + (t.extend = G), + (t.equals = W), + (t.identity = z), + (t.noop = J), + (t.createProxyFunctions = Q), + (t.inherit = K), + (t.inArray = Y), + (t._inArray = Z), + (t.removeFrom = X), + (t._removeFrom = tt), + (t.pushTo = et), + (t._pushTo = rt), + (t.deregAll = nt), + (t.defaults = it), + (t.mergeR = ot), + (t.ancestors = at), + (t.pick = ut), + (t.omit = st), + (t.pluck = ct), + (t.filter = ft), + (t.find = lt), + (t.mapObj = ht), + (t.map = pt), + (t.values = vt), + (t.allTrueR = dt), + (t.anyTrueR = mt), + (t.unnestR = yt), + (t.flattenR = gt), + (t.pushR = _t), + (t.uniqR = wt), + (t.unnest = $t), + (t.flatten = St), + (t.assertPredicate = bt), + (t.assertMap = Rt), + (t.assertFn = Et), + (t.pairs = Ct), + (t.arrayTuples = Tt), + (t.applyPairs = Pt), + (t.tail = kt), + (t.copy = Ot), + (t._extend = xt), + (t.silenceUncaughtInPromise = jt), + (t.silentRejection = At), + (t.notImplemented = q), + (t.services = N), + (t.Glob = w), + (t.curry = i), + (t.compose = o), + (t.pipe = a), + (t.prop = u), + (t.propEq = s), + (t.parse = c), + (t.not = f), + (t.and = l), + (t.or = h), + (t.all = p), + (t.any = v), + (t.is = d), + (t.eq = m), + (t.val = y), + (t.invoke = g), + (t.pattern = _), + (t.isUndefined = R), + (t.isDefined = E), + (t.isNull = C), + (t.isNullOrUndefined = T), + (t.isFunction = P), + (t.isNumber = k), + (t.isString = O), + (t.isObject = x), + (t.isArray = V), + (t.isDate = I), + (t.isRegExp = j), + (t.isState = A), + (t.isInjectable = H), + (t.isPromise = D), + (t.Queue = Ht), + (t.maxLength = Se), + (t.padString = be), + (t.kebobString = Re), + (t.functionToString = Ee), + (t.fnToString = Ce), + (t.stringify = ke), + (t.beforeAfterSubstr = Oe), + (t.hostRegex = xe), + (t.stripLastPathElement = Ve), + (t.splitHash = Ie), + (t.splitQuery = je), + (t.splitEqual = Ae), + (t.trimHashVal = He), + (t.splitOnDelim = De), + (t.joinNeighborsR = qe), + (t.Trace = Qt), + (t.trace = Kt), + (t.Param = se), + (t.ParamTypes = Fe), + (t.StateParams = Ue), + (t.ParamType = ie), + (t.PathNode = ce), + (t.PathUtils = fe), + (t.resolvePolicies = pe), + (t.defaultResolvePolicy = le), + (t.Resolvable = he), + (t.NATIVE_INJECTOR_TOKEN = ye), + (t.ResolveContext = ge), + (t.resolvablesBuilder = Ke), + (t.StateBuilder = Ye), + (t.StateObject = $), + (t.StateMatcher = Ze), + (t.StateQueueManager = Xe), + (t.StateRegistry = tr), + (t.StateService = Mr), + (t.TargetState = Yt), + (t.HookBuilder = ne), + (t.matchState = te), + (t.RegisteredHook = ee), + (t.makeEvent = re), + (t.Rejection = qt), + (t.Transition = $e), + (t.TransitionHook = Xt), + (t.TransitionEventType = qr), + (t.defaultTransOpts = Ur), + (t.TransitionService = Lr), + (t.UrlMatcher = nr), + (t.UrlMatcherFactory = ir), + (t.UrlRouter = sr), + (t.UrlRuleFactory = or), + (t.BaseUrlRule = ar), + (t.UrlService = gr), + (t.ViewService = fr), + (t.UIRouterGlobals = lr), + (t.UIRouter = wr), + (t.$q = Br), + (t.$injector = Jr), + (t.BaseLocationServices = en), + (t.HashLocationService = nn), + (t.MemoryLocationService = an), + (t.PushStateLocationService = sn), + (t.MemoryLocationConfig = cn), + (t.BrowserLocationConfig = fn), + (t.keyValsToObjectR = Qr), + (t.getParams = Kr), + (t.parseUrl = Yr), + (t.buildUrl = Zr), + (t.locationPluginFactory = Xr), + (t.servicesPlugin = ln), + (t.hashLocationPlugin = hn), + (t.pushStateLocationPlugin = pn), + (t.memoryLocationPlugin = vn), + (t.UIRouterPluginBase = dn), + Object.defineProperty(t, '__esModule', { value: !0 }); +}); //# sourceMappingURL=angular-ui-router.min.js.map diff --git a/UI/WebServerResources/js/vendor/angular-ui-router.min.js.map b/UI/WebServerResources/js/vendor/angular-ui-router.min.js.map index 44b8e4f81..290928a1e 100644 --- a/UI/WebServerResources/js/vendor/angular-ui-router.min.js.map +++ b/UI/WebServerResources/js/vendor/angular-ui-router.min.js.map @@ -78,80 +78,80 @@ "@uirouter/angularjs/src/index.ts" ], "sourcesContent": [ - "/**\n * @hidden\n * @module ng1\n */ /** */\ndeclare var angular;\nimport * as ng_from_import from 'angular';\nconst ng_from_global = angular;\n\nexport const ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;\n", - "/**\n * Higher order functions\n *\n * These utility functions are exported, but are subject to change without notice.\n *\n * @module common_hof\n */ /** */\n\nimport { Predicate } from './common';\n/**\n * Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function.\n *\n * Given a function with N parameters, returns a new function that supports partial application.\n * The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters,\n * where M is less than N, it returns a new function that accepts the remaining parameters. It continues to\n * accept more parameters until all N parameters have been supplied.\n *\n *\n * This contrived example uses a partially applied function as an predicate, which returns true\n * if an object is found in both arrays.\n * @example\n * ```\n * // returns true if an object is in both of the two arrays\n * function inBoth(array1, array2, object) {\n * return array1.indexOf(object) !== -1 &&\n * array2.indexOf(object) !== 1;\n * }\n * let obj1, obj2, obj3, obj4, obj5, obj6, obj7\n * let foos = [obj1, obj3]\n * let bars = [obj3, obj4, obj5]\n *\n * // A curried \"copy\" of inBoth\n * let curriedInBoth = curry(inBoth);\n * // Partially apply both the array1 and array2\n * let inFoosAndBars = curriedInBoth(foos, bars);\n *\n * // Supply the final argument; since all arguments are\n * // supplied, the original inBoth function is then called.\n * let obj1InBoth = inFoosAndBars(obj1); // false\n *\n * // Use the inFoosAndBars as a predicate.\n * // Filter, on each iteration, supplies the final argument\n * let allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ];\n * let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ]\n *\n * ```\n *\n * Stolen from: http://stackoverflow.com/questions/4394747/javascript-curry-function\n *\n * @param fn\n * @returns {*|function(): (*|any)}\n */\nexport function curry(fn: Function): Function {\n const initial_args = [].slice.apply(arguments, [1]);\n const func_args_length = fn.length;\n\n function curried(args: any[]) {\n if (args.length >= func_args_length)\n return fn.apply(null, args);\n return function () {\n return curried(args.concat([].slice.apply(arguments)));\n };\n }\n return curried(initial_args);\n}\n\n\n\n/**\n * Given a varargs list of functions, returns a function that composes the argument functions, right-to-left\n * given: f(x), g(x), h(x)\n * let composed = compose(f,g,h)\n * then, composed is: f(g(h(x)))\n */\nexport function compose() {\n const args = arguments;\n const start = args.length - 1;\n return function() {\n let i = start, result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n}\n\n/**\n * Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right\n * given: f(x), g(x), h(x)\n * let piped = pipe(f,g,h);\n * then, piped is: h(g(f(x)))\n */\nexport function pipe(...funcs: Function[]): (obj: any) => any {\n return compose.apply(null, [].slice.call(arguments).reverse());\n}\n\n/**\n * Given a property name, returns a function that returns that property from an object\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = prop(\"name\");\n * getName(obj) === \"blarg\"\n */\nexport const prop = (name: string) =>\n (obj: any) => obj && obj[name];\n\n/**\n * Given a property name and a value, returns a function that returns a boolean based on whether\n * the passed object has a property that matches the value\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = propEq(\"name\", \"blarg\");\n * getName(obj) === true\n */\nexport const propEq = curry((name: string, _val: any, obj: any) => obj && obj[name] === _val);\n\n/**\n * Given a dotted property name, returns a function that returns a nested property from an object, or undefined\n * let obj = { id: 1, nestedObj: { foo: 1, name: \"blarg\" }, };\n * let getName = prop(\"nestedObj.name\");\n * getName(obj) === \"blarg\"\n * let propNotFound = prop(\"this.property.doesnt.exist\");\n * propNotFound(obj) === undefined\n */\nexport const parse = (name: string) =>\n pipe.apply(null, name.split('.').map(prop));\n\n/**\n * Given a function that returns a truthy or falsey value, returns a\n * function that returns the opposite (falsey or truthy) value given the same inputs\n */\nexport const not: (fn: Predicate) => Predicate = (fn: Predicate) =>\n (...args: any[]) => !fn.apply(null, args);\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if both functions return truthy for the given arguments\n */\nexport function and(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) && fn2.apply(null, args);\n}\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if at least one of the functions returns truthy for the given arguments\n */\nexport function or(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) || fn2.apply(null, args);\n}\n\n/**\n * Check if all the elements of an array match a predicate function\n *\n * @param fn1 a predicate function `fn1`\n * @returns a function which takes an array and returns true if `fn1` is true for all elements of the array\n */\nexport const all = (fn1: Predicate) =>\n (arr: any[]) => arr.reduce((b, x) => b && !!fn1(x), true) as boolean;\n\n// tslint:disable-next-line:variable-name\nexport const any = (fn1: Predicate) =>\n (arr: any[]) => arr.reduce((b, x) => b || !!fn1(x), false) as boolean;\n\n/** Given a class, returns a Predicate function that returns true if the object is of that class */\nexport const is = (ctor: { new(...args): T }) =>\n (obj: any): obj is T =>\n (obj != null && obj.constructor === ctor || obj instanceof ctor);\n\n/** Given a value, returns a Predicate function that returns true if another value is === equal to the original value */\nexport const eq: (comp: any) => Predicate = (value: any) => (other: any) =>\n value === other;\n\n/** Given a value, returns a function which returns the value */\nexport const val = (v: T) => () => v;\n\n\n\nexport function invoke(fnName: string): Function;\nexport function invoke(fnName: string, args: any[]): Function;\nexport function invoke(fnName: string, args?: any[]): Function {\n return (obj: any) =>\n obj[fnName].apply(obj, args);\n}\n\n/**\n * Sorta like Pattern Matching (a functional programming conditional construct)\n *\n * See http://c2.com/cgi/wiki?PatternMatching\n *\n * This is a conditional construct which allows a series of predicates and output functions\n * to be checked and then applied. Each predicate receives the input. If the predicate\n * returns truthy, then its matching output function (mapping function) is provided with\n * the input and, then the result is returned.\n *\n * Each combination (2-tuple) of predicate + output function should be placed in an array\n * of size 2: [ predicate, mapFn ]\n *\n * These 2-tuples should be put in an outer array.\n *\n * @example\n * ```\n *\n * // Here's a 2-tuple where the first element is the isString predicate\n * // and the second element is a function that returns a description of the input\n * let firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ];\n *\n * // Second tuple: predicate \"isNumber\", mapfn returns a description\n * let secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ];\n *\n * let third = [ (input) => input === null, (input) => `Oh, null...` ];\n *\n * let fourth = [ (input) => input === undefined, (input) => `notdefined` ];\n *\n * let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]);\n *\n * console.log(descriptionOf(undefined)); // 'notdefined'\n * console.log(descriptionOf(55)); // '(55) That's a number!'\n * console.log(descriptionOf(\"foo\")); // 'Here's your string foo'\n * ```\n *\n * @param struct A 2D array. Each element of the array should be an array, a 2-tuple,\n * with a Predicate and a mapping/output function\n * @returns {function(any): *}\n */\nexport function pattern(struct: Function[][]): Function {\n return function(x: any) {\n for (let i = 0; i < struct.length; i++) {\n if (struct[i][0](x)) return struct[i][1](x);\n }\n };\n}\n\n", - "/**\n * @coreapi\n * @module core\n */\n/**\n * Matches state names using glob-like pattern strings.\n *\n * Globs can be used in specific APIs including:\n *\n * - [[StateService.is]]\n * - [[StateService.includes]]\n * - The first argument to Hook Registration functions like [[TransitionService.onStart]]\n * - [[HookMatchCriteria]] and [[HookMatchCriterion]]\n *\n * A `Glob` string is a pattern which matches state names.\n * Nested state names are split into segments (separated by a dot) when processing.\n * The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz']\n *\n * Globs work according to the following rules:\n *\n * ### Exact match:\n *\n * The glob `'A.B'` matches the state named exactly `'A.B'`.\n *\n * | Glob |Matches states named|Does not match state named|\n * |:------------|:--------------------|:---------------------|\n * | `'A'` | `'A'` | `'B'` , `'A.C'` |\n * | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` |\n * | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`|\n *\n * ### Single star (`*`)\n *\n * A single star (`*`) is a wildcard that matches exactly one segment.\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:---------------------|:--------------------------|\n * | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` |\n * | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` |\n * | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`|\n *\n * ### Double star (`**`)\n *\n * A double star (`'**'`) is a wildcard that matches *zero or more segments*\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:----------------------------------------------|:----------------------------------|\n * | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) |\n * | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` |\n * | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` |\n * | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` |\n *\n */\nexport class Glob {\n text: string;\n glob: Array;\n regexp: RegExp;\n\n /** Returns true if the string has glob-like characters in it */\n static is(text: string) {\n return !!/[!,*]+/.exec(text);\n }\n\n /** Returns a glob from the string, or null if the string isn't Glob-like */\n static fromString(text: string) {\n return Glob.is(text) ? new Glob(text) : null;\n }\n\n constructor(text: string) {\n this.text = text;\n this.glob = text.split('.');\n\n const regexpString = this.text.split('.')\n .map(seg => {\n if (seg === '**') return '(?:|(?:\\\\.[^.]*)*)';\n if (seg === '*') return '\\\\.[^.]*';\n return '\\\\.' + seg;\n }).join('');\n\n this.regexp = new RegExp('^' + regexpString + '$');\n }\n\n matches(name: string) {\n return this.regexp.test('.' + name);\n }\n}\n", - "/**\n * @coreapi\n * @module state\n */\n/** for typedoc */\nimport { StateDeclaration, _ViewDeclaration, _StateDeclaration, LazyLoadResult } from './interface';\nimport { defaults, values, find, inherit } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { Param } from '../params/param';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { TargetState } from './targetState';\nimport { Transition } from '../transition/transition';\nimport { Glob } from '../common/glob';\nimport { isObject, isFunction } from '../common/predicates';\n\n/**\n * Internal representation of a UI-Router state.\n *\n * Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]].\n *\n * A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object.\n *\n * This class prototypally inherits from the corresponding [[StateDeclaration]].\n * Each of its own properties (i.e., `hasOwnProperty`) are built using builders from the [[StateBuilder]].\n */\nexport class StateObject {\n /** The parent [[StateObject]] */\n public parent: StateObject;\n\n /** The name used to register the state */\n public name: string;\n\n /** Prototypally inherits from [[StateDeclaration.abstract]] */\n public abstract: boolean;\n\n /** Prototypally inherits from [[StateDeclaration.resolve]] */\n public resolve: ({ [key: string]: (string|any[]|Function) }|any[]);\n\n /** A list of [[Resolvable]] objects. The internal representation of [[resolve]]. */\n public resolvables: Resolvable[];\n\n /** Prototypally inherits from [[StateDeclaration.resolvePolicy]] */\n public resolvePolicy: any;\n\n /** A compiled URLMatcher which detects when the state's URL is matched */\n public url: UrlMatcher;\n\n /** The parameters for the state, built from the URL and [[StateDeclaration.params]] */\n public params: { [key: string]: Param };\n\n /**\n * The views for the state.\n * Note: `@uirouter/core` does not register a builder for views.\n * The framework specific code should register a `views` builder.\n */\n public views: { [key: string]: _ViewDeclaration; };\n\n /**\n * The original [[StateDeclaration]] used to build this [[StateObject]].\n * Note: `this` object also prototypally inherits from the `self` declaration object.\n */\n public self: StateDeclaration;\n\n /** The nearest parent [[StateObject]] which has a URL */\n public navigable: StateObject;\n\n /** The parent [[StateObject]] objects from this state up to the root */\n public path: StateObject[];\n\n /**\n * Prototypally inherits from [[StateDeclaration.data]]\n * Note: This is the only field on the [[StateDeclaration]] which is mutated.\n * The definition object's `data` field is replaced with a new object\n * which prototypally inherits from the parent state definition's `data` field.\n */\n public data: any;\n\n /**\n * An object containing the parent States' names as keys and\n * true as their values.\n */\n public includes: { [name: string]: boolean };\n\n /** Prototypally inherits from [[StateDeclaration.onExit]] */\n public onExit: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onRetain]] */\n public onRetain: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onEnter]] */\n public onEnter: TransitionStateHookFn;\n\n /** Prototypally inherits from [[StateDeclaration.lazyLoad]] */\n public lazyLoad: (transition: Transition, state: StateDeclaration) => Promise;\n\n /** Prototypally inherits from [[StateDeclaration.redirectTo]] */\n redirectTo: (\n string |\n (($transition$: Transition) => TargetState) |\n { state: (string|StateDeclaration), params: { [key: string]: any }}\n );\n\n /** @hidden */\n __stateObjectCache: {\n /** Might be null */\n nameGlob?: Glob,\n };\n\n /**\n * Create a state object to put the private/internal implementation details onto.\n * The object's prototype chain looks like:\n * (Internal State Object) -> (Copy of State.prototype) -> (State Declaration object) -> (State Declaration's prototype...)\n *\n * @param stateDecl the user-supplied State Declaration\n * @returns {StateObject} an internal State object\n */\n static create(stateDecl: _StateDeclaration): StateObject {\n stateDecl = StateObject.isStateClass(stateDecl) ? new stateDecl() : stateDecl;\n\n const state = inherit(inherit(stateDecl, StateObject.prototype)) as StateObject;\n stateDecl.$$state = () => state;\n state.self = stateDecl;\n state.__stateObjectCache = {\n nameGlob: Glob.fromString(state.name), // might return null\n };\n return state;\n }\n\n /** Predicate which returns true if the object is an class with @State() decorator */\n static isStateClass = (stateDecl: _StateDeclaration): stateDecl is ({ new (): StateDeclaration }) =>\n isFunction(stateDecl) && stateDecl['__uiRouterState'] === true;\n\n /** Predicate which returns true if the object is an internal [[StateObject]] object */\n static isState = (obj: any): obj is StateObject =>\n isObject(obj['__stateObjectCache']);\n\n\n /** @deprecated use State.create() */\n constructor(config?: StateDeclaration) {\n return StateObject.create(config || {});\n }\n\n /**\n * Returns true if the provided parameter is the same state.\n *\n * Compares the identity of the state against the passed value, which is either an object\n * reference to the actual `State` instance, the original definition object passed to\n * `$stateProvider.state()`, or the fully-qualified name.\n *\n * @param ref Can be one of (a) a `State` instance, (b) an object that was passed\n * into `$stateProvider.state()`, (c) the fully-qualified name of a state as a string.\n * @returns Returns `true` if `ref` matches the current `State` instance.\n */\n is(ref: StateObject|StateDeclaration|string): boolean {\n return this === ref || this.self === ref || this.fqn() === ref;\n }\n\n /**\n * @deprecated this does not properly handle dot notation\n * @returns Returns a dot-separated name of the state.\n */\n fqn(): string {\n if (!this.parent || !(this.parent instanceof this.constructor)) return this.name;\n const name = this.parent.fqn();\n return name ? name + '.' + this.name : this.name;\n }\n\n /**\n * Returns the root node of this state's tree.\n *\n * @returns The root of this state's tree.\n */\n root(): StateObject {\n return this.parent && this.parent.root() || this;\n }\n\n /**\n * Gets the state's `Param` objects\n *\n * Gets the list of [[Param]] objects owned by the state.\n * If `opts.inherit` is true, it also includes the ancestor states' [[Param]] objects.\n * If `opts.matchingKeys` exists, returns only `Param`s whose `id` is a key on the `matchingKeys` object\n *\n * @param opts options\n */\n parameters(opts?: { inherit?: boolean, matchingKeys?: any }): Param[] {\n opts = defaults(opts, { inherit: true, matchingKeys: null });\n const inherited = opts.inherit && this.parent && this.parent.parameters() || [];\n return inherited.concat(values(this.params))\n .filter(param => !opts.matchingKeys || opts.matchingKeys.hasOwnProperty(param.id));\n }\n\n /**\n * Returns a single [[Param]] that is owned by the state\n *\n * If `opts.inherit` is true, it also searches the ancestor states` [[Param]]s.\n * @param id the name of the [[Param]] to return\n * @param opts options\n */\n parameter(id: string, opts: { inherit?: boolean } = {}): Param {\n return (\n this.url && this.url.parameter(id, opts) ||\n find(values(this.params), propEq('id', id)) ||\n opts.inherit && this.parent && this.parent.parameter(id)\n );\n }\n\n toString() {\n return this.fqn();\n }\n}\n", - "/** Predicates\n *\n * These predicates return true/false based on the input.\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_predicates\n */\n/** */\nimport { and, not, pipe, prop, or } from './hof';\nimport { Predicate } from './common'; // has or is using\nimport { StateObject } from '../state/stateObject';\n\nconst toStr = Object.prototype.toString;\nconst tis = (t: string) => (x: any) => typeof(x) === t;\nexport const isUndefined = tis('undefined');\nexport const isDefined = not(isUndefined);\nexport const isNull = (o: any) => o === null;\nexport const isNullOrUndefined = or(isNull, isUndefined);\nexport const isFunction: (x: any) => x is Function = tis('function');\nexport const isNumber: (x: any) => x is number = tis('number');\nexport const isString = <(x: any) => x is string> tis('string');\nexport const isObject = (x: any) => x !== null && typeof x === 'object';\nexport const isArray = Array.isArray;\nexport const isDate: (x: any) => x is Date = ((x: any) => toStr.call(x) === '[object Date]');\nexport const isRegExp: (x: any) => x is RegExp = ((x: any) => toStr.call(x) === '[object RegExp]');\nexport const isState: (x: any) => x is StateObject = StateObject.isState;\n\n/**\n * Predicate which checks if a value is injectable\n *\n * A value is \"injectable\" if it is a function, or if it is an ng1 array-notation-style array\n * where all the elements in the array are Strings, except the last one, which is a Function\n */\nexport function isInjectable(val: any) {\n if (isArray(val) && val.length) {\n const head = val.slice(0, -1), tail = val.slice(-1);\n return !(head.filter(not(isString)).length || tail.filter(not(isFunction)).length);\n }\n return isFunction(val);\n}\n\n/**\n * Predicate which checks if a value looks like a Promise\n *\n * It is probably a Promise if it's an object, and it has a `then` property which is a Function\n */\nexport const isPromise = <(x: any) => x is Promise> and(isObject, pipe(prop('then'), isFunction));\n\n", + "/**\n * @hidden\n * @module ng1\n */ /** */\ndeclare var angular;\nimport * as ng_from_import from 'angular';\nconst ng_from_global = angular;\n\nexport const ng = ng_from_import && ng_from_import.module ? ng_from_import : ng_from_global;\n", + "/**\n * Higher order functions\n *\n * These utility functions are exported, but are subject to change without notice.\n *\n * @module common_hof\n */ /** */\n\nimport { Predicate } from './common';\n/**\n * Returns a new function for [Partial Application](https://en.wikipedia.org/wiki/Partial_application) of the original function.\n *\n * Given a function with N parameters, returns a new function that supports partial application.\n * The new function accepts anywhere from 1 to N parameters. When that function is called with M parameters,\n * where M is less than N, it returns a new function that accepts the remaining parameters. It continues to\n * accept more parameters until all N parameters have been supplied.\n *\n *\n * This contrived example uses a partially applied function as an predicate, which returns true\n * if an object is found in both arrays.\n * @example\n * ```\n * // returns true if an object is in both of the two arrays\n * function inBoth(array1, array2, object) {\n * return array1.indexOf(object) !== -1 &&\n * array2.indexOf(object) !== 1;\n * }\n * let obj1, obj2, obj3, obj4, obj5, obj6, obj7\n * let foos = [obj1, obj3]\n * let bars = [obj3, obj4, obj5]\n *\n * // A curried \"copy\" of inBoth\n * let curriedInBoth = curry(inBoth);\n * // Partially apply both the array1 and array2\n * let inFoosAndBars = curriedInBoth(foos, bars);\n *\n * // Supply the final argument; since all arguments are\n * // supplied, the original inBoth function is then called.\n * let obj1InBoth = inFoosAndBars(obj1); // false\n *\n * // Use the inFoosAndBars as a predicate.\n * // Filter, on each iteration, supplies the final argument\n * let allObjs = [ obj1, obj2, obj3, obj4, obj5, obj6, obj7 ];\n * let foundInBoth = allObjs.filter(inFoosAndBars); // [ obj3 ]\n *\n * ```\n *\n * Stolen from: http://stackoverflow.com/questions/4394747/javascript-curry-function\n *\n * @param fn\n * @returns {*|function(): (*|any)}\n */\nexport function curry(fn: Function): Function {\n const initial_args = [].slice.apply(arguments, [1]);\n const func_args_length = fn.length;\n\n function curried(args: any[]) {\n if (args.length >= func_args_length) return fn.apply(null, args);\n return function() {\n return curried(args.concat([].slice.apply(arguments)));\n };\n }\n return curried(initial_args);\n}\n\n/**\n * Given a varargs list of functions, returns a function that composes the argument functions, right-to-left\n * given: f(x), g(x), h(x)\n * let composed = compose(f,g,h)\n * then, composed is: f(g(h(x)))\n */\nexport function compose() {\n const args = arguments;\n const start = args.length - 1;\n return function() {\n let i = start,\n result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n}\n\n/**\n * Given a varargs list of functions, returns a function that is composes the argument functions, left-to-right\n * given: f(x), g(x), h(x)\n * let piped = pipe(f,g,h);\n * then, piped is: h(g(f(x)))\n */\nexport function pipe(...funcs: Function[]): (obj: any) => any {\n return compose.apply(null, [].slice.call(arguments).reverse());\n}\n\n/**\n * Given a property name, returns a function that returns that property from an object\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = prop(\"name\");\n * getName(obj) === \"blarg\"\n */\nexport const prop = (name: string) => (obj: any) => obj && obj[name];\n\n/**\n * Given a property name and a value, returns a function that returns a boolean based on whether\n * the passed object has a property that matches the value\n * let obj = { foo: 1, name: \"blarg\" };\n * let getName = propEq(\"name\", \"blarg\");\n * getName(obj) === true\n */\nexport const propEq = curry((name: string, _val: any, obj: any) => obj && obj[name] === _val);\n\n/**\n * Given a dotted property name, returns a function that returns a nested property from an object, or undefined\n * let obj = { id: 1, nestedObj: { foo: 1, name: \"blarg\" }, };\n * let getName = prop(\"nestedObj.name\");\n * getName(obj) === \"blarg\"\n * let propNotFound = prop(\"this.property.doesnt.exist\");\n * propNotFound(obj) === undefined\n */\nexport const parse = (name: string) => pipe.apply(null, name.split('.').map(prop));\n\n/**\n * Given a function that returns a truthy or falsey value, returns a\n * function that returns the opposite (falsey or truthy) value given the same inputs\n */\nexport const not: (fn: Predicate) => Predicate = (fn: Predicate) => (...args: any[]) =>\n !fn.apply(null, args);\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if both functions return truthy for the given arguments\n */\nexport function and(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) && fn2.apply(null, args);\n}\n\n/**\n * Given two functions that return truthy or falsey values, returns a function that returns truthy\n * if at least one of the functions returns truthy for the given arguments\n */\nexport function or(fn1: Predicate, fn2: Predicate): Predicate {\n return (...args: any[]) => fn1.apply(null, args) || fn2.apply(null, args);\n}\n\n/**\n * Check if all the elements of an array match a predicate function\n *\n * @param fn1 a predicate function `fn1`\n * @returns a function which takes an array and returns true if `fn1` is true for all elements of the array\n */\nexport const all = (fn1: Predicate) => (arr: any[]) => arr.reduce((b, x) => b && !!fn1(x), true) as boolean;\n\n// tslint:disable-next-line:variable-name\nexport const any = (fn1: Predicate) => (arr: any[]) => arr.reduce((b, x) => b || !!fn1(x), false) as boolean;\n\n/** Given a class, returns a Predicate function that returns true if the object is of that class */\nexport const is = (ctor: { new (...args): T }) => (obj: any): obj is T =>\n (obj != null && obj.constructor === ctor) || obj instanceof ctor;\n\n/** Given a value, returns a Predicate function that returns true if another value is === equal to the original value */\nexport const eq: (comp: any) => Predicate = (value: any) => (other: any) => value === other;\n\n/** Given a value, returns a function which returns the value */\nexport const val = (v: T) => () => v;\n\nexport function invoke(fnName: string): Function;\nexport function invoke(fnName: string, args: any[]): Function;\nexport function invoke(fnName: string, args?: any[]): Function {\n return (obj: any) => obj[fnName].apply(obj, args);\n}\n\n/**\n * Sorta like Pattern Matching (a functional programming conditional construct)\n *\n * See http://c2.com/cgi/wiki?PatternMatching\n *\n * This is a conditional construct which allows a series of predicates and output functions\n * to be checked and then applied. Each predicate receives the input. If the predicate\n * returns truthy, then its matching output function (mapping function) is provided with\n * the input and, then the result is returned.\n *\n * Each combination (2-tuple) of predicate + output function should be placed in an array\n * of size 2: [ predicate, mapFn ]\n *\n * These 2-tuples should be put in an outer array.\n *\n * @example\n * ```\n *\n * // Here's a 2-tuple where the first element is the isString predicate\n * // and the second element is a function that returns a description of the input\n * let firstTuple = [ angular.isString, (input) => `Heres your string ${input}` ];\n *\n * // Second tuple: predicate \"isNumber\", mapfn returns a description\n * let secondTuple = [ angular.isNumber, (input) => `(${input}) That's a number!` ];\n *\n * let third = [ (input) => input === null, (input) => `Oh, null...` ];\n *\n * let fourth = [ (input) => input === undefined, (input) => `notdefined` ];\n *\n * let descriptionOf = pattern([ firstTuple, secondTuple, third, fourth ]);\n *\n * console.log(descriptionOf(undefined)); // 'notdefined'\n * console.log(descriptionOf(55)); // '(55) That's a number!'\n * console.log(descriptionOf(\"foo\")); // 'Here's your string foo'\n * ```\n *\n * @param struct A 2D array. Each element of the array should be an array, a 2-tuple,\n * with a Predicate and a mapping/output function\n * @returns {function(any): *}\n */\nexport function pattern(struct: Function[][]): Function {\n return function(x: any) {\n for (let i = 0; i < struct.length; i++) {\n if (struct[i][0](x)) return struct[i][1](x);\n }\n };\n}\n", + "/**\n * @coreapi\n * @module core\n */\n/**\n * Matches state names using glob-like pattern strings.\n *\n * Globs can be used in specific APIs including:\n *\n * - [[StateService.is]]\n * - [[StateService.includes]]\n * - The first argument to Hook Registration functions like [[TransitionService.onStart]]\n * - [[HookMatchCriteria]] and [[HookMatchCriterion]]\n *\n * A `Glob` string is a pattern which matches state names.\n * Nested state names are split into segments (separated by a dot) when processing.\n * The state named `foo.bar.baz` is split into three segments ['foo', 'bar', 'baz']\n *\n * Globs work according to the following rules:\n *\n * ### Exact match:\n *\n * The glob `'A.B'` matches the state named exactly `'A.B'`.\n *\n * | Glob |Matches states named|Does not match state named|\n * |:------------|:--------------------|:---------------------|\n * | `'A'` | `'A'` | `'B'` , `'A.C'` |\n * | `'A.B'` | `'A.B'` | `'A'` , `'A.B.C'` |\n * | `'foo'` | `'foo'` | `'FOO'` , `'foo.bar'`|\n *\n * ### Single star (`*`)\n *\n * A single star (`*`) is a wildcard that matches exactly one segment.\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:---------------------|:--------------------------|\n * | `'*'` | `'A'` , `'Z'` | `'A.B'` , `'Z.Y.X'` |\n * | `'A.*'` | `'A.B'` , `'A.C'` | `'A'` , `'A.B.C'` |\n * | `'A.*.*'` | `'A.B.C'` , `'A.X.Y'`| `'A'`, `'A.B'` , `'Z.Y.X'`|\n *\n * ### Double star (`**`)\n *\n * A double star (`'**'`) is a wildcard that matches *zero or more segments*\n *\n * | Glob |Matches states named |Does not match state named |\n * |:------------|:----------------------------------------------|:----------------------------------|\n * | `'**'` | `'A'` , `'A.B'`, `'Z.Y.X'` | (matches all states) |\n * | `'A.**'` | `'A'` , `'A.B'` , `'A.C.X'` | `'Z.Y.X'` |\n * | `'**.X'` | `'X'` , `'A.X'` , `'Z.Y.X'` | `'A'` , `'A.login.Z'` |\n * | `'A.**.X'` | `'A.X'` , `'A.B.X'` , `'A.B.C.X'` | `'A'` , `'A.B.C'` |\n *\n */\nexport class Glob {\n text: string;\n glob: Array;\n regexp: RegExp;\n\n /** Returns true if the string has glob-like characters in it */\n static is(text: string) {\n return !!/[!,*]+/.exec(text);\n }\n\n /** Returns a glob from the string, or null if the string isn't Glob-like */\n static fromString(text: string) {\n return Glob.is(text) ? new Glob(text) : null;\n }\n\n constructor(text: string) {\n this.text = text;\n this.glob = text.split('.');\n\n const regexpString = this.text\n .split('.')\n .map(seg => {\n if (seg === '**') return '(?:|(?:\\\\.[^.]*)*)';\n if (seg === '*') return '\\\\.[^.]*';\n return '\\\\.' + seg;\n })\n .join('');\n\n this.regexp = new RegExp('^' + regexpString + '$');\n }\n\n matches(name: string) {\n return this.regexp.test('.' + name);\n }\n}\n", + "/**\n * @coreapi\n * @module state\n */\n/** for typedoc */\nimport { StateDeclaration, _ViewDeclaration, _StateDeclaration, LazyLoadResult } from './interface';\nimport { defaults, values, find, inherit } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { Param } from '../params/param';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { TargetState } from './targetState';\nimport { Transition } from '../transition/transition';\nimport { Glob } from '../common/glob';\nimport { isObject, isFunction } from '../common/predicates';\n\n/**\n * Internal representation of a UI-Router state.\n *\n * Instances of this class are created when a [[StateDeclaration]] is registered with the [[StateRegistry]].\n *\n * A registered [[StateDeclaration]] is augmented with a getter ([[StateDeclaration.$$state]]) which returns the corresponding [[StateObject]] object.\n *\n * This class prototypally inherits from the corresponding [[StateDeclaration]].\n * Each of its own properties (i.e., `hasOwnProperty`) are built using builders from the [[StateBuilder]].\n */\nexport class StateObject {\n /** The parent [[StateObject]] */\n public parent: StateObject;\n\n /** The name used to register the state */\n public name: string;\n\n /** Prototypally inherits from [[StateDeclaration.abstract]] */\n public abstract: boolean;\n\n /** Prototypally inherits from [[StateDeclaration.resolve]] */\n public resolve: { [key: string]: string | any[] | Function } | any[];\n\n /** A list of [[Resolvable]] objects. The internal representation of [[resolve]]. */\n public resolvables: Resolvable[];\n\n /** Prototypally inherits from [[StateDeclaration.resolvePolicy]] */\n public resolvePolicy: any;\n\n /** A compiled URLMatcher which detects when the state's URL is matched */\n public url: UrlMatcher;\n\n /** The parameters for the state, built from the URL and [[StateDeclaration.params]] */\n public params: { [key: string]: Param };\n\n /**\n * The views for the state.\n * Note: `@uirouter/core` does not register a builder for views.\n * The framework specific code should register a `views` builder.\n */\n public views: { [key: string]: _ViewDeclaration };\n\n /**\n * The original [[StateDeclaration]] used to build this [[StateObject]].\n * Note: `this` object also prototypally inherits from the `self` declaration object.\n */\n public self: StateDeclaration;\n\n /** The nearest parent [[StateObject]] which has a URL */\n public navigable: StateObject;\n\n /** The parent [[StateObject]] objects from this state up to the root */\n public path: StateObject[];\n\n /**\n * Prototypally inherits from [[StateDeclaration.data]]\n * Note: This is the only field on the [[StateDeclaration]] which is mutated.\n * The definition object's `data` field is replaced with a new object\n * which prototypally inherits from the parent state definition's `data` field.\n */\n public data: any;\n\n /**\n * An object containing the parent States' names as keys and\n * true as their values.\n */\n public includes: { [name: string]: boolean };\n\n /** Prototypally inherits from [[StateDeclaration.onExit]] */\n public onExit: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onRetain]] */\n public onRetain: TransitionStateHookFn;\n /** Prototypally inherits from [[StateDeclaration.onEnter]] */\n public onEnter: TransitionStateHookFn;\n\n /** Prototypally inherits from [[StateDeclaration.lazyLoad]] */\n public lazyLoad: (transition: Transition, state: StateDeclaration) => Promise;\n\n /** Prototypally inherits from [[StateDeclaration.redirectTo]] */\n redirectTo:\n | string\n | (($transition$: Transition) => TargetState)\n | { state: string | StateDeclaration; params: { [key: string]: any } };\n\n /** @hidden */\n __stateObjectCache: {\n /** Might be null */\n nameGlob?: Glob;\n };\n\n /**\n * Create a state object to put the private/internal implementation details onto.\n * The object's prototype chain looks like:\n * (Internal State Object) -> (Copy of State.prototype) -> (State Declaration object) -> (State Declaration's prototype...)\n *\n * @param stateDecl the user-supplied State Declaration\n * @returns {StateObject} an internal State object\n */\n static create(stateDecl: _StateDeclaration): StateObject {\n stateDecl = StateObject.isStateClass(stateDecl) ? new stateDecl() : stateDecl;\n\n const state = inherit(inherit(stateDecl, StateObject.prototype)) as StateObject;\n stateDecl.$$state = () => state;\n state.self = stateDecl;\n state.__stateObjectCache = {\n nameGlob: Glob.fromString(state.name), // might return null\n };\n return state;\n }\n\n /** Predicate which returns true if the object is an class with @State() decorator */\n static isStateClass = (stateDecl: _StateDeclaration): stateDecl is { new (): StateDeclaration } =>\n isFunction(stateDecl) && stateDecl['__uiRouterState'] === true;\n\n /** Predicate which returns true if the object is an internal [[StateObject]] object */\n static isState = (obj: any): obj is StateObject => isObject(obj['__stateObjectCache']);\n\n /** @deprecated use State.create() */\n constructor(config?: StateDeclaration) {\n return StateObject.create(config || {});\n }\n\n /**\n * Returns true if the provided parameter is the same state.\n *\n * Compares the identity of the state against the passed value, which is either an object\n * reference to the actual `State` instance, the original definition object passed to\n * `$stateProvider.state()`, or the fully-qualified name.\n *\n * @param ref Can be one of (a) a `State` instance, (b) an object that was passed\n * into `$stateProvider.state()`, (c) the fully-qualified name of a state as a string.\n * @returns Returns `true` if `ref` matches the current `State` instance.\n */\n is(ref: StateObject | StateDeclaration | string): boolean {\n return this === ref || this.self === ref || this.fqn() === ref;\n }\n\n /**\n * @deprecated this does not properly handle dot notation\n * @returns Returns a dot-separated name of the state.\n */\n fqn(): string {\n if (!this.parent || !(this.parent instanceof this.constructor)) return this.name;\n const name = this.parent.fqn();\n return name ? name + '.' + this.name : this.name;\n }\n\n /**\n * Returns the root node of this state's tree.\n *\n * @returns The root of this state's tree.\n */\n root(): StateObject {\n return (this.parent && this.parent.root()) || this;\n }\n\n /**\n * Gets the state's `Param` objects\n *\n * Gets the list of [[Param]] objects owned by the state.\n * If `opts.inherit` is true, it also includes the ancestor states' [[Param]] objects.\n * If `opts.matchingKeys` exists, returns only `Param`s whose `id` is a key on the `matchingKeys` object\n *\n * @param opts options\n */\n parameters(opts?: { inherit?: boolean; matchingKeys?: any }): Param[] {\n opts = defaults(opts, { inherit: true, matchingKeys: null });\n const inherited = (opts.inherit && this.parent && this.parent.parameters()) || [];\n return inherited\n .concat(values(this.params))\n .filter(param => !opts.matchingKeys || opts.matchingKeys.hasOwnProperty(param.id));\n }\n\n /**\n * Returns a single [[Param]] that is owned by the state\n *\n * If `opts.inherit` is true, it also searches the ancestor states` [[Param]]s.\n * @param id the name of the [[Param]] to return\n * @param opts options\n */\n parameter(id: string, opts: { inherit?: boolean } = {}): Param {\n return (\n (this.url && this.url.parameter(id, opts)) ||\n find(values(this.params), propEq('id', id)) ||\n (opts.inherit && this.parent && this.parent.parameter(id))\n );\n }\n\n toString() {\n return this.fqn();\n }\n}\n", + "/** Predicates\n *\n * These predicates return true/false based on the input.\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_predicates\n */\n/** */\nimport { and, not, pipe, prop, or } from './hof';\nimport { Predicate } from './common'; // has or is using\nimport { StateObject } from '../state/stateObject';\n\nconst toStr = Object.prototype.toString;\nconst tis = (t: string) => (x: any) => typeof x === t;\nexport const isUndefined = tis('undefined');\nexport const isDefined = not(isUndefined);\nexport const isNull = (o: any) => o === null;\nexport const isNullOrUndefined = or(isNull, isUndefined);\nexport const isFunction: (x: any) => x is Function = tis('function');\nexport const isNumber: (x: any) => x is number = tis('number');\nexport const isString = <(x: any) => x is string>tis('string');\nexport const isObject = (x: any) => x !== null && typeof x === 'object';\nexport const isArray = Array.isArray;\nexport const isDate: (x: any) => x is Date = ((x: any) => toStr.call(x) === '[object Date]');\nexport const isRegExp: (x: any) => x is RegExp = ((x: any) => toStr.call(x) === '[object RegExp]');\nexport const isState: (x: any) => x is StateObject = StateObject.isState;\n\n/**\n * Predicate which checks if a value is injectable\n *\n * A value is \"injectable\" if it is a function, or if it is an ng1 array-notation-style array\n * where all the elements in the array are Strings, except the last one, which is a Function\n */\nexport function isInjectable(val: any) {\n if (isArray(val) && val.length) {\n const head = val.slice(0, -1),\n tail = val.slice(-1);\n return !(head.filter(not(isString)).length || tail.filter(not(isFunction)).length);\n }\n return isFunction(val);\n}\n\n/**\n * Predicate which checks if a value looks like a Promise\n *\n * It is probably a Promise if it's an object, and it has a `then` property which is a Function\n */\nexport const isPromise = <(x: any) => x is Promise>and(isObject, pipe(prop('then'), isFunction));\n", "/**\n * This module is a stub for core services such as Dependency Injection or Browser Location.\n * Core services may be implemented by a specific framework, such as ng1 or ng2, or be pure javascript.\n *\n * @module common\n */\n/** for typedoc */\nimport { IInjectable, Obj } from './common';\nimport { Disposable } from '../interface';\nimport { UrlParts } from '../url/interface';\n\nexport let notImplemented = (fnname: string) => () => {\n throw new Error(`${fnname}(): No coreservices implementation for UI-Router is loaded.`);\n};\n\nconst services: CoreServices = {\n $q: undefined,\n $injector: undefined,\n};\n\nexport interface $QLikeDeferred {\n resolve: (val?: any) => void;\n reject: (reason?: any) => void;\n promise: Promise;\n}\n\nexport interface $QLike {\n when(value?: T | PromiseLike): Promise;\n reject(reason: any): Promise;\n defer(): $QLikeDeferred;\n all(promises: { [key: string]: Promise }): Promise;\n all(promises: Promise[]): Promise;\n}\n\nexport interface $InjectorLike {\n strictDi?: boolean;\n get(token: any): any;\n get(token: any): T;\n has(token: any): boolean;\n invoke(fn: IInjectable, context?: any, locals?: Obj): any;\n annotate(fn: IInjectable, strictDi?: boolean): any[];\n}\n\nexport interface CoreServices {\n $q: $QLike;\n $injector: $InjectorLike;\n}\n\nexport interface LocationServices extends Disposable {\n /**\n * Gets the current url string\n *\n * The URL is normalized using the internal [[path]]/[[search]]/[[hash]] values.\n *\n * For example, the URL may be stored in the hash ([[HashLocationServices]]) or\n * have a base HREF prepended ([[PushStateLocationServices]]).\n *\n * The raw URL in the browser might be:\n *\n * ```\n * http://mysite.com/somepath/index.html#/internal/path/123?param1=foo#anchor\n * ```\n *\n * or\n *\n * ```\n * http://mysite.com/basepath/internal/path/123?param1=foo#anchor\n * ```\n *\n * then this method returns:\n *\n * ```\n * /internal/path/123?param1=foo#anchor\n * ```\n *\n *\n * #### Example:\n * ```js\n * locationServices.url(); // \"/some/path?query=value#anchor\"\n * ```\n *\n * @returns the current value of the url, as a string.\n */\n url(): string;\n\n /**\n * Updates the url, or gets the current url\n *\n * Updates the url, changing it to the value in `newurl`\n *\n * #### Example:\n * ```js\n * locationServices.url(\"/some/path?query=value#anchor\", true);\n * ```\n *\n * @param newurl The new value for the URL.\n * This url should reflect only the new internal [[path]], [[search]], and [[hash]] values.\n * It should not include the protocol, site, port, or base path of an absolute HREF.\n * @param replace When true, replaces the current history entry (instead of appending it) with this new url\n * @param state The history's state object, i.e., pushState (if the LocationServices implementation supports it)\n * @return the url (after potentially being processed)\n */\n url(newurl: string, replace?: boolean, state?: any): string;\n\n /**\n * Gets the path part of the current url\n *\n * If the current URL is `/some/path?query=value#anchor`, this returns `/some/path`\n *\n * @return the path portion of the url\n */\n path(): string;\n\n /**\n * Gets the search part of the current url as an object\n *\n * If the current URL is `/some/path?query=value#anchor`, this returns `{ query: 'value' }`\n *\n * @return the search (querystring) portion of the url, as an object\n */\n search(): { [key: string]: any };\n\n /**\n * Gets the hash part of the current url\n *\n * If the current URL is `/some/path?query=value#anchor`, this returns `anchor`\n *\n * @return the hash (anchor) portion of the url\n */\n hash(): string;\n\n /**\n * Registers a url change handler\n *\n * #### Example:\n * ```js\n * let deregisterFn = locationServices.onChange((evt) => console.log(\"url change\", evt));\n * ```\n *\n * @param callback a function that will be called when the url is changing\n * @return a function that de-registers the callback\n */\n onChange(callback: Function): Function;\n}\n\n/**\n * This service returns the location configuration\n *\n * This service returns information about the location configuration.\n * This service is primarily used when building URLs (e.g., for `hrefs`)\n */\nexport interface LocationConfig extends Disposable {\n /**\n * Gets the port, e.g., `80`\n *\n * @return the port number\n */\n port(): number;\n /**\n * Gets the protocol, e.g., `http`\n *\n * @return the protocol\n */\n protocol(): string;\n /**\n * Gets the host, e.g., `localhost`\n *\n * @return the protocol\n */\n host(): string;\n /**\n * Gets the base Href, e.g., `http://localhost/approot/`\n *\n * @return the application's base href\n */\n baseHref(): string;\n /**\n * Returns true when running in pushstate mode\n *\n * @return true when running in pushstate mode\n */\n html5Mode(): boolean;\n /**\n * Gets the hashPrefix (when not running in pushstate mode)\n *\n * If the current url is `http://localhost/app#!/uirouter/path/#anchor`, it returns `!` which is the prefix for the \"hashbang\" portion.\n *\n * @return the hash prefix\n */\n hashPrefix(): string;\n /**\n * Sets the hashPrefix (when not running in pushstate mode)\n *\n * @return the new hash prefix\n */\n hashPrefix(newprefix: string): string;\n}\n\nexport { services };\n", - "/**\n * Random utility functions used in the UI-Router code\n *\n * These functions are exported, but are subject to change without notice.\n *\n * @preferred\n * @module common\n */\n/** for typedoc */\nimport { isFunction, isString, isArray, isRegExp, isDate } from './predicates';\nimport { all, any, prop, curry, not } from './hof';\nimport { services } from './coreservices';\nimport { StateObject } from '../state/stateObject';\n\ndeclare const global;\nexport const root: any = (typeof self === 'object' && self.self === self && self) ||\n (typeof global === 'object' && global.global === global && global) || this;\nconst angular = root.angular || {};\n\nexport const fromJson = angular.fromJson || JSON.parse.bind(JSON);\nexport const toJson = angular.toJson || JSON.stringify.bind(JSON);\nexport const forEach = angular.forEach || _forEach;\nexport const extend = Object.assign || _extend;\nexport const equals = angular.equals || _equals;\nexport function identity(x: any) { return x; }\nexport function noop(): any {}\n\nexport type Mapper = (x: X, key?: (string|number)) => T;\nexport interface TypedMap { [key: string]: T; }\nexport type Predicate = (x?: X) => boolean;\n/**\n * An ng1-style injectable\n *\n * This could be a (non-minified) function such as:\n * ```js\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an explicitly annotated function (minify safe)\n * ```js\n * injectableFunction.$inject = [ 'SomeDependency' ];\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an array style annotated function (minify safe)\n * ```js\n * ['SomeDependency', function injectableFunction(SomeDependency) {\n *\n * }];\n * ```\n *\n * @publicapi\n */\nexport type IInjectable = (Function|any[]);\n\nexport interface Obj extends Object {\n [key: string]: any;\n}\n\n/**\n * Builds proxy functions on the `to` object which pass through to the `from` object.\n *\n * For each key in `fnNames`, creates a proxy function on the `to` object.\n * The proxy function calls the real function on the `from` object.\n *\n *\n * #### Example:\n * This example creates an new class instance whose functions are prebound to the new'd object.\n * ```js\n * class Foo {\n * constructor(data) {\n * // Binds all functions from Foo.prototype to 'this',\n * // then copies them to 'this'\n * bindFunctions(Foo.prototype, this, this);\n * this.data = data;\n * }\n *\n * log() {\n * console.log(this.data);\n * }\n * }\n *\n * let myFoo = new Foo([1,2,3]);\n * var logit = myFoo.log;\n * logit(); // logs [1, 2, 3] from the myFoo 'this' instance\n * ```\n *\n * #### Example:\n * This example creates a bound version of a service function, and copies it to another object\n * ```\n *\n * var SomeService = {\n * this.data = [3, 4, 5];\n * this.log = function() {\n * console.log(this.data);\n * }\n * }\n *\n * // Constructor fn\n * function OtherThing() {\n * // Binds all functions from SomeService to SomeService,\n * // then copies them to 'this'\n * bindFunctions(SomeService, this, SomeService);\n * }\n *\n * let myOtherThing = new OtherThing();\n * myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'\n * ```\n *\n * @param source A function that returns the source object which contains the original functions to be bound\n * @param target A function that returns the target object which will receive the bound functions\n * @param bind A function that returns the object which the functions will be bound to\n * @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object)\n * @param latebind If true, the binding of the function is delayed until the first time it's invoked\n */\nexport function createProxyFunctions(source: Function, target: Obj, bind: Function, fnNames?: string[], latebind = false): Obj {\n const bindFunction = (fnName) =>\n source()[fnName].bind(bind());\n\n const makeLateRebindFn = fnName => function lateRebindFunction() {\n target[fnName] = bindFunction(fnName);\n return target[fnName].apply(null, arguments);\n };\n\n fnNames = fnNames || Object.keys(source());\n\n return fnNames.reduce((acc, name) => {\n acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name);\n return acc;\n }, target);\n}\n\n\n/**\n * prototypal inheritance helper.\n * Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it\n */\nexport const inherit = (parent: Obj, extra?: Obj) =>\n extend(Object.create(parent), extra);\n\n/** Given an array, returns true if the object is found in the array, (using indexOf) */\nexport const inArray: typeof _inArray = curry(_inArray) as any;\nexport function _inArray(array: any[], obj: any): boolean;\nexport function _inArray(array: any[]): (obj: any) => boolean;\nexport function _inArray(array, obj?): any {\n return array.indexOf(obj) !== -1;\n}\n\n/**\n * Given an array, and an item, if the item is found in the array, it removes it (in-place).\n * The same array is returned\n */\nexport const removeFrom: typeof _removeFrom = curry(_removeFrom) as any;\nexport function _removeFrom(array: T[], obj: T): T[];\nexport function _removeFrom(array: T[]): (obj: T) => T[];\nexport function _removeFrom(array, obj?) {\n const idx = array.indexOf(obj);\n if (idx >= 0) array.splice(idx, 1);\n return array;\n}\n\n/** pushes a values to an array and returns the value */\nexport const pushTo: typeof _pushTo = curry(_pushTo) as any;\nexport function _pushTo(arr: T[], val: T): T ;\nexport function _pushTo(arr: T[]): (val: T) => T ;\nexport function _pushTo(arr, val?): any {\n return (arr.push(val), val);\n}\n\n/** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */\nexport const deregAll = (functions: Function[]) =>\n functions.slice().forEach(fn => {\n typeof fn === 'function' && fn();\n removeFrom(functions, fn);\n });\n/**\n * Applies a set of defaults to an options object. The options object is filtered\n * to only those properties of the objects in the defaultsList.\n * Earlier objects in the defaultsList take precedence when applying defaults.\n */\nexport function defaults(opts, ...defaultsList: Obj[]) {\n const _defaultsList = defaultsList.concat({}).reverse();\n const defaultVals = extend.apply(null, _defaultsList);\n return extend({}, defaultVals, pick(opts || {}, Object.keys(defaultVals)));\n}\n\n/** Reduce function that merges each element of the list into a single object, using extend */\nexport const mergeR = (memo: Obj, item: Obj) => extend(memo, item);\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nexport function ancestors(first: StateObject, second: StateObject) {\n const path: StateObject[] = [];\n\n for (const n in first.path) { // tslint:disable-line:forin\n if (first.path[n] !== second.path[n]) break;\n path.push(first.path[n]);\n }\n return path;\n}\n\n/**\n * Return a copy of the object only containing the whitelisted properties.\n *\n * #### Example:\n * ```\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the whitelisted property names\n */\nexport function pick(obj: Obj, propNames: string[]): Obj {\n const objCopy = {};\n for (const _prop in obj) {\n if (propNames.indexOf(_prop) !== -1) {\n objCopy[_prop] = obj[_prop];\n }\n }\n return objCopy;\n}\n\n/**\n * Return a copy of the object omitting the blacklisted properties.\n *\n * @example\n * ```\n *\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = omit(foo, ['a', 'b']); // { c: 3 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the blacklisted property names\n */\nexport function omit(obj: Obj, propNames: string[]): Obj {\n return Object.keys(obj)\n .filter(not(inArray(propNames)))\n .reduce((acc, key) => (acc[key] = obj[key], acc), {});\n}\n\n\n/** Given an array of objects, maps each element to a named property of the element. */\nexport function pluck(collection: Obj[], propName: string): T[];\n/** Given an object, maps each property of the object to a named property of the property. */\nexport function pluck(collection: { [key: string]: any }, propName: string): { [key: string]: any };\n/**\n * Maps an array, or object to a property (by name)\n */\nexport function pluck(collection: any, propName: string): any {\n return map(collection, > prop(propName));\n}\n\n\n/** Given an array of objects, returns a new array containing only the elements which passed the callback predicate */\nexport function filter(collection: T[], callback: (t: T, key?: number) => boolean): T[];\n/** Given an object, returns a new object with only those properties that passed the callback predicate */\nexport function filter(collection: TypedMap, callback: (t: T, key?: string) => boolean): TypedMap;\n/** Filters an Array or an Object's properties based on a predicate */\nexport function filter(collection: any, callback: Function): T {\n const arr = isArray(collection), result: any = arr ? [] : {};\n const accept = arr ? x => result.push(x) : (x, key) => result[key] = x;\n forEach(collection, function(item, i) {\n if (callback(item, i)) accept(item, i);\n });\n return result;\n}\n\n\n/** Given an object, return the first property of that object which passed the callback predicate */\nexport function find(collection: TypedMap, callback: Predicate): T;\n/** Given an array of objects, returns the first object which passed the callback predicate */\nexport function find(collection: T[], callback: Predicate): T;\n/** Finds an object from an array, or a property of an object, that matches a predicate */\nexport function find(collection: any, callback: any) {\n let result;\n\n forEach(collection, function(item, i) {\n if (result) return;\n if (callback(item, i)) result = item;\n });\n\n return result;\n}\n\n/** Given an object, returns a new object, where each property is transformed by the callback function */\nexport let mapObj: (collection: { [key: string]: T }, callback: Mapper, target?: typeof collection) => { [key: string]: U } = map;\n/** Given an array, returns a new array, where each element is transformed by the callback function */\nexport function map(collection: T[], callback: Mapper, target?: typeof collection): U[];\nexport function map(collection: { [key: string]: T }, callback: Mapper, target?: typeof collection): { [key: string]: U };\n/** Maps an array or object properties using a callback function */\nexport function map(collection: any, callback: any, target: typeof collection): any {\n target = target || (isArray(collection) ? [] : {});\n forEach(collection, (item, i) => target[i] = callback(item, i));\n return target;\n}\n\n/**\n * Given an object, return its enumerable property values\n *\n * @example\n * ```\n *\n * let foo = { a: 1, b: 2, c: 3 }\n * let vals = values(foo); // [ 1, 2, 3 ]\n * ```\n */\nexport const values: ( (obj: TypedMap) => T[]) = (obj: Obj) =>\n Object.keys(obj).map(key => obj[key]);\n\n/**\n * Reduce function that returns true if all of the values are truthy.\n *\n * @example\n * ```\n *\n * let vals = [ 1, true, {}, \"hello world\"];\n * vals.reduce(allTrueR, true); // true\n *\n * vals.push(0);\n * vals.reduce(allTrueR, true); // false\n * ```\n */\nexport const allTrueR = (memo: boolean, elem: any) => memo && elem;\n\n/**\n * Reduce function that returns true if any of the values are truthy.\n *\n * * @example\n * ```\n *\n * let vals = [ 0, null, undefined ];\n * vals.reduce(anyTrueR, true); // false\n *\n * vals.push(\"hello world\");\n * vals.reduce(anyTrueR, true); // true\n * ```\n */\nexport const anyTrueR = (memo: boolean, elem: any) => memo || elem;\n\n/**\n * Reduce function which un-nests a single level of arrays\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnestR = (memo: any[], elem: any[]) => memo.concat(elem);\n\n/**\n * Reduce function which recursively un-nests all arrays\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flattenR = (memo: any[], elem: any) =>\n isArray(elem) ? memo.concat(elem.reduce(flattenR, [])) : pushR(memo, elem);\n\n/**\n * Reduce function that pushes an object to an array, then returns the array.\n * Mostly just for [[flattenR]] and [[uniqR]]\n */\nexport function pushR(arr: any[], obj: any) {\n arr.push(obj);\n return arr;\n}\n\n/** Reduce function that filters out duplicates */\nexport const uniqR = (acc: T[], token: T): T[] =>\n inArray(acc, token) ? acc : pushR(acc, token);\n\n/**\n * Return a new array with a single level of arrays unnested.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * unnest(input) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnest = (arr: any[]) => arr.reduce(unnestR, []);\n/**\n * Return a completely flattened version of an array.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * flatten(input) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flatten = (arr: any[]) => arr.reduce(flattenR, []);\n\n/**\n * Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.\n * @example\n * ```\n *\n * let isNumber = (obj) => typeof(obj) === 'number';\n * let allNumbers = [ 1, 2, 3, 4, 5 ];\n * allNumbers.filter(assertPredicate(isNumber)); //OK\n *\n * let oneString = [ 1, 2, 3, 4, \"5\" ];\n * oneString.filter(assertPredicate(isNumber, \"Not all numbers\")); // throws Error(\"\"Not all numbers\"\");\n * ```\n */\nexport const assertPredicate: (predicate: Predicate, errMsg: (string|Function)) => Predicate = assertFn;\n/**\n * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.\n * @example\n * ```\n *\n * var data = { foo: 1, bar: 2 };\n *\n * let keys = [ 'foo', 'bar' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // values is [1, 2]\n *\n * let keys = [ 'foo', 'bar', 'baz' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // throws Error(\"Key not found\")\n * ```\n */\nexport const assertMap: (mapFn: (t: T) => U, errMsg: (string|Function)) => (t: T) => U = assertFn;\nexport function assertFn(predicateOrMap: Function, errMsg: (string|Function) = 'assert failure'): any {\n return (obj) => {\n const result = predicateOrMap(obj);\n if (!result) {\n throw new Error(isFunction(errMsg) ? ( errMsg)(obj) : errMsg);\n }\n return result;\n };\n}\n\n/**\n * Like _.pairs: Given an object, returns an array of key/value pairs\n *\n * @example\n * ```\n *\n * pairs({ foo: \"FOO\", bar: \"BAR }) // [ [ \"foo\", \"FOO\" ], [ \"bar\": \"BAR\" ] ]\n * ```\n */\nexport const pairs = (obj: Obj) =>\n Object.keys(obj).map(key => [ key, obj[key]] );\n\n/**\n * Given two or more parallel arrays, returns an array of tuples where\n * each tuple is composed of [ a[i], b[i], ... z[i] ]\n *\n * @example\n * ```\n *\n * let foo = [ 0, 2, 4, 6 ];\n * let bar = [ 1, 3, 5, 7 ];\n * let baz = [ 10, 30, 50, 70 ];\n * arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]\n * arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]\n * ```\n */\nexport function arrayTuples(...args: any[]): any[] {\n if (args.length === 0) return [];\n const maxArrayLen = args.reduce((min, arr) => Math.min(arr.length, min), 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER\n const result = [];\n\n for (let i = 0; i < maxArrayLen; i++) {\n // This is a hot function\n // Unroll when there are 1-4 arguments\n switch (args.length) {\n case 1: result.push([args[0][i]]); break;\n case 2: result.push([args[0][i], args[1][i]]); break;\n case 3: result.push([args[0][i], args[1][i], args[2][i]]); break;\n case 4: result.push([args[0][i], args[1][i], args[2][i], args[3][i]]); break;\n default:\n result.push(args.map(array => array[i])); break;\n }\n }\n\n return result;\n}\n\n/**\n * Reduce function which builds an object from an array of [key, value] pairs.\n *\n * Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.\n *\n * Each keyValueTuple should be an array with values [ key: string, value: any ]\n *\n * @example\n * ```\n *\n * var pairs = [ [\"fookey\", \"fooval\"], [\"barkey\", \"barval\"] ]\n *\n * var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n *\n * // Or, more simply:\n * var pairsToObj = pairs.reduce(applyPairs, {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n * ```\n */\nexport function applyPairs(memo: TypedMap, keyValTuple: any[]) {\n let key: string, value: any;\n if (isArray(keyValTuple)) [key, value] = keyValTuple;\n if (!isString(key)) throw new Error('invalid parameters to applyPairs');\n memo[key] = value;\n return memo;\n}\n\n/** Get the last element of an array */\nexport function tail(arr: T[]): T {\n return arr.length && arr[arr.length - 1] || undefined;\n}\n\n/**\n * shallow copy from src to dest\n */\nexport function copy(src: Obj, dest?: Obj) {\n if (dest) Object.keys(dest).forEach(key => delete dest[key]);\n if (!dest) dest = {};\n return extend(dest, src);\n}\n\n/** Naive forEach implementation works with Objects or Arrays */\nfunction _forEach(obj: (any[]|any), cb: (el, idx?) => void, _this: Obj) {\n if (isArray(obj)) return obj.forEach(cb, _this);\n Object.keys(obj).forEach(key => cb(obj[key], key));\n}\n\n/** Like Object.assign() */\nexport function _extend(toObj: Obj, ...fromObjs: Obj[]): any;\nexport function _extend(toObj: Obj): any {\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n if (!obj) continue;\n const keys = Object.keys(obj);\n\n for (let j = 0; j < keys.length; j++) {\n toObj[keys[j]] = obj[keys[j]];\n }\n }\n\n return toObj;\n}\n\nfunction _equals(o1: any, o2: any): boolean {\n if (o1 === o2) return true;\n if (o1 === null || o2 === null) return false;\n if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n const t1 = typeof o1, t2 = typeof o2;\n if (t1 !== t2 || t1 !== 'object') return false;\n\n const tup = [o1, o2];\n if (all(isArray)(tup)) return _arraysEq(o1, o2);\n if (all(isDate)(tup)) return o1.getTime() === o2.getTime();\n if (all(isRegExp)(tup)) return o1.toString() === o2.toString();\n if (all(isFunction)(tup)) return true; // meh\n\n const predicates = [isFunction, isArray, isDate, isRegExp];\n if (predicates.map(any).reduce((b, fn) => b || !!fn(tup), false)) return false;\n\n const keys: { [i: string]: boolean } = {};\n for (const key in o1) { // tslint:disable-line:forin\n if (!_equals(o1[key], o2[key])) return false;\n keys[key] = true;\n }\n for (const key in o2) {\n if (!keys[key]) return false;\n }\n\n return true;\n}\n\nfunction _arraysEq(a1: any[], a2: any[]) {\n if (a1.length !== a2.length) return false;\n return arrayTuples(a1, a2).reduce((b, t) => b && _equals(t[0], t[1]), true);\n}\n\n// issue #2676\nexport const silenceUncaughtInPromise = (promise: Promise) =>\n promise.catch(e => 0) && promise;\nexport const silentRejection = (error: any) =>\n silenceUncaughtInPromise(services.$q.reject(error));\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n'use strict';\nimport { extend, silentRejection } from '../common/common';\nimport { stringify } from '../common/strings';\nimport { is } from '../common/hof';\n\nexport enum RejectType {\n SUPERSEDED = 2, ABORTED = 3, INVALID = 4, IGNORED = 5, ERROR = 6,\n}\n\n/** @hidden */\nlet id = 0;\n\nexport class Rejection {\n $id = id++;\n type: number;\n message: string;\n detail: any;\n redirected: boolean;\n\n /** Returns true if the obj is a rejected promise created from the `asPromise` factory */\n static isRejectionPromise(obj: any): boolean {\n return obj && (typeof obj.then === 'function') && is(Rejection)(obj._transitionRejection);\n }\n\n /** Returns a Rejection due to transition superseded */\n static superseded(detail?: any, options?: any): Rejection {\n const message = 'The transition has been superseded by a different transition';\n const rejection = new Rejection(RejectType.SUPERSEDED, message, detail);\n if (options && options.redirected) {\n rejection.redirected = true;\n }\n return rejection;\n }\n\n /** Returns a Rejection due to redirected transition */\n static redirected(detail?: any): Rejection {\n return Rejection.superseded(detail, { redirected: true });\n }\n\n /** Returns a Rejection due to invalid transition */\n static invalid(detail?: any): Rejection {\n const message = 'This transition is invalid';\n return new Rejection(RejectType.INVALID, message, detail);\n }\n\n /** Returns a Rejection due to ignored transition */\n static ignored(detail?: any): Rejection {\n const message = 'The transition was ignored';\n return new Rejection(RejectType.IGNORED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static aborted(detail?: any): Rejection {\n const message = 'The transition has been aborted';\n return new Rejection(RejectType.ABORTED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static errored(detail?: any): Rejection {\n const message = 'The transition errored';\n return new Rejection(RejectType.ERROR, message, detail);\n }\n\n /**\n * Returns a Rejection\n *\n * Normalizes a value as a Rejection.\n * If the value is already a Rejection, returns it.\n * Otherwise, wraps and returns the value as a Rejection (Rejection type: ERROR).\n *\n * @returns `detail` if it is already a `Rejection`, else returns an ERROR Rejection.\n */\n static normalize(detail?: Rejection | Error | any): Rejection {\n return is(Rejection)(detail) ? detail : Rejection.errored(detail);\n }\n\n constructor(type: number, message?: string, detail?: any) {\n this.type = type;\n this.message = message;\n this.detail = detail;\n }\n\n toString() {\n const detailString = (d: any) =>\n d && d.toString !== Object.prototype.toString ? d.toString() : stringify(d);\n const detail = detailString(this.detail);\n const { $id, type, message } = this;\n return `Transition Rejection($id: ${$id} type: ${type}, message: ${message}, detail: ${detail})`;\n }\n\n toPromise(): Promise {\n return extend(silentRejection(this), { _transitionRejection: this });\n }\n}\n", - "/** @module common */\nimport { pushTo } from './common';\n\nexport class Queue {\n private _evictListeners: ((item: T) => void)[] = [];\n public onEvict = pushTo(this._evictListeners);\n\n constructor(private _items: T[] = [], private _limit: number = null) { }\n\n enqueue(item: T) {\n const items = this._items;\n items.push(item);\n if (this._limit && items.length > this._limit) this.evict();\n return item;\n }\n\n evict(): T {\n const item: T = this._items.shift();\n this._evictListeners.forEach(fn => fn(item));\n return item;\n }\n\n dequeue(): T {\n if (this.size())\n return this._items.splice(0, 1)[0];\n }\n\n clear(): Array {\n const current = this._items;\n this._items = [];\n return current;\n }\n\n size(): number {\n return this._items.length;\n }\n\n remove(item: T) {\n const idx = this._items.indexOf(item);\n return idx > -1 && this._items.splice(idx, 1)[0];\n }\n\n peekTail(): T {\n return this._items[this._items.length - 1];\n }\n\n peekHead(): T {\n if (this.size())\n return this._items[0];\n }\n}\n", - "/**\n * # Transition tracing (debug)\n *\n * Enable transition tracing to print transition information to the console,\n * in order to help debug your application.\n * Tracing logs detailed information about each Transition to your console.\n *\n * To enable tracing, import the [[Trace]] singleton and enable one or more categories.\n *\n * ### ES6\n * ```js\n * import {trace} from \"ui-router-ng2\"; // or \"angular-ui-router\"\n * trace.enable(1, 5); // TRANSITION and VIEWCONFIG\n * ```\n *\n * ### CJS\n * ```js\n * let trace = require(\"angular-ui-router\").trace; // or \"ui-router-ng2\"\n * trace.enable(\"TRANSITION\", \"VIEWCONFIG\");\n * ```\n *\n * ### Globals\n * ```js\n * let trace = window[\"angular-ui-router\"].trace; // or \"ui-router-ng2\"\n * trace.enable(); // Trace everything (very verbose)\n * ```\n *\n * ### Angular 1:\n * ```js\n * app.run($trace => $trace.enable());\n * ```\n *\n * @coreapi\n * @module trace\n */\n/* tslint:disable:no-console */\nimport { parse } from '../common/hof';\nimport { isFunction, isNumber } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { ViewTuple } from '../view';\nimport { ActiveUIView, ViewConfig, ViewContext } from '../view/interface';\nimport { stringify, functionToString, maxLength, padString } from './strings';\nimport { Resolvable } from '../resolve/resolvable';\nimport { PathNode } from '../path/pathNode';\nimport { PolicyWhen } from '../resolve/interface';\nimport { TransitionHook } from '../transition/transitionHook';\nimport { HookResult } from '../transition/interface';\nimport { StateObject } from '../state/stateObject';\n\n/** @hidden */\nfunction uiViewString (uiview: ActiveUIView) {\n if (!uiview) return 'ui-view (defunct)';\n const state = uiview.creationContext ? uiview.creationContext.name || '(root)' : '(none)';\n return `[ui-view#${uiview.id} ${uiview.$type}:${uiview.fqn} (${uiview.name}@${state})]`;\n}\n\n/** @hidden */\nconst viewConfigString = (viewConfig: ViewConfig) => {\n const view = viewConfig.viewDecl;\n const state = view.$context.name || '(root)';\n return `[View#${viewConfig.$id} from '${state}' state]: target ui-view: '${view.$uiViewName}@${view.$uiViewContextAnchor}'`;\n};\n\n/** @hidden */\nfunction normalizedCat(input: Category|string): string {\n return isNumber(input) ? Category[input] : Category[Category[input]];\n}\n\n/** @hidden */\nconst consoleLog = Function.prototype.bind.call(console.log, console);\n\n/** @hidden */\nconst consoletable = isFunction(console.table) ? console.table.bind(console) : consoleLog.bind(console);\n\n\n/**\n * Trace categories Enum\n *\n * Enable or disable a category using [[Trace.enable]] or [[Trace.disable]]\n *\n * `trace.enable(Category.TRANSITION)`\n *\n * These can also be provided using a matching string, or position ordinal\n *\n * `trace.enable(\"TRANSITION\")`\n *\n * `trace.enable(1)`\n */\nexport enum Category {\n RESOLVE, TRANSITION, HOOK, UIVIEW, VIEWCONFIG,\n}\n\n/** @hidden */\nconst _tid = parse('$id');\n\n/** @hidden */\nconst _rid = parse('router.$id');\n\n/** @hidden */\nconst transLbl = (trans) => `Transition #${_tid(trans)}-${_rid(trans)}`;\n\n/**\n * Prints UI-Router Transition trace information to the console.\n */\nexport class Trace {\n /** @hidden */\n approximateDigests: number;\n\n /** @hidden */\n private _enabled: { [key: string]: boolean } = {};\n\n /** @hidden */\n constructor() {\n this.approximateDigests = 0;\n }\n\n /** @hidden */\n private _set(enabled: boolean, categories: Category[]) {\n if (!categories.length) {\n categories = Object.keys(Category)\n .map(k => parseInt(k, 10))\n .filter(k => !isNaN(k))\n .map(key => Category[key]);\n }\n categories.map(normalizedCat).forEach(category => this._enabled[category] = enabled);\n }\n\n /**\n * Enables a trace [[Category]]\n *\n * ```js\n * trace.enable(\"TRANSITION\");\n * ```\n *\n * @param categories categories to enable. If `categories` is omitted, all categories are enabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n enable(...categories: (Category|string|number)[]);\n enable(...categories: any[]) { this._set(true, categories); }\n /**\n * Disables a trace [[Category]]\n *\n * ```js\n * trace.disable(\"VIEWCONFIG\");\n * ```\n *\n * @param categories categories to disable. If `categories` is omitted, all categories are disabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n disable(...categories: (Category|string|number)[]);\n disable(...categories: any[]) { this._set(false, categories); }\n\n /**\n * Retrieves the enabled stateus of a [[Category]]\n *\n * ```js\n * trace.enabled(\"VIEWCONFIG\"); // true or false\n * ```\n *\n * @returns boolean true if the category is enabled\n */\n enabled(category: (Category|string|number)): boolean {\n return !!this._enabled[normalizedCat(category)];\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionStart(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Started -> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionIgnored(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Ignored <> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookInvocation(step: TransitionHook, trans: Transition, options: any) {\n if (!this.enabled(Category.HOOK)) return;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = functionToString((step as any).registeredHook.callback);\n console.log(`${transLbl(trans)}: Hook -> ${event} context: ${context}, ${maxLength(200, name)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookResult(hookResult: HookResult, trans: Transition, transitionOptions: any) {\n if (!this.enabled(Category.HOOK)) return;\n console.log(`${transLbl(trans)}: <- Hook returned: ${maxLength(200, stringify(hookResult))}`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvePath(path: PathNode[], when: PolicyWhen, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(`${transLbl(trans)}: Resolving ${path} (${when})`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvableResolved(resolvable: Resolvable, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(`${transLbl(trans)}: <- Resolved ${resolvable} to: ${maxLength(200, stringify(resolvable.data))}`);\n }\n\n /** @internalapi called by ui-router code */\n traceError(reason: any, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Rejected ${stringify(trans)}, reason: ${reason}`);\n }\n\n /** @internalapi called by ui-router code */\n traceSuccess(finalState: StateObject, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Success ${stringify(trans)}, final state: ${finalState.name}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewEvent(event: string, viewData: ActiveUIView, extra = '') {\n if (!this.enabled(Category.UIVIEW)) return;\n console.log(`ui-view: ${padString(30, event)} ${uiViewString(viewData)}${extra}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewConfigUpdated(viewData: ActiveUIView, context: ViewContext) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Updating', viewData, ` with ViewConfig from context='${context}'`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewFill(viewData: ActiveUIView, html: string) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Fill', viewData, ` with: ${maxLength(200, html)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewSync(pairs: ViewTuple[]) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n const uivheader = 'uiview component fqn';\n const cfgheader = 'view config state (view name)';\n const mapping = pairs.map(({ uiView, viewConfig }) => {\n const uiv = uiView && uiView.fqn;\n const cfg = viewConfig && `${viewConfig.viewDecl.$context.name}: (${viewConfig.viewDecl.$name})`;\n return { [uivheader]: uiv, [cfgheader]: cfg };\n }).sort((a, b) => (a[uivheader] || '').localeCompare(b[uivheader] || ''));\n\n consoletable(mapping);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceEvent(event: string, viewConfig: ViewConfig) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${viewConfigString(viewConfig)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceUIViewEvent(event: string, viewData: ActiveUIView) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${uiViewString(viewData)}`);\n }\n}\n\n/**\n * The [[Trace]] singleton\n *\n * #### Example:\n * ```js\n * import {trace} from \"angular-ui-router\";\n * trace.enable(1, 5);\n * ```\n */\nconst trace = new Trace();\nexport { trace };\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { StateDeclaration } from '../state/interface';\nimport { Predicate } from '../common/common';\n\nimport { Transition } from './transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TargetState } from '../state/targetState';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * The TransitionOptions object can be used to change the behavior of a transition.\n *\n * It is passed as the third argument to [[StateService.go]], [[StateService.transitionTo]].\n * It can also be used with a `uiSref`.\n */\nexport interface TransitionOptions {\n /**\n * This option changes how the Transition interacts with the browser's location bar (URL).\n *\n * - If `true`, it will update the url in the location bar.\n * - If `false`, it will not update the url in the location bar.\n * - If it is the string `\"replace\"`, it will update the url and also replace the last history record.\n *\n * @default `true`\n */\n location ?: (boolean|string);\n\n /**\n * When transitioning to relative path (e.g '`^`'), this option defines which state to be relative from.\n * @default `$state.current`\n */\n relative ?: (string|StateDeclaration|StateObject);\n\n /**\n * This option sets whether or not the transition's parameter values should be inherited from\n * the current parameter values.\n *\n * - If `true`, it will inherit parameter values from the current parameter values.\n * - If `false`, only the parameters which are provided to `transitionTo` will be used.\n *\n * @default `false`\n */\n inherit ?: boolean;\n\n /**\n * @deprecated\n */\n notify ?: boolean;\n\n /**\n * This option may be used to force states which are currently active to reload.\n *\n * During a normal transition, a state is \"retained\" if:\n * - It was previously active\n * - The state's parameter values have not changed\n * - All the parent states' parameter values have not changed\n *\n * Forcing a reload of a state will cause it to be exited and entered, which will:\n * - Refetch that state's resolve data\n * - Exit the state (onExit hook)\n * - Re-enter the state (onEnter hook)\n * - Re-render the views (controllers and templates)\n *\n * - When `true`, the destination state (and all parent states) will be reloaded.\n * - When it is a string and is the name of a state, or when it is a State object,\n * that state and any children states will be reloaded.\n *\n * @default `false`\n */\n reload ?: (boolean|string|StateDeclaration|StateObject);\n /**\n * You can define your own Transition Options inside this property and use them, e.g., from a Transition Hook\n */\n custom ?: any;\n /** @internalapi */\n reloadState ?: (StateObject);\n /** @internalapi\n * If this transition is a redirect, this property should be the original Transition (which was redirected to this one)\n */\n redirectedFrom?: Transition;\n /** @internalapi */\n current ?: () => Transition;\n /** @internalapi */\n source ?: 'sref' | 'url' | 'redirect' | 'otherwise' | 'unknown';\n}\n\n/** @internalapi */\nexport interface TransitionHookOptions {\n current ?: () => Transition; // path?\n transition ?: Transition;\n hookType ?: string;\n target ?: any;\n traceData ?: any;\n bind ?: any;\n stateHook ?: boolean;\n}\n\n/**\n * TreeChanges encapsulates the various Paths that are involved in a Transition.\n *\n * Get a TreeChanges object using [[Transition.treeChanges]]\n *\n * A UI-Router Transition is from one Path in a State Tree to another Path. For a given Transition,\n * this object stores the \"to\" and \"from\" paths, as well as subsets of those: the \"retained\",\n * \"exiting\" and \"entering\" paths.\n *\n * Each path in TreeChanges is an array of [[PathNode]] objects. Each PathNode in the array corresponds to a portion\n * of a nested state.\n *\n * For example, if you had a nested state named `foo.bar.baz`, it would have three\n * portions, `foo, bar, baz`. If you transitioned **to** `foo.bar.baz` and inspected the [[TreeChanges.to]]\n * Path, you would find a node in the array for each portion: `foo`, `bar`, and `baz`.\n *\n * ---\n *\n * @todo show visual state tree\n */\nexport interface TreeChanges {\n /** @nodoc */\n [key: string]: PathNode[];\n\n /** The path of nodes in the state tree that the transition is coming *from* */\n from: PathNode[];\n\n /** The path of nodes in the state tree that the transition is going *to* */\n to: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n */\n retained: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining with updated \"to params\" applied.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n *\n * This is a shallow copy of [[retained]], but with new (dynamic) parameter values from [[to]] applied.\n */\n retainedWithToParams: PathNode[];\n\n /**\n * The path of previously active nodes that the transition is exiting.\n *\n * After the Transition is successful, these nodes are no longer active.\n *\n * Note that a state that is being reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n exiting: PathNode[];\n\n /**\n * The path of nodes that the transition is entering.\n *\n * After the Transition is successful, these nodes will be active.\n * Because they are entering, they have their resolves fetched, `onEnter` hooks run, and their views\n * (component(s) or controller(s)+template(s)) refreshed.\n *\n * Note that a state that is reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n entering: PathNode[];\n}\n\nexport type IHookRegistration = (matchCriteria: HookMatchCriteria, callback: HookFn, options?: HookRegOptions) => Function;\n\n/**\n * The signature for Transition Hooks.\n *\n * Transition hooks are callback functions that hook into the lifecycle of transitions.\n * As a transition runs, it reaches certain lifecycle events.\n * As each event occurs, the hooks which are registered for the event are called (in priority order).\n *\n * A transition hook may alter a Transition by returning a [[HookResult]].\n *\n * #### See:\n *\n * - [[IHookRegistry.onBefore]]\n * - [[IHookRegistry.onStart]]\n * - [[IHookRegistry.onFinish]]\n * - [[IHookRegistry.onSuccess]]\n * - [[IHookRegistry.onError]]\n *\n * @param transition the current [[Transition]]\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n *\n */\nexport interface TransitionHookFn {\n (transition: Transition): HookResult;\n}\n\n/**\n * The signature for Transition State Hooks.\n *\n * A function which hooks into a lifecycle event for a specific state.\n *\n * Transition State Hooks are callback functions that hook into the lifecycle events of specific states during a transition.\n * As a transition runs, it may exit some states, retain (keep) states, and enter states.\n * As each lifecycle event occurs, the hooks which are registered for the event and that state are called (in priority order).\n *\n * #### See:\n *\n * - [[IHookRegistry.onExit]]\n * - [[IHookRegistry.onRetain]]\n * - [[IHookRegistry.onEnter]]\n *\n * @param transition the current [[Transition]]\n * @param state the [[StateObject]] that the hook is bound to\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n */\nexport interface TransitionStateHookFn {\n (transition: Transition, state: StateDeclaration): HookResult;\n}\n\n/**\n * The signature for Transition onCreate Hooks.\n *\n * Transition onCreate Hooks are callbacks that allow customization or preprocessing of\n * a Transition before it is returned from [[TransitionService.create]]\n *\n * @param transition the [[Transition]] that was just created\n * @return a [[Transition]] which will then be returned from [[TransitionService.create]]\n */\nexport interface TransitionCreateHookFn {\n (transition: Transition): void;\n}\n\nexport type HookFn = (TransitionHookFn|TransitionStateHookFn|TransitionCreateHookFn);\n\n/**\n * The return value of a [[TransitionHookFn]] or [[TransitionStateHookFn]]\n *\n * When returned from a [[TransitionHookFn]] or [[TransitionStateHookFn]], these values alter the running [[Transition]]:\n *\n * - `false`: the transition will be cancelled.\n * - [[TargetState]]: the transition will be redirected to the new target state (see: [[StateService.target]])\n * - `Promise`: the transition will wait for the promise to resolve or reject\n * - If the promise is rejected (or resolves to `false`), the transition will be cancelled\n * - If the promise resolves to a [[TargetState]], the transition will be redirected\n * - If the promise resolves to anything else, the transition will resume\n * - Anything else: the transition will resume\n */\nexport type HookResult = (boolean | TargetState | void | Promise);\n\n/**\n * These options may be provided when registering a Transition Hook (such as `onStart`)\n */\nexport interface HookRegOptions {\n /**\n * Sets the priority of the registered hook\n *\n * Hooks of the same type (onBefore, onStart, etc) are invoked in priority order. A hook with a higher priority\n * is invoked before a hook with a lower priority.\n *\n * The default hook priority is 0\n */\n priority?: number;\n\n /**\n * Specifies what `this` is bound to during hook invocation.\n */\n bind?: any;\n\n /**\n * Limits the number of times that the hook will be invoked.\n * Once the hook has been invoked this many times, it is automatically deregistered.\n */\n invokeLimit?: number;\n}\n\n/**\n * This interface specifies the api for registering Transition Hooks. Both the\n * [[TransitionService]] and also the [[Transition]] object itself implement this interface.\n * Note: the Transition object only allows hooks to be registered before the Transition is started.\n */\nexport interface IHookRegistry {\n /** @hidden place to store the hooks */\n _registeredHooks: { [key: string]: RegisteredHook[] };\n\n /**\n * Registers a [[TransitionHookFn]], called *before a transition starts*.\n *\n * Registers a transition lifecycle hook, which is invoked before a transition even begins.\n * This hook can be useful to implement logic which prevents a transition from even starting, such\n * as authentication, redirection\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onBefore` hooks are invoked *before a Transition starts*.\n * No resolves have been fetched yet.\n * Each `onBefore` hook is invoked synchronously, in the same call stack as [[StateService.transitionTo]].\n * The registered `onBefore` hooks are invoked in priority order.\n *\n * Note: during the `onBefore` phase, additional hooks can be added to the specific [[Transition]] instance.\n * These \"on-the-fly\" hooks only affect the currently running transition..\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * If any hook modifies the transition *synchronously* (by throwing, returning `false`, or returning\n * a [[TargetState]]), the remainder of the hooks are skipped.\n * If a hook returns a promise, the remainder of the `onBefore` hooks are still invoked synchronously.\n * All promises are resolved, and processed asynchronously before the `onStart` phase of the Transition.\n *\n * ### Examples\n *\n * #### Default Substate\n *\n * This example redirects any transition from 'home' to 'home.dashboard'. This is commonly referred to as a\n * \"default substate\".\n *\n * @example\n * ```js\n * // ng2\n * transitionService.onBefore({ to: 'home' }, (trans: Transition) =>\n * trans.router.stateService.target(\"home.dashboard\"));\n * ```\n *\n * #### Data Driven Default Substate\n *\n * This example provides data-driven default substate functionality. It matches on a transition to any state\n * which has `defaultSubstate: \"some.sub.state\"` defined. See: [[Transition.to]] which returns the \"to state\"\n * definition.\n *\n * @example\n * ```js\n * // ng1\n * // state declaration\n * {\n * name: 'home',\n * template: '
    ',\n * defaultSubstate: 'home.dashboard'\n * }\n *\n * var criteria = {\n * to: function(state) {\n * return state.defaultSubstate != null;\n * }\n * }\n *\n * $transitions.onBefore(criteria, function(trans: Transition) {\n * var substate = trans.to().defaultSubstate;\n * return trans.router.stateService.target(substate);\n * });\n * ```\n *\n *\n * #### Require authentication\n *\n * This example cancels a transition to a state which requires authentication, if the user is not currently authenticated.\n *\n * This example assumes a state tree where all states which require authentication are children of a parent `'requireauth'` state.\n * This example assumes `MyAuthService` synchronously returns a boolean from `isAuthenticated()`.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onBefore( { to: 'requireauth.**' }, function(trans) {\n * var myAuthService = trans.injector().get('MyAuthService');\n * // If isAuthenticated returns false, the transition is cancelled.\n * return myAuthService.isAuthenticated();\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @returns a function which deregisters the hook.\n */\n onBefore(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called when a transition starts.\n *\n * Registers a transition lifecycle hook, which is invoked as a transition starts running.\n * This hook can be useful to perform some asynchronous action before completing a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onStart` hooks are invoked asynchronously when the Transition starts running.\n * This happens after the `onBefore` phase is complete.\n * At this point, the Transition has not yet exited nor entered any states.\n * The registered `onStart` hooks are invoked in priority order.\n *\n * Note: A built-in `onStart` hook with high priority is used to fetch any eager resolve data.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Example\n *\n * #### Login during transition\n *\n * This example intercepts any transition to a state which requires authentication, when the user is\n * not currently authenticated. It allows the user to authenticate asynchronously, then resumes the\n * transition. If the user did not authenticate successfully, it redirects to the \"guest\" state, which\n * does not require authentication.\n *\n * This example assumes:\n * - a state tree where all states which require authentication are children of a parent `'auth'` state.\n * - `MyAuthService.isAuthenticated()` synchronously returns a boolean.\n * - `MyAuthService.authenticate()` presents a login dialog, and returns a promise which is resolved\n * or rejected, whether or not the login attempt was successful.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onStart( { to: 'auth.**' }, function(trans) {\n * var $state = trans.router.stateService;\n * var MyAuthService = trans.injector().get('MyAuthService');\n *\n * // If the user is not authenticated\n * if (!MyAuthService.isAuthenticated()) {\n *\n * // Then return a promise for a successful login.\n * // The transition will wait for this promise to settle\n *\n * return MyAuthService.authenticate().catch(function() {\n *\n * // If the authenticate() method failed for whatever reason,\n * // redirect to a 'guest' state which doesn't require auth.\n * return $state.target(\"guest\");\n * });\n * }\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onStart(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is entered.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being entered.\n *\n * Since this hook is run only when the specific state is being *entered*, it can be useful for\n * performing tasks when entering a submodule/feature area such as initializing a stateful service,\n * or for guarding access to a submodule/feature area.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onEnter` hooks generally specify `{ entering: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onEnter` hooks are invoked when the Transition is entering a state.\n * States are entered after the `onRetain` phase is complete.\n * If more than one state is being entered, the parent state is entered first.\n * The registered `onEnter` hooks for a state are invoked in priority order.\n *\n * Note: A built-in `onEnter` hook with high priority is used to fetch lazy resolve data for states being entered.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onEnter` hooks using the [[TransitionService]], you may define an `onEnter` hook\n * directly on a state declaration (see: [[StateDeclaration.onEnter]]).\n *\n *\n * ### Examples\n *\n * #### Audit Log\n *\n * This example uses a service to log that a user has entered the admin section of an app.\n * This assumes that there are substates of the \"admin\" state, such as \"admin.users\", \"admin.pages\", etc.\n * @example\n * ```\n *\n * $transitions.onEnter({ entering: 'admin' }, function(transition, state) {\n * var AuditService = trans.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * ```\n *\n * #### Audit Log (inside a state declaration)\n *\n * The `onEnter` inside this state declaration is syntactic sugar for the previous Audit Log example.\n * ```\n * {\n * name: 'admin',\n * component: 'admin',\n * onEnter: function($transition$, $state$) {\n * var AuditService = $transition$.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * }\n * ```\n *\n * Note: A state declaration's `onEnter` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onEnter(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is retained/kept.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) for\n * a specific state that was previously active will remain active (is not being entered nor exited).\n *\n * This hook is invoked when a state is \"retained\" or \"kept\".\n * It means the transition is coming *from* a substate of the retained state *to* a substate of the retained state.\n * This hook can be used to perform actions when the user moves from one substate to another, such as between steps in a wizard.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onRetain` hooks generally specify `{ retained: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onRetain` hooks are invoked after any `onExit` hooks have been fired.\n * If more than one state is retained, the child states' `onRetain` hooks are invoked first.\n * The registered `onRetain` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onRetain` hooks using the [[TransitionService]], you may define an `onRetain` hook\n * directly on a state declaration (see: [[StateDeclaration.onRetain]]).\n *\n * Note: A state declaration's `onRetain` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onRetain(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is exited.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being exited.\n *\n * Since this hook is run only when the specific state is being *exited*, it can be useful for\n * performing tasks when leaving a submodule/feature area such as cleaning up a stateful service,\n * or for preventing the user from leaving a state or submodule until some criteria is satisfied.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onExit` hooks generally specify `{ exiting: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onExit` hooks are invoked when the Transition is exiting a state.\n * States are exited after any `onStart` phase is complete.\n * If more than one state is being exited, the child states are exited first.\n * The registered `onExit` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onExit` hooks using the [[TransitionService]], you may define an `onExit` hook\n * directly on a state declaration (see: [[StateDeclaration.onExit]]).\n *\n * Note: A state declaration's `onExit` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onExit(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called *just before a transition finishes*.\n *\n * Registers a transition lifecycle hook, which is invoked just before a transition finishes.\n * This hook is a last chance to cancel or redirect a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onFinish` hooks are invoked after the `onEnter` phase is complete.\n * These hooks are invoked just before the transition is \"committed\".\n * Each hook is invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onFinish(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a successful transition completed.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition successfully completes.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onSuccess` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If the Transition is successful and its promise is resolved, then the `onSuccess` hooks are invoked.\n * Since these hooks are run after the transition is over, their return value is ignored.\n * The `onSuccess` hooks are invoked in priority order.\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onSuccess(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a transition has errored.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition has been rejected for any reason.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * The `onError` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If a Transition fails, its promise is rejected and the `onError` hooks are invoked.\n * The `onError` hooks are invoked in priority order.\n *\n * Since these hooks are run after the transition is over, their return value is ignored.\n *\n * A transition \"errors\" if it was started, but failed to complete (for any reason).\n * A *non-exhaustive list* of reasons a transition can error:\n *\n * - A transition was cancelled because a new transition started while it was still running (`Transition superseded`)\n * - A transition was cancelled by a Transition Hook returning false\n * - A transition was redirected by a Transition Hook returning a [[TargetState]]\n * - A Transition Hook or resolve function threw an error\n * - A Transition Hook returned a rejected promise\n * - A resolve function returned a rejected promise\n *\n * To check the failure reason, inspect the return value of [[Transition.error]].\n *\n * Note: `onError` should be used for targeted error handling, or error recovery.\n * For simple catch-all error reporting, use [[StateService.defaultErrorHandler]].\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onError(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Returns all the registered hooks of a given `hookName` type\n *\n * #### Example:\n * ```\n * $transitions.getHooks(\"onEnter\")\n * ```\n */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/** A predicate type which tests if a [[StateObject]] passes some test. Returns a boolean. */\nexport type IStateMatch = Predicate;\n\n/**\n * This object is used to configure whether or not a Transition Hook is invoked for a particular transition,\n * based on the Transition's \"to state\" and \"from state\".\n *\n * Each property (`to`, `from`, `exiting`, `retained`, and `entering`) can be a state [[Glob]] string,\n * a boolean, or a function that takes a state and returns a boolean (see [[HookMatchCriterion]])\n *\n * All properties are optional. If any property is omitted, it is replaced with the value `true`, and always matches.\n * To match any transition, use an empty criteria object `{}`.\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from the `parent` state and going to the `parent.child` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.child'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any substate of `parent` and going directly to the `parent` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any substate of `mymodule`\n * var match = {\n * to: 'mymodule.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any state that has `data.authRequired`\n * // set to a truthy value.\n * var match = {\n * to: function(state) {\n * return state.data != null && state.data.authRequired === true;\n * }\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition that is exiting `parent.child`\n * var match = {\n * exiting: 'parent.child'\n * }\n * ```\n */\nexport interface HookMatchCriteria {\n [key: string]: HookMatchCriterion | undefined;\n\n /** A [[HookMatchCriterion]] to match the destination state */\n to?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match the original (from) state */\n from?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be exiting */\n exiting?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be retained */\n retained?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be entering */\n entering?: HookMatchCriterion;\n}\n\nexport interface IMatchingNodes {\n [key: string]: PathNode[];\n\n to: PathNode[];\n from: PathNode[];\n exiting: PathNode[];\n retained: PathNode[];\n entering: PathNode[];\n}\n\n/** @hidden */\nexport interface RegisteredHooks {\n [key: string]: RegisteredHook[];\n}\n\n/** @hidden */\nexport interface PathTypes {\n [key: string]: PathType;\n\n to: PathType;\n from: PathType;\n exiting: PathType;\n retained: PathType;\n entering: PathType;\n}\n\n/** @hidden */\nexport interface PathType {\n name: string;\n scope: TransitionHookScope;\n}\n\n/**\n * Hook Criterion used to match a transition.\n *\n * A [[Glob]] string that matches the name of a state.\n *\n * Or, a function with the signature `function(state) { return matches; }`\n * which should return a boolean to indicate if a state matches.\n *\n * Or, `true` to always match\n */\nexport type HookMatchCriterion = (string|IStateMatch|boolean);\n\nexport enum TransitionHookPhase { CREATE, BEFORE, RUN, SUCCESS, ERROR }\nexport enum TransitionHookScope { TRANSITION, STATE }\n", - "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateDeclaration, StateOrName, TargetStateDef } from './interface';\nimport { TransitionOptions } from '../transition/interface';\nimport { StateObject } from './stateObject';\nimport { isString } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { extend } from '../common';\nimport { StateRegistry } from './stateRegistry';\nimport { RawParams } from '../params';\n\n/**\n * Encapsulate the target (destination) state/params/options of a [[Transition]].\n *\n * This class is frequently used to redirect a transition to a new destination.\n *\n * See:\n *\n * - [[HookResult]]\n * - [[TransitionHookFn]]\n * - [[TransitionService.onStart]]\n *\n * To create a `TargetState`, use [[StateService.target]].\n *\n * ---\n *\n * This class wraps:\n *\n * 1) an identifier for a state\n * 2) a set of parameters\n * 3) and transition options\n * 4) the registered state object (the [[StateDeclaration]])\n *\n * Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can\n * either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string).\n * The `TargetState` class normalizes those options.\n *\n * A `TargetState` may be valid (the state being targeted exists in the registry)\n * or invalid (the state being targeted is not registered).\n */\nexport class TargetState {\n private _definition: StateObject;\n private _params: RawParams;\n private _options: TransitionOptions;\n\n /** Returns true if the object has a state property that might be a state or state name */\n static isDef = (obj): obj is TargetStateDef =>\n obj && obj.state && (isString(obj.state) || isString(obj.state.name));\n\n /**\n * The TargetState constructor\n *\n * Note: Do not construct a `TargetState` manually.\n * To create a `TargetState`, use the [[StateService.target]] factory method.\n *\n * @param _stateRegistry The StateRegistry to use to look up the _definition\n * @param _identifier An identifier for a state.\n * Either a fully-qualified state name, or the object used to define the state.\n * @param _params Parameters for the target state\n * @param _options Transition options.\n *\n * @internalapi\n */\n constructor(\n private _stateRegistry: StateRegistry,\n private _identifier: StateOrName,\n _params?: RawParams,\n _options?: TransitionOptions,\n ) {\n this._identifier = _identifier;\n this._params = extend({}, _params || {});\n this._options = extend({}, _options || {});\n this._definition = _stateRegistry.matcher.find(_identifier, this._options.relative);\n }\n\n /** The name of the state this object targets */\n name(): string {\n return this._definition && this._definition.name || this._identifier;\n }\n\n /** The identifier used when creating this TargetState */\n identifier(): StateOrName {\n return this._identifier;\n }\n\n /** The target parameter values */\n params(): RawParams {\n return this._params;\n }\n\n /** The internal state object (if it was found) */\n $state(): StateObject {\n return this._definition;\n }\n\n /** The internal state declaration (if it was found) */\n state(): StateDeclaration {\n return this._definition && this._definition.self;\n }\n\n /** The target options */\n options() {\n return this._options;\n }\n\n /** True if the target state was found */\n exists(): boolean {\n return !!(this._definition && this._definition.self);\n }\n\n /** True if the object is valid */\n valid(): boolean {\n return !this.error();\n }\n\n /** If the object is invalid, returns the reason why */\n error(): string {\n const base = this.options().relative;\n if (!this._definition && !!base) {\n const stateName = base.name ? base.name : base;\n return `Could not resolve '${this.name()}' from state '${stateName}'`;\n }\n if (!this._definition)\n return `No such state '${this.name()}'`;\n if (!this._definition.self)\n return `State '${this.name()}' has an invalid definition`;\n }\n\n toString() {\n return `'${this.name()}'${stringify(this.params())}`;\n }\n\n /**\n * Returns a copy of this TargetState which targets a different state.\n * The new TargetState has the same parameter values and transition options.\n *\n * @param state The new state that should be targeted\n */\n withState(state: StateOrName): TargetState {\n return new TargetState(this._stateRegistry, state, this._params, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified parameter values.\n *\n * @param params the new parameter values to use\n * @param replace When false (default) the new parameter values will be merged with the current values.\n * When true the parameter values will be used instead of the current values.\n */\n withParams(params: RawParams, replace = false): TargetState {\n const newParams: RawParams = replace ? params : extend({}, this._params, params);\n return new TargetState(this._stateRegistry, this._identifier, newParams, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified Transition Options.\n *\n * @param options the new options to use\n * @param replace When false (default) the new options will be merged with the current options.\n * When true the options will be used instead of the current options.\n */\n withOptions(options: TransitionOptions, replace = false): TargetState {\n const newOpts = replace ? options : extend({}, this._options, options);\n return new TargetState(this._stateRegistry, this._identifier, this._params, newOpts);\n }\n}\n", - "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { TransitionHookOptions, HookResult, TransitionHookPhase } from './interface';\nimport { defaults, noop, silentRejection } from '../common/common';\nimport { fnToString, maxLength } from '../common/strings';\nimport { isPromise } from '../common/predicates';\nimport { is, parse } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { Rejection } from './rejectFactory';\nimport { TargetState } from '../state/targetState';\nimport { Transition } from './transition';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\nimport { StateDeclaration } from '../state/interface';\n\nconst defaultOptions: TransitionHookOptions = {\n current: noop,\n transition: null,\n traceData: {},\n bind: null,\n};\n\nexport type GetResultHandler = (hook: TransitionHook) => ResultHandler;\nexport type GetErrorHandler = (hook: TransitionHook) => ErrorHandler;\n\nexport type ResultHandler = (result: HookResult) => Promise;\nexport type ErrorHandler = (error: any) => Promise;\n\n/** @hidden */\nexport class TransitionHook {\n type: TransitionEventType;\n\n /**\n * These GetResultHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetResultHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static HANDLE_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) =>\n hook.handleHookResult(result);\n\n /**\n * If the result is a promise rejection, log it.\n * Otherwise, ignore the result.\n */\n static LOG_REJECTED_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) => {\n isPromise(result) && result.catch(err =>\n hook.logError(Rejection.normalize(err)));\n return undefined;\n }\n\n /**\n * These GetErrorHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetErrorHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static LOG_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) =>\n hook.logError(error);\n\n static REJECT_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) =>\n silentRejection(error);\n\n static THROW_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => {\n throw error;\n }\n\n /**\n * Chains together an array of TransitionHooks.\n *\n * Given a list of [[TransitionHook]] objects, chains them together.\n * Each hook is invoked after the previous one completes.\n *\n * #### Example:\n * ```js\n * var hooks: TransitionHook[] = getHooks();\n * let promise: Promise = TransitionHook.chain(hooks);\n *\n * promise.then(handleSuccess, handleError);\n * ```\n *\n * @param hooks the list of hooks to chain together\n * @param waitFor if provided, the chain is `.then()`'ed off this promise\n * @returns a `Promise` for sequentially invoking the hooks (in order)\n */\n static chain(hooks: TransitionHook[], waitFor?: Promise): Promise {\n // Chain the next hook off the previous\n const createHookChainR = (prev: Promise, nextHook: TransitionHook) =>\n prev.then(() => nextHook.invokeHook());\n return hooks.reduce(createHookChainR, waitFor || services.$q.when());\n }\n\n\n /**\n * Invokes all the provided TransitionHooks, in order.\n * Each hook's return value is checked.\n * If any hook returns a promise, then the rest of the hooks are chained off that promise, and the promise is returned.\n * If no hook returns a promise, then all hooks are processed synchronously.\n *\n * @param hooks the list of TransitionHooks to invoke\n * @param doneCallback a callback that is invoked after all the hooks have successfully completed\n *\n * @returns a promise for the async result, or the result of the callback\n */\n static invokeHooks(hooks: TransitionHook[], doneCallback: (result?: HookResult) => T): Promise | T {\n for (let idx = 0; idx < hooks.length; idx++) {\n const hookResult = hooks[idx].invokeHook();\n\n if (isPromise(hookResult)) {\n const remainingHooks = hooks.slice(idx + 1);\n\n return TransitionHook.chain(remainingHooks, hookResult)\n .then(doneCallback);\n }\n }\n\n return doneCallback();\n }\n\n /**\n * Run all TransitionHooks, ignoring their return value.\n */\n static runAllHooks(hooks: TransitionHook[]): void {\n hooks.forEach(hook => hook.invokeHook());\n }\n\n constructor(private transition: Transition,\n private stateContext: StateDeclaration,\n private registeredHook: RegisteredHook,\n private options: TransitionHookOptions) {\n this.options = defaults(options, defaultOptions);\n this.type = registeredHook.eventType;\n }\n\n private isSuperseded = () =>\n this.type.hookPhase === TransitionHookPhase.RUN && !this.options.transition.isActive();\n\n logError(err): any {\n this.transition.router.stateService.defaultErrorHandler()(err);\n }\n\n invokeHook(): Promise | void {\n const hook = this.registeredHook;\n if (hook._deregistered) return;\n\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n const options = this.options;\n trace.traceHookInvocation(this, this.transition, options);\n\n const invokeCallback = () =>\n hook.callback.call(options.bind, this.transition, this.stateContext);\n\n const normalizeErr = err =>\n Rejection.normalize(err).toPromise();\n\n const handleError = err =>\n hook.eventType.getErrorHandler(this)(err);\n\n const handleResult = result =>\n hook.eventType.getResultHandler(this)(result);\n\n try {\n const result = invokeCallback();\n\n if (!this.type.synchronous && isPromise(result)) {\n return result.catch(normalizeErr)\n .then(handleResult, handleError);\n } else {\n return handleResult(result);\n }\n } catch (err) {\n // If callback throws (synchronously)\n return handleError(Rejection.normalize(err));\n } finally {\n if (hook.invokeLimit && ++hook.invokeCount >= hook.invokeLimit) {\n hook.deregister();\n }\n }\n }\n\n /**\n * This method handles the return value of a Transition Hook.\n *\n * A hook can return false (cancel), a TargetState (redirect),\n * or a promise (which may later resolve to false or a redirect)\n *\n * This also handles \"transition superseded\" -- when a new transition\n * was started while the hook was still running\n */\n handleHookResult(result: HookResult): Promise {\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n // Hook returned a promise\n if (isPromise(result)) {\n // Wait for the promise, then reprocess with the resulting value\n return result.then(val => this.handleHookResult(val));\n }\n\n trace.traceHookResult(result, this.transition, this.options);\n\n // Hook returned false\n if (result === false) {\n // Abort this Transition\n return Rejection.aborted('Hook aborted transition').toPromise();\n }\n\n const isTargetState = is(TargetState);\n // hook returned a TargetState\n if (isTargetState(result)) {\n // Halt the current Transition and redirect (a new Transition) to the TargetState.\n return Rejection.redirected(result).toPromise();\n }\n }\n\n\n /**\n * Return a Rejection promise if the transition is no longer current due\n * to a stopped router (disposed), or a new transition has started and superseded this one.\n */\n private getNotCurrentRejection() {\n const router = this.transition.router;\n\n // The router is stopped\n if (router._disposed) {\n return Rejection.aborted(`UIRouter instance #${router.$id} has been stopped (disposed)`).toPromise();\n }\n\n if (this.transition._aborted) {\n return Rejection.aborted().toPromise();\n }\n\n // This transition is no longer current.\n // Another transition started while this hook was still running.\n if (this.isSuperseded()) {\n // Abort this transition\n return Rejection.superseded(this.options.current()).toPromise();\n }\n }\n\n toString() {\n const { options, registeredHook } = this;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = fnToString(registeredHook.callback);\n return `${event} context: ${context}, ${maxLength(200, name)}`;\n }\n\n}\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { isString, isFunction, Glob, extend, removeFrom, tail, values, identity, mapObj } from '../common';\nimport { PathNode } from '../path/pathNode';\nimport {\n TransitionStateHookFn, TransitionHookFn, TransitionHookPhase, // has or is using\n TransitionHookScope, IHookRegistry, PathType,\n} from './interface';\n\nimport { HookRegOptions, HookMatchCriteria, TreeChanges, HookMatchCriterion, IMatchingNodes, HookFn } from './interface';\nimport { StateObject } from '../state/stateObject';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionService } from './transitionService';\n\n/**\n * Determines if the given state matches the matchCriteria\n *\n * @hidden\n *\n * @param state a State Object to test against\n * @param criterion\n * - If a string, matchState uses the string as a glob-matcher against the state name\n * - If an array (of strings), matchState uses each string in the array as a glob-matchers against the state name\n * and returns a positive match if any of the globs match.\n * - If a function, matchState calls the function with the state and returns true if the function's result is truthy.\n * @returns {boolean}\n */\nexport function matchState(state: StateObject, criterion: HookMatchCriterion) {\n const toMatch = isString(criterion) ? [criterion] : criterion;\n\n function matchGlobs(_state: StateObject) {\n const globStrings = toMatch;\n for (let i = 0; i < globStrings.length; i++) {\n const glob = new Glob(globStrings[i]);\n\n if ((glob && glob.matches(_state.name)) || (!glob && globStrings[i] === _state.name)) {\n return true;\n }\n }\n return false;\n }\n\n const matchFn = (isFunction(toMatch) ? toMatch : matchGlobs);\n return !!matchFn(state);\n}\n\n/**\n * @internalapi\n * The registration data for a registered transition hook\n */\nexport class RegisteredHook {\n priority: number;\n bind: any;\n invokeCount = 0;\n invokeLimit: number;\n _deregistered = false;\n\n constructor(public tranSvc: TransitionService,\n public eventType: TransitionEventType,\n public callback: HookFn,\n public matchCriteria: HookMatchCriteria,\n public removeHookFromRegistry: (hook: RegisteredHook) => void,\n options: HookRegOptions = {} as any) {\n this.priority = options.priority || 0;\n this.bind = options.bind || null;\n this.invokeLimit = options.invokeLimit;\n }\n\n /**\n * Gets the matching [[PathNode]]s\n *\n * Given an array of [[PathNode]]s, and a [[HookMatchCriterion]], returns an array containing\n * the [[PathNode]]s that the criteria matches, or `null` if there were no matching nodes.\n *\n * Returning `null` is significant to distinguish between the default\n * \"match-all criterion value\" of `true` compared to a `() => true` function,\n * when the nodes is an empty array.\n *\n * This is useful to allow a transition match criteria of `entering: true`\n * to still match a transition, even when `entering === []`. Contrast that\n * with `entering: (state) => true` which only matches when a state is actually\n * being entered.\n */\n private _matchingNodes(nodes: PathNode[], criterion: HookMatchCriterion): PathNode[] {\n if (criterion === true) return nodes;\n const matching = nodes.filter(node => matchState(node.state, criterion));\n return matching.length ? matching : null;\n }\n\n /**\n * Gets the default match criteria (all `true`)\n *\n * Returns an object which has all the criteria match paths as keys and `true` as values, i.e.:\n *\n * ```js\n * {\n * to: true,\n * from: true,\n * entering: true,\n * exiting: true,\n * retained: true,\n * }\n */\n private _getDefaultMatchCriteria(): HookMatchCriteria {\n return mapObj(this.tranSvc._pluginapi._getPathTypes(), () => true);\n }\n\n /**\n * Gets matching nodes as [[IMatchingNodes]]\n *\n * Create a IMatchingNodes object from the TransitionHookTypes that is roughly equivalent to:\n *\n * ```js\n * let matches: IMatchingNodes = {\n * to: _matchingNodes([tail(treeChanges.to)], mc.to),\n * from: _matchingNodes([tail(treeChanges.from)], mc.from),\n * exiting: _matchingNodes(treeChanges.exiting, mc.exiting),\n * retained: _matchingNodes(treeChanges.retained, mc.retained),\n * entering: _matchingNodes(treeChanges.entering, mc.entering),\n * };\n * ```\n */\n private _getMatchingNodes(treeChanges: TreeChanges): IMatchingNodes {\n const criteria = extend(this._getDefaultMatchCriteria(), this.matchCriteria);\n const paths: PathType[] = values(this.tranSvc._pluginapi._getPathTypes());\n\n return paths.reduce((mn: IMatchingNodes, pathtype: PathType) => {\n // STATE scope criteria matches against every node in the path.\n // TRANSITION scope criteria matches against only the last node in the path\n const isStateHook = pathtype.scope === TransitionHookScope.STATE;\n const path = treeChanges[pathtype.name] || [];\n const nodes: PathNode[] = isStateHook ? path : [tail(path)];\n\n mn[pathtype.name] = this._matchingNodes(nodes, criteria[pathtype.name]);\n return mn;\n }, {} as IMatchingNodes);\n }\n\n /**\n * Determines if this hook's [[matchCriteria]] match the given [[TreeChanges]]\n *\n * @returns an IMatchingNodes object, or null. If an IMatchingNodes object is returned, its values\n * are the matching [[PathNode]]s for each [[HookMatchCriterion]] (to, from, exiting, retained, entering)\n */\n matches(treeChanges: TreeChanges): IMatchingNodes {\n const matches = this._getMatchingNodes(treeChanges);\n\n // Check if all the criteria matched the TreeChanges object\n const allMatched = values(matches).every(identity);\n return allMatched ? matches : null;\n }\n\n deregister() {\n this.removeHookFromRegistry(this);\n this._deregistered = true;\n }\n}\n\n/** @hidden Return a registration function of the requested type. */\nexport function makeEvent(registry: IHookRegistry, transitionService: TransitionService, eventType: TransitionEventType) {\n // Create the object which holds the registered transition hooks.\n const _registeredHooks = registry._registeredHooks = (registry._registeredHooks || {});\n const hooks = _registeredHooks[eventType.name] = [];\n const removeHookFn: (hook: RegisteredHook) => void = removeFrom(hooks);\n\n // Create hook registration function on the IHookRegistry for the event\n registry[eventType.name] = hookRegistrationFn;\n\n function hookRegistrationFn(matchObject, callback, options = {}) {\n const registeredHook = new RegisteredHook(transitionService, eventType, callback, matchObject, removeHookFn, options);\n hooks.push(registeredHook);\n return registeredHook.deregister.bind(registeredHook);\n }\n\n return hookRegistrationFn;\n}\n", - "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n\nimport { extend, tail, assertPredicate, unnestR, identity } from '../common/common';\nimport { isArray } from '../common/predicates';\n\nimport {\n TransitionOptions, TransitionHookOptions, IHookRegistry, TreeChanges, IMatchingNodes,\n TransitionHookPhase, TransitionHookScope,\n} from './interface';\n\nimport { Transition } from './transition';\nimport { TransitionHook } from './transitionHook';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TransitionService } from './transitionService';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * This class returns applicable TransitionHooks for a specific Transition instance.\n *\n * Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g.\n * myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is\n * determined by the type of hook)\n *\n * The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition.\n *\n * The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder\n * instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private\n * in the Transition class, so we must also provide the Transition's _treeChanges)\n *\n */\nexport class HookBuilder {\n constructor(private transition: Transition) { }\n\n buildHooksForPhase(phase: TransitionHookPhase): TransitionHook[] {\n const $transitions = this.transition.router.transitionService;\n return $transitions._pluginapi._getEvents(phase)\n .map(type => this.buildHooks(type))\n .reduce(unnestR, [])\n .filter(identity);\n }\n\n /**\n * Returns an array of newly built TransitionHook objects.\n *\n * - Finds all RegisteredHooks registered for the given `hookType` which matched the transition's [[TreeChanges]].\n * - Finds [[PathNode]] (or `PathNode[]`) to use as the TransitionHook context(s)\n * - For each of the [[PathNode]]s, creates a TransitionHook\n *\n * @param hookType the type of the hook registration function, e.g., 'onEnter', 'onFinish'.\n */\n buildHooks(hookType: TransitionEventType): TransitionHook[] {\n const transition = this.transition;\n const treeChanges = transition.treeChanges();\n\n // Find all the matching registered hooks for a given hook type\n const matchingHooks = this.getMatchingHooks(hookType, treeChanges);\n if (!matchingHooks) return [];\n\n const baseHookOptions = {\n transition: transition,\n current: transition.options().current,\n };\n\n const makeTransitionHooks = (hook: RegisteredHook) => {\n // Fetch the Nodes that caused this hook to match.\n const matches: IMatchingNodes = hook.matches(treeChanges);\n // Select the PathNode[] that will be used as TransitionHook context objects\n const matchingNodes: PathNode[] = matches[hookType.criteriaMatchPath.name];\n\n // Return an array of HookTuples\n return matchingNodes.map(node => {\n const _options = extend({\n bind: hook.bind,\n traceData: { hookType: hookType.name, context: node },\n }, baseHookOptions);\n\n const state = hookType.criteriaMatchPath.scope === TransitionHookScope.STATE ? node.state.self : null;\n const transitionHook = new TransitionHook(transition, state, hook, _options);\n return { hook, node, transitionHook };\n });\n };\n\n return matchingHooks.map(makeTransitionHooks)\n .reduce(unnestR, [])\n .sort(tupleSort(hookType.reverseSort))\n .map(tuple => tuple.transitionHook);\n }\n\n /**\n * Finds all RegisteredHooks from:\n * - The Transition object instance hook registry\n * - The TransitionService ($transitions) global hook registry\n *\n * which matched:\n * - the eventType\n * - the matchCriteria (to, from, exiting, retained, entering)\n *\n * @returns an array of matched [[RegisteredHook]]s\n */\n public getMatchingHooks(hookType: TransitionEventType, treeChanges: TreeChanges): RegisteredHook[] {\n const isCreate = hookType.hookPhase === TransitionHookPhase.CREATE;\n\n // Instance and Global hook registries\n const $transitions = this.transition.router.transitionService;\n const registries = isCreate ? [ $transitions ] : [ this.transition, $transitions ];\n\n return registries.map((reg: IHookRegistry) => reg.getHooks(hookType.name)) // Get named hooks from registries\n .filter(assertPredicate(isArray, `broken event named: ${hookType.name}`)) // Sanity check\n .reduce(unnestR, []) // Un-nest RegisteredHook[][] to RegisteredHook[] array\n .filter(hook => hook.matches(treeChanges)); // Only those satisfying matchCriteria\n }\n}\n\ninterface HookTuple { hook: RegisteredHook, node: PathNode, transitionHook: TransitionHook }\n\n/**\n * A factory for a sort function for HookTuples.\n *\n * The sort function first compares the PathNode depth (how deep in the state tree a node is), then compares\n * the EventHook priority.\n *\n * @param reverseDepthSort a boolean, when true, reverses the sort order for the node depth\n * @returns a tuple sort function\n */\nfunction tupleSort(reverseDepthSort = false) {\n return function nodeDepthThenPriority(l: HookTuple, r: HookTuple): number {\n const factor = reverseDepthSort ? -1 : 1;\n const depthDelta = (l.node.state.path.length - r.node.state.path.length) * factor;\n return depthDelta !== 0 ? depthDelta : r.hook.priority - l.hook.priority;\n };\n}\n", - "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, filter, map } from '../common/common';\nimport { isArray, isDefined } from '../common/predicates';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * An internal class which implements [[ParamTypeDefinition]].\n *\n * A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types.\n * When a param type definition is registered, an instance of this class is created internally.\n *\n * This class has naive implementations for all the [[ParamTypeDefinition]] methods.\n *\n * Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values.\n *\n * #### Example:\n * ```js\n * var paramTypeDef = {\n * decode: function(val) { return parseInt(val, 10); },\n * encode: function(val) { return val && val.toString(); },\n * equals: function(a, b) { return this.is(a) && a === b; },\n * is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; },\n * pattern: /\\d+/\n * }\n *\n * var paramType = new ParamType(paramTypeDef);\n * ```\n * @internalapi\n */\nexport class ParamType implements ParamTypeDefinition {\n /** @inheritdoc */\n pattern: RegExp = /.*/;\n /** The name/id of the parameter type */\n name: string;\n /** @inheritdoc */\n raw: boolean;\n /** @inheritdoc */\n dynamic: boolean;\n /** @inheritdoc */\n inherit = true;\n\n /**\n * @param def A configuration object which contains the custom type definition. The object's\n * properties will override the default methods and/or pattern in `ParamType`'s public interface.\n * @returns a new ParamType object\n */\n constructor(def: ParamTypeDefinition) {\n extend(this, def);\n }\n\n\n // consider these four methods to be \"abstract methods\" that should be overridden\n /** @inheritdoc */\n is(val: any, key?: string): boolean { return true; }\n /** @inheritdoc */\n encode(val: any, key?: string): (string|string[]) { return val; }\n /** @inheritdoc */\n decode(val: string, key?: string): any { return val; }\n /** @inheritdoc */\n equals(a: any, b: any): boolean { return a == b; } // tslint:disable-line:triple-equals\n\n\n $subPattern() {\n const sub = this.pattern.toString();\n return sub.substr(1, sub.length - 2);\n }\n\n toString() {\n return `{ParamType:${this.name}}`;\n }\n\n /** Given an encoded string, or a decoded object, returns a decoded object */\n $normalize(val: any) {\n return this.is(val) ? val : this.decode(val);\n }\n\n /**\n * Wraps an existing custom ParamType as an array of ParamType, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\n $asArray(mode: (boolean|'auto'), isSearch: boolean) {\n if (!mode) return this;\n if (mode === 'auto' && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n return new ( ArrayType)(this, mode);\n }\n}\n\n/**\n * Wraps up a `ParamType` object to handle array values.\n * @internalapi\n */\nfunction ArrayType(type: ParamType, mode: (boolean|'auto')) {\n // Wrap non-array value as array\n function arrayWrap(val: any): any[] {\n return isArray(val) ? val : (isDefined(val) ? [ val ] : []);\n }\n\n // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n function arrayUnwrap(val: any) {\n switch (val.length) {\n case 0: return undefined;\n case 1: return mode === 'auto' ? val[0] : val;\n default: return val;\n }\n }\n\n // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n function arrayHandler(callback: (x: any) => any, allTruthyMode?: boolean) {\n return function handleArray(val: any) {\n if (isArray(val) && val.length === 0) return val;\n const arr = arrayWrap(val);\n const result = map(arr, callback);\n return (allTruthyMode === true) ? filter(result, x => !x).length === 0 : arrayUnwrap(result);\n };\n }\n\n // Wraps type (.equals) functions to operate on each value of an array\n function arrayEqualsHandler(callback: (l: any, r: any) => boolean) {\n return function handleArray(val1: any, val2: any) {\n const left = arrayWrap(val1), right = arrayWrap(val2);\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!callback(left[i], right[i])) return false;\n }\n return true;\n };\n }\n\n ['encode', 'decode', 'equals', '$normalize'].forEach(name => {\n const paramTypeFn = type[name].bind(type);\n const wrapperFn: Function = name === 'equals' ? arrayEqualsHandler : arrayHandler;\n this[name] = wrapperFn(paramTypeFn);\n });\n\n extend(this, {\n dynamic: type.dynamic,\n name: type.name,\n pattern: type.pattern,\n inherit: type.inherit,\n is: arrayHandler(type.is.bind(type), true),\n $arrayMode: mode,\n });\n}\n", - "/**\n * @coreapi\n * @module params\n */ /** for typedoc */\nimport { extend, filter, map, allTrueR } from '../common/common';\nimport { prop } from '../common/hof';\nimport { isInjectable, isDefined, isString, isArray, isUndefined } from '../common/predicates';\nimport { RawParams, ParamDeclaration } from '../params/interface';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypes } from './paramTypes';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\n\n/** @hidden */\nconst hasOwn = Object.prototype.hasOwnProperty;\n\n/** @hidden */\nconst isShorthand = (cfg: ParamDeclaration) =>\n ['value', 'type', 'squash', 'array', 'dynamic'].filter(hasOwn.bind(cfg || {})).length === 0;\n\n/** @internalapi */\nexport enum DefType {\n PATH,\n SEARCH,\n CONFIG,\n}\n\n/** @hidden */\nfunction unwrapShorthand(cfg: ParamDeclaration): ParamDeclaration {\n cfg = isShorthand(cfg) && { value: cfg } as any || cfg;\n\n getStaticDefaultValue['__cacheable'] = true;\n function getStaticDefaultValue() {\n return cfg.value;\n }\n\n return extend(cfg, {\n $$fn: isInjectable(cfg.value) ? cfg.value : getStaticDefaultValue,\n });\n}\n\n/** @hidden */\nfunction getType(cfg: ParamDeclaration, urlType: ParamType, location: DefType, id: string, paramTypes: ParamTypes) {\n if (cfg.type && urlType && urlType.name !== 'string') throw new Error(`Param '${id}' has two type configurations.`);\n if (cfg.type && urlType && urlType.name === 'string' && paramTypes.type(cfg.type as string)) return paramTypes.type(cfg.type as string);\n if (urlType) return urlType;\n if (!cfg.type) {\n const type = location === DefType.CONFIG ? 'any' :\n location === DefType.PATH ? 'path' :\n location === DefType.SEARCH ? 'query' : 'string';\n return paramTypes.type(type);\n }\n return cfg.type instanceof ParamType ? cfg.type : paramTypes.type(cfg.type as string);\n}\n\n/**\n * @internalapi\n * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n */\nfunction getSquashPolicy(config: ParamDeclaration, isOptional: boolean, defaultPolicy: (boolean|string)) {\n const squash = config.squash;\n if (!isOptional || squash === false) return false;\n if (!isDefined(squash) || squash == null) return defaultPolicy;\n if (squash === true || isString(squash)) return squash;\n throw new Error(`Invalid squash policy: '${squash}'. Valid policies: false, true, or arbitrary string`);\n}\n\n/** @internalapi */\nfunction getReplace(config: ParamDeclaration, arrayMode: boolean, isOptional: boolean, squash: (string|boolean)) {\n const defaultPolicy = [\n { from: '', to: (isOptional || arrayMode ? undefined : '') },\n { from: null, to: (isOptional || arrayMode ? undefined : '') },\n ];\n\n const replace = isArray(config.replace) ? config.replace : [];\n if (isString(squash)) replace.push({ from: squash, to: undefined });\n\n const configuredKeys = map(replace, prop('from'));\n return filter(defaultPolicy, item => configuredKeys.indexOf(item.from) === -1).concat(replace);\n}\n\n\n/** @internalapi */\nexport class Param {\n id: string;\n type: ParamType;\n location: DefType;\n isOptional: boolean;\n dynamic: boolean;\n raw: boolean;\n squash: (boolean|string);\n replace: [{ to: any, from: any }];\n inherit: boolean;\n array: boolean;\n config: any;\n /** Cache the default value if it is a static value */\n _defaultValueCache: {\n defaultValue: any,\n };\n\n static values(params: Param[], values: RawParams = {}): RawParams {\n const paramValues = {} as RawParams;\n for (const param of params) {\n paramValues[param.id] = param.value(values[param.id]);\n }\n return paramValues;\n }\n\n /**\n * Finds [[Param]] objects which have different param values\n *\n * Filters a list of [[Param]] objects to only those whose parameter values differ in two param value objects\n *\n * @param params: The list of Param objects to filter\n * @param values1: The first set of parameter values\n * @param values2: the second set of parameter values\n *\n * @returns any Param objects whose values were different between values1 and values2\n */\n static changed(params: Param[], values1: RawParams = {}, values2: RawParams = {}): Param[] {\n return params.filter(param => !param.type.equals(values1[param.id], values2[param.id]));\n }\n\n /**\n * Checks if two param value objects are equal (for a set of [[Param]] objects)\n *\n * @param params The list of [[Param]] objects to check\n * @param values1 The first set of param values\n * @param values2 The second set of param values\n *\n * @returns true if the param values in values1 and values2 are equal\n */\n static equals(params: Param[], values1 = {}, values2 = {}): boolean {\n return Param.changed(params, values1, values2).length === 0;\n }\n\n /** Returns true if a the parameter values are valid, according to the Param definitions */\n static validates(params: Param[], values: RawParams = {}): boolean {\n return params.map(param => param.validates(values[param.id])).reduce(allTrueR, true);\n }\n\n constructor(id: string, type: ParamType, config: ParamDeclaration, location: DefType, urlMatcherFactory: UrlMatcherFactory) {\n config = unwrapShorthand(config);\n type = getType(config, type, location, id, urlMatcherFactory.paramTypes);\n const arrayMode = getArrayMode();\n type = arrayMode ? type.$asArray(arrayMode, location === DefType.SEARCH) : type;\n const isOptional = config.value !== undefined || location === DefType.SEARCH;\n const dynamic = isDefined(config.dynamic) ? !!config.dynamic : !!type.dynamic;\n const raw = isDefined(config.raw) ? !!config.raw : !!type.raw;\n const squash = getSquashPolicy(config, isOptional, urlMatcherFactory.defaultSquashPolicy());\n const replace = getReplace(config, arrayMode, isOptional, squash);\n const inherit = isDefined(config.inherit) ? !!config.inherit : !!type.inherit;\n\n // array config: param name (param[]) overrides default settings. explicit config overrides param name.\n function getArrayMode() {\n const arrayDefaults = { array: (location === DefType.SEARCH ? 'auto' : false) };\n const arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n return extend(arrayDefaults, arrayParamNomenclature, config).array;\n }\n\n extend(this, { id, type, location, isOptional, dynamic, raw, squash, replace, inherit, array: arrayMode, config });\n }\n\n isDefaultValue(value: any): boolean {\n return this.isOptional && this.type.equals(this.value(), value);\n }\n\n /**\n * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n * default value, which may be the result of an injectable function.\n */\n value(value?: any): any {\n /**\n * [Internal] Get the default value of a parameter, which may be an injectable function.\n */\n const getDefaultValue = () => {\n if (this._defaultValueCache) return this._defaultValueCache.defaultValue;\n\n if (!services.$injector) throw new Error('Injectable functions cannot be called at configuration time');\n\n const defaultValue = services.$injector.invoke(this.config.$$fn);\n\n if (defaultValue !== null && defaultValue !== undefined && !this.type.is(defaultValue))\n throw new Error(`Default value (${defaultValue}) for parameter '${this.id}' is not an instance of ParamType (${this.type.name})`);\n\n if (this.config.$$fn['__cacheable']) {\n this._defaultValueCache = { defaultValue };\n }\n\n return defaultValue;\n };\n\n const replaceSpecialValues = (val: any) => {\n for (const tuple of this.replace) {\n if (tuple.from === val) return tuple.to;\n }\n return val;\n };\n\n value = replaceSpecialValues(value);\n\n return isUndefined(value) ? getDefaultValue() : this.type.$normalize(value);\n }\n\n isSearch(): boolean {\n return this.location === DefType.SEARCH;\n }\n\n validates(value: any): boolean {\n // There was no parameter value, but the param is optional\n if ((isUndefined(value) || value === null) && this.isOptional) return true;\n\n // The value was not of the correct ParamType, and could not be decoded to the correct ParamType\n const normalized = this.type.$normalize(value);\n if (!this.type.is(normalized)) return false;\n\n // The value was of the correct type, but when encoded, did not match the ParamType's regexp\n const encoded = this.type.encode(normalized);\n return !(isString(encoded) && !this.type.pattern.exec( encoded));\n }\n\n toString() {\n return `{Param:${this.id} ${this.type} squash: '${this.squash}' optional: ${this.isOptional}}`;\n }\n}\n", - "/** @module path */ /** for typedoc */\nimport { extend, applyPairs, find, allTrueR, pairs, arrayTuples } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\n\n/**\n * @internalapi\n *\n * A node in a [[TreeChanges]] path\n *\n * For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path.\n * Each PathNode corresponds to a state being entered, exited, or retained.\n * The stateful information includes parameter values and resolve data.\n */\nexport class PathNode {\n /** The state being entered, exited, or retained */\n public state: StateObject;\n /** The parameters declared on the state */\n public paramSchema: Param[];\n /** The parameter values that belong to the state */\n public paramValues: { [key: string]: any };\n /** The individual (stateful) resolvable objects that belong to the state */\n public resolvables: Resolvable[];\n /** The state's declared view configuration objects */\n public views: ViewConfig[];\n\n /**\n * Returns a clone of the PathNode\n * @deprecated use instance method `node.clone()`\n */\n static clone = (node: PathNode) => node.clone();\n\n /** Creates a copy of a PathNode */\n constructor(node: PathNode);\n /** Creates a new (empty) PathNode for a State */\n constructor(state: StateObject);\n constructor(stateOrNode: any) {\n if (stateOrNode instanceof PathNode) {\n const node: PathNode = stateOrNode;\n this.state = node.state;\n this.paramSchema = node.paramSchema.slice();\n this.paramValues = extend({}, node.paramValues);\n this.resolvables = node.resolvables.slice();\n this.views = node.views && node.views.slice();\n } else {\n const state: StateObject = stateOrNode;\n this.state = state;\n this.paramSchema = state.parameters({ inherit: false });\n this.paramValues = {};\n this.resolvables = state.resolvables.map(res => res.clone());\n }\n }\n\n clone() {\n return new PathNode(this);\n }\n\n /** Sets [[paramValues]] for the node, from the values of an object hash */\n applyRawParams(params: RawParams): PathNode {\n const getParamVal = (paramDef: Param) => [ paramDef.id, paramDef.value(params[paramDef.id]) ];\n this.paramValues = this.paramSchema.reduce((memo, pDef) => applyPairs(memo, getParamVal(pDef)), {});\n return this;\n }\n\n /** Gets a specific [[Param]] metadata that belongs to the node */\n parameter(name: string): Param {\n return find(this.paramSchema, propEq('id', name));\n }\n\n /**\n * @returns true if the state and parameter values for another PathNode are\n * equal to the state and param values for this PathNode\n */\n equals(node: PathNode, paramsFn?: GetParamsFn): boolean {\n const diff = this.diff(node, paramsFn);\n return diff && diff.length === 0;\n }\n\n /**\n * Finds Params with different parameter values on another PathNode.\n *\n * Given another node (of the same state), finds the parameter values which differ.\n * Returns the [[Param]] (schema objects) whose parameter values differ.\n *\n * Given another node for a different state, returns `false`\n *\n * @param node The node to compare to\n * @param paramsFn A function that returns which parameters should be compared.\n * @returns The [[Param]]s which differ, or null if the two nodes are for different states\n */\n diff(node: PathNode, paramsFn?: GetParamsFn): Param[] | false {\n if (this.state !== node.state) return false;\n\n const params: Param[] = paramsFn ? paramsFn(this) : this.paramSchema;\n return Param.changed(params, this.paramValues, node.paramValues);\n }\n}\n\n/** @hidden */\nexport type GetParamsFn = (pathNode: PathNode) => Param[];\n", - "/** @module path */ /** for typedoc */\n\nimport {\n extend, find, pick, omit, tail, mergeR, values, unnestR, Predicate, inArray, arrayTuples,\n} from '../common/common';\nimport { prop, propEq, not } from '../common/hof';\n\nimport { RawParams } from '../params/interface';\nimport { TreeChanges } from '../transition/interface';\nimport { ViewConfig } from '../view/interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { GetParamsFn, PathNode } from './pathNode';\nimport { ViewService } from '../view/view';\nimport { Param } from '../params/param';\nimport { StateRegistry } from '../state';\n\n/**\n * This class contains functions which convert TargetStates, Nodes and paths from one type to another.\n */\nexport class PathUtils {\n /** Given a PathNode[], create an TargetState */\n static makeTargetState(registry: StateRegistry, path: PathNode[]): TargetState {\n const state = tail(path).state;\n return new TargetState(registry, state, path.map(prop('paramValues')).reduce(mergeR, {}), {});\n }\n\n static buildPath(targetState: TargetState) {\n const toParams = targetState.params();\n return targetState.$state().path.map(state => new PathNode(state).applyRawParams(toParams));\n }\n\n /** Given a fromPath: PathNode[] and a TargetState, builds a toPath: PathNode[] */\n static buildToPath(fromPath: PathNode[], targetState: TargetState): PathNode[] {\n const toPath: PathNode[] = PathUtils.buildPath(targetState);\n if (targetState.options().inherit) {\n return PathUtils.inheritParams(fromPath, toPath, Object.keys(targetState.params()));\n }\n return toPath;\n }\n\n /**\n * Creates ViewConfig objects and adds to nodes.\n *\n * On each [[PathNode]], creates ViewConfig objects from the views: property of the node's state\n */\n static applyViewConfigs($view: ViewService, path: PathNode[], states: StateObject[]) {\n // Only apply the viewConfigs to the nodes for the given states\n path.filter(node => inArray(states, node.state)).forEach(node => {\n const viewDecls: _ViewDeclaration[] = values(node.state.views || {});\n const subPath = PathUtils.subPath(path, n => n === node);\n const viewConfigs: ViewConfig[][] = viewDecls.map(view => $view.createViewConfig(subPath, view));\n node.views = viewConfigs.reduce(unnestR, []);\n });\n }\n\n /**\n * Given a fromPath and a toPath, returns a new to path which inherits parameters from the fromPath\n *\n * For a parameter in a node to be inherited from the from path:\n * - The toPath's node must have a matching node in the fromPath (by state).\n * - The parameter name must not be found in the toKeys parameter array.\n *\n * Note: the keys provided in toKeys are intended to be those param keys explicitly specified by some\n * caller, for instance, $state.transitionTo(..., toParams). If a key was found in toParams,\n * it is not inherited from the fromPath.\n */\n static inheritParams(fromPath: PathNode[], toPath: PathNode[], toKeys: string[] = []): PathNode[] {\n function nodeParamVals(path: PathNode[], state: StateObject): RawParams {\n const node: PathNode = find(path, propEq('state', state));\n return extend({}, node && node.paramValues);\n }\n\n const noInherit = fromPath.map(node => node.paramSchema)\n .reduce(unnestR, [])\n .filter(param => !param.inherit)\n .map(prop('id'));\n\n /**\n * Given an [[PathNode]] \"toNode\", return a new [[PathNode]] with param values inherited from the\n * matching node in fromPath. Only inherit keys that aren't found in \"toKeys\" from the node in \"fromPath\"\"\n */\n function makeInheritedParamsNode(toNode: PathNode): PathNode {\n // All param values for the node (may include default key/vals, when key was not found in toParams)\n let toParamVals = extend({}, toNode && toNode.paramValues);\n // limited to only those keys found in toParams\n const incomingParamVals = pick(toParamVals, toKeys);\n toParamVals = omit(toParamVals, toKeys);\n const fromParamVals = omit(nodeParamVals(fromPath, toNode.state) || {}, noInherit);\n // extend toParamVals with any fromParamVals, then override any of those those with incomingParamVals\n const ownParamVals: RawParams = extend(toParamVals, fromParamVals, incomingParamVals);\n return new PathNode(toNode.state).applyRawParams(ownParamVals);\n }\n\n // The param keys specified by the incoming toParams\n return toPath.map(makeInheritedParamsNode);\n }\n\n static nonDynamicParams = (node: PathNode): Param[] =>\n node.state.parameters({ inherit: false })\n .filter(param => !param.dynamic);\n\n /**\n * Computes the tree changes (entering, exiting) between a fromPath and toPath.\n */\n static treeChanges(fromPath: PathNode[], toPath: PathNode[], reloadState: StateObject): TreeChanges {\n const max = Math.min(fromPath.length, toPath.length);\n let keep = 0;\n\n const nodesMatch = (node1: PathNode, node2: PathNode) =>\n node1.equals(node2, PathUtils.nonDynamicParams);\n\n while (keep < max && fromPath[keep].state !== reloadState && nodesMatch(fromPath[keep], toPath[keep])) {\n keep++;\n }\n\n /** Given a retained node, return a new node which uses the to node's param values */\n function applyToParams(retainedNode: PathNode, idx: number): PathNode {\n const cloned = retainedNode.clone();\n cloned.paramValues = toPath[idx].paramValues;\n return cloned;\n }\n\n let from: PathNode[], retained: PathNode[], exiting: PathNode[], entering: PathNode[], to: PathNode[];\n\n from = fromPath;\n retained = from.slice(0, keep);\n exiting = from.slice(keep);\n\n // Create a new retained path (with shallow copies of nodes) which have the params of the toPath mapped\n const retainedWithToParams = retained.map(applyToParams);\n entering = toPath.slice(keep);\n to = (retainedWithToParams).concat(entering);\n\n return { from, to, retained, retainedWithToParams, exiting, entering };\n }\n\n /**\n * Returns a new path which is: the subpath of the first path which matches the second path.\n *\n * The new path starts from root and contains any nodes that match the nodes in the second path.\n * It stops before the first non-matching node.\n *\n * Nodes are compared using their state property and their parameter values.\n * If a `paramsFn` is provided, only the [[Param]] returned by the function will be considered when comparing nodes.\n *\n * @param pathA the first path\n * @param pathB the second path\n * @param paramsFn a function which returns the parameters to consider when comparing\n *\n * @returns an array of PathNodes from the first path which match the nodes in the second path\n */\n static matching(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): PathNode[] {\n let done = false;\n const tuples: PathNode[][] = arrayTuples(pathA, pathB);\n return tuples.reduce((matching, [nodeA, nodeB]) => {\n done = done || !nodeA.equals(nodeB, paramsFn);\n return done ? matching : matching.concat(nodeA);\n }, []);\n }\n\n /**\n * Returns true if two paths are identical.\n *\n * @param pathA\n * @param pathB\n * @param paramsFn a function which returns the parameters to consider when comparing\n * @returns true if the the states and parameter values for both paths are identical\n */\n static equals(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): boolean {\n return pathA.length === pathB.length &&\n PathUtils.matching(pathA, pathB, paramsFn).length === pathA.length;\n }\n\n /**\n * Return a subpath of a path, which stops at the first matching node\n *\n * Given an array of nodes, returns a subset of the array starting from the first node,\n * stopping when the first node matches the predicate.\n *\n * @param path a path of [[PathNode]]s\n * @param predicate a [[Predicate]] fn that matches [[PathNode]]s\n * @returns a subpath up to the matching node, or undefined if no match is found\n */\n static subPath(path: PathNode[], predicate: Predicate): PathNode[] {\n const node = find(path, predicate);\n const elementIdx = path.indexOf(node);\n return elementIdx === -1 ? undefined : path.slice(0, elementIdx + 1);\n }\n\n /** Gets the raw parameter values from a path */\n static paramValues = (path: PathNode[]) =>\n path.reduce((acc, node) => extend(acc, node.paramValues), {});\n}\n", - "/**\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { extend, equals, inArray, identity } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { trace } from '../common/trace';\nimport { ResolvePolicy, ResolvableLiteral, resolvePolicies } from './interface';\n\nimport { ResolveContext } from './resolveContext';\nimport { stringify } from '../common/strings';\nimport { isFunction, isObject } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { isNullOrUndefined } from '../common/predicates';\n\n\n// TODO: explicitly make this user configurable\nexport let defaultResolvePolicy: ResolvePolicy = {\n when: 'LAZY',\n async: 'WAIT',\n};\n\n/**\n * The basic building block for the resolve system.\n *\n * Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise),\n * and the unwrapped-when-complete (.data) result of the resolveFn.\n *\n * Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the\n * resolveFn) and returns the resulting promise.\n *\n * Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first\n * parameter to those fns.\n */\nexport class Resolvable implements ResolvableLiteral {\n token: any;\n policy: ResolvePolicy;\n resolveFn: Function;\n deps: any[];\n\n data: any;\n resolved = false;\n promise: Promise = undefined;\n\n static fromData = (token: any, data: any) =>\n new Resolvable(token, () => data, null, null, data);\n\n /** This constructor creates a Resolvable copy */\n constructor(resolvable: Resolvable)\n\n /** This constructor creates a new Resolvable from the plain old [[ResolvableLiteral]] javascript object */\n constructor(resolvable: ResolvableLiteral)\n\n /**\n * This constructor creates a new `Resolvable`\n *\n * #### Example:\n * ```js\n * var resolvable1 = new Resolvable('mytoken', http => http.get('foo.json').toPromise(), [Http]);\n *\n * var resolvable2 = new Resolvable(UserService, dep => new UserService(dep.data), [SomeDependency]);\n *\n * var resolvable1Clone = new Resolvable(resolvable1);\n * ```\n *\n * @param token The new resolvable's injection token, such as `\"userList\"` (a string) or `UserService` (a class).\n * When this token is used during injection, the resolved value will be injected.\n * @param resolveFn The function that returns the resolved value, or a promise for the resolved value\n * @param deps An array of dependencies, which will be injected into the `resolveFn`\n * @param policy the [[ResolvePolicy]] defines when and how the Resolvable is processed\n * @param data Pre-resolved data. If the resolve value is already known, it may be provided here.\n */\n constructor(token: any, resolveFn: Function, deps?: any[], policy?: ResolvePolicy, data?: any)\n constructor(arg1: any, resolveFn?: Function, deps?: any[], policy?: ResolvePolicy, data?: any) {\n if (arg1 instanceof Resolvable) {\n extend(this, arg1);\n } else if (isFunction(resolveFn)) {\n if (isNullOrUndefined(arg1)) throw new Error('new Resolvable(): token argument is required');\n if (!isFunction(resolveFn)) throw new Error('new Resolvable(): resolveFn argument must be a function');\n\n this.token = arg1;\n this.policy = policy;\n this.resolveFn = resolveFn;\n this.deps = deps || [];\n\n this.data = data;\n this.resolved = data !== undefined;\n this.promise = this.resolved ? services.$q.when(this.data) : undefined;\n } else if (isObject(arg1) && arg1.token && (arg1.hasOwnProperty('resolveFn') || arg1.hasOwnProperty('data'))) {\n const literal = arg1;\n return new Resolvable(literal.token, literal.resolveFn, literal.deps, literal.policy, literal.data);\n }\n }\n\n getPolicy(state: StateObject): ResolvePolicy {\n const thisPolicy = this.policy || {};\n const statePolicy = state && state.resolvePolicy || {};\n return {\n when: thisPolicy.when || statePolicy.when || defaultResolvePolicy.when,\n async: thisPolicy.async || statePolicy.async || defaultResolvePolicy.async,\n };\n }\n\n /**\n * Asynchronously resolve this Resolvable's data\n *\n * Given a ResolveContext that this Resolvable is found in:\n * Wait for this Resolvable's dependencies, then invoke this Resolvable's function\n * and update the Resolvable's state\n */\n resolve(resolveContext: ResolveContext, trans?: Transition) {\n const $q = services.$q;\n\n // Gets all dependencies from ResolveContext and wait for them to be resolved\n const getResolvableDependencies = () =>\n $q.all(resolveContext.getDependencies(this).map(resolvable =>\n resolvable.get(resolveContext, trans))) as Promise;\n\n // Invokes the resolve function passing the resolved dependencies as arguments\n const invokeResolveFn = (resolvedDeps: any[]) =>\n this.resolveFn.apply(null, resolvedDeps);\n\n /**\n * For RXWAIT policy:\n *\n * Given an observable returned from a resolve function:\n * - enables .cache() mode (this allows multicast subscribers)\n * - then calls toPromise() (this triggers subscribe() and thus fetches)\n * - Waits for the promise, then return the cached observable (not the first emitted value).\n */\n const waitForRx = (observable$: any) => {\n const cached = observable$.cache(1);\n return cached.take(1).toPromise().then(() => cached);\n };\n\n // If the resolve policy is RXWAIT, wait for the observable to emit something. otherwise pass through.\n const node: PathNode = resolveContext.findNode(this);\n const state: StateObject = node && node.state;\n const maybeWaitForRx = this.getPolicy(state).async === 'RXWAIT' ? waitForRx : identity;\n\n // After the final value has been resolved, update the state of the Resolvable\n const applyResolvedValue = (resolvedValue: any) => {\n this.data = resolvedValue;\n this.resolved = true;\n this.resolveFn = null;\n trace.traceResolvableResolved(this, trans);\n return this.data;\n };\n\n // Sets the promise property first, then getsResolvableDependencies in the context of the promise chain. Always waits one tick.\n return this.promise = $q.when()\n .then(getResolvableDependencies)\n .then(invokeResolveFn)\n .then(maybeWaitForRx)\n .then(applyResolvedValue);\n }\n\n /**\n * Gets a promise for this Resolvable's data.\n *\n * Fetches the data and returns a promise.\n * Returns the existing promise if it has already been fetched once.\n */\n get(resolveContext: ResolveContext, trans?: Transition): Promise {\n return this.promise || this.resolve(resolveContext, trans);\n }\n\n toString() {\n return `Resolvable(token: ${stringify(this.token)}, requires: [${this.deps.map(stringify)}])`;\n }\n\n clone(): Resolvable {\n return new Resolvable(this);\n }\n}\n", - "/**\n * # The Resolve subsystem\n *\n * This subsystem is an asynchronous, hierarchical Dependency Injection system.\n *\n * Typically, resolve is configured on a state using a [[StateDeclaration.resolve]] declaration.\n *\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { Resolvable } from './resolvable';\n\n/**\n * An interface which is similar to an Angular 2 `Provider`\n */\nexport interface ProviderLike {\n provide: any,\n useClass?: any,\n useFactory?: Function,\n useValue?: any,\n useExisting?: any,\n deps?: any[]\n}\n\n/**\n * A plain object used to describe a [[Resolvable]]\n *\n * These objects may be used in the [[StateDeclaration.resolve]] array to declare\n * async data that the state or substates require.\n *\n * #### Example:\n * ```js\n *\n * var state = {\n * name: 'main',\n * resolve: [\n * { token: 'myData', deps: [MyDataApi], resolveFn: (myDataApi) => myDataApi.getData() },\n * ],\n * }\n * ```\n */\nexport interface ResolvableLiteral {\n /**\n * A Dependency Injection token\n *\n * This Resolvable's DI token.\n * The Resolvable will be injectable elsewhere using the token.\n */\n token: any;\n\n /**\n * A function which fetches the Resolvable's data\n *\n * A function which returns one of:\n *\n * - The resolved value (synchronously)\n * - A promise for the resolved value\n * - An Observable of the resolved value(s)\n *\n * This function will be provided the dependencies listed in [[deps]] as its arguments.\n * The resolve system will asynchronously fetch the dependencies before invoking this function.\n */\n resolveFn: Function;\n\n /**\n * Defines the Resolve Policy\n *\n * A policy that defines when to invoke the resolve,\n * and whether to wait for async and unwrap the data\n */\n policy?: ResolvePolicy;\n\n /**\n * The Dependency Injection tokens\n *\n * This is an array of Dependency Injection tokens for the dependencies of the [[resolveFn]].\n *\n * The DI tokens are references to other `Resolvables`, or to other\n * services from the native DI system.\n */\n deps?: any[];\n\n /** Pre-resolved data. */\n data?: any\n}\n\n/**\n * Defines how a resolve is processed during a transition\n *\n * This object is the [[StateDeclaration.resolvePolicy]] property.\n *\n * #### Example:\n * ```js\n * // Fetched when the resolve's state is being entered.\n * // Wait for the promise to resolve.\n * var policy1 = { when: \"LAZY\", async: \"WAIT\" }\n *\n * // Fetched when the Transition is starting.\n * // Do not wait for the returned promise to resolve.\n * // Inject the raw promise/value\n * var policy2 = { when: \"EAGER\", async: \"NOWAIT\" }\n * ```\n *\n * The policy for a given Resolvable is merged from three sources (highest priority first):\n *\n * - 1) Individual resolve definition\n * - 2) State definition\n * - 3) Global default\n *\n * #### Example:\n * ```js\n * // Wait for an Observable to emit one item.\n * // Since `wait` is not specified, it uses the `wait`\n * // policy defined on the state, or the global default\n * // if no `wait` policy is defined on the state\n * var myResolvablePolicy = { async: \"RXWAIT\" }\n * ```\n */\nexport interface ResolvePolicy {\n /**\n * Defines when a Resolvable is resolved (fetched) during a transition\n *\n * - `LAZY` (default)\n * - Resolved as the resolve's state is being entered\n * - `EAGER`\n * - Resolved as the transition is starting\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched when each state is entered.\n * All of `main` resolves are processed before fetching `main.home` resolves.\n * ```js\n * var state = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n *\n * var state = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n * ```\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched at the same time when the transition starts.\n * This happens earlier in the lifecycle than when states are entered.\n * All of the `main` and `main.home` resolves are fetched as soon as possible.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n *\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n * ```\n */\n when?: PolicyWhen;\n\n /**\n * Determines the unwrapping behavior of asynchronous resolve values.\n *\n * - `WAIT` (default)\n * - If a promise is returned from the resolveFn, wait for the promise before proceeding\n * - The unwrapped value from the promise\n * - `NOWAIT`\n * - If a promise is returned from the resolve, do not wait for the promise.\n * - Any other value returned is wrapped in a promise.\n * - The promise will not be unwrapped.\n * - The promise itself will be provided when the resolve is injected or bound elsewhere.\n * - `RXWAIT`\n * - When an Observable is returned from the resolveFn, wait until the Observable emits at least one item.\n * - The Observable item will not be unwrapped.\n * - The Observable stream itself will be provided when the resolve is injected or bound elsewhere.\n *\n * #### Example:\n * The `Transition` will not wait for the resolve promise(s) from `main` to settle before continuing.\n * Resolves for `main` will be provided to components wrapped in a `Promise`.\n *\n * The `Transition` will wait for the `main.home` resolve promises.\n * Resolved values will be unwrapped before being provided to components.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { async: 'NOWAIT' },\n * }\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { async: 'WAIT' }, // default\n * }\n * ```\n */\n async?: PolicyAsync;\n}\n\nexport type PolicyWhen = 'LAZY' | 'EAGER' ;\nexport type PolicyAsync = 'WAIT' | 'NOWAIT' | 'RXWAIT' ;\n\n/** @internalapi */\nexport let resolvePolicies = {\n when: {\n LAZY: 'LAZY',\n EAGER: 'EAGER',\n },\n async: {\n WAIT: 'WAIT',\n NOWAIT: 'NOWAIT',\n RXWAIT: 'RXWAIT',\n },\n};\n", - "/** @module resolve */\n/** for typedoc */\nimport { find, tail, uniqR, unnestR, inArray } from '../common/common';\nimport { propEq, not } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services, $InjectorLike } from '../common/coreservices';\nimport { resolvePolicies, PolicyWhen, ResolvePolicy } from './interface';\nimport { PathNode } from '../path/pathNode';\nimport { Resolvable } from './resolvable';\nimport { StateObject } from '../state/stateObject';\nimport { PathUtils } from '../path/pathUtils';\nimport { stringify } from '../common/strings';\nimport { Transition } from '../transition/transition';\nimport { UIInjector } from '../interface';\nimport { isUndefined } from '../common';\n\nconst whens = resolvePolicies.when;\nconst ALL_WHENS = [whens.EAGER, whens.LAZY];\nconst EAGER_WHENS = [whens.EAGER];\n\n// tslint:disable-next-line:no-inferrable-types\nexport const NATIVE_INJECTOR_TOKEN: string = 'Native Injector';\n\n/**\n * Encapsulates Dependency Injection for a path of nodes\n *\n * UI-Router states are organized as a tree.\n * A nested state has a path of ancestors to the root of the tree.\n * When a state is being activated, each element in the path is wrapped as a [[PathNode]].\n * A `PathNode` is a stateful object that holds things like parameters and resolvables for the state being activated.\n *\n * The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path.\n */\nexport class ResolveContext {\n _injector: UIInjector;\n\n constructor(private _path: PathNode[]) { }\n\n /** Gets all the tokens found in the resolve context, de-duplicated */\n getTokens(): any[] {\n return this._path.reduce((acc, node) => acc.concat(node.resolvables.map(r => r.token)), []).reduce(uniqR, []);\n }\n\n /**\n * Gets the Resolvable that matches the token\n *\n * Gets the last Resolvable that matches the token in this context, or undefined.\n * Throws an error if it doesn't exist in the ResolveContext\n */\n getResolvable(token: any): Resolvable {\n const matching = this._path.map(node => node.resolvables)\n .reduce(unnestR, [])\n .filter((r: Resolvable) => r.token === token);\n return tail(matching);\n }\n\n /** Returns the [[ResolvePolicy]] for the given [[Resolvable]] */\n getPolicy(resolvable: Resolvable): ResolvePolicy {\n const node = this.findNode(resolvable);\n return resolvable.getPolicy(node.state);\n }\n\n /**\n * Returns a ResolveContext that includes a portion of this one\n *\n * Given a state, this method creates a new ResolveContext from this one.\n * The new context starts at the first node (root) and stops at the node for the `state` parameter.\n *\n * #### Why\n *\n * When a transition is created, the nodes in the \"To Path\" are injected from a ResolveContext.\n * A ResolveContext closes over a path of [[PathNode]]s and processes the resolvables.\n * The \"To State\" can inject values from its own resolvables, as well as those from all its ancestor state's (node's).\n * This method is used to create a narrower context when injecting ancestor nodes.\n *\n * @example\n * `let ABCD = new ResolveContext([A, B, C, D]);`\n *\n * Given a path `[A, B, C, D]`, where `A`, `B`, `C` and `D` are nodes for states `a`, `b`, `c`, `d`:\n * When injecting `D`, `D` should have access to all resolvables from `A`, `B`, `C`, `D`.\n * However, `B` should only be able to access resolvables from `A`, `B`.\n *\n * When resolving for the `B` node, first take the full \"To Path\" Context `[A,B,C,D]` and limit to the subpath `[A,B]`.\n * `let AB = ABCD.subcontext(a)`\n */\n subContext(state: StateObject): ResolveContext {\n return new ResolveContext(PathUtils.subPath(this._path, node => node.state === state));\n }\n\n /**\n * Adds Resolvables to the node that matches the state\n *\n * This adds a [[Resolvable]] (generally one created on the fly; not declared on a [[StateDeclaration.resolve]] block).\n * The resolvable is added to the node matching the `state` parameter.\n *\n * These new resolvables are not automatically fetched.\n * The calling code should either fetch them, fetch something that depends on them,\n * or rely on [[resolvePath]] being called when some state is being entered.\n *\n * Note: each resolvable's [[ResolvePolicy]] is merged with the state's policy, and the global default.\n *\n * @param newResolvables the new Resolvables\n * @param state Used to find the node to put the resolvable on\n */\n addResolvables(newResolvables: Resolvable[], state: StateObject) {\n const node = find(this._path, propEq('state', state));\n const keys = newResolvables.map(r => r.token);\n node.resolvables = node.resolvables.filter(r => keys.indexOf(r.token) === -1).concat(newResolvables);\n }\n\n /**\n * Returns a promise for an array of resolved path Element promises\n *\n * @param when\n * @param trans\n * @returns {Promise|any}\n */\n resolvePath(when: PolicyWhen = 'LAZY', trans?: Transition): Promise<{ token: any, value: any }[]> {\n // This option determines which 'when' policy Resolvables we are about to fetch.\n const whenOption: string = inArray(ALL_WHENS, when) ? when : 'LAZY';\n // If the caller specified EAGER, only the EAGER Resolvables are fetched.\n // if the caller specified LAZY, both EAGER and LAZY Resolvables are fetched.`\n const matchedWhens = whenOption === resolvePolicies.when.EAGER ? EAGER_WHENS : ALL_WHENS;\n\n // get the subpath to the state argument, if provided\n trace.traceResolvePath(this._path, when, trans);\n\n const matchesPolicy = (acceptedVals: string[], whenOrAsync: 'when'|'async') =>\n (resolvable: Resolvable) =>\n inArray(acceptedVals, this.getPolicy(resolvable)[whenOrAsync]);\n\n // Trigger all the (matching) Resolvables in the path\n // Reduce all the \"WAIT\" Resolvables into an array\n const promises: Promise[] = this._path.reduce((acc, node) => {\n const nodeResolvables = node.resolvables.filter(matchesPolicy(matchedWhens, 'when'));\n const nowait = nodeResolvables.filter(matchesPolicy(['NOWAIT'], 'async'));\n const wait = nodeResolvables.filter(not(matchesPolicy(['NOWAIT'], 'async')));\n\n // For the matching Resolvables, start their async fetch process.\n const subContext = this.subContext(node.state);\n const getResult = (r: Resolvable) => r.get(subContext, trans)\n // Return a tuple that includes the Resolvable's token\n .then(value => ({ token: r.token, value: value }));\n nowait.forEach(getResult);\n return acc.concat(wait.map(getResult));\n }, []);\n\n // Wait for all the \"WAIT\" resolvables\n return services.$q.all(promises);\n }\n\n injector(): UIInjector {\n return this._injector || (this._injector = new UIInjectorImpl(this));\n }\n\n findNode(resolvable: Resolvable): PathNode {\n return find(this._path, (node: PathNode) => inArray(node.resolvables, resolvable));\n }\n\n /**\n * Gets the async dependencies of a Resolvable\n *\n * Given a Resolvable, returns its dependencies as a Resolvable[]\n */\n getDependencies(resolvable: Resolvable): Resolvable[] {\n const node = this.findNode(resolvable);\n // Find which other resolvables are \"visible\" to the `resolvable` argument\n // subpath stopping at resolvable's node, or the whole path (if the resolvable isn't in the path)\n const subPath: PathNode[] = PathUtils.subPath(this._path, x => x === node) || this._path;\n const availableResolvables: Resolvable[] = subPath\n .reduce((acc, _node) => acc.concat(_node.resolvables), []) // all of subpath's resolvables\n .filter(res => res !== resolvable); // filter out the `resolvable` argument\n\n const getDependency = (token: any) => {\n const matching = availableResolvables.filter(r => r.token === token);\n if (matching.length) return tail(matching);\n\n const fromInjector = this.injector().getNative(token);\n if (isUndefined(fromInjector)) {\n throw new Error('Could not find Dependency Injection token: ' + stringify(token));\n }\n\n return new Resolvable(token, () => fromInjector, [], fromInjector);\n };\n\n return resolvable.deps.map(getDependency);\n }\n}\n\nclass UIInjectorImpl implements UIInjector {\n native: $InjectorLike;\n\n constructor(public context: ResolveContext) {\n this.native = this.get(NATIVE_INJECTOR_TOKEN) || services.$injector;\n }\n\n get(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) {\n if (this.context.getPolicy(resolvable).async === 'NOWAIT') {\n return resolvable.get(this.context);\n }\n\n if (!resolvable.resolved) {\n throw new Error('Resolvable async .get() not complete:' + stringify(resolvable.token));\n }\n return resolvable.data;\n }\n\n return this.getNative(token);\n }\n\n getAsync(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) return resolvable.get(this.context);\n return services.$q.when(this.native.get(token));\n }\n\n getNative(token: any) {\n return this.native && this.native.get(token);\n }\n}\n", - "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { stringify } from '../common/strings';\nimport { map, find, extend, mergeR, tail, omit, arrayTuples, unnestR, identity, anyTrueR } from '../common/common';\nimport { isObject, isUndefined } from '../common/predicates';\nimport { prop, propEq, val, not, is } from '../common/hof';\nimport { StateDeclaration, StateOrName } from '../state/interface';\nimport {\n TransitionOptions, TreeChanges, IHookRegistry, TransitionHookPhase, RegisteredHooks, HookRegOptions,\n HookMatchCriteria, TransitionStateHookFn, TransitionHookFn,\n} from './interface'; // has or is using\nimport { TransitionHook } from './transitionHook';\nimport { matchState, makeEvent, RegisteredHook } from './hookRegistry';\nimport { HookBuilder } from './hookBuilder';\nimport { PathNode } from '../path/pathNode';\nimport { PathUtils } from '../path/pathUtils';\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { RawParams } from '../params/interface';\nimport { ResolvableLiteral } from '../resolve/interface';\n\n/** @hidden */\nconst stateSelf: (_state: StateObject) => StateDeclaration = prop('self');\n\n/**\n * Represents a transition between two states.\n *\n * When navigating to a state, we are transitioning **from** the current state **to** the new state.\n *\n * This object contains all contextual information about the to/from states, parameters, resolves.\n * It has information about all states being entered and exited as a result of the transition.\n */\nexport class Transition implements IHookRegistry {\n\n /** @hidden */\n static diToken = Transition;\n\n /**\n * A unique identifier for the transition.\n *\n * This is an auto incrementing integer, starting from `0`.\n */\n $id: number;\n\n /**\n * A reference to the [[UIRouter]] instance\n *\n * This reference can be used to access the router services, such as the [[StateService]]\n */\n router: UIRouter;\n\n /** @hidden */\n private _deferred = services.$q.defer();\n /**\n * This promise is resolved or rejected based on the outcome of the Transition.\n *\n * When the transition is successful, the promise is resolved\n * When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error\n */\n promise: Promise = this._deferred.promise;\n /**\n * A boolean which indicates if the transition was successful\n *\n * After a successful transition, this value is set to true.\n * After an unsuccessful transition, this value is set to false.\n *\n * The value will be undefined if the transition is not complete\n */\n success: boolean;\n /** @hidden */\n _aborted: boolean;\n /** @hidden */\n private _error: any;\n\n /** @hidden Holds the hook registration functions such as those passed to Transition.onStart() */\n _registeredHooks: RegisteredHooks = { };\n\n /** @hidden */\n private _options: TransitionOptions;\n /** @hidden */\n private _treeChanges: TreeChanges;\n /** @hidden */\n private _targetState: TargetState;\n /** @hidden */\n private _hookBuilder = new HookBuilder(this);\n\n\n /** @hidden */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n\n /** @hidden\n * Creates the transition-level hook registration functions\n * (which can then be used to register hooks)\n */\n private createTransitionHookRegFns() {\n this.router.transitionService._pluginapi._getEvents()\n .filter(type => type.hookPhase !== TransitionHookPhase.CREATE)\n .forEach(type => makeEvent(this, this.router.transitionService, type));\n }\n\n /** @internalapi */\n getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /**\n * Creates a new Transition object.\n *\n * If the target state is not valid, an error is thrown.\n *\n * @internalapi\n *\n * @param fromPath The path of [[PathNode]]s from which the transition is leaving. The last node in the `fromPath`\n * encapsulates the \"from state\".\n * @param targetState The target state and parameters being transitioned to (also, the transition options)\n * @param router The [[UIRouter]] instance\n */\n constructor(fromPath: PathNode[], targetState: TargetState, router: UIRouter) {\n this.router = router;\n this._targetState = targetState;\n\n if (!targetState.valid()) {\n throw new Error(targetState.error());\n }\n\n // current() is assumed to come from targetState.options, but provide a naive implementation otherwise.\n this._options = extend({ current: val(this) }, targetState.options());\n this.$id = router.transitionService._transitionCount++;\n const toPath = PathUtils.buildToPath(fromPath, targetState);\n this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState);\n this.createTransitionHookRegFns();\n\n const onCreateHooks = this._hookBuilder.buildHooksForPhase(TransitionHookPhase.CREATE);\n TransitionHook.invokeHooks(onCreateHooks, () => null);\n\n this.applyViewConfigs(router);\n }\n\n private applyViewConfigs(router: UIRouter) {\n const enteringStates = this._treeChanges.entering.map(node => node.state);\n PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates);\n }\n\n /**\n * @internalapi\n *\n * @returns the internal from [State] object\n */\n $from() {\n return tail(this._treeChanges.from).state;\n }\n\n /**\n * @internalapi\n *\n * @returns the internal to [State] object\n */\n $to() {\n return tail(this._treeChanges.to).state;\n }\n\n /**\n * Returns the \"from state\"\n *\n * Returns the state that the transition is coming *from*.\n *\n * @returns The state declaration object for the Transition's (\"from state\").\n */\n from(): StateDeclaration {\n return this.$from().self;\n }\n\n /**\n * Returns the \"to state\"\n *\n * Returns the state that the transition is going *to*.\n *\n * @returns The state declaration object for the Transition's target state (\"to state\").\n */\n to(): StateDeclaration {\n return this.$to().self;\n }\n\n /**\n * Gets the Target State\n *\n * A transition's [[TargetState]] encapsulates the [[to]] state, the [[params]], and the [[options]] as a single object.\n *\n * @returns the [[TargetState]] of this Transition\n */\n targetState() {\n return this._targetState;\n }\n\n /**\n * Determines whether two transitions are equivalent.\n * @deprecated\n */\n is(compare: (Transition|{to?: any, from?: any})): boolean {\n if (compare instanceof Transition) {\n // TODO: Also compare parameters\n return this.is({ to: compare.$to().name, from: compare.$from().name });\n }\n return !(\n (compare.to && !matchState(this.$to(), compare.to)) ||\n (compare.from && !matchState(this.$from(), compare.from))\n );\n }\n\n /**\n * Gets transition parameter values\n *\n * Returns the parameter values for a transition as key/value pairs.\n * This object is immutable.\n *\n * By default, returns the new parameter values (for the \"to state\").\n *\n * #### Example:\n * ```js\n * var toParams = transition.params();\n * ```\n *\n * To return the previous parameter values, supply `'from'` as the `pathname` argument.\n *\n * #### Example:\n * ```js\n * var fromParams = transition.params('from');\n * ```\n *\n * @param pathname the name of the treeChanges path to get parameter values for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n *\n * @returns transition parameter values for the desired path.\n */\n params(pathname?: string): any;\n params(pathname?: string): T;\n params(pathname = 'to') {\n return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {}));\n }\n\n\n /**\n * Creates a [[UIInjector]] Dependency Injector\n *\n * Returns a Dependency Injector for the Transition's target state (to state).\n * The injector provides resolve values which the target state has access to.\n *\n * The `UIInjector` can also provide values from the native root/global injector (ng1/ng2).\n *\n * #### Example:\n * ```js\n * .onEnter({ entering: 'myState' }, trans => {\n * var myResolveValue = trans.injector().get('myResolve');\n * // Inject a global service from the global/native injector (if it exists)\n * var MyService = trans.injector().get('MyService');\n * })\n * ```\n *\n * In some cases (such as `onBefore`), you may need access to some resolve data but it has not yet been fetched.\n * You can use [[UIInjector.getAsync]] to get a promise for the data.\n * #### Example:\n * ```js\n * .onBefore({}, trans => {\n * return trans.injector().getAsync('myResolve').then(myResolveValue =>\n * return myResolveValue !== 'ABORT';\n * });\n * });\n * ```\n *\n * If a `state` is provided, the injector that is returned will be limited to resolve values that the provided state has access to.\n * This can be useful if both a parent state `foo` and a child state `foo.bar` have both defined a resolve such as `data`.\n * #### Example:\n * ```js\n * .onEnter({ to: 'foo.bar' }, trans => {\n * // returns result of `foo` state's `myResolve` resolve\n * // even though `foo.bar` also has a `myResolve` resolve\n * var fooData = trans.injector('foo').get('myResolve');\n * });\n * ```\n *\n * If you need resolve data from the exiting states, pass `'from'` as `pathName`.\n * The resolve data from the `from` path will be returned.\n * #### Example:\n * ```js\n * .onExit({ exiting: 'foo.bar' }, trans => {\n * // Gets the resolve value of `myResolve` from the state being exited\n * var fooData = trans.injector(null, 'from').get('myResolve');\n * });\n * ```\n *\n *\n * @param state Limits the resolves provided to only the resolves the provided state has access to.\n * @param pathName Default: `'to'`: Chooses the path for which to create the injector. Use this to access resolves for `exiting` states.\n *\n * @returns a [[UIInjector]]\n */\n injector(state?: StateOrName, pathName = 'to'): UIInjector {\n let path: PathNode[] = this._treeChanges[pathName];\n if (state) path = PathUtils.subPath(path, node => node.state === state || node.state.name === state);\n return new ResolveContext(path).injector();\n }\n\n /**\n * Gets all available resolve tokens (keys)\n *\n * This method can be used in conjunction with [[injector]] to inspect the resolve values\n * available to the Transition.\n *\n * This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states\n * in the Transition's [[TreeChanges.to]] path.\n *\n * #### Example:\n * This example logs all resolve values\n * ```js\n * let tokens = trans.getResolveTokens();\n * tokens.forEach(token => console.log(token + \" = \" + trans.injector().get(token)));\n * ```\n *\n * #### Example:\n * This example creates promises for each resolve value.\n * This triggers fetches of resolves (if any have not yet been fetched).\n * When all promises have all settled, it logs the resolve values.\n * ```js\n * let tokens = trans.getResolveTokens();\n * let promise = tokens.map(token => trans.injector().getAsync(token));\n * Promise.all(promises).then(values => console.log(\"Resolved values: \" + values));\n * ```\n *\n * Note: Angular 1 users whould use `$q.all()`\n *\n * @param pathname resolve context's path name (e.g., `to` or `from`)\n *\n * @returns an array of resolve tokens (keys)\n */\n getResolveTokens(pathname = 'to'): any[] {\n return new ResolveContext(this._treeChanges[pathname]).getTokens();\n }\n\n /**\n * Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.\n *\n * Allows a transition hook to dynamically add a Resolvable to this Transition.\n *\n * Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).\n *\n * If a `state` argument is provided, the Resolvable is processed when that state is being entered.\n * If no `state` is provided then the root state is used.\n * If the given `state` has already been entered, the Resolvable is processed when any child state is entered.\n * If no child states will be entered, the Resolvable is processed during the `onFinish` phase of the Transition.\n *\n * The `state` argument also scopes the resolved data.\n * The resolved data is available from the injector for that `state` and any children states.\n *\n * #### Example:\n * ```js\n * transitionService.onBefore({}, transition => {\n * transition.addResolvable({\n * token: 'myResolve',\n * deps: ['MyService'],\n * resolveFn: myService => myService.getData()\n * });\n * });\n * ```\n *\n * @param resolvable a [[ResolvableLiteral]] object (or a [[Resolvable]])\n * @param state the state in the \"to path\" which should receive the new resolve (otherwise, the root state)\n */\n addResolvable(resolvable: Resolvable|ResolvableLiteral, state: StateOrName = ''): void {\n resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable);\n\n const stateName: string = (typeof state === 'string') ? state : state.name;\n const topath = this._treeChanges.to;\n const targetNode = find(topath, node => node.state.name === stateName);\n const resolveContext: ResolveContext = new ResolveContext(topath);\n resolveContext.addResolvables([resolvable as Resolvable], targetNode.state);\n }\n\n /**\n * Gets the transition from which this transition was redirected.\n *\n * If the current transition is a redirect, this method returns the transition that was redirected.\n *\n * #### Example:\n * ```js\n * let transitionA = $state.go('A').transition\n * transitionA.onStart({}, () => $state.target('B'));\n * $transitions.onSuccess({ to: 'B' }, (trans) => {\n * trans.to().name === 'B'; // true\n * trans.redirectedFrom() === transitionA; // true\n * });\n * ```\n *\n * @returns The previous Transition, or null if this Transition is not the result of a redirection\n */\n redirectedFrom(): Transition {\n return this._options.redirectedFrom || null;\n }\n\n /**\n * Gets the original transition in a redirect chain\n *\n * A transition might belong to a long chain of multiple redirects.\n * This method walks the [[redirectedFrom]] chain back to the original (first) transition in the chain.\n *\n * #### Example:\n * ```js\n * // states\n * registry.register({ name: 'A', redirectTo: 'B' });\n * registry.register({ name: 'B', redirectTo: 'C' });\n * registry.register({ name: 'C', redirectTo: 'D' });\n * registry.register({ name: 'D' });\n *\n * let transitionA = $state.go('A').transition\n *\n * $transitions.onSuccess({ to: 'D' }, (trans) => {\n * trans.to().name === 'D'; // true\n * trans.redirectedFrom().to().name === 'C'; // true\n * trans.originalTransition() === transitionA; // true\n * trans.originalTransition().to().name === 'A'; // true\n * });\n * ```\n *\n * @returns The original Transition that started a redirect chain\n */\n originalTransition(): Transition {\n const rf = this.redirectedFrom();\n return (rf && rf.originalTransition()) || this;\n }\n\n /**\n * Get the transition options\n *\n * @returns the options for this Transition.\n */\n options(): TransitionOptions {\n return this._options;\n }\n\n /**\n * Gets the states being entered.\n *\n * @returns an array of states that will be entered during this transition.\n */\n entering(): StateDeclaration[] {\n return map(this._treeChanges.entering, prop('state')).map(stateSelf);\n }\n\n /**\n * Gets the states being exited.\n *\n * @returns an array of states that will be exited during this transition.\n */\n exiting(): StateDeclaration[] {\n return map(this._treeChanges.exiting, prop('state')).map(stateSelf).reverse();\n }\n\n /**\n * Gets the states being retained.\n *\n * @returns an array of states that are already entered from a previous Transition, that will not be\n * exited during this Transition\n */\n retained(): StateDeclaration[] {\n return map(this._treeChanges.retained, prop('state')).map(stateSelf);\n }\n\n /**\n * Get the [[ViewConfig]]s associated with this Transition\n *\n * Each state can define one or more views (template/controller), which are encapsulated as `ViewConfig` objects.\n * This method fetches the `ViewConfigs` for a given path in the Transition (e.g., \"to\" or \"entering\").\n *\n * @param pathname the name of the path to fetch views for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n * @param state If provided, only returns the `ViewConfig`s for a single state in the path\n *\n * @returns a list of ViewConfig objects for the given path.\n */\n views(pathname = 'entering', state?: StateObject): ViewConfig[] {\n let path = this._treeChanges[pathname];\n path = !state ? path : path.filter(propEq('state', state));\n return path.map(prop('views')).filter(identity).reduce(unnestR, []);\n }\n\n /**\n * Return the transition's tree changes\n *\n * A transition goes from one state/parameters to another state/parameters.\n * During a transition, states are entered and/or exited.\n *\n * This function returns various branches (paths) which represent the changes to the\n * active state tree that are caused by the transition.\n *\n * @param pathname The name of the tree changes path to get:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n */\n treeChanges(pathname: string): PathNode[];\n treeChanges(): TreeChanges;\n treeChanges(pathname?: string) {\n return pathname ? this._treeChanges[pathname] : this._treeChanges;\n }\n\n /**\n * Creates a new transition that is a redirection of the current one.\n *\n * This transition can be returned from a [[TransitionService]] hook to\n * redirect a transition to a new state and/or set of parameters.\n *\n * @internalapi\n *\n * @returns Returns a new [[Transition]] instance.\n */\n redirect(targetState: TargetState): Transition {\n let redirects = 1, trans: Transition = this;\n // tslint:disable-next-line:no-conditional-assignment\n while ((trans = trans.redirectedFrom()) != null) {\n if (++redirects > 20) throw new Error(`Too many consecutive Transition redirects (20+)`);\n }\n\n const redirectOpts: TransitionOptions = { redirectedFrom: this, source: 'redirect' };\n // If the original transition was caused by URL sync, then use { location: 'replace' }\n // on the new transition (unless the target state explicitly specifies location: false).\n // This causes the original url to be replaced with the url for the redirect target\n // so the original url disappears from the browser history.\n if (this.options().source === 'url' && targetState.options().location !== false) {\n redirectOpts.location = 'replace';\n }\n\n const newOptions = extend({}, this.options(), targetState.options(), redirectOpts);\n targetState = targetState.withOptions(newOptions, true);\n\n const newTransition = this.router.transitionService.create(this._treeChanges.from, targetState);\n const originalEnteringNodes = this._treeChanges.entering;\n const redirectEnteringNodes = newTransition._treeChanges.entering;\n\n // --- Re-use resolve data from original transition ---\n // When redirecting from a parent state to a child state where the parent parameter values haven't changed\n // (because of the redirect), the resolves fetched by the original transition are still valid in the\n // redirected transition.\n //\n // This allows you to define a redirect on a parent state which depends on an async resolve value.\n // You can wait for the resolve, then redirect to a child state based on the result.\n // The redirected transition does not have to re-fetch the resolve.\n // ---------------------------------------------------------\n\n const nodeIsReloading = (reloadState: StateObject) => (node: PathNode) => {\n return reloadState && node.state.includes[reloadState.name];\n };\n\n // Find any \"entering\" nodes in the redirect path that match the original path and aren't being reloaded\n const matchingEnteringNodes: PathNode[] = PathUtils.matching(redirectEnteringNodes, originalEnteringNodes, PathUtils.nonDynamicParams)\n .filter(not(nodeIsReloading(targetState.options().reloadState)));\n\n // Use the existing (possibly pre-resolved) resolvables for the matching entering nodes.\n matchingEnteringNodes.forEach((node, idx) => {\n node.resolvables = originalEnteringNodes[idx].resolvables;\n });\n\n return newTransition;\n }\n\n /** @hidden If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */\n private _changedParams(): Param[] {\n const tc = this._treeChanges;\n\n /** Return undefined if it's not a \"dynamic\" transition, for the following reasons */\n // If user explicitly wants a reload\n if (this._options.reload) return undefined;\n // If any states are exiting or entering\n if (tc.exiting.length || tc.entering.length) return undefined;\n // If to/from path lengths differ\n if (tc.to.length !== tc.from.length) return undefined;\n // If the to/from paths are different\n const pathsDiffer: boolean = arrayTuples(tc.to, tc.from)\n .map(tuple => tuple[0].state !== tuple[1].state)\n .reduce(anyTrueR, false);\n if (pathsDiffer) return undefined;\n\n // Find any parameter values that differ\n const nodeSchemas: Param[][] = tc.to.map((node: PathNode) => node.paramSchema);\n const [toValues, fromValues] = [tc.to, tc.from].map(path => path.map(x => x.paramValues));\n const tuples = arrayTuples(nodeSchemas, toValues, fromValues);\n\n return tuples.map(([schema, toVals, fromVals]) => Param.changed(schema, toVals, fromVals)).reduce(unnestR, []);\n }\n\n /**\n * Returns true if the transition is dynamic.\n *\n * A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.\n *\n * @returns true if the Transition is dynamic\n */\n dynamic(): boolean {\n const changes = this._changedParams();\n return !changes ? false : changes.map(x => x.dynamic).reduce(anyTrueR, false);\n }\n\n /**\n * Returns true if the transition is ignored.\n *\n * A transition is ignored if no states are entered nor exited, and no parameter values have changed.\n *\n * @returns true if the Transition is ignored.\n */\n ignored(): boolean {\n return !!this._ignoredReason();\n }\n\n /** @hidden */\n _ignoredReason(): 'SameAsCurrent'|'SameAsPending'|undefined {\n const pending = this.router.globals.transition;\n const reloadState = this._options.reloadState;\n\n const same = (pathA, pathB) => {\n if (pathA.length !== pathB.length) return false;\n const matching = PathUtils.matching(pathA, pathB);\n return pathA.length === matching.filter(node => !reloadState || !node.state.includes[reloadState.name]).length;\n };\n\n const newTC = this.treeChanges();\n const pendTC = pending && pending.treeChanges();\n\n if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) return 'SameAsPending';\n if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) return 'SameAsCurrent';\n }\n\n /**\n * Runs the transition\n *\n * This method is generally called from the [[StateService.transitionTo]]\n *\n * @internalapi\n *\n * @returns a promise for a successful transition.\n */\n run(): Promise {\n const runAllHooks = TransitionHook.runAllHooks;\n\n // Gets transition hooks array for the given phase\n const getHooksFor = (phase: TransitionHookPhase) =>\n this._hookBuilder.buildHooksForPhase(phase);\n\n // When the chain is complete, then resolve or reject the deferred\n const transitionSuccess = () => {\n trace.traceSuccess(this.$to(), this);\n this.success = true;\n this._deferred.resolve(this.to());\n runAllHooks(getHooksFor(TransitionHookPhase.SUCCESS));\n };\n\n const transitionError = (reason: any) => {\n trace.traceError(reason, this);\n this.success = false;\n this._deferred.reject(reason);\n this._error = reason;\n runAllHooks(getHooksFor(TransitionHookPhase.ERROR));\n };\n\n const runTransition = () => {\n // Wait to build the RUN hook chain until the BEFORE hooks are done\n // This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object.\n const allRunHooks = getHooksFor(TransitionHookPhase.RUN);\n const done = () => services.$q.when(undefined);\n return TransitionHook.invokeHooks(allRunHooks, done);\n };\n\n const startTransition = () => {\n const globals = this.router.globals;\n\n globals.lastStartedTransitionId = this.$id;\n globals.transition = this;\n globals.transitionHistory.enqueue(this);\n\n trace.traceTransitionStart(this);\n\n return services.$q.when(undefined);\n };\n\n const allBeforeHooks = getHooksFor(TransitionHookPhase.BEFORE);\n TransitionHook.invokeHooks(allBeforeHooks, startTransition)\n .then(runTransition)\n .then(transitionSuccess, transitionError);\n\n return this.promise;\n }\n\n /** Checks if this transition is currently active/running. */\n isActive = () =>\n this.router.globals.transition === this;\n\n /**\n * Checks if the Transition is valid\n *\n * @returns true if the Transition is valid\n */\n valid() {\n return !this.error() || this.success !== undefined;\n }\n\n /**\n * Aborts this transition\n *\n * Imperative API to abort a Transition.\n * This only applies to Transitions that are not yet complete.\n */\n abort() {\n // Do not set flag if the transition is already complete\n if (isUndefined(this.success)) {\n this._aborted = true;\n }\n }\n\n /**\n * The Transition error reason.\n *\n * If the transition is invalid (and could not be run), returns the reason the transition is invalid.\n * If the transition was valid and ran, but was not successful, returns the reason the transition failed.\n *\n * @returns an error message explaining why the transition is invalid, or the reason the transition failed.\n */\n error() {\n const state: StateObject = this.$to();\n\n if (state.self.abstract)\n return `Cannot transition to abstract state '${state.name}'`;\n\n const paramDefs = state.parameters(), values = this.params();\n const invalidParams = paramDefs.filter(param => !param.validates(values[param.id]));\n if (invalidParams.length) {\n return `Param values not valid for state '${state.name}'. Invalid params: [ ${invalidParams.map(param => param.id).join(', ')} ]`;\n }\n\n if (this.success === false)\n return this._error;\n }\n\n /**\n * A string representation of the Transition\n *\n * @returns A string representation of the Transition\n */\n toString () {\n const fromStateOrName = this.from();\n const toStateOrName = this.to();\n\n const avoidEmptyHash = (params: RawParams) =>\n (params['#'] !== null && params['#'] !== undefined) ? params : omit(params, ['#']);\n\n // (X) means the to state is invalid.\n const id = this.$id,\n from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName,\n fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))),\n toValid = this.valid() ? '' : '(X) ',\n to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName,\n toParams = stringify(avoidEmptyHash(this.params()));\n\n return `Transition#${id}( '${from}'${fromParams} -> ${toValid}'${to}'${toParams} )`;\n }\n}\n", - "/**\n * Functions that manipulate strings\n *\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_strings\n */ /** */\n\nimport { isString, isArray, isDefined, isNull, isPromise, isInjectable, isObject } from './predicates';\nimport { Rejection } from '../transition/rejectFactory';\nimport { IInjectable, identity, Obj, tail, pushR } from './common';\nimport { pattern, is, not, val, invoke } from './hof';\nimport { Transition } from '../transition/transition';\nimport { Resolvable } from '../resolve/resolvable';\n\n/**\n * Returns a string shortened to a maximum length\n *\n * If the string is already less than the `max` length, return the string.\n * Else return the string, shortened to `max - 3` and append three dots (\"...\").\n *\n * @param max the maximum length of the string to return\n * @param str the input string\n */\nexport function maxLength(max: number, str: string) {\n if (str.length <= max) return str;\n return str.substr(0, max - 3) + '...';\n}\n\n/**\n * Returns a string, with spaces added to the end, up to a desired str length\n *\n * If the string is already longer than the desired length, return the string.\n * Else returns the string, with extra spaces on the end, such that it reaches `length` characters.\n *\n * @param length the desired length of the string to return\n * @param str the input string\n */\nexport function padString(length: number, str: string) {\n while (str.length < length) str += ' ';\n return str;\n}\n\nexport function kebobString(camelCase: string) {\n return camelCase\n .replace(/^([A-Z])/, $1 => $1.toLowerCase()) // replace first char\n .replace(/([A-Z])/g, $1 => '-' + $1.toLowerCase()); // replace rest\n}\n\nfunction _toJson(obj: Obj) {\n return JSON.stringify(obj);\n}\n\nfunction _fromJson(json: string) {\n return isString(json) ? JSON.parse(json) : json;\n}\n\n\nfunction promiseToString(p: Promise) {\n return `Promise(${JSON.stringify(p)})`;\n}\n\nexport function functionToString(fn: Function) {\n const fnStr = fnToString(fn);\n const namedFunctionMatch = fnStr.match(/^(function [^ ]+\\([^)]*\\))/);\n const toStr = namedFunctionMatch ? namedFunctionMatch[1] : fnStr;\n\n const fnName = fn['name'] || '';\n if (fnName && toStr.match(/function \\(/)) {\n return 'function ' + fnName + toStr.substr(9);\n }\n return toStr;\n}\n\nexport function fnToString(fn: IInjectable) {\n const _fn = isArray(fn) ? fn.slice(-1)[0] : fn;\n return _fn && _fn.toString() || 'undefined';\n}\n\nlet stringifyPatternFn: (val: any) => string = null;\nconst stringifyPattern = function(value: any) {\n const isRejection = Rejection.isRejectionPromise;\n\n stringifyPatternFn = stringifyPatternFn || pattern([\n [not(isDefined), val('undefined')],\n [isNull, val('null')],\n [isPromise, val('[Promise]')],\n [isRejection, (x: any) => x._transitionRejection.toString()],\n [is(Rejection), invoke('toString')],\n [is(Transition), invoke('toString')],\n [is(Resolvable), invoke('toString')],\n [isInjectable, functionToString],\n [val(true), identity],\n ]);\n\n return stringifyPatternFn(value);\n};\n\nexport function stringify(o: any) {\n const seen: any[] = [];\n\n function format(value: any) {\n if (isObject(value)) {\n if (seen.indexOf(value) !== -1) return '[circular ref]';\n seen.push(value);\n }\n return stringifyPattern(value);\n }\n\n return JSON.stringify(o, (key, value) => format(value)).replace(/\\\\\"/g, '\"');\n}\n\n/** Returns a function that splits a string on a character or substring */\nexport const beforeAfterSubstr = (char: string) => (str: string): string[] => {\n if (!str) return ['', ''];\n const idx = str.indexOf(char);\n if (idx === -1) return [str, ''];\n return [str.substr(0, idx), str.substr(idx + 1)];\n};\n\nexport const hostRegex = new RegExp('^(?:[a-z]+:)?//[^/]+/');\nexport const stripLastPathElement = (str: string) => str.replace(/\\/[^/]*$/, '');\nexport const splitHash = beforeAfterSubstr('#');\nexport const splitQuery = beforeAfterSubstr('?');\nexport const splitEqual = beforeAfterSubstr('=');\nexport const trimHashVal = (str: string) => str ? str.replace(/^#/, '') : '';\n\n/**\n * Splits on a delimiter, but returns the delimiters in the array\n *\n * #### Example:\n * ```js\n * var splitOnSlashes = splitOnDelim('/');\n * splitOnSlashes(\"/foo\"); // [\"/\", \"foo\"]\n * splitOnSlashes(\"/foo/\"); // [\"/\", \"foo\", \"/\"]\n * ```\n */\nexport function splitOnDelim(delim: string) {\n const re = new RegExp('(' + delim + ')', 'g');\n return (str: string) =>\n str.split(re).filter(identity);\n}\n\n\n/**\n * Reduce fn that joins neighboring strings\n *\n * Given an array of strings, returns a new array\n * where all neighboring strings have been joined.\n *\n * #### Example:\n * ```js\n * let arr = [\"foo\", \"bar\", 1, \"baz\", \"\", \"qux\" ];\n * arr.reduce(joinNeighborsR, []) // [\"foobar\", 1, \"bazqux\" ]\n * ```\n */\nexport function joinNeighborsR(acc: any[], x: any) {\n if (isString(tail(acc)) && isString(x))\n return acc.slice(0, -1).concat(tail(acc) + x);\n return pushR(acc, x);\n}\n\n", - "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { fromJson, toJson, identity, equals, inherit, map, extend, pick } from '../common/common';\nimport { isDefined, isNullOrUndefined } from '../common/predicates';\nimport { is } from '../common/hof';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * A registry for parameter types.\n *\n * This registry manages the built-in (and custom) parameter types.\n *\n * The built-in parameter types are:\n *\n * - [[string]]\n * - [[path]]\n * - [[query]]\n * - [[hash]]\n * - [[int]]\n * - [[bool]]\n * - [[date]]\n * - [[json]]\n * - [[any]]\n */\nexport class ParamTypes {\n /**\n * Built-in parameter type: `string`\n *\n * This parameter type coerces values to strings.\n * It matches anything (`new RegExp(\".*\")`) in the URL\n */\n static string: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `path`\n *\n * This parameter type is the default type for path parameters.\n * A path parameter is any parameter declared in the path portion of a url\n *\n * - `/foo/:param1/:param2`: two path parameters\n *\n * This parameter type behaves exactly like the [[string]] type with one exception.\n * When matching parameter values in the URL, the `path` type does not match forward slashes `/`.\n *\n * #### Angular 1 note:\n * In ng1, this type is overridden with one that pre-encodes slashes as `~2F` instead of `%2F`.\n * For more details about this angular 1 behavior, see: https://github.com/angular-ui/ui-router/issues/2598\n */\n static path: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `query`\n *\n * This parameter type is the default type for query/search parameters.\n * It behaves the same as the [[string]] parameter type.\n *\n * A query parameter is any parameter declared in the query/search portion of a url\n *\n * - `/bar?param2`: a query parameter\n */\n static query: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `hash`\n *\n * This parameter type is used for the `#` parameter (the hash)\n * It behaves the same as the [[string]] parameter type.\n * @coreapi\n */\n static hash: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `int`\n *\n * This parameter type serializes javascript integers (`number`s which represent an integer) to the URL.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'user',\n * url: '/user/{id:int}'\n * });\n * ```\n * ```js\n * $state.go('user', { id: 1298547 });\n * ```\n *\n * The URL will serialize to: `/user/1298547`.\n *\n * When the parameter value is read, it will be the `number` `1298547`, not the string `\"1298547\"`.\n */\n static int: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `bool`\n *\n * This parameter type serializes `true`/`false` as `1`/`0`\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'inbox',\n * url: '/inbox?{unread:bool}'\n * });\n * ```\n * ```js\n * $state.go('inbox', { unread: true });\n * ```\n *\n * The URL will serialize to: `/inbox?unread=1`.\n *\n * Conversely, if the url is `/inbox?unread=0`, the value of the `unread` parameter will be a `false`.\n */\n static bool: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `date`\n *\n * This parameter type can be used to serialize Javascript dates as parameter values.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'search',\n * url: '/search?{start:date}'\n * });\n * ```\n * ```js\n * $state.go('search', { start: new Date(2000, 0, 1) });\n * ```\n *\n * The URL will serialize to: `/search?start=2000-01-01`.\n *\n * Conversely, if the url is `/search?start=2016-12-25`, the value of the `start` parameter will be a `Date` object where:\n *\n * - `date.getFullYear() === 2016`\n * - `date.getMonth() === 11` (month is 0-based)\n * - `date.getDate() === 25`\n */\n static date: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `json`\n *\n * This parameter type can be used to serialize javascript objects into the URL using JSON serialization.\n *\n * #### Example:\n * This example serializes an plain javascript object to the URL\n * ```js\n * .state({\n * name: 'map',\n * url: '/map/{coords:json}'\n * });\n * ```\n * ```js\n * $state.go('map', { coords: { x: 10399.2, y: 49071 });\n * ```\n *\n * The URL will serialize to: `/map/%7B%22x%22%3A10399.2%2C%22y%22%3A49071%7D`\n */\n static json: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `any`\n *\n * This parameter type is used by default for url-less parameters (parameters that do not appear in the URL).\n * This type does not encode or decode.\n * It is compared using a deep `equals` comparison.\n *\n * #### Example:\n * This example defines a non-url parameter on a [[StateDeclaration]].\n * ```js\n * .state({\n * name: 'new',\n * url: '/new',\n * params: {\n * inrepyto: null\n * }\n * });\n * ```\n * ```js\n * $state.go('new', { inreplyto: currentMessage });\n * ```\n */\n static any: ParamTypeDefinition;\n\n\n /** @hidden */\n types: any;\n /** @hidden */\n enqueue = true;\n /** @hidden */\n typeQueue: any[] = [];\n\n /** @internalapi */\n private defaultTypes: any = pick(ParamTypes.prototype, ['hash', 'string', 'query', 'path', 'int', 'bool', 'date', 'json', 'any']);\n\n /** @internalapi */\n constructor() {\n // Register default types. Store them in the prototype of this.types.\n const makeType = (definition: ParamTypeDefinition, name: string) =>\n new ParamType(extend({ name }, definition));\n this.types = inherit(map(this.defaultTypes, makeType), {});\n }\n\n /** @internalapi */\n dispose() {\n this.types = {};\n }\n\n /**\n * Registers a parameter type\n *\n * End users should call [[UrlMatcherFactory.type]], which delegates to this method.\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n if (!isDefined(definition)) return this.types[name];\n if (this.types.hasOwnProperty(name)) throw new Error(`A type named '${name}' has already been defined.`);\n\n this.types[name] = new ParamType(extend({ name }, definition));\n\n if (definitionFn) {\n this.typeQueue.push({ name, def: definitionFn });\n if (!this.enqueue) this._flushTypeQueue();\n }\n\n return this;\n }\n\n /** @internalapi */\n _flushTypeQueue() {\n while (this.typeQueue.length) {\n const type = this.typeQueue.shift();\n if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n extend(this.types[type.name], services.$injector.invoke(type.def));\n }\n }\n}\n\n/** @hidden */\nfunction initDefaultTypes() {\n\n const makeDefaultType = (def) => {\n const valToString = (val: any) =>\n val != null ? val.toString() : val;\n\n const defaultTypeBase = {\n encode: valToString,\n decode: valToString,\n is: is(String),\n pattern: /.*/,\n // tslint:disable-next-line:triple-equals\n equals: (a: any, b: any) => a == b, // allow coersion for null/undefined/\"\"\n };\n\n return extend({}, defaultTypeBase, def) as ParamTypeDefinition;\n };\n\n // Default Parameter Type Definitions\n extend(ParamTypes.prototype, {\n string: makeDefaultType({}),\n\n path: makeDefaultType({\n pattern: /[^/]*/,\n }),\n\n query: makeDefaultType({}),\n\n hash: makeDefaultType({\n inherit: false,\n }),\n\n int: makeDefaultType({\n decode: (val: string) => parseInt(val, 10),\n is: function(val: any) {\n return !isNullOrUndefined(val) && this.decode(val.toString()) === val;\n },\n pattern: /-?\\d+/,\n }),\n\n bool: makeDefaultType({\n encode: (val: any) => val && 1 || 0,\n decode: (val: string) => parseInt(val, 10) !== 0,\n is: is(Boolean),\n pattern: /0|1/,\n }),\n\n date: makeDefaultType({\n encode: function(val: any) {\n return !this.is(val) ? undefined : [\n val.getFullYear(),\n ('0' + (val.getMonth() + 1)).slice(-2),\n ('0' + val.getDate()).slice(-2),\n ].join('-');\n },\n decode: function(val: string) {\n if (this.is(val)) return val as Date;\n const match = this.capture.exec(val);\n return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n },\n is: (val: any) => val instanceof Date && !isNaN(val.valueOf()),\n equals(l: any, r: any) {\n return ['getFullYear', 'getMonth', 'getDate']\n .reduce((acc, fn) => acc && l[fn]() === r[fn](), true);\n },\n pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/,\n }),\n\n json: makeDefaultType({\n encode: toJson,\n decode: fromJson,\n is: is(Object),\n equals: equals,\n pattern: /[^/]*/,\n }),\n\n // does not encode/decode\n any: makeDefaultType({\n encode: identity,\n decode: identity,\n is: () => true,\n equals: equals,\n }),\n });\n}\n\ninitDefaultTypes();\n\n", - "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, ancestors, Obj } from '../common/common';\nimport { StateObject } from '../state/stateObject';\n\n/** @internalapi */\nexport class StateParams {\n [key: string]: any;\n\n constructor(params: Obj = {}) {\n extend(this, params);\n }\n\n /**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\n $inherit(newParams: Obj, $current: StateObject, $to: StateObject) {\n let parentParams: string[];\n const parents = ancestors($current, $to),\n inherited: Obj = {},\n inheritList: string[] = [];\n\n for (const i in parents) {\n if (!parents[i] || !parents[i].params) continue;\n parentParams = Object.keys(parents[i].params);\n if (!parentParams.length) continue;\n\n for (const j in parentParams) {\n if (inheritList.indexOf(parentParams[j]) >= 0) continue;\n inheritList.push(parentParams[j]);\n inherited[parentParams[j]] = this[parentParams[j]];\n }\n }\n return extend({}, inherited, newParams);\n }\n}\n\n", - "/** @module state */ /** for typedoc */\nimport { Obj, omit, noop, extend, inherit, values, applyPairs, tail, mapObj, identity } from '../common/common';\nimport { isDefined, isFunction, isString, isArray } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { prop, pattern, is, pipe, val } from '../common/hof';\nimport { StateDeclaration } from './interface';\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { Param } from '../params/param';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { services } from '../common/coreservices';\nimport { ResolvePolicy } from '../resolve/interface';\nimport { ParamFactory } from '../url/interface';\n\nconst parseUrl = (url: string): any => {\n if (!isString(url)) return false;\n const root = url.charAt(0) === '^';\n return { val: root ? url.substring(1) : url, root };\n};\n\nexport type BuilderFunction = (state: StateObject, parent?: BuilderFunction) => any;\n\ninterface Builders {\n [key: string]: BuilderFunction[];\n\n name: BuilderFunction[];\n parent: BuilderFunction[];\n data: BuilderFunction[];\n url: BuilderFunction[];\n navigable: BuilderFunction[];\n params: BuilderFunction[];\n views: BuilderFunction[];\n path: BuilderFunction[];\n includes: BuilderFunction[];\n resolvables: BuilderFunction[];\n}\n\n\nfunction nameBuilder(state: StateObject) {\n return state.name;\n}\n\nfunction selfBuilder(state: StateObject) {\n state.self.$$state = () => state;\n return state.self;\n}\n\nfunction dataBuilder(state: StateObject) {\n if (state.parent && state.parent.data) {\n state.data = state.self.data = inherit(state.parent.data, state.data);\n }\n return state.data;\n}\n\nconst getUrlBuilder = ($urlMatcherFactoryProvider: UrlMatcherFactory, root: () => StateObject) =>\nfunction urlBuilder(state: StateObject) {\n const stateDec: StateDeclaration = state;\n\n // For future states, i.e., states whose name ends with `.**`,\n // match anything that starts with the url prefix\n if (stateDec && stateDec.url && stateDec.name && stateDec.name.match(/\\.\\*\\*$/)) {\n stateDec.url += '{remainder:any}'; // match any path (.*)\n }\n\n const parsed = parseUrl(stateDec.url), parent = state.parent;\n const url = !parsed ? stateDec.url : $urlMatcherFactoryProvider.compile(parsed.val, {\n params: state.params || {},\n paramMap: function (paramConfig: any, isSearch: boolean) {\n if (stateDec.reloadOnSearch === false && isSearch) paramConfig = extend(paramConfig || {}, { dynamic: true });\n return paramConfig;\n },\n });\n\n if (!url) return null;\n if (!$urlMatcherFactoryProvider.isMatcher(url)) throw new Error(`Invalid url '${url}' in state '${state}'`);\n return (parsed && parsed.root) ? url : ((parent && parent.navigable) || root()).url.append( url);\n};\n\nconst getNavigableBuilder = (isRoot: (state: StateObject) => boolean) =>\nfunction navigableBuilder(state: StateObject) {\n return !isRoot(state) && state.url ? state : (state.parent ? state.parent.navigable : null);\n};\n\nconst getParamsBuilder = (paramFactory: ParamFactory) =>\nfunction paramsBuilder(state: StateObject): { [key: string]: Param } {\n const makeConfigParam = (config: any, id: string) => paramFactory.fromConfig(id, null, config);\n const urlParams: Param[] = (state.url && state.url.parameters({ inherit: false })) || [];\n const nonUrlParams: Param[] = values(mapObj(omit(state.params || {}, urlParams.map(prop('id'))), makeConfigParam));\n return urlParams.concat(nonUrlParams).map(p => [p.id, p]).reduce(applyPairs, {});\n};\n\nfunction pathBuilder(state: StateObject) {\n return state.parent ? state.parent.path.concat(state) : /*root*/ [state];\n}\n\nfunction includesBuilder(state: StateObject) {\n const includes = state.parent ? extend({}, state.parent.includes) : {};\n includes[state.name] = true;\n return includes;\n}\n\n/**\n * This is a [[StateBuilder.builder]] function for the `resolve:` block on a [[StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * validates the `resolve` property and converts it to a [[Resolvable]] array.\n *\n * resolve: input value can be:\n *\n * {\n * // analyzed but not injected\n * myFooResolve: function() { return \"myFooData\"; },\n *\n * // function.toString() parsed, \"DependencyName\" dep as string (not min-safe)\n * myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },\n *\n * // Array split; \"DependencyName\" dep as string\n * myBazResolve: [ \"DependencyName\", function(dep) { return dep.fetchSomethingAsPromise() },\n *\n * // Array split; DependencyType dep as token (compared using ===)\n * myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },\n *\n * // val.$inject used as deps\n * // where:\n * // corgeResolve.$inject = [\"DependencyName\"];\n * // function corgeResolve(dep) { dep.fetchSometingAsPromise() }\n * // then \"DependencyName\" dep as string\n * myCorgeResolve: corgeResolve,\n *\n * // inject service by name\n * // When a string is found, desugar creating a resolve that injects the named service\n * myGraultResolve: \"SomeService\"\n * }\n *\n * or:\n *\n * [\n * new Resolvable(\"myFooResolve\", function() { return \"myFooData\" }),\n * new Resolvable(\"myBarResolve\", function(dep) { return dep.fetchSomethingAsPromise() }, [ \"DependencyName\" ]),\n * { provide: \"myBazResolve\", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ \"DependencyName\" ] }\n * ]\n */\nexport function resolvablesBuilder(state: StateObject): Resolvable[] {\n interface Tuple { token: any, val: any, deps: any[], policy: ResolvePolicy }\n\n /** convert resolve: {} and resolvePolicy: {} objects to an array of tuples */\n const objects2Tuples = (resolveObj: Obj, resolvePolicies: { [key: string]: ResolvePolicy }) =>\n Object.keys(resolveObj || {}).map(token => ({ token, val: resolveObj[token], deps: undefined, policy: resolvePolicies[token] }));\n\n /** fetch DI annotations from a function or ng1-style array */\n const annotate = (fn: Function) => {\n const $injector = services.$injector;\n // ng1 doesn't have an $injector until runtime.\n // If the $injector doesn't exist, use \"deferred\" literal as a\n // marker indicating they should be annotated when runtime starts\n return fn['$inject'] || ($injector && $injector.annotate(fn, $injector.strictDi)) || 'deferred';\n };\n\n /** true if the object has both `token` and `resolveFn`, and is probably a [[ResolveLiteral]] */\n const isResolveLiteral = (obj: any) => !!(obj.token && obj.resolveFn);\n\n /** true if the object looks like a provide literal, or a ng2 Provider */\n const isLikeNg2Provider = (obj: any) => !!((obj.provide || obj.token) && (obj.useValue || obj.useFactory || obj.useExisting || obj.useClass));\n\n /** true if the object looks like a tuple from obj2Tuples */\n const isTupleFromObj = (obj: any) => !!(obj && obj.val && (isString(obj.val) || isArray(obj.val) || isFunction(obj.val)));\n\n /** extracts the token from a Provider or provide literal */\n const getToken = (p: any) => p.provide || p.token;\n\n /** Given a literal resolve or provider object, returns a Resolvable */\n const literal2Resolvable = pattern([\n [prop('resolveFn'), p => new Resolvable(getToken(p), p.resolveFn, p.deps, p.policy)],\n [prop('useFactory'), p => new Resolvable(getToken(p), p.useFactory, (p.deps || p.dependencies), p.policy)],\n [prop('useClass'), p => new Resolvable(getToken(p), () => new (p.useClass)(), [], p.policy)],\n [prop('useValue'), p => new Resolvable(getToken(p), () => p.useValue, [], p.policy, p.useValue)],\n [prop('useExisting'), p => new Resolvable(getToken(p), identity, [p.useExisting], p.policy)],\n ]);\n\n const tuple2Resolvable = pattern([\n [pipe(prop('val'), isString), (tuple: Tuple) => new Resolvable(tuple.token, identity, [ tuple.val ], tuple.policy)],\n [pipe(prop('val'), isArray), (tuple: Tuple) => new Resolvable(tuple.token, tail( tuple.val), tuple.val.slice(0, -1), tuple.policy)],\n [pipe(prop('val'), isFunction), (tuple: Tuple) => new Resolvable(tuple.token, tuple.val, annotate(tuple.val), tuple.policy)],\n ]);\n\n const item2Resolvable = <(obj: any) => Resolvable> pattern([\n [is(Resolvable), (r: Resolvable) => r],\n [isResolveLiteral, literal2Resolvable],\n [isLikeNg2Provider, literal2Resolvable],\n [isTupleFromObj, tuple2Resolvable],\n [val(true), (obj: any) => { throw new Error('Invalid resolve value: ' + stringify(obj)); }],\n ]);\n\n // If resolveBlock is already an array, use it as-is.\n // Otherwise, assume it's an object and convert to an Array of tuples\n const decl = state.resolve;\n const items: any[] = isArray(decl) ? decl : objects2Tuples(decl, state.resolvePolicy || {});\n return items.map(item2Resolvable);\n}\n\n/**\n * @internalapi A internal global service\n *\n * StateBuilder is a factory for the internal [[StateObject]] objects.\n *\n * When you register a state with the [[StateRegistry]], you register a plain old javascript object which\n * conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding\n * [[StateObject]] object, which has an API and is used internally.\n *\n * Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function\n * using the [[builder]] method.\n */\nexport class StateBuilder {\n /** An object that contains all the BuilderFunctions registered, key'd by the name of the State property they build */\n private builders: Builders;\n\n constructor(private matcher: StateMatcher, urlMatcherFactory: UrlMatcherFactory) {\n const self = this;\n\n const root = () => matcher.find('');\n const isRoot = (state: StateObject) => state.name === '';\n\n function parentBuilder(state: StateObject) {\n if (isRoot(state)) return null;\n return matcher.find(self.parentName(state)) || root();\n }\n\n this.builders = {\n name: [ nameBuilder ],\n self: [ selfBuilder ],\n parent: [ parentBuilder ],\n data: [ dataBuilder ],\n // Build a URLMatcher if necessary, either via a relative or absolute URL\n url: [ getUrlBuilder(urlMatcherFactory, root) ],\n // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n navigable: [ getNavigableBuilder(isRoot) ],\n params: [ getParamsBuilder(urlMatcherFactory.paramFactory) ],\n // Each framework-specific ui-router implementation should define its own `views` builder\n // e.g., src/ng1/statebuilders/views.ts\n views: [],\n // Keep a full path from the root down to this state as this is needed for state activation.\n path: [ pathBuilder ],\n // Speed up $state.includes() as it's used a lot\n includes: [ includesBuilder ],\n resolvables: [ resolvablesBuilder ],\n };\n }\n\n /**\n * Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g., `parent`, `url`, or `path`).\n * More than one BuilderFunction can be registered for a given property.\n *\n * The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.\n *\n * @param name The name of the State property being registered for.\n * @param fn The BuilderFunction which will be used to build the State property\n * @returns a function which deregisters the BuilderFunction\n */\n builder(name: string, fn: BuilderFunction): (BuilderFunction|BuilderFunction[]|Function) {\n const builders = this.builders;\n const array = builders[name] || [];\n // Backwards compat: if only one builder exists, return it, else return whole arary.\n if (isString(name) && !isDefined(fn)) return array.length > 1 ? array : array[0];\n if (!isString(name) || !isFunction(fn)) return;\n\n builders[name] = array;\n builders[name].push(fn);\n return () => builders[name].splice(builders[name].indexOf(fn, 1)) && null;\n }\n\n /**\n * Builds all of the properties on an essentially blank State object, returning a State object which has all its\n * properties and API built.\n *\n * @param state an uninitialized State object\n * @returns the built State object\n */\n build(state: StateObject): StateObject {\n const { matcher, builders } = this;\n const parent = this.parentName(state);\n\n if (parent && !matcher.find(parent, undefined, false)) {\n return null;\n }\n\n for (const key in builders) {\n if (!builders.hasOwnProperty(key)) continue;\n const chain = builders[key].reduce((parentFn: BuilderFunction, step: BuilderFunction) => (_state) => step(_state, parentFn), noop);\n state[key] = chain(state);\n }\n return state;\n }\n\n parentName(state: StateObject) {\n // name = 'foo.bar.baz.**'\n const name = state.name || '';\n // segments = ['foo', 'bar', 'baz', '.**']\n const segments = name.split('.');\n // segments = ['foo', 'bar', 'baz']\n const lastSegment = segments.pop();\n // segments = ['foo', 'bar'] (ignore .** segment for future states)\n if (lastSegment === '**') segments.pop();\n\n if (segments.length) {\n if (state.parent) {\n throw new Error(`States that specify the 'parent:' property should not have a '.' in their name (${name})`);\n }\n\n // 'foo.bar'\n return segments.join('.');\n }\n\n if (!state.parent) return '';\n return isString(state.parent) ? state.parent : state.parent.name;\n }\n\n name(state: StateObject) {\n const name = state.name;\n if (name.indexOf('.') !== -1 || !state.parent) return name;\n\n const parentName = isString(state.parent) ? state.parent : state.parent.name;\n return parentName ? parentName + '.' + name : name;\n }\n}\n", - "/** @module state */ /** for typedoc */\nimport { isString } from '../common/predicates';\nimport { StateOrName } from './interface';\nimport { StateObject } from './stateObject';\nimport { values } from '../common/common';\n\nexport class StateMatcher {\n constructor (private _states: { [key: string]: StateObject }) { }\n\n isRelative(stateName: string) {\n stateName = stateName || '';\n return stateName.indexOf('.') === 0 || stateName.indexOf('^') === 0;\n }\n\n\n find(stateOrName: StateOrName, base?: StateOrName, matchGlob = true): StateObject {\n if (!stateOrName && stateOrName !== '') return undefined;\n const isStr = isString(stateOrName);\n let name: string = isStr ? stateOrName : (stateOrName).name;\n\n if (this.isRelative(name)) name = this.resolvePath(name, base);\n const state = this._states[name];\n\n if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n return state;\n } else if (isStr && matchGlob) {\n const _states = values(this._states);\n const matches = _states.filter(_state =>\n _state.__stateObjectCache.nameGlob &&\n _state.__stateObjectCache.nameGlob.matches(name),\n );\n\n if (matches.length > 1) {\n // tslint:disable-next-line:no-console\n console.log(`stateMatcher.find: Found multiple matches for ${name} using glob: `, matches.map(match => match.name));\n }\n return matches[0];\n }\n return undefined;\n }\n\n resolvePath(name: string, base: StateOrName) {\n if (!base) throw new Error(`No reference point given for path '${name}'`);\n\n const baseState: StateObject = this.find(base);\n\n const splitName = name.split('.');\n const pathLength = splitName.length;\n let i = 0, current = baseState;\n\n for (; i < pathLength; i++) {\n if (splitName[i] === '' && i === 0) {\n current = baseState;\n continue;\n }\n if (splitName[i] === '^') {\n if (!current.parent) throw new Error(`Path '${name}' not valid for state '${baseState.name}'`);\n current = current.parent;\n continue;\n }\n break;\n }\n const relName = splitName.slice(i).join('.');\n return current.name + (current.name && relName ? '.' : '') + relName;\n }\n}\n", - "/** @module state */ /** for typedoc */\nimport { inArray } from '../common/common';\nimport { isString } from '../common/predicates';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { StateObject } from './stateObject';\nimport { StateBuilder } from './stateBuilder';\nimport { StateRegistryListener, StateRegistry } from './stateRegistry';\nimport { Disposable } from '../interface';\nimport { UrlRouter } from '../url/urlRouter';\nimport { prop } from '../common/hof';\nimport { StateMatcher } from './stateMatcher';\n\n/** @internalapi */\nexport class StateQueueManager implements Disposable {\n queue: StateObject[];\n matcher: StateMatcher;\n\n constructor(\n private $registry: StateRegistry,\n private $urlRouter: UrlRouter,\n public states: { [key: string]: StateObject; },\n public builder: StateBuilder,\n public listeners: StateRegistryListener[]) {\n this.queue = [];\n this.matcher = $registry.matcher;\n }\n\n /** @internalapi */\n dispose() {\n this.queue = [];\n }\n\n register(stateDecl: _StateDeclaration) {\n const queue = this.queue;\n const state = StateObject.create(stateDecl);\n const name = state.name;\n\n if (!isString(name)) throw new Error('State must have a valid name');\n if (this.states.hasOwnProperty(name) || inArray(queue.map(prop('name')), name))\n throw new Error(`State '${name}' is already defined`);\n\n queue.push(state);\n this.flush();\n\n return state;\n }\n\n flush() {\n const { queue, states, builder } = this;\n const registered: StateObject[] = [], // states that got registered\n orphans: StateObject[] = [], // states that don't yet have a parent registered\n previousQueueLength = {}; // keep track of how long the queue when an orphan was first encountered\n const getState = (name) =>\n this.states.hasOwnProperty(name) && this.states[name];\n\n while (queue.length > 0) {\n const state: StateObject = queue.shift();\n const name = state.name;\n const result: StateObject = builder.build(state);\n const orphanIdx: number = orphans.indexOf(state);\n\n if (result) {\n const existingState = getState(name);\n if (existingState && existingState.name === name) {\n throw new Error(`State '${name}' is already defined`);\n }\n\n const existingFutureState = getState(name + '.**');\n if (existingFutureState) {\n // Remove future state of the same name\n this.$registry.deregister(existingFutureState);\n }\n\n states[name] = state;\n this.attachRoute(state);\n if (orphanIdx >= 0) orphans.splice(orphanIdx, 1);\n registered.push(state);\n continue;\n }\n\n const prev = previousQueueLength[name];\n previousQueueLength[name] = queue.length;\n if (orphanIdx >= 0 && prev === queue.length) {\n // Wait until two consecutive iterations where no additional states were dequeued successfully.\n // throw new Error(`Cannot register orphaned state '${name}'`);\n queue.push(state);\n return states;\n } else if (orphanIdx < 0) {\n orphans.push(state);\n }\n\n queue.push(state);\n }\n\n if (registered.length) {\n this.listeners.forEach(listener => listener('registered', registered.map(s => s.self)));\n }\n\n return states;\n }\n\n attachRoute(state: StateObject) {\n if (state.abstract || !state.url) return;\n\n this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(state));\n }\n}\n", - "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { StateBuilder } from './stateBuilder';\nimport { StateQueueManager } from './stateQueueManager';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { BuilderFunction } from './stateBuilder';\nimport { StateOrName } from './interface';\nimport { removeFrom } from '../common/common';\nimport { UIRouter } from '../router';\nimport { propEq } from '../common/hof';\n\n/**\n * The signature for the callback function provided to [[StateRegistry.onStatesChanged]].\n *\n * This callback receives two parameters:\n *\n * @param event a string; either \"registered\" or \"deregistered\"\n * @param states the list of [[StateDeclaration]]s that were registered (or deregistered).\n */\nexport type StateRegistryListener = (event: 'registered'|'deregistered', states: StateDeclaration[]) => void;\n\nexport class StateRegistry {\n private _root: StateObject;\n private states: { [key: string]: StateObject } = {};\n\n matcher: StateMatcher;\n private builder: StateBuilder;\n stateQueue: StateQueueManager;\n\n listeners: StateRegistryListener[] = [];\n\n /** @internalapi */\n constructor(private _router: UIRouter) {\n this.matcher = new StateMatcher(this.states);\n this.builder = new StateBuilder(this.matcher, _router.urlMatcherFactory);\n this.stateQueue = new StateQueueManager(this, _router.urlRouter, this.states, this.builder, this.listeners);\n this._registerRoot();\n }\n\n /** @internalapi */\n private _registerRoot() {\n const rootStateDef: StateDeclaration = {\n name: '',\n url: '^',\n views: null,\n params: {\n '#': { value: null, type: 'hash', dynamic: true },\n },\n abstract: true,\n };\n\n const _root = this._root = this.stateQueue.register(rootStateDef);\n _root.navigable = null;\n }\n\n /** @internalapi */\n dispose() {\n this.stateQueue.dispose();\n this.listeners = [];\n this.get().forEach(state => this.get(state) && this.deregister(state));\n }\n\n /**\n * Listen for a State Registry events\n *\n * Adds a callback that is invoked when states are registered or deregistered with the StateRegistry.\n *\n * #### Example:\n * ```js\n * let allStates = registry.get();\n *\n * // Later, invoke deregisterFn() to remove the listener\n * let deregisterFn = registry.onStatesChanged((event, states) => {\n * switch(event) {\n * case: 'registered':\n * states.forEach(state => allStates.push(state));\n * break;\n * case: 'deregistered':\n * states.forEach(state => {\n * let idx = allStates.indexOf(state);\n * if (idx !== -1) allStates.splice(idx, 1);\n * });\n * break;\n * }\n * });\n * ```\n *\n * @param listener a callback function invoked when the registered states changes.\n * The function receives two parameters, `event` and `state`.\n * See [[StateRegistryListener]]\n * @return a function that deregisters the listener\n */\n onStatesChanged(listener: StateRegistryListener): () => void {\n this.listeners.push(listener);\n return function deregisterListener() {\n removeFrom(this.listeners)(listener);\n }.bind(this);\n }\n\n /**\n * Gets the implicit root state\n *\n * Gets the root of the state tree.\n * The root state is implicitly created by UI-Router.\n * Note: this returns the internal [[StateObject]] representation, not a [[StateDeclaration]]\n *\n * @return the root [[StateObject]]\n */\n root() {\n return this._root;\n }\n\n /**\n * Adds a state to the registry\n *\n * Registers a [[StateDeclaration]] or queues it for registration.\n *\n * Note: a state will be queued if the state's parent isn't yet registered.\n *\n * @param stateDefinition the definition of the state to register.\n * @returns the internal [[StateObject]] object.\n * If the state was successfully registered, then the object is fully built (See: [[StateBuilder]]).\n * If the state was only queued, then the object is not fully built.\n */\n register(stateDefinition: _StateDeclaration): StateObject {\n return this.stateQueue.register(stateDefinition);\n }\n\n /** @hidden */\n private _deregisterTree(state: StateObject) {\n const all = this.get().map(s => s.$$state());\n const getChildren = (states: StateObject[]) => {\n const _children = all.filter(s => states.indexOf(s.parent) !== -1);\n return _children.length === 0 ? _children : _children.concat(getChildren(_children));\n };\n\n const children = getChildren([state]);\n const deregistered: StateObject[] = [state].concat(children).reverse();\n\n deregistered.forEach(_state => {\n const $ur = this._router.urlRouter;\n // Remove URL rule\n $ur.rules().filter(propEq('state', _state)).forEach($ur.removeRule.bind($ur));\n // Remove state from registry\n delete this.states[_state.name];\n });\n\n return deregistered;\n }\n\n /**\n * Removes a state from the registry\n *\n * This removes a state from the registry.\n * If the state has children, they are are also removed from the registry.\n *\n * @param stateOrName the state's name or object representation\n * @returns {StateObject[]} a list of removed states\n */\n deregister(stateOrName: StateOrName) {\n const _state = this.get(stateOrName);\n if (!_state) throw new Error(\"Can't deregister state; not found: \" + stateOrName);\n const deregisteredStates = this._deregisterTree(_state.$$state());\n\n this.listeners.forEach(listener => listener('deregistered', deregisteredStates.map(s => s.self)));\n return deregisteredStates;\n }\n\n /**\n * Gets all registered states\n *\n * Calling this method with no arguments will return a list of all the states that are currently registered.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @return a list of [[StateDeclaration]]s\n */\n get(): StateDeclaration[];\n\n /**\n * Gets a registered state\n *\n * Given a state or a name, finds and returns the [[StateDeclaration]] from the registry.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @param stateOrName either the name of a state, or a state object.\n * @param base the base state to use when stateOrName is relative.\n * @return a registered [[StateDeclaration]] that matched the `stateOrName`, or null if the state isn't registered.\n */\n get(stateOrName: StateOrName, base?: StateOrName): StateDeclaration;\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n if (arguments.length === 0)\n return Object.keys(this.states).map(name => this.states[name].self);\n const found = this.matcher.find(stateOrName, base);\n return found && found.self || null;\n }\n\n decorator(name: string, func: BuilderFunction) {\n return this.builder.builder(name, func);\n }\n}\n", - "/**\n * @coreapi\n * @module url\n */\n/** for typedoc */\nimport {\n map, defaults, inherit, identity, unnest, tail, find, Obj, pairs, allTrueR, unnestR, arrayTuples,\n} from '../common/common';\nimport { prop, propEq } from '../common/hof';\nimport { isArray, isString, isDefined } from '../common/predicates';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { RawParams } from '../params/interface';\nimport { ParamFactory } from './interface';\nimport { joinNeighborsR, splitOnDelim } from '../common/strings';\n\n/** @hidden */\nfunction quoteRegExp(str: any, param?: any) {\n let surroundPattern = ['', ''], result = str.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, '\\\\$&');\n if (!param) return result;\n\n switch (param.squash) {\n case false:\n surroundPattern = ['(', ')' + (param.isOptional ? '?' : '')]; break;\n case true:\n result = result.replace(/\\/$/, '');\n surroundPattern = ['(?:\\/(', ')|\\/)?'];\n break;\n default:\n surroundPattern = [`(${param.squash}|`, ')?']; break;\n }\n return result + surroundPattern[0] + param.type.pattern.source + surroundPattern[1];\n}\n\n/** @hidden */\nconst memoizeTo = (obj: Obj, _prop: string, fn: Function) =>\n obj[_prop] = obj[_prop] || fn();\n\n/** @hidden */\nconst splitOnSlash = splitOnDelim('/');\n\n/** @hidden */\ninterface UrlMatcherCache {\n segments?: any[];\n weights?: number[];\n path?: UrlMatcher[];\n parent?: UrlMatcher;\n pattern?: RegExp;\n}\n\n/**\n * Matches URLs against patterns.\n *\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL.\n *\n * A URL pattern consists of a path pattern, optionally followed by '?' and a list of search (query)\n * parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by [[UrlMatcher.exec]].\n *\n * - *Path parameters* are defined using curly brace placeholders (`/somepath/{param}`)\n * or colon placeholders (`/somePath/:param`).\n *\n * - *A parameter RegExp* may be defined for a param after a colon\n * (`/somePath/{param:[a-zA-Z0-9]+}`) in a curly brace placeholder.\n * The regexp must match for the url to be matched.\n * Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Note: a RegExp parameter will encode its value using either [[ParamTypes.path]] or [[ParamTypes.query]].\n *\n * - *Custom parameter types* may also be specified after a colon (`/somePath/{param:int}`) in curly brace parameters.\n * See [[UrlMatcherFactory.type]] for more information.\n *\n * - *Catch-all parameters* are defined using an asterisk placeholder (`/somepath/*catchallparam`).\n * A catch-all * parameter value will contain the remainder of the URL.\n *\n * ---\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters).\n * A path parameter matches any number of characters other than '/'. For catch-all\n * placeholders the path parameter matches any number of characters.\n *\n * Examples:\n *\n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n * trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n * parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n * path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n * in the built-in `date` ParamType matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n */\nexport class UrlMatcher {\n /** @hidden */\n static nameValidator: RegExp = /^\\w+([-.]+\\w+)*(?:\\[\\])?$/;\n\n /** @hidden */\n private _cache: UrlMatcherCache = { path: [this] };\n /** @hidden */\n private _children: UrlMatcher[] = [];\n /** @hidden */\n private _params: Param[] = [];\n /** @hidden */\n private _segments: string[] = [];\n /** @hidden */\n private _compiled: string[] = [];\n\n /** The pattern that was passed into the constructor */\n public pattern: string;\n\n /** @hidden */\n static encodeDashes(str: string) { // Replace dashes with encoded \"\\-\"\n return encodeURIComponent(str).replace(/-/g, c => `%5C%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n }\n\n /** @hidden Given a matcher, return an array with the matcher's path segments and path params, in order */\n static pathSegmentsAndParams(matcher: UrlMatcher) {\n const staticSegments = matcher._segments;\n const pathParams = matcher._params.filter(p => p.location === DefType.PATH);\n return arrayTuples(staticSegments, pathParams.concat(undefined))\n .reduce(unnestR, [])\n .filter(x => x !== '' && isDefined(x));\n }\n\n /** @hidden Given a matcher, return an array with the matcher's query params */\n static queryParams(matcher: UrlMatcher): Param[] {\n return matcher._params.filter(p => p.location === DefType.SEARCH);\n }\n\n /**\n * Compare two UrlMatchers\n *\n * This comparison function converts a UrlMatcher into static and dynamic path segments.\n * Each static path segment is a static string between a path separator (slash character).\n * Each dynamic segment is a path parameter.\n *\n * The comparison function sorts static segments before dynamic ones.\n */\n static compare(a: UrlMatcher, b: UrlMatcher): number {\n /**\n * Turn a UrlMatcher and all its parent matchers into an array\n * of slash literals '/', string literals, and Param objects\n *\n * This example matcher matches strings like \"/foo/:param/tail\":\n * var matcher = $umf.compile(\"/foo\").append($umf.compile(\"/:param\")).append($umf.compile(\"/\")).append($umf.compile(\"tail\"));\n * var result = segments(matcher); // [ '/', 'foo', '/', Param, '/', 'tail' ]\n *\n * Caches the result as `matcher._cache.segments`\n */\n const segments = (matcher: UrlMatcher) =>\n matcher._cache.segments = matcher._cache.segments ||\n matcher._cache.path.map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .reduce(joinNeighborsR, [])\n .map(x => isString(x) ? splitOnSlash(x) : x)\n .reduce(unnestR, []);\n\n /**\n * Gets the sort weight for each segment of a UrlMatcher\n *\n * Caches the result as `matcher._cache.weights`\n */\n const weights = (matcher: UrlMatcher) =>\n matcher._cache.weights = matcher._cache.weights ||\n segments(matcher).map(segment => {\n // Sort slashes first, then static strings, the Params\n if (segment === '/') return 1;\n if (isString(segment)) return 2;\n if (segment instanceof Param) return 3;\n });\n\n /**\n * Pads shorter array in-place (mutates)\n */\n const padArrays = (l: any[], r: any[], padVal: any) => {\n const len = Math.max(l.length, r.length);\n while (l.length < len) l.push(padVal);\n while (r.length < len) r.push(padVal);\n };\n\n const weightsA = weights(a), weightsB = weights(b);\n padArrays(weightsA, weightsB, 0);\n\n const _pairs = arrayTuples(weightsA, weightsB);\n let cmp, i;\n\n for (i = 0; i < _pairs.length; i++) {\n cmp = _pairs[i][0] - _pairs[i][1];\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n }\n\n /**\n * @param pattern The pattern to compile into a matcher.\n * @param paramTypes The [[ParamTypes]] registry\n * @param config A configuration object\n * - `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * - `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n */\n constructor(pattern: string, paramTypes: ParamTypes, paramFactory: ParamFactory, public config?: any) {\n this.pattern = pattern;\n this.config = defaults(this.config, {\n params: {},\n strict: true,\n caseInsensitive: false,\n paramMap: identity,\n });\n\n // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n // '*' name\n // ':' name\n // '{' name '}'\n // '{' name ':' regexp '}'\n // The regular expression is somewhat complicated due to the need to allow curly braces\n // inside the regular expression. The placeholder regexp breaks down as follows:\n // ([:*])([\\w\\[\\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)\n // \\{([\\w\\[\\]]+)(?:\\:\\s*( ... ))?\\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either\n // [^{}\\\\]+ - anything other than curly braces or backslash\n // \\\\. - a backslash escape\n // \\{(?:[^{}\\\\]+|\\\\.)*\\} - a matched set of curly braces containing other atoms\n const placeholder = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const searchPlaceholder = /([:]?)([\\w\\[\\].-]+)|\\{([\\w\\[\\].-]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const patterns: any[][] = [];\n let last = 0, matchArray: RegExpExecArray;\n\n const checkParamErrors = (id: string) => {\n if (!UrlMatcher.nameValidator.test(id)) throw new Error(`Invalid parameter name '${id}' in pattern '${pattern}'`);\n if (find(this._params, propEq('id', id))) throw new Error(`Duplicate parameter name '${id}' in pattern '${pattern}'`);\n };\n\n // Split into static segments separated by path parameter placeholders.\n // The number of segments is always 1 more than the number of parameters.\n const matchDetails = (m: RegExpExecArray, isSearch: boolean) => {\n // IE[78] returns '' for unmatched groups instead of null\n const id: string = m[2] || m[3];\n const regexp: string = isSearch ? m[4] : m[4] || (m[1] === '*' ? '[\\\\s\\\\S]*' : null);\n\n const makeRegexpType = (str) => inherit(paramTypes.type(isSearch ? 'query' : 'path'), {\n pattern: new RegExp(str, this.config.caseInsensitive ? 'i' : undefined),\n });\n\n return {\n id,\n regexp,\n cfg: this.config.params[id],\n segment: pattern.substring(last, m.index),\n type: !regexp ? null : paramTypes.type(regexp) || makeRegexpType(regexp),\n };\n };\n\n let p: any, segment: string;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = placeholder.exec(pattern))) {\n p = matchDetails(matchArray, false);\n if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromPath(p.id, p.type, this.config.paramMap(p.cfg, false)));\n this._segments.push(p.segment);\n patterns.push([p.segment, tail(this._params)]);\n last = placeholder.lastIndex;\n }\n segment = pattern.substring(last);\n\n // Find any search parameter names and remove them from the last segment\n const i = segment.indexOf('?');\n\n if (i >= 0) {\n const search = segment.substring(i);\n segment = segment.substring(0, i);\n\n if (search.length > 0) {\n last = 0;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = searchPlaceholder.exec(search))) {\n p = matchDetails(matchArray, true);\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromSearch(p.id, p.type, this.config.paramMap(p.cfg, true)));\n last = placeholder.lastIndex;\n // check if ?&\n }\n }\n }\n\n this._segments.push(segment);\n this._compiled = patterns.map(_pattern => quoteRegExp.apply(null, _pattern)).concat(quoteRegExp(segment));\n }\n\n /**\n * Creates a new concatenated UrlMatcher\n *\n * Builds a new UrlMatcher by appending another UrlMatcher to this one.\n *\n * @param url A `UrlMatcher` instance to append as a child of the current `UrlMatcher`.\n */\n append(url: UrlMatcher): UrlMatcher {\n this._children.push(url);\n url._cache = {\n path: this._cache.path.concat(url),\n parent: this,\n pattern: null,\n };\n return url;\n }\n\n /** @hidden */\n isRoot(): boolean {\n return this._cache.path[0] === this;\n }\n\n /** Returns the input pattern string */\n toString(): string {\n return this.pattern;\n }\n\n /**\n * Tests the specified url/path against this matcher.\n *\n * Tests if the given url matches this matcher's pattern, and returns an object containing the captured\n * parameter values. Returns null if the path does not match.\n *\n * The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `search`. This means that search parameters are always treated\n * as optional.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n * x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * ```\n *\n * @param path The URL path to match, e.g. `$location.path()`.\n * @param search URL search parameters, e.g. `$location.search()`.\n * @param hash URL hash e.g. `$location.hash()`.\n * @param options\n *\n * @returns The captured parameter values.\n */\n exec(path: string, search: any = {}, hash?: string, options: any = {}): RawParams {\n const match = memoizeTo(this._cache, 'pattern', () => {\n return new RegExp([\n '^',\n unnest(this._cache.path.map(prop('_compiled'))).join(''),\n this.config.strict === false ? '\\/?' : '',\n '$',\n ].join(''), this.config.caseInsensitive ? 'i' : undefined);\n }).exec(path);\n\n if (!match) return null;\n\n // options = defaults(options, { isolate: false });\n\n const allParams: Param[] = this.parameters(),\n pathParams: Param[] = allParams.filter(param => !param.isSearch()),\n searchParams: Param[] = allParams.filter(param => param.isSearch()),\n nPathSegments = this._cache.path.map(urlm => urlm._segments.length - 1).reduce((a, x) => a + x),\n values: RawParams = {};\n\n if (nPathSegments !== match.length - 1)\n throw new Error(`Unbalanced capture group in route '${this.pattern}'`);\n\n function decodePathArray(paramVal: string) {\n const reverseString = (str: string) => str.split('').reverse().join('');\n const unquoteDashes = (str: string) => str.replace(/\\\\-/g, '-');\n\n const split = reverseString(paramVal).split(/-(?!\\\\)/);\n const allReversed = map(split, reverseString);\n return map(allReversed, unquoteDashes).reverse();\n }\n\n for (let i = 0; i < nPathSegments; i++) {\n const param: Param = pathParams[i];\n let value: (any|any[]) = match[i + 1];\n\n // if the param value matches a pre-replace pair, replace the value before decoding.\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (value && param.array === true) value = decodePathArray(value);\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n }\n searchParams.forEach(param => {\n let value = search[param.id];\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n });\n\n if (hash) values['#'] = hash;\n\n return values;\n }\n\n /**\n * @hidden\n * Returns all the [[Param]] objects of all path and search parameters of this pattern in order of appearance.\n *\n * @returns {Array.} An array of [[Param]] objects. Must be treated as read-only. If the\n * pattern has no parameters, an empty array is returned.\n */\n parameters(opts: any = {}): Param[] {\n if (opts.inherit === false) return this._params;\n return unnest(this._cache.path.map(matcher => matcher._params));\n }\n\n /**\n * @hidden\n * Returns a single parameter from this UrlMatcher by id\n *\n * @param id\n * @param opts\n * @returns {T|Param|any|boolean|UrlMatcher|null}\n */\n parameter(id: string, opts: any = {}): Param {\n const findParam = () => {\n for (const param of this._params) {\n if (param.id === id) return param;\n }\n };\n\n const parent = this._cache.parent;\n return findParam() || (opts.inherit !== false && parent && parent.parameter(id, opts)) || null;\n }\n\n /**\n * Validates the input parameter values against this UrlMatcher\n *\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param params The object hash of parameters to validate.\n * @returns Returns `true` if `params` validates, otherwise `false`.\n */\n validates(params: RawParams): boolean {\n const validParamVal = (param: Param, val: any) =>\n !param || param.validates(val);\n\n params = params || {};\n\n // I'm not sure why this checks only the param keys passed in, and not all the params known to the matcher\n const paramSchema = this.parameters().filter(paramDef => params.hasOwnProperty(paramDef.id));\n return paramSchema.map(paramDef => validParamVal(paramDef, params[paramDef.id])).reduce(allTrueR, true);\n }\n\n /**\n * Given a set of parameter values, creates a URL from this UrlMatcher.\n *\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * ```\n *\n * @param values the values to substitute for the parameters in this pattern.\n * @returns the formatted URL (path and optionally search part).\n */\n format(values: RawParams = {}) {\n // Build the full path of UrlMatchers (including all parent UrlMatchers)\n const urlMatchers = this._cache.path;\n\n // Extract all the static segments and Params (processed as ParamDetails)\n // into an ordered array\n const pathSegmentsAndParams: Array = urlMatchers.map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .map(x => isString(x) ? x : getDetails(x));\n\n // Extract the query params into a separate array\n const queryParams: Array = urlMatchers.map(UrlMatcher.queryParams)\n .reduce(unnestR, [])\n .map(getDetails);\n\n const isInvalid = (param: ParamDetails) => param.isValid === false;\n if (pathSegmentsAndParams.concat(queryParams).filter(isInvalid).length) {\n return null;\n }\n\n /**\n * Given a Param, applies the parameter value, then returns detailed information about it\n */\n function getDetails(param: Param): ParamDetails {\n // Normalize to typed value\n const value = param.value(values[param.id]);\n const isValid = param.validates(value);\n const isDefaultValue = param.isDefaultValue(value);\n // Check if we're in squash mode for the parameter\n const squash = isDefaultValue ? param.squash : false;\n // Allow the Parameter's Type to encode the value\n const encoded = param.type.encode(value);\n\n return { param, value, isValid, isDefaultValue, squash, encoded };\n }\n\n // Build up the path-portion from the list of static segments and parameters\n const pathString = pathSegmentsAndParams.reduce((acc: string, x: string|ParamDetails) => {\n // The element is a static segment (a raw string); just append it\n if (isString(x)) return acc + x;\n\n // Otherwise, it's a ParamDetails.\n const { squash, encoded, param } = x;\n\n // If squash is === true, try to remove a slash from the path\n if (squash === true) return (acc.match(/\\/$/)) ? acc.slice(0, -1) : acc;\n // If squash is a string, use the string for the param value\n if (isString(squash)) return acc + squash;\n if (squash !== false) return acc; // ?\n if (encoded == null) return acc;\n // If this parameter value is an array, encode the value using encodeDashes\n if (isArray(encoded)) return acc + map( encoded, UrlMatcher.encodeDashes).join('-');\n // If the parameter type is \"raw\", then do not encodeURIComponent\n if (param.raw) return acc + encoded;\n // Encode the value\n return acc + encodeURIComponent( encoded);\n }, '');\n\n // Build the query string by applying parameter values (array or regular)\n // then mapping to key=value, then flattening and joining using \"&\"\n const queryString = queryParams.map((paramDetails: ParamDetails) => {\n let { param, squash, encoded, isDefaultValue } = paramDetails;\n if (encoded == null || (isDefaultValue && squash !== false)) return;\n if (!isArray(encoded)) encoded = [ encoded];\n if (encoded.length === 0) return;\n if (!param.raw) encoded = map( encoded, encodeURIComponent);\n\n return ( encoded).map(val => `${param.id}=${val}`);\n }).filter(identity).reduce(unnestR, []).join('&');\n\n // Concat the pathstring with the queryString (if exists) and the hashString (if exists)\n return pathString + (queryString ? `?${queryString}` : '') + (values['#'] ? '#' + values['#'] : '');\n }\n}\n\n/** @hidden */\ninterface ParamDetails {\n param: Param;\n value: any;\n isValid: boolean;\n isDefaultValue: boolean;\n squash: (boolean|string);\n encoded: (string|string[]);\n}\n", - "/**\n * @internalapi\n * @module url\n */ /** for typedoc */\nimport { forEach, extend } from '../common/common';\nimport { isObject, isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { ParamTypeDefinition } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { ParamType } from '../params/paramType';\nimport { ParamFactory, UrlMatcherConfig } from './interface';\n\n/**\n * Factory for [[UrlMatcher]] instances.\n *\n * The factory is available to ng1 services as\n * `$urlMatcherFactory` or ng1 providers as `$urlMatcherFactoryProvider`.\n */\nexport class UrlMatcherFactory implements Disposable, UrlMatcherConfig {\n /** @hidden */ paramTypes = new ParamTypes();\n /** @hidden */ _isCaseInsensitive = false;\n /** @hidden */ _isStrictMode = true;\n /** @hidden */ _defaultSquashPolicy: (boolean|string) = false;\n\n /** @internalapi Creates a new [[Param]] for a given location (DefType) */\n paramFactory: ParamFactory = {\n /** Creates a new [[Param]] from a CONFIG block */\n fromConfig: (id: string, type: ParamType, config: any) =>\n new Param(id, type, config, DefType.CONFIG, this),\n\n /** Creates a new [[Param]] from a url PATH */\n fromPath: (id: string, type: ParamType, config: any) =>\n new Param(id, type, config, DefType.PATH, this),\n\n /** Creates a new [[Param]] from a url SEARCH */\n fromSearch: (id: string, type: ParamType, config: any) =>\n new Param(id, type, config, DefType.SEARCH, this),\n };\n\n constructor() {\n extend(this, { UrlMatcher, Param });\n }\n\n /** @inheritdoc */\n caseInsensitive(value?: boolean): boolean {\n return this._isCaseInsensitive = isDefined(value) ? value : this._isCaseInsensitive;\n }\n\n /** @inheritdoc */\n strictMode(value?: boolean): boolean {\n return this._isStrictMode = isDefined(value) ? value : this._isStrictMode;\n }\n\n /** @inheritdoc */\n defaultSquashPolicy(value?: (boolean|string)) {\n if (isDefined(value) && value !== true && value !== false && !isString(value))\n throw new Error(`Invalid squash policy: ${value}. Valid policies: false, true, arbitrary-string`);\n return this._defaultSquashPolicy = isDefined(value) ? value : this._defaultSquashPolicy;\n }\n\n /** @hidden */\n private _getConfig = (config) =>\n extend({ strict: this._isStrictMode, caseInsensitive: this._isCaseInsensitive }, config);\n\n /**\n * Creates a [[UrlMatcher]] for the specified pattern.\n *\n * @param pattern The URL pattern.\n * @param config The config object hash.\n * @returns The UrlMatcher.\n */\n compile(pattern: string, config?: { [key: string]: any }) {\n return new UrlMatcher(pattern, this.paramTypes, this.paramFactory, this._getConfig(config));\n }\n\n /**\n * Returns true if the specified object is a [[UrlMatcher]], or false otherwise.\n *\n * @param object The object to perform the type check against.\n * @returns `true` if the object matches the `UrlMatcher` interface, by\n * implementing all the same methods.\n */\n isMatcher(object: any): boolean {\n // TODO: typeof?\n if (!isObject(object)) return false;\n let result = true;\n\n forEach(UrlMatcher.prototype, (val, name) => {\n if (isFunction(val)) result = result && (isDefined(object[name]) && isFunction(object[name]));\n });\n return result;\n }\n\n /**\n * Creates and registers a custom [[ParamType]] object\n *\n * A [[ParamType]] can be used to generate URLs with typed parameters.\n *\n * @param name The type name.\n * @param definition The type definition. See [[ParamTypeDefinition]] for information on the values accepted.\n * @param definitionFn A function that is injected before the app runtime starts.\n * The result of this function should be a [[ParamTypeDefinition]].\n * The result is merged into the existing `definition`.\n * See [[ParamType]] for information on the values accepted.\n *\n * @returns - if a type was registered: the [[UrlMatcherFactory]]\n * - if only the `name` parameter was specified: the currently registered [[ParamType]] object, or undefined\n *\n * Note: Register custom types *before using them* in a state definition.\n *\n * See [[ParamTypeDefinition]] for examples\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n const type = this.paramTypes.type(name, definition, definitionFn);\n return !isDefined(definition) ? type : this;\n }\n\n /** @hidden */\n $get() {\n this.paramTypes.enqueue = false;\n this.paramTypes._flushTypeQueue();\n return this;\n }\n\n /** @internalapi */\n dispose() {\n this.paramTypes.dispose();\n }\n}\n", - "/**\n * @coreapi\n * @module url\n */ /** */\nimport { UrlMatcher } from './urlMatcher';\nimport { isString, isDefined, isFunction, isState } from '../common/predicates';\nimport { UIRouter } from '../router';\nimport { identity, extend } from '../common/common';\nimport { is, pattern } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport {\n UrlRule, UrlRuleMatchFn, UrlRuleHandlerFn, UrlRuleType, UrlParts, MatcherUrlRule, StateRule, RegExpRule,\n} from './interface';\n\n/**\n * Creates a [[UrlRule]]\n *\n * Creates a [[UrlRule]] from a:\n *\n * - `string`\n * - [[UrlMatcher]]\n * - `RegExp`\n * - [[StateObject]]\n * @internalapi\n */\nexport class UrlRuleFactory {\n static isUrlRule = obj =>\n obj && ['type', 'match', 'handler'].every(key => isDefined(obj[key]));\n\n constructor(public router: UIRouter) { }\n\n compile(str: string) {\n return this.router.urlMatcherFactory.compile(str);\n }\n\n create(what: string|UrlMatcher|StateObject|RegExp|UrlRuleMatchFn, handler?: string|UrlRuleHandlerFn): UrlRule {\n const makeRule = pattern([\n [isString, (_what: string) => makeRule(this.compile(_what))],\n [is(UrlMatcher), (_what: UrlMatcher) => this.fromUrlMatcher(_what, handler)],\n [isState, (_what: StateObject) => this.fromState(_what, this.router)],\n [is(RegExp), (_what: RegExp) => this.fromRegExp(_what, handler)],\n [isFunction, (_what: UrlRuleMatchFn) => new BaseUrlRule(_what, handler as UrlRuleHandlerFn)],\n ]);\n\n const rule = makeRule(what);\n if (!rule) throw new Error(\"invalid 'what' in when()\");\n return rule;\n }\n\n /**\n * A UrlRule which matches based on a UrlMatcher\n *\n * The `handler` may be either a `string`, a [[UrlRuleHandlerFn]] or another [[UrlMatcher]]\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - matched parameter values ([[RawParams]] from [[UrlMatcher.exec]])\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, match => \"/home/\" + match.fooId + \"/\" + match.barId);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n *\n * ## Handler as UrlMatcher\n *\n * If `handler` is a UrlMatcher, the handler matcher is used to create the new url.\n * The `handler` UrlMatcher is formatted using the matched param from the first matcher.\n * The url is replaced with the result.\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var handler = $umf.compile(\"/home/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, handler);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n */\n fromUrlMatcher(urlMatcher: UrlMatcher, handler: string|UrlMatcher|UrlRuleHandlerFn): MatcherUrlRule {\n let _handler: UrlRuleHandlerFn = handler as any;\n if (isString(handler)) handler = this.router.urlMatcherFactory.compile(handler);\n if (is(UrlMatcher)(handler)) _handler = (match: RawParams) => (handler as UrlMatcher).format(match);\n\n function matchUrlParamters(url: UrlParts): RawParams {\n const params = urlMatcher.exec(url.path, url.search, url.hash);\n return urlMatcher.validates(params) && params;\n }\n\n // Prioritize URLs, lowest to highest:\n // - Some optional URL parameters, but none matched\n // - No optional parameters in URL\n // - Some optional parameters, some matched\n // - Some optional parameters, all matched\n function matchPriority(params: RawParams): number {\n const optional = urlMatcher.parameters().filter(param => param.isOptional);\n if (!optional.length) return 0.000001;\n const matched = optional.filter(param => params[param.id]);\n return matched.length / optional.length;\n }\n\n const details = { urlMatcher, matchPriority, type: 'URLMATCHER' };\n return extend(new BaseUrlRule(matchUrlParamters, _handler), details) as MatcherUrlRule;\n }\n\n\n /**\n * A UrlRule which matches a state by its url\n *\n * #### Example:\n * ```js\n * var rule = factory.fromState($state.get('foo'), router);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match);\n * // Starts a transition to 'foo' with params: { fooId: '123', barId: '456' }\n * ```\n */\n fromState(state: StateObject, router: UIRouter): StateRule {\n /**\n * Handles match by transitioning to matched state\n *\n * First checks if the router should start a new transition.\n * A new transition is not required if the current state's URL\n * and the new URL are already identical\n */\n const handler = (match: RawParams) => {\n const $state = router.stateService;\n const globals = router.globals;\n if ($state.href(state, match) !== $state.href(globals.current, globals.params)) {\n $state.transitionTo(state, match, { inherit: true, source: 'url' });\n }\n };\n\n const details = { state, type: 'STATE' };\n return extend(this.fromUrlMatcher(state.url, handler), details) as StateRule;\n }\n\n /**\n * A UrlRule which matches based on a regular expression\n *\n * The `handler` may be either a [[UrlRuleHandlerFn]] or a string.\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - regexp match array (from `regexp`)\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, match => \"/home/\" + match[1])\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n *\n * ## Handler as string\n *\n * If `handler` is a string, the url is *replaced by the string* when the Rule is invoked.\n * The string is first interpolated using `string.replace()` style pattern.\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, \"/home/$1\")\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n */\n fromRegExp(regexp: RegExp, handler: string|UrlRuleHandlerFn): RegExpRule {\n if (regexp.global || regexp.sticky) throw new Error('Rule RegExp must not be global or sticky');\n\n /**\n * If handler is a string, the url will be replaced by the string.\n * If the string has any String.replace() style variables in it (like `$2`),\n * they will be replaced by the captures from [[match]]\n */\n const redirectUrlTo = (match: RegExpExecArray) =>\n // Interpolates matched values into $1 $2, etc using a String.replace()-style pattern\n (handler as string).replace(/\\$(\\$|\\d{1,2})/, (m, what) =>\n match[what === '$' ? 0 : Number(what)]);\n\n const _handler = isString(handler) ? redirectUrlTo : handler;\n\n const matchParamsFromRegexp = (url: UrlParts): RegExpExecArray =>\n regexp.exec(url.path);\n\n const details = { regexp, type: 'REGEXP' };\n return extend(new BaseUrlRule(matchParamsFromRegexp, _handler), details) as RegExpRule;\n }\n}\n\n/**\n * A base rule which calls `match`\n *\n * The value from the `match` function is passed through to the `handler`.\n * @internalapi\n */\nexport class BaseUrlRule implements UrlRule {\n $id: number;\n priority: number;\n type: UrlRuleType = 'RAW';\n handler: UrlRuleHandlerFn;\n matchPriority = (match) => 0 - this.$id;\n\n constructor(public match: UrlRuleMatchFn, handler?: UrlRuleHandlerFn) {\n this.handler = handler || identity;\n }\n}\n", - "/**\n * @internalapi\n * @module url\n */\n/** for typedoc */\nimport { createProxyFunctions, extend, removeFrom } from '../common/common';\nimport { isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { RawParams } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { is, pattern, val } from '../common/hof';\nimport { UrlRuleFactory } from './urlRule';\nimport { TargetState } from '../state/targetState';\nimport { MatcherUrlRule, MatchResult, UrlParts, UrlRule, UrlRuleHandlerFn, UrlRuleMatchFn, UrlRulesApi, UrlSyncApi } from './interface';\nimport { TargetStateDef } from '../state/interface';\nimport { stripLastPathElement } from '../common';\n\n/** @hidden */\nfunction appendBasePath(url: string, isHtml5: boolean, absolute: boolean, baseHref: string): string {\n if (baseHref === '/') return url;\n if (isHtml5) return stripLastPathElement(baseHref) + url;\n if (absolute) return baseHref.slice(1) + url;\n return url;\n}\n\n/** @hidden */\nconst prioritySort = (a: UrlRule, b: UrlRule) =>\n (b.priority || 0) - (a.priority || 0);\n\n/** @hidden */\nconst typeSort = (a: UrlRule, b: UrlRule) => {\n const weights = { 'STATE': 4, 'URLMATCHER': 4, 'REGEXP': 3, 'RAW': 2, 'OTHER': 1 };\n return (weights[a.type] || 0) - (weights[b.type] || 0);\n};\n\n/** @hidden */\nconst urlMatcherSort = (a: MatcherUrlRule, b: MatcherUrlRule) =>\n !a.urlMatcher || !b.urlMatcher ? 0 : UrlMatcher.compare(a.urlMatcher, b.urlMatcher);\n\n/** @hidden */\nconst idSort = (a: UrlRule, b: UrlRule) => {\n // Identically sorted STATE and URLMATCHER best rule will be chosen by `matchPriority` after each rule matches the URL\n const useMatchPriority = { STATE: true, URLMATCHER: true };\n const equal = useMatchPriority[a.type] && useMatchPriority[b.type];\n return equal ? 0 : (a.$id || 0) - (b.$id || 0);\n};\n\n/**\n * Default rule priority sorting function.\n *\n * Sorts rules by:\n *\n * - Explicit priority (set rule priority using [[UrlRulesApi.when]])\n * - Rule type (STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1)\n * - `UrlMatcher` specificity ([[UrlMatcher.compare]]): works for STATE and URLMATCHER types to pick the most specific rule.\n * - Rule registration order (for rule types other than STATE and URLMATCHER)\n * - Equally sorted State and UrlMatcher rules will each match the URL.\n * Then, the *best* match is chosen based on how many parameter values were matched.\n *\n * @coreapi\n */\nlet defaultRuleSortFn: (a: UrlRule, b: UrlRule) => number;\ndefaultRuleSortFn = (a, b) => {\n let cmp = prioritySort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = typeSort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = urlMatcherSort(a as MatcherUrlRule, b as MatcherUrlRule);\n if (cmp !== 0) return cmp;\n\n return idSort(a, b);\n};\n\n/**\n * Updates URL and responds to URL changes\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class updates the URL when the state changes.\n * It also responds to changes in the URL.\n */\nexport class UrlRouter implements UrlRulesApi, UrlSyncApi, Disposable {\n /** used to create [[UrlRule]] objects for common cases */\n public urlRuleFactory: UrlRuleFactory;\n\n /** @hidden */ private _router: UIRouter;\n /** @hidden */ private location: string;\n /** @hidden */ private _sortFn = defaultRuleSortFn;\n /** @hidden */ private _stopFn: Function;\n /** @hidden */ _rules: UrlRule[] = [];\n /** @hidden */ private _otherwiseFn: UrlRule;\n /** @hidden */ interceptDeferred = false;\n /** @hidden */ private _id = 0;\n /** @hidden */ private _sorted = false;\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this.urlRuleFactory = new UrlRuleFactory(router);\n createProxyFunctions(val(UrlRouter.prototype), this, val(this));\n }\n\n /** @internalapi */\n dispose() {\n this.listen(false);\n this._rules = [];\n delete this._otherwiseFn;\n }\n\n /** @inheritdoc */\n sort(compareFn?: (a: UrlRule, b: UrlRule) => number) {\n this._rules = this.stableSort(this._rules, this._sortFn = compareFn || this._sortFn);\n this._sorted = true;\n }\n\n private ensureSorted() {\n this._sorted || this.sort();\n }\n\n private stableSort(arr, compareFn) {\n const arrOfWrapper = arr.map((elem, idx) => ({ elem, idx }));\n\n arrOfWrapper.sort((wrapperA, wrapperB) => {\n const cmpDiff = compareFn(wrapperA.elem, wrapperB.elem);\n return cmpDiff === 0\n ? wrapperA.idx - wrapperB.idx\n : cmpDiff;\n });\n\n return arrOfWrapper.map(wrapper => wrapper.elem);\n }\n\n /**\n * Given a URL, check all rules and return the best [[MatchResult]]\n * @param url\n * @returns {MatchResult}\n */\n match(url: UrlParts): MatchResult {\n this.ensureSorted();\n\n url = extend({ path: '', search: {}, hash: '' }, url);\n const rules = this.rules();\n if (this._otherwiseFn) rules.push(this._otherwiseFn);\n\n // Checks a single rule. Returns { rule: rule, match: match, weight: weight } if it matched, or undefined\n\n const checkRule = (rule: UrlRule): MatchResult => {\n const match = rule.match(url, this._router);\n return match && { match, rule, weight: rule.matchPriority(match) };\n };\n\n // The rules are pre-sorted.\n // - Find the first matching rule.\n // - Find any other matching rule that sorted *exactly the same*, according to `.sort()`.\n // - Choose the rule with the highest match weight.\n let best: MatchResult;\n for (let i = 0; i < rules.length; i++) {\n // Stop when there is a 'best' rule and the next rule sorts differently than it.\n if (best && this._sortFn(rules[i], best.rule) !== 0) break;\n\n const current = checkRule(rules[i]);\n // Pick the best MatchResult\n best = (!best || current && current.weight > best.weight) ? current : best;\n }\n\n return best;\n }\n\n /** @inheritdoc */\n sync(evt?) {\n if (evt && evt.defaultPrevented) return;\n\n const router = this._router,\n $url = router.urlService,\n $state = router.stateService;\n\n const url: UrlParts = {\n path: $url.path(), search: $url.search(), hash: $url.hash(),\n };\n\n const best = this.match(url);\n\n const applyResult = pattern([\n [isString, (newurl: string) => $url.url(newurl, true)],\n [TargetState.isDef, (def: TargetStateDef) => $state.go(def.state, def.params, def.options)],\n [is(TargetState), (target: TargetState) => $state.go(target.state(), target.params(), target.options())],\n ]);\n\n applyResult(best && best.rule.handler(best.match, url, router));\n }\n\n /** @inheritdoc */\n listen(enabled?: boolean): Function {\n if (enabled === false) {\n this._stopFn && this._stopFn();\n delete this._stopFn;\n } else {\n return this._stopFn = this._stopFn || this._router.urlService.onChange(evt => this.sync(evt));\n }\n }\n\n /**\n * Internal API.\n * @internalapi\n */\n update(read?: boolean) {\n const $url = this._router.locationService;\n if (read) {\n this.location = $url.url();\n return;\n }\n if ($url.url() === this.location) return;\n\n $url.url(this.location, true);\n }\n\n /**\n * Internal API.\n *\n * Pushes a new location to the browser history.\n *\n * @internalapi\n * @param urlMatcher\n * @param params\n * @param options\n */\n push(urlMatcher: UrlMatcher, params?: RawParams, options?: { replace?: (string|boolean) }) {\n const replace = options && !!options.replace;\n this._router.urlService.url(urlMatcher.format(params || {}), replace);\n }\n\n /**\n * Builds and returns a URL with interpolated parameters\n *\n * #### Example:\n * ```js\n * matcher = $umf.compile(\"/about/:person\");\n * params = { person: \"bob\" };\n * $bob = $urlRouter.href(matcher, params);\n * // $bob == \"/about/bob\";\n * ```\n *\n * @param urlMatcher The [[UrlMatcher]] object which is used as the template of the URL to generate.\n * @param params An object of parameter values to fill the matcher's required parameters.\n * @param options Options object. The options are:\n *\n * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n *\n * @returns Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n */\n href(urlMatcher: UrlMatcher, params?: any, options?: { absolute: boolean }): string {\n let url = urlMatcher.format(params);\n if (url == null) return null;\n\n options = options || { absolute: false };\n\n const cfg = this._router.urlService.config;\n const isHtml5 = cfg.html5Mode();\n if (!isHtml5 && url !== null) {\n url = '#' + cfg.hashPrefix() + url;\n }\n url = appendBasePath(url, isHtml5, options.absolute, cfg.baseHref());\n\n if (!options.absolute || !url) {\n return url;\n }\n\n const slash = (!isHtml5 && url ? '/' : '');\n const cfgPort = cfg.port();\n const port = (cfgPort === 80 || cfgPort === 443 ? '' : ':' + cfgPort);\n\n return [cfg.protocol(), '://', cfg.host(), port, slash, url].join('');\n }\n\n\n /**\n * Manually adds a URL Rule.\n *\n * Usually, a url rule is added using [[StateDeclaration.url]] or [[when]].\n * This api can be used directly for more control (to register a [[BaseUrlRule]], for example).\n * Rules can be created using [[UrlRouter.urlRuleFactory]], or create manually as simple objects.\n *\n * A rule should have a `match` function which returns truthy if the rule matched.\n * It should also have a `handler` function which is invoked if the rule is the best match.\n *\n * @return a function that deregisters the rule\n */\n rule(rule: UrlRule): Function {\n if (!UrlRuleFactory.isUrlRule(rule)) throw new Error('invalid rule');\n rule.$id = this._id++;\n rule.priority = rule.priority || 0;\n\n this._rules.push(rule);\n this._sorted = false;\n\n return () => this.removeRule(rule);\n }\n\n /** @inheritdoc */\n removeRule(rule): void {\n removeFrom(this._rules, rule);\n }\n\n /** @inheritdoc */\n rules(): UrlRule[] {\n this.ensureSorted();\n return this._rules.slice();\n }\n\n /** @inheritdoc */\n otherwise(handler: string|UrlRuleHandlerFn|TargetState|TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n this._otherwiseFn = this.urlRuleFactory.create(val(true), handlerFn);\n this._sorted = false;\n }\n\n /** @inheritdoc */\n initial(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n const matchFn: UrlRuleMatchFn = (urlParts, router) =>\n router.globals.transitionHistory.size() === 0 && !!/^\\/?$/.exec(urlParts.path);\n\n this.rule(this.urlRuleFactory.create(matchFn, handlerFn));\n }\n\n /** @inheritdoc */\n when(matcher: (RegExp|UrlMatcher|string), handler: string|UrlRuleHandlerFn, options?: { priority: number }): UrlRule {\n const rule = this.urlRuleFactory.create(matcher, handler);\n if (isDefined(options && options.priority)) rule.priority = options.priority;\n this.rule(rule);\n return rule;\n }\n\n /** @inheritdoc */\n deferIntercept(defer?: boolean) {\n if (defer === undefined) defer = true;\n this.interceptDeferred = defer;\n }\n}\n\nfunction getHandlerFn(handler: string|UrlRuleHandlerFn|TargetState|TargetStateDef): UrlRuleHandlerFn {\n if (!isFunction(handler) && !isString(handler) && !is(TargetState)(handler) && !TargetState.isDef(handler)) {\n throw new Error(\"'handler' must be a string, function, TargetState, or have a state: 'newtarget' property\");\n }\n return isFunction(handler) ? handler as UrlRuleHandlerFn : val(handler);\n}\n", - "/**\n * @coreapi\n * @module view\n */ /** for typedoc */\nimport { equals, applyPairs, removeFrom, TypedMap, inArray } from '../common/common';\nimport { curry, prop } from '../common/hof';\nimport { isString, isArray } from '../common/predicates';\nimport { trace } from '../common/trace';\nimport { PathNode } from '../path/pathNode';\nimport { ActiveUIView, ViewContext, ViewConfig } from './interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nexport type ViewConfigFactory = (path: PathNode[], decl: _ViewDeclaration) => ViewConfig|ViewConfig[];\n\nexport interface ViewServicePluginAPI {\n _rootViewContext(context?: ViewContext): ViewContext;\n _viewConfigFactory(viewType: string, factory: ViewConfigFactory);\n _registeredUIViews(): ActiveUIView[];\n _activeViewConfigs(): ViewConfig[];\n _onSync(listener: ViewSyncListener): Function;\n}\n\n// A uiView and its matching viewConfig\nexport interface ViewTuple {\n uiView: ActiveUIView;\n viewConfig: ViewConfig;\n}\n\nexport interface ViewSyncListener {\n (viewTuples: ViewTuple[]): void;\n}\n\n/**\n * The View service\n *\n * This service pairs existing `ui-view` components (which live in the DOM)\n * with view configs (from the state declaration objects: [[StateDeclaration.views]]).\n *\n * - After a successful Transition, the views from the newly entered states are activated via [[activateViewConfig]].\n * The views from exited states are deactivated via [[deactivateViewConfig]].\n * (See: the [[registerActivateViews]] Transition Hook)\n *\n * - As `ui-view` components pop in and out of existence, they register themselves using [[registerUIView]].\n *\n * - When the [[sync]] function is called, the registered `ui-view`(s) ([[ActiveUIView]])\n * are configured with the matching [[ViewConfig]](s)\n *\n */\nexport class ViewService {\n private _uiViews: ActiveUIView[] = [];\n private _viewConfigs: ViewConfig[] = [];\n private _rootContext: ViewContext;\n private _viewConfigFactories: { [key: string]: ViewConfigFactory } = {};\n private _listeners: ViewSyncListener[] = [];\n\n public _pluginapi: ViewServicePluginAPI = {\n _rootViewContext: this._rootViewContext.bind(this),\n _viewConfigFactory: this._viewConfigFactory.bind(this),\n _registeredUIViews: () => this._uiViews,\n _activeViewConfigs: () => this._viewConfigs,\n _onSync: (listener: ViewSyncListener) => {\n this._listeners.push(listener);\n return () => removeFrom(this._listeners, listener);\n },\n };\n\n /**\n * Given a ui-view and a ViewConfig, determines if they \"match\".\n *\n * A ui-view has a fully qualified name (fqn) and a context object. The fqn is built from its overall location in\n * the DOM, describing its nesting relationship to any parent ui-view tags it is nested inside of.\n *\n * A ViewConfig has a target ui-view name and a context anchor. The ui-view name can be a simple name, or\n * can be a segmented ui-view path, describing a portion of a ui-view fqn.\n *\n * In order for a ui-view to match ViewConfig, ui-view's $type must match the ViewConfig's $type\n *\n * If the ViewConfig's target ui-view name is a simple name (no dots), then a ui-view matches if:\n * - the ui-view's name matches the ViewConfig's target name\n * - the ui-view's context matches the ViewConfig's anchor\n *\n * If the ViewConfig's target ui-view name is a segmented name (with dots), then a ui-view matches if:\n * - There exists a parent ui-view where:\n * - the parent ui-view's name matches the first segment (index 0) of the ViewConfig's target name\n * - the parent ui-view's context matches the ViewConfig's anchor\n * - And the remaining segments (index 1..n) of the ViewConfig's target name match the tail of the ui-view's fqn\n *\n * Example:\n *\n * DOM:\n * \n * \n * \n * \n * \n * \n * \n * \n *\n * uiViews: [\n * { fqn: \"$default\", creationContext: { name: \"\" } },\n * { fqn: \"$default.foo\", creationContext: { name: \"A\" } },\n * { fqn: \"$default.foo.$default\", creationContext: { name: \"A.B\" } }\n * { fqn: \"$default.foo.$default.bar\", creationContext: { name: \"A.B.C\" } }\n * ]\n *\n * These four view configs all match the ui-view with the fqn: \"$default.foo.$default.bar\":\n *\n * - ViewConfig1: { uiViewName: \"bar\", uiViewContextAnchor: \"A.B.C\" }\n * - ViewConfig2: { uiViewName: \"$default.bar\", uiViewContextAnchor: \"A.B\" }\n * - ViewConfig3: { uiViewName: \"foo.$default.bar\", uiViewContextAnchor: \"A\" }\n * - ViewConfig4: { uiViewName: \"$default.foo.$default.bar\", uiViewContextAnchor: \"\" }\n *\n * Using ViewConfig3 as an example, it matches the ui-view with fqn \"$default.foo.$default.bar\" because:\n * - The ViewConfig's segmented target name is: [ \"foo\", \"$default\", \"bar\" ]\n * - There exists a parent ui-view (which has fqn: \"$default.foo\") where:\n * - the parent ui-view's name \"foo\" matches the first segment \"foo\" of the ViewConfig's target name\n * - the parent ui-view's context \"A\" matches the ViewConfig's anchor context \"A\"\n * - And the remaining segments [ \"$default\", \"bar\" ].join(\".\"_ of the ViewConfig's target name match\n * the tail of the ui-view's fqn \"default.bar\"\n *\n * @internalapi\n */\n static matches = (uiViewsByFqn: TypedMap, uiView: ActiveUIView) => (viewConfig: ViewConfig) => {\n // Don't supply an ng1 ui-view with an ng2 ViewConfig, etc\n if (uiView.$type !== viewConfig.viewDecl.$type) return false;\n\n // Split names apart from both viewConfig and uiView into segments\n const vc = viewConfig.viewDecl;\n const vcSegments = vc.$uiViewName.split('.');\n const uivSegments = uiView.fqn.split('.');\n\n // Check if the tails of the segment arrays match. ex, these arrays' tails match:\n // vc: [\"foo\", \"bar\"], uiv fqn: [\"$default\", \"foo\", \"bar\"]\n if (!equals(vcSegments, uivSegments.slice(0 - vcSegments.length)))\n return false;\n\n // Now check if the fqn ending at the first segment of the viewConfig matches the context:\n // [\"$default\", \"foo\"].join(\".\") == \"$default.foo\", does the ui-view $default.foo context match?\n const negOffset = (1 - vcSegments.length) || undefined;\n const fqnToFirstSegment = uivSegments.slice(0, negOffset).join('.');\n const uiViewContext = uiViewsByFqn[fqnToFirstSegment].creationContext;\n return vc.$uiViewContextAnchor === (uiViewContext && uiViewContext.name);\n }\n\n /**\n * Normalizes a view's name from a state.views configuration block.\n *\n * This should be used by a framework implementation to calculate the values for\n * [[_ViewDeclaration.$uiViewName]] and [[_ViewDeclaration.$uiViewContextAnchor]].\n *\n * @param context the context object (state declaration) that the view belongs to\n * @param rawViewName the name of the view, as declared in the [[StateDeclaration.views]]\n *\n * @returns the normalized uiViewName and uiViewContextAnchor that the view targets\n */\n static normalizeUIViewTarget(context: ViewContext, rawViewName = '') {\n // TODO: Validate incoming view name with a regexp to allow:\n // ex: \"view.name@foo.bar\" , \"^.^.view.name\" , \"view.name@^.^\" , \"\" ,\n // \"@\" , \"$default@^\" , \"!$default.$default\" , \"!foo.bar\"\n const viewAtContext: string[] = rawViewName.split('@');\n let uiViewName = viewAtContext[0] || '$default'; // default to unnamed view\n let uiViewContextAnchor = isString(viewAtContext[1]) ? viewAtContext[1] : '^'; // default to parent context\n\n // Handle relative view-name sugar syntax.\n // Matches rawViewName \"^.^.^.foo.bar\" into array: [\"^.^.^.foo.bar\", \"^.^.^\", \"foo.bar\"],\n const relativeViewNameSugar = /^(\\^(?:\\.\\^)*)\\.(.*$)/.exec(uiViewName);\n if (relativeViewNameSugar) {\n // Clobbers existing contextAnchor (rawViewName validation will fix this)\n uiViewContextAnchor = relativeViewNameSugar[1]; // set anchor to \"^.^.^\"\n uiViewName = relativeViewNameSugar[2]; // set view-name to \"foo.bar\"\n }\n\n if (uiViewName.charAt(0) === '!') {\n uiViewName = uiViewName.substr(1);\n uiViewContextAnchor = ''; // target absolutely from root\n }\n\n // handle parent relative targeting \"^.^.^\"\n const relativeMatch = /^(\\^(?:\\.\\^)*)$/;\n if (relativeMatch.exec(uiViewContextAnchor)) {\n const anchorState = uiViewContextAnchor.split('.')\n .reduce(((anchor, x) => anchor.parent), context);\n uiViewContextAnchor = anchorState.name;\n } else if (uiViewContextAnchor === '.') {\n uiViewContextAnchor = context.name;\n }\n\n return { uiViewName, uiViewContextAnchor };\n }\n\n constructor() { }\n\n private _rootViewContext(context?: ViewContext): ViewContext {\n return this._rootContext = context || this._rootContext;\n }\n\n private _viewConfigFactory(viewType: string, factory: ViewConfigFactory) {\n this._viewConfigFactories[viewType] = factory;\n }\n\n createViewConfig(path: PathNode[], decl: _ViewDeclaration): ViewConfig[] {\n const cfgFactory = this._viewConfigFactories[decl.$type];\n if (!cfgFactory) throw new Error('ViewService: No view config factory registered for type ' + decl.$type);\n const cfgs = cfgFactory(path, decl);\n return isArray(cfgs) ? cfgs : [cfgs];\n }\n\n /**\n * Deactivates a ViewConfig.\n *\n * This function deactivates a `ViewConfig`.\n * After calling [[sync]], it will un-pair from any `ui-view` with which it is currently paired.\n *\n * @param viewConfig The ViewConfig view to deregister.\n */\n deactivateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('<- Removing', viewConfig);\n removeFrom(this._viewConfigs, viewConfig);\n }\n\n activateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('-> Registering', viewConfig);\n this._viewConfigs.push(viewConfig);\n }\n\n\n sync() {\n const uiViewsByFqn: TypedMap =\n this._uiViews.map(uiv => [uiv.fqn, uiv]).reduce(applyPairs, {});\n\n // Return a weighted depth value for a uiView.\n // The depth is the nesting depth of ui-views (based on FQN; times 10,000)\n // plus the depth of the state that is populating the uiView\n function uiViewDepth(uiView: ActiveUIView) {\n const stateDepth = (context: ViewContext) =>\n context && context.parent ? stateDepth(context.parent) + 1 : 1;\n return (uiView.fqn.split('.').length * 10000) + stateDepth(uiView.creationContext);\n }\n\n // Return the ViewConfig's context's depth in the context tree.\n function viewConfigDepth(config: ViewConfig) {\n let context: ViewContext = config.viewDecl.$context, count = 0;\n while (++count && context.parent) context = context.parent;\n return count;\n }\n\n // Given a depth function, returns a compare function which can return either ascending or descending order\n const depthCompare = curry((depthFn, posNeg, left, right) => posNeg * (depthFn(left) - depthFn(right)));\n\n const matchingConfigPair = (uiView: ActiveUIView): ViewTuple => {\n const matchingConfigs = this._viewConfigs.filter(ViewService.matches(uiViewsByFqn, uiView));\n if (matchingConfigs.length > 1) {\n // This is OK. Child states can target a ui-view that the parent state also targets (the child wins)\n // Sort by depth and return the match from the deepest child\n // console.log(`Multiple matching view configs for ${uiView.fqn}`, matchingConfigs);\n matchingConfigs.sort(depthCompare(viewConfigDepth, -1)); // descending\n }\n return { uiView, viewConfig: matchingConfigs[0] };\n };\n\n const configureUIView = (tuple: ViewTuple) => {\n // If a parent ui-view is reconfigured, it could destroy child ui-views.\n // Before configuring a child ui-view, make sure it's still in the active uiViews array.\n if (this._uiViews.indexOf(tuple.uiView) !== -1)\n tuple.uiView.configUpdated(tuple.viewConfig);\n };\n\n // Sort views by FQN and state depth. Process uiviews nearest the root first.\n const uiViewTuples = this._uiViews.sort(depthCompare(uiViewDepth, 1)).map(matchingConfigPair);\n const matchedViewConfigs = uiViewTuples.map(tuple => tuple.viewConfig);\n const unmatchedConfigTuples = this._viewConfigs\n .filter(config => !inArray(matchedViewConfigs, config))\n .map(viewConfig => ({ uiView: undefined, viewConfig }));\n\n uiViewTuples.forEach(configureUIView);\n\n const allTuples: ViewTuple[] = uiViewTuples.concat(unmatchedConfigTuples);\n this._listeners.forEach(cb => cb(allTuples));\n trace.traceViewSync(allTuples);\n }\n\n /**\n * Registers a `ui-view` component\n *\n * When a `ui-view` component is created, it uses this method to register itself.\n * After registration the [[sync]] method is used to ensure all `ui-view` are configured with the proper [[ViewConfig]].\n *\n * Note: the `ui-view` component uses the `ViewConfig` to determine what view should be loaded inside the `ui-view`,\n * and what the view's state context is.\n *\n * Note: There is no corresponding `deregisterUIView`.\n * A `ui-view` should hang on to the return value of `registerUIView` and invoke it to deregister itself.\n *\n * @param uiView The metadata for a UIView\n * @return a de-registration function used when the view is destroyed.\n */\n registerUIView(uiView: ActiveUIView) {\n trace.traceViewServiceUIViewEvent('-> Registering', uiView);\n const uiViews = this._uiViews;\n const fqnAndTypeMatches = (uiv: ActiveUIView) => uiv.fqn === uiView.fqn && uiv.$type === uiView.$type;\n if (uiViews.filter(fqnAndTypeMatches).length)\n trace.traceViewServiceUIViewEvent('!!!! duplicate uiView named:', uiView);\n\n uiViews.push(uiView);\n this.sync();\n\n return () => {\n const idx = uiViews.indexOf(uiView);\n if (idx === -1) {\n trace.traceViewServiceUIViewEvent('Tried removing non-registered uiView', uiView);\n return;\n }\n trace.traceViewServiceUIViewEvent('<- Deregistering', uiView);\n removeFrom(uiViews)(uiView);\n };\n }\n\n /**\n * Returns the list of views currently available on the page, by fully-qualified name.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n available() {\n return this._uiViews.map(prop('fqn'));\n }\n\n /**\n * Returns the list of views on the page containing loaded content.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n active() {\n return this._uiViews.filter(prop('$config')).map(prop('name'));\n }\n\n}\n", + "/**\n * Random utility functions used in the UI-Router code\n *\n * These functions are exported, but are subject to change without notice.\n *\n * @preferred\n * @module common\n */\n/** for typedoc */\nimport { isFunction, isString, isArray, isRegExp, isDate } from './predicates';\nimport { all, any, prop, curry, not } from './hof';\nimport { services } from './coreservices';\nimport { StateObject } from '../state/stateObject';\n\ndeclare const global;\nexport const root: any =\n (typeof self === 'object' && self.self === self && self) ||\n (typeof global === 'object' && global.global === global && global) ||\n this;\nconst angular = root.angular || {};\n\nexport const fromJson = angular.fromJson || JSON.parse.bind(JSON);\nexport const toJson = angular.toJson || JSON.stringify.bind(JSON);\nexport const forEach = angular.forEach || _forEach;\nexport const extend = Object.assign || _extend;\nexport const equals = angular.equals || _equals;\nexport function identity(x: any) {\n return x;\n}\nexport function noop(): any {}\n\nexport type Mapper = (x: X, key?: string | number) => T;\nexport interface TypedMap {\n [key: string]: T;\n}\nexport type Predicate = (x?: X) => boolean;\n/**\n * An ng1-style injectable\n *\n * This could be a (non-minified) function such as:\n * ```js\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an explicitly annotated function (minify safe)\n * ```js\n * injectableFunction.$inject = [ 'SomeDependency' ];\n * function injectableFunction(SomeDependency) {\n *\n * }\n * ```\n *\n * or an array style annotated function (minify safe)\n * ```js\n * ['SomeDependency', function injectableFunction(SomeDependency) {\n *\n * }];\n * ```\n *\n * @publicapi\n */\nexport type IInjectable = Function | any[];\n\nexport interface Obj extends Object {\n [key: string]: any;\n}\n\n/**\n * Builds proxy functions on the `to` object which pass through to the `from` object.\n *\n * For each key in `fnNames`, creates a proxy function on the `to` object.\n * The proxy function calls the real function on the `from` object.\n *\n *\n * #### Example:\n * This example creates an new class instance whose functions are prebound to the new'd object.\n * ```js\n * class Foo {\n * constructor(data) {\n * // Binds all functions from Foo.prototype to 'this',\n * // then copies them to 'this'\n * bindFunctions(Foo.prototype, this, this);\n * this.data = data;\n * }\n *\n * log() {\n * console.log(this.data);\n * }\n * }\n *\n * let myFoo = new Foo([1,2,3]);\n * var logit = myFoo.log;\n * logit(); // logs [1, 2, 3] from the myFoo 'this' instance\n * ```\n *\n * #### Example:\n * This example creates a bound version of a service function, and copies it to another object\n * ```\n *\n * var SomeService = {\n * this.data = [3, 4, 5];\n * this.log = function() {\n * console.log(this.data);\n * }\n * }\n *\n * // Constructor fn\n * function OtherThing() {\n * // Binds all functions from SomeService to SomeService,\n * // then copies them to 'this'\n * bindFunctions(SomeService, this, SomeService);\n * }\n *\n * let myOtherThing = new OtherThing();\n * myOtherThing.log(); // logs [3, 4, 5] from SomeService's 'this'\n * ```\n *\n * @param source A function that returns the source object which contains the original functions to be bound\n * @param target A function that returns the target object which will receive the bound functions\n * @param bind A function that returns the object which the functions will be bound to\n * @param fnNames The function names which will be bound (Defaults to all the functions found on the 'from' object)\n * @param latebind If true, the binding of the function is delayed until the first time it's invoked\n */\nexport function createProxyFunctions(\n source: Function,\n target: Obj,\n bind: Function,\n fnNames?: string[],\n latebind = false,\n): Obj {\n const bindFunction = fnName => source()[fnName].bind(bind());\n\n const makeLateRebindFn = fnName =>\n function lateRebindFunction() {\n target[fnName] = bindFunction(fnName);\n return target[fnName].apply(null, arguments);\n };\n\n fnNames = fnNames || Object.keys(source());\n\n return fnNames.reduce((acc, name) => {\n acc[name] = latebind ? makeLateRebindFn(name) : bindFunction(name);\n return acc;\n }, target);\n}\n\n/**\n * prototypal inheritance helper.\n * Creates a new object which has `parent` object as its prototype, and then copies the properties from `extra` onto it\n */\nexport const inherit = (parent: Obj, extra?: Obj) => extend(Object.create(parent), extra);\n\n/** Given an array, returns true if the object is found in the array, (using indexOf) */\nexport const inArray: typeof _inArray = curry(_inArray) as any;\nexport function _inArray(array: any[], obj: any): boolean;\nexport function _inArray(array: any[]): (obj: any) => boolean;\nexport function _inArray(array, obj?): any {\n return array.indexOf(obj) !== -1;\n}\n\n/**\n * Given an array, and an item, if the item is found in the array, it removes it (in-place).\n * The same array is returned\n */\nexport const removeFrom: typeof _removeFrom = curry(_removeFrom) as any;\nexport function _removeFrom(array: T[], obj: T): T[];\nexport function _removeFrom(array: T[]): (obj: T) => T[];\nexport function _removeFrom(array, obj?) {\n const idx = array.indexOf(obj);\n if (idx >= 0) array.splice(idx, 1);\n return array;\n}\n\n/** pushes a values to an array and returns the value */\nexport const pushTo: typeof _pushTo = curry(_pushTo) as any;\nexport function _pushTo(arr: T[], val: T): T;\nexport function _pushTo(arr: T[]): (val: T) => T;\nexport function _pushTo(arr, val?): any {\n return arr.push(val), val;\n}\n\n/** Given an array of (deregistration) functions, calls all functions and removes each one from the source array */\nexport const deregAll = (functions: Function[]) =>\n functions.slice().forEach(fn => {\n typeof fn === 'function' && fn();\n removeFrom(functions, fn);\n });\n/**\n * Applies a set of defaults to an options object. The options object is filtered\n * to only those properties of the objects in the defaultsList.\n * Earlier objects in the defaultsList take precedence when applying defaults.\n */\nexport function defaults(opts, ...defaultsList: Obj[]) {\n const _defaultsList = defaultsList.concat({}).reverse();\n const defaultVals = extend.apply(null, _defaultsList);\n return extend({}, defaultVals, pick(opts || {}, Object.keys(defaultVals)));\n}\n\n/** Reduce function that merges each element of the list into a single object, using extend */\nexport const mergeR = (memo: Obj, item: Obj) => extend(memo, item);\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nexport function ancestors(first: StateObject, second: StateObject) {\n const path: StateObject[] = [];\n\n // tslint:disable-next-line:forin\n for (const n in first.path) {\n if (first.path[n] !== second.path[n]) break;\n path.push(first.path[n]);\n }\n return path;\n}\n\n/**\n * Return a copy of the object only containing the whitelisted properties.\n *\n * #### Example:\n * ```\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = pick(foo, ['a', 'b']); // { a: 1, b: 2 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the whitelisted property names\n */\nexport function pick(obj: Obj, propNames: string[]): Obj {\n const objCopy = {};\n for (const _prop in obj) {\n if (propNames.indexOf(_prop) !== -1) {\n objCopy[_prop] = obj[_prop];\n }\n }\n return objCopy;\n}\n\n/**\n * Return a copy of the object omitting the blacklisted properties.\n *\n * @example\n * ```\n *\n * var foo = { a: 1, b: 2, c: 3 };\n * var ab = omit(foo, ['a', 'b']); // { c: 3 }\n * ```\n * @param obj the source object\n * @param propNames an Array of strings, which are the blacklisted property names\n */\nexport function omit(obj: Obj, propNames: string[]): Obj {\n return Object.keys(obj)\n .filter(not(inArray(propNames)))\n .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});\n}\n\n/** Given an array of objects, maps each element to a named property of the element. */\nexport function pluck(collection: Obj[], propName: string): T[];\n/** Given an object, maps each property of the object to a named property of the property. */\nexport function pluck(collection: { [key: string]: any }, propName: string): { [key: string]: any };\n/**\n * Maps an array, or object to a property (by name)\n */\nexport function pluck(collection: any, propName: string): any {\n return map(collection, >prop(propName));\n}\n\n/** Given an array of objects, returns a new array containing only the elements which passed the callback predicate */\nexport function filter(collection: T[], callback: (t: T, key?: number) => boolean): T[];\n/** Given an object, returns a new object with only those properties that passed the callback predicate */\nexport function filter(collection: TypedMap, callback: (t: T, key?: string) => boolean): TypedMap;\n/** Filters an Array or an Object's properties based on a predicate */\nexport function filter(collection: any, callback: Function): T {\n const arr = isArray(collection),\n result: any = arr ? [] : {};\n const accept = arr ? x => result.push(x) : (x, key) => (result[key] = x);\n forEach(collection, function(item, i) {\n if (callback(item, i)) accept(item, i);\n });\n return result;\n}\n\n/** Given an object, return the first property of that object which passed the callback predicate */\nexport function find(collection: TypedMap, callback: Predicate): T;\n/** Given an array of objects, returns the first object which passed the callback predicate */\nexport function find(collection: T[], callback: Predicate): T;\n/** Finds an object from an array, or a property of an object, that matches a predicate */\nexport function find(collection: any, callback: any) {\n let result;\n\n forEach(collection, function(item, i) {\n if (result) return;\n if (callback(item, i)) result = item;\n });\n\n return result;\n}\n\n/** Given an object, returns a new object, where each property is transformed by the callback function */\nexport let mapObj: (\n collection: { [key: string]: T },\n callback: Mapper,\n target?: typeof collection,\n) => { [key: string]: U } = map;\n/** Given an array, returns a new array, where each element is transformed by the callback function */\nexport function map(collection: T[], callback: Mapper, target?: typeof collection): U[];\nexport function map(\n collection: { [key: string]: T },\n callback: Mapper,\n target?: typeof collection,\n): { [key: string]: U };\n/** Maps an array or object properties using a callback function */\nexport function map(collection: any, callback: any, target: typeof collection): any {\n target = target || (isArray(collection) ? [] : {});\n forEach(collection, (item, i) => (target[i] = callback(item, i)));\n return target;\n}\n\n/**\n * Given an object, return its enumerable property values\n *\n * @example\n * ```\n *\n * let foo = { a: 1, b: 2, c: 3 }\n * let vals = values(foo); // [ 1, 2, 3 ]\n * ```\n */\nexport const values: ((obj: TypedMap) => T[]) = (obj: Obj) => Object.keys(obj).map(key => obj[key]);\n\n/**\n * Reduce function that returns true if all of the values are truthy.\n *\n * @example\n * ```\n *\n * let vals = [ 1, true, {}, \"hello world\"];\n * vals.reduce(allTrueR, true); // true\n *\n * vals.push(0);\n * vals.reduce(allTrueR, true); // false\n * ```\n */\nexport const allTrueR = (memo: boolean, elem: any) => memo && elem;\n\n/**\n * Reduce function that returns true if any of the values are truthy.\n *\n * * @example\n * ```\n *\n * let vals = [ 0, null, undefined ];\n * vals.reduce(anyTrueR, true); // false\n *\n * vals.push(\"hello world\");\n * vals.reduce(anyTrueR, true); // true\n * ```\n */\nexport const anyTrueR = (memo: boolean, elem: any) => memo || elem;\n\n/**\n * Reduce function which un-nests a single level of arrays\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnestR = (memo: any[], elem: any[]) => memo.concat(elem);\n\n/**\n * Reduce function which recursively un-nests all arrays\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * input.reduce(unnestR, []) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flattenR = (memo: any[], elem: any) =>\n isArray(elem) ? memo.concat(elem.reduce(flattenR, [])) : pushR(memo, elem);\n\n/**\n * Reduce function that pushes an object to an array, then returns the array.\n * Mostly just for [[flattenR]] and [[uniqR]]\n */\nexport function pushR(arr: any[], obj: any) {\n arr.push(obj);\n return arr;\n}\n\n/** Reduce function that filters out duplicates */\nexport const uniqR = (acc: T[], token: T): T[] => (inArray(acc, token) ? acc : pushR(acc, token));\n\n/**\n * Return a new array with a single level of arrays unnested.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * unnest(input) // [ \"a\", \"b\", \"c\", \"d\", [ \"double, \"nested\" ] ]\n * ```\n */\nexport const unnest = (arr: any[]) => arr.reduce(unnestR, []);\n/**\n * Return a completely flattened version of an array.\n *\n * @example\n * ```\n *\n * let input = [ [ \"a\", \"b\" ], [ \"c\", \"d\" ], [ [ \"double\", \"nested\" ] ] ];\n * flatten(input) // [ \"a\", \"b\", \"c\", \"d\", \"double, \"nested\" ]\n * ```\n */\nexport const flatten = (arr: any[]) => arr.reduce(flattenR, []);\n\n/**\n * Given a .filter Predicate, builds a .filter Predicate which throws an error if any elements do not pass.\n * @example\n * ```\n *\n * let isNumber = (obj) => typeof(obj) === 'number';\n * let allNumbers = [ 1, 2, 3, 4, 5 ];\n * allNumbers.filter(assertPredicate(isNumber)); //OK\n *\n * let oneString = [ 1, 2, 3, 4, \"5\" ];\n * oneString.filter(assertPredicate(isNumber, \"Not all numbers\")); // throws Error(\"\"Not all numbers\"\");\n * ```\n */\nexport const assertPredicate: (predicate: Predicate, errMsg: string | Function) => Predicate = assertFn;\n/**\n * Given a .map function, builds a .map function which throws an error if any mapped elements do not pass a truthyness test.\n * @example\n * ```\n *\n * var data = { foo: 1, bar: 2 };\n *\n * let keys = [ 'foo', 'bar' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // values is [1, 2]\n *\n * let keys = [ 'foo', 'bar', 'baz' ]\n * let values = keys.map(assertMap(key => data[key], \"Key not found\"));\n * // throws Error(\"Key not found\")\n * ```\n */\nexport const assertMap: (mapFn: (t: T) => U, errMsg: string | Function) => (t: T) => U = assertFn;\nexport function assertFn(predicateOrMap: Function, errMsg: string | Function = 'assert failure'): any {\n return obj => {\n const result = predicateOrMap(obj);\n if (!result) {\n throw new Error(isFunction(errMsg) ? (errMsg)(obj) : errMsg);\n }\n return result;\n };\n}\n\n/**\n * Like _.pairs: Given an object, returns an array of key/value pairs\n *\n * @example\n * ```\n *\n * pairs({ foo: \"FOO\", bar: \"BAR }) // [ [ \"foo\", \"FOO\" ], [ \"bar\": \"BAR\" ] ]\n * ```\n */\nexport const pairs = (obj: Obj) => Object.keys(obj).map(key => [key, obj[key]]);\n\n/**\n * Given two or more parallel arrays, returns an array of tuples where\n * each tuple is composed of [ a[i], b[i], ... z[i] ]\n *\n * @example\n * ```\n *\n * let foo = [ 0, 2, 4, 6 ];\n * let bar = [ 1, 3, 5, 7 ];\n * let baz = [ 10, 30, 50, 70 ];\n * arrayTuples(foo, bar); // [ [0, 1], [2, 3], [4, 5], [6, 7] ]\n * arrayTuples(foo, bar, baz); // [ [0, 1, 10], [2, 3, 30], [4, 5, 50], [6, 7, 70] ]\n * ```\n */\nexport function arrayTuples(...args: any[]): any[] {\n if (args.length === 0) return [];\n const maxArrayLen = args.reduce((min, arr) => Math.min(arr.length, min), 9007199254740991); // aka 2^53 − 1 aka Number.MAX_SAFE_INTEGER\n const result = [];\n\n for (let i = 0; i < maxArrayLen; i++) {\n // This is a hot function\n // Unroll when there are 1-4 arguments\n switch (args.length) {\n case 1:\n result.push([args[0][i]]);\n break;\n case 2:\n result.push([args[0][i], args[1][i]]);\n break;\n case 3:\n result.push([args[0][i], args[1][i], args[2][i]]);\n break;\n case 4:\n result.push([args[0][i], args[1][i], args[2][i], args[3][i]]);\n break;\n default:\n result.push(args.map(array => array[i]));\n break;\n }\n }\n\n return result;\n}\n\n/**\n * Reduce function which builds an object from an array of [key, value] pairs.\n *\n * Each iteration sets the key/val pair on the memo object, then returns the memo for the next iteration.\n *\n * Each keyValueTuple should be an array with values [ key: string, value: any ]\n *\n * @example\n * ```\n *\n * var pairs = [ [\"fookey\", \"fooval\"], [\"barkey\", \"barval\"] ]\n *\n * var pairsToObj = pairs.reduce((memo, pair) => applyPairs(memo, pair), {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n *\n * // Or, more simply:\n * var pairsToObj = pairs.reduce(applyPairs, {})\n * // pairsToObj == { fookey: \"fooval\", barkey: \"barval\" }\n * ```\n */\nexport function applyPairs(memo: TypedMap, keyValTuple: any[]) {\n let key: string, value: any;\n if (isArray(keyValTuple)) [key, value] = keyValTuple;\n if (!isString(key)) throw new Error('invalid parameters to applyPairs');\n memo[key] = value;\n return memo;\n}\n\n/** Get the last element of an array */\nexport function tail(arr: T[]): T {\n return (arr.length && arr[arr.length - 1]) || undefined;\n}\n\n/**\n * shallow copy from src to dest\n */\nexport function copy(src: Obj, dest?: Obj) {\n if (dest) Object.keys(dest).forEach(key => delete dest[key]);\n if (!dest) dest = {};\n return extend(dest, src);\n}\n\n/** Naive forEach implementation works with Objects or Arrays */\nfunction _forEach(obj: any[] | any, cb: (el, idx?) => void, _this: Obj) {\n if (isArray(obj)) return obj.forEach(cb, _this);\n Object.keys(obj).forEach(key => cb(obj[key], key));\n}\n\n/** Like Object.assign() */\nexport function _extend(toObj: Obj, ...fromObjs: Obj[]): any;\nexport function _extend(toObj: Obj): any {\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n if (!obj) continue;\n const keys = Object.keys(obj);\n\n for (let j = 0; j < keys.length; j++) {\n toObj[keys[j]] = obj[keys[j]];\n }\n }\n\n return toObj;\n}\n\nfunction _equals(o1: any, o2: any): boolean {\n if (o1 === o2) return true;\n if (o1 === null || o2 === null) return false;\n if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n const t1 = typeof o1,\n t2 = typeof o2;\n if (t1 !== t2 || t1 !== 'object') return false;\n\n const tup = [o1, o2];\n if (all(isArray)(tup)) return _arraysEq(o1, o2);\n if (all(isDate)(tup)) return o1.getTime() === o2.getTime();\n if (all(isRegExp)(tup)) return o1.toString() === o2.toString();\n if (all(isFunction)(tup)) return true; // meh\n\n const predicates = [isFunction, isArray, isDate, isRegExp];\n if (predicates.map(any).reduce((b, fn) => b || !!fn(tup), false)) return false;\n\n const keys: { [i: string]: boolean } = {};\n // tslint:disable-next-line:forin\n for (const key in o1) {\n if (!_equals(o1[key], o2[key])) return false;\n keys[key] = true;\n }\n for (const key in o2) {\n if (!keys[key]) return false;\n }\n\n return true;\n}\n\nfunction _arraysEq(a1: any[], a2: any[]) {\n if (a1.length !== a2.length) return false;\n return arrayTuples(a1, a2).reduce((b, t) => b && _equals(t[0], t[1]), true);\n}\n\n// issue #2676\nexport const silenceUncaughtInPromise = (promise: Promise) => promise.catch(e => 0) && promise;\nexport const silentRejection = (error: any) => silenceUncaughtInPromise(services.$q.reject(error));\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n'use strict';\nimport { extend, silentRejection } from '../common/common';\nimport { stringify } from '../common/strings';\nimport { is } from '../common/hof';\n\nenum RejectType {\n /**\n * A new transition superseded this one.\n *\n * While this transition was running, a new transition started.\n * This transition is cancelled because it was superseded by new transition.\n */\n SUPERSEDED = 2,\n\n /**\n * The transition was aborted\n *\n * The transition was aborted by a hook which returned `false`\n */\n ABORTED = 3,\n\n /**\n * The transition was invalid\n *\n * The transition was never started because it was invalid\n */\n INVALID = 4,\n\n /**\n * The transition was ignored\n *\n * The transition was ignored because it would have no effect.\n *\n * Either:\n *\n * - The transition is targeting the current state and parameter values\n * - The transition is targeting the same state and parameter values as the currently running transition.\n */\n IGNORED = 5,\n\n /**\n * The transition errored.\n *\n * This generally means a hook threw an error or returned a rejected promise\n */\n ERROR = 6,\n}\n\nexport { RejectType };\n\n/** @hidden */\nlet id = 0;\n\nexport class Rejection {\n /** @hidden */\n $id = id++;\n /**\n * The type of the rejection.\n *\n * This value is an number representing the type of transition rejection.\n * If using Typescript, this is a Typescript enum.\n *\n * - [[RejectType.SUPERSEDED]] (`2`)\n * - [[RejectType.ABORTED]] (`3`)\n * - [[RejectType.INVALID]] (`4`)\n * - [[RejectType.IGNORED]] (`5`)\n * - [[RejectType.ERROR]] (`6`)\n *\n */\n type: RejectType;\n\n /**\n * A message describing the rejection\n */\n message: string;\n\n /**\n * A detail object\n *\n * This value varies based on the mechanism for rejecting the transition.\n * For example, if an error was thrown from a hook, the `detail` will be the `Error` object.\n * If a hook returned a rejected promise, the `detail` will be the rejected value.\n */\n detail: any;\n\n /**\n * Indicates if the transition was redirected.\n *\n * When a transition is redirected, the rejection [[type]] will be [[RejectType.SUPERSEDED]] and this flag will be true.\n */\n redirected: boolean;\n\n /** Returns true if the obj is a rejected promise created from the `asPromise` factory */\n static isRejectionPromise(obj: any): boolean {\n return obj && typeof obj.then === 'function' && is(Rejection)(obj._transitionRejection);\n }\n\n /** Returns a Rejection due to transition superseded */\n static superseded(detail?: any, options?: any): Rejection {\n const message = 'The transition has been superseded by a different transition';\n const rejection = new Rejection(RejectType.SUPERSEDED, message, detail);\n if (options && options.redirected) {\n rejection.redirected = true;\n }\n return rejection;\n }\n\n /** Returns a Rejection due to redirected transition */\n static redirected(detail?: any): Rejection {\n return Rejection.superseded(detail, { redirected: true });\n }\n\n /** Returns a Rejection due to invalid transition */\n static invalid(detail?: any): Rejection {\n const message = 'This transition is invalid';\n return new Rejection(RejectType.INVALID, message, detail);\n }\n\n /** Returns a Rejection due to ignored transition */\n static ignored(detail?: any): Rejection {\n const message = 'The transition was ignored';\n return new Rejection(RejectType.IGNORED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static aborted(detail?: any): Rejection {\n const message = 'The transition has been aborted';\n return new Rejection(RejectType.ABORTED, message, detail);\n }\n\n /** Returns a Rejection due to aborted transition */\n static errored(detail?: any): Rejection {\n const message = 'The transition errored';\n return new Rejection(RejectType.ERROR, message, detail);\n }\n\n /**\n * Returns a Rejection\n *\n * Normalizes a value as a Rejection.\n * If the value is already a Rejection, returns it.\n * Otherwise, wraps and returns the value as a Rejection (Rejection type: ERROR).\n *\n * @returns `detail` if it is already a `Rejection`, else returns an ERROR Rejection.\n */\n static normalize(detail?: Rejection | Error | any): Rejection {\n return is(Rejection)(detail) ? detail : Rejection.errored(detail);\n }\n\n constructor(type: number, message?: string, detail?: any) {\n this.type = type;\n this.message = message;\n this.detail = detail;\n }\n\n toString() {\n const detailString = (d: any) => (d && d.toString !== Object.prototype.toString ? d.toString() : stringify(d));\n const detail = detailString(this.detail);\n const { $id, type, message } = this;\n return `Transition Rejection($id: ${$id} type: ${type}, message: ${message}, detail: ${detail})`;\n }\n\n toPromise(): Promise {\n return extend(silentRejection(this), { _transitionRejection: this });\n }\n}\n", + "/** @module common */\nimport { pushTo } from './common';\n\nexport class Queue {\n private _evictListeners: ((item: T) => void)[] = [];\n public onEvict = pushTo(this._evictListeners);\n\n constructor(private _items: T[] = [], private _limit: number = null) {}\n\n enqueue(item: T) {\n const items = this._items;\n items.push(item);\n if (this._limit && items.length > this._limit) this.evict();\n return item;\n }\n\n evict(): T {\n const item: T = this._items.shift();\n this._evictListeners.forEach(fn => fn(item));\n return item;\n }\n\n dequeue(): T {\n if (this.size()) return this._items.splice(0, 1)[0];\n }\n\n clear(): Array {\n const current = this._items;\n this._items = [];\n return current;\n }\n\n size(): number {\n return this._items.length;\n }\n\n remove(item: T) {\n const idx = this._items.indexOf(item);\n return idx > -1 && this._items.splice(idx, 1)[0];\n }\n\n peekTail(): T {\n return this._items[this._items.length - 1];\n }\n\n peekHead(): T {\n if (this.size()) return this._items[0];\n }\n}\n", + "/**\n * # Transition tracing (debug)\n *\n * Enable transition tracing to print transition information to the console,\n * in order to help debug your application.\n * Tracing logs detailed information about each Transition to your console.\n *\n * To enable tracing, import the [[Trace]] singleton and enable one or more categories.\n *\n * ### ES6\n * ```js\n * import {trace} from \"@uirouter/core\";\n * trace.enable(1, 5); // TRANSITION and VIEWCONFIG\n * ```\n *\n * ### CJS\n * ```js\n * let trace = require(\"@uirouter/core\").trace;\n * trace.enable(\"TRANSITION\", \"VIEWCONFIG\");\n * ```\n *\n * ### Globals\n * ```js\n * let trace = window[\"@uirouter/core\"].trace;\n * trace.enable(); // Trace everything (very verbose)\n * ```\n *\n * ### Angular 1:\n * ```js\n * app.run($trace => $trace.enable());\n * ```\n *\n * @coreapi\n * @module trace\n */\n/* tslint:disable:no-console */\nimport { parse } from '../common/hof';\nimport { isFunction, isNumber } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { ViewTuple } from '../view';\nimport { ActiveUIView, ViewConfig, ViewContext } from '../view/interface';\nimport { stringify, functionToString, maxLength, padString } from './strings';\nimport { Resolvable } from '../resolve/resolvable';\nimport { PathNode } from '../path/pathNode';\nimport { PolicyWhen } from '../resolve/interface';\nimport { TransitionHook } from '../transition/transitionHook';\nimport { HookResult } from '../transition/interface';\nimport { StateObject } from '../state/stateObject';\n\n/** @hidden */\nfunction uiViewString(uiview: ActiveUIView) {\n if (!uiview) return 'ui-view (defunct)';\n const state = uiview.creationContext ? uiview.creationContext.name || '(root)' : '(none)';\n return `[ui-view#${uiview.id} ${uiview.$type}:${uiview.fqn} (${uiview.name}@${state})]`;\n}\n\n/** @hidden */\nconst viewConfigString = (viewConfig: ViewConfig) => {\n const view = viewConfig.viewDecl;\n const state = view.$context.name || '(root)';\n return `[View#${viewConfig.$id} from '${state}' state]: target ui-view: '${view.$uiViewName}@${\n view.$uiViewContextAnchor\n }'`;\n};\n\n/** @hidden */\nfunction normalizedCat(input: Category | string): string {\n return isNumber(input) ? Category[input] : Category[Category[input]];\n}\n\n/** @hidden */\nconst consoleLog = Function.prototype.bind.call(console.log, console);\n\n/** @hidden */\nconst consoletable = isFunction(console.table) ? console.table.bind(console) : consoleLog.bind(console);\n\n/**\n * Trace categories Enum\n *\n * Enable or disable a category using [[Trace.enable]] or [[Trace.disable]]\n *\n * `trace.enable(Category.TRANSITION)`\n *\n * These can also be provided using a matching string, or position ordinal\n *\n * `trace.enable(\"TRANSITION\")`\n *\n * `trace.enable(1)`\n */\nenum Category {\n RESOLVE,\n TRANSITION,\n HOOK,\n UIVIEW,\n VIEWCONFIG,\n}\n\nexport { Category };\n\n/** @hidden */\nconst _tid = parse('$id');\n\n/** @hidden */\nconst _rid = parse('router.$id');\n\n/** @hidden */\nconst transLbl = trans => `Transition #${_tid(trans)}-${_rid(trans)}`;\n\n/**\n * Prints UI-Router Transition trace information to the console.\n */\nexport class Trace {\n /** @hidden */\n approximateDigests: number;\n\n /** @hidden */\n private _enabled: { [key: string]: boolean } = {};\n\n /** @hidden */\n constructor() {\n this.approximateDigests = 0;\n }\n\n /** @hidden */\n private _set(enabled: boolean, categories: Category[]) {\n if (!categories.length) {\n categories = Object.keys(Category)\n .map(k => parseInt(k, 10))\n .filter(k => !isNaN(k))\n .map(key => Category[key]);\n }\n categories.map(normalizedCat).forEach(category => (this._enabled[category] = enabled));\n }\n\n /**\n * Enables a trace [[Category]]\n *\n * ```js\n * trace.enable(\"TRANSITION\");\n * ```\n *\n * @param categories categories to enable. If `categories` is omitted, all categories are enabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n enable(...categories: (Category | string | number)[]);\n enable(...categories: any[]) {\n this._set(true, categories);\n }\n /**\n * Disables a trace [[Category]]\n *\n * ```js\n * trace.disable(\"VIEWCONFIG\");\n * ```\n *\n * @param categories categories to disable. If `categories` is omitted, all categories are disabled.\n * Also takes strings (category name) or ordinal (category position)\n */\n disable(...categories: (Category | string | number)[]);\n disable(...categories: any[]) {\n this._set(false, categories);\n }\n\n /**\n * Retrieves the enabled stateus of a [[Category]]\n *\n * ```js\n * trace.enabled(\"VIEWCONFIG\"); // true or false\n * ```\n *\n * @returns boolean true if the category is enabled\n */\n enabled(category: Category | string | number): boolean {\n return !!this._enabled[normalizedCat(category)];\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionStart(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Started -> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceTransitionIgnored(trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: Ignored <> ${stringify(trans)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookInvocation(step: TransitionHook, trans: Transition, options: any) {\n if (!this.enabled(Category.HOOK)) return;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = functionToString((step as any).registeredHook.callback);\n console.log(`${transLbl(trans)}: Hook -> ${event} context: ${context}, ${maxLength(200, name)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceHookResult(hookResult: HookResult, trans: Transition, transitionOptions: any) {\n if (!this.enabled(Category.HOOK)) return;\n console.log(`${transLbl(trans)}: <- Hook returned: ${maxLength(200, stringify(hookResult))}`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvePath(path: PathNode[], when: PolicyWhen, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(`${transLbl(trans)}: Resolving ${path} (${when})`);\n }\n\n /** @internalapi called by ui-router code */\n traceResolvableResolved(resolvable: Resolvable, trans?: Transition) {\n if (!this.enabled(Category.RESOLVE)) return;\n console.log(\n `${transLbl(trans)}: <- Resolved ${resolvable} to: ${maxLength(200, stringify(resolvable.data))}`,\n );\n }\n\n /** @internalapi called by ui-router code */\n traceError(reason: any, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Rejected ${stringify(trans)}, reason: ${reason}`);\n }\n\n /** @internalapi called by ui-router code */\n traceSuccess(finalState: StateObject, trans: Transition) {\n if (!this.enabled(Category.TRANSITION)) return;\n console.log(`${transLbl(trans)}: <- Success ${stringify(trans)}, final state: ${finalState.name}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewEvent(event: string, viewData: ActiveUIView, extra = '') {\n if (!this.enabled(Category.UIVIEW)) return;\n console.log(`ui-view: ${padString(30, event)} ${uiViewString(viewData)}${extra}`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewConfigUpdated(viewData: ActiveUIView, context: ViewContext) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Updating', viewData, ` with ViewConfig from context='${context}'`);\n }\n\n /** @internalapi called by ui-router code */\n traceUIViewFill(viewData: ActiveUIView, html: string) {\n if (!this.enabled(Category.UIVIEW)) return;\n this.traceUIViewEvent('Fill', viewData, ` with: ${maxLength(200, html)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewSync(pairs: ViewTuple[]) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n const uivheader = 'uiview component fqn';\n const cfgheader = 'view config state (view name)';\n const mapping = pairs\n .map(({ uiView, viewConfig }) => {\n const uiv = uiView && uiView.fqn;\n const cfg = viewConfig && `${viewConfig.viewDecl.$context.name}: (${viewConfig.viewDecl.$name})`;\n return { [uivheader]: uiv, [cfgheader]: cfg };\n })\n .sort((a, b) => (a[uivheader] || '').localeCompare(b[uivheader] || ''));\n\n consoletable(mapping);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceEvent(event: string, viewConfig: ViewConfig) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${viewConfigString(viewConfig)}`);\n }\n\n /** @internalapi called by ui-router code */\n traceViewServiceUIViewEvent(event: string, viewData: ActiveUIView) {\n if (!this.enabled(Category.VIEWCONFIG)) return;\n console.log(`VIEWCONFIG: ${event} ${uiViewString(viewData)}`);\n }\n}\n\n/**\n * The [[Trace]] singleton\n *\n * #### Example:\n * ```js\n * import {trace} from \"@uirouter/core\";\n * trace.enable(1, 5);\n * ```\n */\nconst trace = new Trace();\nexport { trace };\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { StateDeclaration } from '../state/interface';\nimport { Predicate } from '../common/common';\n\nimport { Transition } from './transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TargetState } from '../state/targetState';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * The TransitionOptions object can be used to change the behavior of a transition.\n *\n * It is passed as the third argument to [[StateService.go]], [[StateService.transitionTo]].\n * It can also be used with a `uiSref`.\n */\nexport interface TransitionOptions {\n /**\n * This option changes how the Transition interacts with the browser's location bar (URL).\n *\n * - If `true`, it will update the url in the location bar.\n * - If `false`, it will not update the url in the location bar.\n * - If it is the string `\"replace\"`, it will update the url and also replace the last history record.\n *\n * @default `true`\n */\n location?: boolean | string;\n\n /**\n * When transitioning to relative path (e.g '`^`'), this option defines which state to be relative from.\n * @default `$state.current`\n */\n relative?: string | StateDeclaration | StateObject;\n\n /**\n * This option sets whether or not the transition's parameter values should be inherited from\n * the current parameter values.\n *\n * - If `true`, it will inherit parameter values from the current parameter values.\n * - If `false`, only the parameters which are provided to `transitionTo` will be used.\n *\n * @default `false`\n */\n inherit?: boolean;\n\n /**\n * @deprecated\n */\n notify?: boolean;\n\n /**\n * This option may be used to force states which are currently active to reload.\n *\n * During a normal transition, a state is \"retained\" if:\n * - It was previously active\n * - The state's parameter values have not changed\n * - All the parent states' parameter values have not changed\n *\n * Forcing a reload of a state will cause it to be exited and entered, which will:\n * - Refetch that state's resolve data\n * - Exit the state (onExit hook)\n * - Re-enter the state (onEnter hook)\n * - Re-render the views (controllers and templates)\n *\n * - When `true`, the destination state (and all parent states) will be reloaded.\n * - When it is a string and is the name of a state, or when it is a State object,\n * that state and any children states will be reloaded.\n *\n * @default `false`\n */\n reload?: boolean | string | StateDeclaration | StateObject;\n /**\n * You can define your own Transition Options inside this property and use them, e.g., from a Transition Hook\n */\n custom?: any;\n /** @internalapi */\n reloadState?: StateObject;\n /** @internalapi\n * If this transition is a redirect, this property should be the original Transition (which was redirected to this one)\n */\n redirectedFrom?: Transition;\n /** @internalapi */\n current?: () => Transition;\n /** @internalapi */\n source?: 'sref' | 'url' | 'redirect' | 'otherwise' | 'unknown';\n}\n\n/** @internalapi */\nexport interface TransitionHookOptions {\n current?: () => Transition; // path?\n transition?: Transition;\n hookType?: string;\n target?: any;\n traceData?: any;\n bind?: any;\n stateHook?: boolean;\n}\n\n/**\n * TreeChanges encapsulates the various Paths that are involved in a Transition.\n *\n * Get a TreeChanges object using [[Transition.treeChanges]]\n *\n * A UI-Router Transition is from one Path in a State Tree to another Path. For a given Transition,\n * this object stores the \"to\" and \"from\" paths, as well as subsets of those: the \"retained\",\n * \"exiting\" and \"entering\" paths.\n *\n * Each path in TreeChanges is an array of [[PathNode]] objects. Each PathNode in the array corresponds to a portion\n * of a nested state.\n *\n * For example, if you had a nested state named `foo.bar.baz`, it would have three\n * portions, `foo, bar, baz`. If you transitioned **to** `foo.bar.baz` and inspected the [[TreeChanges.to]]\n * Path, you would find a node in the array for each portion: `foo`, `bar`, and `baz`.\n *\n * ---\n *\n * @todo show visual state tree\n */\nexport interface TreeChanges {\n /** @nodoc */\n [key: string]: PathNode[];\n\n /** The path of nodes in the state tree that the transition is coming *from* */\n from: PathNode[];\n\n /** The path of nodes in the state tree that the transition is going *to* */\n to: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n */\n retained: PathNode[];\n\n /**\n * The path of active nodes that the transition is retaining with updated \"to params\" applied.\n *\n * These nodes are neither exited, nor entered.\n * Before and after the transition is successful, these nodes are active.\n *\n * This is a shallow copy of [[retained]], but with new (dynamic) parameter values from [[to]] applied.\n */\n retainedWithToParams: PathNode[];\n\n /**\n * The path of previously active nodes that the transition is exiting.\n *\n * After the Transition is successful, these nodes are no longer active.\n *\n * Note that a state that is being reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n exiting: PathNode[];\n\n /**\n * The path of nodes that the transition is entering.\n *\n * After the Transition is successful, these nodes will be active.\n * Because they are entering, they have their resolves fetched, `onEnter` hooks run, and their views\n * (component(s) or controller(s)+template(s)) refreshed.\n *\n * Note that a state that is reloaded (due to parameter values changing, or `reload: true`) may be in both the\n * `exiting` and `entering` paths.\n */\n entering: PathNode[];\n}\n\nexport type IHookRegistration = (\n matchCriteria: HookMatchCriteria,\n callback: HookFn,\n options?: HookRegOptions,\n) => Function;\n\n/**\n * The signature for Transition Hooks.\n *\n * Transition hooks are callback functions that hook into the lifecycle of transitions.\n * As a transition runs, it reaches certain lifecycle events.\n * As each event occurs, the hooks which are registered for the event are called (in priority order).\n *\n * A transition hook may alter a Transition by returning a [[HookResult]].\n *\n * #### See:\n *\n * - [[IHookRegistry.onBefore]]\n * - [[IHookRegistry.onStart]]\n * - [[IHookRegistry.onFinish]]\n * - [[IHookRegistry.onSuccess]]\n * - [[IHookRegistry.onError]]\n *\n * @param transition the current [[Transition]]\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n *\n */\nexport interface TransitionHookFn {\n (transition: Transition): HookResult;\n}\n\n/**\n * The signature for Transition State Hooks.\n *\n * A function which hooks into a lifecycle event for a specific state.\n *\n * Transition State Hooks are callback functions that hook into the lifecycle events of specific states during a transition.\n * As a transition runs, it may exit some states, retain (keep) states, and enter states.\n * As each lifecycle event occurs, the hooks which are registered for the event and that state are called (in priority order).\n *\n * #### See:\n *\n * - [[IHookRegistry.onExit]]\n * - [[IHookRegistry.onRetain]]\n * - [[IHookRegistry.onEnter]]\n *\n * @param transition the current [[Transition]]\n * @param state the [[StateObject]] that the hook is bound to\n * @param injector (for ng1 or ng2 only) the injector service\n *\n * @returns a [[HookResult]] which may alter the transition\n */\nexport interface TransitionStateHookFn {\n (transition: Transition, state: StateDeclaration): HookResult;\n}\n\n/**\n * The signature for Transition onCreate Hooks.\n *\n * Transition onCreate Hooks are callbacks that allow customization or preprocessing of\n * a Transition before it is returned from [[TransitionService.create]]\n *\n * @param transition the [[Transition]] that was just created\n * @return a [[Transition]] which will then be returned from [[TransitionService.create]]\n */\nexport interface TransitionCreateHookFn {\n (transition: Transition): void;\n}\n\nexport type HookFn = TransitionHookFn | TransitionStateHookFn | TransitionCreateHookFn;\n\n/**\n * The return value of a [[TransitionHookFn]] or [[TransitionStateHookFn]]\n *\n * When returned from a [[TransitionHookFn]] or [[TransitionStateHookFn]], these values alter the running [[Transition]]:\n *\n * - `false`: the transition will be cancelled.\n * - [[TargetState]]: the transition will be redirected to the new target state (see: [[StateService.target]])\n * - `Promise`: the transition will wait for the promise to resolve or reject\n * - If the promise is rejected (or resolves to `false`), the transition will be cancelled\n * - If the promise resolves to a [[TargetState]], the transition will be redirected\n * - If the promise resolves to anything else, the transition will resume\n * - Anything else: the transition will resume\n */\nexport type HookResult = boolean | TargetState | void | Promise;\n\n/**\n * These options may be provided when registering a Transition Hook (such as `onStart`)\n */\nexport interface HookRegOptions {\n /**\n * Sets the priority of the registered hook\n *\n * Hooks of the same type (onBefore, onStart, etc) are invoked in priority order. A hook with a higher priority\n * is invoked before a hook with a lower priority.\n *\n * The default hook priority is 0\n */\n priority?: number;\n\n /**\n * Specifies what `this` is bound to during hook invocation.\n */\n bind?: any;\n\n /**\n * Limits the number of times that the hook will be invoked.\n * Once the hook has been invoked this many times, it is automatically deregistered.\n */\n invokeLimit?: number;\n}\n\n/**\n * This interface specifies the api for registering Transition Hooks. Both the\n * [[TransitionService]] and also the [[Transition]] object itself implement this interface.\n * Note: the Transition object only allows hooks to be registered before the Transition is started.\n */\nexport interface IHookRegistry {\n /** @hidden place to store the hooks */\n _registeredHooks: { [key: string]: RegisteredHook[] };\n\n /**\n * Registers a [[TransitionHookFn]], called *before a transition starts*.\n *\n * Registers a transition lifecycle hook, which is invoked before a transition even begins.\n * This hook can be useful to implement logic which prevents a transition from even starting, such\n * as authentication, redirection\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onBefore` hooks are invoked *before a Transition starts*.\n * No resolves have been fetched yet.\n * Each `onBefore` hook is invoked synchronously, in the same call stack as [[StateService.transitionTo]].\n * The registered `onBefore` hooks are invoked in priority order.\n *\n * Note: during the `onBefore` phase, additional hooks can be added to the specific [[Transition]] instance.\n * These \"on-the-fly\" hooks only affect the currently running transition..\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * If any hook modifies the transition *synchronously* (by throwing, returning `false`, or returning\n * a [[TargetState]]), the remainder of the hooks are skipped.\n * If a hook returns a promise, the remainder of the `onBefore` hooks are still invoked synchronously.\n * All promises are resolved, and processed asynchronously before the `onStart` phase of the Transition.\n *\n * ### Examples\n *\n * #### Default Substate\n *\n * This example redirects any transition from 'home' to 'home.dashboard'. This is commonly referred to as a\n * \"default substate\".\n *\n * @example\n * ```js\n * // ng2\n * transitionService.onBefore({ to: 'home' }, (trans: Transition) =>\n * trans.router.stateService.target(\"home.dashboard\"));\n * ```\n *\n * #### Data Driven Default Substate\n *\n * This example provides data-driven default substate functionality. It matches on a transition to any state\n * which has `defaultSubstate: \"some.sub.state\"` defined. See: [[Transition.to]] which returns the \"to state\"\n * definition.\n *\n * @example\n * ```js\n * // ng1\n * // state declaration\n * {\n * name: 'home',\n * template: '
    ',\n * defaultSubstate: 'home.dashboard'\n * }\n *\n * var criteria = {\n * to: function(state) {\n * return state.defaultSubstate != null;\n * }\n * }\n *\n * $transitions.onBefore(criteria, function(trans: Transition) {\n * var substate = trans.to().defaultSubstate;\n * return trans.router.stateService.target(substate);\n * });\n * ```\n *\n *\n * #### Require authentication\n *\n * This example cancels a transition to a state which requires authentication, if the user is not currently authenticated.\n *\n * This example assumes a state tree where all states which require authentication are children of a parent `'requireauth'` state.\n * This example assumes `MyAuthService` synchronously returns a boolean from `isAuthenticated()`.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onBefore( { to: 'requireauth.**' }, function(trans) {\n * var myAuthService = trans.injector().get('MyAuthService');\n * // If isAuthenticated returns false, the transition is cancelled.\n * return myAuthService.isAuthenticated();\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @returns a function which deregisters the hook.\n */\n onBefore(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called when a transition starts.\n *\n * Registers a transition lifecycle hook, which is invoked as a transition starts running.\n * This hook can be useful to perform some asynchronous action before completing a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onStart` hooks are invoked asynchronously when the Transition starts running.\n * This happens after the `onBefore` phase is complete.\n * At this point, the Transition has not yet exited nor entered any states.\n * The registered `onStart` hooks are invoked in priority order.\n *\n * Note: A built-in `onStart` hook with high priority is used to fetch any eager resolve data.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Example\n *\n * #### Login during transition\n *\n * This example intercepts any transition to a state which requires authentication, when the user is\n * not currently authenticated. It allows the user to authenticate asynchronously, then resumes the\n * transition. If the user did not authenticate successfully, it redirects to the \"guest\" state, which\n * does not require authentication.\n *\n * This example assumes:\n * - a state tree where all states which require authentication are children of a parent `'auth'` state.\n * - `MyAuthService.isAuthenticated()` synchronously returns a boolean.\n * - `MyAuthService.authenticate()` presents a login dialog, and returns a promise which is resolved\n * or rejected, whether or not the login attempt was successful.\n *\n * #### Example:\n * ```js\n * // ng1\n * $transitions.onStart( { to: 'auth.**' }, function(trans) {\n * var $state = trans.router.stateService;\n * var MyAuthService = trans.injector().get('MyAuthService');\n *\n * // If the user is not authenticated\n * if (!MyAuthService.isAuthenticated()) {\n *\n * // Then return a promise for a successful login.\n * // The transition will wait for this promise to settle\n *\n * return MyAuthService.authenticate().catch(function() {\n *\n * // If the authenticate() method failed for whatever reason,\n * // redirect to a 'guest' state which doesn't require auth.\n * return $state.target(\"guest\");\n * });\n * }\n * });\n * ```\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onStart(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is entered.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being entered.\n *\n * Since this hook is run only when the specific state is being *entered*, it can be useful for\n * performing tasks when entering a submodule/feature area such as initializing a stateful service,\n * or for guarding access to a submodule/feature area.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onEnter` hooks generally specify `{ entering: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onEnter` hooks are invoked when the Transition is entering a state.\n * States are entered after the `onRetain` phase is complete.\n * If more than one state is being entered, the parent state is entered first.\n * The registered `onEnter` hooks for a state are invoked in priority order.\n *\n * Note: A built-in `onEnter` hook with high priority is used to fetch lazy resolve data for states being entered.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onEnter` hooks using the [[TransitionService]], you may define an `onEnter` hook\n * directly on a state declaration (see: [[StateDeclaration.onEnter]]).\n *\n *\n * ### Examples\n *\n * #### Audit Log\n *\n * This example uses a service to log that a user has entered the admin section of an app.\n * This assumes that there are substates of the \"admin\" state, such as \"admin.users\", \"admin.pages\", etc.\n * @example\n * ```\n *\n * $transitions.onEnter({ entering: 'admin' }, function(transition, state) {\n * var AuditService = trans.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * ```\n *\n * #### Audit Log (inside a state declaration)\n *\n * The `onEnter` inside this state declaration is syntactic sugar for the previous Audit Log example.\n * ```\n * {\n * name: 'admin',\n * component: 'admin',\n * onEnter: function($transition$, $state$) {\n * var AuditService = $transition$.injector().get('AuditService');\n * AuditService.log(\"Entered \" + state.name + \" module while transitioning to \" + transition.to().name);\n * }\n * }\n * ```\n *\n * Note: A state declaration's `onEnter` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onEnter(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is retained/kept.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) for\n * a specific state that was previously active will remain active (is not being entered nor exited).\n *\n * This hook is invoked when a state is \"retained\" or \"kept\".\n * It means the transition is coming *from* a substate of the retained state *to* a substate of the retained state.\n * This hook can be used to perform actions when the user moves from one substate to another, such as between steps in a wizard.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onRetain` hooks generally specify `{ retained: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onRetain` hooks are invoked after any `onExit` hooks have been fired.\n * If more than one state is retained, the child states' `onRetain` hooks are invoked first.\n * The registered `onRetain` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onRetain` hooks using the [[TransitionService]], you may define an `onRetain` hook\n * directly on a state declaration (see: [[StateDeclaration.onRetain]]).\n *\n * Note: A state declaration's `onRetain` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onRetain(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionStateHookFn]], called when a specific state is exited.\n *\n * Registers a lifecycle hook, which is invoked (during a transition) when a specific state is being exited.\n *\n * Since this hook is run only when the specific state is being *exited*, it can be useful for\n * performing tasks when leaving a submodule/feature area such as cleaning up a stateful service,\n * or for preventing the user from leaving a state or submodule until some criteria is satisfied.\n *\n * See [[TransitionStateHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * `onExit` hooks generally specify `{ exiting: 'somestate' }`.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onExit` hooks are invoked when the Transition is exiting a state.\n * States are exited after any `onStart` phase is complete.\n * If more than one state is being exited, the child states are exited first.\n * The registered `onExit` hooks for a state are invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * ### Inside a state declaration\n *\n * Instead of registering `onExit` hooks using the [[TransitionService]], you may define an `onExit` hook\n * directly on a state declaration (see: [[StateDeclaration.onExit]]).\n *\n * Note: A state declaration's `onExit` function is injected for Angular 1 only.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onExit(matchCriteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called *just before a transition finishes*.\n *\n * Registers a transition lifecycle hook, which is invoked just before a transition finishes.\n * This hook is a last chance to cancel or redirect a transition.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onFinish` hooks are invoked after the `onEnter` phase is complete.\n * These hooks are invoked just before the transition is \"committed\".\n * Each hook is invoked in priority order.\n *\n * ### Return value\n *\n * The hook's return value can be used to pause, cancel, or redirect the current Transition.\n * See [[HookResult]] for more information.\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onFinish(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a successful transition completed.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition successfully completes.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * `onSuccess` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If the Transition is successful and its promise is resolved, then the `onSuccess` hooks are invoked.\n * Since these hooks are run after the transition is over, their return value is ignored.\n * The `onSuccess` hooks are invoked in priority order.\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onSuccess(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Registers a [[TransitionHookFn]], called after a transition has errored.\n *\n * Registers a transition lifecycle hook, which is invoked after a transition has been rejected for any reason.\n *\n * See [[TransitionHookFn]] for the signature of the function.\n *\n * The [[HookMatchCriteria]] is used to determine which Transitions the hook should be invoked for.\n * To match all Transitions, use an empty criteria object `{}`.\n *\n * ### Lifecycle\n *\n * The `onError` hooks are chained off the Transition's promise (see [[Transition.promise]]).\n * If a Transition fails, its promise is rejected and the `onError` hooks are invoked.\n * The `onError` hooks are invoked in priority order.\n *\n * Since these hooks are run after the transition is over, their return value is ignored.\n *\n * A transition \"errors\" if it was started, but failed to complete (for any reason).\n * A *non-exhaustive list* of reasons a transition can error:\n *\n * - A transition was cancelled because a new transition started while it was still running (`Transition superseded`)\n * - A transition was cancelled by a Transition Hook returning false\n * - A transition was redirected by a Transition Hook returning a [[TargetState]]\n * - A Transition Hook or resolve function threw an error\n * - A Transition Hook returned a rejected promise\n * - A resolve function returned a rejected promise\n *\n * To check the failure reason, inspect the return value of [[Transition.error]].\n *\n * Note: `onError` should be used for targeted error handling, or error recovery.\n * For simple catch-all error reporting, use [[StateService.defaultErrorHandler]].\n *\n * ### Return value\n *\n * Since the Transition is already completed, the hook's return value is ignored\n *\n * @param matchCriteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be injected and invoked.\n * @returns a function which deregisters the hook.\n */\n onError(matchCriteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function;\n\n /**\n * Returns all the registered hooks of a given `hookName` type\n *\n * #### Example:\n * ```\n * $transitions.getHooks(\"onEnter\")\n * ```\n */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/** A predicate type which tests if a [[StateObject]] passes some test. Returns a boolean. */\nexport type IStateMatch = Predicate;\n\n/**\n * This object is used to configure whether or not a Transition Hook is invoked for a particular transition,\n * based on the Transition's \"to state\" and \"from state\".\n *\n * Each property (`to`, `from`, `exiting`, `retained`, and `entering`) can be a state [[Glob]] string,\n * a boolean, or a function that takes a state and returns a boolean (see [[HookMatchCriterion]])\n *\n * All properties are optional. If any property is omitted, it is replaced with the value `true`, and always matches.\n * To match any transition, use an empty criteria object `{}`.\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from the `parent` state and going to the `parent.child` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.child'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any substate of `parent` and going directly to the `parent` state.\n * var match = {\n * to: 'parent',\n * from: 'parent.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any substate of `mymodule`\n * var match = {\n * to: 'mymodule.**'\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition coming from any state and going to any state that has `data.authRequired`\n * // set to a truthy value.\n * var match = {\n * to: function(state) {\n * return state.data != null && state.data.authRequired === true;\n * }\n * }\n * ```\n *\n * #### Example:\n * ```js\n * // This matches a transition that is exiting `parent.child`\n * var match = {\n * exiting: 'parent.child'\n * }\n * ```\n */\nexport interface HookMatchCriteria {\n [key: string]: HookMatchCriterion | undefined;\n\n /** A [[HookMatchCriterion]] to match the destination state */\n to?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match the original (from) state */\n from?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be exiting */\n exiting?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be retained */\n retained?: HookMatchCriterion;\n /** A [[HookMatchCriterion]] to match any state that would be entering */\n entering?: HookMatchCriterion;\n}\n\nexport interface IMatchingNodes {\n [key: string]: PathNode[];\n\n to: PathNode[];\n from: PathNode[];\n exiting: PathNode[];\n retained: PathNode[];\n entering: PathNode[];\n}\n\n/** @hidden */\nexport interface RegisteredHooks {\n [key: string]: RegisteredHook[];\n}\n\n/** @hidden */\nexport interface PathTypes {\n [key: string]: PathType;\n\n to: PathType;\n from: PathType;\n exiting: PathType;\n retained: PathType;\n entering: PathType;\n}\n\n/** @hidden */\nexport interface PathType {\n name: string;\n scope: TransitionHookScope;\n}\n\n/**\n * Hook Criterion used to match a transition.\n *\n * A [[Glob]] string that matches the name of a state.\n *\n * Or, a function with the signature `function(state) { return matches; }`\n * which should return a boolean to indicate if a state matches.\n *\n * Or, `true` to always match\n */\nexport type HookMatchCriterion = string | IStateMatch | boolean;\n\nenum TransitionHookPhase {\n CREATE,\n BEFORE,\n RUN,\n SUCCESS,\n ERROR,\n}\nenum TransitionHookScope {\n TRANSITION,\n STATE,\n}\n\nexport { TransitionHookPhase, TransitionHookScope };\n", + "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateDeclaration, StateOrName, TargetStateDef } from './interface';\nimport { TransitionOptions } from '../transition/interface';\nimport { StateObject } from './stateObject';\nimport { isString } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { extend } from '../common';\nimport { StateRegistry } from './stateRegistry';\nimport { RawParams } from '../params';\n\n/**\n * Encapsulate the target (destination) state/params/options of a [[Transition]].\n *\n * This class is frequently used to redirect a transition to a new destination.\n *\n * See:\n *\n * - [[HookResult]]\n * - [[TransitionHookFn]]\n * - [[TransitionService.onStart]]\n *\n * To create a `TargetState`, use [[StateService.target]].\n *\n * ---\n *\n * This class wraps:\n *\n * 1) an identifier for a state\n * 2) a set of parameters\n * 3) and transition options\n * 4) the registered state object (the [[StateDeclaration]])\n *\n * Many UI-Router APIs such as [[StateService.go]] take a [[StateOrName]] argument which can\n * either be a *state object* (a [[StateDeclaration]] or [[StateObject]]) or a *state name* (a string).\n * The `TargetState` class normalizes those options.\n *\n * A `TargetState` may be valid (the state being targeted exists in the registry)\n * or invalid (the state being targeted is not registered).\n */\nexport class TargetState {\n private _definition: StateObject;\n private _params: RawParams;\n private _options: TransitionOptions;\n\n /** Returns true if the object has a state property that might be a state or state name */\n static isDef = (obj): obj is TargetStateDef => obj && obj.state && (isString(obj.state) || isString(obj.state.name));\n\n /**\n * The TargetState constructor\n *\n * Note: Do not construct a `TargetState` manually.\n * To create a `TargetState`, use the [[StateService.target]] factory method.\n *\n * @param _stateRegistry The StateRegistry to use to look up the _definition\n * @param _identifier An identifier for a state.\n * Either a fully-qualified state name, or the object used to define the state.\n * @param _params Parameters for the target state\n * @param _options Transition options.\n *\n * @internalapi\n */\n constructor(\n private _stateRegistry: StateRegistry,\n private _identifier: StateOrName,\n _params?: RawParams,\n _options?: TransitionOptions,\n ) {\n this._identifier = _identifier;\n this._params = extend({}, _params || {});\n this._options = extend({}, _options || {});\n this._definition = _stateRegistry.matcher.find(_identifier, this._options.relative);\n }\n\n /** The name of the state this object targets */\n name(): string {\n return (this._definition && this._definition.name) || this._identifier;\n }\n\n /** The identifier used when creating this TargetState */\n identifier(): StateOrName {\n return this._identifier;\n }\n\n /** The target parameter values */\n params(): RawParams {\n return this._params;\n }\n\n /** The internal state object (if it was found) */\n $state(): StateObject {\n return this._definition;\n }\n\n /** The internal state declaration (if it was found) */\n state(): StateDeclaration {\n return this._definition && this._definition.self;\n }\n\n /** The target options */\n options() {\n return this._options;\n }\n\n /** True if the target state was found */\n exists(): boolean {\n return !!(this._definition && this._definition.self);\n }\n\n /** True if the object is valid */\n valid(): boolean {\n return !this.error();\n }\n\n /** If the object is invalid, returns the reason why */\n error(): string {\n const base = this.options().relative;\n if (!this._definition && !!base) {\n const stateName = base.name ? base.name : base;\n return `Could not resolve '${this.name()}' from state '${stateName}'`;\n }\n if (!this._definition) return `No such state '${this.name()}'`;\n if (!this._definition.self) return `State '${this.name()}' has an invalid definition`;\n }\n\n toString() {\n return `'${this.name()}'${stringify(this.params())}`;\n }\n\n /**\n * Returns a copy of this TargetState which targets a different state.\n * The new TargetState has the same parameter values and transition options.\n *\n * @param state The new state that should be targeted\n */\n withState(state: StateOrName): TargetState {\n return new TargetState(this._stateRegistry, state, this._params, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified parameter values.\n *\n * @param params the new parameter values to use\n * @param replace When false (default) the new parameter values will be merged with the current values.\n * When true the parameter values will be used instead of the current values.\n */\n withParams(params: RawParams, replace = false): TargetState {\n const newParams: RawParams = replace ? params : extend({}, this._params, params);\n return new TargetState(this._stateRegistry, this._identifier, newParams, this._options);\n }\n\n /**\n * Returns a copy of this TargetState, using the specified Transition Options.\n *\n * @param options the new options to use\n * @param replace When false (default) the new options will be merged with the current options.\n * When true the options will be used instead of the current options.\n */\n withOptions(options: TransitionOptions, replace = false): TargetState {\n const newOpts = replace ? options : extend({}, this._options, options);\n return new TargetState(this._stateRegistry, this._identifier, this._params, newOpts);\n }\n}\n", + "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { TransitionHookOptions, HookResult, TransitionHookPhase } from './interface';\nimport { defaults, noop, silentRejection } from '../common/common';\nimport { fnToString, maxLength } from '../common/strings';\nimport { isPromise } from '../common/predicates';\nimport { is, parse } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { Rejection } from './rejectFactory';\nimport { TargetState } from '../state/targetState';\nimport { Transition } from './transition';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\nimport { StateDeclaration } from '../state/interface';\n\nconst defaultOptions: TransitionHookOptions = {\n current: noop,\n transition: null,\n traceData: {},\n bind: null,\n};\n\nexport type GetResultHandler = (hook: TransitionHook) => ResultHandler;\nexport type GetErrorHandler = (hook: TransitionHook) => ErrorHandler;\n\nexport type ResultHandler = (result: HookResult) => Promise;\nexport type ErrorHandler = (error: any) => Promise;\n\n/** @hidden */\nexport class TransitionHook {\n type: TransitionEventType;\n\n /**\n * These GetResultHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetResultHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static HANDLE_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) =>\n hook.handleHookResult(result);\n\n /**\n * If the result is a promise rejection, log it.\n * Otherwise, ignore the result.\n */\n static LOG_REJECTED_RESULT: GetResultHandler = (hook: TransitionHook) => (result: HookResult) => {\n isPromise(result) && result.catch(err => hook.logError(Rejection.normalize(err)));\n return undefined;\n };\n\n /**\n * These GetErrorHandler(s) are used by [[invokeHook]] below\n * Each HookType chooses a GetErrorHandler (See: [[TransitionService._defineCoreEvents]])\n */\n static LOG_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => hook.logError(error);\n\n static REJECT_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => silentRejection(error);\n\n static THROW_ERROR: GetErrorHandler = (hook: TransitionHook) => (error: any) => {\n throw error;\n };\n\n /**\n * Chains together an array of TransitionHooks.\n *\n * Given a list of [[TransitionHook]] objects, chains them together.\n * Each hook is invoked after the previous one completes.\n *\n * #### Example:\n * ```js\n * var hooks: TransitionHook[] = getHooks();\n * let promise: Promise = TransitionHook.chain(hooks);\n *\n * promise.then(handleSuccess, handleError);\n * ```\n *\n * @param hooks the list of hooks to chain together\n * @param waitFor if provided, the chain is `.then()`'ed off this promise\n * @returns a `Promise` for sequentially invoking the hooks (in order)\n */\n static chain(hooks: TransitionHook[], waitFor?: Promise): Promise {\n // Chain the next hook off the previous\n const createHookChainR = (prev: Promise, nextHook: TransitionHook) => prev.then(() => nextHook.invokeHook());\n return hooks.reduce(createHookChainR, waitFor || services.$q.when());\n }\n\n /**\n * Invokes all the provided TransitionHooks, in order.\n * Each hook's return value is checked.\n * If any hook returns a promise, then the rest of the hooks are chained off that promise, and the promise is returned.\n * If no hook returns a promise, then all hooks are processed synchronously.\n *\n * @param hooks the list of TransitionHooks to invoke\n * @param doneCallback a callback that is invoked after all the hooks have successfully completed\n *\n * @returns a promise for the async result, or the result of the callback\n */\n static invokeHooks(hooks: TransitionHook[], doneCallback: (result?: HookResult) => T): Promise | T {\n for (let idx = 0; idx < hooks.length; idx++) {\n const hookResult = hooks[idx].invokeHook();\n\n if (isPromise(hookResult)) {\n const remainingHooks = hooks.slice(idx + 1);\n\n return TransitionHook.chain(remainingHooks, hookResult).then(doneCallback);\n }\n }\n\n return doneCallback();\n }\n\n /**\n * Run all TransitionHooks, ignoring their return value.\n */\n static runAllHooks(hooks: TransitionHook[]): void {\n hooks.forEach(hook => hook.invokeHook());\n }\n\n constructor(\n private transition: Transition,\n private stateContext: StateDeclaration,\n private registeredHook: RegisteredHook,\n private options: TransitionHookOptions,\n ) {\n this.options = defaults(options, defaultOptions);\n this.type = registeredHook.eventType;\n }\n\n private isSuperseded = () => this.type.hookPhase === TransitionHookPhase.RUN && !this.options.transition.isActive();\n\n logError(err): any {\n this.transition.router.stateService.defaultErrorHandler()(err);\n }\n\n invokeHook(): Promise | void {\n const hook = this.registeredHook;\n if (hook._deregistered) return;\n\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n const options = this.options;\n trace.traceHookInvocation(this, this.transition, options);\n\n const invokeCallback = () => hook.callback.call(options.bind, this.transition, this.stateContext);\n\n const normalizeErr = err => Rejection.normalize(err).toPromise();\n\n const handleError = err => hook.eventType.getErrorHandler(this)(err);\n\n const handleResult = result => hook.eventType.getResultHandler(this)(result);\n\n try {\n const result = invokeCallback();\n\n if (!this.type.synchronous && isPromise(result)) {\n return result.catch(normalizeErr).then(handleResult, handleError);\n } else {\n return handleResult(result);\n }\n } catch (err) {\n // If callback throws (synchronously)\n return handleError(Rejection.normalize(err));\n } finally {\n if (hook.invokeLimit && ++hook.invokeCount >= hook.invokeLimit) {\n hook.deregister();\n }\n }\n }\n\n /**\n * This method handles the return value of a Transition Hook.\n *\n * A hook can return false (cancel), a TargetState (redirect),\n * or a promise (which may later resolve to false or a redirect)\n *\n * This also handles \"transition superseded\" -- when a new transition\n * was started while the hook was still running\n */\n handleHookResult(result: HookResult): Promise {\n const notCurrent = this.getNotCurrentRejection();\n if (notCurrent) return notCurrent;\n\n // Hook returned a promise\n if (isPromise(result)) {\n // Wait for the promise, then reprocess with the resulting value\n return result.then(val => this.handleHookResult(val));\n }\n\n trace.traceHookResult(result, this.transition, this.options);\n\n // Hook returned false\n if (result === false) {\n // Abort this Transition\n return Rejection.aborted('Hook aborted transition').toPromise();\n }\n\n const isTargetState = is(TargetState);\n // hook returned a TargetState\n if (isTargetState(result)) {\n // Halt the current Transition and redirect (a new Transition) to the TargetState.\n return Rejection.redirected(result).toPromise();\n }\n }\n\n /**\n * Return a Rejection promise if the transition is no longer current due\n * to a stopped router (disposed), or a new transition has started and superseded this one.\n */\n private getNotCurrentRejection() {\n const router = this.transition.router;\n\n // The router is stopped\n if (router._disposed) {\n return Rejection.aborted(`UIRouter instance #${router.$id} has been stopped (disposed)`).toPromise();\n }\n\n if (this.transition._aborted) {\n return Rejection.aborted().toPromise();\n }\n\n // This transition is no longer current.\n // Another transition started while this hook was still running.\n if (this.isSuperseded()) {\n // Abort this transition\n return Rejection.superseded(this.options.current()).toPromise();\n }\n }\n\n toString() {\n const { options, registeredHook } = this;\n const event = parse('traceData.hookType')(options) || 'internal',\n context = parse('traceData.context.state.name')(options) || parse('traceData.context')(options) || 'unknown',\n name = fnToString(registeredHook.callback);\n return `${event} context: ${context}, ${maxLength(200, name)}`;\n }\n}\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\nimport { isString, isFunction, Glob, extend, removeFrom, tail, values, identity, mapObj } from '../common';\nimport { PathNode } from '../path/pathNode';\nimport {\n TransitionStateHookFn,\n TransitionHookFn,\n TransitionHookPhase, // has or is using\n TransitionHookScope,\n IHookRegistry,\n PathType,\n} from './interface';\n\nimport {\n HookRegOptions,\n HookMatchCriteria,\n TreeChanges,\n HookMatchCriterion,\n IMatchingNodes,\n HookFn,\n} from './interface';\nimport { StateObject } from '../state/stateObject';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionService } from './transitionService';\n\n/**\n * Determines if the given state matches the matchCriteria\n *\n * @hidden\n *\n * @param state a State Object to test against\n * @param criterion\n * - If a string, matchState uses the string as a glob-matcher against the state name\n * - If an array (of strings), matchState uses each string in the array as a glob-matchers against the state name\n * and returns a positive match if any of the globs match.\n * - If a function, matchState calls the function with the state and returns true if the function's result is truthy.\n * @returns {boolean}\n */\nexport function matchState(state: StateObject, criterion: HookMatchCriterion) {\n const toMatch = isString(criterion) ? [criterion] : criterion;\n\n function matchGlobs(_state: StateObject) {\n const globStrings = toMatch;\n for (let i = 0; i < globStrings.length; i++) {\n const glob = new Glob(globStrings[i]);\n\n if ((glob && glob.matches(_state.name)) || (!glob && globStrings[i] === _state.name)) {\n return true;\n }\n }\n return false;\n }\n\n const matchFn = (isFunction(toMatch) ? toMatch : matchGlobs);\n return !!matchFn(state);\n}\n\n/**\n * @internalapi\n * The registration data for a registered transition hook\n */\nexport class RegisteredHook {\n priority: number;\n bind: any;\n invokeCount = 0;\n invokeLimit: number;\n _deregistered = false;\n\n constructor(\n public tranSvc: TransitionService,\n public eventType: TransitionEventType,\n public callback: HookFn,\n public matchCriteria: HookMatchCriteria,\n public removeHookFromRegistry: (hook: RegisteredHook) => void,\n options: HookRegOptions = {} as any,\n ) {\n this.priority = options.priority || 0;\n this.bind = options.bind || null;\n this.invokeLimit = options.invokeLimit;\n }\n\n /**\n * Gets the matching [[PathNode]]s\n *\n * Given an array of [[PathNode]]s, and a [[HookMatchCriterion]], returns an array containing\n * the [[PathNode]]s that the criteria matches, or `null` if there were no matching nodes.\n *\n * Returning `null` is significant to distinguish between the default\n * \"match-all criterion value\" of `true` compared to a `() => true` function,\n * when the nodes is an empty array.\n *\n * This is useful to allow a transition match criteria of `entering: true`\n * to still match a transition, even when `entering === []`. Contrast that\n * with `entering: (state) => true` which only matches when a state is actually\n * being entered.\n */\n private _matchingNodes(nodes: PathNode[], criterion: HookMatchCriterion): PathNode[] {\n if (criterion === true) return nodes;\n const matching = nodes.filter(node => matchState(node.state, criterion));\n return matching.length ? matching : null;\n }\n\n /**\n * Gets the default match criteria (all `true`)\n *\n * Returns an object which has all the criteria match paths as keys and `true` as values, i.e.:\n *\n * ```js\n * {\n * to: true,\n * from: true,\n * entering: true,\n * exiting: true,\n * retained: true,\n * }\n */\n private _getDefaultMatchCriteria(): HookMatchCriteria {\n return mapObj(this.tranSvc._pluginapi._getPathTypes(), () => true);\n }\n\n /**\n * Gets matching nodes as [[IMatchingNodes]]\n *\n * Create a IMatchingNodes object from the TransitionHookTypes that is roughly equivalent to:\n *\n * ```js\n * let matches: IMatchingNodes = {\n * to: _matchingNodes([tail(treeChanges.to)], mc.to),\n * from: _matchingNodes([tail(treeChanges.from)], mc.from),\n * exiting: _matchingNodes(treeChanges.exiting, mc.exiting),\n * retained: _matchingNodes(treeChanges.retained, mc.retained),\n * entering: _matchingNodes(treeChanges.entering, mc.entering),\n * };\n * ```\n */\n private _getMatchingNodes(treeChanges: TreeChanges): IMatchingNodes {\n const criteria = extend(this._getDefaultMatchCriteria(), this.matchCriteria);\n const paths: PathType[] = values(this.tranSvc._pluginapi._getPathTypes());\n\n return paths.reduce(\n (mn: IMatchingNodes, pathtype: PathType) => {\n // STATE scope criteria matches against every node in the path.\n // TRANSITION scope criteria matches against only the last node in the path\n const isStateHook = pathtype.scope === TransitionHookScope.STATE;\n const path = treeChanges[pathtype.name] || [];\n const nodes: PathNode[] = isStateHook ? path : [tail(path)];\n\n mn[pathtype.name] = this._matchingNodes(nodes, criteria[pathtype.name]);\n return mn;\n },\n {} as IMatchingNodes,\n );\n }\n\n /**\n * Determines if this hook's [[matchCriteria]] match the given [[TreeChanges]]\n *\n * @returns an IMatchingNodes object, or null. If an IMatchingNodes object is returned, its values\n * are the matching [[PathNode]]s for each [[HookMatchCriterion]] (to, from, exiting, retained, entering)\n */\n matches(treeChanges: TreeChanges): IMatchingNodes {\n const matches = this._getMatchingNodes(treeChanges);\n\n // Check if all the criteria matched the TreeChanges object\n const allMatched = values(matches).every(identity);\n return allMatched ? matches : null;\n }\n\n deregister() {\n this.removeHookFromRegistry(this);\n this._deregistered = true;\n }\n}\n\n/** @hidden Return a registration function of the requested type. */\nexport function makeEvent(\n registry: IHookRegistry,\n transitionService: TransitionService,\n eventType: TransitionEventType,\n) {\n // Create the object which holds the registered transition hooks.\n const _registeredHooks = (registry._registeredHooks = registry._registeredHooks || {});\n const hooks = (_registeredHooks[eventType.name] = []);\n const removeHookFn: (hook: RegisteredHook) => void = removeFrom(hooks);\n\n // Create hook registration function on the IHookRegistry for the event\n registry[eventType.name] = hookRegistrationFn;\n\n function hookRegistrationFn(matchObject, callback, options = {}) {\n const registeredHook = new RegisteredHook(\n transitionService,\n eventType,\n callback,\n matchObject,\n removeHookFn,\n options,\n );\n hooks.push(registeredHook);\n return registeredHook.deregister.bind(registeredHook);\n }\n\n return hookRegistrationFn;\n}\n", + "/**\n * @coreapi\n * @module transition\n */ /** for typedoc */\n\nimport { extend, tail, assertPredicate, unnestR, identity } from '../common/common';\nimport { isArray } from '../common/predicates';\n\nimport {\n TransitionOptions,\n TransitionHookOptions,\n IHookRegistry,\n TreeChanges,\n IMatchingNodes,\n TransitionHookPhase,\n TransitionHookScope,\n} from './interface';\n\nimport { Transition } from './transition';\nimport { TransitionHook } from './transitionHook';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { TransitionService } from './transitionService';\nimport { TransitionEventType } from './transitionEventType';\nimport { RegisteredHook } from './hookRegistry';\n\n/**\n * This class returns applicable TransitionHooks for a specific Transition instance.\n *\n * Hooks ([[RegisteredHook]]) may be registered globally, e.g., $transitions.onEnter(...), or locally, e.g.\n * myTransition.onEnter(...). The HookBuilder finds matching RegisteredHooks (where the match criteria is\n * determined by the type of hook)\n *\n * The HookBuilder also converts RegisteredHooks objects to TransitionHook objects, which are used to run a Transition.\n *\n * The HookBuilder constructor is given the $transitions service and a Transition instance. Thus, a HookBuilder\n * instance may only be used for one specific Transition object. (side note: the _treeChanges accessor is private\n * in the Transition class, so we must also provide the Transition's _treeChanges)\n *\n */\nexport class HookBuilder {\n constructor(private transition: Transition) {}\n\n buildHooksForPhase(phase: TransitionHookPhase): TransitionHook[] {\n const $transitions = this.transition.router.transitionService;\n return $transitions._pluginapi\n ._getEvents(phase)\n .map(type => this.buildHooks(type))\n .reduce(unnestR, [])\n .filter(identity);\n }\n\n /**\n * Returns an array of newly built TransitionHook objects.\n *\n * - Finds all RegisteredHooks registered for the given `hookType` which matched the transition's [[TreeChanges]].\n * - Finds [[PathNode]] (or `PathNode[]`) to use as the TransitionHook context(s)\n * - For each of the [[PathNode]]s, creates a TransitionHook\n *\n * @param hookType the type of the hook registration function, e.g., 'onEnter', 'onFinish'.\n */\n buildHooks(hookType: TransitionEventType): TransitionHook[] {\n const transition = this.transition;\n const treeChanges = transition.treeChanges();\n\n // Find all the matching registered hooks for a given hook type\n const matchingHooks = this.getMatchingHooks(hookType, treeChanges);\n if (!matchingHooks) return [];\n\n const baseHookOptions = {\n transition: transition,\n current: transition.options().current,\n };\n\n const makeTransitionHooks = (hook: RegisteredHook) => {\n // Fetch the Nodes that caused this hook to match.\n const matches: IMatchingNodes = hook.matches(treeChanges);\n // Select the PathNode[] that will be used as TransitionHook context objects\n const matchingNodes: PathNode[] = matches[hookType.criteriaMatchPath.name];\n\n // Return an array of HookTuples\n return matchingNodes.map(node => {\n const _options = extend(\n {\n bind: hook.bind,\n traceData: { hookType: hookType.name, context: node },\n },\n baseHookOptions,\n );\n\n const state = hookType.criteriaMatchPath.scope === TransitionHookScope.STATE ? node.state.self : null;\n const transitionHook = new TransitionHook(transition, state, hook, _options);\n return { hook, node, transitionHook };\n });\n };\n\n return matchingHooks\n .map(makeTransitionHooks)\n .reduce(unnestR, [])\n .sort(tupleSort(hookType.reverseSort))\n .map(tuple => tuple.transitionHook);\n }\n\n /**\n * Finds all RegisteredHooks from:\n * - The Transition object instance hook registry\n * - The TransitionService ($transitions) global hook registry\n *\n * which matched:\n * - the eventType\n * - the matchCriteria (to, from, exiting, retained, entering)\n *\n * @returns an array of matched [[RegisteredHook]]s\n */\n public getMatchingHooks(hookType: TransitionEventType, treeChanges: TreeChanges): RegisteredHook[] {\n const isCreate = hookType.hookPhase === TransitionHookPhase.CREATE;\n\n // Instance and Global hook registries\n const $transitions = this.transition.router.transitionService;\n const registries = isCreate ? [$transitions] : [this.transition, $transitions];\n\n return registries\n .map((reg: IHookRegistry) => reg.getHooks(hookType.name)) // Get named hooks from registries\n .filter(assertPredicate(isArray, `broken event named: ${hookType.name}`)) // Sanity check\n .reduce(unnestR, []) // Un-nest RegisteredHook[][] to RegisteredHook[] array\n .filter(hook => hook.matches(treeChanges)); // Only those satisfying matchCriteria\n }\n}\n\ninterface HookTuple {\n hook: RegisteredHook;\n node: PathNode;\n transitionHook: TransitionHook;\n}\n\n/**\n * A factory for a sort function for HookTuples.\n *\n * The sort function first compares the PathNode depth (how deep in the state tree a node is), then compares\n * the EventHook priority.\n *\n * @param reverseDepthSort a boolean, when true, reverses the sort order for the node depth\n * @returns a tuple sort function\n */\nfunction tupleSort(reverseDepthSort = false) {\n return function nodeDepthThenPriority(l: HookTuple, r: HookTuple): number {\n const factor = reverseDepthSort ? -1 : 1;\n const depthDelta = (l.node.state.path.length - r.node.state.path.length) * factor;\n return depthDelta !== 0 ? depthDelta : r.hook.priority - l.hook.priority;\n };\n}\n", + "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, filter, map } from '../common/common';\nimport { isArray, isDefined } from '../common/predicates';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * An internal class which implements [[ParamTypeDefinition]].\n *\n * A [[ParamTypeDefinition]] is a plain javascript object used to register custom parameter types.\n * When a param type definition is registered, an instance of this class is created internally.\n *\n * This class has naive implementations for all the [[ParamTypeDefinition]] methods.\n *\n * Used by [[UrlMatcher]] when matching or formatting URLs, or comparing and validating parameter values.\n *\n * #### Example:\n * ```js\n * var paramTypeDef = {\n * decode: function(val) { return parseInt(val, 10); },\n * encode: function(val) { return val && val.toString(); },\n * equals: function(a, b) { return this.is(a) && a === b; },\n * is: function(val) { return angular.isNumber(val) && isFinite(val) && val % 1 === 0; },\n * pattern: /\\d+/\n * }\n *\n * var paramType = new ParamType(paramTypeDef);\n * ```\n * @internalapi\n */\nexport class ParamType implements ParamTypeDefinition {\n /** @inheritdoc */\n pattern: RegExp = /.*/;\n /** The name/id of the parameter type */\n name: string;\n /** @inheritdoc */\n raw: boolean;\n /** @inheritdoc */\n dynamic: boolean;\n /** @inheritdoc */\n inherit = true;\n\n /**\n * @param def A configuration object which contains the custom type definition. The object's\n * properties will override the default methods and/or pattern in `ParamType`'s public interface.\n * @returns a new ParamType object\n */\n constructor(def: ParamTypeDefinition) {\n extend(this, def);\n }\n\n // consider these four methods to be \"abstract methods\" that should be overridden\n /** @inheritdoc */\n is(val: any, key?: string): boolean {\n return true;\n }\n /** @inheritdoc */\n encode(val: any, key?: string): string | string[] {\n return val;\n }\n /** @inheritdoc */\n decode(val: string, key?: string): any {\n return val;\n }\n /** @inheritdoc */\n equals(a: any, b: any): boolean {\n // tslint:disable-next-line:triple-equals\n return a == b;\n }\n\n $subPattern() {\n const sub = this.pattern.toString();\n return sub.substr(1, sub.length - 2);\n }\n\n toString() {\n return `{ParamType:${this.name}}`;\n }\n\n /** Given an encoded string, or a decoded object, returns a decoded object */\n $normalize(val: any) {\n return this.is(val) ? val : this.decode(val);\n }\n\n /**\n * Wraps an existing custom ParamType as an array of ParamType, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\n $asArray(mode: boolean | 'auto', isSearch: boolean) {\n if (!mode) return this;\n if (mode === 'auto' && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n return new (ArrayType)(this, mode);\n }\n}\n\n/**\n * Wraps up a `ParamType` object to handle array values.\n * @internalapi\n */\nfunction ArrayType(type: ParamType, mode: boolean | 'auto') {\n // Wrap non-array value as array\n function arrayWrap(val: any): any[] {\n return isArray(val) ? val : isDefined(val) ? [val] : [];\n }\n\n // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n function arrayUnwrap(val: any) {\n switch (val.length) {\n case 0:\n return undefined;\n case 1:\n return mode === 'auto' ? val[0] : val;\n default:\n return val;\n }\n }\n\n // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n function arrayHandler(callback: (x: any) => any, allTruthyMode?: boolean) {\n return function handleArray(val: any) {\n if (isArray(val) && val.length === 0) return val;\n const arr = arrayWrap(val);\n const result = map(arr, callback);\n return allTruthyMode === true ? filter(result, x => !x).length === 0 : arrayUnwrap(result);\n };\n }\n\n // Wraps type (.equals) functions to operate on each value of an array\n function arrayEqualsHandler(callback: (l: any, r: any) => boolean) {\n return function handleArray(val1: any, val2: any) {\n const left = arrayWrap(val1),\n right = arrayWrap(val2);\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!callback(left[i], right[i])) return false;\n }\n return true;\n };\n }\n\n ['encode', 'decode', 'equals', '$normalize'].forEach(name => {\n const paramTypeFn = type[name].bind(type);\n const wrapperFn: Function = name === 'equals' ? arrayEqualsHandler : arrayHandler;\n this[name] = wrapperFn(paramTypeFn);\n });\n\n extend(this, {\n dynamic: type.dynamic,\n name: type.name,\n pattern: type.pattern,\n inherit: type.inherit,\n is: arrayHandler(type.is.bind(type), true),\n $arrayMode: mode,\n });\n}\n", + "/**\n * @coreapi\n * @module params\n */ /** for typedoc */\nimport { extend, filter, map, allTrueR } from '../common/common';\nimport { prop } from '../common/hof';\nimport { isInjectable, isDefined, isString, isArray, isUndefined } from '../common/predicates';\nimport { RawParams, ParamDeclaration } from '../params/interface';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypes } from './paramTypes';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\n\n/** @hidden */\nconst hasOwn = Object.prototype.hasOwnProperty;\n\n/** @hidden */\nconst isShorthand = (cfg: ParamDeclaration) =>\n ['value', 'type', 'squash', 'array', 'dynamic'].filter(hasOwn.bind(cfg || {})).length === 0;\n\n/** @internalapi */\nenum DefType {\n PATH,\n SEARCH,\n CONFIG,\n}\nexport { DefType };\n\n/** @hidden */\nfunction unwrapShorthand(cfg: ParamDeclaration): ParamDeclaration {\n cfg = (isShorthand(cfg) && ({ value: cfg } as any)) || cfg;\n\n getStaticDefaultValue['__cacheable'] = true;\n function getStaticDefaultValue() {\n return cfg.value;\n }\n\n return extend(cfg, {\n $$fn: isInjectable(cfg.value) ? cfg.value : getStaticDefaultValue,\n });\n}\n\n/** @hidden */\nfunction getType(cfg: ParamDeclaration, urlType: ParamType, location: DefType, id: string, paramTypes: ParamTypes) {\n if (cfg.type && urlType && urlType.name !== 'string') throw new Error(`Param '${id}' has two type configurations.`);\n if (cfg.type && urlType && urlType.name === 'string' && paramTypes.type(cfg.type as string))\n return paramTypes.type(cfg.type as string);\n if (urlType) return urlType;\n if (!cfg.type) {\n const type =\n location === DefType.CONFIG\n ? 'any'\n : location === DefType.PATH\n ? 'path'\n : location === DefType.SEARCH\n ? 'query'\n : 'string';\n return paramTypes.type(type);\n }\n return cfg.type instanceof ParamType ? cfg.type : paramTypes.type(cfg.type as string);\n}\n\n/**\n * @internalapi\n * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n */\nfunction getSquashPolicy(config: ParamDeclaration, isOptional: boolean, defaultPolicy: boolean | string) {\n const squash = config.squash;\n if (!isOptional || squash === false) return false;\n if (!isDefined(squash) || squash == null) return defaultPolicy;\n if (squash === true || isString(squash)) return squash;\n throw new Error(`Invalid squash policy: '${squash}'. Valid policies: false, true, or arbitrary string`);\n}\n\n/** @internalapi */\nfunction getReplace(config: ParamDeclaration, arrayMode: boolean, isOptional: boolean, squash: string | boolean) {\n const defaultPolicy = [\n { from: '', to: isOptional || arrayMode ? undefined : '' },\n { from: null, to: isOptional || arrayMode ? undefined : '' },\n ];\n\n const replace = isArray(config.replace) ? config.replace : [];\n if (isString(squash)) replace.push({ from: squash, to: undefined });\n\n const configuredKeys = map(replace, prop('from'));\n return filter(defaultPolicy, item => configuredKeys.indexOf(item.from) === -1).concat(replace);\n}\n\n/** @internalapi */\nexport class Param {\n id: string;\n type: ParamType;\n location: DefType;\n isOptional: boolean;\n dynamic: boolean;\n raw: boolean;\n squash: boolean | string;\n replace: [{ to: any; from: any }];\n inherit: boolean;\n array: boolean;\n config: any;\n /** Cache the default value if it is a static value */\n _defaultValueCache: {\n defaultValue: any;\n };\n\n static values(params: Param[], values: RawParams = {}): RawParams {\n const paramValues = {} as RawParams;\n for (const param of params) {\n paramValues[param.id] = param.value(values[param.id]);\n }\n return paramValues;\n }\n\n /**\n * Finds [[Param]] objects which have different param values\n *\n * Filters a list of [[Param]] objects to only those whose parameter values differ in two param value objects\n *\n * @param params: The list of Param objects to filter\n * @param values1: The first set of parameter values\n * @param values2: the second set of parameter values\n *\n * @returns any Param objects whose values were different between values1 and values2\n */\n static changed(params: Param[], values1: RawParams = {}, values2: RawParams = {}): Param[] {\n return params.filter(param => !param.type.equals(values1[param.id], values2[param.id]));\n }\n\n /**\n * Checks if two param value objects are equal (for a set of [[Param]] objects)\n *\n * @param params The list of [[Param]] objects to check\n * @param values1 The first set of param values\n * @param values2 The second set of param values\n *\n * @returns true if the param values in values1 and values2 are equal\n */\n static equals(params: Param[], values1 = {}, values2 = {}): boolean {\n return Param.changed(params, values1, values2).length === 0;\n }\n\n /** Returns true if a the parameter values are valid, according to the Param definitions */\n static validates(params: Param[], values: RawParams = {}): boolean {\n return params.map(param => param.validates(values[param.id])).reduce(allTrueR, true);\n }\n\n constructor(\n id: string,\n type: ParamType,\n config: ParamDeclaration,\n location: DefType,\n urlMatcherFactory: UrlMatcherFactory,\n ) {\n config = unwrapShorthand(config);\n type = getType(config, type, location, id, urlMatcherFactory.paramTypes);\n const arrayMode = getArrayMode();\n type = arrayMode ? type.$asArray(arrayMode, location === DefType.SEARCH) : type;\n const isOptional = config.value !== undefined || location === DefType.SEARCH;\n const dynamic = isDefined(config.dynamic) ? !!config.dynamic : !!type.dynamic;\n const raw = isDefined(config.raw) ? !!config.raw : !!type.raw;\n const squash = getSquashPolicy(config, isOptional, urlMatcherFactory.defaultSquashPolicy());\n const replace = getReplace(config, arrayMode, isOptional, squash);\n const inherit = isDefined(config.inherit) ? !!config.inherit : !!type.inherit;\n\n // array config: param name (param[]) overrides default settings. explicit config overrides param name.\n function getArrayMode() {\n const arrayDefaults = { array: location === DefType.SEARCH ? 'auto' : false };\n const arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n return extend(arrayDefaults, arrayParamNomenclature, config).array;\n }\n\n extend(this, { id, type, location, isOptional, dynamic, raw, squash, replace, inherit, array: arrayMode, config });\n }\n\n isDefaultValue(value: any): boolean {\n return this.isOptional && this.type.equals(this.value(), value);\n }\n\n /**\n * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n * default value, which may be the result of an injectable function.\n */\n value(value?: any): any {\n /**\n * [Internal] Get the default value of a parameter, which may be an injectable function.\n */\n const getDefaultValue = () => {\n if (this._defaultValueCache) return this._defaultValueCache.defaultValue;\n\n if (!services.$injector) throw new Error('Injectable functions cannot be called at configuration time');\n\n const defaultValue = services.$injector.invoke(this.config.$$fn);\n\n if (defaultValue !== null && defaultValue !== undefined && !this.type.is(defaultValue))\n throw new Error(\n `Default value (${defaultValue}) for parameter '${this.id}' is not an instance of ParamType (${\n this.type.name\n })`,\n );\n\n if (this.config.$$fn['__cacheable']) {\n this._defaultValueCache = { defaultValue };\n }\n\n return defaultValue;\n };\n\n const replaceSpecialValues = (val: any) => {\n for (const tuple of this.replace) {\n if (tuple.from === val) return tuple.to;\n }\n return val;\n };\n\n value = replaceSpecialValues(value);\n\n return isUndefined(value) ? getDefaultValue() : this.type.$normalize(value);\n }\n\n isSearch(): boolean {\n return this.location === DefType.SEARCH;\n }\n\n validates(value: any): boolean {\n // There was no parameter value, but the param is optional\n if ((isUndefined(value) || value === null) && this.isOptional) return true;\n\n // The value was not of the correct ParamType, and could not be decoded to the correct ParamType\n const normalized = this.type.$normalize(value);\n if (!this.type.is(normalized)) return false;\n\n // The value was of the correct type, but when encoded, did not match the ParamType's regexp\n const encoded = this.type.encode(normalized);\n return !(isString(encoded) && !this.type.pattern.exec(encoded));\n }\n\n toString() {\n return `{Param:${this.id} ${this.type} squash: '${this.squash}' optional: ${this.isOptional}}`;\n }\n}\n", + "/** @module path */ /** for typedoc */\nimport { extend, applyPairs, find, allTrueR, pairs, arrayTuples } from '../common/common';\nimport { propEq } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\n\n/**\n * @internalapi\n *\n * A node in a [[TreeChanges]] path\n *\n * For a [[TreeChanges]] path, this class holds the stateful information for a single node in the path.\n * Each PathNode corresponds to a state being entered, exited, or retained.\n * The stateful information includes parameter values and resolve data.\n */\nexport class PathNode {\n /** The state being entered, exited, or retained */\n public state: StateObject;\n /** The parameters declared on the state */\n public paramSchema: Param[];\n /** The parameter values that belong to the state */\n public paramValues: { [key: string]: any };\n /** The individual (stateful) resolvable objects that belong to the state */\n public resolvables: Resolvable[];\n /** The state's declared view configuration objects */\n public views: ViewConfig[];\n\n /**\n * Returns a clone of the PathNode\n * @deprecated use instance method `node.clone()`\n */\n static clone = (node: PathNode) => node.clone();\n\n /** Creates a copy of a PathNode */\n constructor(node: PathNode);\n /** Creates a new (empty) PathNode for a State */\n constructor(state: StateObject);\n constructor(stateOrNode: any) {\n if (stateOrNode instanceof PathNode) {\n const node: PathNode = stateOrNode;\n this.state = node.state;\n this.paramSchema = node.paramSchema.slice();\n this.paramValues = extend({}, node.paramValues);\n this.resolvables = node.resolvables.slice();\n this.views = node.views && node.views.slice();\n } else {\n const state: StateObject = stateOrNode;\n this.state = state;\n this.paramSchema = state.parameters({ inherit: false });\n this.paramValues = {};\n this.resolvables = state.resolvables.map(res => res.clone());\n }\n }\n\n clone() {\n return new PathNode(this);\n }\n\n /** Sets [[paramValues]] for the node, from the values of an object hash */\n applyRawParams(params: RawParams): PathNode {\n const getParamVal = (paramDef: Param) => [paramDef.id, paramDef.value(params[paramDef.id])];\n this.paramValues = this.paramSchema.reduce((memo, pDef) => applyPairs(memo, getParamVal(pDef)), {});\n return this;\n }\n\n /** Gets a specific [[Param]] metadata that belongs to the node */\n parameter(name: string): Param {\n return find(this.paramSchema, propEq('id', name));\n }\n\n /**\n * @returns true if the state and parameter values for another PathNode are\n * equal to the state and param values for this PathNode\n */\n equals(node: PathNode, paramsFn?: GetParamsFn): boolean {\n const diff = this.diff(node, paramsFn);\n return diff && diff.length === 0;\n }\n\n /**\n * Finds Params with different parameter values on another PathNode.\n *\n * Given another node (of the same state), finds the parameter values which differ.\n * Returns the [[Param]] (schema objects) whose parameter values differ.\n *\n * Given another node for a different state, returns `false`\n *\n * @param node The node to compare to\n * @param paramsFn A function that returns which parameters should be compared.\n * @returns The [[Param]]s which differ, or null if the two nodes are for different states\n */\n diff(node: PathNode, paramsFn?: GetParamsFn): Param[] | false {\n if (this.state !== node.state) return false;\n\n const params: Param[] = paramsFn ? paramsFn(this) : this.paramSchema;\n return Param.changed(params, this.paramValues, node.paramValues);\n }\n}\n\n/** @hidden */\nexport type GetParamsFn = (pathNode: PathNode) => Param[];\n", + "/** @module path */ /** for typedoc */\n\nimport {\n extend,\n find,\n pick,\n omit,\n tail,\n mergeR,\n values,\n unnestR,\n Predicate,\n inArray,\n arrayTuples,\n} from '../common/common';\nimport { prop, propEq, not } from '../common/hof';\n\nimport { RawParams } from '../params/interface';\nimport { TreeChanges } from '../transition/interface';\nimport { ViewConfig } from '../view/interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { GetParamsFn, PathNode } from './pathNode';\nimport { ViewService } from '../view/view';\nimport { Param } from '../params/param';\nimport { StateRegistry } from '../state';\n\n/**\n * This class contains functions which convert TargetStates, Nodes and paths from one type to another.\n */\nexport class PathUtils {\n /** Given a PathNode[], create an TargetState */\n static makeTargetState(registry: StateRegistry, path: PathNode[]): TargetState {\n const state = tail(path).state;\n return new TargetState(registry, state, path.map(prop('paramValues')).reduce(mergeR, {}), {});\n }\n\n static buildPath(targetState: TargetState) {\n const toParams = targetState.params();\n return targetState.$state().path.map(state => new PathNode(state).applyRawParams(toParams));\n }\n\n /** Given a fromPath: PathNode[] and a TargetState, builds a toPath: PathNode[] */\n static buildToPath(fromPath: PathNode[], targetState: TargetState): PathNode[] {\n const toPath: PathNode[] = PathUtils.buildPath(targetState);\n if (targetState.options().inherit) {\n return PathUtils.inheritParams(fromPath, toPath, Object.keys(targetState.params()));\n }\n return toPath;\n }\n\n /**\n * Creates ViewConfig objects and adds to nodes.\n *\n * On each [[PathNode]], creates ViewConfig objects from the views: property of the node's state\n */\n static applyViewConfigs($view: ViewService, path: PathNode[], states: StateObject[]) {\n // Only apply the viewConfigs to the nodes for the given states\n path.filter(node => inArray(states, node.state)).forEach(node => {\n const viewDecls: _ViewDeclaration[] = values(node.state.views || {});\n const subPath = PathUtils.subPath(path, n => n === node);\n const viewConfigs: ViewConfig[][] = viewDecls.map(view => $view.createViewConfig(subPath, view));\n node.views = viewConfigs.reduce(unnestR, []);\n });\n }\n\n /**\n * Given a fromPath and a toPath, returns a new to path which inherits parameters from the fromPath\n *\n * For a parameter in a node to be inherited from the from path:\n * - The toPath's node must have a matching node in the fromPath (by state).\n * - The parameter name must not be found in the toKeys parameter array.\n *\n * Note: the keys provided in toKeys are intended to be those param keys explicitly specified by some\n * caller, for instance, $state.transitionTo(..., toParams). If a key was found in toParams,\n * it is not inherited from the fromPath.\n */\n static inheritParams(fromPath: PathNode[], toPath: PathNode[], toKeys: string[] = []): PathNode[] {\n function nodeParamVals(path: PathNode[], state: StateObject): RawParams {\n const node: PathNode = find(path, propEq('state', state));\n return extend({}, node && node.paramValues);\n }\n\n const noInherit = fromPath\n .map(node => node.paramSchema)\n .reduce(unnestR, [])\n .filter(param => !param.inherit)\n .map(prop('id'));\n\n /**\n * Given an [[PathNode]] \"toNode\", return a new [[PathNode]] with param values inherited from the\n * matching node in fromPath. Only inherit keys that aren't found in \"toKeys\" from the node in \"fromPath\"\"\n */\n function makeInheritedParamsNode(toNode: PathNode): PathNode {\n // All param values for the node (may include default key/vals, when key was not found in toParams)\n let toParamVals = extend({}, toNode && toNode.paramValues);\n // limited to only those keys found in toParams\n const incomingParamVals = pick(toParamVals, toKeys);\n toParamVals = omit(toParamVals, toKeys);\n const fromParamVals = omit(nodeParamVals(fromPath, toNode.state) || {}, noInherit);\n // extend toParamVals with any fromParamVals, then override any of those those with incomingParamVals\n const ownParamVals: RawParams = extend(toParamVals, fromParamVals, incomingParamVals);\n return new PathNode(toNode.state).applyRawParams(ownParamVals);\n }\n\n // The param keys specified by the incoming toParams\n return toPath.map(makeInheritedParamsNode);\n }\n\n static nonDynamicParams = (node: PathNode): Param[] =>\n node.state.parameters({ inherit: false }).filter(param => !param.dynamic);\n\n /**\n * Computes the tree changes (entering, exiting) between a fromPath and toPath.\n */\n static treeChanges(fromPath: PathNode[], toPath: PathNode[], reloadState: StateObject): TreeChanges {\n const max = Math.min(fromPath.length, toPath.length);\n let keep = 0;\n\n const nodesMatch = (node1: PathNode, node2: PathNode) => node1.equals(node2, PathUtils.nonDynamicParams);\n\n while (keep < max && fromPath[keep].state !== reloadState && nodesMatch(fromPath[keep], toPath[keep])) {\n keep++;\n }\n\n /** Given a retained node, return a new node which uses the to node's param values */\n function applyToParams(retainedNode: PathNode, idx: number): PathNode {\n const cloned = retainedNode.clone();\n cloned.paramValues = toPath[idx].paramValues;\n return cloned;\n }\n\n let from: PathNode[], retained: PathNode[], exiting: PathNode[], entering: PathNode[], to: PathNode[];\n\n from = fromPath;\n retained = from.slice(0, keep);\n exiting = from.slice(keep);\n\n // Create a new retained path (with shallow copies of nodes) which have the params of the toPath mapped\n const retainedWithToParams = retained.map(applyToParams);\n entering = toPath.slice(keep);\n to = retainedWithToParams.concat(entering);\n\n return { from, to, retained, retainedWithToParams, exiting, entering };\n }\n\n /**\n * Returns a new path which is: the subpath of the first path which matches the second path.\n *\n * The new path starts from root and contains any nodes that match the nodes in the second path.\n * It stops before the first non-matching node.\n *\n * Nodes are compared using their state property and their parameter values.\n * If a `paramsFn` is provided, only the [[Param]] returned by the function will be considered when comparing nodes.\n *\n * @param pathA the first path\n * @param pathB the second path\n * @param paramsFn a function which returns the parameters to consider when comparing\n *\n * @returns an array of PathNodes from the first path which match the nodes in the second path\n */\n static matching(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): PathNode[] {\n let done = false;\n const tuples: PathNode[][] = arrayTuples(pathA, pathB);\n return tuples.reduce((matching, [nodeA, nodeB]) => {\n done = done || !nodeA.equals(nodeB, paramsFn);\n return done ? matching : matching.concat(nodeA);\n }, []);\n }\n\n /**\n * Returns true if two paths are identical.\n *\n * @param pathA\n * @param pathB\n * @param paramsFn a function which returns the parameters to consider when comparing\n * @returns true if the the states and parameter values for both paths are identical\n */\n static equals(pathA: PathNode[], pathB: PathNode[], paramsFn?: GetParamsFn): boolean {\n return pathA.length === pathB.length && PathUtils.matching(pathA, pathB, paramsFn).length === pathA.length;\n }\n\n /**\n * Return a subpath of a path, which stops at the first matching node\n *\n * Given an array of nodes, returns a subset of the array starting from the first node,\n * stopping when the first node matches the predicate.\n *\n * @param path a path of [[PathNode]]s\n * @param predicate a [[Predicate]] fn that matches [[PathNode]]s\n * @returns a subpath up to the matching node, or undefined if no match is found\n */\n static subPath(path: PathNode[], predicate: Predicate): PathNode[] {\n const node = find(path, predicate);\n const elementIdx = path.indexOf(node);\n return elementIdx === -1 ? undefined : path.slice(0, elementIdx + 1);\n }\n\n /** Gets the raw parameter values from a path */\n static paramValues = (path: PathNode[]) => path.reduce((acc, node) => extend(acc, node.paramValues), {});\n}\n", + "/**\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { extend, equals, inArray, identity } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { trace } from '../common/trace';\nimport { ResolvePolicy, ResolvableLiteral, resolvePolicies } from './interface';\n\nimport { ResolveContext } from './resolveContext';\nimport { stringify } from '../common/strings';\nimport { isFunction, isObject } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { StateObject } from '../state/stateObject';\nimport { PathNode } from '../path/pathNode';\nimport { isNullOrUndefined } from '../common/predicates';\n\n// TODO: explicitly make this user configurable\nexport let defaultResolvePolicy: ResolvePolicy = {\n when: 'LAZY',\n async: 'WAIT',\n};\n\n/**\n * The basic building block for the resolve system.\n *\n * Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise),\n * and the unwrapped-when-complete (.data) result of the resolveFn.\n *\n * Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the\n * resolveFn) and returns the resulting promise.\n *\n * Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first\n * parameter to those fns.\n */\nexport class Resolvable implements ResolvableLiteral {\n token: any;\n policy: ResolvePolicy;\n resolveFn: Function;\n deps: any[];\n\n data: any;\n resolved = false;\n promise: Promise = undefined;\n\n static fromData = (token: any, data: any) => new Resolvable(token, () => data, null, null, data);\n\n /** This constructor creates a Resolvable copy */\n constructor(resolvable: Resolvable);\n\n /** This constructor creates a new Resolvable from the plain old [[ResolvableLiteral]] javascript object */\n constructor(resolvable: ResolvableLiteral);\n\n /**\n * This constructor creates a new `Resolvable`\n *\n * #### Example:\n * ```js\n * var resolvable1 = new Resolvable('mytoken', http => http.get('foo.json').toPromise(), [Http]);\n *\n * var resolvable2 = new Resolvable(UserService, dep => new UserService(dep.data), [SomeDependency]);\n *\n * var resolvable1Clone = new Resolvable(resolvable1);\n * ```\n *\n * @param token The new resolvable's injection token, such as `\"userList\"` (a string) or `UserService` (a class).\n * When this token is used during injection, the resolved value will be injected.\n * @param resolveFn The function that returns the resolved value, or a promise for the resolved value\n * @param deps An array of dependencies, which will be injected into the `resolveFn`\n * @param policy the [[ResolvePolicy]] defines when and how the Resolvable is processed\n * @param data Pre-resolved data. If the resolve value is already known, it may be provided here.\n */\n constructor(token: any, resolveFn: Function, deps?: any[], policy?: ResolvePolicy, data?: any);\n constructor(arg1: any, resolveFn?: Function, deps?: any[], policy?: ResolvePolicy, data?: any) {\n if (arg1 instanceof Resolvable) {\n extend(this, arg1);\n } else if (isFunction(resolveFn)) {\n if (isNullOrUndefined(arg1)) throw new Error('new Resolvable(): token argument is required');\n if (!isFunction(resolveFn)) throw new Error('new Resolvable(): resolveFn argument must be a function');\n\n this.token = arg1;\n this.policy = policy;\n this.resolveFn = resolveFn;\n this.deps = deps || [];\n\n this.data = data;\n this.resolved = data !== undefined;\n this.promise = this.resolved ? services.$q.when(this.data) : undefined;\n } else if (isObject(arg1) && arg1.token && (arg1.hasOwnProperty('resolveFn') || arg1.hasOwnProperty('data'))) {\n const literal = arg1;\n return new Resolvable(literal.token, literal.resolveFn, literal.deps, literal.policy, literal.data);\n }\n }\n\n getPolicy(state: StateObject): ResolvePolicy {\n const thisPolicy = this.policy || {};\n const statePolicy = (state && state.resolvePolicy) || {};\n return {\n when: thisPolicy.when || statePolicy.when || defaultResolvePolicy.when,\n async: thisPolicy.async || statePolicy.async || defaultResolvePolicy.async,\n };\n }\n\n /**\n * Asynchronously resolve this Resolvable's data\n *\n * Given a ResolveContext that this Resolvable is found in:\n * Wait for this Resolvable's dependencies, then invoke this Resolvable's function\n * and update the Resolvable's state\n */\n resolve(resolveContext: ResolveContext, trans?: Transition) {\n const $q = services.$q;\n\n // Gets all dependencies from ResolveContext and wait for them to be resolved\n const getResolvableDependencies = () =>\n $q.all(resolveContext.getDependencies(this).map(resolvable => resolvable.get(resolveContext, trans))) as Promise<\n any[]\n >;\n\n // Invokes the resolve function passing the resolved dependencies as arguments\n const invokeResolveFn = (resolvedDeps: any[]) => this.resolveFn.apply(null, resolvedDeps);\n\n /**\n * For RXWAIT policy:\n *\n * Given an observable returned from a resolve function:\n * - enables .cache() mode (this allows multicast subscribers)\n * - then calls toPromise() (this triggers subscribe() and thus fetches)\n * - Waits for the promise, then return the cached observable (not the first emitted value).\n */\n const waitForRx = (observable$: any) => {\n const cached = observable$.cache(1);\n return cached\n .take(1)\n .toPromise()\n .then(() => cached);\n };\n\n // If the resolve policy is RXWAIT, wait for the observable to emit something. otherwise pass through.\n const node: PathNode = resolveContext.findNode(this);\n const state: StateObject = node && node.state;\n const maybeWaitForRx = this.getPolicy(state).async === 'RXWAIT' ? waitForRx : identity;\n\n // After the final value has been resolved, update the state of the Resolvable\n const applyResolvedValue = (resolvedValue: any) => {\n this.data = resolvedValue;\n this.resolved = true;\n this.resolveFn = null;\n trace.traceResolvableResolved(this, trans);\n return this.data;\n };\n\n // Sets the promise property first, then getsResolvableDependencies in the context of the promise chain. Always waits one tick.\n return (this.promise = $q\n .when()\n .then(getResolvableDependencies)\n .then(invokeResolveFn)\n .then(maybeWaitForRx)\n .then(applyResolvedValue));\n }\n\n /**\n * Gets a promise for this Resolvable's data.\n *\n * Fetches the data and returns a promise.\n * Returns the existing promise if it has already been fetched once.\n */\n get(resolveContext: ResolveContext, trans?: Transition): Promise {\n return this.promise || this.resolve(resolveContext, trans);\n }\n\n toString() {\n return `Resolvable(token: ${stringify(this.token)}, requires: [${this.deps.map(stringify)}])`;\n }\n\n clone(): Resolvable {\n return new Resolvable(this);\n }\n}\n", + "/**\n * # The Resolve subsystem\n *\n * This subsystem is an asynchronous, hierarchical Dependency Injection system.\n *\n * Typically, resolve is configured on a state using a [[StateDeclaration.resolve]] declaration.\n *\n * @coreapi\n * @module resolve\n */ /** for typedoc */\nimport { Resolvable } from './resolvable';\n\n/**\n * An interface which is similar to an Angular 2 `Provider`\n */\nexport interface ProviderLike {\n provide: any;\n useClass?: any;\n useFactory?: Function;\n useValue?: any;\n useExisting?: any;\n deps?: any[];\n}\n\n/**\n * A plain object used to describe a [[Resolvable]]\n *\n * These objects may be used in the [[StateDeclaration.resolve]] array to declare\n * async data that the state or substates require.\n *\n * #### Example:\n * ```js\n *\n * var state = {\n * name: 'main',\n * resolve: [\n * { token: 'myData', deps: [MyDataApi], resolveFn: (myDataApi) => myDataApi.getData() },\n * ],\n * }\n * ```\n */\nexport interface ResolvableLiteral {\n /**\n * A Dependency Injection token\n *\n * This Resolvable's DI token.\n * The Resolvable will be injectable elsewhere using the token.\n */\n token: any;\n\n /**\n * A function which fetches the Resolvable's data\n *\n * A function which returns one of:\n *\n * - The resolved value (synchronously)\n * - A promise for the resolved value\n * - An Observable of the resolved value(s)\n *\n * This function will be provided the dependencies listed in [[deps]] as its arguments.\n * The resolve system will asynchronously fetch the dependencies before invoking this function.\n */\n resolveFn: Function;\n\n /**\n * Defines the Resolve Policy\n *\n * A policy that defines when to invoke the resolve,\n * and whether to wait for async and unwrap the data\n */\n policy?: ResolvePolicy;\n\n /**\n * The Dependency Injection tokens\n *\n * This is an array of Dependency Injection tokens for the dependencies of the [[resolveFn]].\n *\n * The DI tokens are references to other `Resolvables`, or to other\n * services from the native DI system.\n */\n deps?: any[];\n\n /** Pre-resolved data. */\n data?: any;\n}\n\n/**\n * Defines how a resolve is processed during a transition\n *\n * This object is the [[StateDeclaration.resolvePolicy]] property.\n *\n * #### Example:\n * ```js\n * // Fetched when the resolve's state is being entered.\n * // Wait for the promise to resolve.\n * var policy1 = { when: \"LAZY\", async: \"WAIT\" }\n *\n * // Fetched when the Transition is starting.\n * // Do not wait for the returned promise to resolve.\n * // Inject the raw promise/value\n * var policy2 = { when: \"EAGER\", async: \"NOWAIT\" }\n * ```\n *\n * The policy for a given Resolvable is merged from three sources (highest priority first):\n *\n * - 1) Individual resolve definition\n * - 2) State definition\n * - 3) Global default\n *\n * #### Example:\n * ```js\n * // Wait for an Observable to emit one item.\n * // Since `wait` is not specified, it uses the `wait`\n * // policy defined on the state, or the global default\n * // if no `wait` policy is defined on the state\n * var myResolvablePolicy = { async: \"RXWAIT\" }\n * ```\n */\nexport interface ResolvePolicy {\n /**\n * Defines when a Resolvable is resolved (fetched) during a transition\n *\n * - `LAZY` (default)\n * - Resolved as the resolve's state is being entered\n * - `EAGER`\n * - Resolved as the transition is starting\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched when each state is entered.\n * All of `main` resolves are processed before fetching `main.home` resolves.\n * ```js\n * var state = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n *\n * var state = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'LAZY' }, // default\n * }\n * ```\n *\n * #### Example:\n * Resolves for `main` and `main.home` are fetched at the same time when the transition starts.\n * This happens earlier in the lifecycle than when states are entered.\n * All of the `main` and `main.home` resolves are fetched as soon as possible.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n *\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { when: 'EAGER' },\n * }\n * ```\n */\n when?: PolicyWhen;\n\n /**\n * Determines the unwrapping behavior of asynchronous resolve values.\n *\n * - `WAIT` (default)\n * - If a promise is returned from the resolveFn, wait for the promise before proceeding\n * - The unwrapped value from the promise\n * - `NOWAIT`\n * - If a promise is returned from the resolve, do not wait for the promise.\n * - Any other value returned is wrapped in a promise.\n * - The promise will not be unwrapped.\n * - The promise itself will be provided when the resolve is injected or bound elsewhere.\n * - `RXWAIT`\n * - When an Observable is returned from the resolveFn, wait until the Observable emits at least one item.\n * - The Observable item will not be unwrapped.\n * - The Observable stream itself will be provided when the resolve is injected or bound elsewhere.\n *\n * #### Example:\n * The `Transition` will not wait for the resolve promise(s) from `main` to settle before continuing.\n * Resolves for `main` will be provided to components wrapped in a `Promise`.\n *\n * The `Transition` will wait for the `main.home` resolve promises.\n * Resolved values will be unwrapped before being provided to components.\n * ```js\n * var mainState = {\n * name: 'main',\n * resolve: mainResolves, // defined elsewhere\n * resolvePolicy: { async: 'NOWAIT' },\n * }\n * var homeState = {\n * name: 'main.home',\n * resolve: homeResolves, // defined elsewhere\n * resolvePolicy: { async: 'WAIT' }, // default\n * }\n * ```\n */\n async?: PolicyAsync;\n}\n\nexport type PolicyWhen = 'LAZY' | 'EAGER';\nexport type PolicyAsync = 'WAIT' | 'NOWAIT' | 'RXWAIT';\n\n/** @internalapi */\nexport let resolvePolicies = {\n when: {\n LAZY: 'LAZY',\n EAGER: 'EAGER',\n },\n async: {\n WAIT: 'WAIT',\n NOWAIT: 'NOWAIT',\n RXWAIT: 'RXWAIT',\n },\n};\n", + "/** @module resolve */\n/** for typedoc */\nimport { find, tail, uniqR, unnestR, inArray } from '../common/common';\nimport { propEq, not } from '../common/hof';\nimport { trace } from '../common/trace';\nimport { services, $InjectorLike } from '../common/coreservices';\nimport { resolvePolicies, PolicyWhen, ResolvePolicy } from './interface';\nimport { PathNode } from '../path/pathNode';\nimport { Resolvable } from './resolvable';\nimport { StateObject } from '../state/stateObject';\nimport { PathUtils } from '../path/pathUtils';\nimport { stringify } from '../common/strings';\nimport { Transition } from '../transition/transition';\nimport { UIInjector } from '../interface';\nimport { isUndefined } from '../common';\n\nconst whens = resolvePolicies.when;\nconst ALL_WHENS = [whens.EAGER, whens.LAZY];\nconst EAGER_WHENS = [whens.EAGER];\n\n// tslint:disable-next-line:no-inferrable-types\nexport const NATIVE_INJECTOR_TOKEN: string = 'Native Injector';\n\n/**\n * Encapsulates Dependency Injection for a path of nodes\n *\n * UI-Router states are organized as a tree.\n * A nested state has a path of ancestors to the root of the tree.\n * When a state is being activated, each element in the path is wrapped as a [[PathNode]].\n * A `PathNode` is a stateful object that holds things like parameters and resolvables for the state being activated.\n *\n * The ResolveContext closes over the [[PathNode]]s, and provides DI for the last node in the path.\n */\nexport class ResolveContext {\n _injector: UIInjector;\n\n constructor(private _path: PathNode[]) {}\n\n /** Gets all the tokens found in the resolve context, de-duplicated */\n getTokens(): any[] {\n return this._path.reduce((acc, node) => acc.concat(node.resolvables.map(r => r.token)), []).reduce(uniqR, []);\n }\n\n /**\n * Gets the Resolvable that matches the token\n *\n * Gets the last Resolvable that matches the token in this context, or undefined.\n * Throws an error if it doesn't exist in the ResolveContext\n */\n getResolvable(token: any): Resolvable {\n const matching = this._path\n .map(node => node.resolvables)\n .reduce(unnestR, [])\n .filter((r: Resolvable) => r.token === token);\n return tail(matching);\n }\n\n /** Returns the [[ResolvePolicy]] for the given [[Resolvable]] */\n getPolicy(resolvable: Resolvable): ResolvePolicy {\n const node = this.findNode(resolvable);\n return resolvable.getPolicy(node.state);\n }\n\n /**\n * Returns a ResolveContext that includes a portion of this one\n *\n * Given a state, this method creates a new ResolveContext from this one.\n * The new context starts at the first node (root) and stops at the node for the `state` parameter.\n *\n * #### Why\n *\n * When a transition is created, the nodes in the \"To Path\" are injected from a ResolveContext.\n * A ResolveContext closes over a path of [[PathNode]]s and processes the resolvables.\n * The \"To State\" can inject values from its own resolvables, as well as those from all its ancestor state's (node's).\n * This method is used to create a narrower context when injecting ancestor nodes.\n *\n * @example\n * `let ABCD = new ResolveContext([A, B, C, D]);`\n *\n * Given a path `[A, B, C, D]`, where `A`, `B`, `C` and `D` are nodes for states `a`, `b`, `c`, `d`:\n * When injecting `D`, `D` should have access to all resolvables from `A`, `B`, `C`, `D`.\n * However, `B` should only be able to access resolvables from `A`, `B`.\n *\n * When resolving for the `B` node, first take the full \"To Path\" Context `[A,B,C,D]` and limit to the subpath `[A,B]`.\n * `let AB = ABCD.subcontext(a)`\n */\n subContext(state: StateObject): ResolveContext {\n return new ResolveContext(PathUtils.subPath(this._path, node => node.state === state));\n }\n\n /**\n * Adds Resolvables to the node that matches the state\n *\n * This adds a [[Resolvable]] (generally one created on the fly; not declared on a [[StateDeclaration.resolve]] block).\n * The resolvable is added to the node matching the `state` parameter.\n *\n * These new resolvables are not automatically fetched.\n * The calling code should either fetch them, fetch something that depends on them,\n * or rely on [[resolvePath]] being called when some state is being entered.\n *\n * Note: each resolvable's [[ResolvePolicy]] is merged with the state's policy, and the global default.\n *\n * @param newResolvables the new Resolvables\n * @param state Used to find the node to put the resolvable on\n */\n addResolvables(newResolvables: Resolvable[], state: StateObject) {\n const node = find(this._path, propEq('state', state));\n const keys = newResolvables.map(r => r.token);\n node.resolvables = node.resolvables.filter(r => keys.indexOf(r.token) === -1).concat(newResolvables);\n }\n\n /**\n * Returns a promise for an array of resolved path Element promises\n *\n * @param when\n * @param trans\n * @returns {Promise|any}\n */\n resolvePath(when: PolicyWhen = 'LAZY', trans?: Transition): Promise<{ token: any; value: any }[]> {\n // This option determines which 'when' policy Resolvables we are about to fetch.\n const whenOption: string = inArray(ALL_WHENS, when) ? when : 'LAZY';\n // If the caller specified EAGER, only the EAGER Resolvables are fetched.\n // if the caller specified LAZY, both EAGER and LAZY Resolvables are fetched.`\n const matchedWhens = whenOption === resolvePolicies.when.EAGER ? EAGER_WHENS : ALL_WHENS;\n\n // get the subpath to the state argument, if provided\n trace.traceResolvePath(this._path, when, trans);\n\n const matchesPolicy = (acceptedVals: string[], whenOrAsync: 'when' | 'async') => (resolvable: Resolvable) =>\n inArray(acceptedVals, this.getPolicy(resolvable)[whenOrAsync]);\n\n // Trigger all the (matching) Resolvables in the path\n // Reduce all the \"WAIT\" Resolvables into an array\n const promises: Promise[] = this._path.reduce((acc, node) => {\n const nodeResolvables = node.resolvables.filter(matchesPolicy(matchedWhens, 'when'));\n const nowait = nodeResolvables.filter(matchesPolicy(['NOWAIT'], 'async'));\n const wait = nodeResolvables.filter(not(matchesPolicy(['NOWAIT'], 'async')));\n\n // For the matching Resolvables, start their async fetch process.\n const subContext = this.subContext(node.state);\n const getResult = (r: Resolvable) =>\n r\n .get(subContext, trans)\n // Return a tuple that includes the Resolvable's token\n .then(value => ({ token: r.token, value: value }));\n nowait.forEach(getResult);\n return acc.concat(wait.map(getResult));\n }, []);\n\n // Wait for all the \"WAIT\" resolvables\n return services.$q.all(promises);\n }\n\n injector(): UIInjector {\n return this._injector || (this._injector = new UIInjectorImpl(this));\n }\n\n findNode(resolvable: Resolvable): PathNode {\n return find(this._path, (node: PathNode) => inArray(node.resolvables, resolvable));\n }\n\n /**\n * Gets the async dependencies of a Resolvable\n *\n * Given a Resolvable, returns its dependencies as a Resolvable[]\n */\n getDependencies(resolvable: Resolvable): Resolvable[] {\n const node = this.findNode(resolvable);\n // Find which other resolvables are \"visible\" to the `resolvable` argument\n // subpath stopping at resolvable's node, or the whole path (if the resolvable isn't in the path)\n const subPath: PathNode[] = PathUtils.subPath(this._path, x => x === node) || this._path;\n const availableResolvables: Resolvable[] = subPath\n .reduce((acc, _node) => acc.concat(_node.resolvables), []) // all of subpath's resolvables\n .filter(res => res !== resolvable); // filter out the `resolvable` argument\n\n const getDependency = (token: any) => {\n const matching = availableResolvables.filter(r => r.token === token);\n if (matching.length) return tail(matching);\n\n const fromInjector = this.injector().getNative(token);\n if (isUndefined(fromInjector)) {\n throw new Error('Could not find Dependency Injection token: ' + stringify(token));\n }\n\n return new Resolvable(token, () => fromInjector, [], fromInjector);\n };\n\n return resolvable.deps.map(getDependency);\n }\n}\n\nclass UIInjectorImpl implements UIInjector {\n native: $InjectorLike;\n\n constructor(public context: ResolveContext) {\n this.native = this.get(NATIVE_INJECTOR_TOKEN) || services.$injector;\n }\n\n get(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) {\n if (this.context.getPolicy(resolvable).async === 'NOWAIT') {\n return resolvable.get(this.context);\n }\n\n if (!resolvable.resolved) {\n throw new Error('Resolvable async .get() not complete:' + stringify(resolvable.token));\n }\n return resolvable.data;\n }\n\n return this.getNative(token);\n }\n\n getAsync(token: any) {\n const resolvable = this.context.getResolvable(token);\n if (resolvable) return resolvable.get(this.context);\n return services.$q.when(this.native.get(token));\n }\n\n getNative(token: any) {\n return this.native && this.native.get(token);\n }\n}\n", + "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport { trace } from '../common/trace';\nimport { services } from '../common/coreservices';\nimport { stringify } from '../common/strings';\nimport { map, find, extend, mergeR, tail, omit, arrayTuples, unnestR, identity, anyTrueR } from '../common/common';\nimport { isObject, isUndefined } from '../common/predicates';\nimport { prop, propEq, val, not, is } from '../common/hof';\nimport { StateDeclaration, StateOrName } from '../state/interface';\nimport {\n TransitionOptions,\n TreeChanges,\n IHookRegistry,\n TransitionHookPhase,\n RegisteredHooks,\n HookRegOptions,\n HookMatchCriteria,\n TransitionStateHookFn,\n TransitionHookFn,\n} from './interface'; // has or is using\nimport { TransitionHook } from './transitionHook';\nimport { matchState, makeEvent, RegisteredHook } from './hookRegistry';\nimport { HookBuilder } from './hookBuilder';\nimport { PathNode } from '../path/pathNode';\nimport { PathUtils } from '../path/pathUtils';\nimport { StateObject } from '../state/stateObject';\nimport { TargetState } from '../state/targetState';\nimport { Param } from '../params/param';\nimport { Resolvable } from '../resolve/resolvable';\nimport { ViewConfig } from '../view/interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { RawParams } from '../params/interface';\nimport { ResolvableLiteral } from '../resolve/interface';\nimport { Rejection } from './rejectFactory';\n\n/** @hidden */\nconst stateSelf: (_state: StateObject) => StateDeclaration = prop('self');\n\n/**\n * Represents a transition between two states.\n *\n * When navigating to a state, we are transitioning **from** the current state **to** the new state.\n *\n * This object contains all contextual information about the to/from states, parameters, resolves.\n * It has information about all states being entered and exited as a result of the transition.\n */\nexport class Transition implements IHookRegistry {\n /** @hidden */\n static diToken = Transition;\n\n /**\n * A unique identifier for the transition.\n *\n * This is an auto incrementing integer, starting from `0`.\n */\n $id: number;\n\n /**\n * A reference to the [[UIRouter]] instance\n *\n * This reference can be used to access the router services, such as the [[StateService]]\n */\n router: UIRouter;\n\n /** @hidden */\n private _deferred = services.$q.defer();\n /**\n * This promise is resolved or rejected based on the outcome of the Transition.\n *\n * When the transition is successful, the promise is resolved\n * When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error\n */\n promise: Promise = this._deferred.promise;\n /**\n * A boolean which indicates if the transition was successful\n *\n * After a successful transition, this value is set to true.\n * After an unsuccessful transition, this value is set to false.\n *\n * The value will be undefined if the transition is not complete\n */\n success: boolean;\n /** @hidden */\n _aborted: boolean;\n /** @hidden */\n private _error: Rejection;\n\n /** @hidden Holds the hook registration functions such as those passed to Transition.onStart() */\n _registeredHooks: RegisteredHooks = {};\n\n /** @hidden */\n private _options: TransitionOptions;\n /** @hidden */\n private _treeChanges: TreeChanges;\n /** @hidden */\n private _targetState: TargetState;\n /** @hidden */\n private _hookBuilder = new HookBuilder(this);\n\n /** @hidden */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n\n /** @hidden\n * Creates the transition-level hook registration functions\n * (which can then be used to register hooks)\n */\n private createTransitionHookRegFns() {\n this.router.transitionService._pluginapi\n ._getEvents()\n .filter(type => type.hookPhase !== TransitionHookPhase.CREATE)\n .forEach(type => makeEvent(this, this.router.transitionService, type));\n }\n\n /** @internalapi */\n getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /**\n * Creates a new Transition object.\n *\n * If the target state is not valid, an error is thrown.\n *\n * @internalapi\n *\n * @param fromPath The path of [[PathNode]]s from which the transition is leaving. The last node in the `fromPath`\n * encapsulates the \"from state\".\n * @param targetState The target state and parameters being transitioned to (also, the transition options)\n * @param router The [[UIRouter]] instance\n */\n constructor(fromPath: PathNode[], targetState: TargetState, router: UIRouter) {\n this.router = router;\n this._targetState = targetState;\n\n if (!targetState.valid()) {\n throw new Error(targetState.error());\n }\n\n // current() is assumed to come from targetState.options, but provide a naive implementation otherwise.\n this._options = extend({ current: val(this) }, targetState.options());\n this.$id = router.transitionService._transitionCount++;\n const toPath = PathUtils.buildToPath(fromPath, targetState);\n this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState);\n this.createTransitionHookRegFns();\n\n const onCreateHooks = this._hookBuilder.buildHooksForPhase(TransitionHookPhase.CREATE);\n TransitionHook.invokeHooks(onCreateHooks, () => null);\n\n this.applyViewConfigs(router);\n }\n\n private applyViewConfigs(router: UIRouter) {\n const enteringStates = this._treeChanges.entering.map(node => node.state);\n PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates);\n }\n\n /**\n * @internalapi\n *\n * @returns the internal from [State] object\n */\n $from() {\n return tail(this._treeChanges.from).state;\n }\n\n /**\n * @internalapi\n *\n * @returns the internal to [State] object\n */\n $to() {\n return tail(this._treeChanges.to).state;\n }\n\n /**\n * Returns the \"from state\"\n *\n * Returns the state that the transition is coming *from*.\n *\n * @returns The state declaration object for the Transition's (\"from state\").\n */\n from(): StateDeclaration {\n return this.$from().self;\n }\n\n /**\n * Returns the \"to state\"\n *\n * Returns the state that the transition is going *to*.\n *\n * @returns The state declaration object for the Transition's target state (\"to state\").\n */\n to(): StateDeclaration {\n return this.$to().self;\n }\n\n /**\n * Gets the Target State\n *\n * A transition's [[TargetState]] encapsulates the [[to]] state, the [[params]], and the [[options]] as a single object.\n *\n * @returns the [[TargetState]] of this Transition\n */\n targetState() {\n return this._targetState;\n }\n\n /**\n * Determines whether two transitions are equivalent.\n * @deprecated\n */\n is(compare: Transition | { to?: any; from?: any }): boolean {\n if (compare instanceof Transition) {\n // TODO: Also compare parameters\n return this.is({ to: compare.$to().name, from: compare.$from().name });\n }\n return !(\n (compare.to && !matchState(this.$to(), compare.to)) ||\n (compare.from && !matchState(this.$from(), compare.from))\n );\n }\n\n /**\n * Gets transition parameter values\n *\n * Returns the parameter values for a transition as key/value pairs.\n * This object is immutable.\n *\n * By default, returns the new parameter values (for the \"to state\").\n *\n * #### Example:\n * ```js\n * var toParams = transition.params();\n * ```\n *\n * To return the previous parameter values, supply `'from'` as the `pathname` argument.\n *\n * #### Example:\n * ```js\n * var fromParams = transition.params('from');\n * ```\n *\n * @param pathname the name of the treeChanges path to get parameter values for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n *\n * @returns transition parameter values for the desired path.\n */\n params(pathname?: string): { [paramName: string]: any };\n params(pathname?: string): T;\n params(pathname = 'to') {\n return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {}));\n }\n\n /**\n * Creates a [[UIInjector]] Dependency Injector\n *\n * Returns a Dependency Injector for the Transition's target state (to state).\n * The injector provides resolve values which the target state has access to.\n *\n * The `UIInjector` can also provide values from the native root/global injector (ng1/ng2).\n *\n * #### Example:\n * ```js\n * .onEnter({ entering: 'myState' }, trans => {\n * var myResolveValue = trans.injector().get('myResolve');\n * // Inject a global service from the global/native injector (if it exists)\n * var MyService = trans.injector().get('MyService');\n * })\n * ```\n *\n * In some cases (such as `onBefore`), you may need access to some resolve data but it has not yet been fetched.\n * You can use [[UIInjector.getAsync]] to get a promise for the data.\n * #### Example:\n * ```js\n * .onBefore({}, trans => {\n * return trans.injector().getAsync('myResolve').then(myResolveValue =>\n * return myResolveValue !== 'ABORT';\n * });\n * });\n * ```\n *\n * If a `state` is provided, the injector that is returned will be limited to resolve values that the provided state has access to.\n * This can be useful if both a parent state `foo` and a child state `foo.bar` have both defined a resolve such as `data`.\n * #### Example:\n * ```js\n * .onEnter({ to: 'foo.bar' }, trans => {\n * // returns result of `foo` state's `myResolve` resolve\n * // even though `foo.bar` also has a `myResolve` resolve\n * var fooData = trans.injector('foo').get('myResolve');\n * });\n * ```\n *\n * If you need resolve data from the exiting states, pass `'from'` as `pathName`.\n * The resolve data from the `from` path will be returned.\n * #### Example:\n * ```js\n * .onExit({ exiting: 'foo.bar' }, trans => {\n * // Gets the resolve value of `myResolve` from the state being exited\n * var fooData = trans.injector(null, 'from').get('myResolve');\n * });\n * ```\n *\n *\n * @param state Limits the resolves provided to only the resolves the provided state has access to.\n * @param pathName Default: `'to'`: Chooses the path for which to create the injector. Use this to access resolves for `exiting` states.\n *\n * @returns a [[UIInjector]]\n */\n injector(state?: StateOrName, pathName = 'to'): UIInjector {\n let path: PathNode[] = this._treeChanges[pathName];\n if (state) path = PathUtils.subPath(path, node => node.state === state || node.state.name === state);\n return new ResolveContext(path).injector();\n }\n\n /**\n * Gets all available resolve tokens (keys)\n *\n * This method can be used in conjunction with [[injector]] to inspect the resolve values\n * available to the Transition.\n *\n * This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states\n * in the Transition's [[TreeChanges.to]] path.\n *\n * #### Example:\n * This example logs all resolve values\n * ```js\n * let tokens = trans.getResolveTokens();\n * tokens.forEach(token => console.log(token + \" = \" + trans.injector().get(token)));\n * ```\n *\n * #### Example:\n * This example creates promises for each resolve value.\n * This triggers fetches of resolves (if any have not yet been fetched).\n * When all promises have all settled, it logs the resolve values.\n * ```js\n * let tokens = trans.getResolveTokens();\n * let promise = tokens.map(token => trans.injector().getAsync(token));\n * Promise.all(promises).then(values => console.log(\"Resolved values: \" + values));\n * ```\n *\n * Note: Angular 1 users whould use `$q.all()`\n *\n * @param pathname resolve context's path name (e.g., `to` or `from`)\n *\n * @returns an array of resolve tokens (keys)\n */\n getResolveTokens(pathname = 'to'): any[] {\n return new ResolveContext(this._treeChanges[pathname]).getTokens();\n }\n\n /**\n * Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.\n *\n * Allows a transition hook to dynamically add a Resolvable to this Transition.\n *\n * Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).\n *\n * If a `state` argument is provided, the Resolvable is processed when that state is being entered.\n * If no `state` is provided then the root state is used.\n * If the given `state` has already been entered, the Resolvable is processed when any child state is entered.\n * If no child states will be entered, the Resolvable is processed during the `onFinish` phase of the Transition.\n *\n * The `state` argument also scopes the resolved data.\n * The resolved data is available from the injector for that `state` and any children states.\n *\n * #### Example:\n * ```js\n * transitionService.onBefore({}, transition => {\n * transition.addResolvable({\n * token: 'myResolve',\n * deps: ['MyService'],\n * resolveFn: myService => myService.getData()\n * });\n * });\n * ```\n *\n * @param resolvable a [[ResolvableLiteral]] object (or a [[Resolvable]])\n * @param state the state in the \"to path\" which should receive the new resolve (otherwise, the root state)\n */\n addResolvable(resolvable: Resolvable | ResolvableLiteral, state: StateOrName = ''): void {\n resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable);\n\n const stateName: string = typeof state === 'string' ? state : state.name;\n const topath = this._treeChanges.to;\n const targetNode = find(topath, node => node.state.name === stateName);\n const resolveContext: ResolveContext = new ResolveContext(topath);\n resolveContext.addResolvables([resolvable as Resolvable], targetNode.state);\n }\n\n /**\n * Gets the transition from which this transition was redirected.\n *\n * If the current transition is a redirect, this method returns the transition that was redirected.\n *\n * #### Example:\n * ```js\n * let transitionA = $state.go('A').transition\n * transitionA.onStart({}, () => $state.target('B'));\n * $transitions.onSuccess({ to: 'B' }, (trans) => {\n * trans.to().name === 'B'; // true\n * trans.redirectedFrom() === transitionA; // true\n * });\n * ```\n *\n * @returns The previous Transition, or null if this Transition is not the result of a redirection\n */\n redirectedFrom(): Transition {\n return this._options.redirectedFrom || null;\n }\n\n /**\n * Gets the original transition in a redirect chain\n *\n * A transition might belong to a long chain of multiple redirects.\n * This method walks the [[redirectedFrom]] chain back to the original (first) transition in the chain.\n *\n * #### Example:\n * ```js\n * // states\n * registry.register({ name: 'A', redirectTo: 'B' });\n * registry.register({ name: 'B', redirectTo: 'C' });\n * registry.register({ name: 'C', redirectTo: 'D' });\n * registry.register({ name: 'D' });\n *\n * let transitionA = $state.go('A').transition\n *\n * $transitions.onSuccess({ to: 'D' }, (trans) => {\n * trans.to().name === 'D'; // true\n * trans.redirectedFrom().to().name === 'C'; // true\n * trans.originalTransition() === transitionA; // true\n * trans.originalTransition().to().name === 'A'; // true\n * });\n * ```\n *\n * @returns The original Transition that started a redirect chain\n */\n originalTransition(): Transition {\n const rf = this.redirectedFrom();\n return (rf && rf.originalTransition()) || this;\n }\n\n /**\n * Get the transition options\n *\n * @returns the options for this Transition.\n */\n options(): TransitionOptions {\n return this._options;\n }\n\n /**\n * Gets the states being entered.\n *\n * @returns an array of states that will be entered during this transition.\n */\n entering(): StateDeclaration[] {\n return map(this._treeChanges.entering, prop('state')).map(stateSelf);\n }\n\n /**\n * Gets the states being exited.\n *\n * @returns an array of states that will be exited during this transition.\n */\n exiting(): StateDeclaration[] {\n return map(this._treeChanges.exiting, prop('state'))\n .map(stateSelf)\n .reverse();\n }\n\n /**\n * Gets the states being retained.\n *\n * @returns an array of states that are already entered from a previous Transition, that will not be\n * exited during this Transition\n */\n retained(): StateDeclaration[] {\n return map(this._treeChanges.retained, prop('state')).map(stateSelf);\n }\n\n /**\n * Get the [[ViewConfig]]s associated with this Transition\n *\n * Each state can define one or more views (template/controller), which are encapsulated as `ViewConfig` objects.\n * This method fetches the `ViewConfigs` for a given path in the Transition (e.g., \"to\" or \"entering\").\n *\n * @param pathname the name of the path to fetch views for:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n * @param state If provided, only returns the `ViewConfig`s for a single state in the path\n *\n * @returns a list of ViewConfig objects for the given path.\n */\n views(pathname = 'entering', state?: StateObject): ViewConfig[] {\n let path = this._treeChanges[pathname];\n path = !state ? path : path.filter(propEq('state', state));\n return path\n .map(prop('views'))\n .filter(identity)\n .reduce(unnestR, []);\n }\n\n /**\n * Return the transition's tree changes\n *\n * A transition goes from one state/parameters to another state/parameters.\n * During a transition, states are entered and/or exited.\n *\n * This function returns various branches (paths) which represent the changes to the\n * active state tree that are caused by the transition.\n *\n * @param pathname The name of the tree changes path to get:\n * (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)\n */\n treeChanges(pathname: string): PathNode[];\n treeChanges(): TreeChanges;\n treeChanges(pathname?: string) {\n return pathname ? this._treeChanges[pathname] : this._treeChanges;\n }\n\n /**\n * Creates a new transition that is a redirection of the current one.\n *\n * This transition can be returned from a [[TransitionService]] hook to\n * redirect a transition to a new state and/or set of parameters.\n *\n * @internalapi\n *\n * @returns Returns a new [[Transition]] instance.\n */\n redirect(targetState: TargetState): Transition {\n let redirects = 1,\n trans: Transition = this;\n // tslint:disable-next-line:no-conditional-assignment\n while ((trans = trans.redirectedFrom()) != null) {\n if (++redirects > 20) throw new Error(`Too many consecutive Transition redirects (20+)`);\n }\n\n const redirectOpts: TransitionOptions = { redirectedFrom: this, source: 'redirect' };\n // If the original transition was caused by URL sync, then use { location: 'replace' }\n // on the new transition (unless the target state explicitly specifies location: false).\n // This causes the original url to be replaced with the url for the redirect target\n // so the original url disappears from the browser history.\n if (this.options().source === 'url' && targetState.options().location !== false) {\n redirectOpts.location = 'replace';\n }\n\n const newOptions = extend({}, this.options(), targetState.options(), redirectOpts);\n targetState = targetState.withOptions(newOptions, true);\n\n const newTransition = this.router.transitionService.create(this._treeChanges.from, targetState);\n const originalEnteringNodes = this._treeChanges.entering;\n const redirectEnteringNodes = newTransition._treeChanges.entering;\n\n // --- Re-use resolve data from original transition ---\n // When redirecting from a parent state to a child state where the parent parameter values haven't changed\n // (because of the redirect), the resolves fetched by the original transition are still valid in the\n // redirected transition.\n //\n // This allows you to define a redirect on a parent state which depends on an async resolve value.\n // You can wait for the resolve, then redirect to a child state based on the result.\n // The redirected transition does not have to re-fetch the resolve.\n // ---------------------------------------------------------\n\n const nodeIsReloading = (reloadState: StateObject) => (node: PathNode) => {\n return reloadState && node.state.includes[reloadState.name];\n };\n\n // Find any \"entering\" nodes in the redirect path that match the original path and aren't being reloaded\n const matchingEnteringNodes: PathNode[] = PathUtils.matching(\n redirectEnteringNodes,\n originalEnteringNodes,\n PathUtils.nonDynamicParams,\n ).filter(not(nodeIsReloading(targetState.options().reloadState)));\n\n // Use the existing (possibly pre-resolved) resolvables for the matching entering nodes.\n matchingEnteringNodes.forEach((node, idx) => {\n node.resolvables = originalEnteringNodes[idx].resolvables;\n });\n\n return newTransition;\n }\n\n /** @hidden If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */\n private _changedParams(): Param[] {\n const tc = this._treeChanges;\n\n /** Return undefined if it's not a \"dynamic\" transition, for the following reasons */\n // If user explicitly wants a reload\n if (this._options.reload) return undefined;\n // If any states are exiting or entering\n if (tc.exiting.length || tc.entering.length) return undefined;\n // If to/from path lengths differ\n if (tc.to.length !== tc.from.length) return undefined;\n // If the to/from paths are different\n const pathsDiffer: boolean = arrayTuples(tc.to, tc.from)\n .map(tuple => tuple[0].state !== tuple[1].state)\n .reduce(anyTrueR, false);\n if (pathsDiffer) return undefined;\n\n // Find any parameter values that differ\n const nodeSchemas: Param[][] = tc.to.map((node: PathNode) => node.paramSchema);\n const [toValues, fromValues] = [tc.to, tc.from].map(path => path.map(x => x.paramValues));\n const tuples = arrayTuples(nodeSchemas, toValues, fromValues);\n\n return tuples.map(([schema, toVals, fromVals]) => Param.changed(schema, toVals, fromVals)).reduce(unnestR, []);\n }\n\n /**\n * Returns true if the transition is dynamic.\n *\n * A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.\n *\n * @returns true if the Transition is dynamic\n */\n dynamic(): boolean {\n const changes = this._changedParams();\n return !changes ? false : changes.map(x => x.dynamic).reduce(anyTrueR, false);\n }\n\n /**\n * Returns true if the transition is ignored.\n *\n * A transition is ignored if no states are entered nor exited, and no parameter values have changed.\n *\n * @returns true if the Transition is ignored.\n */\n ignored(): boolean {\n return !!this._ignoredReason();\n }\n\n /** @hidden */\n _ignoredReason(): 'SameAsCurrent' | 'SameAsPending' | undefined {\n const pending = this.router.globals.transition;\n const reloadState = this._options.reloadState;\n\n const same = (pathA, pathB) => {\n if (pathA.length !== pathB.length) return false;\n const matching = PathUtils.matching(pathA, pathB);\n return pathA.length === matching.filter(node => !reloadState || !node.state.includes[reloadState.name]).length;\n };\n\n const newTC = this.treeChanges();\n const pendTC = pending && pending.treeChanges();\n\n if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) return 'SameAsPending';\n if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) return 'SameAsCurrent';\n }\n\n /**\n * Runs the transition\n *\n * This method is generally called from the [[StateService.transitionTo]]\n *\n * @internalapi\n *\n * @returns a promise for a successful transition.\n */\n run(): Promise {\n const runAllHooks = TransitionHook.runAllHooks;\n\n // Gets transition hooks array for the given phase\n const getHooksFor = (phase: TransitionHookPhase) => this._hookBuilder.buildHooksForPhase(phase);\n\n // When the chain is complete, then resolve or reject the deferred\n const transitionSuccess = () => {\n trace.traceSuccess(this.$to(), this);\n this.success = true;\n this._deferred.resolve(this.to());\n runAllHooks(getHooksFor(TransitionHookPhase.SUCCESS));\n };\n\n const transitionError = (reason: Rejection) => {\n trace.traceError(reason, this);\n this.success = false;\n this._deferred.reject(reason);\n this._error = reason;\n runAllHooks(getHooksFor(TransitionHookPhase.ERROR));\n };\n\n const runTransition = () => {\n // Wait to build the RUN hook chain until the BEFORE hooks are done\n // This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object.\n const allRunHooks = getHooksFor(TransitionHookPhase.RUN);\n const done = () => services.$q.when(undefined);\n return TransitionHook.invokeHooks(allRunHooks, done);\n };\n\n const startTransition = () => {\n const globals = this.router.globals;\n\n globals.lastStartedTransitionId = this.$id;\n globals.transition = this;\n globals.transitionHistory.enqueue(this);\n\n trace.traceTransitionStart(this);\n\n return services.$q.when(undefined);\n };\n\n const allBeforeHooks = getHooksFor(TransitionHookPhase.BEFORE);\n TransitionHook.invokeHooks(allBeforeHooks, startTransition)\n .then(runTransition)\n .then(transitionSuccess, transitionError);\n\n return this.promise;\n }\n\n /** Checks if this transition is currently active/running. */\n isActive = () => this.router.globals.transition === this;\n\n /**\n * Checks if the Transition is valid\n *\n * @returns true if the Transition is valid\n */\n valid() {\n return !this.error() || this.success !== undefined;\n }\n\n /**\n * Aborts this transition\n *\n * Imperative API to abort a Transition.\n * This only applies to Transitions that are not yet complete.\n */\n abort() {\n // Do not set flag if the transition is already complete\n if (isUndefined(this.success)) {\n this._aborted = true;\n }\n }\n\n /**\n * The Transition error reason.\n *\n * If the transition is invalid (and could not be run), returns the reason the transition is invalid.\n * If the transition was valid and ran, but was not successful, returns the reason the transition failed.\n *\n * @returns a transition rejection explaining why the transition is invalid, or the reason the transition failed.\n */\n error(): Rejection {\n const state: StateObject = this.$to();\n\n if (state.self.abstract) {\n return Rejection.invalid(`Cannot transition to abstract state '${state.name}'`);\n }\n\n const paramDefs = state.parameters();\n const values = this.params();\n const invalidParams = paramDefs.filter(param => !param.validates(values[param.id]));\n\n if (invalidParams.length) {\n const invalidValues = invalidParams.map(param => `[${param.id}:${stringify(values[param.id])}]`).join(', ');\n const detail = `The following parameter values are not valid for state '${state.name}': ${invalidValues}`;\n return Rejection.invalid(detail);\n }\n\n if (this.success === false) return this._error;\n }\n\n /**\n * A string representation of the Transition\n *\n * @returns A string representation of the Transition\n */\n toString() {\n const fromStateOrName = this.from();\n const toStateOrName = this.to();\n\n const avoidEmptyHash = (params: RawParams) =>\n params['#'] !== null && params['#'] !== undefined ? params : omit(params, ['#']);\n\n // (X) means the to state is invalid.\n const id = this.$id,\n from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName,\n fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))),\n toValid = this.valid() ? '' : '(X) ',\n to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName,\n toParams = stringify(avoidEmptyHash(this.params()));\n\n return `Transition#${id}( '${from}'${fromParams} -> ${toValid}'${to}'${toParams} )`;\n }\n}\n", + "/**\n * Functions that manipulate strings\n *\n * Although these functions are exported, they are subject to change without notice.\n *\n * @module common_strings\n */ /** */\n\nimport { isString, isArray, isDefined, isNull, isPromise, isInjectable, isObject } from './predicates';\nimport { Rejection } from '../transition/rejectFactory';\nimport { IInjectable, identity, Obj, tail, pushR } from './common';\nimport { pattern, is, not, val, invoke } from './hof';\nimport { Transition } from '../transition/transition';\nimport { Resolvable } from '../resolve/resolvable';\n\n/**\n * Returns a string shortened to a maximum length\n *\n * If the string is already less than the `max` length, return the string.\n * Else return the string, shortened to `max - 3` and append three dots (\"...\").\n *\n * @param max the maximum length of the string to return\n * @param str the input string\n */\nexport function maxLength(max: number, str: string) {\n if (str.length <= max) return str;\n return str.substr(0, max - 3) + '...';\n}\n\n/**\n * Returns a string, with spaces added to the end, up to a desired str length\n *\n * If the string is already longer than the desired length, return the string.\n * Else returns the string, with extra spaces on the end, such that it reaches `length` characters.\n *\n * @param length the desired length of the string to return\n * @param str the input string\n */\nexport function padString(length: number, str: string) {\n while (str.length < length) str += ' ';\n return str;\n}\n\nexport function kebobString(camelCase: string) {\n return camelCase\n .replace(/^([A-Z])/, $1 => $1.toLowerCase()) // replace first char\n .replace(/([A-Z])/g, $1 => '-' + $1.toLowerCase()); // replace rest\n}\n\nfunction _toJson(obj: Obj) {\n return JSON.stringify(obj);\n}\n\nfunction _fromJson(json: string) {\n return isString(json) ? JSON.parse(json) : json;\n}\n\nfunction promiseToString(p: Promise) {\n return `Promise(${JSON.stringify(p)})`;\n}\n\nexport function functionToString(fn: Function) {\n const fnStr = fnToString(fn);\n const namedFunctionMatch = fnStr.match(/^(function [^ ]+\\([^)]*\\))/);\n const toStr = namedFunctionMatch ? namedFunctionMatch[1] : fnStr;\n\n const fnName = fn['name'] || '';\n if (fnName && toStr.match(/function \\(/)) {\n return 'function ' + fnName + toStr.substr(9);\n }\n return toStr;\n}\n\nexport function fnToString(fn: IInjectable) {\n const _fn = isArray(fn) ? fn.slice(-1)[0] : fn;\n return (_fn && _fn.toString()) || 'undefined';\n}\n\nlet stringifyPatternFn: (val: any) => string = null;\nconst stringifyPattern = function(value: any) {\n const isRejection = Rejection.isRejectionPromise;\n\n stringifyPatternFn =\n stringifyPatternFn ||\n pattern([\n [not(isDefined), val('undefined')],\n [isNull, val('null')],\n [isPromise, val('[Promise]')],\n [isRejection, (x: any) => x._transitionRejection.toString()],\n [is(Rejection), invoke('toString')],\n [is(Transition), invoke('toString')],\n [is(Resolvable), invoke('toString')],\n [isInjectable, functionToString],\n [val(true), identity],\n ]);\n\n return stringifyPatternFn(value);\n};\n\nexport function stringify(o: any) {\n const seen: any[] = [];\n\n function format(value: any) {\n if (isObject(value)) {\n if (seen.indexOf(value) !== -1) return '[circular ref]';\n seen.push(value);\n }\n return stringifyPattern(value);\n }\n\n return JSON.stringify(o, (key, value) => format(value)).replace(/\\\\\"/g, '\"');\n}\n\n/** Returns a function that splits a string on a character or substring */\nexport const beforeAfterSubstr = (char: string) => (str: string): string[] => {\n if (!str) return ['', ''];\n const idx = str.indexOf(char);\n if (idx === -1) return [str, ''];\n return [str.substr(0, idx), str.substr(idx + 1)];\n};\n\nexport const hostRegex = new RegExp('^(?:[a-z]+:)?//[^/]+/');\nexport const stripLastPathElement = (str: string) => str.replace(/\\/[^/]*$/, '');\nexport const splitHash = beforeAfterSubstr('#');\nexport const splitQuery = beforeAfterSubstr('?');\nexport const splitEqual = beforeAfterSubstr('=');\nexport const trimHashVal = (str: string) => (str ? str.replace(/^#/, '') : '');\n\n/**\n * Splits on a delimiter, but returns the delimiters in the array\n *\n * #### Example:\n * ```js\n * var splitOnSlashes = splitOnDelim('/');\n * splitOnSlashes(\"/foo\"); // [\"/\", \"foo\"]\n * splitOnSlashes(\"/foo/\"); // [\"/\", \"foo\", \"/\"]\n * ```\n */\nexport function splitOnDelim(delim: string) {\n const re = new RegExp('(' + delim + ')', 'g');\n return (str: string) => str.split(re).filter(identity);\n}\n\n/**\n * Reduce fn that joins neighboring strings\n *\n * Given an array of strings, returns a new array\n * where all neighboring strings have been joined.\n *\n * #### Example:\n * ```js\n * let arr = [\"foo\", \"bar\", 1, \"baz\", \"\", \"qux\" ];\n * arr.reduce(joinNeighborsR, []) // [\"foobar\", 1, \"bazqux\" ]\n * ```\n */\nexport function joinNeighborsR(acc: any[], x: any) {\n if (isString(tail(acc)) && isString(x)) return acc.slice(0, -1).concat(tail(acc) + x);\n return pushR(acc, x);\n}\n", + "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { fromJson, toJson, identity, equals, inherit, map, extend, pick } from '../common/common';\nimport { isDefined, isNullOrUndefined } from '../common/predicates';\nimport { is } from '../common/hof';\nimport { services } from '../common/coreservices';\nimport { ParamType } from './paramType';\nimport { ParamTypeDefinition } from './interface';\n\n/**\n * A registry for parameter types.\n *\n * This registry manages the built-in (and custom) parameter types.\n *\n * The built-in parameter types are:\n *\n * - [[string]]\n * - [[path]]\n * - [[query]]\n * - [[hash]]\n * - [[int]]\n * - [[bool]]\n * - [[date]]\n * - [[json]]\n * - [[any]]\n */\nexport class ParamTypes {\n /**\n * Built-in parameter type: `string`\n *\n * This parameter type coerces values to strings.\n * It matches anything (`new RegExp(\".*\")`) in the URL\n */\n static string: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `path`\n *\n * This parameter type is the default type for path parameters.\n * A path parameter is any parameter declared in the path portion of a url\n *\n * - `/foo/:param1/:param2`: two path parameters\n *\n * This parameter type behaves exactly like the [[string]] type with one exception.\n * When matching parameter values in the URL, the `path` type does not match forward slashes `/`.\n *\n * #### Angular 1 note:\n * In ng1, this type is overridden with one that pre-encodes slashes as `~2F` instead of `%2F`.\n * For more details about this angular 1 behavior, see: https://github.com/angular-ui/ui-router/issues/2598\n */\n static path: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `query`\n *\n * This parameter type is the default type for query/search parameters.\n * It behaves the same as the [[string]] parameter type.\n *\n * A query parameter is any parameter declared in the query/search portion of a url\n *\n * - `/bar?param2`: a query parameter\n */\n static query: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `hash`\n *\n * This parameter type is used for the `#` parameter (the hash)\n * It behaves the same as the [[string]] parameter type.\n * @coreapi\n */\n static hash: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `int`\n *\n * This parameter type serializes javascript integers (`number`s which represent an integer) to the URL.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'user',\n * url: '/user/{id:int}'\n * });\n * ```\n * ```js\n * $state.go('user', { id: 1298547 });\n * ```\n *\n * The URL will serialize to: `/user/1298547`.\n *\n * When the parameter value is read, it will be the `number` `1298547`, not the string `\"1298547\"`.\n */\n static int: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `bool`\n *\n * This parameter type serializes `true`/`false` as `1`/`0`\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'inbox',\n * url: '/inbox?{unread:bool}'\n * });\n * ```\n * ```js\n * $state.go('inbox', { unread: true });\n * ```\n *\n * The URL will serialize to: `/inbox?unread=1`.\n *\n * Conversely, if the url is `/inbox?unread=0`, the value of the `unread` parameter will be a `false`.\n */\n static bool: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `date`\n *\n * This parameter type can be used to serialize Javascript dates as parameter values.\n *\n * #### Example:\n * ```js\n * .state({\n * name: 'search',\n * url: '/search?{start:date}'\n * });\n * ```\n * ```js\n * $state.go('search', { start: new Date(2000, 0, 1) });\n * ```\n *\n * The URL will serialize to: `/search?start=2000-01-01`.\n *\n * Conversely, if the url is `/search?start=2016-12-25`, the value of the `start` parameter will be a `Date` object where:\n *\n * - `date.getFullYear() === 2016`\n * - `date.getMonth() === 11` (month is 0-based)\n * - `date.getDate() === 25`\n */\n static date: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `json`\n *\n * This parameter type can be used to serialize javascript objects into the URL using JSON serialization.\n *\n * #### Example:\n * This example serializes an plain javascript object to the URL\n * ```js\n * .state({\n * name: 'map',\n * url: '/map/{coords:json}'\n * });\n * ```\n * ```js\n * $state.go('map', { coords: { x: 10399.2, y: 49071 });\n * ```\n *\n * The URL will serialize to: `/map/%7B%22x%22%3A10399.2%2C%22y%22%3A49071%7D`\n */\n static json: ParamTypeDefinition;\n\n /**\n * Built-in parameter type: `any`\n *\n * This parameter type is used by default for url-less parameters (parameters that do not appear in the URL).\n * This type does not encode or decode.\n * It is compared using a deep `equals` comparison.\n *\n * #### Example:\n * This example defines a non-url parameter on a [[StateDeclaration]].\n * ```js\n * .state({\n * name: 'new',\n * url: '/new',\n * params: {\n * inrepyto: null\n * }\n * });\n * ```\n * ```js\n * $state.go('new', { inreplyto: currentMessage });\n * ```\n */\n static any: ParamTypeDefinition;\n\n /** @hidden */\n types: any;\n /** @hidden */\n enqueue = true;\n /** @hidden */\n typeQueue: any[] = [];\n\n /** @internalapi */\n private defaultTypes: any = pick(ParamTypes.prototype, [\n 'hash',\n 'string',\n 'query',\n 'path',\n 'int',\n 'bool',\n 'date',\n 'json',\n 'any',\n ]);\n\n /** @internalapi */\n constructor() {\n // Register default types. Store them in the prototype of this.types.\n const makeType = (definition: ParamTypeDefinition, name: string) => new ParamType(extend({ name }, definition));\n this.types = inherit(map(this.defaultTypes, makeType), {});\n }\n\n /** @internalapi */\n dispose() {\n this.types = {};\n }\n\n /**\n * Registers a parameter type\n *\n * End users should call [[UrlMatcherFactory.type]], which delegates to this method.\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n if (!isDefined(definition)) return this.types[name];\n if (this.types.hasOwnProperty(name)) throw new Error(`A type named '${name}' has already been defined.`);\n\n this.types[name] = new ParamType(extend({ name }, definition));\n\n if (definitionFn) {\n this.typeQueue.push({ name, def: definitionFn });\n if (!this.enqueue) this._flushTypeQueue();\n }\n\n return this;\n }\n\n /** @internalapi */\n _flushTypeQueue() {\n while (this.typeQueue.length) {\n const type = this.typeQueue.shift();\n if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n extend(this.types[type.name], services.$injector.invoke(type.def));\n }\n }\n}\n\n/** @hidden */\nfunction initDefaultTypes() {\n const makeDefaultType = def => {\n const valToString = (val: any) => (val != null ? val.toString() : val);\n\n const defaultTypeBase = {\n encode: valToString,\n decode: valToString,\n is: is(String),\n pattern: /.*/,\n // tslint:disable-next-line:triple-equals\n equals: (a: any, b: any) => a == b, // allow coersion for null/undefined/\"\"\n };\n\n return extend({}, defaultTypeBase, def) as ParamTypeDefinition;\n };\n\n // Default Parameter Type Definitions\n extend(ParamTypes.prototype, {\n string: makeDefaultType({}),\n\n path: makeDefaultType({\n pattern: /[^/]*/,\n }),\n\n query: makeDefaultType({}),\n\n hash: makeDefaultType({\n inherit: false,\n }),\n\n int: makeDefaultType({\n decode: (val: string) => parseInt(val, 10),\n is: function(val: any) {\n return !isNullOrUndefined(val) && this.decode(val.toString()) === val;\n },\n pattern: /-?\\d+/,\n }),\n\n bool: makeDefaultType({\n encode: (val: any) => (val && 1) || 0,\n decode: (val: string) => parseInt(val, 10) !== 0,\n is: is(Boolean),\n pattern: /0|1/,\n }),\n\n date: makeDefaultType({\n encode: function(val: any) {\n return !this.is(val)\n ? undefined\n : [val.getFullYear(), ('0' + (val.getMonth() + 1)).slice(-2), ('0' + val.getDate()).slice(-2)].join('-');\n },\n decode: function(val: string) {\n if (this.is(val)) return (val) as Date;\n const match = this.capture.exec(val);\n return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n },\n is: (val: any) => val instanceof Date && !isNaN(val.valueOf()),\n equals(l: any, r: any) {\n return ['getFullYear', 'getMonth', 'getDate'].reduce((acc, fn) => acc && l[fn]() === r[fn](), true);\n },\n pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/,\n }),\n\n json: makeDefaultType({\n encode: toJson,\n decode: fromJson,\n is: is(Object),\n equals: equals,\n pattern: /[^/]*/,\n }),\n\n // does not encode/decode\n any: makeDefaultType({\n encode: identity,\n decode: identity,\n is: () => true,\n equals: equals,\n }),\n });\n}\n\ninitDefaultTypes();\n", + "/**\n * @coreapi\n * @module params\n */\n/** */\nimport { extend, ancestors, Obj } from '../common/common';\nimport { StateObject } from '../state/stateObject';\n\n/** @internalapi */\nexport class StateParams {\n [key: string]: any;\n\n constructor(params: Obj = {}) {\n extend(this, params);\n }\n\n /**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\n $inherit(newParams: Obj, $current: StateObject, $to: StateObject) {\n let parentParams: string[];\n const parents = ancestors($current, $to),\n inherited: Obj = {},\n inheritList: string[] = [];\n\n for (const i in parents) {\n if (!parents[i] || !parents[i].params) continue;\n parentParams = Object.keys(parents[i].params);\n if (!parentParams.length) continue;\n\n for (const j in parentParams) {\n if (inheritList.indexOf(parentParams[j]) >= 0) continue;\n inheritList.push(parentParams[j]);\n inherited[parentParams[j]] = this[parentParams[j]];\n }\n }\n return extend({}, inherited, newParams);\n }\n}\n", + "/** @module state */ /** for typedoc */\nimport { Obj, omit, noop, extend, inherit, values, applyPairs, tail, mapObj, identity } from '../common/common';\nimport { isDefined, isFunction, isString, isArray } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { prop, pattern, is, pipe, val } from '../common/hof';\nimport { StateDeclaration } from './interface';\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { Param } from '../params/param';\nimport { UrlMatcherFactory } from '../url/urlMatcherFactory';\nimport { UrlMatcher } from '../url/urlMatcher';\nimport { Resolvable } from '../resolve/resolvable';\nimport { services } from '../common/coreservices';\nimport { ResolvePolicy } from '../resolve/interface';\nimport { ParamFactory } from '../url/interface';\n\nconst parseUrl = (url: string): any => {\n if (!isString(url)) return false;\n const root = url.charAt(0) === '^';\n return { val: root ? url.substring(1) : url, root };\n};\n\nexport type BuilderFunction = (state: StateObject, parent?: BuilderFunction) => any;\n\ninterface Builders {\n [key: string]: BuilderFunction[];\n\n name: BuilderFunction[];\n parent: BuilderFunction[];\n data: BuilderFunction[];\n url: BuilderFunction[];\n navigable: BuilderFunction[];\n params: BuilderFunction[];\n views: BuilderFunction[];\n path: BuilderFunction[];\n includes: BuilderFunction[];\n resolvables: BuilderFunction[];\n}\n\nfunction nameBuilder(state: StateObject) {\n return state.name;\n}\n\nfunction selfBuilder(state: StateObject) {\n state.self.$$state = () => state;\n return state.self;\n}\n\nfunction dataBuilder(state: StateObject) {\n if (state.parent && state.parent.data) {\n state.data = state.self.data = inherit(state.parent.data, state.data);\n }\n return state.data;\n}\n\nconst getUrlBuilder = ($urlMatcherFactoryProvider: UrlMatcherFactory, root: () => StateObject) =>\n function urlBuilder(state: StateObject) {\n const stateDec: StateDeclaration = state;\n\n // For future states, i.e., states whose name ends with `.**`,\n // match anything that starts with the url prefix\n if (stateDec && stateDec.url && stateDec.name && stateDec.name.match(/\\.\\*\\*$/)) {\n stateDec.url += '{remainder:any}'; // match any path (.*)\n }\n\n const parsed = parseUrl(stateDec.url),\n parent = state.parent;\n const url = !parsed\n ? stateDec.url\n : $urlMatcherFactoryProvider.compile(parsed.val, {\n params: state.params || {},\n paramMap: function(paramConfig: any, isSearch: boolean) {\n if (stateDec.reloadOnSearch === false && isSearch)\n paramConfig = extend(paramConfig || {}, { dynamic: true });\n return paramConfig;\n },\n });\n\n if (!url) return null;\n if (!$urlMatcherFactoryProvider.isMatcher(url)) throw new Error(`Invalid url '${url}' in state '${state}'`);\n return parsed && parsed.root ? url : ((parent && parent.navigable) || root()).url.append(url);\n };\n\nconst getNavigableBuilder = (isRoot: (state: StateObject) => boolean) =>\n function navigableBuilder(state: StateObject) {\n return !isRoot(state) && state.url ? state : state.parent ? state.parent.navigable : null;\n };\n\nconst getParamsBuilder = (paramFactory: ParamFactory) =>\n function paramsBuilder(state: StateObject): { [key: string]: Param } {\n const makeConfigParam = (config: any, id: string) => paramFactory.fromConfig(id, null, config);\n const urlParams: Param[] = (state.url && state.url.parameters({ inherit: false })) || [];\n const nonUrlParams: Param[] = values(mapObj(omit(state.params || {}, urlParams.map(prop('id'))), makeConfigParam));\n return urlParams\n .concat(nonUrlParams)\n .map(p => [p.id, p])\n .reduce(applyPairs, {});\n };\n\nfunction pathBuilder(state: StateObject) {\n return state.parent ? state.parent.path.concat(state) : /*root*/ [state];\n}\n\nfunction includesBuilder(state: StateObject) {\n const includes = state.parent ? extend({}, state.parent.includes) : {};\n includes[state.name] = true;\n return includes;\n}\n\n/**\n * This is a [[StateBuilder.builder]] function for the `resolve:` block on a [[StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * validates the `resolve` property and converts it to a [[Resolvable]] array.\n *\n * resolve: input value can be:\n *\n * {\n * // analyzed but not injected\n * myFooResolve: function() { return \"myFooData\"; },\n *\n * // function.toString() parsed, \"DependencyName\" dep as string (not min-safe)\n * myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },\n *\n * // Array split; \"DependencyName\" dep as string\n * myBazResolve: [ \"DependencyName\", function(dep) { return dep.fetchSomethingAsPromise() },\n *\n * // Array split; DependencyType dep as token (compared using ===)\n * myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },\n *\n * // val.$inject used as deps\n * // where:\n * // corgeResolve.$inject = [\"DependencyName\"];\n * // function corgeResolve(dep) { dep.fetchSometingAsPromise() }\n * // then \"DependencyName\" dep as string\n * myCorgeResolve: corgeResolve,\n *\n * // inject service by name\n * // When a string is found, desugar creating a resolve that injects the named service\n * myGraultResolve: \"SomeService\"\n * }\n *\n * or:\n *\n * [\n * new Resolvable(\"myFooResolve\", function() { return \"myFooData\" }),\n * new Resolvable(\"myBarResolve\", function(dep) { return dep.fetchSomethingAsPromise() }, [ \"DependencyName\" ]),\n * { provide: \"myBazResolve\", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ \"DependencyName\" ] }\n * ]\n */\nexport function resolvablesBuilder(state: StateObject): Resolvable[] {\n interface Tuple {\n token: any;\n val: any;\n deps: any[];\n policy: ResolvePolicy;\n }\n\n /** convert resolve: {} and resolvePolicy: {} objects to an array of tuples */\n const objects2Tuples = (resolveObj: Obj, resolvePolicies: { [key: string]: ResolvePolicy }) =>\n Object.keys(resolveObj || {}).map(token => ({\n token,\n val: resolveObj[token],\n deps: undefined,\n policy: resolvePolicies[token],\n }));\n\n /** fetch DI annotations from a function or ng1-style array */\n const annotate = (fn: Function) => {\n const $injector = services.$injector;\n // ng1 doesn't have an $injector until runtime.\n // If the $injector doesn't exist, use \"deferred\" literal as a\n // marker indicating they should be annotated when runtime starts\n return fn['$inject'] || ($injector && $injector.annotate(fn, $injector.strictDi)) || 'deferred';\n };\n\n /** true if the object has both `token` and `resolveFn`, and is probably a [[ResolveLiteral]] */\n const isResolveLiteral = (obj: any) => !!(obj.token && obj.resolveFn);\n\n /** true if the object looks like a provide literal, or a ng2 Provider */\n const isLikeNg2Provider = (obj: any) =>\n !!((obj.provide || obj.token) && (obj.useValue || obj.useFactory || obj.useExisting || obj.useClass));\n\n /** true if the object looks like a tuple from obj2Tuples */\n const isTupleFromObj = (obj: any) =>\n !!(obj && obj.val && (isString(obj.val) || isArray(obj.val) || isFunction(obj.val)));\n\n /** extracts the token from a Provider or provide literal */\n const getToken = (p: any) => p.provide || p.token;\n\n /** Given a literal resolve or provider object, returns a Resolvable */\n const literal2Resolvable = pattern([\n [prop('resolveFn'), p => new Resolvable(getToken(p), p.resolveFn, p.deps, p.policy)],\n [prop('useFactory'), p => new Resolvable(getToken(p), p.useFactory, p.deps || p.dependencies, p.policy)],\n [prop('useClass'), p => new Resolvable(getToken(p), () => new (p.useClass)(), [], p.policy)],\n [prop('useValue'), p => new Resolvable(getToken(p), () => p.useValue, [], p.policy, p.useValue)],\n [prop('useExisting'), p => new Resolvable(getToken(p), identity, [p.useExisting], p.policy)],\n ]);\n\n const tuple2Resolvable = pattern([\n [pipe(prop('val'), isString), (tuple: Tuple) => new Resolvable(tuple.token, identity, [tuple.val], tuple.policy)],\n [\n pipe(prop('val'), isArray),\n (tuple: Tuple) => new Resolvable(tuple.token, tail(tuple.val), tuple.val.slice(0, -1), tuple.policy),\n ],\n [\n pipe(prop('val'), isFunction),\n (tuple: Tuple) => new Resolvable(tuple.token, tuple.val, annotate(tuple.val), tuple.policy),\n ],\n ]);\n\n const item2Resolvable = <(obj: any) => Resolvable>pattern([\n [is(Resolvable), (r: Resolvable) => r],\n [isResolveLiteral, literal2Resolvable],\n [isLikeNg2Provider, literal2Resolvable],\n [isTupleFromObj, tuple2Resolvable],\n [\n val(true),\n (obj: any) => {\n throw new Error('Invalid resolve value: ' + stringify(obj));\n },\n ],\n ]);\n\n // If resolveBlock is already an array, use it as-is.\n // Otherwise, assume it's an object and convert to an Array of tuples\n const decl = state.resolve;\n const items: any[] = isArray(decl) ? decl : objects2Tuples(decl, state.resolvePolicy || {});\n return items.map(item2Resolvable);\n}\n\n/**\n * @internalapi A internal global service\n *\n * StateBuilder is a factory for the internal [[StateObject]] objects.\n *\n * When you register a state with the [[StateRegistry]], you register a plain old javascript object which\n * conforms to the [[StateDeclaration]] interface. This factory takes that object and builds the corresponding\n * [[StateObject]] object, which has an API and is used internally.\n *\n * Custom properties or API may be added to the internal [[StateObject]] object by registering a decorator function\n * using the [[builder]] method.\n */\nexport class StateBuilder {\n /** An object that contains all the BuilderFunctions registered, key'd by the name of the State property they build */\n private builders: Builders;\n\n constructor(private matcher: StateMatcher, urlMatcherFactory: UrlMatcherFactory) {\n const self = this;\n\n const root = () => matcher.find('');\n const isRoot = (state: StateObject) => state.name === '';\n\n function parentBuilder(state: StateObject) {\n if (isRoot(state)) return null;\n return matcher.find(self.parentName(state)) || root();\n }\n\n this.builders = {\n name: [nameBuilder],\n self: [selfBuilder],\n parent: [parentBuilder],\n data: [dataBuilder],\n // Build a URLMatcher if necessary, either via a relative or absolute URL\n url: [getUrlBuilder(urlMatcherFactory, root)],\n // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n navigable: [getNavigableBuilder(isRoot)],\n params: [getParamsBuilder(urlMatcherFactory.paramFactory)],\n // Each framework-specific ui-router implementation should define its own `views` builder\n // e.g., src/ng1/statebuilders/views.ts\n views: [],\n // Keep a full path from the root down to this state as this is needed for state activation.\n path: [pathBuilder],\n // Speed up $state.includes() as it's used a lot\n includes: [includesBuilder],\n resolvables: [resolvablesBuilder],\n };\n }\n\n /**\n * Registers a [[BuilderFunction]] for a specific [[StateObject]] property (e.g., `parent`, `url`, or `path`).\n * More than one BuilderFunction can be registered for a given property.\n *\n * The BuilderFunction(s) will be used to define the property on any subsequently built [[StateObject]] objects.\n *\n * @param name The name of the State property being registered for.\n * @param fn The BuilderFunction which will be used to build the State property\n * @returns a function which deregisters the BuilderFunction\n */\n builder(name: string, fn: BuilderFunction): BuilderFunction | BuilderFunction[] | Function {\n const builders = this.builders;\n const array = builders[name] || [];\n // Backwards compat: if only one builder exists, return it, else return whole arary.\n if (isString(name) && !isDefined(fn)) return array.length > 1 ? array : array[0];\n if (!isString(name) || !isFunction(fn)) return;\n\n builders[name] = array;\n builders[name].push(fn);\n return () => builders[name].splice(builders[name].indexOf(fn, 1)) && null;\n }\n\n /**\n * Builds all of the properties on an essentially blank State object, returning a State object which has all its\n * properties and API built.\n *\n * @param state an uninitialized State object\n * @returns the built State object\n */\n build(state: StateObject): StateObject {\n const { matcher, builders } = this;\n const parent = this.parentName(state);\n\n if (parent && !matcher.find(parent, undefined, false)) {\n return null;\n }\n\n for (const key in builders) {\n if (!builders.hasOwnProperty(key)) continue;\n const chain = builders[key].reduce(\n (parentFn: BuilderFunction, step: BuilderFunction) => _state => step(_state, parentFn),\n noop,\n );\n state[key] = chain(state);\n }\n return state;\n }\n\n parentName(state: StateObject) {\n // name = 'foo.bar.baz.**'\n const name = state.name || '';\n // segments = ['foo', 'bar', 'baz', '.**']\n const segments = name.split('.');\n // segments = ['foo', 'bar', 'baz']\n const lastSegment = segments.pop();\n // segments = ['foo', 'bar'] (ignore .** segment for future states)\n if (lastSegment === '**') segments.pop();\n\n if (segments.length) {\n if (state.parent) {\n throw new Error(`States that specify the 'parent:' property should not have a '.' in their name (${name})`);\n }\n\n // 'foo.bar'\n return segments.join('.');\n }\n\n if (!state.parent) return '';\n return isString(state.parent) ? state.parent : state.parent.name;\n }\n\n name(state: StateObject) {\n const name = state.name;\n if (name.indexOf('.') !== -1 || !state.parent) return name;\n\n const parentName = isString(state.parent) ? state.parent : state.parent.name;\n return parentName ? parentName + '.' + name : name;\n }\n}\n", + "/** @module state */ /** for typedoc */\nimport { isString } from '../common/predicates';\nimport { StateOrName } from './interface';\nimport { StateObject } from './stateObject';\nimport { values } from '../common/common';\n\nexport class StateMatcher {\n constructor(private _states: { [key: string]: StateObject }) {}\n\n isRelative(stateName: string) {\n stateName = stateName || '';\n return stateName.indexOf('.') === 0 || stateName.indexOf('^') === 0;\n }\n\n find(stateOrName: StateOrName, base?: StateOrName, matchGlob = true): StateObject {\n if (!stateOrName && stateOrName !== '') return undefined;\n const isStr = isString(stateOrName);\n let name: string = isStr ? stateOrName : (stateOrName).name;\n\n if (this.isRelative(name)) name = this.resolvePath(name, base);\n const state = this._states[name];\n\n if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n return state;\n } else if (isStr && matchGlob) {\n const _states = values(this._states);\n const matches = _states.filter(\n _state => _state.__stateObjectCache.nameGlob && _state.__stateObjectCache.nameGlob.matches(name),\n );\n\n if (matches.length > 1) {\n // tslint:disable-next-line:no-console\n console.log(\n `stateMatcher.find: Found multiple matches for ${name} using glob: `,\n matches.map(match => match.name),\n );\n }\n return matches[0];\n }\n return undefined;\n }\n\n resolvePath(name: string, base: StateOrName) {\n if (!base) throw new Error(`No reference point given for path '${name}'`);\n\n const baseState: StateObject = this.find(base);\n\n const splitName = name.split('.');\n const pathLength = splitName.length;\n let i = 0,\n current = baseState;\n\n for (; i < pathLength; i++) {\n if (splitName[i] === '' && i === 0) {\n current = baseState;\n continue;\n }\n if (splitName[i] === '^') {\n if (!current.parent) throw new Error(`Path '${name}' not valid for state '${baseState.name}'`);\n current = current.parent;\n continue;\n }\n break;\n }\n const relName = splitName.slice(i).join('.');\n return current.name + (current.name && relName ? '.' : '') + relName;\n }\n}\n", + "/** @module state */ /** for typedoc */\nimport { inArray } from '../common/common';\nimport { isString } from '../common/predicates';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { StateObject } from './stateObject';\nimport { StateBuilder } from './stateBuilder';\nimport { StateRegistryListener, StateRegistry } from './stateRegistry';\nimport { Disposable } from '../interface';\nimport { UrlRouter } from '../url/urlRouter';\nimport { prop } from '../common/hof';\nimport { StateMatcher } from './stateMatcher';\n\n/** @internalapi */\nexport class StateQueueManager implements Disposable {\n queue: StateObject[];\n matcher: StateMatcher;\n\n constructor(\n private $registry: StateRegistry,\n private $urlRouter: UrlRouter,\n public states: { [key: string]: StateObject },\n public builder: StateBuilder,\n public listeners: StateRegistryListener[],\n ) {\n this.queue = [];\n this.matcher = $registry.matcher;\n }\n\n /** @internalapi */\n dispose() {\n this.queue = [];\n }\n\n register(stateDecl: _StateDeclaration) {\n const queue = this.queue;\n const state = StateObject.create(stateDecl);\n const name = state.name;\n\n if (!isString(name)) throw new Error('State must have a valid name');\n if (this.states.hasOwnProperty(name) || inArray(queue.map(prop('name')), name))\n throw new Error(`State '${name}' is already defined`);\n\n queue.push(state);\n this.flush();\n\n return state;\n }\n\n flush() {\n const { queue, states, builder } = this;\n const registered: StateObject[] = [], // states that got registered\n orphans: StateObject[] = [], // states that don't yet have a parent registered\n previousQueueLength = {}; // keep track of how long the queue when an orphan was first encountered\n const getState = name => this.states.hasOwnProperty(name) && this.states[name];\n const notifyListeners = () => {\n if (registered.length) {\n this.listeners.forEach(listener => listener('registered', registered.map(s => s.self)));\n }\n };\n\n while (queue.length > 0) {\n const state: StateObject = queue.shift();\n const name = state.name;\n const result: StateObject = builder.build(state);\n const orphanIdx: number = orphans.indexOf(state);\n\n if (result) {\n const existingState = getState(name);\n if (existingState && existingState.name === name) {\n throw new Error(`State '${name}' is already defined`);\n }\n\n const existingFutureState = getState(name + '.**');\n if (existingFutureState) {\n // Remove future state of the same name\n this.$registry.deregister(existingFutureState);\n }\n\n states[name] = state;\n this.attachRoute(state);\n if (orphanIdx >= 0) orphans.splice(orphanIdx, 1);\n registered.push(state);\n continue;\n }\n\n const prev = previousQueueLength[name];\n previousQueueLength[name] = queue.length;\n if (orphanIdx >= 0 && prev === queue.length) {\n // Wait until two consecutive iterations where no additional states were dequeued successfully.\n // throw new Error(`Cannot register orphaned state '${name}'`);\n queue.push(state);\n notifyListeners();\n return states;\n } else if (orphanIdx < 0) {\n orphans.push(state);\n }\n\n queue.push(state);\n }\n\n notifyListeners();\n return states;\n }\n\n attachRoute(state: StateObject) {\n if (state.abstract || !state.url) return;\n\n this.$urlRouter.rule(this.$urlRouter.urlRuleFactory.create(state));\n }\n}\n", + "/**\n * @coreapi\n * @module state\n */ /** for typedoc */\n\nimport { StateObject } from './stateObject';\nimport { StateMatcher } from './stateMatcher';\nimport { StateBuilder } from './stateBuilder';\nimport { StateQueueManager } from './stateQueueManager';\nimport { StateDeclaration, _StateDeclaration } from './interface';\nimport { BuilderFunction } from './stateBuilder';\nimport { StateOrName } from './interface';\nimport { removeFrom } from '../common/common';\nimport { UIRouter } from '../router';\nimport { propEq } from '../common/hof';\n\n/**\n * The signature for the callback function provided to [[StateRegistry.onStatesChanged]].\n *\n * This callback receives two parameters:\n *\n * @param event a string; either \"registered\" or \"deregistered\"\n * @param states the list of [[StateDeclaration]]s that were registered (or deregistered).\n */\nexport type StateRegistryListener = (event: 'registered' | 'deregistered', states: StateDeclaration[]) => void;\n\nexport class StateRegistry {\n private _root: StateObject;\n private states: { [key: string]: StateObject } = {};\n\n matcher: StateMatcher;\n private builder: StateBuilder;\n stateQueue: StateQueueManager;\n\n listeners: StateRegistryListener[] = [];\n\n /** @internalapi */\n constructor(private _router: UIRouter) {\n this.matcher = new StateMatcher(this.states);\n this.builder = new StateBuilder(this.matcher, _router.urlMatcherFactory);\n this.stateQueue = new StateQueueManager(this, _router.urlRouter, this.states, this.builder, this.listeners);\n this._registerRoot();\n }\n\n /** @internalapi */\n private _registerRoot() {\n const rootStateDef: StateDeclaration = {\n name: '',\n url: '^',\n views: null,\n params: {\n '#': { value: null, type: 'hash', dynamic: true },\n },\n abstract: true,\n };\n\n const _root = (this._root = this.stateQueue.register(rootStateDef));\n _root.navigable = null;\n }\n\n /** @internalapi */\n dispose() {\n this.stateQueue.dispose();\n this.listeners = [];\n this.get().forEach(state => this.get(state) && this.deregister(state));\n }\n\n /**\n * Listen for a State Registry events\n *\n * Adds a callback that is invoked when states are registered or deregistered with the StateRegistry.\n *\n * #### Example:\n * ```js\n * let allStates = registry.get();\n *\n * // Later, invoke deregisterFn() to remove the listener\n * let deregisterFn = registry.onStatesChanged((event, states) => {\n * switch(event) {\n * case: 'registered':\n * states.forEach(state => allStates.push(state));\n * break;\n * case: 'deregistered':\n * states.forEach(state => {\n * let idx = allStates.indexOf(state);\n * if (idx !== -1) allStates.splice(idx, 1);\n * });\n * break;\n * }\n * });\n * ```\n *\n * @param listener a callback function invoked when the registered states changes.\n * The function receives two parameters, `event` and `state`.\n * See [[StateRegistryListener]]\n * @return a function that deregisters the listener\n */\n onStatesChanged(listener: StateRegistryListener): () => void {\n this.listeners.push(listener);\n return function deregisterListener() {\n removeFrom(this.listeners)(listener);\n }.bind(this);\n }\n\n /**\n * Gets the implicit root state\n *\n * Gets the root of the state tree.\n * The root state is implicitly created by UI-Router.\n * Note: this returns the internal [[StateObject]] representation, not a [[StateDeclaration]]\n *\n * @return the root [[StateObject]]\n */\n root() {\n return this._root;\n }\n\n /**\n * Adds a state to the registry\n *\n * Registers a [[StateDeclaration]] or queues it for registration.\n *\n * Note: a state will be queued if the state's parent isn't yet registered.\n *\n * @param stateDefinition the definition of the state to register.\n * @returns the internal [[StateObject]] object.\n * If the state was successfully registered, then the object is fully built (See: [[StateBuilder]]).\n * If the state was only queued, then the object is not fully built.\n */\n register(stateDefinition: _StateDeclaration): StateObject {\n return this.stateQueue.register(stateDefinition);\n }\n\n /** @hidden */\n private _deregisterTree(state: StateObject) {\n const all = this.get().map(s => s.$$state());\n const getChildren = (states: StateObject[]) => {\n const _children = all.filter(s => states.indexOf(s.parent) !== -1);\n return _children.length === 0 ? _children : _children.concat(getChildren(_children));\n };\n\n const children = getChildren([state]);\n const deregistered: StateObject[] = [state].concat(children).reverse();\n\n deregistered.forEach(_state => {\n const $ur = this._router.urlRouter;\n // Remove URL rule\n $ur\n .rules()\n .filter(propEq('state', _state))\n .forEach($ur.removeRule.bind($ur));\n // Remove state from registry\n delete this.states[_state.name];\n });\n\n return deregistered;\n }\n\n /**\n * Removes a state from the registry\n *\n * This removes a state from the registry.\n * If the state has children, they are are also removed from the registry.\n *\n * @param stateOrName the state's name or object representation\n * @returns {StateObject[]} a list of removed states\n */\n deregister(stateOrName: StateOrName) {\n const _state = this.get(stateOrName);\n if (!_state) throw new Error(\"Can't deregister state; not found: \" + stateOrName);\n const deregisteredStates = this._deregisterTree(_state.$$state());\n\n this.listeners.forEach(listener => listener('deregistered', deregisteredStates.map(s => s.self)));\n return deregisteredStates;\n }\n\n /**\n * Gets all registered states\n *\n * Calling this method with no arguments will return a list of all the states that are currently registered.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @return a list of [[StateDeclaration]]s\n */\n get(): StateDeclaration[];\n\n /**\n * Gets a registered state\n *\n * Given a state or a name, finds and returns the [[StateDeclaration]] from the registry.\n * Note: this does not return states that are *queued* but not yet registered.\n *\n * @param stateOrName either the name of a state, or a state object.\n * @param base the base state to use when stateOrName is relative.\n * @return a registered [[StateDeclaration]] that matched the `stateOrName`, or null if the state isn't registered.\n */\n get(stateOrName: StateOrName, base?: StateOrName): StateDeclaration;\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n if (arguments.length === 0) return Object.keys(this.states).map(name => this.states[name].self);\n const found = this.matcher.find(stateOrName, base);\n return (found && found.self) || null;\n }\n\n decorator(name: string, func: BuilderFunction) {\n return this.builder.builder(name, func);\n }\n}\n", + "/**\n * @coreapi\n * @module url\n */\n/** for typedoc */\nimport {\n map,\n defaults,\n inherit,\n identity,\n unnest,\n tail,\n find,\n Obj,\n pairs,\n allTrueR,\n unnestR,\n arrayTuples,\n} from '../common/common';\nimport { prop, propEq } from '../common/hof';\nimport { isArray, isString, isDefined } from '../common/predicates';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { RawParams } from '../params/interface';\nimport { ParamFactory } from './interface';\nimport { joinNeighborsR, splitOnDelim } from '../common/strings';\n\n/** @hidden */\nfunction quoteRegExp(str: any, param?: any) {\n let surroundPattern = ['', ''],\n result = str.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, '\\\\$&');\n if (!param) return result;\n\n switch (param.squash) {\n case false:\n surroundPattern = ['(', ')' + (param.isOptional ? '?' : '')];\n break;\n case true:\n result = result.replace(/\\/$/, '');\n surroundPattern = ['(?:/(', ')|/)?'];\n break;\n default:\n surroundPattern = [`(${param.squash}|`, ')?'];\n break;\n }\n return result + surroundPattern[0] + param.type.pattern.source + surroundPattern[1];\n}\n\n/** @hidden */\nconst memoizeTo = (obj: Obj, _prop: string, fn: Function) => (obj[_prop] = obj[_prop] || fn());\n\n/** @hidden */\nconst splitOnSlash = splitOnDelim('/');\n\n/** @hidden */\ninterface UrlMatcherCache {\n segments?: any[];\n weights?: number[];\n path?: UrlMatcher[];\n parent?: UrlMatcher;\n pattern?: RegExp;\n}\n\n/**\n * Matches URLs against patterns.\n *\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL.\n *\n * A URL pattern consists of a path pattern, optionally followed by '?' and a list of search (query)\n * parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by [[UrlMatcher.exec]].\n *\n * - *Path parameters* are defined using curly brace placeholders (`/somepath/{param}`)\n * or colon placeholders (`/somePath/:param`).\n *\n * - *A parameter RegExp* may be defined for a param after a colon\n * (`/somePath/{param:[a-zA-Z0-9]+}`) in a curly brace placeholder.\n * The regexp must match for the url to be matched.\n * Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Note: a RegExp parameter will encode its value using either [[ParamTypes.path]] or [[ParamTypes.query]].\n *\n * - *Custom parameter types* may also be specified after a colon (`/somePath/{param:int}`) in curly brace parameters.\n * See [[UrlMatcherFactory.type]] for more information.\n *\n * - *Catch-all parameters* are defined using an asterisk placeholder (`/somepath/*catchallparam`).\n * A catch-all * parameter value will contain the remainder of the URL.\n *\n * ---\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters).\n * A path parameter matches any number of characters other than '/'. For catch-all\n * placeholders the path parameter matches any number of characters.\n *\n * Examples:\n *\n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n * trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n * parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n * path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n * in the built-in `date` ParamType matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n */\nexport class UrlMatcher {\n /** @hidden */\n static nameValidator: RegExp = /^\\w+([-.]+\\w+)*(?:\\[\\])?$/;\n\n /** @hidden */\n private _cache: UrlMatcherCache = { path: [this] };\n /** @hidden */\n private _children: UrlMatcher[] = [];\n /** @hidden */\n private _params: Param[] = [];\n /** @hidden */\n private _segments: string[] = [];\n /** @hidden */\n private _compiled: string[] = [];\n\n /** The pattern that was passed into the constructor */\n public pattern: string;\n\n /** @hidden */\n static encodeDashes(str: string) {\n // Replace dashes with encoded \"\\-\"\n return encodeURIComponent(str).replace(\n /-/g,\n c =>\n `%5C%${c\n .charCodeAt(0)\n .toString(16)\n .toUpperCase()}`,\n );\n }\n\n /** @hidden Given a matcher, return an array with the matcher's path segments and path params, in order */\n static pathSegmentsAndParams(matcher: UrlMatcher) {\n const staticSegments = matcher._segments;\n const pathParams = matcher._params.filter(p => p.location === DefType.PATH);\n return arrayTuples(staticSegments, pathParams.concat(undefined))\n .reduce(unnestR, [])\n .filter(x => x !== '' && isDefined(x));\n }\n\n /** @hidden Given a matcher, return an array with the matcher's query params */\n static queryParams(matcher: UrlMatcher): Param[] {\n return matcher._params.filter(p => p.location === DefType.SEARCH);\n }\n\n /**\n * Compare two UrlMatchers\n *\n * This comparison function converts a UrlMatcher into static and dynamic path segments.\n * Each static path segment is a static string between a path separator (slash character).\n * Each dynamic segment is a path parameter.\n *\n * The comparison function sorts static segments before dynamic ones.\n */\n static compare(a: UrlMatcher, b: UrlMatcher): number {\n /**\n * Turn a UrlMatcher and all its parent matchers into an array\n * of slash literals '/', string literals, and Param objects\n *\n * This example matcher matches strings like \"/foo/:param/tail\":\n * var matcher = $umf.compile(\"/foo\").append($umf.compile(\"/:param\")).append($umf.compile(\"/\")).append($umf.compile(\"tail\"));\n * var result = segments(matcher); // [ '/', 'foo', '/', Param, '/', 'tail' ]\n *\n * Caches the result as `matcher._cache.segments`\n */\n const segments = (matcher: UrlMatcher) =>\n (matcher._cache.segments =\n matcher._cache.segments ||\n matcher._cache.path\n .map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .reduce(joinNeighborsR, [])\n .map(x => (isString(x) ? splitOnSlash(x) : x))\n .reduce(unnestR, []));\n\n /**\n * Gets the sort weight for each segment of a UrlMatcher\n *\n * Caches the result as `matcher._cache.weights`\n */\n const weights = (matcher: UrlMatcher) =>\n (matcher._cache.weights =\n matcher._cache.weights ||\n segments(matcher).map(segment => {\n // Sort slashes first, then static strings, the Params\n if (segment === '/') return 1;\n if (isString(segment)) return 2;\n if (segment instanceof Param) return 3;\n }));\n\n /**\n * Pads shorter array in-place (mutates)\n */\n const padArrays = (l: any[], r: any[], padVal: any) => {\n const len = Math.max(l.length, r.length);\n while (l.length < len) l.push(padVal);\n while (r.length < len) r.push(padVal);\n };\n\n const weightsA = weights(a),\n weightsB = weights(b);\n padArrays(weightsA, weightsB, 0);\n\n const _pairs = arrayTuples(weightsA, weightsB);\n let cmp, i;\n\n for (i = 0; i < _pairs.length; i++) {\n cmp = _pairs[i][0] - _pairs[i][1];\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n }\n\n /**\n * @param pattern The pattern to compile into a matcher.\n * @param paramTypes The [[ParamTypes]] registry\n * @param config A configuration object\n * - `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * - `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n */\n constructor(pattern: string, paramTypes: ParamTypes, paramFactory: ParamFactory, public config?: any) {\n this.pattern = pattern;\n this.config = defaults(this.config, {\n params: {},\n strict: true,\n caseInsensitive: false,\n paramMap: identity,\n });\n\n // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n // '*' name\n // ':' name\n // '{' name '}'\n // '{' name ':' regexp '}'\n // The regular expression is somewhat complicated due to the need to allow curly braces\n // inside the regular expression. The placeholder regexp breaks down as follows:\n // ([:*])([\\w\\[\\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)\n // \\{([\\w\\[\\]]+)(?:\\:\\s*( ... ))?\\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either\n // [^{}\\\\]+ - anything other than curly braces or backslash\n // \\\\. - a backslash escape\n // \\{(?:[^{}\\\\]+|\\\\.)*\\} - a matched set of curly braces containing other atoms\n const placeholder = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const searchPlaceholder = /([:]?)([\\w\\[\\].-]+)|\\{([\\w\\[\\].-]+)(?:\\:\\s*((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g;\n const patterns: any[][] = [];\n let last = 0,\n matchArray: RegExpExecArray;\n\n const checkParamErrors = (id: string) => {\n if (!UrlMatcher.nameValidator.test(id)) throw new Error(`Invalid parameter name '${id}' in pattern '${pattern}'`);\n if (find(this._params, propEq('id', id)))\n throw new Error(`Duplicate parameter name '${id}' in pattern '${pattern}'`);\n };\n\n // Split into static segments separated by path parameter placeholders.\n // The number of segments is always 1 more than the number of parameters.\n const matchDetails = (m: RegExpExecArray, isSearch: boolean) => {\n // IE[78] returns '' for unmatched groups instead of null\n const id: string = m[2] || m[3];\n const regexp: string = isSearch ? m[4] : m[4] || (m[1] === '*' ? '[\\\\s\\\\S]*' : null);\n\n const makeRegexpType = str =>\n inherit(paramTypes.type(isSearch ? 'query' : 'path'), {\n pattern: new RegExp(str, this.config.caseInsensitive ? 'i' : undefined),\n });\n\n return {\n id,\n regexp,\n cfg: this.config.params[id],\n segment: pattern.substring(last, m.index),\n type: !regexp ? null : paramTypes.type(regexp) || makeRegexpType(regexp),\n };\n };\n\n let p: any, segment: string;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = placeholder.exec(pattern))) {\n p = matchDetails(matchArray, false);\n if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromPath(p.id, p.type, this.config.paramMap(p.cfg, false)));\n this._segments.push(p.segment);\n patterns.push([p.segment, tail(this._params)]);\n last = placeholder.lastIndex;\n }\n segment = pattern.substring(last);\n\n // Find any search parameter names and remove them from the last segment\n const i = segment.indexOf('?');\n\n if (i >= 0) {\n const search = segment.substring(i);\n segment = segment.substring(0, i);\n\n if (search.length > 0) {\n last = 0;\n\n // tslint:disable-next-line:no-conditional-assignment\n while ((matchArray = searchPlaceholder.exec(search))) {\n p = matchDetails(matchArray, true);\n checkParamErrors(p.id);\n this._params.push(paramFactory.fromSearch(p.id, p.type, this.config.paramMap(p.cfg, true)));\n last = placeholder.lastIndex;\n // check if ?&\n }\n }\n }\n\n this._segments.push(segment);\n this._compiled = patterns.map(_pattern => quoteRegExp.apply(null, _pattern)).concat(quoteRegExp(segment));\n }\n\n /**\n * Creates a new concatenated UrlMatcher\n *\n * Builds a new UrlMatcher by appending another UrlMatcher to this one.\n *\n * @param url A `UrlMatcher` instance to append as a child of the current `UrlMatcher`.\n */\n append(url: UrlMatcher): UrlMatcher {\n this._children.push(url);\n url._cache = {\n path: this._cache.path.concat(url),\n parent: this,\n pattern: null,\n };\n return url;\n }\n\n /** @hidden */\n isRoot(): boolean {\n return this._cache.path[0] === this;\n }\n\n /** Returns the input pattern string */\n toString(): string {\n return this.pattern;\n }\n\n /**\n * Tests the specified url/path against this matcher.\n *\n * Tests if the given url matches this matcher's pattern, and returns an object containing the captured\n * parameter values. Returns null if the path does not match.\n *\n * The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `search`. This means that search parameters are always treated\n * as optional.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n * x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * ```\n *\n * @param path The URL path to match, e.g. `$location.path()`.\n * @param search URL search parameters, e.g. `$location.search()`.\n * @param hash URL hash e.g. `$location.hash()`.\n * @param options\n *\n * @returns The captured parameter values.\n */\n exec(path: string, search: any = {}, hash?: string, options: any = {}): RawParams {\n const match = memoizeTo(this._cache, 'pattern', () => {\n return new RegExp(\n [\n '^',\n unnest(this._cache.path.map(prop('_compiled'))).join(''),\n this.config.strict === false ? '/?' : '',\n '$',\n ].join(''),\n this.config.caseInsensitive ? 'i' : undefined,\n );\n }).exec(path);\n\n if (!match) return null;\n\n // options = defaults(options, { isolate: false });\n\n const allParams: Param[] = this.parameters(),\n pathParams: Param[] = allParams.filter(param => !param.isSearch()),\n searchParams: Param[] = allParams.filter(param => param.isSearch()),\n nPathSegments = this._cache.path.map(urlm => urlm._segments.length - 1).reduce((a, x) => a + x),\n values: RawParams = {};\n\n if (nPathSegments !== match.length - 1) throw new Error(`Unbalanced capture group in route '${this.pattern}'`);\n\n function decodePathArray(paramVal: string) {\n const reverseString = (str: string) =>\n str\n .split('')\n .reverse()\n .join('');\n const unquoteDashes = (str: string) => str.replace(/\\\\-/g, '-');\n\n const split = reverseString(paramVal).split(/-(?!\\\\)/);\n const allReversed = map(split, reverseString);\n return map(allReversed, unquoteDashes).reverse();\n }\n\n for (let i = 0; i < nPathSegments; i++) {\n const param: Param = pathParams[i];\n let value: any | any[] = match[i + 1];\n\n // if the param value matches a pre-replace pair, replace the value before decoding.\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (value && param.array === true) value = decodePathArray(value);\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n }\n searchParams.forEach(param => {\n let value = search[param.id];\n for (let j = 0; j < param.replace.length; j++) {\n if (param.replace[j].from === value) value = param.replace[j].to;\n }\n if (isDefined(value)) value = param.type.decode(value);\n values[param.id] = param.value(value);\n });\n\n if (hash) values['#'] = hash;\n\n return values;\n }\n\n /**\n * @hidden\n * Returns all the [[Param]] objects of all path and search parameters of this pattern in order of appearance.\n *\n * @returns {Array.} An array of [[Param]] objects. Must be treated as read-only. If the\n * pattern has no parameters, an empty array is returned.\n */\n parameters(opts: any = {}): Param[] {\n if (opts.inherit === false) return this._params;\n return unnest(this._cache.path.map(matcher => matcher._params));\n }\n\n /**\n * @hidden\n * Returns a single parameter from this UrlMatcher by id\n *\n * @param id\n * @param opts\n * @returns {T|Param|any|boolean|UrlMatcher|null}\n */\n parameter(id: string, opts: any = {}): Param {\n const findParam = () => {\n for (const param of this._params) {\n if (param.id === id) return param;\n }\n };\n\n const parent = this._cache.parent;\n return findParam() || (opts.inherit !== false && parent && parent.parameter(id, opts)) || null;\n }\n\n /**\n * Validates the input parameter values against this UrlMatcher\n *\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param params The object hash of parameters to validate.\n * @returns Returns `true` if `params` validates, otherwise `false`.\n */\n validates(params: RawParams): boolean {\n const validParamVal = (param: Param, val: any) => !param || param.validates(val);\n\n params = params || {};\n\n // I'm not sure why this checks only the param keys passed in, and not all the params known to the matcher\n const paramSchema = this.parameters().filter(paramDef => params.hasOwnProperty(paramDef.id));\n return paramSchema.map(paramDef => validParamVal(paramDef, params[paramDef.id])).reduce(allTrueR, true);\n }\n\n /**\n * Given a set of parameter values, creates a URL from this UrlMatcher.\n *\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters.\n *\n * #### Example:\n * ```js\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * ```\n *\n * @param values the values to substitute for the parameters in this pattern.\n * @returns the formatted URL (path and optionally search part).\n */\n format(values: RawParams = {}) {\n // Build the full path of UrlMatchers (including all parent UrlMatchers)\n const urlMatchers = this._cache.path;\n\n // Extract all the static segments and Params (processed as ParamDetails)\n // into an ordered array\n const pathSegmentsAndParams: Array = urlMatchers\n .map(UrlMatcher.pathSegmentsAndParams)\n .reduce(unnestR, [])\n .map(x => (isString(x) ? x : getDetails(x)));\n\n // Extract the query params into a separate array\n const queryParams: Array = urlMatchers\n .map(UrlMatcher.queryParams)\n .reduce(unnestR, [])\n .map(getDetails);\n\n const isInvalid = (param: ParamDetails) => param.isValid === false;\n if (pathSegmentsAndParams.concat(queryParams).filter(isInvalid).length) {\n return null;\n }\n\n /**\n * Given a Param, applies the parameter value, then returns detailed information about it\n */\n function getDetails(param: Param): ParamDetails {\n // Normalize to typed value\n const value = param.value(values[param.id]);\n const isValid = param.validates(value);\n const isDefaultValue = param.isDefaultValue(value);\n // Check if we're in squash mode for the parameter\n const squash = isDefaultValue ? param.squash : false;\n // Allow the Parameter's Type to encode the value\n const encoded = param.type.encode(value);\n\n return { param, value, isValid, isDefaultValue, squash, encoded };\n }\n\n // Build up the path-portion from the list of static segments and parameters\n const pathString = pathSegmentsAndParams.reduce((acc: string, x: string | ParamDetails) => {\n // The element is a static segment (a raw string); just append it\n if (isString(x)) return acc + x;\n\n // Otherwise, it's a ParamDetails.\n const { squash, encoded, param } = x;\n\n // If squash is === true, try to remove a slash from the path\n if (squash === true) return acc.match(/\\/$/) ? acc.slice(0, -1) : acc;\n // If squash is a string, use the string for the param value\n if (isString(squash)) return acc + squash;\n if (squash !== false) return acc; // ?\n if (encoded == null) return acc;\n // If this parameter value is an array, encode the value using encodeDashes\n if (isArray(encoded)) return acc + map(encoded, UrlMatcher.encodeDashes).join('-');\n // If the parameter type is \"raw\", then do not encodeURIComponent\n if (param.raw) return acc + encoded;\n // Encode the value\n return acc + encodeURIComponent(encoded);\n }, '');\n\n // Build the query string by applying parameter values (array or regular)\n // then mapping to key=value, then flattening and joining using \"&\"\n const queryString = queryParams\n .map((paramDetails: ParamDetails) => {\n let { param, squash, encoded, isDefaultValue } = paramDetails;\n if (encoded == null || (isDefaultValue && squash !== false)) return;\n if (!isArray(encoded)) encoded = [encoded];\n if (encoded.length === 0) return;\n if (!param.raw) encoded = map(encoded, encodeURIComponent);\n\n return (encoded).map(val => `${param.id}=${val}`);\n })\n .filter(identity)\n .reduce(unnestR, [])\n .join('&');\n\n // Concat the pathstring with the queryString (if exists) and the hashString (if exists)\n return pathString + (queryString ? `?${queryString}` : '') + (values['#'] ? '#' + values['#'] : '');\n }\n}\n\n/** @hidden */\ninterface ParamDetails {\n param: Param;\n value: any;\n isValid: boolean;\n isDefaultValue: boolean;\n squash: boolean | string;\n encoded: string | string[];\n}\n", + "/**\n * @internalapi\n * @module url\n */ /** for typedoc */\nimport { forEach, extend } from '../common/common';\nimport { isObject, isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { Param, DefType } from '../params/param';\nimport { ParamTypes } from '../params/paramTypes';\nimport { ParamTypeDefinition } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { ParamType } from '../params/paramType';\nimport { ParamFactory, UrlMatcherConfig } from './interface';\n\n/**\n * Factory for [[UrlMatcher]] instances.\n *\n * The factory is available to ng1 services as\n * `$urlMatcherFactory` or ng1 providers as `$urlMatcherFactoryProvider`.\n */\nexport class UrlMatcherFactory implements Disposable, UrlMatcherConfig {\n /** @hidden */ paramTypes = new ParamTypes();\n /** @hidden */ _isCaseInsensitive = false;\n /** @hidden */ _isStrictMode = true;\n /** @hidden */ _defaultSquashPolicy: boolean | string = false;\n\n /** @internalapi Creates a new [[Param]] for a given location (DefType) */\n paramFactory: ParamFactory = {\n /** Creates a new [[Param]] from a CONFIG block */\n fromConfig: (id: string, type: ParamType, config: any) => new Param(id, type, config, DefType.CONFIG, this),\n\n /** Creates a new [[Param]] from a url PATH */\n fromPath: (id: string, type: ParamType, config: any) => new Param(id, type, config, DefType.PATH, this),\n\n /** Creates a new [[Param]] from a url SEARCH */\n fromSearch: (id: string, type: ParamType, config: any) => new Param(id, type, config, DefType.SEARCH, this),\n };\n\n constructor() {\n extend(this, { UrlMatcher, Param });\n }\n\n /** @inheritdoc */\n caseInsensitive(value?: boolean): boolean {\n return (this._isCaseInsensitive = isDefined(value) ? value : this._isCaseInsensitive);\n }\n\n /** @inheritdoc */\n strictMode(value?: boolean): boolean {\n return (this._isStrictMode = isDefined(value) ? value : this._isStrictMode);\n }\n\n /** @inheritdoc */\n defaultSquashPolicy(value?: boolean | string) {\n if (isDefined(value) && value !== true && value !== false && !isString(value))\n throw new Error(`Invalid squash policy: ${value}. Valid policies: false, true, arbitrary-string`);\n return (this._defaultSquashPolicy = isDefined(value) ? value : this._defaultSquashPolicy);\n }\n\n /** @hidden */\n private _getConfig = config =>\n extend({ strict: this._isStrictMode, caseInsensitive: this._isCaseInsensitive }, config);\n\n /**\n * Creates a [[UrlMatcher]] for the specified pattern.\n *\n * @param pattern The URL pattern.\n * @param config The config object hash.\n * @returns The UrlMatcher.\n */\n compile(pattern: string, config?: { [key: string]: any }) {\n return new UrlMatcher(pattern, this.paramTypes, this.paramFactory, this._getConfig(config));\n }\n\n /**\n * Returns true if the specified object is a [[UrlMatcher]], or false otherwise.\n *\n * @param object The object to perform the type check against.\n * @returns `true` if the object matches the `UrlMatcher` interface, by\n * implementing all the same methods.\n */\n isMatcher(object: any): boolean {\n // TODO: typeof?\n if (!isObject(object)) return false;\n let result = true;\n\n forEach(UrlMatcher.prototype, (val, name) => {\n if (isFunction(val)) result = result && (isDefined(object[name]) && isFunction(object[name]));\n });\n return result;\n }\n\n /**\n * Creates and registers a custom [[ParamType]] object\n *\n * A [[ParamType]] can be used to generate URLs with typed parameters.\n *\n * @param name The type name.\n * @param definition The type definition. See [[ParamTypeDefinition]] for information on the values accepted.\n * @param definitionFn A function that is injected before the app runtime starts.\n * The result of this function should be a [[ParamTypeDefinition]].\n * The result is merged into the existing `definition`.\n * See [[ParamType]] for information on the values accepted.\n *\n * @returns - if a type was registered: the [[UrlMatcherFactory]]\n * - if only the `name` parameter was specified: the currently registered [[ParamType]] object, or undefined\n *\n * Note: Register custom types *before using them* in a state definition.\n *\n * See [[ParamTypeDefinition]] for examples\n */\n type(name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) {\n const type = this.paramTypes.type(name, definition, definitionFn);\n return !isDefined(definition) ? type : this;\n }\n\n /** @hidden */\n $get() {\n this.paramTypes.enqueue = false;\n this.paramTypes._flushTypeQueue();\n return this;\n }\n\n /** @internalapi */\n dispose() {\n this.paramTypes.dispose();\n }\n}\n", + "/**\n * @coreapi\n * @module url\n */ /** */\nimport { UrlMatcher } from './urlMatcher';\nimport { isString, isDefined, isFunction, isState } from '../common/predicates';\nimport { UIRouter } from '../router';\nimport { identity, extend } from '../common/common';\nimport { is, pattern } from '../common/hof';\nimport { StateObject } from '../state/stateObject';\nimport { RawParams } from '../params/interface';\nimport {\n UrlRule,\n UrlRuleMatchFn,\n UrlRuleHandlerFn,\n UrlRuleType,\n UrlParts,\n MatcherUrlRule,\n StateRule,\n RegExpRule,\n} from './interface';\n\n/**\n * Creates a [[UrlRule]]\n *\n * Creates a [[UrlRule]] from a:\n *\n * - `string`\n * - [[UrlMatcher]]\n * - `RegExp`\n * - [[StateObject]]\n * @internalapi\n */\nexport class UrlRuleFactory {\n static isUrlRule = obj => obj && ['type', 'match', 'handler'].every(key => isDefined(obj[key]));\n\n constructor(public router: UIRouter) {}\n\n compile(str: string) {\n return this.router.urlMatcherFactory.compile(str);\n }\n\n create(\n what: string | UrlMatcher | StateObject | RegExp | UrlRuleMatchFn,\n handler?: string | UrlRuleHandlerFn,\n ): UrlRule {\n const makeRule = pattern([\n [isString, (_what: string) => makeRule(this.compile(_what))],\n [is(UrlMatcher), (_what: UrlMatcher) => this.fromUrlMatcher(_what, handler)],\n [isState, (_what: StateObject) => this.fromState(_what, this.router)],\n [is(RegExp), (_what: RegExp) => this.fromRegExp(_what, handler)],\n [isFunction, (_what: UrlRuleMatchFn) => new BaseUrlRule(_what, handler as UrlRuleHandlerFn)],\n ]);\n\n const rule = makeRule(what);\n if (!rule) throw new Error(\"invalid 'what' in when()\");\n return rule;\n }\n\n /**\n * A UrlRule which matches based on a UrlMatcher\n *\n * The `handler` may be either a `string`, a [[UrlRuleHandlerFn]] or another [[UrlMatcher]]\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - matched parameter values ([[RawParams]] from [[UrlMatcher.exec]])\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, match => \"/home/\" + match.fooId + \"/\" + match.barId);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n *\n * ## Handler as UrlMatcher\n *\n * If `handler` is a UrlMatcher, the handler matcher is used to create the new url.\n * The `handler` UrlMatcher is formatted using the matched param from the first matcher.\n * The url is replaced with the result.\n *\n * #### Example:\n * ```js\n * var urlMatcher = $umf.compile(\"/foo/:fooId/:barId\");\n * var handler = $umf.compile(\"/home/:fooId/:barId\");\n * var rule = factory.fromUrlMatcher(urlMatcher, handler);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match); // '/home/123/456'\n * ```\n */\n fromUrlMatcher(urlMatcher: UrlMatcher, handler: string | UrlMatcher | UrlRuleHandlerFn): MatcherUrlRule {\n let _handler: UrlRuleHandlerFn = handler as any;\n if (isString(handler)) handler = this.router.urlMatcherFactory.compile(handler);\n if (is(UrlMatcher)(handler)) _handler = (match: RawParams) => (handler as UrlMatcher).format(match);\n\n function matchUrlParamters(url: UrlParts): RawParams {\n const params = urlMatcher.exec(url.path, url.search, url.hash);\n return urlMatcher.validates(params) && params;\n }\n\n // Prioritize URLs, lowest to highest:\n // - Some optional URL parameters, but none matched\n // - No optional parameters in URL\n // - Some optional parameters, some matched\n // - Some optional parameters, all matched\n function matchPriority(params: RawParams): number {\n const optional = urlMatcher.parameters().filter(param => param.isOptional);\n if (!optional.length) return 0.000001;\n const matched = optional.filter(param => params[param.id]);\n return matched.length / optional.length;\n }\n\n const details = { urlMatcher, matchPriority, type: 'URLMATCHER' };\n return extend(new BaseUrlRule(matchUrlParamters, _handler), details) as MatcherUrlRule;\n }\n\n /**\n * A UrlRule which matches a state by its url\n *\n * #### Example:\n * ```js\n * var rule = factory.fromState($state.get('foo'), router);\n * var match = rule.match('/foo/123/456'); // results in { fooId: '123', barId: '456' }\n * var result = rule.handler(match);\n * // Starts a transition to 'foo' with params: { fooId: '123', barId: '456' }\n * ```\n */\n fromState(state: StateObject, router: UIRouter): StateRule {\n /**\n * Handles match by transitioning to matched state\n *\n * First checks if the router should start a new transition.\n * A new transition is not required if the current state's URL\n * and the new URL are already identical\n */\n const handler = (match: RawParams) => {\n const $state = router.stateService;\n const globals = router.globals;\n if ($state.href(state, match) !== $state.href(globals.current, globals.params)) {\n $state.transitionTo(state, match, { inherit: true, source: 'url' });\n }\n };\n\n const details = { state, type: 'STATE' };\n return extend(this.fromUrlMatcher(state.url, handler), details) as StateRule;\n }\n\n /**\n * A UrlRule which matches based on a regular expression\n *\n * The `handler` may be either a [[UrlRuleHandlerFn]] or a string.\n *\n * ## Handler as a function\n *\n * If `handler` is a function, the function is invoked with:\n *\n * - regexp match array (from `regexp`)\n * - url: the current Url ([[UrlParts]])\n * - router: the router object ([[UIRouter]])\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, match => \"/home/\" + match[1])\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n *\n * ## Handler as string\n *\n * If `handler` is a string, the url is *replaced by the string* when the Rule is invoked.\n * The string is first interpolated using `string.replace()` style pattern.\n *\n * #### Example:\n * ```js\n * var rule = factory.fromRegExp(/^\\/foo\\/(bar|baz)$/, \"/home/$1\")\n * var match = rule.match('/foo/bar'); // results in [ '/foo/bar', 'bar' ]\n * var result = rule.handler(match); // '/home/bar'\n * ```\n */\n fromRegExp(regexp: RegExp, handler: string | UrlRuleHandlerFn): RegExpRule {\n if (regexp.global || regexp.sticky) throw new Error('Rule RegExp must not be global or sticky');\n\n /**\n * If handler is a string, the url will be replaced by the string.\n * If the string has any String.replace() style variables in it (like `$2`),\n * they will be replaced by the captures from [[match]]\n */\n const redirectUrlTo = (match: RegExpExecArray) =>\n // Interpolates matched values into $1 $2, etc using a String.replace()-style pattern\n (handler as string).replace(/\\$(\\$|\\d{1,2})/, (m, what) => match[what === '$' ? 0 : Number(what)]);\n\n const _handler = isString(handler) ? redirectUrlTo : handler;\n\n const matchParamsFromRegexp = (url: UrlParts): RegExpExecArray => regexp.exec(url.path);\n\n const details = { regexp, type: 'REGEXP' };\n return extend(new BaseUrlRule(matchParamsFromRegexp, _handler), details) as RegExpRule;\n }\n}\n\n/**\n * A base rule which calls `match`\n *\n * The value from the `match` function is passed through to the `handler`.\n * @internalapi\n */\nexport class BaseUrlRule implements UrlRule {\n $id: number;\n priority: number;\n type: UrlRuleType = 'RAW';\n handler: UrlRuleHandlerFn;\n matchPriority = match => 0 - this.$id;\n\n constructor(public match: UrlRuleMatchFn, handler?: UrlRuleHandlerFn) {\n this.handler = handler || identity;\n }\n}\n", + "/**\n * @internalapi\n * @module url\n */\n/** for typedoc */\nimport { createProxyFunctions, extend, removeFrom } from '../common/common';\nimport { isDefined, isFunction, isString } from '../common/predicates';\nimport { UrlMatcher } from './urlMatcher';\nimport { RawParams } from '../params/interface';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { is, pattern, val } from '../common/hof';\nimport { UrlRuleFactory } from './urlRule';\nimport { TargetState } from '../state/targetState';\nimport {\n MatcherUrlRule,\n MatchResult,\n UrlParts,\n UrlRule,\n UrlRuleHandlerFn,\n UrlRuleMatchFn,\n UrlRulesApi,\n UrlSyncApi,\n} from './interface';\nimport { TargetStateDef } from '../state/interface';\nimport { stripLastPathElement } from '../common';\n\n/** @hidden */\nfunction appendBasePath(url: string, isHtml5: boolean, absolute: boolean, baseHref: string): string {\n if (baseHref === '/') return url;\n if (isHtml5) return stripLastPathElement(baseHref) + url;\n if (absolute) return baseHref.slice(1) + url;\n return url;\n}\n\n/** @hidden */\nconst prioritySort = (a: UrlRule, b: UrlRule) => (b.priority || 0) - (a.priority || 0);\n\n/** @hidden */\nconst typeSort = (a: UrlRule, b: UrlRule) => {\n const weights = { STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1 };\n return (weights[a.type] || 0) - (weights[b.type] || 0);\n};\n\n/** @hidden */\nconst urlMatcherSort = (a: MatcherUrlRule, b: MatcherUrlRule) =>\n !a.urlMatcher || !b.urlMatcher ? 0 : UrlMatcher.compare(a.urlMatcher, b.urlMatcher);\n\n/** @hidden */\nconst idSort = (a: UrlRule, b: UrlRule) => {\n // Identically sorted STATE and URLMATCHER best rule will be chosen by `matchPriority` after each rule matches the URL\n const useMatchPriority = { STATE: true, URLMATCHER: true };\n const equal = useMatchPriority[a.type] && useMatchPriority[b.type];\n return equal ? 0 : (a.$id || 0) - (b.$id || 0);\n};\n\n/**\n * Default rule priority sorting function.\n *\n * Sorts rules by:\n *\n * - Explicit priority (set rule priority using [[UrlRulesApi.when]])\n * - Rule type (STATE: 4, URLMATCHER: 4, REGEXP: 3, RAW: 2, OTHER: 1)\n * - `UrlMatcher` specificity ([[UrlMatcher.compare]]): works for STATE and URLMATCHER types to pick the most specific rule.\n * - Rule registration order (for rule types other than STATE and URLMATCHER)\n * - Equally sorted State and UrlMatcher rules will each match the URL.\n * Then, the *best* match is chosen based on how many parameter values were matched.\n *\n * @coreapi\n */\nlet defaultRuleSortFn: (a: UrlRule, b: UrlRule) => number;\ndefaultRuleSortFn = (a, b) => {\n let cmp = prioritySort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = typeSort(a, b);\n if (cmp !== 0) return cmp;\n\n cmp = urlMatcherSort(a as MatcherUrlRule, b as MatcherUrlRule);\n if (cmp !== 0) return cmp;\n\n return idSort(a, b);\n};\n\n/**\n * Updates URL and responds to URL changes\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class updates the URL when the state changes.\n * It also responds to changes in the URL.\n */\nexport class UrlRouter implements UrlRulesApi, UrlSyncApi, Disposable {\n /** used to create [[UrlRule]] objects for common cases */\n public urlRuleFactory: UrlRuleFactory;\n\n /** @hidden */ private _router: UIRouter;\n /** @hidden */ private location: string;\n /** @hidden */ private _sortFn = defaultRuleSortFn;\n /** @hidden */ private _stopFn: Function;\n /** @hidden */ _rules: UrlRule[] = [];\n /** @hidden */ private _otherwiseFn: UrlRule;\n /** @hidden */ interceptDeferred = false;\n /** @hidden */ private _id = 0;\n /** @hidden */ private _sorted = false;\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this.urlRuleFactory = new UrlRuleFactory(router);\n createProxyFunctions(val(UrlRouter.prototype), this, val(this));\n }\n\n /** @internalapi */\n dispose() {\n this.listen(false);\n this._rules = [];\n delete this._otherwiseFn;\n }\n\n /** @inheritdoc */\n sort(compareFn?: (a: UrlRule, b: UrlRule) => number) {\n this._rules = this.stableSort(this._rules, (this._sortFn = compareFn || this._sortFn));\n this._sorted = true;\n }\n\n private ensureSorted() {\n this._sorted || this.sort();\n }\n\n private stableSort(arr, compareFn) {\n const arrOfWrapper = arr.map((elem, idx) => ({ elem, idx }));\n\n arrOfWrapper.sort((wrapperA, wrapperB) => {\n const cmpDiff = compareFn(wrapperA.elem, wrapperB.elem);\n return cmpDiff === 0 ? wrapperA.idx - wrapperB.idx : cmpDiff;\n });\n\n return arrOfWrapper.map(wrapper => wrapper.elem);\n }\n\n /**\n * Given a URL, check all rules and return the best [[MatchResult]]\n * @param url\n * @returns {MatchResult}\n */\n match(url: UrlParts): MatchResult {\n this.ensureSorted();\n\n url = extend({ path: '', search: {}, hash: '' }, url);\n const rules = this.rules();\n if (this._otherwiseFn) rules.push(this._otherwiseFn);\n\n // Checks a single rule. Returns { rule: rule, match: match, weight: weight } if it matched, or undefined\n\n const checkRule = (rule: UrlRule): MatchResult => {\n const match = rule.match(url, this._router);\n return match && { match, rule, weight: rule.matchPriority(match) };\n };\n\n // The rules are pre-sorted.\n // - Find the first matching rule.\n // - Find any other matching rule that sorted *exactly the same*, according to `.sort()`.\n // - Choose the rule with the highest match weight.\n let best: MatchResult;\n for (let i = 0; i < rules.length; i++) {\n // Stop when there is a 'best' rule and the next rule sorts differently than it.\n if (best && this._sortFn(rules[i], best.rule) !== 0) break;\n\n const current = checkRule(rules[i]);\n // Pick the best MatchResult\n best = !best || (current && current.weight > best.weight) ? current : best;\n }\n\n return best;\n }\n\n /** @inheritdoc */\n sync(evt?) {\n if (evt && evt.defaultPrevented) return;\n\n const router = this._router,\n $url = router.urlService,\n $state = router.stateService;\n\n const url: UrlParts = {\n path: $url.path(),\n search: $url.search(),\n hash: $url.hash(),\n };\n\n const best = this.match(url);\n\n const applyResult = pattern([\n [isString, (newurl: string) => $url.url(newurl, true)],\n [TargetState.isDef, (def: TargetStateDef) => $state.go(def.state, def.params, def.options)],\n [is(TargetState), (target: TargetState) => $state.go(target.state(), target.params(), target.options())],\n ]);\n\n applyResult(best && best.rule.handler(best.match, url, router));\n }\n\n /** @inheritdoc */\n listen(enabled?: boolean): Function {\n if (enabled === false) {\n this._stopFn && this._stopFn();\n delete this._stopFn;\n } else {\n return (this._stopFn = this._stopFn || this._router.urlService.onChange(evt => this.sync(evt)));\n }\n }\n\n /**\n * Internal API.\n * @internalapi\n */\n update(read?: boolean) {\n const $url = this._router.locationService;\n if (read) {\n this.location = $url.url();\n return;\n }\n if ($url.url() === this.location) return;\n\n $url.url(this.location, true);\n }\n\n /**\n * Internal API.\n *\n * Pushes a new location to the browser history.\n *\n * @internalapi\n * @param urlMatcher\n * @param params\n * @param options\n */\n push(urlMatcher: UrlMatcher, params?: RawParams, options?: { replace?: string | boolean }) {\n const replace = options && !!options.replace;\n this._router.urlService.url(urlMatcher.format(params || {}), replace);\n }\n\n /**\n * Builds and returns a URL with interpolated parameters\n *\n * #### Example:\n * ```js\n * matcher = $umf.compile(\"/about/:person\");\n * params = { person: \"bob\" };\n * $bob = $urlRouter.href(matcher, params);\n * // $bob == \"/about/bob\";\n * ```\n *\n * @param urlMatcher The [[UrlMatcher]] object which is used as the template of the URL to generate.\n * @param params An object of parameter values to fill the matcher's required parameters.\n * @param options Options object. The options are:\n *\n * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n *\n * @returns Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n */\n href(urlMatcher: UrlMatcher, params?: any, options?: { absolute: boolean }): string {\n let url = urlMatcher.format(params);\n if (url == null) return null;\n\n options = options || { absolute: false };\n\n const cfg = this._router.urlService.config;\n const isHtml5 = cfg.html5Mode();\n if (!isHtml5 && url !== null) {\n url = '#' + cfg.hashPrefix() + url;\n }\n url = appendBasePath(url, isHtml5, options.absolute, cfg.baseHref());\n\n if (!options.absolute || !url) {\n return url;\n }\n\n const slash = !isHtml5 && url ? '/' : '';\n const cfgPort = cfg.port();\n const port = (cfgPort === 80 || cfgPort === 443 ? '' : ':' + cfgPort);\n\n return [cfg.protocol(), '://', cfg.host(), port, slash, url].join('');\n }\n\n /**\n * Manually adds a URL Rule.\n *\n * Usually, a url rule is added using [[StateDeclaration.url]] or [[when]].\n * This api can be used directly for more control (to register a [[BaseUrlRule]], for example).\n * Rules can be created using [[UrlRouter.urlRuleFactory]], or create manually as simple objects.\n *\n * A rule should have a `match` function which returns truthy if the rule matched.\n * It should also have a `handler` function which is invoked if the rule is the best match.\n *\n * @return a function that deregisters the rule\n */\n rule(rule: UrlRule): Function {\n if (!UrlRuleFactory.isUrlRule(rule)) throw new Error('invalid rule');\n rule.$id = this._id++;\n rule.priority = rule.priority || 0;\n\n this._rules.push(rule);\n this._sorted = false;\n\n return () => this.removeRule(rule);\n }\n\n /** @inheritdoc */\n removeRule(rule): void {\n removeFrom(this._rules, rule);\n }\n\n /** @inheritdoc */\n rules(): UrlRule[] {\n this.ensureSorted();\n return this._rules.slice();\n }\n\n /** @inheritdoc */\n otherwise(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n this._otherwiseFn = this.urlRuleFactory.create(val(true), handlerFn);\n this._sorted = false;\n }\n\n /** @inheritdoc */\n initial(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef) {\n const handlerFn: UrlRuleHandlerFn = getHandlerFn(handler);\n\n const matchFn: UrlRuleMatchFn = (urlParts, router) =>\n router.globals.transitionHistory.size() === 0 && !!/^\\/?$/.exec(urlParts.path);\n\n this.rule(this.urlRuleFactory.create(matchFn, handlerFn));\n }\n\n /** @inheritdoc */\n when(\n matcher: RegExp | UrlMatcher | string,\n handler: string | UrlRuleHandlerFn,\n options?: { priority: number },\n ): UrlRule {\n const rule = this.urlRuleFactory.create(matcher, handler);\n if (isDefined(options && options.priority)) rule.priority = options.priority;\n this.rule(rule);\n return rule;\n }\n\n /** @inheritdoc */\n deferIntercept(defer?: boolean) {\n if (defer === undefined) defer = true;\n this.interceptDeferred = defer;\n }\n}\n\nfunction getHandlerFn(handler: string | UrlRuleHandlerFn | TargetState | TargetStateDef): UrlRuleHandlerFn {\n if (!isFunction(handler) && !isString(handler) && !is(TargetState)(handler) && !TargetState.isDef(handler)) {\n throw new Error(\"'handler' must be a string, function, TargetState, or have a state: 'newtarget' property\");\n }\n return isFunction(handler) ? (handler as UrlRuleHandlerFn) : val(handler);\n}\n", + "/**\n * @coreapi\n * @module view\n */ /** for typedoc */\nimport { equals, applyPairs, removeFrom, TypedMap, inArray } from '../common/common';\nimport { curry, prop } from '../common/hof';\nimport { isString, isArray } from '../common/predicates';\nimport { trace } from '../common/trace';\nimport { PathNode } from '../path/pathNode';\nimport { ActiveUIView, ViewContext, ViewConfig } from './interface';\nimport { _ViewDeclaration } from '../state/interface';\n\nexport type ViewConfigFactory = (path: PathNode[], decl: _ViewDeclaration) => ViewConfig | ViewConfig[];\n\nexport interface ViewServicePluginAPI {\n _rootViewContext(context?: ViewContext): ViewContext;\n _viewConfigFactory(viewType: string, factory: ViewConfigFactory);\n _registeredUIViews(): ActiveUIView[];\n _activeViewConfigs(): ViewConfig[];\n _onSync(listener: ViewSyncListener): Function;\n}\n\n// A uiView and its matching viewConfig\nexport interface ViewTuple {\n uiView: ActiveUIView;\n viewConfig: ViewConfig;\n}\n\nexport interface ViewSyncListener {\n (viewTuples: ViewTuple[]): void;\n}\n\n/**\n * The View service\n *\n * This service pairs existing `ui-view` components (which live in the DOM)\n * with view configs (from the state declaration objects: [[StateDeclaration.views]]).\n *\n * - After a successful Transition, the views from the newly entered states are activated via [[activateViewConfig]].\n * The views from exited states are deactivated via [[deactivateViewConfig]].\n * (See: the [[registerActivateViews]] Transition Hook)\n *\n * - As `ui-view` components pop in and out of existence, they register themselves using [[registerUIView]].\n *\n * - When the [[sync]] function is called, the registered `ui-view`(s) ([[ActiveUIView]])\n * are configured with the matching [[ViewConfig]](s)\n *\n */\nexport class ViewService {\n private _uiViews: ActiveUIView[] = [];\n private _viewConfigs: ViewConfig[] = [];\n private _rootContext: ViewContext;\n private _viewConfigFactories: { [key: string]: ViewConfigFactory } = {};\n private _listeners: ViewSyncListener[] = [];\n\n public _pluginapi: ViewServicePluginAPI = {\n _rootViewContext: this._rootViewContext.bind(this),\n _viewConfigFactory: this._viewConfigFactory.bind(this),\n _registeredUIViews: () => this._uiViews,\n _activeViewConfigs: () => this._viewConfigs,\n _onSync: (listener: ViewSyncListener) => {\n this._listeners.push(listener);\n return () => removeFrom(this._listeners, listener);\n },\n };\n\n /**\n * Given a ui-view and a ViewConfig, determines if they \"match\".\n *\n * A ui-view has a fully qualified name (fqn) and a context object. The fqn is built from its overall location in\n * the DOM, describing its nesting relationship to any parent ui-view tags it is nested inside of.\n *\n * A ViewConfig has a target ui-view name and a context anchor. The ui-view name can be a simple name, or\n * can be a segmented ui-view path, describing a portion of a ui-view fqn.\n *\n * In order for a ui-view to match ViewConfig, ui-view's $type must match the ViewConfig's $type\n *\n * If the ViewConfig's target ui-view name is a simple name (no dots), then a ui-view matches if:\n * - the ui-view's name matches the ViewConfig's target name\n * - the ui-view's context matches the ViewConfig's anchor\n *\n * If the ViewConfig's target ui-view name is a segmented name (with dots), then a ui-view matches if:\n * - There exists a parent ui-view where:\n * - the parent ui-view's name matches the first segment (index 0) of the ViewConfig's target name\n * - the parent ui-view's context matches the ViewConfig's anchor\n * - And the remaining segments (index 1..n) of the ViewConfig's target name match the tail of the ui-view's fqn\n *\n * Example:\n *\n * DOM:\n * \n * \n * \n * \n * \n * \n * \n * \n *\n * uiViews: [\n * { fqn: \"$default\", creationContext: { name: \"\" } },\n * { fqn: \"$default.foo\", creationContext: { name: \"A\" } },\n * { fqn: \"$default.foo.$default\", creationContext: { name: \"A.B\" } }\n * { fqn: \"$default.foo.$default.bar\", creationContext: { name: \"A.B.C\" } }\n * ]\n *\n * These four view configs all match the ui-view with the fqn: \"$default.foo.$default.bar\":\n *\n * - ViewConfig1: { uiViewName: \"bar\", uiViewContextAnchor: \"A.B.C\" }\n * - ViewConfig2: { uiViewName: \"$default.bar\", uiViewContextAnchor: \"A.B\" }\n * - ViewConfig3: { uiViewName: \"foo.$default.bar\", uiViewContextAnchor: \"A\" }\n * - ViewConfig4: { uiViewName: \"$default.foo.$default.bar\", uiViewContextAnchor: \"\" }\n *\n * Using ViewConfig3 as an example, it matches the ui-view with fqn \"$default.foo.$default.bar\" because:\n * - The ViewConfig's segmented target name is: [ \"foo\", \"$default\", \"bar\" ]\n * - There exists a parent ui-view (which has fqn: \"$default.foo\") where:\n * - the parent ui-view's name \"foo\" matches the first segment \"foo\" of the ViewConfig's target name\n * - the parent ui-view's context \"A\" matches the ViewConfig's anchor context \"A\"\n * - And the remaining segments [ \"$default\", \"bar\" ].join(\".\"_ of the ViewConfig's target name match\n * the tail of the ui-view's fqn \"default.bar\"\n *\n * @internalapi\n */\n static matches = (uiViewsByFqn: TypedMap, uiView: ActiveUIView) => (viewConfig: ViewConfig) => {\n // Don't supply an ng1 ui-view with an ng2 ViewConfig, etc\n if (uiView.$type !== viewConfig.viewDecl.$type) return false;\n\n // Split names apart from both viewConfig and uiView into segments\n const vc = viewConfig.viewDecl;\n const vcSegments = vc.$uiViewName.split('.');\n const uivSegments = uiView.fqn.split('.');\n\n // Check if the tails of the segment arrays match. ex, these arrays' tails match:\n // vc: [\"foo\", \"bar\"], uiv fqn: [\"$default\", \"foo\", \"bar\"]\n if (!equals(vcSegments, uivSegments.slice(0 - vcSegments.length))) return false;\n\n // Now check if the fqn ending at the first segment of the viewConfig matches the context:\n // [\"$default\", \"foo\"].join(\".\") == \"$default.foo\", does the ui-view $default.foo context match?\n const negOffset = 1 - vcSegments.length || undefined;\n const fqnToFirstSegment = uivSegments.slice(0, negOffset).join('.');\n const uiViewContext = uiViewsByFqn[fqnToFirstSegment].creationContext;\n return vc.$uiViewContextAnchor === (uiViewContext && uiViewContext.name);\n };\n\n /**\n * Normalizes a view's name from a state.views configuration block.\n *\n * This should be used by a framework implementation to calculate the values for\n * [[_ViewDeclaration.$uiViewName]] and [[_ViewDeclaration.$uiViewContextAnchor]].\n *\n * @param context the context object (state declaration) that the view belongs to\n * @param rawViewName the name of the view, as declared in the [[StateDeclaration.views]]\n *\n * @returns the normalized uiViewName and uiViewContextAnchor that the view targets\n */\n static normalizeUIViewTarget(context: ViewContext, rawViewName = '') {\n // TODO: Validate incoming view name with a regexp to allow:\n // ex: \"view.name@foo.bar\" , \"^.^.view.name\" , \"view.name@^.^\" , \"\" ,\n // \"@\" , \"$default@^\" , \"!$default.$default\" , \"!foo.bar\"\n const viewAtContext: string[] = rawViewName.split('@');\n let uiViewName = viewAtContext[0] || '$default'; // default to unnamed view\n let uiViewContextAnchor = isString(viewAtContext[1]) ? viewAtContext[1] : '^'; // default to parent context\n\n // Handle relative view-name sugar syntax.\n // Matches rawViewName \"^.^.^.foo.bar\" into array: [\"^.^.^.foo.bar\", \"^.^.^\", \"foo.bar\"],\n const relativeViewNameSugar = /^(\\^(?:\\.\\^)*)\\.(.*$)/.exec(uiViewName);\n if (relativeViewNameSugar) {\n // Clobbers existing contextAnchor (rawViewName validation will fix this)\n uiViewContextAnchor = relativeViewNameSugar[1]; // set anchor to \"^.^.^\"\n uiViewName = relativeViewNameSugar[2]; // set view-name to \"foo.bar\"\n }\n\n if (uiViewName.charAt(0) === '!') {\n uiViewName = uiViewName.substr(1);\n uiViewContextAnchor = ''; // target absolutely from root\n }\n\n // handle parent relative targeting \"^.^.^\"\n const relativeMatch = /^(\\^(?:\\.\\^)*)$/;\n if (relativeMatch.exec(uiViewContextAnchor)) {\n const anchorState = uiViewContextAnchor.split('.').reduce((anchor, x) => anchor.parent, context);\n uiViewContextAnchor = anchorState.name;\n } else if (uiViewContextAnchor === '.') {\n uiViewContextAnchor = context.name;\n }\n\n return { uiViewName, uiViewContextAnchor };\n }\n\n constructor() {}\n\n private _rootViewContext(context?: ViewContext): ViewContext {\n return (this._rootContext = context || this._rootContext);\n }\n\n private _viewConfigFactory(viewType: string, factory: ViewConfigFactory) {\n this._viewConfigFactories[viewType] = factory;\n }\n\n createViewConfig(path: PathNode[], decl: _ViewDeclaration): ViewConfig[] {\n const cfgFactory = this._viewConfigFactories[decl.$type];\n if (!cfgFactory) throw new Error('ViewService: No view config factory registered for type ' + decl.$type);\n const cfgs = cfgFactory(path, decl);\n return isArray(cfgs) ? cfgs : [cfgs];\n }\n\n /**\n * Deactivates a ViewConfig.\n *\n * This function deactivates a `ViewConfig`.\n * After calling [[sync]], it will un-pair from any `ui-view` with which it is currently paired.\n *\n * @param viewConfig The ViewConfig view to deregister.\n */\n deactivateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('<- Removing', viewConfig);\n removeFrom(this._viewConfigs, viewConfig);\n }\n\n activateViewConfig(viewConfig: ViewConfig) {\n trace.traceViewServiceEvent('-> Registering', viewConfig);\n this._viewConfigs.push(viewConfig);\n }\n\n sync() {\n const uiViewsByFqn: TypedMap = this._uiViews.map(uiv => [uiv.fqn, uiv]).reduce(applyPairs, {});\n\n // Return a weighted depth value for a uiView.\n // The depth is the nesting depth of ui-views (based on FQN; times 10,000)\n // plus the depth of the state that is populating the uiView\n function uiViewDepth(uiView: ActiveUIView) {\n const stateDepth = (context: ViewContext) => (context && context.parent ? stateDepth(context.parent) + 1 : 1);\n return uiView.fqn.split('.').length * 10000 + stateDepth(uiView.creationContext);\n }\n\n // Return the ViewConfig's context's depth in the context tree.\n function viewConfigDepth(config: ViewConfig) {\n let context: ViewContext = config.viewDecl.$context,\n count = 0;\n while (++count && context.parent) context = context.parent;\n return count;\n }\n\n // Given a depth function, returns a compare function which can return either ascending or descending order\n const depthCompare = curry((depthFn, posNeg, left, right) => posNeg * (depthFn(left) - depthFn(right)));\n\n const matchingConfigPair = (uiView: ActiveUIView): ViewTuple => {\n const matchingConfigs = this._viewConfigs.filter(ViewService.matches(uiViewsByFqn, uiView));\n if (matchingConfigs.length > 1) {\n // This is OK. Child states can target a ui-view that the parent state also targets (the child wins)\n // Sort by depth and return the match from the deepest child\n // console.log(`Multiple matching view configs for ${uiView.fqn}`, matchingConfigs);\n matchingConfigs.sort(depthCompare(viewConfigDepth, -1)); // descending\n }\n return { uiView, viewConfig: matchingConfigs[0] };\n };\n\n const configureUIView = (tuple: ViewTuple) => {\n // If a parent ui-view is reconfigured, it could destroy child ui-views.\n // Before configuring a child ui-view, make sure it's still in the active uiViews array.\n if (this._uiViews.indexOf(tuple.uiView) !== -1) tuple.uiView.configUpdated(tuple.viewConfig);\n };\n\n // Sort views by FQN and state depth. Process uiviews nearest the root first.\n const uiViewTuples = this._uiViews.sort(depthCompare(uiViewDepth, 1)).map(matchingConfigPair);\n const matchedViewConfigs = uiViewTuples.map(tuple => tuple.viewConfig);\n const unmatchedConfigTuples = this._viewConfigs\n .filter(config => !inArray(matchedViewConfigs, config))\n .map(viewConfig => ({ uiView: undefined, viewConfig }));\n\n uiViewTuples.forEach(configureUIView);\n\n const allTuples: ViewTuple[] = uiViewTuples.concat(unmatchedConfigTuples);\n this._listeners.forEach(cb => cb(allTuples));\n trace.traceViewSync(allTuples);\n }\n\n /**\n * Registers a `ui-view` component\n *\n * When a `ui-view` component is created, it uses this method to register itself.\n * After registration the [[sync]] method is used to ensure all `ui-view` are configured with the proper [[ViewConfig]].\n *\n * Note: the `ui-view` component uses the `ViewConfig` to determine what view should be loaded inside the `ui-view`,\n * and what the view's state context is.\n *\n * Note: There is no corresponding `deregisterUIView`.\n * A `ui-view` should hang on to the return value of `registerUIView` and invoke it to deregister itself.\n *\n * @param uiView The metadata for a UIView\n * @return a de-registration function used when the view is destroyed.\n */\n registerUIView(uiView: ActiveUIView) {\n trace.traceViewServiceUIViewEvent('-> Registering', uiView);\n const uiViews = this._uiViews;\n const fqnAndTypeMatches = (uiv: ActiveUIView) => uiv.fqn === uiView.fqn && uiv.$type === uiView.$type;\n if (uiViews.filter(fqnAndTypeMatches).length)\n trace.traceViewServiceUIViewEvent('!!!! duplicate uiView named:', uiView);\n\n uiViews.push(uiView);\n this.sync();\n\n return () => {\n const idx = uiViews.indexOf(uiView);\n if (idx === -1) {\n trace.traceViewServiceUIViewEvent('Tried removing non-registered uiView', uiView);\n return;\n }\n trace.traceViewServiceUIViewEvent('<- Deregistering', uiView);\n removeFrom(uiViews)(uiView);\n };\n }\n\n /**\n * Returns the list of views currently available on the page, by fully-qualified name.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n available() {\n return this._uiViews.map(prop('fqn'));\n }\n\n /**\n * Returns the list of views on the page containing loaded content.\n *\n * @return {Array} Returns an array of fully-qualified view names.\n */\n active() {\n return this._uiViews.filter(prop('$config')).map(prop('name'));\n }\n}\n", "/**\n * @coreapi\n * @module core\n */ /** */\nimport { StateParams } from './params/stateParams';\nimport { StateDeclaration } from './state/interface';\nimport { StateObject } from './state/stateObject';\nimport { Transition } from './transition/transition';\nimport { Queue } from './common/queue';\nimport { Disposable } from './interface';\n\n/**\n * Global router state\n *\n * This is where we hold the global mutable state such as current state, current\n * params, current transition, etc.\n */\nexport class UIRouterGlobals implements Disposable {\n /**\n * Current parameter values\n *\n * The parameter values from the latest successful transition\n */\n params: StateParams = new StateParams();\n\n /**\n * Current state\n *\n * The to-state from the latest successful transition\n */\n current: StateDeclaration;\n\n /**\n * Current state (internal object)\n *\n * The to-state from the latest successful transition\n * @internalapi\n */\n $current: StateObject;\n\n /**\n * The current started/running transition.\n * This transition has reached at least the onStart phase, but is not yet complete\n */\n transition: Transition;\n\n /** @internalapi */\n lastStartedTransitionId = -1;\n\n /** @internalapi */\n transitionHistory = new Queue([], 1);\n\n /** @internalapi */\n successfulTransitions = new Queue([], 1);\n\n dispose() {\n this.transitionHistory.clear();\n this.successfulTransitions.clear();\n this.transition = null;\n }\n}\n", - "/**\n * @coreapi\n * @module url\n */ /** */\n\nimport { UIRouter } from '../router';\nimport { LocationServices, notImplemented, LocationConfig } from '../common/coreservices';\nimport { noop, createProxyFunctions } from '../common/common';\nimport { UrlConfigApi, UrlSyncApi, UrlRulesApi, UrlParts, MatchResult } from './interface';\n\n/** @hidden */\nconst makeStub = (keys: string[]): any =>\n keys.reduce((acc, key) => (acc[key] = notImplemented(key), acc), { dispose: noop });\n\n/* tslint:disable:align */\n/** @hidden */ const locationServicesFns = ['url', 'path', 'search', 'hash', 'onChange'];\n/** @hidden */ const locationConfigFns = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix'];\n/** @hidden */ const umfFns = ['type', 'caseInsensitive', 'strictMode', 'defaultSquashPolicy'];\n/** @hidden */ const rulesFns = ['sort', 'when', 'initial', 'otherwise', 'rules', 'rule', 'removeRule'];\n/** @hidden */ const syncFns = ['deferIntercept', 'listen', 'sync', 'match'];\n/* tslint:enable:align */\n\n/**\n * API for URL management\n */\nexport class UrlService implements LocationServices, UrlSyncApi {\n /** @hidden */\n static locationServiceStub: LocationServices = makeStub(locationServicesFns);\n /** @hidden */\n static locationConfigStub: LocationConfig = makeStub(locationConfigFns);\n\n /**\n * A nested API for managing URL rules and rewrites\n *\n * See: [[UrlRulesApi]] for details\n */\n rules: UrlRulesApi;\n\n /**\n * A nested API to configure the URL and retrieve URL information\n *\n * See: [[UrlConfigApi]] for details\n */\n config: UrlConfigApi;\n\n /** @hidden */\n private router: UIRouter;\n\n /** @hidden */\n constructor(router: UIRouter, lateBind = true) {\n this.router = router;\n this.rules = {} as any;\n this.config = {} as any;\n\n // proxy function calls from UrlService to the LocationService/LocationConfig\n const locationServices = () => router.locationService;\n createProxyFunctions(locationServices, this, locationServices, locationServicesFns, lateBind);\n\n const locationConfig = () => router.locationConfig;\n createProxyFunctions(locationConfig, this.config, locationConfig, locationConfigFns, lateBind);\n\n const umf = () => router.urlMatcherFactory;\n createProxyFunctions(umf, this.config, umf, umfFns);\n\n const urlRouter = () => router.urlRouter;\n createProxyFunctions(urlRouter, this.rules, urlRouter, rulesFns);\n createProxyFunctions(urlRouter, this, urlRouter, syncFns);\n }\n\n /** @inheritdoc */\n url(): string;\n /** @inheritdoc */\n url(newurl: string, replace?: boolean, state?): void;\n url(newurl?, replace?, state?): any { return; }\n /** @inheritdoc */\n path(): string { return; }\n /** @inheritdoc */\n search(): { [key: string]: any } { return; }\n /** @inheritdoc */\n hash(): string { return; }\n /** @inheritdoc */\n onChange(callback: Function): Function { return; }\n\n\n /**\n * Returns the current URL parts\n *\n * This method returns the current URL components as a [[UrlParts]] object.\n *\n * @returns the current url parts\n */\n parts(): UrlParts {\n return { path: this.path(), search: this.search(), hash: this.hash() };\n }\n\n dispose() { }\n\n /** @inheritdoc */\n sync(evt?) { return; }\n /** @inheritdoc */\n listen(enabled?: boolean): Function { return; }\n /** @inheritdoc */\n deferIntercept(defer?: boolean) { return; }\n /** @inheritdoc */\n match(urlParts: UrlParts): MatchResult { return; }\n\n}\n", - "/**\n * @coreapi\n * @module core\n */ /** */\nimport { UrlMatcherFactory } from './url/urlMatcherFactory';\nimport { UrlRouter } from './url/urlRouter';\nimport { TransitionService } from './transition/transitionService';\nimport { ViewService } from './view/view';\nimport { StateRegistry } from './state/stateRegistry';\nimport { StateService } from './state/stateService';\nimport { UIRouterGlobals } from './globals';\nimport { UIRouterPlugin, Disposable } from './interface';\nimport { values, removeFrom } from './common/common';\nimport { isFunction } from './common/predicates';\nimport { UrlService } from './url/urlService';\nimport { LocationServices, LocationConfig } from './common/coreservices';\nimport { Trace, trace } from './common/trace';\n\n/** @hidden */\nlet _routerInstance = 0;\n\n/**\n * The master class used to instantiate an instance of UI-Router.\n *\n * UI-Router (for each specific framework) will create an instance of this class during bootstrap.\n * This class instantiates and wires the UI-Router services together.\n *\n * After a new instance of the UIRouter class is created, it should be configured for your app.\n * For instance, app states should be registered with the [[UIRouter.stateRegistry]].\n *\n * ---\n *\n * Normally the framework code will bootstrap UI-Router.\n * If you are bootstrapping UIRouter manually, tell it to monitor the URL by calling\n * [[UrlService.listen]] then [[UrlService.sync]].\n */\nexport class UIRouter {\n /** @hidden */ $id = _routerInstance++;\n /** @hidden */ _disposed = false;\n /** @hidden */ private _disposables: Disposable[] = [];\n\n /** Provides trace information to the console */\n trace: Trace = trace;\n\n /** Provides services related to ui-view synchronization */\n viewService = new ViewService();\n\n /** Global router state */\n globals: UIRouterGlobals = new UIRouterGlobals();\n\n /** Provides services related to Transitions */\n transitionService: TransitionService = new TransitionService(this);\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlMatcherFactory: UrlMatcherFactory = new UrlMatcherFactory();\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlRouter: UrlRouter = new UrlRouter(this);\n\n /** Provides a registry for states, and related registration services */\n stateRegistry: StateRegistry = new StateRegistry(this);\n\n /** Provides services related to states */\n stateService = new StateService(this);\n\n /** Provides services related to the URL */\n urlService: UrlService = new UrlService(this);\n\n /** @hidden plugin instances are registered here */\n private _plugins: { [key: string]: UIRouterPlugin } = {};\n\n\n /** Registers an object to be notified when the router is disposed */\n disposable(disposable: Disposable) {\n this._disposables.push(disposable);\n }\n\n /**\n * Disposes this router instance\n *\n * When called, clears resources retained by the router by calling `dispose(this)` on all\n * registered [[disposable]] objects.\n *\n * Or, if a `disposable` object is provided, calls `dispose(this)` on that object only.\n *\n * @param disposable (optional) the disposable to dispose\n */\n dispose(disposable?: any): void {\n if (disposable && isFunction(disposable.dispose)) {\n disposable.dispose(this);\n return undefined;\n }\n\n this._disposed = true;\n this._disposables.slice().forEach(d => {\n try {\n typeof d.dispose === 'function' && d.dispose(this);\n removeFrom(this._disposables, d);\n } catch (ignored) {}\n });\n }\n\n /**\n * Creates a new `UIRouter` object\n *\n * @param locationService a [[LocationServices]] implementation\n * @param locationConfig a [[LocationConfig]] implementation\n * @internalapi\n */\n constructor(\n public locationService: LocationServices = UrlService.locationServiceStub,\n public locationConfig: LocationConfig = UrlService.locationConfigStub,\n ) {\n\n this.viewService._pluginapi._rootViewContext(this.stateRegistry.root());\n this.globals.$current = this.stateRegistry.root();\n this.globals.current = this.globals.$current.self;\n\n this.disposable(this.globals);\n this.disposable(this.stateService);\n this.disposable(this.stateRegistry);\n this.disposable(this.transitionService);\n this.disposable(this.urlRouter);\n this.disposable(locationService);\n this.disposable(locationConfig);\n }\n\n /** Add plugin (as ES6 class) */\n plugin(plugin: { new(router: UIRouter, options?: any): T }, options?: any): T;\n /** Add plugin (as javascript constructor function) */\n plugin(plugin: { (router: UIRouter, options?: any): void }, options?: any): T;\n /** Add plugin (as javascript factory function) */\n plugin(plugin: PluginFactory, options?: any): T;\n /**\n * Adds a plugin to UI-Router\n *\n * This method adds a UI-Router Plugin.\n * A plugin can enhance or change UI-Router behavior using any public API.\n *\n * #### Example:\n * ```js\n * import { MyCoolPlugin } from \"ui-router-cool-plugin\";\n *\n * var plugin = router.addPlugin(MyCoolPlugin);\n * ```\n *\n * ### Plugin authoring\n *\n * A plugin is simply a class (or constructor function) which accepts a [[UIRouter]] instance and (optionally) an options object.\n *\n * The plugin can implement its functionality using any of the public APIs of [[UIRouter]].\n * For example, it may configure router options or add a Transition Hook.\n *\n * The plugin can then be published as a separate module.\n *\n * #### Example:\n * ```js\n * export class MyAuthPlugin implements UIRouterPlugin {\n * constructor(router: UIRouter, options: any) {\n * this.name = \"MyAuthPlugin\";\n * let $transitions = router.transitionService;\n * let $state = router.stateService;\n *\n * let authCriteria = {\n * to: (state) => state.data && state.data.requiresAuth\n * };\n *\n * function authHook(transition: Transition) {\n * let authService = transition.injector().get('AuthService');\n * if (!authService.isAuthenticated()) {\n * return $state.target('login');\n * }\n * }\n *\n * $transitions.onStart(authCriteria, authHook);\n * }\n * }\n * ```\n *\n * @param plugin one of:\n * - a plugin class which implements [[UIRouterPlugin]]\n * - a constructor function for a [[UIRouterPlugin]] which accepts a [[UIRouter]] instance\n * - a factory function which accepts a [[UIRouter]] instance and returns a [[UIRouterPlugin]] instance\n * @param options options to pass to the plugin class/factory\n * @returns the registered plugin instance\n */\n plugin(plugin: any, options: any = {}): T {\n const pluginInstance = new plugin(this, options);\n if (!pluginInstance.name) throw new Error('Required property `name` missing on plugin: ' + pluginInstance);\n this._disposables.push(pluginInstance);\n return this._plugins[pluginInstance.name] = pluginInstance;\n }\n\n /**\n * Returns registered plugins\n *\n * Returns the registered plugin of the given `pluginName`.\n * If no `pluginName` is given, returns all registered plugins\n *\n * @param pluginName (optional) the name of the plugin to get\n * @return the named plugin (undefined if not found), or all plugins (if `pluginName` is omitted)\n */\n getPlugin(pluginName: string): UIRouterPlugin;\n getPlugin(): UIRouterPlugin[];\n getPlugin(pluginName?: string): UIRouterPlugin|UIRouterPlugin[] {\n return pluginName ? this._plugins[pluginName] : values(this._plugins);\n }\n}\n\n/** @internalapi */\nexport type PluginFactory = (router: UIRouter, options?: any) => T;\n", - "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { UIRouter } from '../router';\nimport { TransitionService } from '../transition/transitionService';\nimport { Resolvable } from '../resolve';\nimport { extend, inArray, map, mapObj, uniqR, unnestR, values } from '../common';\nimport { PathNode } from '../path';\nimport { TreeChanges } from \"../transition\";\n\nfunction addCoreResolvables(trans: Transition) {\n trans.addResolvable(Resolvable.fromData(UIRouter, trans.router), '');\n trans.addResolvable(Resolvable.fromData(Transition, trans), '');\n trans.addResolvable(Resolvable.fromData('$transition$', trans), '');\n trans.addResolvable(Resolvable.fromData('$stateParams', trans.params()), '');\n\n trans.entering().forEach(state => {\n trans.addResolvable(Resolvable.fromData('$state$', state), state);\n });\n}\n\nexport const registerAddCoreResolvables = (transitionService: TransitionService) =>\n transitionService.onCreate({}, addCoreResolvables);\n\nconst TRANSITION_TOKENS = ['$transition$', Transition];\nconst isTransition = inArray(TRANSITION_TOKENS);\n\n// References to Transition in the treeChanges pathnodes makes all\n// previous Transitions reachable in memory, causing a memory leak\n// This function removes resolves for '$transition$' and `Transition` from the treeChanges.\n// Do not use this on current transitions, only on old ones.\nexport const treeChangesCleanup = (trans: Transition) => {\n const nodes = values(trans.treeChanges()).reduce(unnestR, []).reduce(uniqR, []);\n\n // If the resolvable is a Transition, return a new resolvable with null data\n const replaceTransitionWithNull = (r: Resolvable): Resolvable => {\n return isTransition(r.token) ? Resolvable.fromData(r.token, null) : r;\n };\n\n nodes.forEach((node: PathNode) => {\n node.resolvables = node.resolvables.map(replaceTransitionWithNull);\n });\n};\n", - "/** @module hooks */ /** */\nimport { isString, isFunction } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { services } from '../common/coreservices';\nimport { TargetState } from '../state/targetState';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\n\n/**\n * A [[TransitionHookFn]] that redirects to a different state or params\n *\n * Registered using `transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectHook);`\n *\n * See [[StateDeclaration.redirectTo]]\n */\nconst redirectToHook: TransitionHookFn = (trans: Transition) => {\n const redirect = trans.to().redirectTo;\n if (!redirect) return;\n\n const $state = trans.router.stateService;\n\n function handleResult(result: any) {\n if (!result) return;\n if (result instanceof TargetState) return result;\n if (isString(result)) return $state.target( result, trans.params(), trans.options());\n if (result['state'] || result['params'])\n return $state.target(result['state'] || trans.to(), result['params'] || trans.params(), trans.options());\n }\n\n if (isFunction(redirect)) {\n return services.$q.when(redirect(trans)).then(handleResult);\n }\n return handleResult(redirect);\n};\n\nexport const registerRedirectToHook = (transitionService: TransitionService) =>\n transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectToHook);\n", - "/** @module hooks */\n/** for typedoc */\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { StateDeclaration } from '../state/interface';\nimport { StateObject } from '../state/stateObject';\n\n/**\n * A factory which creates an onEnter, onExit or onRetain transition hook function\n *\n * The returned function invokes the (for instance) state.onEnter hook when the\n * state is being entered.\n *\n * @hidden\n */\nfunction makeEnterExitRetainHook(hookName: string): TransitionStateHookFn {\n return (transition: Transition, state: StateDeclaration) => {\n const _state: StateObject = state.$$state();\n const hookFn: TransitionStateHookFn = _state[hookName];\n return hookFn(transition, state);\n };\n}\n\n/**\n * The [[TransitionStateHookFn]] for onExit\n *\n * When the state is being exited, the state's .onExit function is invoked.\n *\n * Registered using `transitionService.onExit({ exiting: (state) => !!state.onExit }, onExitHook);`\n *\n * See: [[IHookRegistry.onExit]]\n */\nconst onExitHook: TransitionStateHookFn = makeEnterExitRetainHook('onExit');\nexport const registerOnExitHook = (transitionService: TransitionService) =>\n transitionService.onExit({ exiting: state => !!state.onExit }, onExitHook);\n\n/**\n * The [[TransitionStateHookFn]] for onRetain\n *\n * When the state was already entered, and is not being exited or re-entered, the state's .onRetain function is invoked.\n *\n * Registered using `transitionService.onRetain({ retained: (state) => !!state.onRetain }, onRetainHook);`\n *\n * See: [[IHookRegistry.onRetain]]\n */\nconst onRetainHook: TransitionStateHookFn = makeEnterExitRetainHook('onRetain');\nexport const registerOnRetainHook = (transitionService: TransitionService) =>\n transitionService.onRetain({ retained: state => !!state.onRetain }, onRetainHook);\n\n/**\n * The [[TransitionStateHookFn]] for onEnter\n *\n * When the state is being entered, the state's .onEnter function is invoked.\n *\n * Registered using `transitionService.onEnter({ entering: (state) => !!state.onEnter }, onEnterHook);`\n *\n * See: [[IHookRegistry.onEnter]]\n */\nconst onEnterHook: TransitionStateHookFn = makeEnterExitRetainHook('onEnter');\nexport const registerOnEnterHook = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: state => !!state.onEnter }, onEnterHook);\n\n", - "/** @module hooks */\n/** for typedoc */\nimport { noop } from '../common/common';\nimport { Transition } from '../transition/transition';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { TransitionStateHookFn, TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\nimport { val } from '../common/hof';\nimport { StateDeclaration } from '../state/interface';\n\nexport const RESOLVE_HOOK_PRIORITY = 1000;\n\n/**\n * A [[TransitionHookFn]] which resolves all EAGER Resolvables in the To Path\n *\n * Registered using `transitionService.onStart({}, eagerResolvePath, { priority: 1000 });`\n *\n * When a Transition starts, this hook resolves all the EAGER Resolvables, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst eagerResolvePath: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to)\n .resolvePath('EAGER', trans)\n .then(noop);\n\nexport const registerEagerResolvePath = (transitionService: TransitionService) =>\n transitionService.onStart({}, eagerResolvePath, { priority: RESOLVE_HOOK_PRIORITY });\n\n/**\n * A [[TransitionHookFn]] which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path\n *\n * Registered using `transitionService.onEnter({ entering: () => true }, lazyResolveState, { priority: 1000 });`\n *\n * When a State is being entered, this hook resolves all the Resolvables for this state, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst lazyResolveState: TransitionStateHookFn = (trans: Transition, state: StateDeclaration) =>\n new ResolveContext(trans.treeChanges().to)\n .subContext(state.$$state())\n .resolvePath('LAZY', trans)\n .then(noop);\n\nexport const registerLazyResolveState = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: val(true) }, lazyResolveState, { priority: RESOLVE_HOOK_PRIORITY });\n\n\n/**\n * A [[TransitionHookFn]] which resolves any dynamically added (LAZY or EAGER) Resolvables.\n *\n * Registered using `transitionService.onFinish({}, eagerResolvePath, { priority: 1000 });`\n *\n * After all entering states have been entered, this hook resolves any remaining Resolvables.\n * These are typically dynamic resolves which were added by some Transition Hook using [[Transition.addResolvable]].\n *\n * See [[StateDeclaration.resolve]]\n */\nconst resolveRemaining: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to)\n .resolvePath('LAZY', trans)\n .then(noop);\n\nexport const registerResolveRemaining = (transitionService: TransitionService) =>\n transitionService.onFinish({}, resolveRemaining, { priority: RESOLVE_HOOK_PRIORITY });\n", - "/** @module hooks */ /** for typedoc */\nimport { noop } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { Transition } from '../transition/transition';\nimport { ViewService } from '../view/view';\nimport { ViewConfig } from '../view/interface';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n\n/**\n * A [[TransitionHookFn]] which waits for the views to load\n *\n * Registered using `transitionService.onStart({}, loadEnteringViews);`\n *\n * Allows the views to do async work in [[ViewConfig.load]] before the transition continues.\n * In angular 1, this includes loading the templates.\n */\nconst loadEnteringViews: TransitionHookFn = (transition: Transition) => {\n const $q = services.$q;\n const enteringViews = transition.views('entering');\n if (!enteringViews.length) return;\n return $q.all(enteringViews.map(view => $q.when(view.load()))).then(noop);\n};\n\nexport const registerLoadEnteringViews = (transitionService: TransitionService) =>\n transitionService.onFinish({}, loadEnteringViews);\n\n/**\n * A [[TransitionHookFn]] which activates the new views when a transition is successful.\n *\n * Registered using `transitionService.onSuccess({}, activateViews);`\n *\n * After a transition is complete, this hook deactivates the old views from the previous state,\n * and activates the new views from the destination state.\n *\n * See [[ViewService]]\n */\nconst activateViews: TransitionHookFn = (transition: Transition) => {\n const enteringViews = transition.views('entering');\n const exitingViews = transition.views('exiting');\n if (!enteringViews.length && !exitingViews.length) return;\n\n const $view: ViewService = transition.router.viewService;\n\n exitingViews.forEach((vc: ViewConfig) => $view.deactivateViewConfig(vc));\n enteringViews.forEach((vc: ViewConfig) => $view.activateViewConfig(vc));\n\n $view.sync();\n};\n\nexport const registerActivateViews = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, activateViews);\n", - "/** @module hooks */\n/** for typedoc */\nimport { Transition } from '../transition/transition';\nimport { copy } from '../common/common';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates global UI-Router state\n *\n * Registered using `transitionService.onBefore({}, updateGlobalState);`\n *\n * Before a [[Transition]] starts, updates the global value of \"the current transition\" ([[Globals.transition]]).\n * After a successful [[Transition]], updates the global values of \"the current state\"\n * ([[Globals.current]] and [[Globals.$current]]) and \"the current param values\" ([[Globals.params]]).\n *\n * See also the deprecated properties:\n * [[StateService.transition]], [[StateService.current]], [[StateService.params]]\n */\nconst updateGlobalState = (trans: Transition) => {\n const globals = trans.router.globals;\n\n const transitionSuccessful = () => {\n globals.successfulTransitions.enqueue(trans);\n globals.$current = trans.$to();\n globals.current = globals.$current.self;\n\n copy(trans.params(), globals.params);\n };\n\n const clearCurrentTransition = () => {\n // Do not clear globals.transition if a different transition has started in the meantime\n if (globals.transition === trans) globals.transition = null;\n };\n\n trans.onSuccess({}, transitionSuccessful, { priority: 10000 });\n trans.promise.then(clearCurrentTransition, clearCurrentTransition);\n};\n\nexport const registerUpdateGlobalState = (transitionService: TransitionService) =>\n transitionService.onCreate({}, updateGlobalState);\n", - "/** @module hooks */ /** */\nimport { UrlRouter } from '../url/urlRouter';\nimport { StateService } from '../state/stateService';\nimport { Transition } from '../transition/transition';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates the URL after a successful transition\n *\n * Registered using `transitionService.onSuccess({}, updateUrl);`\n */\nconst updateUrl: TransitionHookFn = (transition: Transition) => {\n const options = transition.options();\n const $state: StateService = transition.router.stateService;\n const $urlRouter: UrlRouter = transition.router.urlRouter;\n\n // Dont update the url in these situations:\n // The transition was triggered by a URL sync (options.source === 'url')\n // The user doesn't want the url to update (options.location === false)\n // The destination state, and all parents have no navigable url\n if (options.source !== 'url' && options.location && $state.$current.navigable) {\n const urlOptions = { replace: options.location === 'replace' };\n $urlRouter.push($state.$current.navigable.url, $state.params, urlOptions);\n }\n\n $urlRouter.update(true);\n};\n\nexport const registerUpdateUrl = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, updateUrl, { priority: 9999 });\n", - "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\nimport { StateDeclaration, LazyLoadResult } from '../state/interface';\nimport { services } from '../common/coreservices';\nimport { StateRule } from '../url/interface';\n\n/**\n * A [[TransitionHookFn]] that performs lazy loading\n *\n * When entering a state \"abc\" which has a `lazyLoad` function defined:\n * - Invoke the `lazyLoad` function (unless it is already in process)\n * - Flag the hook function as \"in process\"\n * - The function should return a promise (that resolves when lazy loading is complete)\n * - Wait for the promise to settle\n * - If the promise resolves to a [[LazyLoadResult]], then register those states\n * - Flag the hook function as \"not in process\"\n * - If the hook was successful\n * - Remove the `lazyLoad` function from the state declaration\n * - If all the hooks were successful\n * - Retry the transition (by returning a TargetState)\n *\n * ```\n * .state('abc', {\n * component: 'fooComponent',\n * lazyLoad: () => System.import('./fooComponent')\n * });\n * ```\n *\n * See [[StateDeclaration.lazyLoad]]\n */\nconst lazyLoadHook: TransitionHookFn = (transition: Transition) => {\n const router = transition.router;\n\n function retryTransition() {\n if (transition.originalTransition().options().source !== 'url') {\n // The original transition was not triggered via url sync\n // The lazy state should be loaded now, so re-try the original transition\n const orig = transition.targetState();\n return router.stateService.target(orig.identifier(), orig.params(), orig.options());\n }\n\n // The original transition was triggered via url sync\n // Run the URL rules and find the best match\n const $url = router.urlService;\n const result = $url.match($url.parts());\n const rule = result && result.rule;\n\n // If the best match is a state, redirect the transition (instead\n // of calling sync() which supersedes the current transition)\n if (rule && rule.type === 'STATE') {\n const state = (rule as StateRule).state;\n const params = result.match;\n return router.stateService.target(state, params, transition.options());\n }\n\n // No matching state found, so let .sync() choose the best non-state match/otherwise\n router.urlService.sync();\n }\n\n const promises = transition.entering()\n .filter(state => !!state.$$state().lazyLoad)\n .map(state => lazyLoadState(transition, state));\n\n return services.$q.all(promises).then(retryTransition);\n};\n\nexport const registerLazyLoadHook = (transitionService: TransitionService) =>\n transitionService.onBefore({ entering: (state) => !!state.lazyLoad }, lazyLoadHook);\n\n\n/**\n * Invokes a state's lazy load function\n *\n * @param transition a Transition context\n * @param state the state to lazy load\n * @returns A promise for the lazy load result\n */\nexport function lazyLoadState(transition: Transition, state: StateDeclaration): Promise {\n const lazyLoadFn = state.$$state().lazyLoad;\n\n // Store/get the lazy load promise on/from the hookfn so it doesn't get re-invoked\n let promise = lazyLoadFn['_promise'];\n if (!promise) {\n const success = (result) => {\n delete state.lazyLoad;\n delete state.$$state().lazyLoad;\n delete lazyLoadFn['_promise'];\n return result;\n };\n\n const error = (err) => {\n delete lazyLoadFn['_promise'];\n return services.$q.reject(err);\n };\n\n promise = lazyLoadFn['_promise'] =\n services.$q.when(lazyLoadFn(transition, state))\n .then(updateStateRegistry)\n .then(success, error);\n }\n\n /** Register any lazy loaded state definitions */\n function updateStateRegistry(result: LazyLoadResult) {\n if (result && Array.isArray(result.states)) {\n result.states.forEach(_state => transition.router.stateRegistry.register(_state));\n }\n return result;\n }\n\n return promise;\n}\n", - "/** @module transition */ /** */\nimport { TransitionHookPhase, PathType } from './interface';\nimport { GetErrorHandler, GetResultHandler, TransitionHook } from './transitionHook';\n/**\n * This class defines a type of hook, such as `onBefore` or `onEnter`.\n * Plugins can define custom hook types, such as sticky states does for `onInactive`.\n *\n * @interalapi\n */\nexport class TransitionEventType {\n /* tslint:disable:no-inferrable-types */\n constructor(public name: string,\n public hookPhase: TransitionHookPhase,\n public hookOrder: number,\n public criteriaMatchPath: PathType,\n public reverseSort: boolean = false,\n public getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n public getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n public synchronous: boolean = false,\n ) { }\n}\n", - "/** @module hooks */ /** */\n\nimport { trace } from '../common/trace';\nimport { Rejection } from '../transition/rejectFactory';\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that skips a transition if it should be ignored\n *\n * This hook is invoked at the end of the onBefore phase.\n *\n * If the transition should be ignored (because no parameter or states changed)\n * then the transition is ignored and not processed.\n */\nfunction ignoredHook(trans: Transition) {\n const ignoredReason = trans._ignoredReason();\n if (!ignoredReason) return;\n\n trace.traceTransitionIgnored(trans);\n\n const pending = trans.router.globals.transition;\n\n // The user clicked a link going back to the *current state* ('A')\n // However, there is also a pending transition in flight (to 'B')\n // Abort the transition to 'B' because the user now wants to be back at 'A'.\n if (ignoredReason === 'SameAsCurrent' && pending) {\n pending.abort();\n }\n\n return Rejection.ignored().toPromise();\n}\n\nexport const registerIgnoredTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, ignoredHook, { priority: -9999 });\n", - "/** @module hooks */ /** */\n\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that rejects the Transition if it is invalid\n *\n * This hook is invoked at the end of the onBefore phase.\n * If the transition is invalid (for example, param values do not validate)\n * then the transition is rejected.\n */\nfunction invalidTransitionHook(trans: Transition) {\n if (!trans.valid()) {\n throw new Error(trans.error());\n }\n}\n\nexport const registerInvalidTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, invalidTransitionHook, { priority: -10000 });\n", - "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport {\n IHookRegistry, TransitionOptions, TransitionHookScope, TransitionHookPhase, TransitionCreateHookFn, HookMatchCriteria,\n HookRegOptions, PathTypes, PathType, RegisteredHooks, TransitionHookFn, TransitionStateHookFn,\n} from './interface';\nimport { Transition } from './transition';\nimport { makeEvent, RegisteredHook } from './hookRegistry';\nimport { TargetState } from '../state/targetState';\nimport { PathNode } from '../path/pathNode';\nimport { ViewService } from '../view/view';\nimport { UIRouter } from '../router';\nimport { registerAddCoreResolvables, treeChangesCleanup } from '../hooks/coreResolvables';\nimport { registerRedirectToHook } from '../hooks/redirectTo';\nimport { registerOnExitHook, registerOnRetainHook, registerOnEnterHook } from '../hooks/onEnterExitRetain';\nimport { registerEagerResolvePath, registerLazyResolveState, registerResolveRemaining } from '../hooks/resolve';\nimport { registerLoadEnteringViews, registerActivateViews } from '../hooks/views';\nimport { registerUpdateGlobalState } from '../hooks/updateGlobals';\nimport { registerUpdateUrl } from '../hooks/url';\nimport { registerLazyLoadHook } from '../hooks/lazyLoad';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionHook, GetResultHandler, GetErrorHandler } from './transitionHook';\nimport { isDefined } from '../common/predicates';\nimport { removeFrom, values, createProxyFunctions } from '../common/common';\nimport { Disposable } from '../interface'; // has or is using\nimport { val } from '../common/hof';\nimport { registerIgnoredTransitionHook } from '../hooks/ignoredTransition';\nimport { registerInvalidTransitionHook } from '../hooks/invalidTransition';\n\n/**\n * The default [[Transition]] options.\n *\n * Include this object when applying custom defaults:\n * let reloadOpts = { reload: true, notify: true }\n * let options = defaults(theirOpts, customDefaults, defaultOptions);\n */\nexport let defaultTransOpts: TransitionOptions = {\n location : true,\n relative : null,\n inherit : false,\n notify : true,\n reload : false,\n custom : {},\n current : () => null,\n source : 'unknown',\n};\n\n\n/**\n * Plugin API for Transition Service\n * @internalapi\n */\nexport interface TransitionServicePluginAPI {\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n */\n _definePathType(name: string, hookScope: TransitionHookScope);\n\n /**\n * Gets a Path definition used as a criterion against a TreeChanges path\n */\n _getPathTypes(): PathTypes;\n\n /**\n * Defines a transition hook type and returns a transition hook registration\n * function (which can then be used to register hooks of this type).\n */\n _defineEvent(name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort?: boolean,\n getResultHandler?: GetResultHandler,\n getErrorHandler?: GetErrorHandler,\n rejectIfSuperseded?: boolean);\n\n /**\n * Returns the known event types, such as `onBefore`\n * If a phase argument is provided, returns only events for the given phase.\n */\n _getEvents(phase?: TransitionHookPhase): TransitionEventType[];\n\n /** Returns the hooks registered for the given hook name */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/**\n * This class provides services related to Transitions.\n *\n * - Most importantly, it allows global Transition Hooks to be registered.\n * - It allows the default transition error handler to be set.\n * - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]).\n *\n * At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class.\n */\nexport class TransitionService implements IHookRegistry, Disposable {\n /** @hidden */\n _transitionCount = 0;\n\n /** @hidden */\n public $view: ViewService;\n\n /** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */\n private _eventTypes: TransitionEventType[] = [];\n /** @hidden The registered transition hooks */\n _registeredHooks = { } as RegisteredHooks;\n /** @hidden The paths on a criteria object */\n private _criteriaPaths = { } as PathTypes;\n /** @hidden */\n private _router: UIRouter;\n\n /** @internalapi */\n _pluginapi: TransitionServicePluginAPI;\n\n /**\n * This object has hook de-registration functions for the built-in hooks.\n * This can be used by third parties libraries that wish to customize the behaviors\n *\n * @hidden\n */\n _deregisterHookFns: {\n addCoreResolves: Function;\n ignored: Function;\n invalid: Function;\n redirectTo: Function;\n onExit: Function;\n onRetain: Function;\n onEnter: Function;\n eagerResolve: Function;\n lazyResolve: Function;\n resolveAll: Function;\n loadViews: Function;\n activateViews: Function;\n updateGlobals: Function;\n updateUrl: Function;\n lazyLoad: Function;\n };\n\n /** @hidden */\n constructor(_router: UIRouter) {\n this._router = _router;\n this.$view = _router.viewService;\n this._deregisterHookFns = {};\n this._pluginapi = createProxyFunctions(val(this), {}, val(this), [\n '_definePathType',\n '_defineEvent',\n '_getPathTypes',\n '_getEvents',\n 'getHooks',\n ]);\n\n this._defineCorePaths();\n this._defineCoreEvents();\n this._registerCoreTransitionHooks();\n _router.globals.successfulTransitions.onEvict(treeChangesCleanup);\n }\n\n /**\n * Registers a [[TransitionHookFn]], called *while a transition is being constructed*.\n *\n * Registers a transition lifecycle hook, which is invoked during transition construction.\n *\n * This low level hook should only be used by plugins.\n * This can be a useful time for plugins to add resolves or mutate the transition as needed.\n * The Sticky States plugin uses this hook to modify the treechanges.\n *\n * ### Lifecycle\n *\n * `onCreate` hooks are invoked *while a transition is being constructed*.\n *\n * ### Return value\n *\n * The hook's return value is ignored\n *\n * @internalapi\n * @param criteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @param options the registration options\n * @returns a function which deregisters the hook.\n */\n onCreate(criteria: HookMatchCriteria, callback: TransitionCreateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function { return; }\n\n /**\n * dispose\n * @internalapi\n */\n dispose(router: UIRouter) {\n values(this._registeredHooks).forEach((hooksArray: RegisteredHook[]) => hooksArray.forEach(hook => {\n hook._deregistered = true;\n removeFrom(hooksArray, hook);\n }));\n }\n\n /**\n * Creates a new [[Transition]] object\n *\n * This is a factory function for creating new Transition objects.\n * It is used internally by the [[StateService]] and should generally not be called by application code.\n *\n * @param fromPath the path to the current state (the from state)\n * @param targetState the target state (destination)\n * @returns a Transition\n */\n create(fromPath: PathNode[], targetState: TargetState): Transition {\n return new Transition(fromPath, targetState, this._router);\n }\n\n /** @hidden */\n private _defineCoreEvents() {\n const Phase = TransitionHookPhase;\n const TH = TransitionHook;\n const paths = this._criteriaPaths;\n const NORMAL_SORT = false, REVERSE_SORT = true;\n const SYNCHRONOUS = true;\n\n this._defineEvent('onCreate', Phase.CREATE, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.THROW_ERROR, SYNCHRONOUS);\n\n this._defineEvent('onBefore', Phase.BEFORE, 0, paths.to);\n\n this._defineEvent('onStart', Phase.RUN, 0, paths.to);\n this._defineEvent('onExit', Phase.RUN, 100, paths.exiting, REVERSE_SORT);\n this._defineEvent('onRetain', Phase.RUN, 200, paths.retained);\n this._defineEvent('onEnter', Phase.RUN, 300, paths.entering);\n this._defineEvent('onFinish', Phase.RUN, 400, paths.to);\n\n this._defineEvent('onSuccess', Phase.SUCCESS, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.LOG_ERROR, SYNCHRONOUS);\n this._defineEvent('onError', Phase.ERROR, 0, paths.to, NORMAL_SORT, TH.LOG_REJECTED_RESULT, TH.LOG_ERROR, SYNCHRONOUS);\n }\n\n /** @hidden */\n private _defineCorePaths() {\n const { STATE, TRANSITION } = TransitionHookScope;\n\n this._definePathType('to', TRANSITION);\n this._definePathType('from', TRANSITION);\n this._definePathType('exiting', STATE);\n this._definePathType('retained', STATE);\n this._definePathType('entering', STATE);\n }\n\n /** @hidden */\n _defineEvent(name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort = false,\n getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n synchronous = false) {\n const eventType = new TransitionEventType(name, hookPhase, hookOrder, criteriaMatchPath, reverseSort, getResultHandler, getErrorHandler, synchronous);\n\n this._eventTypes.push(eventType);\n makeEvent(this, this, eventType);\n }\n\n /** @hidden */ // tslint:disable-next-line\n private _getEvents(phase?: TransitionHookPhase): TransitionEventType[] {\n const transitionHookTypes = isDefined(phase) ?\n this._eventTypes.filter(type => type.hookPhase === phase) :\n this._eventTypes.slice();\n\n return transitionHookTypes.sort((l, r) => {\n const cmpByPhase = l.hookPhase - r.hookPhase;\n return cmpByPhase === 0 ? l.hookOrder - r.hookOrder : cmpByPhase;\n });\n }\n\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n *\n * @hidden\n */\n private _definePathType(name: string, hookScope: TransitionHookScope) {\n this._criteriaPaths[name] = { name, scope: hookScope };\n }\n\n /** * @hidden */ // tslint:disable-next-line\n private _getPathTypes(): PathTypes {\n return this._criteriaPaths;\n }\n\n /** @hidden */\n public getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /** @hidden */\n private _registerCoreTransitionHooks() {\n const fns = this._deregisterHookFns;\n\n fns.addCoreResolves = registerAddCoreResolvables(this);\n fns.ignored = registerIgnoredTransitionHook(this);\n fns.invalid = registerInvalidTransitionHook(this);\n\n // Wire up redirectTo hook\n fns.redirectTo = registerRedirectToHook(this);\n\n // Wire up onExit/Retain/Enter state hooks\n fns.onExit = registerOnExitHook(this);\n fns.onRetain = registerOnRetainHook(this);\n fns.onEnter = registerOnEnterHook(this);\n\n // Wire up Resolve hooks\n fns.eagerResolve = registerEagerResolvePath(this);\n fns.lazyResolve = registerLazyResolveState(this);\n fns.resolveAll = registerResolveRemaining(this);\n\n // Wire up the View management hooks\n fns.loadViews = registerLoadEnteringViews(this);\n fns.activateViews = registerActivateViews(this);\n\n // Updates global state after a transition\n fns.updateGlobals = registerUpdateGlobalState(this);\n\n // After globals.current is updated at priority: 10000\n fns.updateUrl = registerUpdateUrl(this);\n\n // Lazy load state trees\n fns.lazyLoad = registerLazyLoadHook(this);\n }\n}\n", - "/**\n * @coreapi\n * @module state\n */\n/** */\nimport { createProxyFunctions, defaults, extend, inArray, noop, removeFrom, silenceUncaughtInPromise, silentRejection } from '../common/common';\nimport { isDefined, isObject, isString } from '../common/predicates';\nimport { Queue } from '../common/queue';\nimport { services } from '../common/coreservices';\n\nimport { PathUtils } from '../path/pathUtils';\nimport { PathNode } from '../path/pathNode';\n\nimport { HookResult, TransitionOptions } from '../transition/interface';\nimport { defaultTransOpts } from '../transition/transitionService';\nimport { Rejection, RejectType } from '../transition/rejectFactory';\nimport { Transition } from '../transition/transition';\n\nimport { HrefOptions, LazyLoadResult, StateDeclaration, StateOrName, TransitionPromise } from './interface';\nimport { StateObject } from './stateObject';\nimport { TargetState } from './targetState';\n\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Glob } from '../common/glob';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { lazyLoadState } from '../hooks/lazyLoad';\nimport { not, val } from '../common/hof';\nimport { StateParams } from '../params/stateParams';\n\nexport type OnInvalidCallback =\n (toState?: TargetState, fromState?: TargetState, injector?: UIInjector) => HookResult;\n\n/**\n * Provides state related service functions\n *\n * This class provides services related to ui-router states.\n * An instance of this class is located on the global [[UIRouter]] object.\n */\nexport class StateService {\n /** @internalapi */\n invalidCallbacks: OnInvalidCallback[] = [];\n\n /**\n * The [[Transition]] currently in progress (or null)\n *\n * This is a passthrough through to [[UIRouterGlobals.transition]]\n */\n get transition() { return this.router.globals.transition; }\n /**\n * The latest successful state parameters\n *\n * This is a passthrough through to [[UIRouterGlobals.params]]\n */\n get params(): StateParams { return this.router.globals.params; }\n /**\n * The current [[StateDeclaration]]\n *\n * This is a passthrough through to [[UIRouterGlobals.current]]\n */\n get current() { return this.router.globals.current; }\n /**\n * The current [[StateObject]]\n *\n * This is a passthrough through to [[UIRouterGlobals.$current]]\n */\n get $current() { return this.router.globals.$current; }\n\n /** @internalapi */\n constructor(private router: UIRouter) {\n const getters = ['current', '$current', 'params', 'transition'];\n const boundFns = Object.keys(StateService.prototype).filter(not(inArray(getters)));\n createProxyFunctions(val(StateService.prototype), this, val(this), boundFns);\n }\n\n /** @internalapi */\n dispose() {\n this.defaultErrorHandler(noop);\n this.invalidCallbacks = [];\n }\n\n /**\n * Handler for when [[transitionTo]] is called with an invalid state.\n *\n * Invokes the [[onInvalid]] callbacks, in natural order.\n * Each callback's return value is checked in sequence until one of them returns an instance of TargetState.\n * The results of the callbacks are wrapped in $q.when(), so the callbacks may return promises.\n *\n * If a callback returns an TargetState, then it is used as arguments to $state.transitionTo() and the result returned.\n *\n * @internalapi\n */\n private _handleInvalidTargetState(fromPath: PathNode[], toState: TargetState) {\n const fromState = PathUtils.makeTargetState(this.router.stateRegistry, fromPath);\n const globals = this.router.globals;\n const latestThing = () => globals.transitionHistory.peekTail();\n const latest = latestThing();\n const callbackQueue = new Queue(this.invalidCallbacks.slice());\n const injector = new ResolveContext(fromPath).injector();\n\n const checkForRedirect = (result: HookResult) => {\n if (!(result instanceof TargetState)) {\n return;\n }\n\n let target = result;\n // Recreate the TargetState, in case the state is now defined.\n target = this.target(target.identifier(), target.params(), target.options());\n\n if (!target.valid()) {\n return Rejection.invalid(target.error()).toPromise();\n }\n\n if (latestThing() !== latest) {\n return Rejection.superseded().toPromise();\n }\n\n return this.transitionTo(target.identifier(), target.params(), target.options());\n };\n\n function invokeNextCallback() {\n const nextCallback = callbackQueue.dequeue();\n if (nextCallback === undefined) return Rejection.invalid(toState.error()).toPromise();\n\n const callbackResult = services.$q.when(nextCallback(toState, fromState, injector));\n return callbackResult.then(checkForRedirect).then(result => result || invokeNextCallback());\n }\n\n return invokeNextCallback();\n }\n\n /**\n * Registers an Invalid State handler\n *\n * Registers a [[OnInvalidCallback]] function to be invoked when [[StateService.transitionTo]]\n * has been called with an invalid state reference parameter\n *\n * Example:\n * ```js\n * stateService.onInvalid(function(to, from, injector) {\n * if (to.name() === 'foo') {\n * let lazyLoader = injector.get('LazyLoadService');\n * return lazyLoader.load('foo')\n * .then(() => stateService.target('foo'));\n * }\n * });\n * ```\n *\n * @param {function} callback invoked when the toState is invalid\n * This function receives the (invalid) toState, the fromState, and an injector.\n * The function may optionally return a [[TargetState]] or a Promise for a TargetState.\n * If one is returned, it is treated as a redirect.\n *\n * @returns a function which deregisters the callback\n */\n onInvalid(callback: OnInvalidCallback): Function {\n this.invalidCallbacks.push(callback);\n return function deregisterListener() {\n removeFrom(this.invalidCallbacks)(callback);\n }.bind(this);\n }\n\n\n /**\n * Reloads the current state\n *\n * A method that force reloads the current state, or a partial state hierarchy.\n * All resolves are re-resolved, and components reinstantiated.\n *\n * #### Example:\n * ```js\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * $state.reload();\n * }\n * });\n * ```\n *\n * Note: `reload()` is just an alias for:\n *\n * ```js\n * $state.transitionTo($state.current, $state.params, {\n * reload: true, inherit: false\n * });\n * ```\n *\n * @param reloadState A state name or a state object.\n * If present, this state and all its children will be reloaded, but ancestors will not reload.\n *\n * #### Example:\n * ```js\n * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'\n * //and current state is 'contacts.detail.item'\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * //will reload 'contact.detail' and nested 'contact.detail.item' states\n * $state.reload('contact.detail');\n * }\n * });\n * ```\n *\n * @returns A promise representing the state of the new transition. See [[StateService.go]]\n */\n reload(reloadState?: StateOrName): Promise {\n return this.transitionTo(this.current, this.params, {\n reload: isDefined(reloadState) ? reloadState : true,\n inherit: false,\n notify: false,\n });\n }\n\n /**\n * Transition to a different state and/or parameters\n *\n * Convenience method for transitioning to a new state.\n *\n * `$state.go` calls `$state.transitionTo` internally but automatically sets options to\n * `{ location: true, inherit: true, relative: router.globals.$current, notify: true }`.\n * This allows you to use either an absolute or relative `to` argument (because of `relative: router.globals.$current`).\n * It also allows you to specify * only the parameters you'd like to update, while letting unspecified parameters\n * inherit from the current parameter values (because of `inherit: true`).\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.go('contact.detail');\n * };\n * });\n * ```\n *\n * @param to Absolute state name, state object, or relative state path (relative to current state).\n *\n * Some examples:\n *\n * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n * - `$state.go('^')` - will go to the parent state\n * - `$state.go('^.sibling')` - if current state is `home.child`, will go to the `home.sibling` state\n * - `$state.go('.child.grandchild')` - if current state is home, will go to the `home.child.grandchild` state\n *\n * @param params A map of the parameters that will be sent to the state, will populate $stateParams.\n *\n * Any parameters that are not specified will be inherited from current parameter values (because of `inherit: true`).\n * This allows, for example, going to a sibling state that shares parameters defined by a parent state.\n *\n * @param options Transition options\n *\n * @returns {promise} A promise representing the state of the new transition.\n */\n go(to: StateOrName, params?: RawParams, options?: TransitionOptions): TransitionPromise {\n const defautGoOpts = { relative: this.$current, inherit: true };\n const transOpts = defaults(options, defautGoOpts, defaultTransOpts);\n return this.transitionTo(to, params, transOpts);\n }\n\n /**\n * Creates a [[TargetState]]\n *\n * This is a factory method for creating a TargetState\n *\n * This may be returned from a Transition Hook to redirect a transition, for example.\n */\n target(identifier: StateOrName, params?: RawParams, options: TransitionOptions = {}): TargetState {\n // If we're reloading, find the state object to reload from\n if (isObject(options.reload) && !(options.reload).name)\n throw new Error('Invalid reload state object');\n const reg = this.router.stateRegistry;\n options.reloadState = options.reload === true ? reg.root() : reg.matcher.find( options.reload, options.relative);\n\n if (options.reload && !options.reloadState)\n throw new Error(`No such reload state '${(isString(options.reload) ? options.reload : (options.reload).name)}'`);\n\n return new TargetState(this.router.stateRegistry, identifier, params, options);\n }\n\n private getCurrentPath(): PathNode[] {\n const globals = this.router.globals;\n const latestSuccess: Transition = globals.successfulTransitions.peekTail();\n const rootPath = () => [ new PathNode(this.router.stateRegistry.root()) ];\n return latestSuccess ? latestSuccess.treeChanges().to : rootPath();\n }\n\n /**\n * Low-level method for transitioning to a new state.\n *\n * The [[go]] method (which uses `transitionTo` internally) is recommended in most situations.\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.transitionTo('contact.detail');\n * };\n * });\n * ```\n *\n * @param to State name or state object.\n * @param toParams A map of the parameters that will be sent to the state,\n * will populate $stateParams.\n * @param options Transition options\n *\n * @returns A promise representing the state of the new transition. See [[go]]\n */\n transitionTo(to: StateOrName, toParams: RawParams = {}, options: TransitionOptions = {}): TransitionPromise {\n const router = this.router;\n const globals = router.globals;\n options = defaults(options, defaultTransOpts);\n const getCurrent = () =>\n globals.transition;\n options = extend(options, { current: getCurrent });\n\n const ref: TargetState = this.target(to, toParams, options);\n const currentPath = this.getCurrentPath();\n\n if (!ref.exists())\n return this._handleInvalidTargetState(currentPath, ref);\n\n if (!ref.valid())\n return silentRejection(ref.error());\n\n /**\n * Special handling for Ignored, Aborted, and Redirected transitions\n *\n * The semantics for the transition.run() promise and the StateService.transitionTo()\n * promise differ. For instance, the run() promise may be rejected because it was\n * IGNORED, but the transitionTo() promise is resolved because from the user perspective\n * no error occurred. Likewise, the transition.run() promise may be rejected because of\n * a Redirect, but the transitionTo() promise is chained to the new Transition's promise.\n */\n const rejectedTransitionHandler = (trans: Transition) => (error: any): Promise => {\n if (error instanceof Rejection) {\n const isLatest = router.globals.lastStartedTransitionId === trans.$id;\n\n if (error.type === RejectType.IGNORED) {\n isLatest && router.urlRouter.update();\n // Consider ignored `Transition.run()` as a successful `transitionTo`\n return services.$q.when(globals.current);\n }\n\n const detail: any = error.detail;\n if (error.type === RejectType.SUPERSEDED && error.redirected && detail instanceof TargetState) {\n // If `Transition.run()` was redirected, allow the `transitionTo()` promise to resolve successfully\n // by returning the promise for the new (redirect) `Transition.run()`.\n const redirect: Transition = trans.redirect(detail);\n return redirect.run().catch(rejectedTransitionHandler(redirect));\n }\n\n if (error.type === RejectType.ABORTED) {\n isLatest && router.urlRouter.update();\n return services.$q.reject(error);\n }\n }\n\n const errorHandler = this.defaultErrorHandler();\n errorHandler(error);\n\n return services.$q.reject(error);\n };\n\n const transition = this.router.transitionService.create(currentPath, ref);\n const transitionToPromise = transition.run().catch(rejectedTransitionHandler(transition));\n silenceUncaughtInPromise(transitionToPromise); // issue #2676\n\n // Return a promise for the transition, which also has the transition object on it.\n return extend(transitionToPromise, { transition });\n }\n\n /**\n * Checks if the current state *is* the provided state\n *\n * Similar to [[includes]] but only checks for the full state name.\n * If params is supplied then it will be tested for strict equality against the current\n * active params object, so all params must match with none missing and no extras.\n *\n * #### Example:\n * ```js\n * $state.$current.name = 'contacts.details.item';\n *\n * // absolute name\n * $state.is('contact.details.item'); // returns true\n * $state.is(contactDetailItemStateObject); // returns true\n * ```\n *\n * // relative name (. and ^), typically from a template\n * // E.g. from the 'contacts.details' template\n * ```html\n *
    Item
    \n * ```\n *\n * @param stateOrName The state name (absolute or relative) or state object you'd like to check.\n * @param params A param object, e.g. `{sectionId: section.id}`, that you'd like\n * to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns Returns true if it is the state.\n */\n is(stateOrName: StateOrName, params?: RawParams, options?: { relative?: StateOrName }): boolean {\n options = defaults(options, { relative: this.$current });\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n if (!isDefined(state)) return undefined;\n if (this.$current !== state) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n /**\n * Checks if the current state *includes* the provided state\n *\n * A method to determine if the current active state is equal to or is the child of the\n * state stateName. If any params are passed then they will be tested for a match as well.\n * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n *\n * #### Example when `$state.$current.name === 'contacts.details.item'`\n * ```js\n * // Using partial names\n * $state.includes(\"contacts\"); // returns true\n * $state.includes(\"contacts.details\"); // returns true\n * $state.includes(\"contacts.details.item\"); // returns true\n * $state.includes(\"contacts.list\"); // returns false\n * $state.includes(\"about\"); // returns false\n * ```\n *\n * #### Glob Examples when `* $state.$current.name === 'contacts.details.item.url'`:\n * ```js\n * $state.includes(\"*.details.*.*\"); // returns true\n * $state.includes(\"*.details.**\"); // returns true\n * $state.includes(\"**.item.**\"); // returns true\n * $state.includes(\"*.details.item.url\"); // returns true\n * $state.includes(\"*.details.*.url\"); // returns true\n * $state.includes(\"*.details.*\"); // returns false\n * $state.includes(\"item.**\"); // returns false\n * ```\n *\n * @param stateOrName A partial name, relative name, glob pattern,\n * or state object to be searched for within the current state name.\n * @param params A param object, e.g. `{sectionId: section.id}`,\n * that you'd like to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns {boolean} Returns true if it does include the state\n */\n includes(stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions): boolean {\n options = defaults(options, { relative: this.$current });\n const glob = isString(stateOrName) && Glob.fromString( stateOrName);\n\n if (glob) {\n if (!glob.matches(this.$current.name)) return false;\n stateOrName = this.$current.name;\n }\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative), include = this.$current.includes;\n\n if (!isDefined(state)) return undefined;\n if (!isDefined(include[state.name])) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n\n /**\n * Generates a URL for a state and parameters\n *\n * Returns the url for the given state populated with the given params.\n *\n * #### Example:\n * ```js\n * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n * ```\n *\n * @param stateOrName The state name or state object you'd like to generate a url from.\n * @param params An object of parameter values to fill the state's required parameters.\n * @param options Options object. The options are:\n *\n * @returns {string} compiled state url\n */\n href(stateOrName: StateOrName, params: RawParams, options?: HrefOptions): string {\n const defaultHrefOpts = {\n lossy: true,\n inherit: true,\n absolute: false,\n relative: this.$current,\n };\n options = defaults(options, defaultHrefOpts);\n params = params || {};\n\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n\n if (!isDefined(state)) return null;\n if (options.inherit) params = this.params.$inherit(params, this.$current, state);\n\n const nav = (state && options.lossy) ? state.navigable : state;\n\n if (!nav || nav.url === undefined || nav.url === null) {\n return null;\n }\n return this.router.urlRouter.href(nav.url, params, {\n absolute: options.absolute,\n });\n }\n\n /** @hidden */\n private _defaultErrorHandler: ((_error: any) => void) = function $defaultErrorHandler($error$) {\n if ($error$ instanceof Error && $error$.stack) {\n console.error($error$);\n console.error($error$.stack);\n } else if ($error$ instanceof Rejection) {\n console.error($error$.toString());\n if ($error$.detail && $error$.detail.stack)\n console.error($error$.detail.stack);\n } else {\n console.error($error$);\n }\n };\n\n /**\n * Sets or gets the default [[transitionTo]] error handler.\n *\n * The error handler is called when a [[Transition]] is rejected or when any error occurred during the Transition.\n * This includes errors caused by resolves and transition hooks.\n *\n * Note:\n * This handler does not receive certain Transition rejections.\n * Redirected and Ignored Transitions are not considered to be errors by [[StateService.transitionTo]].\n *\n * The built-in default error handler logs the error to the console.\n *\n * You can provide your own custom handler.\n *\n * #### Example:\n * ```js\n * stateService.defaultErrorHandler(function() {\n * // Do not log transitionTo errors\n * });\n * ```\n *\n * @param handler a global error handler function\n * @returns the current global error handler\n */\n defaultErrorHandler(handler?: (error: any) => void): (error: any) => void {\n return this._defaultErrorHandler = handler || this._defaultErrorHandler;\n }\n\n /**\n * Gets a registered [[StateDeclaration]] object\n *\n * Returns the state declaration object for any specific state, or for all registered states.\n *\n * @param stateOrName (absolute or relative) If provided, will only get the declaration object for the requested state.\n * If not provided, returns an array of ALL states.\n * @param base When `stateOrName` is a relative state reference (such as `.bar.baz`), the state will be retrieved relative to this state.\n *\n * @returns a [[StateDeclaration]] object (or array of all registered [[StateDeclaration]] objects.)\n */\n get(stateOrName: StateOrName, base: StateOrName): StateDeclaration;\n get(stateOrName: StateOrName): StateDeclaration;\n get(): StateDeclaration[];\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n const reg = this.router.stateRegistry;\n if (arguments.length === 0) return reg.get();\n return reg.get(stateOrName, base || this.$current);\n }\n\n /**\n * Lazy loads a state\n *\n * Explicitly runs a state's [[StateDeclaration.lazyLoad]] function.\n *\n * @param stateOrName the state that should be lazy loaded\n * @param transition the optional Transition context to use (if the lazyLoad function requires an injector, etc)\n * Note: If no transition is provided, a noop transition is created using the from the current state to the current state.\n * This noop transition is not actually run.\n *\n * @returns a promise to lazy load\n */\n lazyLoad(stateOrName: StateOrName, transition?: Transition): Promise {\n const state: StateDeclaration = this.get(stateOrName);\n if (!state || !state.lazyLoad) throw new Error('Can not lazy load ' + stateOrName);\n\n const currentPath = this.getCurrentPath();\n const target = PathUtils.makeTargetState(this.router.stateRegistry, currentPath);\n transition = transition || this.router.transitionService.create(currentPath, target);\n\n return lazyLoadState(transition, state);\n }\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isArray, isObject, $QLike } from '../common/index';\n\n/**\n * An angular1-like promise api\n *\n * This object implements four methods similar to the\n * [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This API provides native ES6 promise support wrapped as a $q-like API.\n * Internally, UI-Router uses this $q object to perform promise operations.\n * The `angular-ui-router` (ui-router for angular 1) uses the $q API provided by angular.\n *\n * $q-like promise api\n */\nexport const $q = {\n /** Normalizes a value as a promise */\n when: (val) => new Promise((resolve, reject) => resolve(val)),\n\n /** Normalizes a value as a promise rejection */\n reject: (val) => new Promise((resolve, reject) => { reject(val); }),\n\n /** @returns a deferred object, which has `resolve` and `reject` functions */\n defer: () => {\n const deferred: any = {};\n deferred.promise = new Promise((resolve, reject) => {\n deferred.resolve = resolve;\n deferred.reject = reject;\n });\n return deferred;\n },\n\n /** Like Promise.all(), but also supports object key/promise notation like $q */\n all: (promises: { [key: string]: Promise } | Promise[]) => {\n if (isArray(promises)) {\n return Promise.all(promises);\n }\n\n if (isObject(promises)) {\n // Convert promises map to promises array.\n // When each promise resolves, map it to a tuple { key: key, val: val }\n const chain = Object.keys(promises)\n .map(key => promises[key].then(val => ({ key, val })));\n\n // Then wait for all promises to resolve, and convert them back to an object\n return $q.all(chain).then(values =>\n values.reduce((acc, tuple) => { acc[tuple.key] = tuple.val; return acc; }, {}));\n }\n },\n} as $QLike;\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n extend, assertPredicate, isFunction, isArray, isInjectable, $InjectorLike, IInjectable,\n} from '../common/index';\n\n// globally available injectables\nconst globals = {};\nconst STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nconst ARGUMENT_NAMES = /([^\\s,]+)/g;\n\n/**\n * A basic angular1-like injector api\n *\n * This object implements four methods similar to the\n * [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This object provides a naive implementation of a globally scoped dependency injection system.\n * It supports the following DI approaches:\n *\n * ### Function parameter names\n *\n * A function's `.toString()` is called, and the parameter names are parsed.\n * This only works when the parameter names aren't \"mangled\" by a minifier such as UglifyJS.\n *\n * ```js\n * function injectedFunction(FooService, BarService) {\n * // FooService and BarService are injected\n * }\n * ```\n *\n * ### Function annotation\n *\n * A function may be annotated with an array of dependency names as the `$inject` property.\n *\n * ```js\n * injectedFunction.$inject = [ 'FooService', 'BarService' ];\n * function injectedFunction(fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }\n * ```\n *\n * ### Array notation\n *\n * An array provides the names of the dependencies to inject (as strings).\n * The function is the last element of the array.\n *\n * ```js\n * [ 'FooService', 'BarService', function (fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }]\n * ```\n *\n * @type {$InjectorLike}\n */\nexport const $injector = {\n /** Gets an object from DI based on a string token */\n get: name => globals[name],\n\n /** Returns true if an object named `name` exists in global DI */\n has: (name) => $injector.get(name) != null,\n\n /**\n * Injects a function\n *\n * @param fn the function to inject\n * @param context the function's `this` binding\n * @param locals An object with additional DI tokens and values, such as `{ someToken: { foo: 1 } }`\n */\n invoke: (fn: IInjectable, context?, locals?) => {\n const all = extend({}, globals, locals || {});\n const params = $injector.annotate(fn);\n const ensureExist = assertPredicate((key: string) => all.hasOwnProperty(key), key => `DI can't find injectable: '${key}'`);\n const args = params.filter(ensureExist).map(x => all[x]);\n if (isFunction(fn)) return fn.apply(context, args);\n else return (fn as any[]).slice(-1)[0].apply(context, args);\n },\n\n /**\n * Returns a function's dependencies\n *\n * Analyzes a function (or array) and returns an array of DI tokens that the function requires.\n * @return an array of `string`s\n */\n annotate: (fn: IInjectable): any[] => {\n if (!isInjectable(fn)) throw new Error(`Not an injectable function: ${fn}`);\n if (fn && (fn as any).$inject) return (fn as any).$inject;\n if (isArray(fn)) return fn.slice(0, -1);\n const fnStr = fn.toString().replace(STRIP_COMMENTS, '');\n const result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);\n return result || [];\n },\n} as $InjectorLike;\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n LocationConfig, LocationServices, identity, unnestR, isArray, splitEqual, splitHash, splitQuery,\n} from '../common';\nimport { UIRouter } from '../router';\n\nexport const keyValsToObjectR = (accum, [key, val]) => {\n if (!accum.hasOwnProperty(key)) {\n accum[key] = val;\n } else if (isArray(accum[key])) {\n accum[key].push(val);\n } else {\n accum[key] = [accum[key], val];\n }\n return accum;\n};\n\nexport const getParams = (queryString: string): any =>\n queryString.split('&').filter(identity).map(splitEqual).reduce(keyValsToObjectR, {});\n\nexport function parseUrl(url: string) {\n const orEmptyString = x => x || '';\n const [beforehash, hash] = splitHash(url).map(orEmptyString);\n const [path, search] = splitQuery(beforehash).map(orEmptyString);\n\n return { path, search, hash, url };\n}\n\nexport const buildUrl = (loc: LocationServices) => {\n const path = loc.path();\n const searchObject = loc.search();\n const hash = loc.hash();\n\n const search = Object.keys(searchObject).map(key => {\n const param = searchObject[key];\n const vals = isArray(param) ? param : [param];\n return vals.map(val => key + '=' + val);\n }).reduce(unnestR, []).join('&');\n\n return path + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n};\n\nexport function locationPluginFactory(\n name: string,\n isHtml5: boolean,\n serviceClass: { new(uiRouter?: UIRouter): LocationServices },\n configurationClass: { new(uiRouter?: UIRouter, isHtml5?: boolean): LocationConfig },\n) {\n return function(uiRouter: UIRouter) {\n const service = uiRouter.locationService = new serviceClass(uiRouter);\n const configuration = uiRouter.locationConfig = new configurationClass(uiRouter, isHtml5);\n\n function dispose(router: UIRouter) {\n router.dispose(service);\n router.dispose(configuration);\n }\n\n return { name, service, configuration, dispose };\n };\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */ /** */\n\nimport { deregAll, isDefined, LocationServices, removeFrom, root } from '../common';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { HistoryLike, LocationLike } from './interface';\nimport { buildUrl, getParams, parseUrl } from './utils';\n\n/** A base `LocationServices` */\nexport abstract class BaseLocationServices implements LocationServices, Disposable {\n private _listeners: Function[] = [];\n _location: LocationLike;\n _history: HistoryLike;\n\n _listener = evt => this._listeners.forEach(cb => cb(evt));\n\n constructor(router: UIRouter, public fireAfterUpdate: boolean) {\n this._location = root.location;\n this._history = root.history;\n }\n\n /**\n * This should return the current internal URL representation.\n *\n * The internal URL includes only the portion that UI-Router matches.\n * It does not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n */\n protected abstract _get(): string;\n\n /**\n * This should set the current URL.\n *\n * The `url` param should include only the portion that UI-Router matches on.\n * It should not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n *\n * However, after this function completes, the browser URL should reflect the entire (fully qualified)\n * HREF including those data.\n */\n protected abstract _set(state: any, title: string, url: string, replace: boolean);\n\n hash = () => parseUrl(this._get()).hash;\n path = () => parseUrl(this._get()).path;\n search = () => getParams(parseUrl(this._get()).search);\n\n url(url?: string, replace = true): string {\n if (isDefined(url) && url !== this._get()) {\n this._set(null, null, url, replace);\n\n if (this.fireAfterUpdate) {\n this._listeners.forEach(cb => cb({ url }));\n }\n }\n\n return buildUrl(this);\n }\n\n onChange(cb: EventListener) {\n this._listeners.push(cb);\n return () => removeFrom(this._listeners, cb);\n }\n\n dispose(router: UIRouter) {\n deregAll(this._listeners);\n }\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { root, trimHashVal } from '../common';\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\n\n/** A `LocationServices` that uses the browser hash \"#\" to get/set the current location */\nexport class HashLocationService extends BaseLocationServices {\n constructor(router: UIRouter) {\n super(router, false);\n root.addEventListener('hashchange', this._listener, false);\n }\n\n _get() {\n return trimHashVal(this._location.hash);\n }\n _set(state: any, title: string, url: string, replace: boolean) {\n this._location.hash = url;\n }\n\n dispose (router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('hashchange', this._listener);\n }\n}\n\n", + "/**\n * @coreapi\n * @module url\n */ /** */\n\nimport { UIRouter } from '../router';\nimport { LocationServices, notImplemented, LocationConfig } from '../common/coreservices';\nimport { noop, createProxyFunctions } from '../common/common';\nimport { UrlConfigApi, UrlSyncApi, UrlRulesApi, UrlParts, MatchResult } from './interface';\n\n/** @hidden */\nconst makeStub = (keys: string[]): any =>\n keys.reduce((acc, key) => ((acc[key] = notImplemented(key)), acc), { dispose: noop });\n\n/** @hidden */\nconst locationServicesFns = ['url', 'path', 'search', 'hash', 'onChange'];\n/** @hidden */\nconst locationConfigFns = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix'];\n/** @hidden */\nconst umfFns = ['type', 'caseInsensitive', 'strictMode', 'defaultSquashPolicy'];\n/** @hidden */\nconst rulesFns = ['sort', 'when', 'initial', 'otherwise', 'rules', 'rule', 'removeRule'];\n/** @hidden */\nconst syncFns = ['deferIntercept', 'listen', 'sync', 'match'];\n\n/**\n * API for URL management\n */\nexport class UrlService implements LocationServices, UrlSyncApi {\n /** @hidden */\n static locationServiceStub: LocationServices = makeStub(locationServicesFns);\n /** @hidden */\n static locationConfigStub: LocationConfig = makeStub(locationConfigFns);\n\n /**\n * A nested API for managing URL rules and rewrites\n *\n * See: [[UrlRulesApi]] for details\n */\n rules: UrlRulesApi;\n\n /**\n * A nested API to configure the URL and retrieve URL information\n *\n * See: [[UrlConfigApi]] for details\n */\n config: UrlConfigApi;\n\n /** @hidden */\n private router: UIRouter;\n\n /** @hidden */\n constructor(router: UIRouter, lateBind = true) {\n this.router = router;\n this.rules = {} as any;\n this.config = {} as any;\n\n // proxy function calls from UrlService to the LocationService/LocationConfig\n const locationServices = () => router.locationService;\n createProxyFunctions(locationServices, this, locationServices, locationServicesFns, lateBind);\n\n const locationConfig = () => router.locationConfig;\n createProxyFunctions(locationConfig, this.config, locationConfig, locationConfigFns, lateBind);\n\n const umf = () => router.urlMatcherFactory;\n createProxyFunctions(umf, this.config, umf, umfFns);\n\n const urlRouter = () => router.urlRouter;\n createProxyFunctions(urlRouter, this.rules, urlRouter, rulesFns);\n createProxyFunctions(urlRouter, this, urlRouter, syncFns);\n }\n\n /** @inheritdoc */\n url(): string;\n /** @inheritdoc */\n url(newurl: string, replace?: boolean, state?): void;\n url(newurl?, replace?, state?): any {\n return;\n }\n /** @inheritdoc */\n path(): string {\n return;\n }\n /** @inheritdoc */\n search(): { [key: string]: any } {\n return;\n }\n /** @inheritdoc */\n hash(): string {\n return;\n }\n /** @inheritdoc */\n onChange(callback: Function): Function {\n return;\n }\n\n /**\n * Returns the current URL parts\n *\n * This method returns the current URL components as a [[UrlParts]] object.\n *\n * @returns the current url parts\n */\n parts(): UrlParts {\n return { path: this.path(), search: this.search(), hash: this.hash() };\n }\n\n dispose() {}\n\n /** @inheritdoc */\n sync(evt?) {\n return;\n }\n /** @inheritdoc */\n listen(enabled?: boolean): Function {\n return;\n }\n /** @inheritdoc */\n deferIntercept(defer?: boolean) {\n return;\n }\n /** @inheritdoc */\n match(urlParts: UrlParts): MatchResult {\n return;\n }\n}\n", + "/**\n * @coreapi\n * @module core\n */ /** */\nimport { UrlMatcherFactory } from './url/urlMatcherFactory';\nimport { UrlRouter } from './url/urlRouter';\nimport { TransitionService } from './transition/transitionService';\nimport { ViewService } from './view/view';\nimport { StateRegistry } from './state/stateRegistry';\nimport { StateService } from './state/stateService';\nimport { UIRouterGlobals } from './globals';\nimport { UIRouterPlugin, Disposable } from './interface';\nimport { values, removeFrom } from './common/common';\nimport { isFunction } from './common/predicates';\nimport { UrlService } from './url/urlService';\nimport { LocationServices, LocationConfig } from './common/coreservices';\nimport { Trace, trace } from './common/trace';\n\n/** @hidden */\nlet _routerInstance = 0;\n\n/**\n * The master class used to instantiate an instance of UI-Router.\n *\n * UI-Router (for each specific framework) will create an instance of this class during bootstrap.\n * This class instantiates and wires the UI-Router services together.\n *\n * After a new instance of the UIRouter class is created, it should be configured for your app.\n * For instance, app states should be registered with the [[UIRouter.stateRegistry]].\n *\n * ---\n *\n * Normally the framework code will bootstrap UI-Router.\n * If you are bootstrapping UIRouter manually, tell it to monitor the URL by calling\n * [[UrlService.listen]] then [[UrlService.sync]].\n */\nexport class UIRouter {\n /** @hidden */ $id = _routerInstance++;\n /** @hidden */ _disposed = false;\n /** @hidden */ private _disposables: Disposable[] = [];\n\n /** Provides trace information to the console */\n trace: Trace = trace;\n\n /** Provides services related to ui-view synchronization */\n viewService = new ViewService();\n\n /** Global router state */\n globals: UIRouterGlobals = new UIRouterGlobals();\n\n /** Provides services related to Transitions */\n transitionService: TransitionService = new TransitionService(this);\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlMatcherFactory: UrlMatcherFactory = new UrlMatcherFactory();\n\n /**\n * Deprecated for public use. Use [[urlService]] instead.\n * @deprecated Use [[urlService]] instead\n */\n urlRouter: UrlRouter = new UrlRouter(this);\n\n /** Provides a registry for states, and related registration services */\n stateRegistry: StateRegistry = new StateRegistry(this);\n\n /** Provides services related to states */\n stateService = new StateService(this);\n\n /** Provides services related to the URL */\n urlService: UrlService = new UrlService(this);\n\n /** @hidden plugin instances are registered here */\n private _plugins: { [key: string]: UIRouterPlugin } = {};\n\n /** Registers an object to be notified when the router is disposed */\n disposable(disposable: Disposable) {\n this._disposables.push(disposable);\n }\n\n /**\n * Disposes this router instance\n *\n * When called, clears resources retained by the router by calling `dispose(this)` on all\n * registered [[disposable]] objects.\n *\n * Or, if a `disposable` object is provided, calls `dispose(this)` on that object only.\n *\n * @param disposable (optional) the disposable to dispose\n */\n dispose(disposable?: any): void {\n if (disposable && isFunction(disposable.dispose)) {\n disposable.dispose(this);\n return undefined;\n }\n\n this._disposed = true;\n this._disposables.slice().forEach(d => {\n try {\n typeof d.dispose === 'function' && d.dispose(this);\n removeFrom(this._disposables, d);\n } catch (ignored) {}\n });\n }\n\n /**\n * Creates a new `UIRouter` object\n *\n * @param locationService a [[LocationServices]] implementation\n * @param locationConfig a [[LocationConfig]] implementation\n * @internalapi\n */\n constructor(\n public locationService: LocationServices = UrlService.locationServiceStub,\n public locationConfig: LocationConfig = UrlService.locationConfigStub,\n ) {\n this.viewService._pluginapi._rootViewContext(this.stateRegistry.root());\n this.globals.$current = this.stateRegistry.root();\n this.globals.current = this.globals.$current.self;\n\n this.disposable(this.globals);\n this.disposable(this.stateService);\n this.disposable(this.stateRegistry);\n this.disposable(this.transitionService);\n this.disposable(this.urlRouter);\n this.disposable(locationService);\n this.disposable(locationConfig);\n }\n\n /** Add plugin (as ES6 class) */\n plugin(plugin: { new (router: UIRouter, options?: any): T }, options?: any): T;\n /** Add plugin (as javascript constructor function) */\n plugin(plugin: { (router: UIRouter, options?: any): void }, options?: any): T;\n /** Add plugin (as javascript factory function) */\n plugin(plugin: PluginFactory, options?: any): T;\n /**\n * Adds a plugin to UI-Router\n *\n * This method adds a UI-Router Plugin.\n * A plugin can enhance or change UI-Router behavior using any public API.\n *\n * #### Example:\n * ```js\n * import { MyCoolPlugin } from \"ui-router-cool-plugin\";\n *\n * var plugin = router.addPlugin(MyCoolPlugin);\n * ```\n *\n * ### Plugin authoring\n *\n * A plugin is simply a class (or constructor function) which accepts a [[UIRouter]] instance and (optionally) an options object.\n *\n * The plugin can implement its functionality using any of the public APIs of [[UIRouter]].\n * For example, it may configure router options or add a Transition Hook.\n *\n * The plugin can then be published as a separate module.\n *\n * #### Example:\n * ```js\n * export class MyAuthPlugin implements UIRouterPlugin {\n * constructor(router: UIRouter, options: any) {\n * this.name = \"MyAuthPlugin\";\n * let $transitions = router.transitionService;\n * let $state = router.stateService;\n *\n * let authCriteria = {\n * to: (state) => state.data && state.data.requiresAuth\n * };\n *\n * function authHook(transition: Transition) {\n * let authService = transition.injector().get('AuthService');\n * if (!authService.isAuthenticated()) {\n * return $state.target('login');\n * }\n * }\n *\n * $transitions.onStart(authCriteria, authHook);\n * }\n * }\n * ```\n *\n * @param plugin one of:\n * - a plugin class which implements [[UIRouterPlugin]]\n * - a constructor function for a [[UIRouterPlugin]] which accepts a [[UIRouter]] instance\n * - a factory function which accepts a [[UIRouter]] instance and returns a [[UIRouterPlugin]] instance\n * @param options options to pass to the plugin class/factory\n * @returns the registered plugin instance\n */\n plugin(plugin: any, options: any = {}): T {\n const pluginInstance = new plugin(this, options);\n if (!pluginInstance.name) throw new Error('Required property `name` missing on plugin: ' + pluginInstance);\n this._disposables.push(pluginInstance);\n return (this._plugins[pluginInstance.name] = pluginInstance);\n }\n\n /**\n * Returns registered plugins\n *\n * Returns the registered plugin of the given `pluginName`.\n * If no `pluginName` is given, returns all registered plugins\n *\n * @param pluginName (optional) the name of the plugin to get\n * @return the named plugin (undefined if not found), or all plugins (if `pluginName` is omitted)\n */\n getPlugin(pluginName: string): UIRouterPlugin;\n getPlugin(): UIRouterPlugin[];\n getPlugin(pluginName?: string): UIRouterPlugin | UIRouterPlugin[] {\n return pluginName ? this._plugins[pluginName] : values(this._plugins);\n }\n}\n\n/** @internalapi */\nexport type PluginFactory = (router: UIRouter, options?: any) => T;\n", + "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { UIRouter } from '../router';\nimport { TransitionService } from '../transition/transitionService';\nimport { Resolvable } from '../resolve';\nimport { extend, inArray, map, mapObj, uniqR, unnestR, values } from '../common';\nimport { PathNode } from '../path';\nimport { TreeChanges } from '../transition';\n\nfunction addCoreResolvables(trans: Transition) {\n trans.addResolvable(Resolvable.fromData(UIRouter, trans.router), '');\n trans.addResolvable(Resolvable.fromData(Transition, trans), '');\n trans.addResolvable(Resolvable.fromData('$transition$', trans), '');\n trans.addResolvable(Resolvable.fromData('$stateParams', trans.params()), '');\n\n trans.entering().forEach(state => {\n trans.addResolvable(Resolvable.fromData('$state$', state), state);\n });\n}\n\nexport const registerAddCoreResolvables = (transitionService: TransitionService) =>\n transitionService.onCreate({}, addCoreResolvables);\n\nconst TRANSITION_TOKENS = ['$transition$', Transition];\nconst isTransition = inArray(TRANSITION_TOKENS);\n\n// References to Transition in the treeChanges pathnodes makes all\n// previous Transitions reachable in memory, causing a memory leak\n// This function removes resolves for '$transition$' and `Transition` from the treeChanges.\n// Do not use this on current transitions, only on old ones.\nexport const treeChangesCleanup = (trans: Transition) => {\n const nodes = values(trans.treeChanges())\n .reduce(unnestR, [])\n .reduce(uniqR, []);\n\n // If the resolvable is a Transition, return a new resolvable with null data\n const replaceTransitionWithNull = (r: Resolvable): Resolvable => {\n return isTransition(r.token) ? Resolvable.fromData(r.token, null) : r;\n };\n\n nodes.forEach((node: PathNode) => {\n node.resolvables = node.resolvables.map(replaceTransitionWithNull);\n });\n};\n", + "/** @module hooks */ /** */\nimport { isString, isFunction } from '../common/predicates';\nimport { Transition } from '../transition/transition';\nimport { services } from '../common/coreservices';\nimport { TargetState } from '../state/targetState';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\n\n/**\n * A [[TransitionHookFn]] that redirects to a different state or params\n *\n * Registered using `transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectHook);`\n *\n * See [[StateDeclaration.redirectTo]]\n */\nconst redirectToHook: TransitionHookFn = (trans: Transition) => {\n const redirect = trans.to().redirectTo;\n if (!redirect) return;\n\n const $state = trans.router.stateService;\n\n function handleResult(result: any) {\n if (!result) return;\n if (result instanceof TargetState) return result;\n if (isString(result)) return $state.target(result, trans.params(), trans.options());\n if (result['state'] || result['params'])\n return $state.target(result['state'] || trans.to(), result['params'] || trans.params(), trans.options());\n }\n\n if (isFunction(redirect)) {\n return services.$q.when(redirect(trans)).then(handleResult);\n }\n return handleResult(redirect);\n};\n\nexport const registerRedirectToHook = (transitionService: TransitionService) =>\n transitionService.onStart({ to: state => !!state.redirectTo }, redirectToHook);\n", + "/** @module hooks */\n/** for typedoc */\nimport { TransitionStateHookFn } from '../transition/interface';\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { StateDeclaration } from '../state/interface';\nimport { StateObject } from '../state/stateObject';\n\n/**\n * A factory which creates an onEnter, onExit or onRetain transition hook function\n *\n * The returned function invokes the (for instance) state.onEnter hook when the\n * state is being entered.\n *\n * @hidden\n */\nfunction makeEnterExitRetainHook(hookName: string): TransitionStateHookFn {\n return (transition: Transition, state: StateDeclaration) => {\n const _state: StateObject = state.$$state();\n const hookFn: TransitionStateHookFn = _state[hookName];\n return hookFn(transition, state);\n };\n}\n\n/**\n * The [[TransitionStateHookFn]] for onExit\n *\n * When the state is being exited, the state's .onExit function is invoked.\n *\n * Registered using `transitionService.onExit({ exiting: (state) => !!state.onExit }, onExitHook);`\n *\n * See: [[IHookRegistry.onExit]]\n */\nconst onExitHook: TransitionStateHookFn = makeEnterExitRetainHook('onExit');\nexport const registerOnExitHook = (transitionService: TransitionService) =>\n transitionService.onExit({ exiting: state => !!state.onExit }, onExitHook);\n\n/**\n * The [[TransitionStateHookFn]] for onRetain\n *\n * When the state was already entered, and is not being exited or re-entered, the state's .onRetain function is invoked.\n *\n * Registered using `transitionService.onRetain({ retained: (state) => !!state.onRetain }, onRetainHook);`\n *\n * See: [[IHookRegistry.onRetain]]\n */\nconst onRetainHook: TransitionStateHookFn = makeEnterExitRetainHook('onRetain');\nexport const registerOnRetainHook = (transitionService: TransitionService) =>\n transitionService.onRetain({ retained: state => !!state.onRetain }, onRetainHook);\n\n/**\n * The [[TransitionStateHookFn]] for onEnter\n *\n * When the state is being entered, the state's .onEnter function is invoked.\n *\n * Registered using `transitionService.onEnter({ entering: (state) => !!state.onEnter }, onEnterHook);`\n *\n * See: [[IHookRegistry.onEnter]]\n */\nconst onEnterHook: TransitionStateHookFn = makeEnterExitRetainHook('onEnter');\nexport const registerOnEnterHook = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: state => !!state.onEnter }, onEnterHook);\n", + "/** @module hooks */\n/** for typedoc */\nimport { noop } from '../common/common';\nimport { Transition } from '../transition/transition';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { TransitionStateHookFn, TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\nimport { val } from '../common/hof';\nimport { StateDeclaration } from '../state/interface';\n\nexport const RESOLVE_HOOK_PRIORITY = 1000;\n\n/**\n * A [[TransitionHookFn]] which resolves all EAGER Resolvables in the To Path\n *\n * Registered using `transitionService.onStart({}, eagerResolvePath, { priority: 1000 });`\n *\n * When a Transition starts, this hook resolves all the EAGER Resolvables, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst eagerResolvePath: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to).resolvePath('EAGER', trans).then(noop);\n\nexport const registerEagerResolvePath = (transitionService: TransitionService) =>\n transitionService.onStart({}, eagerResolvePath, { priority: RESOLVE_HOOK_PRIORITY });\n\n/**\n * A [[TransitionHookFn]] which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path\n *\n * Registered using `transitionService.onEnter({ entering: () => true }, lazyResolveState, { priority: 1000 });`\n *\n * When a State is being entered, this hook resolves all the Resolvables for this state, which the transition then waits for.\n *\n * See [[StateDeclaration.resolve]]\n */\nconst lazyResolveState: TransitionStateHookFn = (trans: Transition, state: StateDeclaration) =>\n new ResolveContext(trans.treeChanges().to)\n .subContext(state.$$state())\n .resolvePath('LAZY', trans)\n .then(noop);\n\nexport const registerLazyResolveState = (transitionService: TransitionService) =>\n transitionService.onEnter({ entering: val(true) }, lazyResolveState, { priority: RESOLVE_HOOK_PRIORITY });\n\n/**\n * A [[TransitionHookFn]] which resolves any dynamically added (LAZY or EAGER) Resolvables.\n *\n * Registered using `transitionService.onFinish({}, eagerResolvePath, { priority: 1000 });`\n *\n * After all entering states have been entered, this hook resolves any remaining Resolvables.\n * These are typically dynamic resolves which were added by some Transition Hook using [[Transition.addResolvable]].\n *\n * See [[StateDeclaration.resolve]]\n */\nconst resolveRemaining: TransitionHookFn = (trans: Transition) =>\n new ResolveContext(trans.treeChanges().to).resolvePath('LAZY', trans).then(noop);\n\nexport const registerResolveRemaining = (transitionService: TransitionService) =>\n transitionService.onFinish({}, resolveRemaining, { priority: RESOLVE_HOOK_PRIORITY });\n", + "/** @module hooks */ /** for typedoc */\nimport { noop } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { Transition } from '../transition/transition';\nimport { ViewService } from '../view/view';\nimport { ViewConfig } from '../view/interface';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which waits for the views to load\n *\n * Registered using `transitionService.onStart({}, loadEnteringViews);`\n *\n * Allows the views to do async work in [[ViewConfig.load]] before the transition continues.\n * In angular 1, this includes loading the templates.\n */\nconst loadEnteringViews: TransitionHookFn = (transition: Transition) => {\n const $q = services.$q;\n const enteringViews = transition.views('entering');\n if (!enteringViews.length) return;\n return $q.all(enteringViews.map(view => $q.when(view.load()))).then(noop);\n};\n\nexport const registerLoadEnteringViews = (transitionService: TransitionService) =>\n transitionService.onFinish({}, loadEnteringViews);\n\n/**\n * A [[TransitionHookFn]] which activates the new views when a transition is successful.\n *\n * Registered using `transitionService.onSuccess({}, activateViews);`\n *\n * After a transition is complete, this hook deactivates the old views from the previous state,\n * and activates the new views from the destination state.\n *\n * See [[ViewService]]\n */\nconst activateViews: TransitionHookFn = (transition: Transition) => {\n const enteringViews = transition.views('entering');\n const exitingViews = transition.views('exiting');\n if (!enteringViews.length && !exitingViews.length) return;\n\n const $view: ViewService = transition.router.viewService;\n\n exitingViews.forEach((vc: ViewConfig) => $view.deactivateViewConfig(vc));\n enteringViews.forEach((vc: ViewConfig) => $view.activateViewConfig(vc));\n\n $view.sync();\n};\n\nexport const registerActivateViews = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, activateViews);\n", + "/** @module hooks */\n/** for typedoc */\nimport { Transition } from '../transition/transition';\nimport { copy } from '../common/common';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates global UI-Router state\n *\n * Registered using `transitionService.onBefore({}, updateGlobalState);`\n *\n * Before a [[Transition]] starts, updates the global value of \"the current transition\" ([[Globals.transition]]).\n * After a successful [[Transition]], updates the global values of \"the current state\"\n * ([[Globals.current]] and [[Globals.$current]]) and \"the current param values\" ([[Globals.params]]).\n *\n * See also the deprecated properties:\n * [[StateService.transition]], [[StateService.current]], [[StateService.params]]\n */\nconst updateGlobalState = (trans: Transition) => {\n const globals = trans.router.globals;\n\n const transitionSuccessful = () => {\n globals.successfulTransitions.enqueue(trans);\n globals.$current = trans.$to();\n globals.current = globals.$current.self;\n\n copy(trans.params(), globals.params);\n };\n\n const clearCurrentTransition = () => {\n // Do not clear globals.transition if a different transition has started in the meantime\n if (globals.transition === trans) globals.transition = null;\n };\n\n trans.onSuccess({}, transitionSuccessful, { priority: 10000 });\n trans.promise.then(clearCurrentTransition, clearCurrentTransition);\n};\n\nexport const registerUpdateGlobalState = (transitionService: TransitionService) =>\n transitionService.onCreate({}, updateGlobalState);\n", + "/** @module hooks */ /** */\nimport { UrlRouter } from '../url/urlRouter';\nimport { StateService } from '../state/stateService';\nimport { Transition } from '../transition/transition';\nimport { TransitionHookFn } from '../transition/interface';\nimport { TransitionService } from '../transition/transitionService';\n\n/**\n * A [[TransitionHookFn]] which updates the URL after a successful transition\n *\n * Registered using `transitionService.onSuccess({}, updateUrl);`\n */\nconst updateUrl: TransitionHookFn = (transition: Transition) => {\n const options = transition.options();\n const $state: StateService = transition.router.stateService;\n const $urlRouter: UrlRouter = transition.router.urlRouter;\n\n // Dont update the url in these situations:\n // The transition was triggered by a URL sync (options.source === 'url')\n // The user doesn't want the url to update (options.location === false)\n // The destination state, and all parents have no navigable url\n if (options.source !== 'url' && options.location && $state.$current.navigable) {\n const urlOptions = { replace: options.location === 'replace' };\n $urlRouter.push($state.$current.navigable.url, $state.params, urlOptions);\n }\n\n $urlRouter.update(true);\n};\n\nexport const registerUpdateUrl = (transitionService: TransitionService) =>\n transitionService.onSuccess({}, updateUrl, { priority: 9999 });\n", + "/** @module hooks */ /** */\nimport { Transition } from '../transition/transition';\nimport { TransitionService } from '../transition/transitionService';\nimport { TransitionHookFn } from '../transition/interface';\nimport { StateDeclaration, LazyLoadResult } from '../state/interface';\nimport { services } from '../common/coreservices';\nimport { StateRule } from '../url/interface';\n\n/**\n * A [[TransitionHookFn]] that performs lazy loading\n *\n * When entering a state \"abc\" which has a `lazyLoad` function defined:\n * - Invoke the `lazyLoad` function (unless it is already in process)\n * - Flag the hook function as \"in process\"\n * - The function should return a promise (that resolves when lazy loading is complete)\n * - Wait for the promise to settle\n * - If the promise resolves to a [[LazyLoadResult]], then register those states\n * - Flag the hook function as \"not in process\"\n * - If the hook was successful\n * - Remove the `lazyLoad` function from the state declaration\n * - If all the hooks were successful\n * - Retry the transition (by returning a TargetState)\n *\n * ```\n * .state('abc', {\n * component: 'fooComponent',\n * lazyLoad: () => System.import('./fooComponent')\n * });\n * ```\n *\n * See [[StateDeclaration.lazyLoad]]\n */\nconst lazyLoadHook: TransitionHookFn = (transition: Transition) => {\n const router = transition.router;\n\n function retryTransition() {\n if (transition.originalTransition().options().source !== 'url') {\n // The original transition was not triggered via url sync\n // The lazy state should be loaded now, so re-try the original transition\n const orig = transition.targetState();\n return router.stateService.target(orig.identifier(), orig.params(), orig.options());\n }\n\n // The original transition was triggered via url sync\n // Run the URL rules and find the best match\n const $url = router.urlService;\n const result = $url.match($url.parts());\n const rule = result && result.rule;\n\n // If the best match is a state, redirect the transition (instead\n // of calling sync() which supersedes the current transition)\n if (rule && rule.type === 'STATE') {\n const state = (rule as StateRule).state;\n const params = result.match;\n return router.stateService.target(state, params, transition.options());\n }\n\n // No matching state found, so let .sync() choose the best non-state match/otherwise\n router.urlService.sync();\n }\n\n const promises = transition\n .entering()\n .filter(state => !!state.$$state().lazyLoad)\n .map(state => lazyLoadState(transition, state));\n\n return services.$q.all(promises).then(retryTransition);\n};\n\nexport const registerLazyLoadHook = (transitionService: TransitionService) =>\n transitionService.onBefore({ entering: state => !!state.lazyLoad }, lazyLoadHook);\n\n/**\n * Invokes a state's lazy load function\n *\n * @param transition a Transition context\n * @param state the state to lazy load\n * @returns A promise for the lazy load result\n */\nexport function lazyLoadState(transition: Transition, state: StateDeclaration): Promise {\n const lazyLoadFn = state.$$state().lazyLoad;\n\n // Store/get the lazy load promise on/from the hookfn so it doesn't get re-invoked\n let promise = lazyLoadFn['_promise'];\n if (!promise) {\n const success = result => {\n delete state.lazyLoad;\n delete state.$$state().lazyLoad;\n delete lazyLoadFn['_promise'];\n return result;\n };\n\n const error = err => {\n delete lazyLoadFn['_promise'];\n return services.$q.reject(err);\n };\n\n promise = lazyLoadFn['_promise'] = services.$q\n .when(lazyLoadFn(transition, state))\n .then(updateStateRegistry)\n .then(success, error);\n }\n\n /** Register any lazy loaded state definitions */\n function updateStateRegistry(result: LazyLoadResult) {\n if (result && Array.isArray(result.states)) {\n result.states.forEach(_state => transition.router.stateRegistry.register(_state));\n }\n return result;\n }\n\n return promise;\n}\n", + "/** @module transition */ /** */\nimport { TransitionHookPhase, PathType } from './interface';\nimport { GetErrorHandler, GetResultHandler, TransitionHook } from './transitionHook';\n/**\n * This class defines a type of hook, such as `onBefore` or `onEnter`.\n * Plugins can define custom hook types, such as sticky states does for `onInactive`.\n *\n * @interalapi\n */\nexport class TransitionEventType {\n /* tslint:disable:no-inferrable-types */\n constructor(\n public name: string,\n public hookPhase: TransitionHookPhase,\n public hookOrder: number,\n public criteriaMatchPath: PathType,\n public reverseSort: boolean = false,\n public getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n public getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n public synchronous: boolean = false,\n ) {}\n}\n", + "/** @module hooks */ /** */\n\nimport { trace } from '../common/trace';\nimport { Rejection } from '../transition/rejectFactory';\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that skips a transition if it should be ignored\n *\n * This hook is invoked at the end of the onBefore phase.\n *\n * If the transition should be ignored (because no parameter or states changed)\n * then the transition is ignored and not processed.\n */\nfunction ignoredHook(trans: Transition) {\n const ignoredReason = trans._ignoredReason();\n if (!ignoredReason) return;\n\n trace.traceTransitionIgnored(trans);\n\n const pending = trans.router.globals.transition;\n\n // The user clicked a link going back to the *current state* ('A')\n // However, there is also a pending transition in flight (to 'B')\n // Abort the transition to 'B' because the user now wants to be back at 'A'.\n if (ignoredReason === 'SameAsCurrent' && pending) {\n pending.abort();\n }\n\n return Rejection.ignored().toPromise();\n}\n\nexport const registerIgnoredTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, ignoredHook, { priority: -9999 });\n", + "/** @module hooks */ /** */\n\nimport { TransitionService } from '../transition/transitionService';\nimport { Transition } from '../transition/transition';\n\n/**\n * A [[TransitionHookFn]] that rejects the Transition if it is invalid\n *\n * This hook is invoked at the end of the onBefore phase.\n * If the transition is invalid (for example, param values do not validate)\n * then the transition is rejected.\n */\nfunction invalidTransitionHook(trans: Transition) {\n if (!trans.valid()) {\n throw new Error(trans.error().toString());\n }\n}\n\nexport const registerInvalidTransitionHook = (transitionService: TransitionService) =>\n transitionService.onBefore({}, invalidTransitionHook, { priority: -10000 });\n", + "/**\n * @coreapi\n * @module transition\n */\n/** for typedoc */\nimport {\n IHookRegistry,\n TransitionOptions,\n TransitionHookScope,\n TransitionHookPhase,\n TransitionCreateHookFn,\n HookMatchCriteria,\n HookRegOptions,\n PathTypes,\n PathType,\n RegisteredHooks,\n TransitionHookFn,\n TransitionStateHookFn,\n} from './interface';\nimport { Transition } from './transition';\nimport { makeEvent, RegisteredHook } from './hookRegistry';\nimport { TargetState } from '../state/targetState';\nimport { PathNode } from '../path/pathNode';\nimport { ViewService } from '../view/view';\nimport { UIRouter } from '../router';\nimport { registerAddCoreResolvables, treeChangesCleanup } from '../hooks/coreResolvables';\nimport { registerRedirectToHook } from '../hooks/redirectTo';\nimport { registerOnExitHook, registerOnRetainHook, registerOnEnterHook } from '../hooks/onEnterExitRetain';\nimport { registerEagerResolvePath, registerLazyResolveState, registerResolveRemaining } from '../hooks/resolve';\nimport { registerLoadEnteringViews, registerActivateViews } from '../hooks/views';\nimport { registerUpdateGlobalState } from '../hooks/updateGlobals';\nimport { registerUpdateUrl } from '../hooks/url';\nimport { registerLazyLoadHook } from '../hooks/lazyLoad';\nimport { TransitionEventType } from './transitionEventType';\nimport { TransitionHook, GetResultHandler, GetErrorHandler } from './transitionHook';\nimport { isDefined } from '../common/predicates';\nimport { removeFrom, values, createProxyFunctions } from '../common/common';\nimport { Disposable } from '../interface'; // has or is using\nimport { val } from '../common/hof';\nimport { registerIgnoredTransitionHook } from '../hooks/ignoredTransition';\nimport { registerInvalidTransitionHook } from '../hooks/invalidTransition';\n\n/**\n * The default [[Transition]] options.\n *\n * Include this object when applying custom defaults:\n * let reloadOpts = { reload: true, notify: true }\n * let options = defaults(theirOpts, customDefaults, defaultOptions);\n */\nexport let defaultTransOpts: TransitionOptions = {\n location: true,\n relative: null,\n inherit: false,\n notify: true,\n reload: false,\n custom: {},\n current: () => null,\n source: 'unknown',\n};\n\n/**\n * Plugin API for Transition Service\n * @internalapi\n */\nexport interface TransitionServicePluginAPI {\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n */\n _definePathType(name: string, hookScope: TransitionHookScope);\n\n /**\n * Gets a Path definition used as a criterion against a TreeChanges path\n */\n _getPathTypes(): PathTypes;\n\n /**\n * Defines a transition hook type and returns a transition hook registration\n * function (which can then be used to register hooks of this type).\n */\n _defineEvent(\n name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort?: boolean,\n getResultHandler?: GetResultHandler,\n getErrorHandler?: GetErrorHandler,\n rejectIfSuperseded?: boolean,\n );\n\n /**\n * Returns the known event types, such as `onBefore`\n * If a phase argument is provided, returns only events for the given phase.\n */\n _getEvents(phase?: TransitionHookPhase): TransitionEventType[];\n\n /** Returns the hooks registered for the given hook name */\n getHooks(hookName: string): RegisteredHook[];\n}\n\n/**\n * This class provides services related to Transitions.\n *\n * - Most importantly, it allows global Transition Hooks to be registered.\n * - It allows the default transition error handler to be set.\n * - It also has a factory function for creating new [[Transition]] objects, (used internally by the [[StateService]]).\n *\n * At bootstrap, [[UIRouter]] creates a single instance (singleton) of this class.\n */\nexport class TransitionService implements IHookRegistry, Disposable {\n /** @hidden */\n _transitionCount = 0;\n\n /** @hidden */\n public $view: ViewService;\n\n /** @hidden The transition hook types, such as `onEnter`, `onStart`, etc */\n private _eventTypes: TransitionEventType[] = [];\n /** @hidden The registered transition hooks */\n _registeredHooks = {} as RegisteredHooks;\n /** @hidden The paths on a criteria object */\n private _criteriaPaths = {} as PathTypes;\n /** @hidden */\n private _router: UIRouter;\n\n /** @internalapi */\n _pluginapi: TransitionServicePluginAPI;\n\n /**\n * This object has hook de-registration functions for the built-in hooks.\n * This can be used by third parties libraries that wish to customize the behaviors\n *\n * @hidden\n */\n _deregisterHookFns: {\n addCoreResolves: Function;\n ignored: Function;\n invalid: Function;\n redirectTo: Function;\n onExit: Function;\n onRetain: Function;\n onEnter: Function;\n eagerResolve: Function;\n lazyResolve: Function;\n resolveAll: Function;\n loadViews: Function;\n activateViews: Function;\n updateGlobals: Function;\n updateUrl: Function;\n lazyLoad: Function;\n };\n\n /** @hidden */\n constructor(_router: UIRouter) {\n this._router = _router;\n this.$view = _router.viewService;\n this._deregisterHookFns = {};\n this._pluginapi = createProxyFunctions(val(this), {}, val(this), [\n '_definePathType',\n '_defineEvent',\n '_getPathTypes',\n '_getEvents',\n 'getHooks',\n ]);\n\n this._defineCorePaths();\n this._defineCoreEvents();\n this._registerCoreTransitionHooks();\n _router.globals.successfulTransitions.onEvict(treeChangesCleanup);\n }\n\n /**\n * Registers a [[TransitionHookFn]], called *while a transition is being constructed*.\n *\n * Registers a transition lifecycle hook, which is invoked during transition construction.\n *\n * This low level hook should only be used by plugins.\n * This can be a useful time for plugins to add resolves or mutate the transition as needed.\n * The Sticky States plugin uses this hook to modify the treechanges.\n *\n * ### Lifecycle\n *\n * `onCreate` hooks are invoked *while a transition is being constructed*.\n *\n * ### Return value\n *\n * The hook's return value is ignored\n *\n * @internalapi\n * @param criteria defines which Transitions the Hook should be invoked for.\n * @param callback the hook function which will be invoked.\n * @param options the registration options\n * @returns a function which deregisters the hook.\n */\n onCreate(criteria: HookMatchCriteria, callback: TransitionCreateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n /** @inheritdoc */\n onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {\n return;\n }\n\n /**\n * dispose\n * @internalapi\n */\n dispose(router: UIRouter) {\n values(this._registeredHooks).forEach((hooksArray: RegisteredHook[]) =>\n hooksArray.forEach(hook => {\n hook._deregistered = true;\n removeFrom(hooksArray, hook);\n }),\n );\n }\n\n /**\n * Creates a new [[Transition]] object\n *\n * This is a factory function for creating new Transition objects.\n * It is used internally by the [[StateService]] and should generally not be called by application code.\n *\n * @param fromPath the path to the current state (the from state)\n * @param targetState the target state (destination)\n * @returns a Transition\n */\n create(fromPath: PathNode[], targetState: TargetState): Transition {\n return new Transition(fromPath, targetState, this._router);\n }\n\n /** @hidden */\n private _defineCoreEvents() {\n const Phase = TransitionHookPhase;\n const TH = TransitionHook;\n const paths = this._criteriaPaths;\n const NORMAL_SORT = false,\n REVERSE_SORT = true;\n const SYNCHRONOUS = true;\n\n this._defineEvent(\n 'onCreate',\n Phase.CREATE,\n 0,\n paths.to,\n NORMAL_SORT,\n TH.LOG_REJECTED_RESULT,\n TH.THROW_ERROR,\n SYNCHRONOUS,\n );\n\n this._defineEvent('onBefore', Phase.BEFORE, 0, paths.to);\n\n this._defineEvent('onStart', Phase.RUN, 0, paths.to);\n this._defineEvent('onExit', Phase.RUN, 100, paths.exiting, REVERSE_SORT);\n this._defineEvent('onRetain', Phase.RUN, 200, paths.retained);\n this._defineEvent('onEnter', Phase.RUN, 300, paths.entering);\n this._defineEvent('onFinish', Phase.RUN, 400, paths.to);\n\n this._defineEvent(\n 'onSuccess',\n Phase.SUCCESS,\n 0,\n paths.to,\n NORMAL_SORT,\n TH.LOG_REJECTED_RESULT,\n TH.LOG_ERROR,\n SYNCHRONOUS,\n );\n this._defineEvent(\n 'onError',\n Phase.ERROR,\n 0,\n paths.to,\n NORMAL_SORT,\n TH.LOG_REJECTED_RESULT,\n TH.LOG_ERROR,\n SYNCHRONOUS,\n );\n }\n\n /** @hidden */\n private _defineCorePaths() {\n const { STATE, TRANSITION } = TransitionHookScope;\n\n this._definePathType('to', TRANSITION);\n this._definePathType('from', TRANSITION);\n this._definePathType('exiting', STATE);\n this._definePathType('retained', STATE);\n this._definePathType('entering', STATE);\n }\n\n /** @hidden */\n _defineEvent(\n name: string,\n hookPhase: TransitionHookPhase,\n hookOrder: number,\n criteriaMatchPath: PathType,\n reverseSort = false,\n getResultHandler: GetResultHandler = TransitionHook.HANDLE_RESULT,\n getErrorHandler: GetErrorHandler = TransitionHook.REJECT_ERROR,\n synchronous = false,\n ) {\n const eventType = new TransitionEventType(\n name,\n hookPhase,\n hookOrder,\n criteriaMatchPath,\n reverseSort,\n getResultHandler,\n getErrorHandler,\n synchronous,\n );\n\n this._eventTypes.push(eventType);\n makeEvent(this, this, eventType);\n }\n\n /** @hidden */\n // tslint:disable-next-line\n private _getEvents(phase?: TransitionHookPhase): TransitionEventType[] {\n const transitionHookTypes = isDefined(phase)\n ? this._eventTypes.filter(type => type.hookPhase === phase)\n : this._eventTypes.slice();\n\n return transitionHookTypes.sort((l, r) => {\n const cmpByPhase = l.hookPhase - r.hookPhase;\n return cmpByPhase === 0 ? l.hookOrder - r.hookOrder : cmpByPhase;\n });\n }\n\n /**\n * Adds a Path to be used as a criterion against a TreeChanges path\n *\n * For example: the `exiting` path in [[HookMatchCriteria]] is a STATE scoped path.\n * It was defined by calling `defineTreeChangesCriterion('exiting', TransitionHookScope.STATE)`\n * Each state in the exiting path is checked against the criteria and returned as part of the match.\n *\n * Another example: the `to` path in [[HookMatchCriteria]] is a TRANSITION scoped path.\n * It was defined by calling `defineTreeChangesCriterion('to', TransitionHookScope.TRANSITION)`\n * Only the tail of the `to` path is checked against the criteria and returned as part of the match.\n *\n * @hidden\n */\n private _definePathType(name: string, hookScope: TransitionHookScope) {\n this._criteriaPaths[name] = { name, scope: hookScope };\n }\n\n /** * @hidden */\n // tslint:disable-next-line\n private _getPathTypes(): PathTypes {\n return this._criteriaPaths;\n }\n\n /** @hidden */\n public getHooks(hookName: string): RegisteredHook[] {\n return this._registeredHooks[hookName];\n }\n\n /** @hidden */\n private _registerCoreTransitionHooks() {\n const fns = this._deregisterHookFns;\n\n fns.addCoreResolves = registerAddCoreResolvables(this);\n fns.ignored = registerIgnoredTransitionHook(this);\n fns.invalid = registerInvalidTransitionHook(this);\n\n // Wire up redirectTo hook\n fns.redirectTo = registerRedirectToHook(this);\n\n // Wire up onExit/Retain/Enter state hooks\n fns.onExit = registerOnExitHook(this);\n fns.onRetain = registerOnRetainHook(this);\n fns.onEnter = registerOnEnterHook(this);\n\n // Wire up Resolve hooks\n fns.eagerResolve = registerEagerResolvePath(this);\n fns.lazyResolve = registerLazyResolveState(this);\n fns.resolveAll = registerResolveRemaining(this);\n\n // Wire up the View management hooks\n fns.loadViews = registerLoadEnteringViews(this);\n fns.activateViews = registerActivateViews(this);\n\n // Updates global state after a transition\n fns.updateGlobals = registerUpdateGlobalState(this);\n\n // After globals.current is updated at priority: 10000\n fns.updateUrl = registerUpdateUrl(this);\n\n // Lazy load state trees\n fns.lazyLoad = registerLazyLoadHook(this);\n }\n}\n", + "/**\n * @coreapi\n * @module state\n */\n/** */\nimport {\n createProxyFunctions,\n defaults,\n extend,\n inArray,\n noop,\n removeFrom,\n silenceUncaughtInPromise,\n silentRejection,\n} from '../common/common';\nimport { isDefined, isObject, isString } from '../common/predicates';\nimport { Queue } from '../common/queue';\nimport { services } from '../common/coreservices';\n\nimport { PathUtils } from '../path/pathUtils';\nimport { PathNode } from '../path/pathNode';\n\nimport { HookResult, TransitionOptions } from '../transition/interface';\nimport { defaultTransOpts } from '../transition/transitionService';\nimport { Rejection, RejectType } from '../transition/rejectFactory';\nimport { Transition } from '../transition/transition';\n\nimport { HrefOptions, LazyLoadResult, StateDeclaration, StateOrName, TransitionPromise } from './interface';\nimport { StateObject } from './stateObject';\nimport { TargetState } from './targetState';\n\nimport { RawParams } from '../params/interface';\nimport { Param } from '../params/param';\nimport { Glob } from '../common/glob';\nimport { UIRouter } from '../router';\nimport { UIInjector } from '../interface';\nimport { ResolveContext } from '../resolve/resolveContext';\nimport { lazyLoadState } from '../hooks/lazyLoad';\nimport { not, val } from '../common/hof';\nimport { StateParams } from '../params/stateParams';\n\nexport type OnInvalidCallback = (toState?: TargetState, fromState?: TargetState, injector?: UIInjector) => HookResult;\n\n/**\n * Provides state related service functions\n *\n * This class provides services related to ui-router states.\n * An instance of this class is located on the global [[UIRouter]] object.\n */\nexport class StateService {\n /** @internalapi */\n invalidCallbacks: OnInvalidCallback[] = [];\n\n /**\n * The [[Transition]] currently in progress (or null)\n *\n * This is a passthrough through to [[UIRouterGlobals.transition]]\n */\n get transition() {\n return this.router.globals.transition;\n }\n /**\n * The latest successful state parameters\n *\n * This is a passthrough through to [[UIRouterGlobals.params]]\n */\n get params(): StateParams {\n return this.router.globals.params;\n }\n /**\n * The current [[StateDeclaration]]\n *\n * This is a passthrough through to [[UIRouterGlobals.current]]\n */\n get current() {\n return this.router.globals.current;\n }\n /**\n * The current [[StateObject]]\n *\n * This is a passthrough through to [[UIRouterGlobals.$current]]\n */\n get $current() {\n return this.router.globals.$current;\n }\n\n /** @internalapi */\n constructor(private router: UIRouter) {\n const getters = ['current', '$current', 'params', 'transition'];\n const boundFns = Object.keys(StateService.prototype).filter(not(inArray(getters)));\n createProxyFunctions(val(StateService.prototype), this, val(this), boundFns);\n }\n\n /** @internalapi */\n dispose() {\n this.defaultErrorHandler(noop);\n this.invalidCallbacks = [];\n }\n\n /**\n * Handler for when [[transitionTo]] is called with an invalid state.\n *\n * Invokes the [[onInvalid]] callbacks, in natural order.\n * Each callback's return value is checked in sequence until one of them returns an instance of TargetState.\n * The results of the callbacks are wrapped in $q.when(), so the callbacks may return promises.\n *\n * If a callback returns an TargetState, then it is used as arguments to $state.transitionTo() and the result returned.\n *\n * @internalapi\n */\n private _handleInvalidTargetState(fromPath: PathNode[], toState: TargetState) {\n const fromState = PathUtils.makeTargetState(this.router.stateRegistry, fromPath);\n const globals = this.router.globals;\n const latestThing = () => globals.transitionHistory.peekTail();\n const latest = latestThing();\n const callbackQueue = new Queue(this.invalidCallbacks.slice());\n const injector = new ResolveContext(fromPath).injector();\n\n const checkForRedirect = (result: HookResult) => {\n if (!(result instanceof TargetState)) {\n return;\n }\n\n let target = result;\n // Recreate the TargetState, in case the state is now defined.\n target = this.target(target.identifier(), target.params(), target.options());\n\n if (!target.valid()) {\n return Rejection.invalid(target.error()).toPromise();\n }\n\n if (latestThing() !== latest) {\n return Rejection.superseded().toPromise();\n }\n\n return this.transitionTo(target.identifier(), target.params(), target.options());\n };\n\n function invokeNextCallback() {\n const nextCallback = callbackQueue.dequeue();\n if (nextCallback === undefined) return Rejection.invalid(toState.error()).toPromise();\n\n const callbackResult = services.$q.when(nextCallback(toState, fromState, injector));\n return callbackResult.then(checkForRedirect).then(result => result || invokeNextCallback());\n }\n\n return invokeNextCallback();\n }\n\n /**\n * Registers an Invalid State handler\n *\n * Registers a [[OnInvalidCallback]] function to be invoked when [[StateService.transitionTo]]\n * has been called with an invalid state reference parameter\n *\n * Example:\n * ```js\n * stateService.onInvalid(function(to, from, injector) {\n * if (to.name() === 'foo') {\n * let lazyLoader = injector.get('LazyLoadService');\n * return lazyLoader.load('foo')\n * .then(() => stateService.target('foo'));\n * }\n * });\n * ```\n *\n * @param {function} callback invoked when the toState is invalid\n * This function receives the (invalid) toState, the fromState, and an injector.\n * The function may optionally return a [[TargetState]] or a Promise for a TargetState.\n * If one is returned, it is treated as a redirect.\n *\n * @returns a function which deregisters the callback\n */\n onInvalid(callback: OnInvalidCallback): Function {\n this.invalidCallbacks.push(callback);\n return function deregisterListener() {\n removeFrom(this.invalidCallbacks)(callback);\n }.bind(this);\n }\n\n /**\n * Reloads the current state\n *\n * A method that force reloads the current state, or a partial state hierarchy.\n * All resolves are re-resolved, and components reinstantiated.\n *\n * #### Example:\n * ```js\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * $state.reload();\n * }\n * });\n * ```\n *\n * Note: `reload()` is just an alias for:\n *\n * ```js\n * $state.transitionTo($state.current, $state.params, {\n * reload: true, inherit: false\n * });\n * ```\n *\n * @param reloadState A state name or a state object.\n * If present, this state and all its children will be reloaded, but ancestors will not reload.\n *\n * #### Example:\n * ```js\n * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'\n * //and current state is 'contacts.detail.item'\n * let app angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.reload = function(){\n * //will reload 'contact.detail' and nested 'contact.detail.item' states\n * $state.reload('contact.detail');\n * }\n * });\n * ```\n *\n * @returns A promise representing the state of the new transition. See [[StateService.go]]\n */\n reload(reloadState?: StateOrName): Promise {\n return this.transitionTo(this.current, this.params, {\n reload: isDefined(reloadState) ? reloadState : true,\n inherit: false,\n notify: false,\n });\n }\n\n /**\n * Transition to a different state and/or parameters\n *\n * Convenience method for transitioning to a new state.\n *\n * `$state.go` calls `$state.transitionTo` internally but automatically sets options to\n * `{ location: true, inherit: true, relative: router.globals.$current, notify: true }`.\n * This allows you to use either an absolute or relative `to` argument (because of `relative: router.globals.$current`).\n * It also allows you to specify * only the parameters you'd like to update, while letting unspecified parameters\n * inherit from the current parameter values (because of `inherit: true`).\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.go('contact.detail');\n * };\n * });\n * ```\n *\n * @param to Absolute state name, state object, or relative state path (relative to current state).\n *\n * Some examples:\n *\n * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n * - `$state.go('^')` - will go to the parent state\n * - `$state.go('^.sibling')` - if current state is `home.child`, will go to the `home.sibling` state\n * - `$state.go('.child.grandchild')` - if current state is home, will go to the `home.child.grandchild` state\n *\n * @param params A map of the parameters that will be sent to the state, will populate $stateParams.\n *\n * Any parameters that are not specified will be inherited from current parameter values (because of `inherit: true`).\n * This allows, for example, going to a sibling state that shares parameters defined by a parent state.\n *\n * @param options Transition options\n *\n * @returns {promise} A promise representing the state of the new transition.\n */\n go(to: StateOrName, params?: RawParams, options?: TransitionOptions): TransitionPromise {\n const defautGoOpts = { relative: this.$current, inherit: true };\n const transOpts = defaults(options, defautGoOpts, defaultTransOpts);\n return this.transitionTo(to, params, transOpts);\n }\n\n /**\n * Creates a [[TargetState]]\n *\n * This is a factory method for creating a TargetState\n *\n * This may be returned from a Transition Hook to redirect a transition, for example.\n */\n target(identifier: StateOrName, params?: RawParams, options: TransitionOptions = {}): TargetState {\n // If we're reloading, find the state object to reload from\n if (isObject(options.reload) && !(options.reload).name) throw new Error('Invalid reload state object');\n const reg = this.router.stateRegistry;\n options.reloadState =\n options.reload === true ? reg.root() : reg.matcher.find(options.reload, options.relative);\n\n if (options.reload && !options.reloadState)\n throw new Error(\n `No such reload state '${isString(options.reload) ? options.reload : (options.reload).name}'`,\n );\n\n return new TargetState(this.router.stateRegistry, identifier, params, options);\n }\n\n private getCurrentPath(): PathNode[] {\n const globals = this.router.globals;\n const latestSuccess: Transition = globals.successfulTransitions.peekTail();\n const rootPath = () => [new PathNode(this.router.stateRegistry.root())];\n return latestSuccess ? latestSuccess.treeChanges().to : rootPath();\n }\n\n /**\n * Low-level method for transitioning to a new state.\n *\n * The [[go]] method (which uses `transitionTo` internally) is recommended in most situations.\n *\n * #### Example:\n * ```js\n * let app = angular.module('app', ['ui.router']);\n *\n * app.controller('ctrl', function ($scope, $state) {\n * $scope.changeState = function () {\n * $state.transitionTo('contact.detail');\n * };\n * });\n * ```\n *\n * @param to State name or state object.\n * @param toParams A map of the parameters that will be sent to the state,\n * will populate $stateParams.\n * @param options Transition options\n *\n * @returns A promise representing the state of the new transition. See [[go]]\n */\n transitionTo(to: StateOrName, toParams: RawParams = {}, options: TransitionOptions = {}): TransitionPromise {\n const router = this.router;\n const globals = router.globals;\n options = defaults(options, defaultTransOpts);\n const getCurrent = () => globals.transition;\n options = extend(options, { current: getCurrent });\n\n const ref: TargetState = this.target(to, toParams, options);\n const currentPath = this.getCurrentPath();\n\n if (!ref.exists()) return this._handleInvalidTargetState(currentPath, ref);\n\n if (!ref.valid()) return silentRejection(ref.error());\n\n /**\n * Special handling for Ignored, Aborted, and Redirected transitions\n *\n * The semantics for the transition.run() promise and the StateService.transitionTo()\n * promise differ. For instance, the run() promise may be rejected because it was\n * IGNORED, but the transitionTo() promise is resolved because from the user perspective\n * no error occurred. Likewise, the transition.run() promise may be rejected because of\n * a Redirect, but the transitionTo() promise is chained to the new Transition's promise.\n */\n const rejectedTransitionHandler = (trans: Transition) => (error: any): Promise => {\n if (error instanceof Rejection) {\n const isLatest = router.globals.lastStartedTransitionId === trans.$id;\n\n if (error.type === RejectType.IGNORED) {\n isLatest && router.urlRouter.update();\n // Consider ignored `Transition.run()` as a successful `transitionTo`\n return services.$q.when(globals.current);\n }\n\n const detail: any = error.detail;\n if (error.type === RejectType.SUPERSEDED && error.redirected && detail instanceof TargetState) {\n // If `Transition.run()` was redirected, allow the `transitionTo()` promise to resolve successfully\n // by returning the promise for the new (redirect) `Transition.run()`.\n const redirect: Transition = trans.redirect(detail);\n return redirect.run().catch(rejectedTransitionHandler(redirect));\n }\n\n if (error.type === RejectType.ABORTED) {\n isLatest && router.urlRouter.update();\n return services.$q.reject(error);\n }\n }\n\n const errorHandler = this.defaultErrorHandler();\n errorHandler(error);\n\n return services.$q.reject(error);\n };\n\n const transition = this.router.transitionService.create(currentPath, ref);\n const transitionToPromise = transition.run().catch(rejectedTransitionHandler(transition));\n silenceUncaughtInPromise(transitionToPromise); // issue #2676\n\n // Return a promise for the transition, which also has the transition object on it.\n return extend(transitionToPromise, { transition });\n }\n\n /**\n * Checks if the current state *is* the provided state\n *\n * Similar to [[includes]] but only checks for the full state name.\n * If params is supplied then it will be tested for strict equality against the current\n * active params object, so all params must match with none missing and no extras.\n *\n * #### Example:\n * ```js\n * $state.$current.name = 'contacts.details.item';\n *\n * // absolute name\n * $state.is('contact.details.item'); // returns true\n * $state.is(contactDetailItemStateObject); // returns true\n * ```\n *\n * // relative name (. and ^), typically from a template\n * // E.g. from the 'contacts.details' template\n * ```html\n *
    Item
    \n * ```\n *\n * @param stateOrName The state name (absolute or relative) or state object you'd like to check.\n * @param params A param object, e.g. `{sectionId: section.id}`, that you'd like\n * to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns Returns true if it is the state.\n */\n is(stateOrName: StateOrName, params?: RawParams, options?: { relative?: StateOrName }): boolean {\n options = defaults(options, { relative: this.$current });\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n if (!isDefined(state)) return undefined;\n if (this.$current !== state) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n /**\n * Checks if the current state *includes* the provided state\n *\n * A method to determine if the current active state is equal to or is the child of the\n * state stateName. If any params are passed then they will be tested for a match as well.\n * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n *\n * #### Example when `$state.$current.name === 'contacts.details.item'`\n * ```js\n * // Using partial names\n * $state.includes(\"contacts\"); // returns true\n * $state.includes(\"contacts.details\"); // returns true\n * $state.includes(\"contacts.details.item\"); // returns true\n * $state.includes(\"contacts.list\"); // returns false\n * $state.includes(\"about\"); // returns false\n * ```\n *\n * #### Glob Examples when `* $state.$current.name === 'contacts.details.item.url'`:\n * ```js\n * $state.includes(\"*.details.*.*\"); // returns true\n * $state.includes(\"*.details.**\"); // returns true\n * $state.includes(\"**.item.**\"); // returns true\n * $state.includes(\"*.details.item.url\"); // returns true\n * $state.includes(\"*.details.*.url\"); // returns true\n * $state.includes(\"*.details.*\"); // returns false\n * $state.includes(\"item.**\"); // returns false\n * ```\n *\n * @param stateOrName A partial name, relative name, glob pattern,\n * or state object to be searched for within the current state name.\n * @param params A param object, e.g. `{sectionId: section.id}`,\n * that you'd like to test against the current active state.\n * @param options An options object. The options are:\n * - `relative`: If `stateOrName` is a relative state name and `options.relative` is set, .is will\n * test relative to `options.relative` state (or name).\n *\n * @returns {boolean} Returns true if it does include the state\n */\n includes(stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions): boolean {\n options = defaults(options, { relative: this.$current });\n const glob = isString(stateOrName) && Glob.fromString(stateOrName);\n\n if (glob) {\n if (!glob.matches(this.$current.name)) return false;\n stateOrName = this.$current.name;\n }\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative),\n include = this.$current.includes;\n\n if (!isDefined(state)) return undefined;\n if (!isDefined(include[state.name])) return false;\n if (!params) return true;\n\n const schema: Param[] = state.parameters({ inherit: true, matchingKeys: params });\n return Param.equals(schema, Param.values(schema, params), this.params);\n }\n\n /**\n * Generates a URL for a state and parameters\n *\n * Returns the url for the given state populated with the given params.\n *\n * #### Example:\n * ```js\n * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n * ```\n *\n * @param stateOrName The state name or state object you'd like to generate a url from.\n * @param params An object of parameter values to fill the state's required parameters.\n * @param options Options object. The options are:\n *\n * @returns {string} compiled state url\n */\n href(stateOrName: StateOrName, params: RawParams, options?: HrefOptions): string {\n const defaultHrefOpts = {\n lossy: true,\n inherit: true,\n absolute: false,\n relative: this.$current,\n };\n options = defaults(options, defaultHrefOpts);\n params = params || {};\n\n const state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);\n\n if (!isDefined(state)) return null;\n if (options.inherit) params = this.params.$inherit(params, this.$current, state);\n\n const nav = state && options.lossy ? state.navigable : state;\n\n if (!nav || nav.url === undefined || nav.url === null) {\n return null;\n }\n return this.router.urlRouter.href(nav.url, params, {\n absolute: options.absolute,\n });\n }\n\n /** @hidden */\n private _defaultErrorHandler: ((_error: any) => void) = function $defaultErrorHandler($error$) {\n if ($error$ instanceof Error && $error$.stack) {\n console.error($error$);\n console.error($error$.stack);\n } else if ($error$ instanceof Rejection) {\n console.error($error$.toString());\n if ($error$.detail && $error$.detail.stack) console.error($error$.detail.stack);\n } else {\n console.error($error$);\n }\n };\n\n /**\n * Sets or gets the default [[transitionTo]] error handler.\n *\n * The error handler is called when a [[Transition]] is rejected or when any error occurred during the Transition.\n * This includes errors caused by resolves and transition hooks.\n *\n * Note:\n * This handler does not receive certain Transition rejections.\n * Redirected and Ignored Transitions are not considered to be errors by [[StateService.transitionTo]].\n *\n * The built-in default error handler logs the error to the console.\n *\n * You can provide your own custom handler.\n *\n * #### Example:\n * ```js\n * stateService.defaultErrorHandler(function() {\n * // Do not log transitionTo errors\n * });\n * ```\n *\n * @param handler a global error handler function\n * @returns the current global error handler\n */\n defaultErrorHandler(handler?: (error: any) => void): (error: any) => void {\n return (this._defaultErrorHandler = handler || this._defaultErrorHandler);\n }\n\n /**\n * Gets a registered [[StateDeclaration]] object\n *\n * Returns the state declaration object for any specific state, or for all registered states.\n *\n * @param stateOrName (absolute or relative) If provided, will only get the declaration object for the requested state.\n * If not provided, returns an array of ALL states.\n * @param base When `stateOrName` is a relative state reference (such as `.bar.baz`), the state will be retrieved relative to this state.\n *\n * @returns a [[StateDeclaration]] object (or array of all registered [[StateDeclaration]] objects.)\n */\n get(stateOrName: StateOrName, base: StateOrName): StateDeclaration;\n get(stateOrName: StateOrName): StateDeclaration;\n get(): StateDeclaration[];\n get(stateOrName?: StateOrName, base?: StateOrName): any {\n const reg = this.router.stateRegistry;\n if (arguments.length === 0) return reg.get();\n return reg.get(stateOrName, base || this.$current);\n }\n\n /**\n * Lazy loads a state\n *\n * Explicitly runs a state's [[StateDeclaration.lazyLoad]] function.\n *\n * @param stateOrName the state that should be lazy loaded\n * @param transition the optional Transition context to use (if the lazyLoad function requires an injector, etc)\n * Note: If no transition is provided, a noop transition is created using the from the current state to the current state.\n * This noop transition is not actually run.\n *\n * @returns a promise to lazy load\n */\n lazyLoad(stateOrName: StateOrName, transition?: Transition): Promise {\n const state: StateDeclaration = this.get(stateOrName);\n if (!state || !state.lazyLoad) throw new Error('Can not lazy load ' + stateOrName);\n\n const currentPath = this.getCurrentPath();\n const target = PathUtils.makeTargetState(this.router.stateRegistry, currentPath);\n transition = transition || this.router.transitionService.create(currentPath, target);\n\n return lazyLoadState(transition, state);\n }\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isArray, isObject, $QLike } from '../common/index';\n\n/**\n * An angular1-like promise api\n *\n * This object implements four methods similar to the\n * [angular 1 promise api](https://docs.angularjs.org/api/ng/service/$q)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This API provides native ES6 promise support wrapped as a $q-like API.\n * Internally, UI-Router uses this $q object to perform promise operations.\n * The `angular-ui-router` (ui-router for angular 1) uses the $q API provided by angular.\n *\n * $q-like promise api\n */\nexport const $q = {\n /** Normalizes a value as a promise */\n when: val => new Promise((resolve, reject) => resolve(val)),\n\n /** Normalizes a value as a promise rejection */\n reject: val =>\n new Promise((resolve, reject) => {\n reject(val);\n }),\n\n /** @returns a deferred object, which has `resolve` and `reject` functions */\n defer: () => {\n const deferred: any = {};\n deferred.promise = new Promise((resolve, reject) => {\n deferred.resolve = resolve;\n deferred.reject = reject;\n });\n return deferred;\n },\n\n /** Like Promise.all(), but also supports object key/promise notation like $q */\n all: (promises: { [key: string]: Promise } | Promise[]) => {\n if (isArray(promises)) {\n return Promise.all(promises);\n }\n\n if (isObject(promises)) {\n // Convert promises map to promises array.\n // When each promise resolves, map it to a tuple { key: key, val: val }\n const chain = Object.keys(promises).map(key => promises[key].then(val => ({ key, val })));\n\n // Then wait for all promises to resolve, and convert them back to an object\n return $q.all(chain).then(values =>\n values.reduce((acc, tuple) => {\n acc[tuple.key] = tuple.val;\n return acc;\n }, {}),\n );\n }\n },\n} as $QLike;\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n extend,\n assertPredicate,\n isFunction,\n isArray,\n isInjectable,\n $InjectorLike,\n IInjectable,\n} from '../common/index';\n\n// globally available injectables\nconst globals = {};\nconst STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/gm;\nconst ARGUMENT_NAMES = /([^\\s,]+)/g;\n\n/**\n * A basic angular1-like injector api\n *\n * This object implements four methods similar to the\n * [angular 1 dependency injector](https://docs.angularjs.org/api/auto/service/$injector)\n *\n * UI-Router evolved from an angular 1 library to a framework agnostic library.\n * However, some of the `@uirouter/core` code uses these ng1 style APIs to support ng1 style dependency injection.\n *\n * This object provides a naive implementation of a globally scoped dependency injection system.\n * It supports the following DI approaches:\n *\n * ### Function parameter names\n *\n * A function's `.toString()` is called, and the parameter names are parsed.\n * This only works when the parameter names aren't \"mangled\" by a minifier such as UglifyJS.\n *\n * ```js\n * function injectedFunction(FooService, BarService) {\n * // FooService and BarService are injected\n * }\n * ```\n *\n * ### Function annotation\n *\n * A function may be annotated with an array of dependency names as the `$inject` property.\n *\n * ```js\n * injectedFunction.$inject = [ 'FooService', 'BarService' ];\n * function injectedFunction(fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }\n * ```\n *\n * ### Array notation\n *\n * An array provides the names of the dependencies to inject (as strings).\n * The function is the last element of the array.\n *\n * ```js\n * [ 'FooService', 'BarService', function (fs, bs) {\n * // FooService and BarService are injected as fs and bs parameters\n * }]\n * ```\n *\n * @type {$InjectorLike}\n */\nexport const $injector = {\n /** Gets an object from DI based on a string token */\n get: name => globals[name],\n\n /** Returns true if an object named `name` exists in global DI */\n has: name => $injector.get(name) != null,\n\n /**\n * Injects a function\n *\n * @param fn the function to inject\n * @param context the function's `this` binding\n * @param locals An object with additional DI tokens and values, such as `{ someToken: { foo: 1 } }`\n */\n invoke: (fn: IInjectable, context?, locals?) => {\n const all = extend({}, globals, locals || {});\n const params = $injector.annotate(fn);\n const ensureExist = assertPredicate(\n (key: string) => all.hasOwnProperty(key),\n key => `DI can't find injectable: '${key}'`,\n );\n const args = params.filter(ensureExist).map(x => all[x]);\n if (isFunction(fn)) return fn.apply(context, args);\n else return (fn as any[]).slice(-1)[0].apply(context, args);\n },\n\n /**\n * Returns a function's dependencies\n *\n * Analyzes a function (or array) and returns an array of DI tokens that the function requires.\n * @return an array of `string`s\n */\n annotate: (fn: IInjectable): any[] => {\n if (!isInjectable(fn)) throw new Error(`Not an injectable function: ${fn}`);\n if (fn && (fn as any).$inject) return (fn as any).$inject;\n if (isArray(fn)) return fn.slice(0, -1);\n const fnStr = fn.toString().replace(STRIP_COMMENTS, '');\n const result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);\n return result || [];\n },\n} as $InjectorLike;\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport {\n LocationConfig,\n LocationServices,\n identity,\n unnestR,\n isArray,\n splitEqual,\n splitHash,\n splitQuery,\n} from '../common';\nimport { UIRouter } from '../router';\n\nexport const keyValsToObjectR = (accum, [key, val]) => {\n if (!accum.hasOwnProperty(key)) {\n accum[key] = val;\n } else if (isArray(accum[key])) {\n accum[key].push(val);\n } else {\n accum[key] = [accum[key], val];\n }\n return accum;\n};\n\nexport const getParams = (queryString: string): any =>\n queryString\n .split('&')\n .filter(identity)\n .map(splitEqual)\n .reduce(keyValsToObjectR, {});\n\nexport function parseUrl(url: string) {\n const orEmptyString = x => x || '';\n const [beforehash, hash] = splitHash(url).map(orEmptyString);\n const [path, search] = splitQuery(beforehash).map(orEmptyString);\n\n return { path, search, hash, url };\n}\n\nexport const buildUrl = (loc: LocationServices) => {\n const path = loc.path();\n const searchObject = loc.search();\n const hash = loc.hash();\n\n const search = Object.keys(searchObject)\n .map(key => {\n const param = searchObject[key];\n const vals = isArray(param) ? param : [param];\n return vals.map(val => key + '=' + val);\n })\n .reduce(unnestR, [])\n .join('&');\n\n return path + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n};\n\nexport function locationPluginFactory(\n name: string,\n isHtml5: boolean,\n serviceClass: { new (uiRouter?: UIRouter): LocationServices },\n configurationClass: { new (uiRouter?: UIRouter, isHtml5?: boolean): LocationConfig },\n) {\n return function(uiRouter: UIRouter) {\n const service = (uiRouter.locationService = new serviceClass(uiRouter));\n const configuration = (uiRouter.locationConfig = new configurationClass(uiRouter, isHtml5));\n\n function dispose(router: UIRouter) {\n router.dispose(service);\n router.dispose(configuration);\n }\n\n return { name, service, configuration, dispose };\n };\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */ /** */\n\nimport { deregAll, isDefined, LocationServices, removeFrom, root } from '../common';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { HistoryLike, LocationLike } from './interface';\nimport { buildUrl, getParams, parseUrl } from './utils';\n\n/** A base `LocationServices` */\nexport abstract class BaseLocationServices implements LocationServices, Disposable {\n private _listeners: Function[] = [];\n _location: LocationLike;\n _history: HistoryLike;\n\n _listener = evt => this._listeners.forEach(cb => cb(evt));\n\n constructor(router: UIRouter, public fireAfterUpdate: boolean) {\n this._location = root.location;\n this._history = root.history;\n }\n\n /**\n * This should return the current internal URL representation.\n *\n * The internal URL includes only the portion that UI-Router matches.\n * It does not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n */\n protected abstract _get(): string;\n\n /**\n * This should set the current URL.\n *\n * The `url` param should include only the portion that UI-Router matches on.\n * It should not include:\n * - protocol\n * - server\n * - port\n * - base href or hash\n *\n * However, after this function completes, the browser URL should reflect the entire (fully qualified)\n * HREF including those data.\n */\n protected abstract _set(state: any, title: string, url: string, replace: boolean);\n\n hash = () => parseUrl(this._get()).hash;\n path = () => parseUrl(this._get()).path;\n search = () => getParams(parseUrl(this._get()).search);\n\n url(url?: string, replace = true): string {\n if (isDefined(url) && url !== this._get()) {\n this._set(null, null, url, replace);\n\n if (this.fireAfterUpdate) {\n this._listeners.forEach(cb => cb({ url }));\n }\n }\n\n return buildUrl(this);\n }\n\n onChange(cb: EventListener) {\n this._listeners.push(cb);\n return () => removeFrom(this._listeners, cb);\n }\n\n dispose(router: UIRouter) {\n deregAll(this._listeners);\n }\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { root, trimHashVal } from '../common';\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\n\n/** A `LocationServices` that uses the browser hash \"#\" to get/set the current location */\nexport class HashLocationService extends BaseLocationServices {\n constructor(router: UIRouter) {\n super(router, false);\n root.addEventListener('hashchange', this._listener, false);\n }\n\n _get() {\n return trimHashVal(this._location.hash);\n }\n _set(state: any, title: string, url: string, replace: boolean) {\n this._location.hash = url;\n }\n\n dispose(router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('hashchange', this._listener);\n }\n}\n", "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { BaseLocationServices } from './baseLocationService';\nimport { UIRouter } from '../router';\n\n/** A `LocationServices` that gets/sets the current location from an in-memory object */\nexport class MemoryLocationService extends BaseLocationServices {\n _url: string;\n\n constructor(router: UIRouter) {\n super(router, true);\n }\n\n _get() {\n return this._url;\n }\n\n _set(state: any, title: string, url: string, replace: boolean) {\n this._url = url;\n }\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\nimport { LocationConfig, root, splitHash, splitQuery, stripLastPathElement } from '../common';\n\n/**\n * A `LocationServices` that gets/sets the current location using the browser's `location` and `history` apis\n *\n * Uses `history.pushState` and `history.replaceState`\n */\nexport class PushStateLocationService extends BaseLocationServices {\n _config: LocationConfig;\n\n constructor(router: UIRouter) {\n super(router, true);\n this._config = router.urlService.config;\n root.addEventListener('popstate', this._listener, false);\n }\n\n /**\n * Gets the base prefix without:\n * - trailing slash\n * - trailing filename\n * - protocol and hostname\n *\n * If , this returns '/base'.\n * If , this returns '/foo/base'.\n * If , this returns '/base'.\n * If , this returns '/base'.\n * If , this returns ''.\n * If , this returns ''.\n * If , this returns ''.\n *\n * See: https://html.spec.whatwg.org/dev/semantics.html#the-base-element\n */\n private _getBasePrefix() {\n return stripLastPathElement(this._config.baseHref());\n }\n\n protected _get() {\n let { pathname, hash, search } = this._location;\n search = splitQuery(search)[1]; // strip ? if found\n hash = splitHash(hash)[1]; // strip # if found\n\n const basePrefix = this._getBasePrefix();\n const exactBaseHrefMatch = pathname === this._config.baseHref();\n const startsWithBase = pathname.substr(0, basePrefix.length) === basePrefix;\n pathname = exactBaseHrefMatch ? '/' : startsWithBase ? pathname.substring(basePrefix.length) : pathname;\n\n return pathname + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n }\n\n protected _set(state: any, title: string, url: string, replace: boolean) {\n const basePrefix = this._getBasePrefix();\n const slash = url && url[0] !== '/' ? '/' : '';\n const fullUrl = (url === '' || url === '/') ? this._config.baseHref() : basePrefix + slash + url;\n\n if (replace) {\n this._history.replaceState(state, title, fullUrl);\n } else {\n this._history.pushState(state, title, fullUrl);\n }\n }\n\n public dispose(router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('popstate', this._listener);\n }\n}\n\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { LocationConfig } from '../common/coreservices';\nimport { isDefined } from '../common/predicates';\nimport { noop } from '../common/common';\n\n/** A `LocationConfig` mock that gets/sets all config from an in-memory object */\nexport class MemoryLocationConfig implements LocationConfig {\n dispose = noop;\n\n _baseHref = '';\n _port = 80;\n _protocol = 'http';\n _host = 'localhost';\n _hashPrefix = '';\n\n port = () => this._port;\n protocol = () => this._protocol;\n host = () => this._host;\n baseHref = () => this._baseHref;\n html5Mode = () => false;\n hashPrefix = (newval?) => isDefined(newval) ? this._hashPrefix = newval : this._hashPrefix;\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isDefined } from '../common/predicates';\nimport { LocationConfig } from '../common/coreservices';\n\n/** A `LocationConfig` that delegates to the browser's `location` object */\nexport class BrowserLocationConfig implements LocationConfig {\n private _baseHref = undefined;\n private _hashPrefix = '';\n\n constructor(router?, private _isHtml5 = false) { }\n\n port(): number {\n if (location.port) {\n return Number(location.port);\n }\n\n return this.protocol() === 'https' ? 443 : 80;\n }\n\n protocol(): string {\n return location.protocol.replace(/:/g, '');\n }\n\n host(): string {\n return location.hostname;\n }\n\n html5Mode(): boolean {\n return this._isHtml5;\n }\n\n hashPrefix(): string;\n hashPrefix(newprefix?: string): string {\n return isDefined(newprefix) ? this._hashPrefix = newprefix : this._hashPrefix;\n }\n\n baseHref(href?: string): string {\n return isDefined(href) ? this._baseHref = href :\n isDefined(this._baseHref) ? this._baseHref : this.applyDocumentBaseHref();\n }\n\n applyDocumentBaseHref() {\n const baseTag: HTMLBaseElement = document.getElementsByTagName('base')[0];\n return this._baseHref = baseTag ? baseTag.href.substr(location.origin.length) : location.pathname || '/';\n }\n\n dispose() {}\n}\n", - "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { BrowserLocationConfig } from './browserLocationConfig';\nimport { HashLocationService } from './hashLocationService';\nimport { locationPluginFactory } from './utils';\nimport { LocationPlugin, ServicesPlugin } from './interface';\nimport { UIRouter } from '../router';\nimport { PushStateLocationService } from './pushStateLocationService';\nimport { MemoryLocationService } from './memoryLocationService';\nimport { MemoryLocationConfig } from './memoryLocationConfig';\nimport { $injector } from './injector';\nimport { $q } from './q';\nimport { services } from '../common/coreservices';\n\nexport function servicesPlugin(router: UIRouter): ServicesPlugin {\n services.$injector = $injector;\n services.$q = $q;\n\n return { name: 'vanilla.services', $q, $injector, dispose: () => null };\n}\n\n/** A `UIRouterPlugin` uses the browser hash to get/set the current location */\nexport const hashLocationPlugin: (router: UIRouter) => LocationPlugin =\n locationPluginFactory('vanilla.hashBangLocation', false, HashLocationService, BrowserLocationConfig);\n\n/** A `UIRouterPlugin` that gets/sets the current location using the browser's `location` and `history` apis */\nexport const pushStateLocationPlugin: (router: UIRouter) => LocationPlugin =\n locationPluginFactory('vanilla.pushStateLocation', true, PushStateLocationService, BrowserLocationConfig);\n\n/** A `UIRouterPlugin` that gets/sets the current location from an in-memory object */\nexport const memoryLocationPlugin: (router: UIRouter) => LocationPlugin =\n locationPluginFactory('vanilla.memoryLocation', false, MemoryLocationService, MemoryLocationConfig);\n", - "/**\n * # Core classes and interfaces\n *\n * The classes and interfaces that are core to ui-router and do not belong\n * to a more specific subsystem (such as resolve).\n *\n * @coreapi\n * @preferred\n * @module core\n */ /** for typedoc */\n\n// Need to import or export at least one concrete something\nimport { noop } from './common/common';\nimport { UIRouter } from './router';\n\n/**\n * An interface for getting values from dependency injection.\n *\n * This is primarily used to get resolve values for a given token.\n * An instance of the `UIInjector` can be retrieved from the current transition using [[Transition.injector]].\n *\n * ---\n *\n * If no resolve is found for a token, then it will delegate to the native injector.\n * The native injector may be Angular 1 `$injector`, Angular 2 `Injector`, or a simple polyfill.\n *\n * In Angular 2, the native injector might be the root Injector,\n * or it might be a lazy loaded `NgModule` injector scoped to a lazy load state tree.\n */\nexport interface UIInjector {\n /**\n * Gets a value from the injector.\n *\n * For a given token, returns the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this throws an error.\n *\n * #### Example:\n * ```js\n * var myResolve = injector.get('myResolve');\n * ```\n *\n * #### ng1 Example:\n * ```js\n * // Fetch StateService\n * injector.get('$state').go('home');\n * ```\n *\n * #### ng2 Example:\n * ```js\n * import {StateService} from \"ui-router-ng2\";\n * // Fetch StateService\n * injector.get(StateService).go('home');\n * ```\n *\n * #### Typescript Example:\n * ```js\n * var stringArray = injector.get('myStringArray');\n * ```\n *\n * ### `NOWAIT` policy\n *\n * When using [[ResolvePolicy.async]] === `NOWAIT`, the value returned from `get()` is a promise for the result.\n * The promise is not automatically unwrapped.\n *\n * @param token the key for the value to get. May be a string, a class, or any arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n get(token: any): any;\n /** Gets a value as type `T` (generics parameter) */\n get(token: any): T;\n\n /**\n * Asynchronously gets a value from the injector\n *\n * For a given token, returns a promise for the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this triggers the resolve to load.\n *\n * #### Example:\n * ```js\n * return injector.getAsync('myResolve').then(value => {\n * if (value === 'declined') return false;\n * });\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return a Promise for the Dependency Injection value that matches the token\n */\n getAsync(token: any): Promise;\n /** Asynchronously gets a value as type `T` (generics parameter) */\n getAsync(token: any): Promise;\n\n /**\n * Gets a value from the native injector\n *\n * Returns a value from the native injector, bypassing anything in the [[ResolveContext]].\n *\n * Example:\n * ```js\n * let someThing = injector.getNative(SomeToken);\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n getNative(token: any): any;\n getNative(token: any): T;\n}\n\n/** @internalapi */\nexport interface UIRouterPlugin extends Disposable {\n name: string;\n}\n\n/** @internalapi */\nexport abstract class UIRouterPluginBase implements UIRouterPlugin, Disposable {\n abstract name: string;\n dispose(router: UIRouter) { }\n}\n\n/** @internalapi */\nexport interface Disposable {\n /** Instructs the Disposable to clean up any resources */\n dispose(router?: UIRouter);\n}\n", - "/** @module ng1 */ /** */\nimport { ng as angular } from '../angular';\nimport {\n StateObject, pick, forEach, tail, extend,\n isArray, isInjectable, isDefined, isString, services, trace,\n ViewConfig, ViewService, ViewConfigFactory, PathNode, ResolveContext, Resolvable, IInjectable,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration } from '../interface';\nimport { TemplateFactory } from '../templateFactory';\nimport IInjectorService = angular.auto.IInjectorService;\n\nexport function getNg1ViewConfigFactory(): ViewConfigFactory {\n let templateFactory: TemplateFactory = null;\n return (path, view) => {\n templateFactory = templateFactory || services.$injector.get('$templateFactory');\n return [new Ng1ViewConfig(path, view, templateFactory)];\n };\n}\n\nconst hasAnyKey = (keys, obj) =>\n keys.reduce((acc, key) => acc || isDefined(obj[key]), false);\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `views`.\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * handles the `views` property with logic specific to @uirouter/angularjs (ng1).\n *\n * If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object\n * and applies the state-level configuration to a view named `$default`.\n */\nexport function ng1ViewsBuilder(state: StateObject) {\n // Do not process root state\n if (!state.parent) return {};\n\n const tplKeys = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'],\n ctrlKeys = ['controller', 'controllerProvider', 'controllerAs', 'resolveAs'],\n compKeys = ['component', 'bindings', 'componentProvider'],\n nonCompKeys = tplKeys.concat(ctrlKeys),\n allViewKeys = compKeys.concat(nonCompKeys);\n\n // Do not allow a state to have both state-level props and also a `views: {}` property.\n // A state without a `views: {}` property can declare properties for the `$default` view as properties of the state.\n // However, the `$default` approach should not be mixed with a separate `views: ` block.\n if (isDefined(state.views) && hasAnyKey(allViewKeys, state)) {\n throw new Error(`State '${state.name}' has a 'views' object. ` +\n `It cannot also have \"view properties\" at the state level. ` +\n `Move the following properties into a view (in the 'views' object): ` +\n ` ${allViewKeys.filter(key => isDefined(state[key])).join(', ')}`);\n }\n\n const views: { [key: string]: Ng1ViewDeclaration } = {},\n viewsObject = state.views || { '$default': pick(state, allViewKeys) };\n\n forEach(viewsObject, function (config: Ng1ViewDeclaration, name: string) {\n // Account for views: { \"\": { template... } }\n name = name || '$default';\n // Account for views: { header: \"headerComponent\" }\n if (isString(config)) config = { component: config };\n\n // Make a shallow copy of the config object\n config = extend({}, config);\n\n // Do not allow a view to mix props for component-style view with props for template/controller-style view\n if (hasAnyKey(compKeys, config) && hasAnyKey(nonCompKeys, config)) {\n throw new Error(`Cannot combine: ${compKeys.join('|')} with: ${nonCompKeys.join('|')} in stateview: '${name}@${state.name}'`);\n }\n\n config.resolveAs = config.resolveAs || '$resolve';\n config.$type = 'ng1';\n config.$context = state;\n config.$name = name;\n\n const normalized = ViewService.normalizeUIViewTarget(config.$context, config.$name);\n config.$uiViewName = normalized.uiViewName;\n config.$uiViewContextAnchor = normalized.uiViewContextAnchor;\n\n views[name] = config;\n });\n return views;\n}\n\nlet id = 0;\nexport class Ng1ViewConfig implements ViewConfig {\n $id = id++;\n loaded = false;\n controller: Function; // actually IInjectable|string\n template: string;\n component: string;\n locals: any; // TODO: delete me\n\n constructor(public path: PathNode[], public viewDecl: Ng1ViewDeclaration, public factory: TemplateFactory) { }\n\n load() {\n const $q = services.$q;\n const context = new ResolveContext(this.path);\n const params = this.path.reduce((acc, node) => extend(acc, node.paramValues), {});\n\n const promises: any = {\n template: $q.when(this.factory.fromConfig(this.viewDecl, params, context)),\n controller: $q.when(this.getController(context)),\n };\n\n return $q.all(promises).then((results) => {\n trace.traceViewServiceEvent('Loaded', this);\n this.controller = results.controller;\n extend(this, results.template); // Either { template: \"tpl\" } or { component: \"cmpName\" }\n return this;\n });\n }\n\n getTemplate = (uiView, context: ResolveContext) =>\n this.component ? this.factory.makeComponentTemplate(uiView, context, this.component, this.viewDecl.bindings) : this.template;\n\n /**\n * Gets the controller for a view configuration.\n *\n * @returns {Function|Promise.} Returns a controller, or a promise that resolves to a controller.\n */\n getController(context: ResolveContext): (IInjectable|string|Promise) {\n const provider = this.viewDecl.controllerProvider;\n if (!isInjectable(provider)) return this.viewDecl.controller;\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail( provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n}\n", - "/** @module view */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport { IAugmentedJQuery } from 'angular';\nimport {\n isArray, isDefined, isFunction, isObject, services, Obj, IInjectable, tail, kebobString, unnestR, ResolveContext,\n Resolvable, RawParams,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration, TemplateFactoryProvider } from './interface';\n\n/**\n * Service which manages loading of templates from a ViewConfig.\n */\nexport class TemplateFactory implements TemplateFactoryProvider {\n /** @hidden */ private _useHttp = angular.version.minor < 3;\n /** @hidden */ private $templateRequest;\n /** @hidden */ private $templateCache;\n /** @hidden */ private $http;\n\n /** @hidden */ $get = ['$http', '$templateCache', '$injector', ($http, $templateCache, $injector) => {\n this.$templateRequest = $injector.has && $injector.has('$templateRequest') && $injector.get('$templateRequest');\n this.$http = $http;\n this.$templateCache = $templateCache;\n return this;\n }];\n\n /** @hidden */\n useHttpService(value: boolean) {\n this._useHttp = value;\n }\n\n /**\n * Creates a template from a configuration object.\n *\n * @param config Configuration object for which to load a template.\n * The following properties are search in the specified order, and the first one\n * that is defined is used to create the template:\n *\n * @param params Parameters to pass to the template function.\n * @param context The resolve context associated with the template's view\n *\n * @return {string|object} The template html as a string, or a promise for\n * that string,or `null` if no template is configured.\n */\n fromConfig(config: Ng1ViewDeclaration, params: any, context: ResolveContext): Promise<{ template?: string, component?: string }> {\n const defaultTemplate = '';\n\n const asTemplate = (result) => services.$q.when(result).then(str => ({ template: str }));\n const asComponent = (result) => services.$q.when(result).then(str => ({ component: str }));\n\n return (\n isDefined(config.template) ? asTemplate(this.fromString(config.template, params)) :\n isDefined(config.templateUrl) ? asTemplate(this.fromUrl(config.templateUrl, params)) :\n isDefined(config.templateProvider) ? asTemplate(this.fromProvider(config.templateProvider, params, context)) :\n isDefined(config.component) ? asComponent(config.component) :\n isDefined(config.componentProvider) ? asComponent(this.fromComponentProvider(config.componentProvider, params, context)) :\n asTemplate(defaultTemplate)\n );\n }\n\n /**\n * Creates a template from a string or a function returning a string.\n *\n * @param template html template as a string or function that returns an html template as a string.\n * @param params Parameters to pass to the template function.\n *\n * @return {string|object} The template html as a string, or a promise for that\n * string.\n */\n fromString(template: (string | Function), params?: RawParams) {\n return isFunction(template) ? ( template)(params) : template;\n }\n\n /**\n * Loads a template from the a URL via `$http` and `$templateCache`.\n *\n * @param {string|Function} url url of the template to load, or a function\n * that returns a url.\n * @param {Object} params Parameters to pass to the url function.\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromUrl(url: (string | Function), params: any) {\n if (isFunction(url)) url = ( url)(params);\n if (url == null) return null;\n\n if (this._useHttp) {\n return this.$http.get(url, { cache: this.$templateCache, headers: { Accept: 'text/html' } })\n .then(function (response) {\n return response.data;\n });\n }\n\n return this.$templateRequest(url);\n }\n\n /**\n * Creates a template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail( provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a component's template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string} The template html as a string: \"\".\n */\n fromComponentProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail( provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a template from a component's name\n *\n * This implements route-to-component.\n * It works by retrieving the component (directive) metadata from the injector.\n * It analyses the component's bindings, then constructs a template that instantiates the component.\n * The template wires input and output bindings to resolves or from the parent component.\n *\n * @param uiView {object} The parent ui-view (for binding outputs to callbacks)\n * @param context The ResolveContext (for binding outputs to callbacks returned from resolves)\n * @param component {string} Component's name in camel case.\n * @param bindings An object defining the component's bindings: {foo: '<'}\n * @return {string} The template as a string: \"\".\n */\n makeComponentTemplate(uiView: IAugmentedJQuery, context: ResolveContext, component: string, bindings?: any) {\n bindings = bindings || {};\n\n // Bind once prefix\n const prefix = angular.version.minor >= 3 ? '::' : '';\n // Convert to kebob name. Add x- prefix if the string starts with `x-` or `data-`\n const kebob = (camelCase: string) => {\n const kebobed = kebobString(camelCase);\n return /^(x|data)-/.exec(kebobed) ? `x-${kebobed}` : kebobed;\n };\n\n\n const attributeTpl = (input: BindingTuple) => {\n const { name, type } = input;\n const attrName = kebob(name);\n // If the ui-view has an attribute which matches a binding on the routed component\n // then pass that attribute through to the routed component template.\n // Prefer ui-view wired mappings to resolve data, unless the resolve was explicitly bound using `bindings:`\n if (uiView.attr(attrName) && !bindings[name])\n return `${attrName}='${uiView.attr(attrName)}'`;\n\n const resolveName = bindings[name] || name;\n // Pre-evaluate the expression for \"@\" bindings by enclosing in {{ }}\n // some-attr=\"{{ ::$resolve.someResolveName }}\"\n if (type === '@')\n return `${attrName}='{{${prefix}$resolve.${resolveName}}}'`;\n\n // Wire \"&\" callbacks to resolves that return a callback function\n // Get the result of the resolve (should be a function) and annotate it to get its arguments.\n // some-attr=\"$resolve.someResolveResultName(foo, bar)\"\n if (type === '&') {\n const res = context.getResolvable(resolveName);\n const fn = res && res.data;\n const args = fn && services.$injector.annotate(fn) || [];\n // account for array style injection, i.e., ['foo', function(foo) {}]\n const arrayIdxStr = isArray(fn) ? `[${fn.length - 1}]` : '';\n return `${attrName}='$resolve.${resolveName}${arrayIdxStr}(${args.join(',')})'`;\n }\n\n // some-attr=\"::$resolve.someResolveName\"\n return `${attrName}='${prefix}$resolve.${resolveName}'`;\n };\n\n const attrs = getComponentBindings(component).map(attributeTpl).join(' ');\n const kebobName = kebob(component);\n return `<${kebobName} ${attrs}>`;\n }\n}\n\n// Gets all the directive(s)' inputs ('@', '=', and '<') and outputs ('&')\nfunction getComponentBindings(name: string) {\n const cmpDefs = services.$injector.get(name + 'Directive'); // could be multiple\n if (!cmpDefs || !cmpDefs.length) throw new Error(`Unable to find component named '${name}'`);\n return cmpDefs.map(getBindings).reduce(unnestR, []);\n}\n\n// Given a directive definition, find its object input attributes\n// Use different properties, depending on the type of directive (component, bindToController, normal)\nconst getBindings = (def: any) => {\n if (isObject(def.bindToController)) return scopeBindings(def.bindToController);\n return scopeBindings(def.scope);\n};\n\ninterface BindingTuple {\n name: string;\n type: string;\n}\n\n// for ng 1.2 style, process the scope: { input: \"=foo\" }\n// for ng 1.3 through ng 1.5, process the component's bindToController: { input: \"=foo\" } object\nconst scopeBindings = (bindingsObj: Obj) => Object.keys(bindingsObj || {})\n // [ 'input', [ '=foo', '=', 'foo' ] ]\n .map(key => [key, /^([=<@&])[?]?(.*)/.exec(bindingsObj[key])])\n // skip malformed values\n .filter(tuple => isDefined(tuple) && isArray(tuple[1]))\n // { name: ('foo' || 'input'), type: '=' }\n .map(tuple => ({ name: tuple[1][2] || tuple[0], type: tuple[1][1] } as BindingTuple));\n\n", - "/** @module ng1 */ /** for typedoc */\nimport {\n val, isObject, createProxyFunctions, BuilderFunction, StateRegistry, StateService, OnInvalidCallback,\n} from '@uirouter/core';\nimport { Ng1StateDeclaration } from './interface';\n\n/**\n * The Angular 1 `StateProvider`\n *\n * The `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\nexport class StateProvider {\n constructor(private stateRegistry: StateRegistry, private stateService: StateService) {\n createProxyFunctions(val(StateProvider.prototype), this, val(this));\n }\n\n /**\n * Decorates states when they are registered\n *\n * Allows you to extend (carefully) or override (at your own peril) the\n * `stateBuilder` object used internally by [[StateRegistry]].\n * This can be used to add custom functionality to ui-router,\n * for example inferring templateUrl based on the state name.\n *\n * When passing only a name, it returns the current (original or decorated) builder\n * function that matches `name`.\n *\n * The builder functions that can be decorated are listed below. Though not all\n * necessarily have a good use case for decoration, that is up to you to decide.\n *\n * In addition, users can attach custom decorators, which will generate new\n * properties within the state's internal definition. There is currently no clear\n * use-case for this beyond accessing internal states (i.e. $state.$current),\n * however, expect this to become increasingly relevant as we introduce additional\n * meta-programming features.\n *\n * **Warning**: Decorators should not be interdependent because the order of\n * execution of the builder functions in non-deterministic. Builder functions\n * should only be dependent on the state definition object and super function.\n *\n *\n * Existing builder functions and current return values:\n *\n * - **parent** `{object}` - returns the parent state object.\n * - **data** `{object}` - returns state data, including any inherited data that is not\n * overridden by own values (if any).\n * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n * or `null`.\n * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is\n * navigable).\n * - **params** `{object}` - returns an array of state params that are ensured to\n * be a super-set of parent's params.\n * - **views** `{object}` - returns a views object where each key is an absolute view\n * name (i.e. \"viewName@stateName\") and each value is the config object\n * (template, controller) for the view. Even when you don't use the views object\n * explicitly on a state config, one is still created for you internally.\n * So by decorating this builder function you have access to decorating template\n * and controller properties.\n * - **ownParams** `{object}` - returns an array of params that belong to the state,\n * not including any params defined by ancestor states.\n * - **path** `{string}` - returns the full path from the root down to this state.\n * Needed for state activation.\n * - **includes** `{object}` - returns an object that includes every state that\n * would pass a `$state.includes()` test.\n *\n * #### Example:\n * Override the internal 'views' builder with a function that takes the state\n * definition, and a reference to the internal function being overridden:\n * ```js\n * $stateProvider.decorator('views', function (state, parent) {\n * let result = {},\n * views = parent(state);\n *\n * angular.forEach(views, function (config, name) {\n * let autoName = (state.name + '.' + name).replace('.', '/');\n * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n * result[name] = config;\n * });\n * return result;\n * });\n *\n * $stateProvider.state('home', {\n * views: {\n * 'contact.list': { controller: 'ListController' },\n * 'contact.item': { controller: 'ItemController' }\n * }\n * });\n * ```\n *\n *\n * ```js\n * // Auto-populates list and item views with /partials/home/contact/list.html,\n * // and /partials/home/contact/item.html, respectively.\n * $state.go('home');\n * ```\n *\n * @param {string} name The name of the builder function to decorate.\n * @param {object} func A function that is responsible for decorating the original\n * builder function. The function receives two parameters:\n *\n * - `{object}` - state - The state config object.\n * - `{object}` - super - The original builder function.\n *\n * @return {object} $stateProvider - $stateProvider instance\n */\n decorator(name: string, func: BuilderFunction) {\n return this.stateRegistry.decorator(name, func) || this;\n }\n\n /**\n * Registers a state\n *\n * ### This is a passthrough to [[StateRegistry.register]].\n *\n * Registers a state configuration under a given state name.\n * The stateConfig object has the following acceptable properties.\n *\n *
    \n *\n * - **`template`** - {string|function=} - html template as a string or a function that returns\n * an html template as a string which should be used by the uiView directives. This property\n * takes precedence over templateUrl.\n *\n * If `template` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateUrl`** - {string|function=} - path or function that returns a path to an html\n * template that should be used by uiView.\n *\n * If `templateUrl` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateProvider`** - {function=} - Provider function that returns HTML content\n * string.\n *\n * \n *\n * - **`controller`** - {string|function=} - Controller fn that should be associated with newly\n * related scope or the name of a registered controller if passed as a string.\n *\n * \n *\n * - **`controllerProvider`** - {function=} - Injectable provider function that returns\n * the actual controller or string.\n *\n * \n *\n * - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be\n * published to scope under the controllerAs name.\n *\n * \n *\n * - **`resolve`** - {object.<string, function>=} - An optional map of dependencies which\n * should be injected into the controller. If any of these dependencies are promises,\n * the router will wait for them all to be resolved or one to be rejected before the\n * controller is instantiated. If all the promises are resolved successfully, the values\n * of the resolved promises are injected and $stateChangeSuccess event is fired. If any\n * of the promises are rejected the $stateChangeError event is fired. The map object is:\n *\n * - key - {string}: name of dependency to be injected into controller\n * - factory - {string|function}: If string then it is alias for service. Otherwise if function,\n * it is injected and return value it treated as dependency. If result is a promise, it is\n * resolved before its value is injected into controller.\n *\n * \n *\n * - **`url`** - {string=} - A url with optional parameters. When a state is navigated or\n * transitioned to, the `$stateParams` service will be populated with any\n * parameters that were passed.\n *\n * \n *\n * - **`params`** - {object=} - An array of parameter names or regular expressions. Only\n * use this within a state if you are not using url. Otherwise you can specify your\n * parameters within the url. When a state is navigated or transitioned to, the\n * $stateParams service will be populated with any parameters that were passed.\n *\n * \n *\n * - **`views`** - {object=} - Use the views property to set up multiple views or to target views\n * manually/explicitly.\n *\n * \n *\n * - **`abstract`** - {boolean=} - An abstract state will never be directly activated,\n * but can provide inherited properties to its common children states.\n *\n * \n *\n * - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way\n * to trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to\n * trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state\n * just because a search/query parameter has changed (via $location.search() or $location.hash()).\n * Useful for when you'd like to modify $location.search() without triggering a reload.\n *\n * \n *\n * - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.\n *\n * #### Example:\n * Some state name examples\n * ```js\n * // stateName can be a single top-level name (must be unique).\n * $stateProvider.state(\"home\", {});\n *\n * // Or it can be a nested state name. This state is a child of the\n * // above \"home\" state.\n * $stateProvider.state(\"home.newest\", {});\n *\n * // Nest states as deeply as needed.\n * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n *\n * // state() returns $stateProvider, so you can chain state declarations.\n * $stateProvider\n * .state(\"home\", {})\n * .state(\"about\", {})\n * .state(\"contacts\", {});\n * ```\n *\n * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n * @param {object} definition State configuration object.\n */\n state(name: string, definition: Ng1StateDeclaration): StateProvider;\n state(definition: Ng1StateDeclaration): StateProvider;\n state(name: any, definition?: any) {\n if (isObject(name)) {\n definition = name;\n } else {\n definition.name = name;\n }\n this.stateRegistry.register(definition);\n return this;\n }\n\n /**\n * Registers an invalid state handler\n *\n * This is a passthrough to [[StateService.onInvalid]] for ng1.\n */\n\n onInvalid(callback: OnInvalidCallback): Function {\n return this.stateService.onInvalid(callback);\n }\n}\n", - "/** @module ng1 */ /** */\nimport {\n StateObject, TransitionStateHookFn, HookResult, Transition, services, ResolveContext, extend, BuilderFunction,\n} from '@uirouter/core';\nimport { getLocals } from '../services';\nimport { Ng1StateDeclaration } from '../interface';\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,\n * `onRetain` callback hooks on a [[Ng1StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * ensures that those hooks are injectable for @uirouter/angularjs (ng1).\n */\nexport const getStateHookBuilder = (hookName: 'onEnter'|'onExit'|'onRetain') =>\nfunction stateHookBuilder(stateObject: StateObject, parentFn: BuilderFunction): TransitionStateHookFn {\n const hook = stateObject[hookName];\n const pathname = hookName === 'onExit' ? 'from' : 'to';\n\n function decoratedNg1Hook(trans: Transition, state: Ng1StateDeclaration): HookResult {\n const resolveContext = new ResolveContext(trans.treeChanges(pathname));\n const subContext = resolveContext.subContext(state.$$state());\n const locals = extend(getLocals(subContext), { $state$: state, $transition$: trans });\n return services.$injector.invoke(hook, this, locals);\n }\n\n return hook ? decoratedNg1Hook : undefined;\n};\n", - "/**\n * @internalapi\n * @module ng1\n */ /** */\nimport { LocationConfig, LocationServices, UIRouter, ParamType, isDefined } from '@uirouter/core';\nimport { val, createProxyFunctions, removeFrom, isObject } from '@uirouter/core';\nimport { ILocationService, ILocationProvider } from 'angular';\n\n/**\n * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service\n */\nexport class Ng1LocationServices implements LocationConfig, LocationServices {\n private $locationProvider: ILocationProvider;\n private $location: ILocationService;\n private $sniffer;\n\n path;\n search;\n hash;\n hashPrefix;\n port;\n protocol;\n host;\n baseHref;\n\n // .onChange() registry\n private _urlListeners: Function[] = [];\n\n /**\n * Applys ng1-specific path parameter encoding\n *\n * The Angular 1 `$location` service is a bit weird.\n * It doesn't allow slashes to be encoded/decoded bi-directionally.\n *\n * See the writeup at https://github.com/angular-ui/ui-router/issues/2598\n *\n * This code patches the `path` parameter type so it encoded/decodes slashes as ~2F\n *\n * @param router\n */\n static monkeyPatchPathParameterType(router: UIRouter) {\n const pathType: ParamType = router.urlMatcherFactory.type('path');\n\n pathType.encode = (x: any) =>\n x != null ? x.toString().replace(/(~|\\/)/g, m => ({ '~': '~~', '/': '~2F' }[m])) : x;\n\n pathType.decode = (x: string) =>\n x != null ? x.toString().replace(/(~~|~2F)/g, m => ({ '~~': '~', '~2F': '/' }[m])) : x;\n\n }\n\n dispose() { }\n\n constructor($locationProvider: ILocationProvider) {\n this.$locationProvider = $locationProvider;\n const _lp = val($locationProvider);\n createProxyFunctions(_lp, this, _lp, ['hashPrefix']);\n }\n\n onChange(callback: Function) {\n this._urlListeners.push(callback);\n return () => removeFrom(this._urlListeners)(callback);\n }\n\n html5Mode() {\n let html5Mode: any = this.$locationProvider.html5Mode();\n html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode;\n return html5Mode && this.$sniffer.history;\n }\n\n url(newUrl?: string, replace = false, state?) {\n if (isDefined(newUrl)) this.$location.url(newUrl);\n if (replace) this.$location.replace();\n if (state) this.$location.state(state);\n return this.$location.url();\n }\n\n _runtimeServices($rootScope, $location: ILocationService, $sniffer, $browser) {\n this.$location = $location;\n this.$sniffer = $sniffer;\n\n // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange\n $rootScope.$on('$locationChangeSuccess', evt => this._urlListeners.forEach(fn => fn(evt)));\n const _loc = val($location);\n const _browser = val($browser);\n\n // Bind these LocationService functions to $location\n createProxyFunctions(_loc, this, _loc, ['replace', 'path', 'search', 'hash']);\n // Bind these LocationConfig functions to $location\n createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);\n // Bind these LocationConfig functions to $browser\n createProxyFunctions(_browser, this, _browser, ['baseHref']);\n }\n}\n", - "/** @module url */ /** */\nimport {\n UIRouter, UrlRouter, LocationServices, $InjectorLike, BaseUrlRule, UrlRuleHandlerFn, UrlMatcher,\n IInjectable,\n} from '@uirouter/core';\nimport { services, isString, isFunction, isArray, identity } from '@uirouter/core';\n\nexport interface RawNg1RuleFunction {\n ($injector: $InjectorLike, $location: LocationServices): string|void;\n}\n\n/**\n * Manages rules for client-side URL\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class manages the router rules for what to do when the URL changes.\n *\n * This provider remains for backwards compatibility.\n *\n * @deprecated\n */\nexport class UrlRouterProvider {\n /** @hidden */ _router: UIRouter;\n /** @hidden */ _urlRouter: UrlRouter;\n\n static injectableHandler(router: UIRouter, handler): UrlRuleHandlerFn {\n return match =>\n services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params });\n }\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this._urlRouter = router.urlRouter;\n }\n\n /** @hidden */\n $get() {\n const urlRouter = this._urlRouter;\n urlRouter.update(true);\n if (!urlRouter.interceptDeferred) urlRouter.listen();\n return urlRouter;\n }\n\n /**\n * Registers a url handler function.\n *\n * Registers a low level url handler (a `rule`).\n * A rule detects specific URL patterns and returns a redirect, or performs some action.\n *\n * If a rule returns a string, the URL is replaced with the string, and all rules are fired again.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Here's an example of how you might allow case insensitive urls\n * $urlRouterProvider.rule(function ($injector, $location) {\n * var path = $location.path(),\n * normalized = path.toLowerCase();\n *\n * if (path !== normalized) {\n * return normalized;\n * }\n * });\n * });\n * ```\n *\n * @param ruleFn\n * Handler function that takes `$injector` and `$location` services as arguments.\n * You can use them to detect a url and return a different url as a string.\n *\n * @return [[UrlRouterProvider]] (`this`)\n */\n rule(ruleFn: RawNg1RuleFunction): UrlRouterProvider {\n if (!isFunction(ruleFn)) throw new Error(\"'rule' must be a function\");\n\n const match = () =>\n ruleFn(services.$injector, this._router.locationService);\n\n const rule = new BaseUrlRule(match, identity);\n this._urlRouter.rule(rule);\n return this;\n }\n\n /**\n * Defines the path or behavior to use when no url can be matched.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // if the path doesn't match any of the urls you configured\n * // otherwise will take care of routing the user to the\n * // specified url\n * $urlRouterProvider.otherwise('/index');\n *\n * // Example of using function rule as param\n * $urlRouterProvider.otherwise(function ($injector, $location) {\n * return '/a/valid/url';\n * });\n * });\n * ```\n *\n * @param rule\n * The url path you want to redirect to or a function rule that returns the url path or performs a `$state.go()`.\n * The function version is passed two params: `$injector` and `$location` services, and should return a url string.\n *\n * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n */\n otherwise(rule: string | RawNg1RuleFunction): UrlRouterProvider {\n const urlRouter = this._urlRouter;\n\n if (isString(rule)) {\n urlRouter.otherwise(rule);\n } else if (isFunction(rule)) {\n urlRouter.otherwise(() => rule(services.$injector, this._router.locationService));\n } else {\n throw new Error(\"'rule' must be a string or function\");\n }\n\n return this;\n }\n\n /**\n * Registers a handler for a given url matching.\n *\n * If the handler is a string, it is\n * treated as a redirect, and is interpolated according to the syntax of match\n * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n *\n * If the handler is a function, it is injectable.\n * It gets invoked if `$location` matches.\n * You have the option of inject the match object as `$match`.\n *\n * The handler can return\n *\n * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n * will continue trying to find another one that matches.\n * - **string** which is treated as a redirect and passed to `$location.url()`\n * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n * if ($state.$current.navigable !== state ||\n * !equalForKeys($match, $stateParams) {\n * $state.transitionTo(state, $match, false);\n * }\n * });\n * });\n * ```\n *\n * @param what A pattern string to match, compiled as a [[UrlMatcher]].\n * @param handler The path (or function that returns a path) that you want to redirect your user to.\n * @param ruleCallback [optional] A callback that receives the `rule` registered with [[UrlMatcher.rule]]\n *\n * Note: the handler may also invoke arbitrary code, such as `$state.go()`\n */\n when(what: (RegExp|UrlMatcher|string), handler: string|IInjectable) {\n if (isArray(handler) || isFunction(handler)) {\n handler = UrlRouterProvider.injectableHandler(this._router, handler);\n }\n\n this._urlRouter.when(what, handler as any);\n return this;\n }\n\n /**\n * Disables monitoring of the URL.\n *\n * Call this method before UI-Router has bootstrapped.\n * It will stop UI-Router from performing the initial url sync.\n *\n * This can be useful to perform some asynchronous initialization before the router starts.\n * Once the initialization is complete, call [[listen]] to tell UI-Router to start watching and synchronizing the URL.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Prevent $urlRouter from automatically intercepting URL changes;\n * $urlRouterProvider.deferIntercept();\n * })\n *\n * app.run(function (MyService, $urlRouter, $http) {\n * $http.get(\"/stuff\").then(function(resp) {\n * MyService.doStuff(resp.data);\n * $urlRouter.listen();\n * $urlRouter.sync();\n * });\n * });\n * ```\n *\n * @param defer Indicates whether to defer location change interception.\n * Passing no parameter is equivalent to `true`.\n */\n deferIntercept(defer?: boolean) {\n this._urlRouter.deferIntercept(defer);\n }\n}\n", - "/**\n * # Angular 1 types\n *\n * UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc.\n * The customizations to the core types for Angular UI-Router are documented here.\n *\n * The optional [[$resolve]] service is also documented here.\n *\n * @module ng1\n * @preferred\n */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport {\n IRootScopeService, IQService, ILocationService, ILocationProvider, IHttpService, ITemplateCacheService,\n} from 'angular';\nimport {\n services, applyPairs, isString, trace, extend, UIRouter, StateService, UrlRouter, UrlMatcherFactory, ResolveContext,\n unnestR, TypedMap,\n} from '@uirouter/core';\nimport { ng1ViewsBuilder, getNg1ViewConfigFactory } from './statebuilders/views';\nimport { TemplateFactory } from './templateFactory';\nimport { StateProvider } from './stateProvider';\nimport { getStateHookBuilder } from './statebuilders/onEnterExitRetain';\nimport { Ng1LocationServices } from './locationServices';\nimport { UrlRouterProvider } from './urlRouterProvider';\nimport IInjectorService = angular.auto.IInjectorService; // tslint:disable-line\n\nangular.module('ui.router.angular1', []);\nconst mod_init = angular.module('ui.router.init', []);\nconst mod_util = angular.module('ui.router.util', ['ng', 'ui.router.init']);\nconst mod_rtr = angular.module('ui.router.router', ['ui.router.util']);\nconst mod_state = angular.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']);\nconst mod_main = angular.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']);\nlet mod_cmpt = angular.module('ui.router.compat', ['ui.router']); // tslint:disable-line\n\ndeclare module '@uirouter/core/lib/router' {\n interface UIRouter { // tslint:disable-line:no-shadowed-variable\n /** @hidden */\n stateProvider: StateProvider;\n /** @hidden */\n urlRouterProvider: UrlRouterProvider;\n }\n}\n\nlet router: UIRouter = null;\n\n$uiRouterProvider.$inject = ['$locationProvider'];\n/** This angular 1 provider instantiates a Router and exposes its services via the angular injector */\nfunction $uiRouterProvider($locationProvider: ILocationProvider) {\n\n // Create a new instance of the Router when the $uiRouterProvider is initialized\n router = this.router = new UIRouter();\n router.stateProvider = new StateProvider(router.stateRegistry, router.stateService);\n\n // Apply ng1 specific StateBuilder code for `views`, `resolve`, and `onExit/Retain/Enter` properties\n router.stateRegistry.decorator('views', ng1ViewsBuilder);\n router.stateRegistry.decorator('onExit', getStateHookBuilder('onExit'));\n router.stateRegistry.decorator('onRetain', getStateHookBuilder('onRetain'));\n router.stateRegistry.decorator('onEnter', getStateHookBuilder('onEnter'));\n\n router.viewService._pluginapi._viewConfigFactory('ng1', getNg1ViewConfigFactory());\n\n const ng1LocationService = router.locationService = router.locationConfig = new Ng1LocationServices($locationProvider);\n\n Ng1LocationServices.monkeyPatchPathParameterType(router);\n\n // backwards compat: also expose router instance as $uiRouterProvider.router\n router['router'] = router;\n router['$get'] = $get;\n $get.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache'];\n function $get($location: ILocationService, $browser: any, $sniffer: any, $rootScope: ng.IScope, $http: IHttpService, $templateCache: ITemplateCacheService) {\n ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser);\n delete router['router'];\n delete router['$get'];\n return router;\n }\n return router;\n}\n\nconst getProviderFor = (serviceName) => [ '$uiRouterProvider', ($urp) => {\n const service = $urp.router[serviceName];\n service['$get'] = () => service;\n return service;\n}];\n\n// This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime)\nrunBlock.$inject = ['$injector', '$q', '$uiRouter'];\nfunction runBlock($injector: IInjectorService, $q: IQService, $uiRouter: UIRouter) {\n services.$injector = $injector;\n services.$q = $q;\n\n // The $injector is now available.\n // Find any resolvables that had dependency annotation deferred\n $uiRouter.stateRegistry.get()\n .map(x => x.$$state().resolvables)\n .reduce(unnestR, [])\n .filter(x => x.deps === 'deferred')\n .forEach(resolvable => resolvable.deps = $injector.annotate(resolvable.resolveFn, $injector.strictDi));\n}\n\n// $urlRouter service and $urlRouterProvider\nconst getUrlRouterProvider = (uiRouter: UIRouter) =>\n uiRouter.urlRouterProvider = new UrlRouterProvider(uiRouter);\n\n// $state service and $stateProvider\n// $urlRouter service and $urlRouterProvider\nconst getStateProvider = () =>\n extend(router.stateProvider, { $get: () => router.stateService });\n\nwatchDigests.$inject = ['$rootScope'];\nexport function watchDigests($rootScope: IRootScopeService) {\n $rootScope.$watch(function() { trace.approximateDigests++; });\n}\n\nmod_init .provider('$uiRouter', $uiRouterProvider);\nmod_rtr .provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]);\nmod_util .provider('$urlService', getProviderFor('urlService'));\nmod_util .provider('$urlMatcherFactory', ['$uiRouterProvider', () => router.urlMatcherFactory]);\nmod_util .provider('$templateFactory', () => new TemplateFactory());\nmod_state.provider('$stateRegistry', getProviderFor('stateRegistry'));\nmod_state.provider('$uiRouterGlobals', getProviderFor('globals'));\nmod_state.provider('$transitions', getProviderFor('transitionService'));\nmod_state.provider('$state', ['$uiRouterProvider', getStateProvider]);\n\nmod_state.factory ('$stateParams', ['$uiRouter', ($uiRouter: UIRouter) => $uiRouter.globals.params]);\nmod_main .factory ('$view', () => router.viewService);\nmod_main .service ('$trace', () => trace);\n\nmod_main .run (watchDigests);\nmod_util .run (['$urlMatcherFactory', function ($urlMatcherFactory: UrlMatcherFactory) { }]);\nmod_state.run (['$state', function ($state: StateService) { }]);\nmod_rtr .run (['$urlRouter', function ($urlRouter: UrlRouter) { }]);\nmod_init .run (runBlock);\n\n/** @hidden TODO: find a place to move this */\nexport const getLocals = (ctx: ResolveContext): TypedMap => {\n const tokens = ctx.getTokens().filter(isString);\n\n const tuples = tokens .map(key => {\n const resolvable = ctx.getResolvable(key);\n const waitPolicy = ctx.getPolicy(resolvable).async;\n return [ key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data ];\n });\n\n return tuples.reduce(applyPairs, {});\n};\n\n", - "/**\n * # Angular 1 Directives\n *\n * These are the directives included in UI-Router for Angular 1.\n * These directives are used in templates to create viewports and link/navigate to states.\n *\n * @ng1api\n * @preferred\n * @module directives\n */ /** for typedoc */\nimport { ng as angular } from '../angular';\nimport { IAugmentedJQuery, ITimeoutService, IScope, IInterpolateService } from 'angular';\n\nimport {\n Obj, extend, forEach, tail, isString, isObject, isArray, parse, noop, unnestR, identity, uniqR, inArray, removeFrom,\n RawParams, PathNode, StateOrName, StateService, StateDeclaration, UIRouter,\n} from '@uirouter/core';\nimport { UIViewData } from './viewDirective';\nimport EventHandler = JQuery.EventHandler;\n\n/** @hidden Used for typedoc */\nexport interface ng1_directive {} // tslint:disable-line:class-name\n\n/** @hidden */\nfunction parseStateRef(ref: string) {\n let parsed;\n const paramsOnly = ref.match(/^\\s*({[^}]*})\\s*$/);\n if (paramsOnly) ref = '(' + paramsOnly[1] + ')';\n\n parsed = ref.replace(/\\n/g, ' ').match(/^\\s*([^(]*?)\\s*(\\((.*)\\))?\\s*$/);\n if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n return { state: parsed[1] || null, paramExpr: parsed[3] || null };\n}\n\n/** @hidden */\nfunction stateContext(el: IAugmentedJQuery) {\n const $uiView: UIViewData = (el.parent() as IAugmentedJQuery).inheritedData('$uiView');\n const path: PathNode[] = parse('$cfg.path')($uiView);\n return path ? tail(path).state.name : undefined;\n}\n\n/** @hidden */\nfunction processedDef($state: StateService, $element: IAugmentedJQuery, def: Def): Def {\n const uiState = def.uiState || $state.current.name;\n const uiStateOpts = extend(defaultOpts($element, $state), def.uiStateOpts || {});\n const href = $state.href(uiState, def.uiStateParams, uiStateOpts);\n return { uiState, uiStateParams: def.uiStateParams, uiStateOpts, href };\n}\n\n/** @hidden */\ninterface TypeInfo {\n attr: string;\n isAnchor: boolean;\n clickable: boolean;\n}\n\n/** @hidden */\nfunction getTypeInfo(el: IAugmentedJQuery): TypeInfo {\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n const isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';\n const isForm = el[0].nodeName === 'FORM';\n\n return {\n attr: isForm ? 'action' : (isSvg ? 'xlink:href' : 'href'),\n isAnchor: el.prop('tagName').toUpperCase() === 'A',\n clickable: !isForm,\n };\n}\n\n/** @hidden */\nfunction clickHook(el: IAugmentedJQuery, $state: StateService, $timeout: ITimeoutService, type: TypeInfo, getDef: () => Def) {\n return function (e: JQueryMouseEventObject) {\n const button = e.which || e.button, target = getDef();\n\n if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {\n // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n const transition = $timeout(function () {\n $state.go(target.uiState, target.uiStateParams, target.uiStateOpts);\n });\n e.preventDefault();\n\n // if the state has no URL, ignore one preventDefault from the directive.\n let ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;\n\n e.preventDefault = function () {\n if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);\n };\n }\n };\n}\n\n/** @hidden */\nfunction defaultOpts(el: IAugmentedJQuery, $state: StateService) {\n return {\n relative: stateContext(el) || $state.$current,\n inherit: true,\n source: 'sref',\n };\n}\n\n/** @hidden */\nfunction bindEvents(element: IAugmentedJQuery, scope: IScope, hookFn: EventHandler, uiStateOpts: any): void {\n let events;\n\n if (uiStateOpts) {\n events = uiStateOpts.events;\n }\n\n if (!isArray(events)) {\n events = ['click'];\n }\n\n const on = element.on ? 'on' : 'bind';\n for (const event of events) {\n element[on](event, hookFn);\n }\n\n scope.$on('$destroy', function() {\n const off = element.off ? 'off' : 'unbind';\n for (const event of events) {\n element[off](event, hookFn);\n }\n });\n}\n\n/**\n * `ui-sref`: A directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of the `ui-sref` is the name of the state to link to.\n *\n * #### Example:\n * This will activate the `home` state when the link is clicked.\n * ```html\n * Home\n * ```\n *\n * ### Relative Links\n * You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]).\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create a relative `ui-sref` which always targets the same destination.\n *\n * #### Example:\n * Both these links are relative to the parent state, even when a child state is currently active.\n * ```html\n * child 1 state\n * child 2 state\n * ```\n *\n * This link activates the parent state.\n * ```html\n * Return\n * ```\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * #### Example:\n * Assuming the `users` state has a url of `/users/`\n * ```html\n * Users\n * ```\n *\n * ### Parameter Values\n * In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state.\n * Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses.\n * The content inside the parentheses is an expression, evaluated to the parameter values.\n *\n * #### Example:\n * This example renders a list of links to users.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ user.displayName }}\n *
  • \n * ```\n *\n * Note:\n * The parameter values expression is `$watch`ed for updates.\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-sref-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Examples\n * If you have the following template:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n * \n * ```\n *\n * Then (assuming the current state is `contacts`) the rendered html including hrefs would be:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n *
      \n *
    • \n * Joe\n *
    • \n *
    • \n * Alice\n *
    • \n *
    • \n * Bob\n *
    • \n *
    \n *\n * Home\n * ```\n *\n * ### Notes\n *\n * - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses.\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n *\n * - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons).\n * If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive.\n */\nlet uiSrefDirective: ng1_directive;\nuiSrefDirective = ['$uiRouter', '$timeout',\n function $StateRefDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function (scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const ref = parseStateRef(attrs.uiSref);\n rawDef.uiState = ref.state;\n rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {};\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n if (ref.paramExpr) {\n scope.$watch(ref.paramExpr, function (val) {\n rawDef.uiStateParams = extend({}, val);\n update();\n }, true);\n rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr));\n }\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n }];\n\n/**\n * `ui-state`: A fully dynamic directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.**\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to.\n * **This is in contrast with `ui-sref`, which takes a state name as a string literal.**\n *\n * #### Example:\n * Create a list of links.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Relative Links\n * If the expression evaluates to a relative path, it is processed like [[uiSref]].\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create relative `ui-state` which always targets the same destination.\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * ### Parameter Values\n * In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state.\n * Param values should be provided using the `ui-state-params` attribute.\n * The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * This example renders a list of links with param values.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n * The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-state-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Notes\n *\n * - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`.\n * However, it might be simpler to use [[uiSref]] parameter-only links.\n *\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n * ```\n */\nlet uiStateDirective: ng1_directive;\nuiStateDirective = ['$uiRouter', '$timeout',\n function $StateRefDynamicDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function (scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts'];\n const watchDeregFns = inputAttrs.reduce((acc, attr) => (acc[attr] = noop, acc), {});\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n inputAttrs.forEach((field) => {\n rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null;\n\n attrs.$observe(field, (expr) => {\n watchDeregFns[field]();\n watchDeregFns[field] = scope.$watch(expr, (newval) => {\n rawDef[field] = newval;\n update();\n }, true);\n });\n });\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n }];\n\n\n/**\n * `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active\n *\n * A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the\n * related directive's state is active (and remove them when it is inactive).\n *\n * The primary use-case is to highlight the active link in navigation menus,\n * distinguishing it from the inactive menu items.\n *\n * ### Linking to a `ui-sref` or `ui-state`\n * `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element.\n * If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**.\n *\n * ### Matching\n *\n * The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**.\n * This is a \"fuzzy match\" which uses [[StateService.includes]].\n *\n * The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active).\n * This is an \"exact match\" which uses [[StateService.is]].\n *\n * ### Parameter values\n * If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted.\n * This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted.\n *\n * #### Example:\n * ```html\n *
  • \n * {{ user.lastName }}\n *
  • \n * ```\n *\n * ### Examples\n *\n * Given the following template:\n * #### Example:\n * ```html\n * \n * ```\n *\n * When the app state is `app.user` (or any child state),\n * and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n *\n * ```html\n * \n * ```\n *\n * ### Glob mode\n *\n * It is possible to pass `ui-sref-active` an expression that evaluates to an object.\n * The objects keys represent active class names and values represent the respective state names/globs.\n * `ui-sref-active` will match if the current active state **includes** any of\n * the specified state names/globs, even the abstract ones.\n *\n * #### Example:\n * Given the following template, with \"admin\" being an abstract state:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * Arrays are also supported as values in the `ngClass`-like interface.\n * This allows multiple states to add `active` class.\n *\n * #### Example:\n * Given the following template, with \"admin.roles\" being the current state, the class will be added too:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * When the current state is \"admin.roles\" the \"active\" class will be applied to both the `
    ` and `` elements.\n * It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`.\n *\n * ### Notes:\n *\n * - The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'`\n */\nlet uiSrefActiveDirective: ng1_directive;\nuiSrefActiveDirective = ['$state', '$stateParams', '$interpolate', '$uiRouter',\n function $StateRefActiveDirective($state: StateService, $stateParams: Obj, $interpolate: IInterpolateService, $uiRouter: UIRouter) {\n return {\n restrict: 'A',\n controller: ['$scope', '$element', '$attrs',\n function ($scope: IScope, $element: IAugmentedJQuery, $attrs: any) {\n let states: StateData[] = [];\n let activeEqClass: string;\n let uiSrefActive: any;\n\n // There probably isn't much point in $observing this\n // uiSrefActive and uiSrefActiveEq share the same directive object with some\n // slight difference in logic routing\n activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);\n\n try {\n uiSrefActive = $scope.$eval($attrs.uiSrefActive);\n } catch (e) {\n // Do nothing. uiSrefActive is not a valid expression.\n // Fall back to using $interpolate below\n }\n uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);\n setStatesFromDefinitionObject(uiSrefActive);\n\n // Allow uiSref to communicate with uiSrefActive[Equals]\n this.$$addStateInfo = function (newState: string, newParams: Obj) {\n // we already got an explicit state provided by ui-sref-active, so we\n // shadow the one that comes from ui-sref\n if (isObject(uiSrefActive) && states.length > 0) {\n return;\n }\n const deregister = addState(newState, newParams, uiSrefActive);\n update();\n return deregister;\n };\n\n function updateAfterTransition(trans) {\n trans.promise.then(update, noop);\n }\n $scope.$on('$destroy', setupEventListeners());\n if ($uiRouter.globals.transition) {\n updateAfterTransition($uiRouter.globals.transition);\n }\n\n function setupEventListeners () {\n const deregisterStatesChangedListener = $uiRouter.stateRegistry.onStatesChanged(handleStatesChanged);\n const deregisterOnStartListener = $uiRouter.transitionService.onStart({}, updateAfterTransition);\n const deregisterStateChangeSuccessListener = $scope.$on('$stateChangeSuccess', update);\n return function cleanUp () {\n deregisterStatesChangedListener();\n deregisterOnStartListener();\n deregisterStateChangeSuccessListener();\n };\n }\n\n function handleStatesChanged () {\n setStatesFromDefinitionObject(uiSrefActive);\n }\n\n function setStatesFromDefinitionObject (statesDefinition: object) {\n if (isObject(statesDefinition)) {\n states = [];\n forEach(statesDefinition, function (stateOrName: StateOrName | Array, activeClass: string) {\n // Helper function to abstract adding state.\n const addStateForClass = function (stateOrName: string, activeClass: string) {\n const ref = parseStateRef(stateOrName);\n addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);\n };\n\n if (isString(stateOrName)) {\n // If state is string, just add it.\n addStateForClass(stateOrName as string, activeClass)\n } else if (isArray(stateOrName)) {\n // If state is an array, iterate over it and add each array item individually.\n forEach(stateOrName, function (stateOrName: string) {\n addStateForClass(stateOrName, activeClass)\n });\n }\n });\n }\n }\n\n function addState(stateName: string, stateParams: Obj, activeClass: string) {\n const state = $state.get(stateName, stateContext($element));\n\n const stateInfo = {\n state: state || { name: stateName },\n params: stateParams,\n activeClass: activeClass,\n };\n\n states.push(stateInfo);\n\n return function removeState() {\n removeFrom(states)(stateInfo);\n };\n }\n\n // Update route state\n function update() {\n const splitClasses = str =>\n str.split(/\\s/).filter(identity);\n const getClasses = (stateList: StateData[]) =>\n stateList.map(x => x.activeClass).map(splitClasses).reduce(unnestR, []);\n\n const allClasses = getClasses(states).concat(splitClasses(activeEqClass)).reduce(uniqR, []);\n const fuzzyClasses = getClasses(states.filter(x => $state.includes(x.state.name, x.params)));\n const exactlyMatchesAny = !!states.filter(x => $state.is(x.state.name, x.params)).length;\n const exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : [];\n\n const addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []);\n const removeClasses = allClasses.filter(cls => !inArray(addClasses, cls));\n\n $scope.$evalAsync(() => {\n addClasses.forEach(className => $element.addClass(className));\n removeClasses.forEach(className => $element.removeClass(className));\n });\n }\n\n update();\n }],\n };\n }];\n\n/** @hidden */\ninterface Def { uiState: string; href: string; uiStateParams: Obj; uiStateOpts: any; }\n/** @hidden */\ninterface StateData { state: StateDeclaration; params: RawParams; activeClass: string; }\n\nangular.module('ui.router.state')\n .directive('uiSref', uiSrefDirective)\n .directive('uiSrefActive', uiSrefActiveDirective)\n .directive('uiSrefActiveEq', uiSrefActiveDirective)\n .directive('uiState', uiStateDirective);\n", - "/**\n * @ng1api\n * @module directives\n */ /** for typedoc */\nimport { ng as angular } from '../angular';\nimport { IInterpolateService, IScope, ITranscludeFunction, IAugmentedJQuery, ITimeoutService } from 'angular';\n\nimport {\n extend, unnestR, filter, tail, isDefined, isFunction, isString, trace, parse,\n ActiveUIView, TransitionService, ResolveContext, Transition, PathNode, StateDeclaration,\n Param, kebobString, HookRegOptions, ViewService, $QLike, Obj, TypedMap, noop,\n} from '@uirouter/core';\nimport { Ng1ViewConfig } from '../statebuilders/views';\nimport { Ng1Controller, Ng1StateDeclaration } from '../interface';\nimport { getLocals } from '../services';\nimport { ng1_directive } from './stateDirectives';\n\n/** @hidden */\nexport type UIViewData = {\n $cfg: Ng1ViewConfig;\n $uiView: ActiveUIView;\n};\n\n/** @hidden */\nexport type UIViewAnimData = {\n $animEnter: Promise;\n $animLeave: Promise;\n $$animLeave: { resolve: () => any; } // \"deferred\"\n};\n\n/**\n * `ui-view`: A viewport directive which is filled in by a view from the active state.\n *\n * ### Attributes\n *\n * - `name`: (Optional) A view name.\n * The name should be unique amongst the other views in the same state.\n * You can have views of the same name that live in different states.\n * The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]).\n *\n * - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated.\n * Uses [[$uiViewScroll]] to do the scrolling.\n *\n * - `onload`: Expression to evaluate whenever the view updates.\n *\n * #### Example:\n * A view can be unnamed or named.\n * ```html\n * \n *
    \n *\n * \n *
    \n *\n * \n * \n * ```\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a\n * single view and it is unnamed then you can populate it like so:\n *\n * ```html\n *
    \n * $stateProvider.state(\"home\", {\n * template: \"

    HELLO!

    \"\n * })\n * ```\n *\n * The above is a convenient shortcut equivalent to specifying your view explicitly with the\n * [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name:\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * But typically you'll only use the views property if you name your view or have more than one view\n * in the same template. There's not really a compelling reason to name a view if its the only one,\n * but you could if you wanted, like so:\n *\n * ```html\n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"main\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * Really though, you'll use views to set up multiple views:\n *\n * ```html\n *
    \n *
    \n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * },\n * \"chart\": {\n * template: \"\"\n * },\n * \"data\": {\n * template: \"\"\n * }\n * }\n * })\n * ```\n *\n * #### Examples for `autoscroll`:\n * ```html\n * \n * \n *\n * \n * \n * \n * \n * ```\n *\n * Resolve data:\n *\n * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this\n * can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template.\n *\n * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the\n * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which\n * depends on `$resolve` data.\n *\n * #### Example:\n * ```js\n * $stateProvider.state('home', {\n * template: '',\n * resolve: {\n * user: function(UserService) { return UserService.fetchUser(); }\n * }\n * });\n * ```\n */\nexport let uiView: ng1_directive;\nuiView = ['$view', '$animate', '$uiViewScroll', '$interpolate', '$q',\nfunction $ViewDirective($view: ViewService, $animate: any, $uiViewScroll: any, $interpolate: IInterpolateService, $q: $QLike) {\n\n function getRenderer(attrs: Obj, scope: IScope) {\n return {\n enter: function(element: JQuery, target: any, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.enter(element, null, target).then(cb);\n } else {\n $animate.enter(element, null, target, cb);\n }\n },\n leave: function(element: JQuery, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.leave(element).then(cb);\n } else {\n $animate.leave(element, cb);\n }\n },\n };\n }\n\n function configsEqual(config1: Ng1ViewConfig, config2: Ng1ViewConfig) {\n return config1 === config2;\n }\n\n const rootData = {\n $cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } },\n $uiView: { },\n };\n\n const directive = {\n count: 0,\n restrict: 'ECA',\n terminal: true,\n priority: 400,\n transclude: 'element',\n compile: function (tElement: JQuery, tAttrs: Obj, $transclude: ITranscludeFunction) {\n\n return function (scope: IScope, $element: IAugmentedJQuery, attrs: Obj) {\n const onloadExp = attrs['onload'] || '',\n autoScrollExp = attrs['autoscroll'],\n renderer = getRenderer(attrs, scope),\n inherited = $element.inheritedData('$uiView') || rootData,\n name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default';\n\n let previousEl: JQuery,\n currentEl: JQuery,\n currentScope: IScope,\n viewConfig: Ng1ViewConfig,\n unregister: Function;\n\n const activeUIView: ActiveUIView = {\n $type: 'ng1',\n id: directive.count++, // Global sequential ID for ui-view tags added to DOM\n name: name, // ui-view name (
    \n fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + '.' + name : name, // fully qualified name, describes location in DOM\n config: null, // The ViewConfig loaded (from a state.views definition)\n configUpdated: configUpdatedCallback, // Called when the matching ViewConfig changes\n get creationContext() { // The context in which this ui-view \"tag\" was created\n const fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited);\n // Allow \n // See https://github.com/angular-ui/ui-router/issues/3355\n const fromParentTag = parse('$uiView.creationContext')(inherited);\n return fromParentTagConfig || fromParentTag;\n },\n };\n\n trace.traceUIViewEvent('Linking', activeUIView);\n\n function configUpdatedCallback(config?: Ng1ViewConfig) {\n if (config && !(config instanceof Ng1ViewConfig)) return;\n if (configsEqual(viewConfig, config)) return;\n trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context);\n\n viewConfig = config;\n updateView(config);\n }\n\n $element.data('$uiView', { $uiView: activeUIView });\n\n updateView();\n\n unregister = $view.registerUIView(activeUIView);\n scope.$on('$destroy', function() {\n trace.traceUIViewEvent('Destroying/Unregistering', activeUIView);\n unregister();\n });\n\n function cleanupLastView() {\n if (previousEl) {\n trace.traceUIViewEvent('Removing (previous) el', previousEl.data('$uiView'));\n previousEl.remove();\n previousEl = null;\n }\n\n if (currentScope) {\n trace.traceUIViewEvent('Destroying scope', activeUIView);\n currentScope.$destroy();\n currentScope = null;\n }\n\n if (currentEl) {\n const _viewData = currentEl.data('$uiViewAnim');\n trace.traceUIViewEvent('Animate out', _viewData);\n renderer.leave(currentEl, function() {\n _viewData.$$animLeave.resolve();\n previousEl = null;\n });\n\n previousEl = currentEl;\n currentEl = null;\n }\n }\n\n function updateView(config?: Ng1ViewConfig) {\n const newScope = scope.$new();\n const animEnter = $q.defer(), animLeave = $q.defer();\n\n const $uiViewData: UIViewData = {\n $cfg: config,\n $uiView: activeUIView,\n };\n\n const $uiViewAnim: UIViewAnimData = {\n $animEnter: animEnter.promise,\n $animLeave: animLeave.promise,\n $$animLeave: animLeave,\n };\n\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoading\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description\n *\n * Fired once the view **begins loading**, *before* the DOM is rendered.\n *\n * @param {Object} event Event object.\n * @param {string} viewName Name of the view.\n */\n newScope.$emit('$viewContentLoading', name);\n\n const cloned = $transclude(newScope, function(clone) {\n clone.data('$uiViewAnim', $uiViewAnim);\n clone.data('$uiView', $uiViewData);\n renderer.enter(clone, $element, function onUIViewEnter() {\n animEnter.resolve();\n if (currentScope) currentScope.$emit('$viewContentAnimationEnded');\n\n if (isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {\n $uiViewScroll(clone);\n }\n });\n\n cleanupLastView();\n });\n\n currentEl = cloned;\n currentScope = newScope;\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoaded\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description *\n * Fired once the view is **loaded**, *after* the DOM is rendered.\n *\n * @param {Object} event Event object.\n */\n currentScope.$emit('$viewContentLoaded', config || viewConfig);\n currentScope.$eval(onloadExp);\n }\n };\n },\n };\n\n return directive;\n}];\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout'];\n/** @hidden */\nfunction $ViewDirectiveFill($compile: angular.ICompileService,\n $controller: angular.IControllerService,\n $transitions: TransitionService,\n $view: ViewService,\n $q: angular.IQService,\n $timeout: ITimeoutService) {\n const getControllerAs = parse('viewDecl.controllerAs');\n const getResolveAs = parse('viewDecl.resolveAs');\n\n return {\n restrict: 'ECA',\n priority: -400,\n compile: function (tElement: JQuery) {\n const initial = tElement.html();\n tElement.empty();\n\n return function (scope: IScope, $element: JQuery) {\n const data: UIViewData = $element.data('$uiView');\n if (!data) {\n $element.html(initial);\n $compile($element.contents() as any)(scope);\n return;\n }\n\n const cfg: Ng1ViewConfig = data.$cfg || { viewDecl: {}, getTemplate: noop };\n const resolveCtx: ResolveContext = cfg.path && new ResolveContext(cfg.path);\n $element.html(cfg.getTemplate($element, resolveCtx) || initial);\n trace.traceUIViewFill(data.$uiView, $element.html());\n\n const link = $compile($element.contents() as any);\n const controller = cfg.controller;\n const controllerAs: string = getControllerAs(cfg);\n const resolveAs: string = getResolveAs(cfg);\n const locals = resolveCtx && getLocals(resolveCtx);\n\n scope[resolveAs] = locals;\n\n if (controller) {\n const controllerInstance = $controller(controller, extend({}, locals, { $scope: scope, $element: $element }));\n if (controllerAs) {\n scope[controllerAs] = controllerInstance;\n scope[controllerAs][resolveAs] = locals;\n }\n\n // TODO: Use $view service as a central point for registering component-level hooks\n // Then, when a component is created, tell the $view service, so it can invoke hooks\n // $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element });\n // scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element }));\n\n $element.data('$ngControllerController', controllerInstance);\n $element.children().data('$ngControllerController', controllerInstance);\n\n registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg);\n }\n\n // Wait for the component to appear in the DOM\n if (isString(cfg.viewDecl.component)) {\n const cmp = cfg.viewDecl.component;\n const kebobName = kebobString(cmp);\n const tagRegexp = new RegExp(`^(x-|data-)?${kebobName}$`, 'i');\n\n const getComponentController = () => {\n const directiveEl = [].slice.call($element[0].children)\n .filter((el: Element) => el && el.tagName && tagRegexp.exec(el.tagName)) ;\n\n return directiveEl && angular.element(directiveEl).data(`$${cmp}Controller`);\n };\n\n const deregisterWatch = scope.$watch(getComponentController, function(ctrlInstance) {\n if (!ctrlInstance) return;\n registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg);\n deregisterWatch();\n });\n }\n\n link(scope);\n };\n },\n };\n}\n\n/** @hidden */\nconst hasComponentImpl = typeof (angular as any).module('ui.router')['component'] === 'function';\n/** @hidden incrementing id */\nlet _uiCanExitId = 0;\n\n/** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */\nfunction registerControllerCallbacks($q: angular.IQService,\n $transitions: TransitionService,\n controllerInstance: Ng1Controller,\n $scope: IScope,\n cfg: Ng1ViewConfig) {\n // Call $onInit() ASAP\n if (isFunction(controllerInstance.$onInit) && !(cfg.viewDecl.component && hasComponentImpl)) {\n controllerInstance.$onInit();\n }\n\n const viewState: Ng1StateDeclaration = tail(cfg.path).state.self;\n\n const hookOptions: HookRegOptions = { bind: controllerInstance };\n // Add component-level hook for onParamsChange\n if (isFunction(controllerInstance.uiOnParamsChanged)) {\n const resolveContext: ResolveContext = new ResolveContext(cfg.path);\n const viewCreationTrans = resolveContext.getResolvable('$transition$').data;\n\n // Fire callback on any successful transition\n const paramsUpdated = ($transition$: Transition) => {\n // Exit early if the $transition$ is the same as the view was created within.\n // Exit early if the $transition$ will exit the state the view is for.\n if ($transition$ === viewCreationTrans || $transition$.exiting().indexOf(viewState as StateDeclaration) !== -1) return;\n\n const toParams = $transition$.params('to') as TypedMap;\n const fromParams = $transition$.params>('from') as TypedMap;\n const toSchema: Param[] = $transition$.treeChanges().to.map((node: PathNode) => node.paramSchema).reduce(unnestR, []);\n const fromSchema: Param[] = $transition$.treeChanges().from.map((node: PathNode) => node.paramSchema).reduce(unnestR, []);\n\n // Find the to params that have different values than the from params\n const changedToParams = toSchema.filter((param: Param) => {\n const idx = fromSchema.indexOf(param);\n return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]);\n });\n\n // Only trigger callback if a to param has changed or is new\n if (changedToParams.length) {\n const changedKeys: string[] = changedToParams.map(x => x.id);\n // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params.\n const newValues = filter(toParams, (val, key) => changedKeys.indexOf(key) !== -1);\n controllerInstance.uiOnParamsChanged(newValues, $transition$);\n }\n };\n $scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions));\n }\n\n // Add component-level hook for uiCanExit\n if (isFunction(controllerInstance.uiCanExit)) {\n const id = _uiCanExitId++;\n const cacheProp = '_uiCanExitIds';\n\n // Returns true if a redirect transition already answered truthy\n const prevTruthyAnswer = (trans: Transition) =>\n !!trans && (trans[cacheProp] && trans[cacheProp][id] === true || prevTruthyAnswer(trans.redirectedFrom()));\n\n // If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition\n const wrappedHook = (trans: Transition) => {\n let promise;\n const ids = trans[cacheProp] = trans[cacheProp] || {};\n\n if (!prevTruthyAnswer(trans)) {\n promise = $q.when(controllerInstance.uiCanExit(trans));\n promise.then(val => ids[id] = (val !== false));\n }\n return promise;\n };\n\n const criteria = { exiting: viewState.name };\n $scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions));\n }\n}\n\nangular.module('ui.router.state').directive('uiView', uiView);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n", - "/** @module ng1 */ /** for typedoc */\n\nimport { ng as angular } from './angular';\nimport { Obj, StateService, StateOrName } from '@uirouter/core';\n\n/**\n * `isState` Filter: truthy if the current state is the parameter\n *\n * Translates to [[StateService.is]] `$state.is(\"stateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state is 'stateName'
    \n * ```\n */\n$IsStateFilter.$inject = ['$state'];\nexport function $IsStateFilter($state: StateService) {\n const isFilter: any = function(state: StateOrName, params: Obj, options?: { relative?: StateOrName }) {\n return $state.is(state, params, options);\n };\n isFilter.$stateful = true;\n return isFilter;\n}\n\n/**\n * `includedByState` Filter: truthy if the current state includes the parameter\n *\n * Translates to [[StateService.includes]]` $state.is(\"fullOrPartialStateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state includes 'fullOrPartialStateName'
    \n * ```\n */\n$IncludedByStateFilter.$inject = ['$state'];\nexport function $IncludedByStateFilter($state: StateService) {\n const includesFilter: any = function(state: StateOrName, params: Obj, options: { relative?: StateOrName }) {\n return $state.includes(state, params, options);\n };\n includesFilter.$stateful = true;\n return includesFilter;\n}\n\nangular.module('ui.router.state')\n .filter('isState', $IsStateFilter)\n .filter('includedByState', $IncludedByStateFilter);\n", - "/** @module ng1 */ /** */\nimport { ng as angular } from './angular';\nimport { IServiceProviderFactory } from 'angular';\nimport IAnchorScrollService = angular.IAnchorScrollService;\nimport ITimeoutService = angular.ITimeoutService;\n\nexport interface UIViewScrollProvider {\n /**\n * Uses standard anchorScroll behavior\n *\n * Reverts [[$uiViewScroll]] back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * service for scrolling based on the url anchor.\n */\n useAnchorScroll(): void;\n}\n\n\n/** @hidden */\nfunction $ViewScrollProvider() {\n\n let useAnchorScroll = false;\n\n this.useAnchorScroll = function () {\n useAnchorScroll = true;\n };\n\n this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll: IAnchorScrollService, $timeout: ITimeoutService): Function {\n if (useAnchorScroll) {\n return $anchorScroll;\n }\n\n return function ($element: JQuery) {\n return $timeout(function () {\n $element[0].scrollIntoView();\n }, 0, false);\n };\n }];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n", - "/**\n * Main entry point for angular 1.x build\n * @module ng1\n */ /** */\n\nexport * from './interface';\nexport * from './services';\nexport * from './statebuilders/views';\nexport * from './stateProvider';\nexport * from './urlRouterProvider';\n\nimport './injectables';\nimport './directives/stateDirectives';\nimport './stateFilters';\nimport './directives/viewDirective';\nimport './viewScroll';\n\nexport default 'ui.router';\n\nimport * as core from '@uirouter/core';\nexport { core };\nexport * from '@uirouter/core';\n\n" + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { UIRouter } from '../router';\nimport { BaseLocationServices } from './baseLocationService';\nimport { LocationConfig, root, splitHash, splitQuery, stripLastPathElement } from '../common';\n\n/**\n * A `LocationServices` that gets/sets the current location using the browser's `location` and `history` apis\n *\n * Uses `history.pushState` and `history.replaceState`\n */\nexport class PushStateLocationService extends BaseLocationServices {\n _config: LocationConfig;\n\n constructor(router: UIRouter) {\n super(router, true);\n this._config = router.urlService.config;\n root.addEventListener('popstate', this._listener, false);\n }\n\n /**\n * Gets the base prefix without:\n * - trailing slash\n * - trailing filename\n * - protocol and hostname\n *\n * If , this returns '/base'.\n * If , this returns '/foo/base'.\n * If , this returns '/base'.\n * If , this returns '/base'.\n * If , this returns ''.\n * If , this returns ''.\n * If , this returns ''.\n *\n * See: https://html.spec.whatwg.org/dev/semantics.html#the-base-element\n */\n private _getBasePrefix() {\n return stripLastPathElement(this._config.baseHref());\n }\n\n protected _get() {\n let { pathname, hash, search } = this._location;\n search = splitQuery(search)[1]; // strip ? if found\n hash = splitHash(hash)[1]; // strip # if found\n\n const basePrefix = this._getBasePrefix();\n const exactBaseHrefMatch = pathname === this._config.baseHref();\n const startsWithBase = pathname.substr(0, basePrefix.length) === basePrefix;\n pathname = exactBaseHrefMatch ? '/' : startsWithBase ? pathname.substring(basePrefix.length) : pathname;\n\n return pathname + (search ? '?' + search : '') + (hash ? '#' + hash : '');\n }\n\n protected _set(state: any, title: string, url: string, replace: boolean) {\n const basePrefix = this._getBasePrefix();\n const slash = url && url[0] !== '/' ? '/' : '';\n const fullUrl = url === '' || url === '/' ? this._config.baseHref() : basePrefix + slash + url;\n\n if (replace) {\n this._history.replaceState(state, title, fullUrl);\n } else {\n this._history.pushState(state, title, fullUrl);\n }\n }\n\n public dispose(router: UIRouter) {\n super.dispose(router);\n root.removeEventListener('popstate', this._listener);\n }\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { LocationConfig } from '../common/coreservices';\nimport { isDefined } from '../common/predicates';\nimport { noop } from '../common/common';\n\n/** A `LocationConfig` mock that gets/sets all config from an in-memory object */\nexport class MemoryLocationConfig implements LocationConfig {\n dispose = noop;\n\n _baseHref = '';\n _port = 80;\n _protocol = 'http';\n _host = 'localhost';\n _hashPrefix = '';\n\n port = () => this._port;\n protocol = () => this._protocol;\n host = () => this._host;\n baseHref = () => this._baseHref;\n html5Mode = () => false;\n hashPrefix = (newval?) => (isDefined(newval) ? (this._hashPrefix = newval) : this._hashPrefix);\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { isDefined } from '../common/predicates';\nimport { LocationConfig } from '../common/coreservices';\n\n/** A `LocationConfig` that delegates to the browser's `location` object */\nexport class BrowserLocationConfig implements LocationConfig {\n private _baseHref = undefined;\n private _hashPrefix = '';\n\n constructor(router?, private _isHtml5 = false) {}\n\n port(): number {\n if (location.port) {\n return Number(location.port);\n }\n\n return this.protocol() === 'https' ? 443 : 80;\n }\n\n protocol(): string {\n return location.protocol.replace(/:/g, '');\n }\n\n host(): string {\n return location.hostname;\n }\n\n html5Mode(): boolean {\n return this._isHtml5;\n }\n\n hashPrefix(): string;\n hashPrefix(newprefix?: string): string {\n return isDefined(newprefix) ? (this._hashPrefix = newprefix) : this._hashPrefix;\n }\n\n baseHref(href?: string): string {\n return isDefined(href)\n ? (this._baseHref = href)\n : isDefined(this._baseHref) ? this._baseHref : this.applyDocumentBaseHref();\n }\n\n applyDocumentBaseHref() {\n const baseTag: HTMLBaseElement = document.getElementsByTagName('base')[0];\n return (this._baseHref = baseTag ? baseTag.href.substr(location.origin.length) : location.pathname || '/');\n }\n\n dispose() {}\n}\n", + "/**\n * @internalapi\n * @module vanilla\n */\n/** */\nimport { BrowserLocationConfig } from './browserLocationConfig';\nimport { HashLocationService } from './hashLocationService';\nimport { locationPluginFactory } from './utils';\nimport { LocationPlugin, ServicesPlugin } from './interface';\nimport { UIRouter } from '../router';\nimport { PushStateLocationService } from './pushStateLocationService';\nimport { MemoryLocationService } from './memoryLocationService';\nimport { MemoryLocationConfig } from './memoryLocationConfig';\nimport { $injector } from './injector';\nimport { $q } from './q';\nimport { services } from '../common/coreservices';\n\nexport function servicesPlugin(router: UIRouter): ServicesPlugin {\n services.$injector = $injector;\n services.$q = $q;\n\n return { name: 'vanilla.services', $q, $injector, dispose: () => null };\n}\n\n/** A `UIRouterPlugin` uses the browser hash to get/set the current location */\nexport const hashLocationPlugin: (router: UIRouter) => LocationPlugin = locationPluginFactory(\n 'vanilla.hashBangLocation',\n false,\n HashLocationService,\n BrowserLocationConfig,\n);\n\n/** A `UIRouterPlugin` that gets/sets the current location using the browser's `location` and `history` apis */\nexport const pushStateLocationPlugin: (router: UIRouter) => LocationPlugin = locationPluginFactory(\n 'vanilla.pushStateLocation',\n true,\n PushStateLocationService,\n BrowserLocationConfig,\n);\n\n/** A `UIRouterPlugin` that gets/sets the current location from an in-memory object */\nexport const memoryLocationPlugin: (router: UIRouter) => LocationPlugin = locationPluginFactory(\n 'vanilla.memoryLocation',\n false,\n MemoryLocationService,\n MemoryLocationConfig,\n);\n", + "/**\n * # Core classes and interfaces\n *\n * The classes and interfaces that are core to ui-router and do not belong\n * to a more specific subsystem (such as resolve).\n *\n * @coreapi\n * @preferred\n * @module core\n */ /** for typedoc */\n\n// Need to import or export at least one concrete something\nimport { noop } from './common/common';\nimport { UIRouter } from './router';\n\n/**\n * An interface for getting values from dependency injection.\n *\n * This is primarily used to get resolve values for a given token.\n * An instance of the `UIInjector` can be retrieved from the current transition using [[Transition.injector]].\n *\n * ---\n *\n * If no resolve is found for a token, then it will delegate to the native injector.\n * The native injector may be Angular 1 `$injector`, Angular 2 `Injector`, or a simple polyfill.\n *\n * In Angular 2, the native injector might be the root Injector,\n * or it might be a lazy loaded `NgModule` injector scoped to a lazy load state tree.\n */\nexport interface UIInjector {\n /**\n * Gets a value from the injector.\n *\n * For a given token, returns the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this throws an error.\n *\n * #### Example:\n * ```js\n * var myResolve = injector.get('myResolve');\n * ```\n *\n * #### ng1 Example:\n * ```js\n * // Fetch StateService\n * injector.get('$state').go('home');\n * ```\n *\n * #### ng2 Example:\n * ```js\n * import {StateService} from \"ui-router-ng2\";\n * // Fetch StateService\n * injector.get(StateService).go('home');\n * ```\n *\n * #### Typescript Example:\n * ```js\n * var stringArray = injector.get('myStringArray');\n * ```\n *\n * ### `NOWAIT` policy\n *\n * When using [[ResolvePolicy.async]] === `NOWAIT`, the value returned from `get()` is a promise for the result.\n * The promise is not automatically unwrapped.\n *\n * @param token the key for the value to get. May be a string, a class, or any arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n get(token: any): any;\n /** Gets a value as type `T` (generics parameter) */\n get(token: any): T;\n\n /**\n * Asynchronously gets a value from the injector\n *\n * For a given token, returns a promise for the value from the injector that matches the token.\n * If the token is for a resolve that has not yet been fetched, this triggers the resolve to load.\n *\n * #### Example:\n * ```js\n * return injector.getAsync('myResolve').then(value => {\n * if (value === 'declined') return false;\n * });\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return a Promise for the Dependency Injection value that matches the token\n */\n getAsync(token: any): Promise;\n /** Asynchronously gets a value as type `T` (generics parameter) */\n getAsync(token: any): Promise;\n\n /**\n * Gets a value from the native injector\n *\n * Returns a value from the native injector, bypassing anything in the [[ResolveContext]].\n *\n * Example:\n * ```js\n * let someThing = injector.getNative(SomeToken);\n * ```\n *\n * @param token the key for the value to get. May be a string or arbitrary object.\n * @return the Dependency Injection value that matches the token\n */\n getNative(token: any): any;\n getNative(token: any): T;\n}\n\n/** @internalapi */\nexport interface UIRouterPlugin extends Disposable {\n name: string;\n}\n\n/** @internalapi */\nexport abstract class UIRouterPluginBase implements UIRouterPlugin, Disposable {\n abstract name: string;\n dispose(router: UIRouter) {}\n}\n\n/** @internalapi */\nexport interface Disposable {\n /** Instructs the Disposable to clean up any resources */\n dispose(router?: UIRouter);\n}\n", + "/** @module ng1 */ /** */\nimport { ng as angular } from '../angular';\nimport {\n StateObject,\n pick,\n forEach,\n tail,\n extend,\n isArray,\n isInjectable,\n isDefined,\n isString,\n services,\n trace,\n ViewConfig,\n ViewService,\n ViewConfigFactory,\n PathNode,\n ResolveContext,\n Resolvable,\n IInjectable,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration } from '../interface';\nimport { TemplateFactory } from '../templateFactory';\nimport IInjectorService = angular.auto.IInjectorService;\n\nexport function getNg1ViewConfigFactory(): ViewConfigFactory {\n let templateFactory: TemplateFactory = null;\n return (path, view) => {\n templateFactory = templateFactory || services.$injector.get('$templateFactory');\n return [new Ng1ViewConfig(path, view, templateFactory)];\n };\n}\n\nconst hasAnyKey = (keys, obj) => keys.reduce((acc, key) => acc || isDefined(obj[key]), false);\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `views`.\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * handles the `views` property with logic specific to @uirouter/angularjs (ng1).\n *\n * If no `views: {}` property exists on the [[StateDeclaration]], then it creates the `views` object\n * and applies the state-level configuration to a view named `$default`.\n */\nexport function ng1ViewsBuilder(state: StateObject) {\n // Do not process root state\n if (!state.parent) return {};\n\n const tplKeys = ['templateProvider', 'templateUrl', 'template', 'notify', 'async'],\n ctrlKeys = ['controller', 'controllerProvider', 'controllerAs', 'resolveAs'],\n compKeys = ['component', 'bindings', 'componentProvider'],\n nonCompKeys = tplKeys.concat(ctrlKeys),\n allViewKeys = compKeys.concat(nonCompKeys);\n\n // Do not allow a state to have both state-level props and also a `views: {}` property.\n // A state without a `views: {}` property can declare properties for the `$default` view as properties of the state.\n // However, the `$default` approach should not be mixed with a separate `views: ` block.\n if (isDefined(state.views) && hasAnyKey(allViewKeys, state)) {\n throw new Error(\n `State '${state.name}' has a 'views' object. ` +\n `It cannot also have \"view properties\" at the state level. ` +\n `Move the following properties into a view (in the 'views' object): ` +\n ` ${allViewKeys.filter(key => isDefined(state[key])).join(', ')}`,\n );\n }\n\n const views: { [key: string]: Ng1ViewDeclaration } = {},\n viewsObject = state.views || { $default: pick(state, allViewKeys) };\n\n forEach(viewsObject, function(config: Ng1ViewDeclaration, name: string) {\n // Account for views: { \"\": { template... } }\n name = name || '$default';\n // Account for views: { header: \"headerComponent\" }\n if (isString(config)) config = { component: config };\n\n // Make a shallow copy of the config object\n config = extend({}, config);\n\n // Do not allow a view to mix props for component-style view with props for template/controller-style view\n if (hasAnyKey(compKeys, config) && hasAnyKey(nonCompKeys, config)) {\n throw new Error(\n `Cannot combine: ${compKeys.join('|')} with: ${nonCompKeys.join('|')} in stateview: '${name}@${state.name}'`,\n );\n }\n\n config.resolveAs = config.resolveAs || '$resolve';\n config.$type = 'ng1';\n config.$context = state;\n config.$name = name;\n\n const normalized = ViewService.normalizeUIViewTarget(config.$context, config.$name);\n config.$uiViewName = normalized.uiViewName;\n config.$uiViewContextAnchor = normalized.uiViewContextAnchor;\n\n views[name] = config;\n });\n return views;\n}\n\nlet id = 0;\nexport class Ng1ViewConfig implements ViewConfig {\n $id = id++;\n loaded = false;\n controller: Function; // actually IInjectable|string\n template: string;\n component: string;\n locals: any; // TODO: delete me\n\n constructor(public path: PathNode[], public viewDecl: Ng1ViewDeclaration, public factory: TemplateFactory) {}\n\n load() {\n const $q = services.$q;\n const context = new ResolveContext(this.path);\n const params = this.path.reduce((acc, node) => extend(acc, node.paramValues), {});\n\n const promises: any = {\n template: $q.when(this.factory.fromConfig(this.viewDecl, params, context)),\n controller: $q.when(this.getController(context)),\n };\n\n return $q.all(promises).then(results => {\n trace.traceViewServiceEvent('Loaded', this);\n this.controller = results.controller;\n extend(this, results.template); // Either { template: \"tpl\" } or { component: \"cmpName\" }\n return this;\n });\n }\n\n getTemplate = (uiView, context: ResolveContext) =>\n this.component\n ? this.factory.makeComponentTemplate(uiView, context, this.component, this.viewDecl.bindings)\n : this.template;\n\n /**\n * Gets the controller for a view configuration.\n *\n * @returns {Function|Promise.} Returns a controller, or a promise that resolves to a controller.\n */\n getController(context: ResolveContext): IInjectable | string | Promise {\n const provider = this.viewDecl.controllerProvider;\n if (!isInjectable(provider)) return this.viewDecl.controller;\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail(provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n}\n", + "/** @module view */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport { IAugmentedJQuery } from 'angular';\nimport {\n isArray,\n isDefined,\n isFunction,\n isObject,\n services,\n Obj,\n IInjectable,\n tail,\n kebobString,\n unnestR,\n ResolveContext,\n Resolvable,\n RawParams,\n} from '@uirouter/core';\nimport { Ng1ViewDeclaration, TemplateFactoryProvider } from './interface';\n\n/**\n * Service which manages loading of templates from a ViewConfig.\n */\nexport class TemplateFactory implements TemplateFactoryProvider {\n /** @hidden */ private _useHttp = angular.version.minor < 3;\n /** @hidden */ private $templateRequest;\n /** @hidden */ private $templateCache;\n /** @hidden */ private $http;\n\n /** @hidden */ $get = [\n '$http',\n '$templateCache',\n '$injector',\n ($http, $templateCache, $injector) => {\n this.$templateRequest = $injector.has && $injector.has('$templateRequest') && $injector.get('$templateRequest');\n this.$http = $http;\n this.$templateCache = $templateCache;\n return this;\n },\n ];\n\n /** @hidden */\n useHttpService(value: boolean) {\n this._useHttp = value;\n }\n\n /**\n * Creates a template from a configuration object.\n *\n * @param config Configuration object for which to load a template.\n * The following properties are search in the specified order, and the first one\n * that is defined is used to create the template:\n *\n * @param params Parameters to pass to the template function.\n * @param context The resolve context associated with the template's view\n *\n * @return {string|object} The template html as a string, or a promise for\n * that string,or `null` if no template is configured.\n */\n fromConfig(\n config: Ng1ViewDeclaration,\n params: any,\n context: ResolveContext,\n ): Promise<{ template?: string; component?: string }> {\n const defaultTemplate = '';\n\n const asTemplate = result => services.$q.when(result).then(str => ({ template: str }));\n const asComponent = result => services.$q.when(result).then(str => ({ component: str }));\n\n return isDefined(config.template)\n ? asTemplate(this.fromString(config.template, params))\n : isDefined(config.templateUrl)\n ? asTemplate(this.fromUrl(config.templateUrl, params))\n : isDefined(config.templateProvider)\n ? asTemplate(this.fromProvider(config.templateProvider, params, context))\n : isDefined(config.component)\n ? asComponent(config.component)\n : isDefined(config.componentProvider)\n ? asComponent(this.fromComponentProvider(config.componentProvider, params, context))\n : asTemplate(defaultTemplate);\n }\n\n /**\n * Creates a template from a string or a function returning a string.\n *\n * @param template html template as a string or function that returns an html template as a string.\n * @param params Parameters to pass to the template function.\n *\n * @return {string|object} The template html as a string, or a promise for that\n * string.\n */\n fromString(template: string | Function, params?: RawParams) {\n return isFunction(template) ? (template)(params) : template;\n }\n\n /**\n * Loads a template from the a URL via `$http` and `$templateCache`.\n *\n * @param {string|Function} url url of the template to load, or a function\n * that returns a url.\n * @param {Object} params Parameters to pass to the url function.\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromUrl(url: string | Function, params: any) {\n if (isFunction(url)) url = (url)(params);\n if (url == null) return null;\n\n if (this._useHttp) {\n return this.$http\n .get(url, { cache: this.$templateCache, headers: { Accept: 'text/html' } })\n .then(function(response) {\n return response.data;\n });\n }\n\n return this.$templateRequest(url);\n }\n\n /**\n * Creates a template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string|Promise.} The template html as a string, or a promise\n * for that string.\n */\n fromProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail(provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a component's template by invoking an injectable provider function.\n *\n * @param provider Function to invoke via `locals`\n * @param {Function} injectFn a function used to invoke the template provider\n * @return {string} The template html as a string: \"\".\n */\n fromComponentProvider(provider: IInjectable, params: any, context: ResolveContext) {\n const deps = services.$injector.annotate(provider);\n const providerFn = isArray(provider) ? tail(provider) : provider;\n const resolvable = new Resolvable('', providerFn, deps);\n return resolvable.get(context);\n }\n\n /**\n * Creates a template from a component's name\n *\n * This implements route-to-component.\n * It works by retrieving the component (directive) metadata from the injector.\n * It analyses the component's bindings, then constructs a template that instantiates the component.\n * The template wires input and output bindings to resolves or from the parent component.\n *\n * @param uiView {object} The parent ui-view (for binding outputs to callbacks)\n * @param context The ResolveContext (for binding outputs to callbacks returned from resolves)\n * @param component {string} Component's name in camel case.\n * @param bindings An object defining the component's bindings: {foo: '<'}\n * @return {string} The template as a string: \"\".\n */\n makeComponentTemplate(uiView: IAugmentedJQuery, context: ResolveContext, component: string, bindings?: any) {\n bindings = bindings || {};\n\n // Bind once prefix\n const prefix = angular.version.minor >= 3 ? '::' : '';\n // Convert to kebob name. Add x- prefix if the string starts with `x-` or `data-`\n const kebob = (camelCase: string) => {\n const kebobed = kebobString(camelCase);\n return /^(x|data)-/.exec(kebobed) ? `x-${kebobed}` : kebobed;\n };\n\n const attributeTpl = (input: BindingTuple) => {\n const { name, type } = input;\n const attrName = kebob(name);\n // If the ui-view has an attribute which matches a binding on the routed component\n // then pass that attribute through to the routed component template.\n // Prefer ui-view wired mappings to resolve data, unless the resolve was explicitly bound using `bindings:`\n if (uiView.attr(attrName) && !bindings[name]) return `${attrName}='${uiView.attr(attrName)}'`;\n\n const resolveName = bindings[name] || name;\n // Pre-evaluate the expression for \"@\" bindings by enclosing in {{ }}\n // some-attr=\"{{ ::$resolve.someResolveName }}\"\n if (type === '@') return `${attrName}='{{${prefix}$resolve.${resolveName}}}'`;\n\n // Wire \"&\" callbacks to resolves that return a callback function\n // Get the result of the resolve (should be a function) and annotate it to get its arguments.\n // some-attr=\"$resolve.someResolveResultName(foo, bar)\"\n if (type === '&') {\n const res = context.getResolvable(resolveName);\n const fn = res && res.data;\n const args = (fn && services.$injector.annotate(fn)) || [];\n // account for array style injection, i.e., ['foo', function(foo) {}]\n const arrayIdxStr = isArray(fn) ? `[${fn.length - 1}]` : '';\n return `${attrName}='$resolve.${resolveName}${arrayIdxStr}(${args.join(',')})'`;\n }\n\n // some-attr=\"::$resolve.someResolveName\"\n return `${attrName}='${prefix}$resolve.${resolveName}'`;\n };\n\n const attrs = getComponentBindings(component)\n .map(attributeTpl)\n .join(' ');\n const kebobName = kebob(component);\n return `<${kebobName} ${attrs}>`;\n }\n}\n\n// Gets all the directive(s)' inputs ('@', '=', and '<') and outputs ('&')\nfunction getComponentBindings(name: string) {\n const cmpDefs = services.$injector.get(name + 'Directive'); // could be multiple\n if (!cmpDefs || !cmpDefs.length) throw new Error(`Unable to find component named '${name}'`);\n return cmpDefs.map(getBindings).reduce(unnestR, []);\n}\n\n// Given a directive definition, find its object input attributes\n// Use different properties, depending on the type of directive (component, bindToController, normal)\nconst getBindings = (def: any) => {\n if (isObject(def.bindToController)) return scopeBindings(def.bindToController);\n return scopeBindings(def.scope);\n};\n\ninterface BindingTuple {\n name: string;\n type: string;\n}\n\n// for ng 1.2 style, process the scope: { input: \"=foo\" }\n// for ng 1.3 through ng 1.5, process the component's bindToController: { input: \"=foo\" } object\nconst scopeBindings = (bindingsObj: Obj) =>\n Object.keys(bindingsObj || {})\n // [ 'input', [ '=foo', '=', 'foo' ] ]\n .map(key => [key, /^([=<@&])[?]?(.*)/.exec(bindingsObj[key])])\n // skip malformed values\n .filter(tuple => isDefined(tuple) && isArray(tuple[1]))\n // { name: ('foo' || 'input'), type: '=' }\n .map(tuple => ({ name: tuple[1][2] || tuple[0], type: tuple[1][1] } as BindingTuple));\n", + "/** @module ng1 */ /** for typedoc */\nimport {\n val,\n isObject,\n createProxyFunctions,\n BuilderFunction,\n StateRegistry,\n StateService,\n OnInvalidCallback,\n} from '@uirouter/core';\nimport { Ng1StateDeclaration } from './interface';\n\n/**\n * The Angular 1 `StateProvider`\n *\n * The `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\nexport class StateProvider {\n constructor(private stateRegistry: StateRegistry, private stateService: StateService) {\n createProxyFunctions(val(StateProvider.prototype), this, val(this));\n }\n\n /**\n * Decorates states when they are registered\n *\n * Allows you to extend (carefully) or override (at your own peril) the\n * `stateBuilder` object used internally by [[StateRegistry]].\n * This can be used to add custom functionality to ui-router,\n * for example inferring templateUrl based on the state name.\n *\n * When passing only a name, it returns the current (original or decorated) builder\n * function that matches `name`.\n *\n * The builder functions that can be decorated are listed below. Though not all\n * necessarily have a good use case for decoration, that is up to you to decide.\n *\n * In addition, users can attach custom decorators, which will generate new\n * properties within the state's internal definition. There is currently no clear\n * use-case for this beyond accessing internal states (i.e. $state.$current),\n * however, expect this to become increasingly relevant as we introduce additional\n * meta-programming features.\n *\n * **Warning**: Decorators should not be interdependent because the order of\n * execution of the builder functions in non-deterministic. Builder functions\n * should only be dependent on the state definition object and super function.\n *\n *\n * Existing builder functions and current return values:\n *\n * - **parent** `{object}` - returns the parent state object.\n * - **data** `{object}` - returns state data, including any inherited data that is not\n * overridden by own values (if any).\n * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n * or `null`.\n * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is\n * navigable).\n * - **params** `{object}` - returns an array of state params that are ensured to\n * be a super-set of parent's params.\n * - **views** `{object}` - returns a views object where each key is an absolute view\n * name (i.e. \"viewName@stateName\") and each value is the config object\n * (template, controller) for the view. Even when you don't use the views object\n * explicitly on a state config, one is still created for you internally.\n * So by decorating this builder function you have access to decorating template\n * and controller properties.\n * - **ownParams** `{object}` - returns an array of params that belong to the state,\n * not including any params defined by ancestor states.\n * - **path** `{string}` - returns the full path from the root down to this state.\n * Needed for state activation.\n * - **includes** `{object}` - returns an object that includes every state that\n * would pass a `$state.includes()` test.\n *\n * #### Example:\n * Override the internal 'views' builder with a function that takes the state\n * definition, and a reference to the internal function being overridden:\n * ```js\n * $stateProvider.decorator('views', function (state, parent) {\n * let result = {},\n * views = parent(state);\n *\n * angular.forEach(views, function (config, name) {\n * let autoName = (state.name + '.' + name).replace('.', '/');\n * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n * result[name] = config;\n * });\n * return result;\n * });\n *\n * $stateProvider.state('home', {\n * views: {\n * 'contact.list': { controller: 'ListController' },\n * 'contact.item': { controller: 'ItemController' }\n * }\n * });\n * ```\n *\n *\n * ```js\n * // Auto-populates list and item views with /partials/home/contact/list.html,\n * // and /partials/home/contact/item.html, respectively.\n * $state.go('home');\n * ```\n *\n * @param {string} name The name of the builder function to decorate.\n * @param {object} func A function that is responsible for decorating the original\n * builder function. The function receives two parameters:\n *\n * - `{object}` - state - The state config object.\n * - `{object}` - super - The original builder function.\n *\n * @return {object} $stateProvider - $stateProvider instance\n */\n decorator(name: string, func: BuilderFunction) {\n return this.stateRegistry.decorator(name, func) || this;\n }\n\n /**\n * Registers a state\n *\n * ### This is a passthrough to [[StateRegistry.register]].\n *\n * Registers a state configuration under a given state name.\n * The stateConfig object has the following acceptable properties.\n *\n *
    \n *\n * - **`template`** - {string|function=} - html template as a string or a function that returns\n * an html template as a string which should be used by the uiView directives. This property\n * takes precedence over templateUrl.\n *\n * If `template` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateUrl`** - {string|function=} - path or function that returns a path to an html\n * template that should be used by uiView.\n *\n * If `templateUrl` is a function, it will be called with the following parameters:\n *\n * - {array.<object>} - state parameters extracted from the current $location.path() by\n * applying the current state\n *\n * \n *\n * - **`templateProvider`** - {function=} - Provider function that returns HTML content\n * string.\n *\n * \n *\n * - **`controller`** - {string|function=} - Controller fn that should be associated with newly\n * related scope or the name of a registered controller if passed as a string.\n *\n * \n *\n * - **`controllerProvider`** - {function=} - Injectable provider function that returns\n * the actual controller or string.\n *\n * \n *\n * - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be\n * published to scope under the controllerAs name.\n *\n * \n *\n * - **`resolve`** - {object.<string, function>=} - An optional map of dependencies which\n * should be injected into the controller. If any of these dependencies are promises,\n * the router will wait for them all to be resolved or one to be rejected before the\n * controller is instantiated. If all the promises are resolved successfully, the values\n * of the resolved promises are injected and $stateChangeSuccess event is fired. If any\n * of the promises are rejected the $stateChangeError event is fired. The map object is:\n *\n * - key - {string}: name of dependency to be injected into controller\n * - factory - {string|function}: If string then it is alias for service. Otherwise if function,\n * it is injected and return value it treated as dependency. If result is a promise, it is\n * resolved before its value is injected into controller.\n *\n * \n *\n * - **`url`** - {string=} - A url with optional parameters. When a state is navigated or\n * transitioned to, the `$stateParams` service will be populated with any\n * parameters that were passed.\n *\n * \n *\n * - **`params`** - {object=} - An array of parameter names or regular expressions. Only\n * use this within a state if you are not using url. Otherwise you can specify your\n * parameters within the url. When a state is navigated or transitioned to, the\n * $stateParams service will be populated with any parameters that were passed.\n *\n * \n *\n * - **`views`** - {object=} - Use the views property to set up multiple views or to target views\n * manually/explicitly.\n *\n * \n *\n * - **`abstract`** - {boolean=} - An abstract state will never be directly activated,\n * but can provide inherited properties to its common children states.\n *\n * \n *\n * - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way\n * to trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to\n * trigger an action or dispatch an event, such as opening a dialog.\n * If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.\n *\n * \n *\n * - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state\n * just because a search/query parameter has changed (via $location.search() or $location.hash()).\n * Useful for when you'd like to modify $location.search() without triggering a reload.\n *\n * \n *\n * - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.\n *\n * #### Example:\n * Some state name examples\n * ```js\n * // stateName can be a single top-level name (must be unique).\n * $stateProvider.state(\"home\", {});\n *\n * // Or it can be a nested state name. This state is a child of the\n * // above \"home\" state.\n * $stateProvider.state(\"home.newest\", {});\n *\n * // Nest states as deeply as needed.\n * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n *\n * // state() returns $stateProvider, so you can chain state declarations.\n * $stateProvider\n * .state(\"home\", {})\n * .state(\"about\", {})\n * .state(\"contacts\", {});\n * ```\n *\n * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n * @param {object} definition State configuration object.\n */\n state(name: string, definition: Ng1StateDeclaration): StateProvider;\n state(definition: Ng1StateDeclaration): StateProvider;\n state(name: any, definition?: any) {\n if (isObject(name)) {\n definition = name;\n } else {\n definition.name = name;\n }\n this.stateRegistry.register(definition);\n return this;\n }\n\n /**\n * Registers an invalid state handler\n *\n * This is a passthrough to [[StateService.onInvalid]] for ng1.\n */\n\n onInvalid(callback: OnInvalidCallback): Function {\n return this.stateService.onInvalid(callback);\n }\n}\n", + "/** @module ng1 */ /** */\nimport {\n StateObject,\n TransitionStateHookFn,\n HookResult,\n Transition,\n services,\n ResolveContext,\n extend,\n BuilderFunction,\n} from '@uirouter/core';\nimport { getLocals } from '../services';\nimport { Ng1StateDeclaration } from '../interface';\n\n/**\n * This is a [[StateBuilder.builder]] function for angular1 `onEnter`, `onExit`,\n * `onRetain` callback hooks on a [[Ng1StateDeclaration]].\n *\n * When the [[StateBuilder]] builds a [[StateObject]] object from a raw [[StateDeclaration]], this builder\n * ensures that those hooks are injectable for @uirouter/angularjs (ng1).\n */\nexport const getStateHookBuilder = (hookName: 'onEnter' | 'onExit' | 'onRetain') =>\n function stateHookBuilder(stateObject: StateObject, parentFn: BuilderFunction): TransitionStateHookFn {\n const hook = stateObject[hookName];\n const pathname = hookName === 'onExit' ? 'from' : 'to';\n\n function decoratedNg1Hook(trans: Transition, state: Ng1StateDeclaration): HookResult {\n const resolveContext = new ResolveContext(trans.treeChanges(pathname));\n const subContext = resolveContext.subContext(state.$$state());\n const locals = extend(getLocals(subContext), { $state$: state, $transition$: trans });\n return services.$injector.invoke(hook, this, locals);\n }\n\n return hook ? decoratedNg1Hook : undefined;\n };\n", + "/**\n * @internalapi\n * @module ng1\n */ /** */\nimport { LocationConfig, LocationServices, UIRouter, ParamType, isDefined } from '@uirouter/core';\nimport { val, createProxyFunctions, removeFrom, isObject } from '@uirouter/core';\nimport { ILocationService, ILocationProvider } from 'angular';\n\n/**\n * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service\n */\nexport class Ng1LocationServices implements LocationConfig, LocationServices {\n private $locationProvider: ILocationProvider;\n private $location: ILocationService;\n private $sniffer;\n\n path;\n search;\n hash;\n hashPrefix;\n port;\n protocol;\n host;\n baseHref;\n\n // .onChange() registry\n private _urlListeners: Function[] = [];\n\n /**\n * Applys ng1-specific path parameter encoding\n *\n * The Angular 1 `$location` service is a bit weird.\n * It doesn't allow slashes to be encoded/decoded bi-directionally.\n *\n * See the writeup at https://github.com/angular-ui/ui-router/issues/2598\n *\n * This code patches the `path` parameter type so it encoded/decodes slashes as ~2F\n *\n * @param router\n */\n static monkeyPatchPathParameterType(router: UIRouter) {\n const pathType: ParamType = router.urlMatcherFactory.type('path');\n\n pathType.encode = (x: any) =>\n x != null ? x.toString().replace(/(~|\\/)/g, m => ({ '~': '~~', '/': '~2F' }[m])) : x;\n\n pathType.decode = (x: string) =>\n x != null ? x.toString().replace(/(~~|~2F)/g, m => ({ '~~': '~', '~2F': '/' }[m])) : x;\n }\n\n dispose() {}\n\n constructor($locationProvider: ILocationProvider) {\n this.$locationProvider = $locationProvider;\n const _lp = val($locationProvider);\n createProxyFunctions(_lp, this, _lp, ['hashPrefix']);\n }\n\n onChange(callback: Function) {\n this._urlListeners.push(callback);\n return () => removeFrom(this._urlListeners)(callback);\n }\n\n html5Mode() {\n let html5Mode: any = this.$locationProvider.html5Mode();\n html5Mode = isObject(html5Mode) ? html5Mode.enabled : html5Mode;\n return html5Mode && this.$sniffer.history;\n }\n\n url(newUrl?: string, replace = false, state?) {\n if (isDefined(newUrl)) this.$location.url(newUrl);\n if (replace) this.$location.replace();\n if (state) this.$location.state(state);\n return this.$location.url();\n }\n\n _runtimeServices($rootScope, $location: ILocationService, $sniffer, $browser) {\n this.$location = $location;\n this.$sniffer = $sniffer;\n\n // Bind $locationChangeSuccess to the listeners registered in LocationService.onChange\n $rootScope.$on('$locationChangeSuccess', evt => this._urlListeners.forEach(fn => fn(evt)));\n const _loc = val($location);\n const _browser = val($browser);\n\n // Bind these LocationService functions to $location\n createProxyFunctions(_loc, this, _loc, ['replace', 'path', 'search', 'hash']);\n // Bind these LocationConfig functions to $location\n createProxyFunctions(_loc, this, _loc, ['port', 'protocol', 'host']);\n // Bind these LocationConfig functions to $browser\n createProxyFunctions(_browser, this, _browser, ['baseHref']);\n }\n}\n", + "/** @module url */ /** */\nimport {\n UIRouter,\n UrlRouter,\n LocationServices,\n $InjectorLike,\n BaseUrlRule,\n UrlRuleHandlerFn,\n UrlMatcher,\n IInjectable,\n} from '@uirouter/core';\nimport { services, isString, isFunction, isArray, identity } from '@uirouter/core';\n\nexport interface RawNg1RuleFunction {\n ($injector: $InjectorLike, $location: LocationServices): string | void;\n}\n\n/**\n * Manages rules for client-side URL\n *\n * ### Deprecation warning:\n * This class is now considered to be an internal API\n * Use the [[UrlService]] instead.\n * For configuring URL rules, use the [[UrlRulesApi]] which can be found as [[UrlService.rules]].\n *\n * This class manages the router rules for what to do when the URL changes.\n *\n * This provider remains for backwards compatibility.\n *\n * @deprecated\n */\nexport class UrlRouterProvider {\n /** @hidden */ _router: UIRouter;\n /** @hidden */ _urlRouter: UrlRouter;\n\n static injectableHandler(router: UIRouter, handler): UrlRuleHandlerFn {\n return match => services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params });\n }\n\n /** @hidden */\n constructor(router: UIRouter) {\n this._router = router;\n this._urlRouter = router.urlRouter;\n }\n\n /** @hidden */\n $get() {\n const urlRouter = this._urlRouter;\n urlRouter.update(true);\n if (!urlRouter.interceptDeferred) urlRouter.listen();\n return urlRouter;\n }\n\n /**\n * Registers a url handler function.\n *\n * Registers a low level url handler (a `rule`).\n * A rule detects specific URL patterns and returns a redirect, or performs some action.\n *\n * If a rule returns a string, the URL is replaced with the string, and all rules are fired again.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Here's an example of how you might allow case insensitive urls\n * $urlRouterProvider.rule(function ($injector, $location) {\n * var path = $location.path(),\n * normalized = path.toLowerCase();\n *\n * if (path !== normalized) {\n * return normalized;\n * }\n * });\n * });\n * ```\n *\n * @param ruleFn\n * Handler function that takes `$injector` and `$location` services as arguments.\n * You can use them to detect a url and return a different url as a string.\n *\n * @return [[UrlRouterProvider]] (`this`)\n */\n rule(ruleFn: RawNg1RuleFunction): UrlRouterProvider {\n if (!isFunction(ruleFn)) throw new Error(\"'rule' must be a function\");\n\n const match = () => ruleFn(services.$injector, this._router.locationService);\n\n const rule = new BaseUrlRule(match, identity);\n this._urlRouter.rule(rule);\n return this;\n }\n\n /**\n * Defines the path or behavior to use when no url can be matched.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // if the path doesn't match any of the urls you configured\n * // otherwise will take care of routing the user to the\n * // specified url\n * $urlRouterProvider.otherwise('/index');\n *\n * // Example of using function rule as param\n * $urlRouterProvider.otherwise(function ($injector, $location) {\n * return '/a/valid/url';\n * });\n * });\n * ```\n *\n * @param rule\n * The url path you want to redirect to or a function rule that returns the url path or performs a `$state.go()`.\n * The function version is passed two params: `$injector` and `$location` services, and should return a url string.\n *\n * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n */\n otherwise(rule: string | RawNg1RuleFunction): UrlRouterProvider {\n const urlRouter = this._urlRouter;\n\n if (isString(rule)) {\n urlRouter.otherwise(rule);\n } else if (isFunction(rule)) {\n urlRouter.otherwise(() => rule(services.$injector, this._router.locationService));\n } else {\n throw new Error(\"'rule' must be a string or function\");\n }\n\n return this;\n }\n\n /**\n * Registers a handler for a given url matching.\n *\n * If the handler is a string, it is\n * treated as a redirect, and is interpolated according to the syntax of match\n * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n *\n * If the handler is a function, it is injectable.\n * It gets invoked if `$location` matches.\n * You have the option of inject the match object as `$match`.\n *\n * The handler can return\n *\n * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n * will continue trying to find another one that matches.\n * - **string** which is treated as a redirect and passed to `$location.url()`\n * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n * if ($state.$current.navigable !== state ||\n * !equalForKeys($match, $stateParams) {\n * $state.transitionTo(state, $match, false);\n * }\n * });\n * });\n * ```\n *\n * @param what A pattern string to match, compiled as a [[UrlMatcher]].\n * @param handler The path (or function that returns a path) that you want to redirect your user to.\n * @param ruleCallback [optional] A callback that receives the `rule` registered with [[UrlMatcher.rule]]\n *\n * Note: the handler may also invoke arbitrary code, such as `$state.go()`\n */\n when(what: RegExp | UrlMatcher | string, handler: string | IInjectable) {\n if (isArray(handler) || isFunction(handler)) {\n handler = UrlRouterProvider.injectableHandler(this._router, handler);\n }\n\n this._urlRouter.when(what, handler as any);\n return this;\n }\n\n /**\n * Disables monitoring of the URL.\n *\n * Call this method before UI-Router has bootstrapped.\n * It will stop UI-Router from performing the initial url sync.\n *\n * This can be useful to perform some asynchronous initialization before the router starts.\n * Once the initialization is complete, call [[listen]] to tell UI-Router to start watching and synchronizing the URL.\n *\n * #### Example:\n * ```js\n * var app = angular.module('app', ['ui.router']);\n *\n * app.config(function ($urlRouterProvider) {\n * // Prevent $urlRouter from automatically intercepting URL changes;\n * $urlRouterProvider.deferIntercept();\n * })\n *\n * app.run(function (MyService, $urlRouter, $http) {\n * $http.get(\"/stuff\").then(function(resp) {\n * MyService.doStuff(resp.data);\n * $urlRouter.listen();\n * $urlRouter.sync();\n * });\n * });\n * ```\n *\n * @param defer Indicates whether to defer location change interception.\n * Passing no parameter is equivalent to `true`.\n */\n deferIntercept(defer?: boolean) {\n this._urlRouter.deferIntercept(defer);\n }\n}\n", + "/**\n * # Angular 1 types\n *\n * UI-Router core provides various Typescript types which you can use for code completion and validating parameter values, etc.\n * The customizations to the core types for Angular UI-Router are documented here.\n *\n * The optional [[$resolve]] service is also documented here.\n *\n * @module ng1\n * @preferred\n */\n/** for typedoc */\nimport { ng as angular } from './angular';\nimport {\n IRootScopeService,\n IQService,\n ILocationService,\n ILocationProvider,\n IHttpService,\n ITemplateCacheService,\n} from 'angular';\nimport {\n services,\n applyPairs,\n isString,\n trace,\n extend,\n UIRouter,\n StateService,\n UrlRouter,\n UrlMatcherFactory,\n ResolveContext,\n unnestR,\n TypedMap,\n} from '@uirouter/core';\nimport { ng1ViewsBuilder, getNg1ViewConfigFactory } from './statebuilders/views';\nimport { TemplateFactory } from './templateFactory';\nimport { StateProvider } from './stateProvider';\nimport { getStateHookBuilder } from './statebuilders/onEnterExitRetain';\nimport { Ng1LocationServices } from './locationServices';\nimport { UrlRouterProvider } from './urlRouterProvider';\nimport IInjectorService = angular.auto.IInjectorService; // tslint:disable-line\n\nangular.module('ui.router.angular1', []);\nconst mod_init = angular.module('ui.router.init', []);\nconst mod_util = angular.module('ui.router.util', ['ng', 'ui.router.init']);\nconst mod_rtr = angular.module('ui.router.router', ['ui.router.util']);\nconst mod_state = angular.module('ui.router.state', ['ui.router.router', 'ui.router.util', 'ui.router.angular1']);\nconst mod_main = angular.module('ui.router', ['ui.router.init', 'ui.router.state', 'ui.router.angular1']);\nlet mod_cmpt = angular.module('ui.router.compat', ['ui.router']); // tslint:disable-line\n\ndeclare module '@uirouter/core/lib/router' {\n interface UIRouter {\n // tslint:disable-line:no-shadowed-variable\n /** @hidden */\n stateProvider: StateProvider;\n /** @hidden */\n urlRouterProvider: UrlRouterProvider;\n }\n}\n\nlet router: UIRouter = null;\n\n$uiRouterProvider.$inject = ['$locationProvider'];\n/** This angular 1 provider instantiates a Router and exposes its services via the angular injector */\nfunction $uiRouterProvider($locationProvider: ILocationProvider) {\n // Create a new instance of the Router when the $uiRouterProvider is initialized\n router = this.router = new UIRouter();\n router.stateProvider = new StateProvider(router.stateRegistry, router.stateService);\n\n // Apply ng1 specific StateBuilder code for `views`, `resolve`, and `onExit/Retain/Enter` properties\n router.stateRegistry.decorator('views', ng1ViewsBuilder);\n router.stateRegistry.decorator('onExit', getStateHookBuilder('onExit'));\n router.stateRegistry.decorator('onRetain', getStateHookBuilder('onRetain'));\n router.stateRegistry.decorator('onEnter', getStateHookBuilder('onEnter'));\n\n router.viewService._pluginapi._viewConfigFactory('ng1', getNg1ViewConfigFactory());\n\n const ng1LocationService = (router.locationService = router.locationConfig = new Ng1LocationServices(\n $locationProvider,\n ));\n\n Ng1LocationServices.monkeyPatchPathParameterType(router);\n\n // backwards compat: also expose router instance as $uiRouterProvider.router\n router['router'] = router;\n router['$get'] = $get;\n $get.$inject = ['$location', '$browser', '$sniffer', '$rootScope', '$http', '$templateCache'];\n function $get(\n $location: ILocationService,\n $browser: any,\n $sniffer: any,\n $rootScope: ng.IScope,\n $http: IHttpService,\n $templateCache: ITemplateCacheService,\n ) {\n ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser);\n delete router['router'];\n delete router['$get'];\n return router;\n }\n return router;\n}\n\nconst getProviderFor = serviceName => [\n '$uiRouterProvider',\n $urp => {\n const service = $urp.router[serviceName];\n service['$get'] = () => service;\n return service;\n },\n];\n\n// This effectively calls $get() on `$uiRouterProvider` to trigger init (when ng enters runtime)\nrunBlock.$inject = ['$injector', '$q', '$uiRouter'];\nfunction runBlock($injector: IInjectorService, $q: IQService, $uiRouter: UIRouter) {\n services.$injector = $injector;\n services.$q = $q;\n\n // The $injector is now available.\n // Find any resolvables that had dependency annotation deferred\n $uiRouter.stateRegistry\n .get()\n .map(x => x.$$state().resolvables)\n .reduce(unnestR, [])\n .filter(x => x.deps === 'deferred')\n .forEach(resolvable => (resolvable.deps = $injector.annotate(resolvable.resolveFn, $injector.strictDi)));\n}\n\n// $urlRouter service and $urlRouterProvider\nconst getUrlRouterProvider = (uiRouter: UIRouter) => (uiRouter.urlRouterProvider = new UrlRouterProvider(uiRouter));\n\n// $state service and $stateProvider\n// $urlRouter service and $urlRouterProvider\nconst getStateProvider = () => extend(router.stateProvider, { $get: () => router.stateService });\n\nwatchDigests.$inject = ['$rootScope'];\nexport function watchDigests($rootScope: IRootScopeService) {\n $rootScope.$watch(function() {\n trace.approximateDigests++;\n });\n}\n\nmod_init.provider('$uiRouter', $uiRouterProvider);\nmod_rtr.provider('$urlRouter', ['$uiRouterProvider', getUrlRouterProvider]);\nmod_util.provider('$urlService', getProviderFor('urlService'));\nmod_util.provider('$urlMatcherFactory', ['$uiRouterProvider', () => router.urlMatcherFactory]);\nmod_util.provider('$templateFactory', () => new TemplateFactory());\nmod_state.provider('$stateRegistry', getProviderFor('stateRegistry'));\nmod_state.provider('$uiRouterGlobals', getProviderFor('globals'));\nmod_state.provider('$transitions', getProviderFor('transitionService'));\nmod_state.provider('$state', ['$uiRouterProvider', getStateProvider]);\n\nmod_state.factory('$stateParams', ['$uiRouter', ($uiRouter: UIRouter) => $uiRouter.globals.params]);\nmod_main.factory('$view', () => router.viewService);\nmod_main.service('$trace', () => trace);\n\nmod_main.run(watchDigests);\nmod_util.run(['$urlMatcherFactory', function($urlMatcherFactory: UrlMatcherFactory) {}]);\nmod_state.run(['$state', function($state: StateService) {}]);\nmod_rtr.run(['$urlRouter', function($urlRouter: UrlRouter) {}]);\nmod_init.run(runBlock);\n\n/** @hidden TODO: find a place to move this */\nexport const getLocals = (ctx: ResolveContext): TypedMap => {\n const tokens = ctx.getTokens().filter(isString);\n\n const tuples = tokens.map(key => {\n const resolvable = ctx.getResolvable(key);\n const waitPolicy = ctx.getPolicy(resolvable).async;\n return [key, waitPolicy === 'NOWAIT' ? resolvable.promise : resolvable.data];\n });\n\n return tuples.reduce(applyPairs, {});\n};\n", + "/**\n * # Angular 1 Directives\n *\n * These are the directives included in UI-Router for Angular 1.\n * These directives are used in templates to create viewports and link/navigate to states.\n *\n * @ng1api\n * @preferred\n * @module directives\n */ /** for typedoc */\nimport { ng as angular } from '../angular';\nimport { IAugmentedJQuery, ITimeoutService, IScope, IInterpolateService } from 'angular';\n\nimport {\n Obj,\n extend,\n forEach,\n tail,\n isString,\n isObject,\n isArray,\n parse,\n noop,\n unnestR,\n identity,\n uniqR,\n inArray,\n removeFrom,\n RawParams,\n PathNode,\n StateOrName,\n StateService,\n StateDeclaration,\n UIRouter,\n} from '@uirouter/core';\nimport { UIViewData } from './viewDirective';\nimport EventHandler = JQuery.EventHandler;\n\n/** @hidden Used for typedoc */\nexport interface ng1_directive {} // tslint:disable-line:class-name\n\n/** @hidden */\nfunction parseStateRef(ref: string) {\n let parsed;\n const paramsOnly = ref.match(/^\\s*({[^}]*})\\s*$/);\n if (paramsOnly) ref = '(' + paramsOnly[1] + ')';\n\n parsed = ref.replace(/\\n/g, ' ').match(/^\\s*([^(]*?)\\s*(\\((.*)\\))?\\s*$/);\n if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n return { state: parsed[1] || null, paramExpr: parsed[3] || null };\n}\n\n/** @hidden */\nfunction stateContext(el: IAugmentedJQuery) {\n const $uiView: UIViewData = (el.parent() as IAugmentedJQuery).inheritedData('$uiView');\n const path: PathNode[] = parse('$cfg.path')($uiView);\n return path ? tail(path).state.name : undefined;\n}\n\n/** @hidden */\nfunction processedDef($state: StateService, $element: IAugmentedJQuery, def: Def): Def {\n const uiState = def.uiState || $state.current.name;\n const uiStateOpts = extend(defaultOpts($element, $state), def.uiStateOpts || {});\n const href = $state.href(uiState, def.uiStateParams, uiStateOpts);\n return { uiState, uiStateParams: def.uiStateParams, uiStateOpts, href };\n}\n\n/** @hidden */\ninterface TypeInfo {\n attr: string;\n isAnchor: boolean;\n clickable: boolean;\n}\n\n/** @hidden */\nfunction getTypeInfo(el: IAugmentedJQuery): TypeInfo {\n // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n const isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';\n const isForm = el[0].nodeName === 'FORM';\n\n return {\n attr: isForm ? 'action' : isSvg ? 'xlink:href' : 'href',\n isAnchor: el.prop('tagName').toUpperCase() === 'A',\n clickable: !isForm,\n };\n}\n\n/** @hidden */\nfunction clickHook(\n el: IAugmentedJQuery,\n $state: StateService,\n $timeout: ITimeoutService,\n type: TypeInfo,\n getDef: () => Def,\n) {\n return function(e: JQueryMouseEventObject) {\n const button = e.which || e.button,\n target = getDef();\n\n if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {\n // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n const transition = $timeout(function() {\n $state.go(target.uiState, target.uiStateParams, target.uiStateOpts);\n });\n e.preventDefault();\n\n // if the state has no URL, ignore one preventDefault from the directive.\n let ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;\n\n e.preventDefault = function() {\n if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);\n };\n }\n };\n}\n\n/** @hidden */\nfunction defaultOpts(el: IAugmentedJQuery, $state: StateService) {\n return {\n relative: stateContext(el) || $state.$current,\n inherit: true,\n source: 'sref',\n };\n}\n\n/** @hidden */\nfunction bindEvents(element: IAugmentedJQuery, scope: IScope, hookFn: EventHandler, uiStateOpts: any): void {\n let events;\n\n if (uiStateOpts) {\n events = uiStateOpts.events;\n }\n\n if (!isArray(events)) {\n events = ['click'];\n }\n\n const on = element.on ? 'on' : 'bind';\n for (const event of events) {\n element[on](event, hookFn);\n }\n\n scope.$on('$destroy', function() {\n const off = element.off ? 'off' : 'unbind';\n for (const event of events) {\n element[off](event, hookFn);\n }\n });\n}\n\n/**\n * `ui-sref`: A directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of the `ui-sref` is the name of the state to link to.\n *\n * #### Example:\n * This will activate the `home` state when the link is clicked.\n * ```html\n * Home\n * ```\n *\n * ### Relative Links\n * You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]).\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create a relative `ui-sref` which always targets the same destination.\n *\n * #### Example:\n * Both these links are relative to the parent state, even when a child state is currently active.\n * ```html\n * child 1 state\n * child 2 state\n * ```\n *\n * This link activates the parent state.\n * ```html\n * Return\n * ```\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * #### Example:\n * Assuming the `users` state has a url of `/users/`\n * ```html\n * Users\n * ```\n *\n * ### Parameter Values\n * In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state.\n * Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses.\n * The content inside the parentheses is an expression, evaluated to the parameter values.\n *\n * #### Example:\n * This example renders a list of links to users.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ user.displayName }}\n *
  • \n * ```\n *\n * Note:\n * The parameter values expression is `$watch`ed for updates.\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-sref-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Examples\n * If you have the following template:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n * \n * ```\n *\n * Then (assuming the current state is `contacts`) the rendered html including hrefs would be:\n *\n * ```html\n * Home\n * About\n * Next page\n *\n *
      \n *
    • \n * Joe\n *
    • \n *
    • \n * Alice\n *
    • \n *
    • \n * Bob\n *
    • \n *
    \n *\n * Home\n * ```\n *\n * ### Notes\n *\n * - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses.\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n *\n * - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons).\n * If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive.\n */\nlet uiSrefDirective: ng1_directive;\nuiSrefDirective = [\n '$uiRouter',\n '$timeout',\n function $StateRefDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function(scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const ref = parseStateRef(attrs.uiSref);\n rawDef.uiState = ref.state;\n rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {};\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n if (ref.paramExpr) {\n scope.$watch(\n ref.paramExpr,\n function(val) {\n rawDef.uiStateParams = extend({}, val);\n update();\n },\n true,\n );\n rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr));\n }\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n },\n];\n\n/**\n * `ui-state`: A fully dynamic directive for linking to a state\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.**\n *\n * A directive which links to a state (and optionally, parameters).\n * When clicked, this directive activates the linked state with the supplied parameter values.\n *\n * ### Linked State\n * The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to.\n * **This is in contrast with `ui-sref`, which takes a state name as a string literal.**\n *\n * #### Example:\n * Create a list of links.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Relative Links\n * If the expression evaluates to a relative path, it is processed like [[uiSref]].\n * You just need to be aware that the path is relative to the state that *created* the link.\n * This allows a state to create relative `ui-state` which always targets the same destination.\n *\n * ### hrefs\n * If the linked state has a URL, the directive will automatically generate and\n * update the `href` attribute (using the [[StateService.href]] method).\n *\n * ### Parameter Values\n * In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state.\n * Param values should be provided using the `ui-state-params` attribute.\n * The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * This example renders a list of links with param values.\n * The state's `userId` parameter value comes from each user's `user.id` property.\n * ```html\n *
  • \n * {{ link.displayName }}\n *
  • \n * ```\n *\n * ### Transition Options\n * You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute.\n * Options are restricted to `location`, `inherit`, and `reload`.\n * The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression.\n *\n * #### Example:\n * ```html\n * Home\n * ```\n *\n * ### Other DOM Events\n *\n * You can also customize which DOM events to respond to (instead of `click`) by\n * providing an `events` array in the `ui-state-opts` attribute.\n *\n * #### Example:\n * ```html\n * \n * ```\n *\n * ### Highlighting the active link\n * This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.\n *\n * ### Notes\n *\n * - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`.\n * However, it might be simpler to use [[uiSref]] parameter-only links.\n *\n * #### Example:\n * Sets the `lang` parameter to `en` and remains on the same state.\n *\n * ```html\n * English\n * ```\n *\n * - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.\n * ```\n */\nlet uiStateDirective: ng1_directive;\nuiStateDirective = [\n '$uiRouter',\n '$timeout',\n function $StateRefDynamicDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {\n const $state = $uiRouter.stateService;\n\n return {\n restrict: 'A',\n require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n link: function(scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {\n const type = getTypeInfo(element);\n const active = uiSrefActive[1] || uiSrefActive[0];\n let unlinkInfoFn: Function = null;\n let hookFn;\n\n const rawDef = {} as Def;\n const getDef = () => processedDef($state, element, rawDef);\n\n const inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts'];\n const watchDeregFns = inputAttrs.reduce((acc, attr) => ((acc[attr] = noop), acc), {});\n\n function update() {\n const def = getDef();\n if (unlinkInfoFn) unlinkInfoFn();\n if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);\n if (def.href != null) attrs.$set(type.attr, def.href);\n }\n\n inputAttrs.forEach(field => {\n rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null;\n\n attrs.$observe(field, expr => {\n watchDeregFns[field]();\n watchDeregFns[field] = scope.$watch(\n expr,\n newval => {\n rawDef[field] = newval;\n update();\n },\n true,\n );\n });\n });\n\n update();\n\n scope.$on('$destroy', $uiRouter.stateRegistry.onStatesChanged(update));\n scope.$on('$destroy', $uiRouter.transitionService.onSuccess({}, update));\n\n if (!type.clickable) return;\n hookFn = clickHook(element, $state, $timeout, type, getDef);\n bindEvents(element, scope, hookFn, rawDef.uiStateOpts);\n },\n };\n },\n];\n\n/**\n * `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active\n *\n * A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the\n * related directive's state is active (and remove them when it is inactive).\n *\n * The primary use-case is to highlight the active link in navigation menus,\n * distinguishing it from the inactive menu items.\n *\n * ### Linking to a `ui-sref` or `ui-state`\n * `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element.\n * If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**.\n *\n * ### Matching\n *\n * The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**.\n * This is a \"fuzzy match\" which uses [[StateService.includes]].\n *\n * The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active).\n * This is an \"exact match\" which uses [[StateService.is]].\n *\n * ### Parameter values\n * If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted.\n * This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted.\n *\n * #### Example:\n * ```html\n *
  • \n * {{ user.lastName }}\n *
  • \n * ```\n *\n * ### Examples\n *\n * Given the following template:\n * #### Example:\n * ```html\n * \n * ```\n *\n * When the app state is `app.user` (or any child state),\n * and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n *\n * ```html\n * \n * ```\n *\n * ### Glob mode\n *\n * It is possible to pass `ui-sref-active` an expression that evaluates to an object.\n * The objects keys represent active class names and values represent the respective state names/globs.\n * `ui-sref-active` will match if the current active state **includes** any of\n * the specified state names/globs, even the abstract ones.\n *\n * #### Example:\n * Given the following template, with \"admin\" being an abstract state:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * Arrays are also supported as values in the `ngClass`-like interface.\n * This allows multiple states to add `active` class.\n *\n * #### Example:\n * Given the following template, with \"admin.roles\" being the current state, the class will be added too:\n * ```html\n *
    \n * Roles\n *
    \n * ```\n *\n * When the current state is \"admin.roles\" the \"active\" class will be applied to both the `
    ` and `` elements.\n * It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`.\n *\n * ### Notes:\n *\n * - The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'`\n */\nlet uiSrefActiveDirective: ng1_directive;\nuiSrefActiveDirective = [\n '$state',\n '$stateParams',\n '$interpolate',\n '$uiRouter',\n function $StateRefActiveDirective(\n $state: StateService,\n $stateParams: Obj,\n $interpolate: IInterpolateService,\n $uiRouter: UIRouter,\n ) {\n return {\n restrict: 'A',\n controller: [\n '$scope',\n '$element',\n '$attrs',\n function($scope: IScope, $element: IAugmentedJQuery, $attrs: any) {\n let states: StateData[] = [];\n let activeEqClass: string;\n let uiSrefActive: any;\n\n // There probably isn't much point in $observing this\n // uiSrefActive and uiSrefActiveEq share the same directive object with some\n // slight difference in logic routing\n activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);\n\n try {\n uiSrefActive = $scope.$eval($attrs.uiSrefActive);\n } catch (e) {\n // Do nothing. uiSrefActive is not a valid expression.\n // Fall back to using $interpolate below\n }\n uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);\n setStatesFromDefinitionObject(uiSrefActive);\n\n // Allow uiSref to communicate with uiSrefActive[Equals]\n this.$$addStateInfo = function(newState: string, newParams: Obj) {\n // we already got an explicit state provided by ui-sref-active, so we\n // shadow the one that comes from ui-sref\n if (isObject(uiSrefActive) && states.length > 0) {\n return;\n }\n const deregister = addState(newState, newParams, uiSrefActive);\n update();\n return deregister;\n };\n\n function updateAfterTransition(trans) {\n trans.promise.then(update, noop);\n }\n $scope.$on('$destroy', setupEventListeners());\n if ($uiRouter.globals.transition) {\n updateAfterTransition($uiRouter.globals.transition);\n }\n\n function setupEventListeners() {\n const deregisterStatesChangedListener = $uiRouter.stateRegistry.onStatesChanged(handleStatesChanged);\n const deregisterOnStartListener = $uiRouter.transitionService.onStart({}, updateAfterTransition);\n const deregisterStateChangeSuccessListener = $scope.$on('$stateChangeSuccess', update);\n return function cleanUp() {\n deregisterStatesChangedListener();\n deregisterOnStartListener();\n deregisterStateChangeSuccessListener();\n };\n }\n\n function handleStatesChanged() {\n setStatesFromDefinitionObject(uiSrefActive);\n }\n\n function setStatesFromDefinitionObject(statesDefinition: object) {\n if (isObject(statesDefinition)) {\n states = [];\n forEach(statesDefinition, function(stateOrName: StateOrName | Array, activeClass: string) {\n // Helper function to abstract adding state.\n const addStateForClass = function(stateOrName: string, activeClass: string) {\n const ref = parseStateRef(stateOrName);\n addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);\n };\n\n if (isString(stateOrName)) {\n // If state is string, just add it.\n addStateForClass(stateOrName as string, activeClass);\n } else if (isArray(stateOrName)) {\n // If state is an array, iterate over it and add each array item individually.\n forEach(stateOrName, function(stateOrName: string) {\n addStateForClass(stateOrName, activeClass);\n });\n }\n });\n }\n }\n\n function addState(stateName: string, stateParams: Obj, activeClass: string) {\n const state = $state.get(stateName, stateContext($element));\n\n const stateInfo = {\n state: state || { name: stateName },\n params: stateParams,\n activeClass: activeClass,\n };\n\n states.push(stateInfo);\n\n return function removeState() {\n removeFrom(states)(stateInfo);\n };\n }\n\n // Update route state\n function update() {\n const splitClasses = str => str.split(/\\s/).filter(identity);\n const getClasses = (stateList: StateData[]) =>\n stateList\n .map(x => x.activeClass)\n .map(splitClasses)\n .reduce(unnestR, []);\n\n const allClasses = getClasses(states)\n .concat(splitClasses(activeEqClass))\n .reduce(uniqR, []);\n const fuzzyClasses = getClasses(states.filter(x => $state.includes(x.state.name, x.params)));\n const exactlyMatchesAny = !!states.filter(x => $state.is(x.state.name, x.params)).length;\n const exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : [];\n\n const addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []);\n const removeClasses = allClasses.filter(cls => !inArray(addClasses, cls));\n\n $scope.$evalAsync(() => {\n addClasses.forEach(className => $element.addClass(className));\n removeClasses.forEach(className => $element.removeClass(className));\n });\n }\n\n update();\n },\n ],\n };\n },\n];\n\n/** @hidden */\ninterface Def {\n uiState: string;\n href: string;\n uiStateParams: Obj;\n uiStateOpts: any;\n}\n/** @hidden */\ninterface StateData {\n state: StateDeclaration;\n params: RawParams;\n activeClass: string;\n}\n\nangular\n .module('ui.router.state')\n .directive('uiSref', uiSrefDirective)\n .directive('uiSrefActive', uiSrefActiveDirective)\n .directive('uiSrefActiveEq', uiSrefActiveDirective)\n .directive('uiState', uiStateDirective);\n", + "/**\n * @ng1api\n * @module directives\n */\n\nimport {\n $QLike,\n ActiveUIView,\n extend,\n filter,\n HookRegOptions,\n isDefined,\n isFunction,\n isString,\n kebobString,\n noop,\n Obj,\n Param,\n parse,\n PathNode,\n ResolveContext,\n StateDeclaration,\n tail,\n trace,\n Transition,\n TransitionService,\n TypedMap,\n unnestR,\n ViewService,\n} from '@uirouter/core';\nimport { IAugmentedJQuery, IInterpolateService, IScope, ITimeoutService, ITranscludeFunction } from 'angular';\nimport { ng as angular } from '../angular';\nimport { Ng1Controller, Ng1StateDeclaration } from '../interface';\nimport { getLocals } from '../services';\nimport { Ng1ViewConfig } from '../statebuilders/views';\nimport { ng1_directive } from './stateDirectives';\n\n/** @hidden */\nexport type UIViewData = {\n $cfg: Ng1ViewConfig;\n $uiView: ActiveUIView;\n};\n\n/** @hidden */\nexport type UIViewAnimData = {\n $animEnter: Promise;\n $animLeave: Promise;\n $$animLeave: { resolve: () => any }; // \"deferred\"\n};\n\n/**\n * `ui-view`: A viewport directive which is filled in by a view from the active state.\n *\n * ### Attributes\n *\n * - `name`: (Optional) A view name.\n * The name should be unique amongst the other views in the same state.\n * You can have views of the same name that live in different states.\n * The ui-view can be targeted in a View using the name ([[Ng1StateDeclaration.views]]).\n *\n * - `autoscroll`: an expression. When it evaluates to true, the `ui-view` will be scrolled into view when it is activated.\n * Uses [[$uiViewScroll]] to do the scrolling.\n *\n * - `onload`: Expression to evaluate whenever the view updates.\n *\n * #### Example:\n * A view can be unnamed or named.\n * ```html\n * \n *
    \n *\n * \n *
    \n *\n * \n * \n * ```\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a\n * single view and it is unnamed then you can populate it like so:\n *\n * ```html\n *
    \n * $stateProvider.state(\"home\", {\n * template: \"

    HELLO!

    \"\n * })\n * ```\n *\n * The above is a convenient shortcut equivalent to specifying your view explicitly with the\n * [[Ng1StateDeclaration.views]] config property, by name, in this case an empty name:\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * But typically you'll only use the views property if you name your view or have more than one view\n * in the same template. There's not really a compelling reason to name a view if its the only one,\n * but you could if you wanted, like so:\n *\n * ```html\n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"main\": {\n * template: \"

    HELLO!

    \"\n * }\n * }\n * })\n * ```\n *\n * Really though, you'll use views to set up multiple views:\n *\n * ```html\n *
    \n *
    \n *
    \n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"

    HELLO!

    \"\n * },\n * \"chart\": {\n * template: \"\"\n * },\n * \"data\": {\n * template: \"\"\n * }\n * }\n * })\n * ```\n *\n * #### Examples for `autoscroll`:\n * ```html\n * \n * \n *\n * \n * \n * \n * \n * ```\n *\n * Resolve data:\n *\n * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this\n * can be customized using [[Ng1ViewDeclaration.resolveAs]]). This can be then accessed from the template.\n *\n * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the\n * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which\n * depends on `$resolve` data.\n *\n * #### Example:\n * ```js\n * $stateProvider.state('home', {\n * template: '',\n * resolve: {\n * user: function(UserService) { return UserService.fetchUser(); }\n * }\n * });\n * ```\n */\nexport let uiView: ng1_directive;\nuiView = [\n '$view',\n '$animate',\n '$uiViewScroll',\n '$interpolate',\n '$q',\n function $ViewDirective(\n $view: ViewService,\n $animate: any,\n $uiViewScroll: any,\n $interpolate: IInterpolateService,\n $q: $QLike,\n ) {\n function getRenderer(attrs: Obj, scope: IScope) {\n return {\n enter: function(element: JQuery, target: any, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.enter(element, null, target).then(cb);\n } else {\n $animate.enter(element, null, target, cb);\n }\n },\n leave: function(element: JQuery, cb: Function) {\n if (angular.version.minor > 2) {\n $animate.leave(element).then(cb);\n } else {\n $animate.leave(element, cb);\n }\n },\n };\n }\n\n function configsEqual(config1: Ng1ViewConfig, config2: Ng1ViewConfig) {\n return config1 === config2;\n }\n\n const rootData = {\n $cfg: { viewDecl: { $context: $view._pluginapi._rootViewContext() } },\n $uiView: {},\n };\n\n const directive = {\n count: 0,\n restrict: 'ECA',\n terminal: true,\n priority: 400,\n transclude: 'element',\n compile: function(tElement: JQuery, tAttrs: Obj, $transclude: ITranscludeFunction) {\n return function(scope: IScope, $element: IAugmentedJQuery, attrs: Obj) {\n const onloadExp = attrs['onload'] || '',\n autoScrollExp = attrs['autoscroll'],\n renderer = getRenderer(attrs, scope),\n inherited = $element.inheritedData('$uiView') || rootData,\n name = $interpolate(attrs['uiView'] || attrs['name'] || '')(scope) || '$default';\n\n let previousEl: JQuery,\n currentEl: JQuery,\n currentScope: IScope,\n viewConfig: Ng1ViewConfig,\n unregister: Function;\n\n const activeUIView: ActiveUIView = {\n $type: 'ng1',\n id: directive.count++, // Global sequential ID for ui-view tags added to DOM\n name: name, // ui-view name (
    \n fqn: inherited.$uiView.fqn ? inherited.$uiView.fqn + '.' + name : name, // fully qualified name, describes location in DOM\n config: null, // The ViewConfig loaded (from a state.views definition)\n configUpdated: configUpdatedCallback, // Called when the matching ViewConfig changes\n get creationContext() {\n // The context in which this ui-view \"tag\" was created\n const fromParentTagConfig = parse('$cfg.viewDecl.$context')(inherited);\n // Allow \n // See https://github.com/angular-ui/ui-router/issues/3355\n const fromParentTag = parse('$uiView.creationContext')(inherited);\n return fromParentTagConfig || fromParentTag;\n },\n };\n\n trace.traceUIViewEvent('Linking', activeUIView);\n\n function configUpdatedCallback(config?: Ng1ViewConfig) {\n if (config && !(config instanceof Ng1ViewConfig)) return;\n if (configsEqual(viewConfig, config)) return;\n trace.traceUIViewConfigUpdated(activeUIView, config && config.viewDecl && config.viewDecl.$context);\n\n viewConfig = config;\n updateView(config);\n }\n\n $element.data('$uiView', { $uiView: activeUIView });\n\n updateView();\n\n unregister = $view.registerUIView(activeUIView);\n scope.$on('$destroy', function() {\n trace.traceUIViewEvent('Destroying/Unregistering', activeUIView);\n unregister();\n });\n\n function cleanupLastView() {\n if (previousEl) {\n trace.traceUIViewEvent('Removing (previous) el', previousEl.data('$uiView'));\n previousEl.remove();\n previousEl = null;\n }\n\n if (currentScope) {\n trace.traceUIViewEvent('Destroying scope', activeUIView);\n currentScope.$destroy();\n currentScope = null;\n }\n\n if (currentEl) {\n const _viewData = currentEl.data('$uiViewAnim');\n trace.traceUIViewEvent('Animate out', _viewData);\n renderer.leave(currentEl, function() {\n _viewData.$$animLeave.resolve();\n previousEl = null;\n });\n\n previousEl = currentEl;\n currentEl = null;\n }\n }\n\n function updateView(config?: Ng1ViewConfig) {\n const newScope = scope.$new();\n const animEnter = $q.defer(),\n animLeave = $q.defer();\n\n const $uiViewData: UIViewData = {\n $cfg: config,\n $uiView: activeUIView,\n };\n\n const $uiViewAnim: UIViewAnimData = {\n $animEnter: animEnter.promise,\n $animLeave: animLeave.promise,\n $$animLeave: animLeave,\n };\n\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoading\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description\n *\n * Fired once the view **begins loading**, *before* the DOM is rendered.\n *\n * @param {Object} event Event object.\n * @param {string} viewName Name of the view.\n */\n newScope.$emit('$viewContentLoading', name);\n\n const cloned = $transclude(newScope, function(clone) {\n clone.data('$uiViewAnim', $uiViewAnim);\n clone.data('$uiView', $uiViewData);\n renderer.enter(clone, $element, function onUIViewEnter() {\n animEnter.resolve();\n if (currentScope) currentScope.$emit('$viewContentAnimationEnded');\n\n if ((isDefined(autoScrollExp) && !autoScrollExp) || scope.$eval(autoScrollExp)) {\n $uiViewScroll(clone);\n }\n });\n\n cleanupLastView();\n });\n\n currentEl = cloned;\n currentScope = newScope;\n /**\n * @ngdoc event\n * @name ui.router.state.directive:ui-view#$viewContentLoaded\n * @eventOf ui.router.state.directive:ui-view\n * @eventType emits on ui-view directive scope\n * @description *\n * Fired once the view is **loaded**, *after* the DOM is rendered.\n *\n * @param {Object} event Event object.\n */\n currentScope.$emit('$viewContentLoaded', config || viewConfig);\n currentScope.$eval(onloadExp);\n }\n };\n },\n };\n\n return directive;\n },\n];\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$transitions', '$view', '$q', '$timeout'];\n\n/** @hidden */\nfunction $ViewDirectiveFill(\n $compile: angular.ICompileService,\n $controller: angular.IControllerService,\n $transitions: TransitionService,\n $view: ViewService,\n $q: angular.IQService,\n $timeout: ITimeoutService,\n) {\n const getControllerAs = parse('viewDecl.controllerAs');\n const getResolveAs = parse('viewDecl.resolveAs');\n\n return {\n restrict: 'ECA',\n priority: -400,\n compile: function(tElement: JQuery) {\n const initial = tElement.html();\n tElement.empty();\n\n return function(scope: IScope, $element: JQuery) {\n const data: UIViewData = $element.data('$uiView');\n if (!data) {\n $element.html(initial);\n $compile($element.contents() as any)(scope);\n return;\n }\n\n const cfg: Ng1ViewConfig = data.$cfg || { viewDecl: {}, getTemplate: noop };\n const resolveCtx: ResolveContext = cfg.path && new ResolveContext(cfg.path);\n $element.html(cfg.getTemplate($element, resolveCtx) || initial);\n trace.traceUIViewFill(data.$uiView, $element.html());\n\n const link = $compile($element.contents() as any);\n const controller = cfg.controller;\n const controllerAs: string = getControllerAs(cfg);\n const resolveAs: string = getResolveAs(cfg);\n const locals = resolveCtx && getLocals(resolveCtx);\n\n scope[resolveAs] = locals;\n\n if (controller) {\n const controllerInstance = $controller(\n controller,\n extend({}, locals, { $scope: scope, $element: $element }),\n );\n if (controllerAs) {\n scope[controllerAs] = controllerInstance;\n scope[controllerAs][resolveAs] = locals;\n }\n\n // TODO: Use $view service as a central point for registering component-level hooks\n // Then, when a component is created, tell the $view service, so it can invoke hooks\n // $view.componentLoaded(controllerInstance, { $scope: scope, $element: $element });\n // scope.$on('$destroy', () => $view.componentUnloaded(controllerInstance, { $scope: scope, $element: $element }));\n\n $element.data('$ngControllerController', controllerInstance);\n $element.children().data('$ngControllerController', controllerInstance);\n\n registerControllerCallbacks($q, $transitions, controllerInstance, scope, cfg);\n }\n\n // Wait for the component to appear in the DOM\n if (isString(cfg.viewDecl.component)) {\n const cmp = cfg.viewDecl.component;\n const kebobName = kebobString(cmp);\n const tagRegexp = new RegExp(`^(x-|data-)?${kebobName}$`, 'i');\n\n const getComponentController = () => {\n const directiveEl = [].slice\n .call($element[0].children)\n .filter((el: Element) => el && el.tagName && tagRegexp.exec(el.tagName));\n\n return directiveEl && angular.element(directiveEl).data(`$${cmp}Controller`);\n };\n\n const deregisterWatch = scope.$watch(getComponentController, function(ctrlInstance) {\n if (!ctrlInstance) return;\n registerControllerCallbacks($q, $transitions, ctrlInstance, scope, cfg);\n deregisterWatch();\n });\n }\n\n link(scope);\n };\n },\n };\n}\n\n/** @hidden */\nconst hasComponentImpl = typeof (angular as any).module('ui.router')['component'] === 'function';\n/** @hidden incrementing id */\nlet _uiCanExitId = 0;\n\n/** @hidden TODO: move these callbacks to $view and/or `/hooks/components.ts` or something */\nfunction registerControllerCallbacks(\n $q: angular.IQService,\n $transitions: TransitionService,\n controllerInstance: Ng1Controller,\n $scope: IScope,\n cfg: Ng1ViewConfig,\n) {\n // Call $onInit() ASAP\n if (isFunction(controllerInstance.$onInit) && !(cfg.viewDecl.component && hasComponentImpl)) {\n controllerInstance.$onInit();\n }\n\n const viewState: Ng1StateDeclaration = tail(cfg.path).state.self;\n\n const hookOptions: HookRegOptions = { bind: controllerInstance };\n // Add component-level hook for onUiParamsChanged\n if (isFunction(controllerInstance.uiOnParamsChanged)) {\n const resolveContext: ResolveContext = new ResolveContext(cfg.path);\n const viewCreationTrans = resolveContext.getResolvable('$transition$').data;\n\n // Fire callback on any successful transition\n const paramsUpdated = ($transition$: Transition) => {\n // Exit early if the $transition$ is the same as the view was created within.\n // Exit early if the $transition$ will exit the state the view is for.\n if ($transition$ === viewCreationTrans || $transition$.exiting().indexOf(viewState as StateDeclaration) !== -1)\n return;\n\n const toParams = $transition$.params('to') as TypedMap;\n const fromParams = $transition$.params>('from') as TypedMap;\n const getNodeSchema = (node: PathNode) => node.paramSchema;\n const toSchema: Param[] = $transition$\n .treeChanges('to')\n .map(getNodeSchema)\n .reduce(unnestR, []);\n const fromSchema: Param[] = $transition$\n .treeChanges('from')\n .map(getNodeSchema)\n .reduce(unnestR, []);\n\n // Find the to params that have different values than the from params\n const changedToParams = toSchema.filter((param: Param) => {\n const idx = fromSchema.indexOf(param);\n return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]);\n });\n\n // Only trigger callback if a to param has changed or is new\n if (changedToParams.length) {\n const changedKeys: string[] = changedToParams.map(x => x.id);\n // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params.\n const newValues = filter(toParams, (val, key) => changedKeys.indexOf(key) !== -1);\n controllerInstance.uiOnParamsChanged(newValues, $transition$);\n }\n };\n $scope.$on('$destroy', $transitions.onSuccess({}, paramsUpdated, hookOptions));\n }\n\n // Add component-level hook for uiCanExit\n if (isFunction(controllerInstance.uiCanExit)) {\n const id = _uiCanExitId++;\n const cacheProp = '_uiCanExitIds';\n\n // Returns true if a redirect transition already answered truthy\n const prevTruthyAnswer = (trans: Transition) =>\n !!trans && ((trans[cacheProp] && trans[cacheProp][id] === true) || prevTruthyAnswer(trans.redirectedFrom()));\n\n // If a user answered yes, but the transition was later redirected, don't also ask for the new redirect transition\n const wrappedHook = (trans: Transition) => {\n let promise;\n const ids = (trans[cacheProp] = trans[cacheProp] || {});\n\n if (!prevTruthyAnswer(trans)) {\n promise = $q.when(controllerInstance.uiCanExit(trans));\n promise.then(val => (ids[id] = val !== false));\n }\n return promise;\n };\n\n const criteria = { exiting: viewState.name };\n $scope.$on('$destroy', $transitions.onBefore(criteria, wrappedHook, hookOptions));\n }\n}\n\nangular.module('ui.router.state').directive('uiView', uiView);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n", + "/** @module ng1 */ /** for typedoc */\n\nimport { ng as angular } from './angular';\nimport { Obj, StateService, StateOrName } from '@uirouter/core';\n\n/**\n * `isState` Filter: truthy if the current state is the parameter\n *\n * Translates to [[StateService.is]] `$state.is(\"stateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state is 'stateName'
    \n * ```\n */\n$IsStateFilter.$inject = ['$state'];\nexport function $IsStateFilter($state: StateService) {\n const isFilter: any = function(state: StateOrName, params: Obj, options?: { relative?: StateOrName }) {\n return $state.is(state, params, options);\n };\n isFilter.$stateful = true;\n return isFilter;\n}\n\n/**\n * `includedByState` Filter: truthy if the current state includes the parameter\n *\n * Translates to [[StateService.includes]]` $state.is(\"fullOrPartialStateName\")`.\n *\n * #### Example:\n * ```html\n *
    show if state includes 'fullOrPartialStateName'
    \n * ```\n */\n$IncludedByStateFilter.$inject = ['$state'];\nexport function $IncludedByStateFilter($state: StateService) {\n const includesFilter: any = function(state: StateOrName, params: Obj, options: { relative?: StateOrName }) {\n return $state.includes(state, params, options);\n };\n includesFilter.$stateful = true;\n return includesFilter;\n}\n\nangular\n .module('ui.router.state')\n .filter('isState', $IsStateFilter)\n .filter('includedByState', $IncludedByStateFilter);\n", + "/** @module ng1 */ /** */\nimport { ng as angular } from './angular';\nimport { IServiceProviderFactory } from 'angular';\nimport IAnchorScrollService = angular.IAnchorScrollService;\nimport ITimeoutService = angular.ITimeoutService;\n\nexport interface UIViewScrollProvider {\n /**\n * Uses standard anchorScroll behavior\n *\n * Reverts [[$uiViewScroll]] back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * service for scrolling based on the url anchor.\n */\n useAnchorScroll(): void;\n}\n\n/** @hidden */\nfunction $ViewScrollProvider() {\n let useAnchorScroll = false;\n\n this.useAnchorScroll = function() {\n useAnchorScroll = true;\n };\n\n this.$get = [\n '$anchorScroll',\n '$timeout',\n function($anchorScroll: IAnchorScrollService, $timeout: ITimeoutService): Function {\n if (useAnchorScroll) {\n return $anchorScroll;\n }\n\n return function($element: JQuery) {\n return $timeout(\n function() {\n $element[0].scrollIntoView();\n },\n 0,\n false,\n );\n };\n },\n ];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n", + "/**\n * Main entry point for angular 1.x build\n * @module ng1\n */ /** */\n\nexport * from './interface';\nexport * from './services';\nexport * from './statebuilders/views';\nexport * from './stateProvider';\nexport * from './urlRouterProvider';\n\nimport './injectables';\nimport './directives/stateDirectives';\nimport './stateFilters';\nimport './directives/viewDirective';\nimport './viewScroll';\n\nexport default 'ui.router';\n\nimport * as core from '@uirouter/core';\nexport { core };\nexport * from '@uirouter/core';\n" ], "names": [ "ng_from_global", @@ -834,8 +834,10 @@ "traceError", "_error", "abstract", + "invalid", "paramDefs", "invalidParams", + "invalidValues", "fromStateOrName", "toStateOrName", "avoidEmptyHash", @@ -964,14 +966,15 @@ "orphans", "previousQueueLength", "getState", + "notifyListeners", + "listener", + "s", "name_1", "build", "orphanIdx", "existingState", "existingFutureState", "attachRoute", - "listener", - "s", "rule", "urlRuleFactory", "_router", @@ -1276,7 +1279,6 @@ "onBefore", "ignoredHook", "registerIgnoredTransitionHook", - "invalid", "invalidTransitionHook", "registerInvalidTransitionHook", "onStart", @@ -1672,6 +1674,7 @@ "uiOnParamsChanged", "viewCreationTrans_1", "fromParams", + "getNodeSchema", "toSchema", "fromSchema", "changedToParams", @@ -1685,5 +1688,5 @@ "$anchorScroll", "scrollIntoView" ], - "mappings": ";;;;;;;;;;kPAMA,IAAMA,EAAiBC,QAEVC,EAAMC,GAAkBC,SAAyBD,EAAiBH,EC4C/E,WAAsBK,GACpB,IAAMC,KAAkBC,MAAMC,MAAMC,WAAY,IAC1CC,EAAmBL,EAAGM,OAS5B,OAPA,WAAiBC,GACf,OAAIA,EAAKD,QAAUD,EACVL,EAAGG,MAAM,KAAMI,GACjB,WACL,OAAOC,EAAQD,EAAKE,UAAUP,MAAMC,MAAMC,cAGvCI,CAAQP,GAWjB,aACE,IAAMM,EAAOH,UACPM,EAAQH,EAAKD,OAAS,EAC5B,OAAO,WAEL,IADA,IAAIK,EAAID,EAAOE,EAASL,EAAKG,GAAOP,MAAMU,KAAMT,WACzCO,KAAKC,EAASL,EAAKI,GAAG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