sogo/UI/WebServerResources/js/vendor/angular-ui-router.js.map

176 lines
742 KiB
Plaintext
Raw Normal View History

2017-10-19 08:14:42 +02:00
{
"version": 3,
"file": "angular-ui-router.js",
"sources": [
2018-08-24 06:30:03 +02:00
"angular-ui-router/src/angular.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/hof.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/predicates.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/coreservices.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/common.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/glob.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/queue.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/rejectFactory.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/strings.ts",
2019-12-31 07:15:45 +01:00
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/safeConsole.ts",
2018-08-24 06:30:03 +02:00
"angular-ui-router/node_modules/@uirouter/core/lib-esm/common/@uirouter/core/common/trace.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/params/@uirouter/core/params/paramType.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/params/@uirouter/core/params/param.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/params/@uirouter/core/params/paramTypes.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/params/@uirouter/core/params/stateParams.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/path/@uirouter/core/path/pathNode.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/state/@uirouter/core/state/targetState.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/path/@uirouter/core/path/pathUtils.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/resolve/@uirouter/core/resolve/interface.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/resolve/@uirouter/core/resolve/resolvable.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/resolve/@uirouter/core/resolve/resolveContext.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/state/@uirouter/core/state/stateBuilder.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/state/@uirouter/core/state/stateObject.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/state/@uirouter/core/state/stateMatcher.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/state/@uirouter/core/state/stateQueueManager.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/state/@uirouter/core/state/stateRegistry.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/interface.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/transitionHook.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/hookRegistry.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/hookBuilder.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/transition.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/url/@uirouter/core/url/urlMatcher.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/url/@uirouter/core/url/urlMatcherFactory.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/url/@uirouter/core/url/urlRule.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/url/@uirouter/core/url/urlRouter.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/view/@uirouter/core/view/view.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/@uirouter/core/globals.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/url/@uirouter/core/url/urlRules.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/url/@uirouter/core/url/urlConfig.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/url/@uirouter/core/url/urlService.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/@uirouter/core/router.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/coreResolvables.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/redirectTo.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/onEnterExitRetain.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/resolve.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/views.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/updateGlobals.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/url.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/lazyLoad.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/transitionEventType.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/ignoredTransition.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/hooks/@uirouter/core/hooks/invalidTransition.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/transition/@uirouter/core/transition/transitionService.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/state/@uirouter/core/state/stateService.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/q.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/injector.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/utils.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/baseLocationService.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/hashLocationService.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/memoryLocationService.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/pushStateLocationService.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/memoryLocationConfig.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/browserLocationConfig.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/vanilla/@uirouter/core/vanilla/plugins.ts",
"angular-ui-router/node_modules/@uirouter/core/lib-esm/@uirouter/core/interface.ts",
"angular-ui-router/src/statebuilders/views.ts",
"angular-ui-router/src/templateFactory.ts",
"angular-ui-router/src/stateProvider.ts",
"angular-ui-router/src/statebuilders/onEnterExitRetain.ts",
"angular-ui-router/src/locationServices.ts",
"angular-ui-router/src/urlRouterProvider.ts",
"angular-ui-router/src/services.ts",
"angular-ui-router/src/directives/stateDirectives.ts",
"angular-ui-router/src/stateFilters.ts",
"angular-ui-router/src/directives/viewDirective.ts",
"angular-ui-router/src/viewScroll.ts",
"angular-ui-router/src/index.ts"
2017-10-19 08:14:42 +02:00
],
"sourcesContent": [
2020-08-10 16:56:55 +02:00
"/** @publicapi @module ng1 */ /** */\nimport * as ng_from_import from 'angular';\n/** @hidden */ declare let angular;\n/** @hidden */ const ng_from_global = angular;\n/** @hidden */ export const ng = ng_from_import && ng_from_import.module ? ng_from_import : ng_from_global;\n",
2020-07-21 06:35:43 +02:00
"/**\n * Higher order functions\n *\n * These utility functions are exported, but are subject to change without notice.\n *\n * @packageDocumentation\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 * @param fn\n * @returns {*|function(): (*|any)}\n */\nexport function curry(fn: Function): Function {\n return function curried() {\n if (arguments.length >= fn.length) {\n return fn.apply(this, arguments);\n }\n const args = Array.prototype.slice.call(arguments);\n return curried.bind(this, ...args);\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,\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 * 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 * @packageDocumentation\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 = <any>tis('function');\nexport const isNumber: (x: any) => x is number = <any>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 = <any>((x: any) => toStr.call(x) === '[object Date]');\nexport const isRegExp: (x: any) => x is RegExp = <any>((x: any) => toStr.call(x) === '[object RegExp]');\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<any>>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 * @packageDocumentation\n */\nimport { IInjectable, Obj } from './common';\nimport { Disposable } from '../interface';\nimport { UrlConfig, UrlService } from '../url';\n\nconst noImpl = (fnname: string) => () => {\n throw new Error(`No implementation for ${fnname}. The framework specific code did not implement this method.`);\n};\n\nexport const makeStub = <T>(service: string, methods: (keyof T)[]): T =>\n methods.reduce((acc, key) => ((acc[key] = noImpl(`${service}.${key}()`) as any), acc), {} as T);\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<any>;\n}\n\nexport interface $QLike {\n when<T>(value?: T | PromiseLike<T>): Promise<T>;\n reject<T>(reason: any): Promise<T>;\n defer(): $QLikeDeferred;\n all(promises: { [key: string]: Promise<any> }): Promise<any>;\n all(promises: Promise<any>[]): Promise<any[]>;\n}\n\nexport interface $InjectorLike {\n strictDi?: boolean;\n get(token: any): any;\n get<T>(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\n/**\n * Handles low level URL read/write\n *\n * This service handles low level reads and updates of the URL and listens for url changes.\n * Implementors should pass these through to the underlying URL mechanism.\n * The underlying URL mechanism might be browser APIs, framework APIs, or some 3rd party URL management library.\n *\n * UI-Router Core includes three basic implementations:\n *\n * - [[PushStateLocationService]]\n * - [[HashLocationService]]\n * - [[MemoryLocationService]]\n */\nexport interface LocationServices extends Disposable {\n /** See: [[UrlService.url]] */ url: UrlService['url'];\n /** See: [[UrlService.path]] */ path: UrlService['path'];\n /** See: [[UrlService.search]] */ search: UrlService['search'];\n /** See: [[UrlService.hash]] */ hash: UrlService['hash'];\n /** See: [[UrlService.onChange]] */ onChange: UrlService['onChange'];\n}\n\n/**\n * Returns low level URL configuration and metadata\n *\n * This service returns information about the location configuration.\n * This service is primarily used when building URLs (e.g., for `hrefs`)\n *\n * Implementors should pass these through to the underlying URL APIs.\n * The underlying URL mechanism might be browser APIs, framework APIs, or some 3rd party URL management library.\n *\n * UI-Router Core includes two basic implementations:\n *\n * - [[BrowserLocationConfig]]\n * - [[MemoryLocationConfig]]\n */\nexport interface LocationConfig extends Disposable {\n /** See: [[UrlConfig.port]] */ port: UrlConfig['port'];\n /** See: [[UrlConfig.protocol]] */ protocol: UrlConfig['protocol'];\n /** See: [[UrlConfig.host]] */ host: UrlConfig['host'];\n /** See: [[UrlConfig.baseHref]] */ baseHref: UrlConfig['baseHref'];\n /** See: [[UrlConfig.html5Mode]] */ html5Mode: UrlConfig['html5Mode'];\n /** See: [[UrlConfig.hashPrefix]] */ hashPrefix: UrlConfig['hashPrefix'];\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 * @packageDocumentation\n * @preferred\n */\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, T> = (x: X, key?: string | number) => T;\nexport interface TypedMap<T> {\n [key: string]: T;\n}\nexport type Predicate<X> = (x?: X) => boolean;\nexport type PredicateBinary<X, Y> = (x?: X, y?: Y) => 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 */\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 lateReb
"/**\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 * @packageDocumentation\n */\nexport class Glob {\n text: string;\n glob: Array<string>;\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",
"import { pushTo } from './common';\n\nexport class Queue<T> {\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<T> {\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",
"'use strict';\nimport { extend, silentRejection } from '../common/common';\nimport { stringify } from '../common/strings';\nimport { is } from '../common/hof';\n\n/** An enum for Transition Rejection reasons */\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/** @internal */\nlet id = 0;\n\nexport class Rejection {\n /** @internal */\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
"/**\n * Functions that manipulate strings\n *\n * Although these functions are exported, they are subject to change without notice.\n *\n * @packageDocumentation\n */\n\nimport { isArray, isFunction, isInjectable, isNull, isObject, isPromise, isString, isUndefined } from './predicates';\nimport { Rejection } from '../transition/rejectFactory';\nimport { identity, IInjectable, pushR, tail } from './common';\nimport { pattern, val } from './hof';\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\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\nconst isRejection = Rejection.isRejectionPromise;\nconst hasToString = (obj: any) =>\n isObject(obj) && !isArray(obj) && obj.constructor !== Object && isFunction(obj.toString);\n\nconst stringifyPattern = pattern([\n [isUndefined, val('undefined')],\n [isNull, val('null')],\n [isPromise, val('[Promise]')],\n [isRejection, (x: any) => x._transitionRejection.toString()],\n [hasToString, (x: object) => x.toString()],\n [isInjectable, functionToString],\n [val(true), identity],\n]) as (val: any) => string;\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 if (isUndefined(o)) {\n // Workaround for IE & Edge Spec incompatibility where replacer function would not be called when JSON.stringify\n // is given `undefined` as value. To work around that, we simply detect `undefined` and bail out early by\n // manually stringifying it.\n return format(o);\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 delim
"/**\n * workaround for missing console object in IE9 when dev tools haven't been opened o_O\n * @packageDocumentation\n */\n/* tslint:disable:no-console */\nimport { noop } from './common';\n\nconst noopConsoleStub = { log: noop, error: noop, table: noop };\n\nfunction ie9Console(console) {\n const bound = (fn: Function) => Function.prototype.bind.call(fn, console);\n return {\n log: bound(console.log),\n error: bound(console.log),\n table: bound(console.log),\n };\n}\n\nfunction fallbackConsole(console) {\n const log = console.log.bind(console);\n const error = console.error ? console.error.bind(console) : log;\n const table = console.table ? console.table.bind(console) : log;\n return { log, error, table };\n}\n\nfunction getSafeConsole() {\n // @ts-ignore\n const isIE9 = typeof document !== 'undefined' && document.documentMode && document.documentMode === 9;\n if (isIE9) {\n return window && window.console ? ie9Console(window.console) : noopConsoleStub;\n } else if (!console.table || !console.error) {\n return fallbackConsole(console);\n } else {\n return console;\n }\n}\n\nexport const safeConsole = getSafeConsole();\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 * @packageDocumentation\n */\nimport { parse } from '../common/hof';\nimport { 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 { safeConsole } from './safeConsole';\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\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\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\nfunction normalizedCat(input: Category | string): string {\n return isNumber(input) ? Category[input] : Category[Category[input]];\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 */\nenum Category {\n RESOLVE,\n TRANSITION,\n HOOK,\n UIVIEW,\n VIEWCONFIG,\n}\n\nexport { Category };\n\nconst _tid = parse('$id');\nconst _rid = parse('router.$id');\n\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 /** @internal */\n approximateDigests: number;\n\n /** @internal */\n private _enabled: { [key: string]: boolean } = {};\n\n /** @internal */\n constructor() {\n this.approximateDigests = 0;\n }\n\n /** @internal */\n private _set(enabled: boolean, categories: Category[]) {\n if (!categories.length) {\n categories = <any>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
"import { 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 */\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 (<any>ArrayType)(this, mode);\n }\n}\n\n/** Wraps up a `ParamType` object to handle array values. */\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
"import { extend, filter, map, allTrueR, find } 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 { StateDeclaration } from '../state';\nimport { UrlConfig } from '../url';\n\nconst hasOwn = Object.prototype.hasOwnProperty;\n\nconst isShorthand = (cfg: ParamDeclaration) =>\n ['value', 'type', 'squash', 'array', 'dynamic'].filter(hasOwn.bind(cfg || {})).length === 0;\n\nenum DefType {\n PATH,\n SEARCH,\n CONFIG,\n}\nexport { DefType };\n\nfunction getParamDeclaration(paramName: string, location: DefType, state: StateDeclaration): ParamDeclaration {\n const noReloadOnSearch = (state.reloadOnSearch === false && location === DefType.SEARCH) || undefined;\n const dynamic = find([state.dynamic, noReloadOnSearch], isDefined);\n const defaultConfig = isDefined(dynamic) ? { dynamic } : {};\n const paramConfig = unwrapShorthand(state && state.params && state.params[paramName]);\n return extend(defaultConfig, paramConfig);\n}\n\nfunction unwrapShorthand(cfg: ParamDeclaration): ParamDeclaration {\n cfg = isShorthand(cfg) ? ({ value: cfg } as ParamDeclaration) : cfg;\n\n getStaticDefaultValue['__cacheable'] = true;\n function getStaticDefaultValue() {\n return cfg.value;\n }\n\n const $$fn = isInjectable(cfg.value) ? cfg.value : getStaticDefaultValue;\n return extend(cfg, { $$fn });\n}\n\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/** returns false, true, or the squash value to indicate the \"default parameter url squash policy\". */\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\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\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]
"import { 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 *\n * To register custom parameter types, use [[UrlConfig.type]], i.e.,\n *\n * ```js\n * router.urlService.config.type(customType)\n * ```\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 */\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`
"import { extend, ancestors, Obj } from '../common/common';\nimport { StateObject } from '../state/stateObject';\n\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",
"import { 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 * 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/** @internal */\nexport type GetParamsFn = (pathNode: PathNode) => Param[];\n",
"import { StateDeclaration, StateOrName, TargetStateDef } from './interface';\nimport { TransitionOptions } from '../transition/interface';\nimport { StateObject } from './stateObject';\nimport { isObject, 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 return obj && obj.state && (isString(obj.state) || (isObject(obj.state) && isString(obj.state.name)));\n };\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 * @internal\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) || <string>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 = <any>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.na
"import {\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\n .filter((node) => inArray(states, node.state))\n .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 key
"/**\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 * @packageDocumentation\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 * import { RXWAIT } from '@uirouter/rx';\n *\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
"import { extend, identity } from '../common/common';\nimport { services } from '../common/coreservices';\nimport { trace } from '../common/trace';\nimport { ResolvePolicy, ResolvableLiteral, PolicyAsync } 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<any> = 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 = <ResolvableLiteral>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
"import { 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 resolv
"import { applyPairs, extend, identity, inherit, mapObj, noop, Obj, omit, tail, values, copy } from '../common/common';\nimport { isArray, isDefined, isFunction, isString } from '../common/predicates';\nimport { stringify } from '../common/strings';\nimport { is, pattern, pipe, prop, 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 { ParamDeclaration } from '../params';\nimport { ParamFactory } from '../url';\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\n/**\n * A function that builds the final value for a specific field on a [[StateObject]].\n *\n * A series of builder functions for a given field are chained together.\n * The final value returned from the chain of builders is applied to the built [[StateObject]].\n * Builder functions should call the [[parent]] function either first or last depending on the desired composition behavior.\n *\n * @param state the _partially built_ [[StateObject]]. The [[StateDeclaration]] can be inspected via [[StateObject.self]]\n * @param parent the previous builder function in the series.\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(stateObject: StateObject) {\n let stateDec: StateDeclaration = stateObject.self;\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 const newStateDec: StateDeclaration = {};\n copy(stateDec, newStateDec);\n newStateDec.url += '{remainder:any}'; // match any path (.*)\n stateDec = newStateDec;\n }\n\n const parent = stateObject.parent;\n const parsed = parseUrl(stateDec.url);\n const url = !parsed ? stateDec.url : $urlMatcherFactoryProvider.compile(parsed.val, { state: stateDec });\n\n if (!url) return null;\n if (!$urlMatcherFactoryProvider.isMatcher(url)) throw new Error(`Invalid url '${url}' in state '${stateObject}'`);\n return parsed && parsed.root ? url : ((parent && parent.navigable) || root()).url.append(<UrlMatcher>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: ParamDeclaration, id: string) => paramFactory.fromConfig(id, null, state.self);\n const urlParams: Param[] = (state.url && state.url.parameters({ inheri
"import { 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<LazyLoadResult>;\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 /** @internal */\n __stateObjectCache: {\n /** Might be null */\n nameGlob?: Glob;\n };\n\n /**\n * Create a state object to put the private/internal implementation detai
"import { isString } from '../common/predicates';\nimport { StateOrName } from './interface';\nimport { StateObject } from './stateObject';\nimport { values } from '../common/common';\nimport { safeConsole } from '../common/safeConsole';\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 : (<any>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 safeConsole.error(\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",
"import { inArray, isString, prop } from '../common';\nimport { _StateDeclaration } from './interface';\nimport { StateObject } from './stateObject';\nimport { StateBuilder } from './stateBuilder';\nimport { StateRegistryListener } from './stateRegistry';\nimport { Disposable } from '../interface';\nimport { UIRouter } from '../router';\n\nexport class StateQueueManager implements Disposable {\n queue: StateObject[] = [];\n\n constructor(\n private router: UIRouter,\n public states: { [key: string]: StateObject },\n public builder: StateBuilder,\n public listeners: StateRegistryListener[]\n ) {}\n\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) =>\n listener(\n 'registered',\n registered.map((s) => s.self)\n )\n );\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.router.stateRegistry.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 const rulesApi = this.router.urlService.rules;\n rulesApi.rule(rulesApi.urlRuleFactory.create(state));\n }\n}\n",
"import { 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\n/**\n * A registry for all of the application's [[StateDeclaration]]s\n *\n * This API is found at `router.stateRegistry` ([[UIRouter.stateRegistry]])\n */\nexport class StateRegistry {\n private _root: StateObject;\n private states: { [key: string]: StateObject } = {};\n\n /** @internal */\n matcher: StateMatcher;\n private builder: StateBuilder;\n /** @internal */\n stateQueue: StateQueueManager;\n\n /** @internal */\n listeners: StateRegistryListener[] = [];\n\n /** @internal */\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(router, this.states, this.builder, this.listeners);\n this._registerRoot();\n }\n\n /** @internal */\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 /** @internal */\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
2020-12-22 16:06:25 +01:00
"import { StateDeclaration } from '../state/interface';\nimport { PredicateBinary } 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 | 'replace';\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 `true`\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 /**\n * This option may be used to cancel the active transition (if one is active) in favour of the this one.\n * This is the default behaviour or ui-router.\n *\n *\n * - When `true`, the active transition will be canceled and new transition will begin.\n * - when `false`, the transition will be canceled if a transition is already running. This can be useful in cases where\n * you only want to navigate to a different state if you are not already navigating somewhere.\n *\n * @default `true`\n */\n supercede?: boolean;\n /** @internal */\n reloadState?: StateObject;\n /** @internal\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 /** @internal */\n current?: () => Transition;\n /** @internal */\n source?: 'sref' | 'url' | 'redirect' | 'otherwise' | 'unknown';\n}\n\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 Pa
2020-07-21 06:35:43 +02:00
"import { 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<HookResult>;\nexport type ErrorHandler = (error: any) => Promise<any>;\n\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<any> = 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<any>): Promise<any> {\n // Chain the next hook off the previous\n const createHookChainR = (prev: Promise<any>, 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<T>(hooks: TransitionHook[], doneCallback: (result?: HookResult) => T): Promise<any> | T {\n for (let idx = 0; idx < hooks.length; idx++) {\n const hookResult = hooks[idx].invokeHook();\n\n if (isPromise(hookResult)) {\n
"import { 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 { Transition } from './transition';\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 * @internal\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, transition: Transition) {\n const toMatch = isString(criterion) ? [criterion] : criterion;\n\n function matchGlobs(_state: StateObject) {\n const globStrings = <string[]>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 = <any>(isFunction(toMatch) ? toMatch : matchGlobs);\n return !!matchFn(state, transition);\n}\n\n/**\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, transition: Transition): PathNode[] {\n if (criterion === true) return nodes;\n const matching = nodes.filter((node) => matchState(node.state, criterion, transition));\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 IMatch
"import { 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 */\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, transition);\n if (!matchingHooks) return [];\n\n const baseHookOptions = <TransitionHookOptions>{\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, transition);\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 <HookTuple>{ 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
"import { 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';\nimport { applyPairs, flattenR, uniqR } from '../common';\n\n/** @internal */\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 /** @internal */\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 /** @internal */\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<any> = 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 /** @internal */\n _aborted: boolean;\n /** @internal */\n private _error: Rejection;\n\n /** @internal Holds the hook registration functions such as those passed to Transition.onStart() */\n _registeredHooks: RegisteredHooks = {};\n\n /** @internal */\n private _options: TransitionOptions;\n /** @internal */\n private _treeChanges: TreeChanges;\n /** @internal */\n private _targetState: TargetState;\n /** @internal */\n private _hookBuilder = new HookBuilder(this);\n\n /** @internal */\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;
2020-12-22 16:06:25 +01:00
"import { map, inherit, identity, unnest, tail, find, Obj, allTrueR, unnestR, arrayTuples } 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 { UrlMatcherCompileConfig } from './interface';\nimport { joinNeighborsR, splitOnDelim } from '../common/strings';\nimport { ParamType } from '../params';\nimport { defaults } from '../common';\nimport { ParamFactory } from './urlMatcherFactory';\n\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\nconst memoizeTo = (obj: Obj, _prop: string, fn: Function) => (obj[_prop] = obj[_prop] || fn());\n\nconst splitOnSlash = splitOnDelim('/');\n\ninterface UrlMatcherCache {\n segments?: any[];\n weights?: number[];\n path?: UrlMatcher[];\n parent?: UrlMatcher;\n pattern?: RegExp;\n}\n\ninterface MatchDetails {\n id: string;\n regexp: string;\n segment: string;\n type: ParamType;\n}\n\nconst defaultConfig: UrlMatcherCompileConfig = {\n state: { params: {} },\n strict: true,\n caseInsensitive: true,\n decodeParams: true,\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 pr
2020-07-21 06:35:43 +02:00
"import { extend, forEach, isDefined, isFunction, isObject } from '../common';\nimport { UrlMatcher } from './urlMatcher';\nimport { DefType, Param, ParamType, ParamTypeDefinition } from '../params';\nimport { UrlMatcherCompileConfig } from './interface';\nimport { StateDeclaration } from '../state';\nimport { UIRouter } from '../router';\n\nexport class ParamFactory {\n fromConfig(id: string, type: ParamType, state: StateDeclaration) {\n return new Param(id, type, DefType.CONFIG, this.router.urlService.config, state);\n }\n\n fromPath(id: string, type: ParamType, state: StateDeclaration) {\n return new Param(id, type, DefType.PATH, this.router.urlService.config, state);\n }\n\n fromSearch(id: string, type: ParamType, state: StateDeclaration) {\n return new Param(id, type, DefType.SEARCH, this.router.urlService.config, state);\n }\n\n constructor(private router: UIRouter) {}\n}\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 {\n /** Creates a new [[Param]] for a given location (DefType) */\n paramFactory = new ParamFactory(this.router);\n // TODO: Check if removal of this will break anything, then remove these\n UrlMatcher: typeof UrlMatcher = UrlMatcher;\n Param: typeof Param = Param;\n\n // TODO: move implementations to UrlConfig (urlService.config)\n constructor(/** @internal */ private router: UIRouter) {}\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?: UrlMatcherCompileConfig) {\n const urlConfig = this.router.urlService.config;\n // backward-compatible support for config.params -> config.state.params\n const params = config && !config.state && (config as any).params;\n config = params ? { state: { params }, ...config } : config;\n const globalConfig: UrlMatcherCompileConfig = {\n strict: urlConfig._isStrictMode,\n caseInsensitive: urlConfig._isCaseInsensitive,\n decodeParams: urlConfig._decodeParams,\n };\n return new UrlMatcher(pattern, urlConfig.paramTypes, this.paramFactory, extend(globalConfig, 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 /** @internal */\n $get() {\n const urlConfig = this.router.urlService.config;\n urlConfig.paramTypes.enqueue = false;\n urlConfig.paramTypes._flushTypeQueue();\n return this;\n }\n\n /** @deprecated use [[UrlConfig.caseInsensitive]] */\n caseInsensitive = (value?: boolean) => this.router.urlService.config.caseInsensitive(value);\n\n /** @deprecated use [[UrlConfig.defaultSquashPolicy]] */\n defaultSquashPolicy = (value?: boolean | string) => this.router.urlService.config.defaultSquashPolicy(value);\n\n /** @deprecated use [[UrlConfig.strictMode]] */\n strictMode = (value?: boolean) => this.router.urlService.config.strictMode(value);\n\n /** @deprecated use [[UrlConfig.type]] */\n type = (name: string, definition?: ParamTypeDefinition, definitionFn?: () => ParamTypeDefinition) => {\n return this.router.urlService.config.type(name, definition, definitionFn) || this;\n };\n}\n",
"import { StateDeclaration } from '../state';\nimport { UrlMatcher } from './urlMatcher';\nimport { isString, isDefined, isFunction } from '../common/predicates';\nimport { UIRouter } from '../router';\nimport { identity, extend } from '../common/common';\nimport { is, or, 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 */\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 | StateDeclaration | RegExp | UrlRuleMatchFn,\n handler?: string | UrlRuleHandlerFn\n ): UrlRule {\n const { isState, isStateDeclaration } = StateObject;\n const makeRule = pattern([\n [isString, (_what: string) => makeRule(this.compile(_what))],\n [is(UrlMatcher), (_what: UrlMatcher) => this.fromUrlMatcher(_what, handler)],\n [or(isState, isStateDeclaration), (_what: StateObject | StateDeclaration) => 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 m
"import { stripLastPathElement } from '../common';\nimport { UrlMatcher } from './urlMatcher';\nimport { RawParams } from '../params';\nimport { UIRouter } from '../router';\nimport { UrlRuleFactory } from './urlRule';\nimport { MatchResult, UrlParts, UrlRule, UrlRuleHandlerFn } from './interface';\nimport { TargetState, TargetStateDef } from '../state';\n\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/**\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 [[UrlRules]] which can be found as [[UrlService.rules]].\n */\nexport class UrlRouter {\n /** used to create [[UrlRule]] objects for common cases */\n public urlRuleFactory: UrlRuleFactory;\n /** @internal */ private location: string;\n\n /** @internal */\n constructor(/** @internal */ private router: UIRouter) {\n this.urlRuleFactory = new UrlRuleFactory(router);\n }\n\n /** Internal API. */\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 * @internal\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 = <any>(cfgPort === 80 || cfgPort === 443 ? '' : ':' + cfgPort);\n\n return [cfg.protocol(), '://', cfg.host(), port, slash, url].join('');\n }\n\n // Delegate these calls to [[UrlService]]\n /** @deprecated use [[UrlService.sync]]*/\n public sync = (evt?) => this.router.urlService.sync(evt);\n /** @deprecated use [[UrlService.listen]]*/\n public listen = (enabled?: boolean): Function => this.router.urlService.listen(enabled);\n /** @deprecated use [[UrlService.deferIntercept]]*/\n public deferIntercept = (defer?: boolean) => this.router.urlService.deferIntercept(defer);\n /** @deprecated use [[UrlService.interceptDeferred]]*/\n public get interceptDeferred() {\n return this.router.urlService.interceptDeferred;\n }\n /** @deprecated use [[UrlService.ma
"import { equals, applyPairs, removeFrom, TypedMap, inArray, find } 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';\nimport { UIRouter } from '../router';\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 /** @param id router.$id + \".\" + uiView.id */\n _registeredUIView(id: string): ActiveUIView;\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 /** @internal */ private _uiViews: ActiveUIView[] = [];\n /** @internal */ private _viewConfigs: ViewConfig[] = [];\n /** @internal */ private _rootContext: ViewContext;\n /** @internal */ private _viewConfigFactories: { [key: string]: ViewConfigFactory } = {};\n /** @internal */ private _listeners: ViewSyncListener[] = [];\n\n /** @internal */\n public _pluginapi: ViewServicePluginAPI = {\n _rootViewContext: this._rootViewContext.bind(this),\n _viewConfigFactory: this._viewConfigFactory.bind(this),\n _registeredUIView: (id: string) => find(this._uiViews, (view) => `${this.router.$id}.${view.id}` === id),\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-
"import { 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 * @internal\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 /** @internal */\n lastStartedTransitionId = -1;\n\n /** @internal */\n transitionHistory = new Queue<Transition>([], 1);\n\n /** @internal */\n successfulTransitions = new Queue<Transition>([], 1);\n\n dispose() {\n this.transitionHistory.clear();\n this.successfulTransitions.clear();\n this.transition = null;\n }\n}\n",
"import { UIRouter } from '../router';\nimport { Disposable } from '../interface';\nimport { MatcherUrlRule, UrlRule, UrlRuleHandlerFn, UrlRuleMatchFn, UrlRulesApi } from './interface';\nimport { TargetState, TargetStateDef } from '../state';\nimport { UrlMatcher } from './urlMatcher';\nimport { is, isDefined, isFunction, isString, removeFrom, val } from '../common';\nimport { UrlRuleFactory } from './urlRule';\n\nconst prioritySort = (a: UrlRule, b: UrlRule) => (b.priority || 0) - (a.priority || 0);\n\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\nconst urlMatcherSort = (a: MatcherUrlRule, b: MatcherUrlRule) =>\n !a.urlMatcher || !b.urlMatcher ? 0 : UrlMatcher.compare(a.urlMatcher, b.urlMatcher);\n\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 [[UrlRules.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 */\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\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/**\n * API for managing URL rules\n *\n * This API is used to create and manage URL rules.\n * URL rules are a mechanism to respond to specific URL patterns.\n *\n * The most commonly used methods are [[otherwise]] and [[when]].\n *\n * This API is found at `router.urlService.rules` (see: [[UIRouter.urlService]], [[URLService.rules]])\n */\nexport class UrlRules implements Disposable {\n /** used to create [[UrlRule]] objects for common cases */\n public urlRuleFactory: UrlRuleFactory;\n\n /** @internal */ private _sortFn = defaultRuleSortFn;\n /** @internal */ private _otherwiseFn: UrlRule;\n /** @internal */ private _sorted: boolean;\n /** @internal */ private _rules: UrlRule[] = [];\n /** @internal */ private _id = 0;\n\n /** @internal */\n constructor(/** @internal */ private router: UIRouter) {\n this.urlRuleFactory = new UrlRuleFactory(router);\n }\n\n /** @internal */\n public dispose(router?: UIRouter) {\n this._rules = [];\n delete this._otherwiseFn;\n }\n\n /**\n * Defines the initial state, path, or behavior to use when the app starts.\n *\n * This rule defines the initial/starting state for the application.\n *\n * This rule is triggered the first time the URL is checked (when the app initially loads).\n * The rule is triggered only when the url matches either `\"\"` or `\"/\"`.\n *\n * Note: The rule is intended to be used when the root of the application is directly linked to.\n * When the URL is *not* `\"\"` or `\"/\"` and doesn't mat
"import { Disposable } from '../interface';\nimport { UIRouter } from '../router';\nimport { ParamTypeDefinition, ParamTypes } from '../params';\nimport { isDefined, isString } from '../common';\n\n/**\n * An API to customize the URL behavior and retrieve URL configuration\n *\n * This API is used to customize the behavior of the URL.\n * This includes optional trailing slashes ([[strictMode]]), case sensitivity ([[caseInsensitive]]),\n * and custom parameter encoding (custom [[type]]).\n *\n * It also has information about the location (url) configuration such as [[port]] and [[baseHref]].\n * This information can be used to build absolute URLs, such as\n * `https://example.com:443/basepath/state/substate?param1=a#hashvalue`;\n *\n * This API is found at `router.urlService.config` (see: [[UIRouter.urlService]], [[URLService.config]])\n */\nexport class UrlConfig implements Disposable {\n /** @internal */ paramTypes = new ParamTypes();\n /** @internal */ _decodeParams = true;\n /** @internal */ _isCaseInsensitive = false;\n /** @internal */ _isStrictMode = true;\n /** @internal */ _defaultSquashPolicy: boolean | string = false;\n\n /** @internal */ constructor(/** @internal */ private router: UIRouter) {}\n /** @internal */ public dispose = () => this.paramTypes.dispose();\n\n // Delegate these calls to the current LocationConfig implementation\n\n /**\n * Gets the base Href, e.g., `http://localhost/approot/`\n *\n * @return the application's base href\n */\n public baseHref = (): string => this.router.locationConfig.baseHref();\n\n /**\n * Gets or sets the hashPrefix\n *\n * This only applies when not running in [[html5Mode]] (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\n public hashPrefix = (newprefix?: string): string => this.router.locationConfig.hashPrefix(newprefix);\n /**\n * Gets the host, e.g., `localhost`\n *\n * @return the protocol\n */\n public host = (): string => this.router.locationConfig.host();\n\n /**\n * Returns true when running in pushstate mode\n *\n * @return true when running in html5 mode (pushstate mode).\n */\n public html5Mode = (): boolean => this.router.locationConfig.html5Mode();\n\n /**\n * Gets the port, e.g., `80`\n *\n * @return the port number\n */\n public port = (): number => this.router.locationConfig.port();\n\n /**\n * Gets the protocol, e.g., `http`\n *\n * @return the protocol\n */\n public protocol = (): string => this.router.locationConfig.protocol();\n\n /**\n * Defines whether URL matching should be case sensitive (the default behavior), or not.\n *\n * #### Example:\n * ```js\n * // Allow case insensitive url matches\n * urlService.config.caseInsensitive(true);\n * ```\n *\n * @param value `false` to match URL in a case sensitive manner; otherwise `true`;\n * @returns the current value of caseInsensitive\n */\n public caseInsensitive(value?: boolean): boolean {\n return (this._isCaseInsensitive = isDefined(value) ? value : this._isCaseInsensitive);\n }\n\n /**\n * Sets the default behavior when generating or matching URLs with default parameter values.\n *\n * #### Example:\n * ```js\n * // Remove default parameter values from the url\n * urlService.config.defaultSquashPolicy(true);\n * ```\n *\n * @param value A string that defines the default parameter URL squashing behavior.\n * - `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL\n * - `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the\n * parameter is surrounded by slashes, squash (remove) one slash from the URL\n * - any other string, e.g. \"~\": When generating an href with a default parameter value, squash (remove)\n * the parameter value from the URL and replace it with this string.\n
"import { UIRouter } from '../router';\nimport { extend, is, isString, LocationServices, pattern } from '../common';\nimport { MatchResult, UrlParts, UrlRule, UrlSyncApi } from './interface';\nimport { UrlRules } from './urlRules';\nimport { UrlConfig } from './urlConfig';\nimport { TargetState, TargetStateDef } from '../state';\n\n/**\n * API for URL management\n */\nexport class UrlService implements LocationServices, UrlSyncApi {\n /** @internal */ private _stopListeningFn: Function;\n /** @internal */ interceptDeferred = false;\n\n /**\n * The nested [[UrlRules]] API for managing URL rules and rewrites\n *\n * See: [[UrlRules]] for details\n */\n public rules = new UrlRules(this.router);\n\n /**\n * The nested [[UrlConfig]] API to configure the URL and retrieve URL information\n *\n * See: [[UrlConfig]] for details\n */\n public config = new UrlConfig(this.router);\n\n /** @internal */\n constructor(/** @internal */ private router: UIRouter) {}\n /** @internal */\n public dispose() {\n this.listen(false);\n (this.rules as UrlRules).dispose();\n }\n\n /**\n * Gets the current URL parts\n *\n * This method returns the different parts of the current URL (the [[path]], [[search]], and [[hash]]) as a [[UrlParts]] object.\n */\n public parts(): UrlParts {\n return { path: this.path(), search: this.search(), hash: this.hash() };\n }\n\n /**\n * Activates the best rule for the current URL\n *\n * Checks the current URL for a matching [[UrlRule]], then invokes that rule's handler.\n * This method is called internally any time the URL has changed.\n *\n * This effectively activates the state (or redirect, etc) which matches the current URL.\n *\n * #### Example:\n * ```js\n * urlService.deferIntercept();\n *\n * fetch('/states.json').then(resp => resp.json()).then(data => {\n * data.forEach(state => $stateRegistry.register(state));\n * urlService.listen();\n * // Find the matching URL and invoke the handler.\n * urlService.sync();\n * });\n * ```\n */\n public sync(evt?) {\n if (evt && evt.defaultPrevented) return;\n const { urlService, stateService } = this.router;\n\n const url: UrlParts = { path: urlService.path(), search: urlService.search(), hash: urlService.hash() };\n const best = this.match(url);\n\n const applyResult = pattern([\n [isString, (newurl: string) => urlService.url(newurl, true)],\n [TargetState.isDef, (def: TargetStateDef) => stateService.go(def.state, def.params, def.options)],\n [is(TargetState), (target: TargetState) => stateService.go(target.state(), target.params(), target.options())],\n ]);\n\n applyResult(best && best.rule.handler(best.match, url, this.router));\n }\n\n /**\n * Starts or stops listening for URL changes\n *\n * Call this sometime after calling [[deferIntercept]] to start monitoring the url.\n * This causes UI-Router to start listening for changes to the URL, if it wasn't already listening.\n *\n * If called with `false`, UI-Router will stop listening (call listen(true) to start listening again).\n *\n * #### Example:\n * ```js\n * urlService.deferIntercept();\n *\n * fetch('/states.json').then(resp => resp.json()).then(data => {\n * data.forEach(state => $stateRegistry.register(state));\n * // Start responding to URL changes\n * urlService.listen();\n * urlService.sync();\n * });\n * ```\n *\n * @param enabled `true` or `false` to start or stop listening to URL changes\n */\n public listen(enabled?: boolean): Function {\n if (enabled === false) {\n this._stopListeningFn && this._stopListeningFn();\n delete this._stopListeningFn;\n } else {\n return (this._stopListeningFn =\n this._stopListeningFn || this.router.urlService.onChange((evt) => this.sync(evt)));\n }\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 use
"import { 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';\nimport { makeStub } from './common';\n\n/** @internal */\nlet _routerInstance = 0;\n\n/** @internal */\nconst locSvcFns: (keyof LocationServices)[] = ['url', 'path', 'search', 'hash', 'onChange'];\n/** @internal */\nconst locCfgFns: (keyof LocationConfig)[] = ['port', 'protocol', 'host', 'baseHref', 'html5Mode', 'hashPrefix'];\n/** @internal */\nconst locationServiceStub = makeStub<LocationServices>('LocationServices', locSvcFns);\n/** @internal */\nconst locationConfigStub = makeStub<LocationConfig>('LocationConfig', locCfgFns);\n\n/**\n * An instance of UI-Router.\n *\n * This object contains references to service APIs which define your application's routing behavior.\n */\nexport class UIRouter {\n /** @internal */ $id = _routerInstance++;\n /** @internal */ _disposed = false;\n /** @internal */ private _disposables: Disposable[] = [];\n\n /** Enable/disable tracing to the javascript console */\n trace: Trace = trace;\n\n /** Provides services related to ui-view synchronization */\n viewService = new ViewService(this);\n\n /** An object that contains global router state, such as the current state and params */\n globals: UIRouterGlobals = new UIRouterGlobals();\n\n /** A service that exposes global Transition Hooks */\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(this);\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 services related to the URL */\n urlService: UrlService = new UrlService(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 /** @internal 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 * @internal\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 * @internal\n */\n constructor(\n public locationService: LocationServices = locationServiceStub,\n public locationConfig
"import { Transition } from '../transition/transition';\nimport { UIRouter } from '../router';\nimport { TransitionService } from '../transition/transitionService';\nimport { Resolvable } from '../resolve';\nimport { inArray, uniqR, unnestR, values } from '../common';\nimport { PathNode } from '../path';\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",
"import { 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(<any>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",
"import { 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 */\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",
"import { 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).subContext(state.$$state()).resolvePath('LAZY', trans).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",
"import { 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",
"import { 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",
"import { 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",
"import { 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: () => 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<LazyLoadResult> {\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 re
"import { 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 */\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",
"import { 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",
"import { 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",
"import {\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 supercede: true,\n custom: {},\n current: () => null,\n source: 'unknown',\n};\n\n/**\n * Plugin API for Transition Service\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
"import {\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 services related to ui-router states.\n *\n * This API is located at `router.stateService` ([[UIRouter.stateService]])\n */\nexport class StateService {\n /** @internal */\n invalidCallbacks: OnInvalidCallback[] = [];\n\n /**\n * The [[Transition]] currently in progress (or null)\n *\n * @deprecated 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 * @deprecated 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 * @deprecated This is a passthrough through to [[UIRouterGlobals.current]]\n */\n get current() {\n return this.router.globals.current;\n }\n /**\n * The current [[StateObject]] (an internal API)\n *\n * @deprecated This is a passthrough through to [[UIRouterGlobals.$current]]\n */\n get $current() {\n return this.router.globals.$current;\n }\n\n /** @internal */\n constructor(/** @internal */ 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 /** @internal */\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 * @internal\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<OnInvalidCallback>(this.invalidCallbacks.slice());\n const injector = new ResolveContext(fromPath).injector();\n\n const checkForRedirect = (result: HookResult) => {\n if (!(result instanceof Target
"import { 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<any> } | Promise<any>[]) => {\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",
"import {\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",
"import {\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.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)\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",
"import { 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",
"import { 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",
"import { 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",
"import { 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 <base href='/base/'>, this returns '/base'.\n * If <base href='/foo/base/'>, this returns '/foo/base'.\n * If <base href='/base/index.html'>, this returns '/base'.\n * If <base href='http://localhost:8080/base/index.html'>, this returns '/base'.\n * If <base href='/base'>, this returns ''.\n * If <base href='http://localhost:8080'>, this returns ''.\n * If <base href='http://localhost:8080/'>, 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",
"import { 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",
"import { isDefined, isUndefined } 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 if (isDefined(href)) this._baseHref = href;\n if (isUndefined(this._baseHref)) this._baseHref = this.getBaseHref();\n return this._baseHref;\n }\n\n private getBaseHref() {\n const baseTag: HTMLBaseElement = document.getElementsByTagName('base')[0];\n if (baseTag && baseTag.href) {\n return baseTag.href.replace(/^([^/:]*:)?\\/\\/[^/]*/, '');\n }\n\n return this._isHtml5 ? '/' : location.pathname || '/';\n }\n\n dispose() {}\n}\n",
"import { 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 * @packageDocumentation\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<string[]>('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<T>(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<any>;\n /** Asynchronously gets a value as type `T` (generics parameter) */\n getAsync<T>(token: any): Promise<T>;\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<T>(token: any): T;\n}\n\nexport interface UIRouterPlugin extends Disposable {\n name: string;\n}\n\nexport abstract class UIRouterPluginBase implements UIRouterPlugin, Disposable {\n abstract name: string;\n dispose(router: UIRouter) {}\n}\n\nexport interface Disposable {\n /** Instructs the Disposable to clean up any resources */\n dispose(router?: UIRouter);\n}\n",
2020-08-10 16:56:55 +02:00
"/** @publicapi @module ng1 */ /** */\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';\n\n/** @internalapi */\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\n/** @internalapi */\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 *\n * @internalapi\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: <string>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\n/** @hidden */\nlet id = 0;\n\n/** @internalapi */\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:
2020-07-21 06:35:43 +02:00
"/** @publicapi @module view */ /** */\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 = '<ui-view></ui-view>';\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) ? (<any>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.<string>} 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 = (<any>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 invokin
2018-08-24 06:30:03 +02:00
"/** @publicapi @module ng1 */ /** */\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 (stat
2020-08-10 16:56:55 +02:00
"/** @publicapi @module ng1 */ /** */\nimport {\n StateObject,\n TransitionStateHookFn,\n HookResult,\n Transition,\n services,\n ResolveContext,\n extend,\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 *\n * @internalapi\n */\nexport const getStateHookBuilder = (hookName: 'onEnter' | 'onExit' | 'onRetain') =>\n function stateHookBuilder(stateObject: StateObject): 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",
"/** @publicapi @module ng1 */ /** */\nimport { LocationConfig, LocationServices, UIRouter, ParamType, isDefined } from '@uirouter/core';\nimport { val, createProxyFunctions, removeFrom, isObject } from '@uirouter/core';\nimport { ILocationService, ILocationProvider, IWindowService } from 'angular';\n\n/**\n * Implements UI-Router LocationServices and LocationConfig using Angular 1's $location service\n * @internalapi\n */\nexport class Ng1LocationServices implements LocationConfig, LocationServices {\n private $locationProvider: ILocationProvider;\n private $location: ILocationService;\n private $sniffer: any;\n private $browser: any;\n private $window: IWindowService;\n\n path;\n search;\n hash;\n hashPrefix;\n port;\n protocol;\n host;\n\n private _baseHref: string;\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 // eslint-disable-next-line @typescript-eslint/no-empty-function\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 baseHref() {\n return this._baseHref || (this._baseHref = this.$browser.baseHref() || this.$window.location.pathname);\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, $window: IWindowService) {\n this.$location = $location;\n this.$sniffer = $sniffer;\n this.$browser = $browser;\n this.$window = $window;\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\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 }\n}\n",
"/** @publicapi @module url */ /** */\nimport {\n UIRouter,\n LocationServices,\n $InjectorLike,\n BaseUrlRule,\n UrlRuleHandlerFn,\n UrlMatcher,\n IInjectable,\n UrlRouter,\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 * @internalapi\n * @deprecated\n */\nexport class UrlRouterProvider {\n static injectableHandler(router: UIRouter, handler: IInjectable): UrlRuleHandlerFn {\n return (match) => services.$injector.invoke(handler, null, { $match: match, $stateParams: router.globals.params });\n }\n\n /** @hidden */\n constructor(/** @hidden */ private router: UIRouter) {}\n\n /** @hidden */\n $get(): UrlRouter {\n const urlService = this.router.urlService;\n this.router.urlRouter.update(true);\n if (!urlService.interceptDeferred) urlService.listen();\n return this.router.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.router.urlService.rules.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 urlRules = this.router.urlService.rules;\n if (isString(rule)) {\n urlRules.otherwise(rule);\n } else if (isFunction(rule)) {\n urlRules.otherwise(() => rule(services.$injector, this.router.locationS
"/* eslint-disable @typescript-eslint/no-empty-function */\n/* eslint-disable @typescript-eslint/no-unused-vars */\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 * @preferred @publicapi @module ng1\n */ /** */\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;\n\nangular.module('ui.router.angular1', []);\nconst mod_init = angular.module('ui.router.init', ['ng']);\nconst mod_util = angular.module('ui.router.util', ['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']);\nconst mod_cmpt = angular.module('ui.router.compat', ['ui.router']);\n\ndeclare module '@uirouter/core/lib/router' {\n interface UIRouter {\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 // Disable decoding of params by UrlMatcherFactory because $location already handles this\n router.urlService.config._decodeParams = false;\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', '$window', '$sniffer', '$rootScope', '$http', '$templateCache'];\n function $get(\n $location: ILocationService,\n $browser: any,\n $window: any,\n $sniffer: any,\n $rootScope: ng.IScope,\n $http: IHttpService,\n $templateCache: ITemplateCacheService\n ) {\n ng1LocationService._runtimeServices($rootScope, $location, $sniffer, $browser, $window);\n delete router['router'];\n delete router['$get'];\n return router;\n }\n return router;\n}\n\nconst getProviderFor = (serviceName) => [\n '$uiRouterProvi
"/* eslint-disable @typescript-eslint/no-empty-interface */\n/* eslint-disable prefer-const */\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 * @preferred @publicapi @module directives\n */ /** */\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';\n\n/** @hidden Used for typedoc */\nexport interface ng1_directive {}\n\n/** @hidden */\nfunction parseStateRef(ref: string) {\n const paramsOnly = ref.match(/^\\s*({[^}]*})\\s*$/);\n if (paramsOnly) ref = '(' + paramsOnly[1] + ')';\n\n const 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 || e.altKey || 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 if (!el.attr('disabled')) {\n $state.go(target.uiState, target.uiStateParams, target.uiStateOpts);\n }\n });\n e.preventDefault();\n\n // if the state has no URL, ignore one preventDefault from the <a> 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: EventListener, 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 even
2020-07-21 06:35:43 +02:00
"/** @publicapi @module ng1 */ /** */\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 * <div ng-if=\"'stateName' | isState\">show if state is 'stateName'</div>\n * ```\n */\n$IsStateFilter.$inject = ['$state'];\nfunction $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 * <div ng-if=\"'fullOrPartialStateName' | includedByState\">show if state includes 'fullOrPartialStateName'</div>\n * ```\n */\n$IncludedByStateFilter.$inject = ['$state'];\nfunction $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').filter('isState', $IsStateFilter).filter('includedByState', $IncludedByStateFilter);\n\nexport { $IsStateFilter, $IncludedByStateFilter };\n",
2020-08-10 16:56:55 +02:00
"/** @publicapi @module directives */ /** */\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, 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<any>;\n $animLeave: Promise<any>;\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 * <!-- Unnamed -->\n * <div ui-view></div>\n *\n * <!-- Named -->\n * <div ui-view=\"viewName\"></div>\n *\n * <!-- Named (different style) -->\n * <ui-view name=\"viewName\"></ui-view>\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 * <div ui-view></div>\n * $stateProvider.state(\"home\", {\n * template: \"<h1>HELLO!</h1>\"\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: \"<h1>HELLO!</h1>\"\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 * <div ui-view=\"main\"></div>\n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"main\": {\n * template: \"<h1>HELLO!</h1>\"\n * }\n * }\n * })\n * ```\n *\n * Really though, you'll use views to set up multiple views:\n *\n * ```html\n * <div ui-view></div>\n * <div ui-view=\"chart\"></div>\n * <div ui-view=\"data\"></div>\n * ```\n *\n * ```js\n * $stateProvider.state(\"home\", {\n * views: {\n * \"\": {\n * template: \"<h1>HELLO!</h1>\"\n * },\n * \"chart\": {\n * template: \"<chart_thing/>\"\n * },\n * \"data\": {\n * template: \"<data_thing/>\"\n * }\n * }\n * })\n * ```\n *\n * #### Examples for `autoscroll`:\n * ```html\n * <!-- If autoscroll present with no expression,\n * then scroll ui-view into view -->\n * <ui-view autoscroll/>\n *\n * <!-- If autoscroll present with valid expression,\n * then scroll ui-view into view if expression evaluates to true -->\n * <ui-view autoscroll='true'/>\n * <ui-view autoscroll='false'/>\n * <ui-view autoscroll='scopeVariable'/>\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
2020-07-21 06:35:43 +02:00
"/** @publicapi @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', <IServiceProviderFactory>$ViewScrollProvider);\n",
2018-08-24 06:30:03 +02:00
"/**\n * Main entry point for angular 1.x build\n * @publicapi @module ng1\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"
2017-10-19 08:14:42 +02:00
],
"names": [
"ng_from_import.module",
"this",
"angular",
"RejectType",
"Category",
"DefType",
2018-08-24 06:30:03 +02:00
"TransitionHookPhase",
"TransitionHookScope",
2017-10-19 08:14:42 +02:00
"parseUrl",
"__extends",
2019-10-03 07:13:07 +02:00
"id"
2017-10-19 08:14:42 +02:00
],
2020-12-22 16:06:25 +01:00
"mappings": ";;;;;;;;;;;;;;;;IAAA;IAGA,eAAe,IAAM,cAAc,GAAG,OAAO,CAAC;IAC9C,eAAsB,IAAM,EAAE,GAAG,cAAc,IAAIA,qBAAqB,GAAG,cAAc,GAAG,cAAc;;ICJ1G;;;;;;;;;;;;;;IASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAyCgB,KAAK,CAAC,EAAY;QAChC,OAAO,SAAS,OAAO;YACrB,IAAI,SAAS,CAAC,MAAM,IAAI,EAAE,CAAC,MAAM,EAAE;gBACjC,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;aAClC;YACD,IAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACnD,OAAO,OAAO,CAAC,IAAI,OAAZ,OAAO,kBAAM,IAAI,GAAK,IAAI,GAAE;SACpC,CAAC;IACJ,CAAC;IAED;;;;;;aAMgB,OAAO;QACrB,IAAM,IAAI,GAAG,SAAS,CAAC;QACvB,IAAM,KAAK,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAC9B,OAAO;YACL,IAAI,CAAC,GAAG,KAAK,EACX,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;YAC9C,OAAO,CAAC,EAAE;gBAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YAChD,OAAO,MAAM,CAAC;SACf,CAAC;IACJ,CAAC;IAED;;;;;;aAMgB,IAAI;QAAC,eAAoB;aAApB,UAAoB,EAApB,qBAAoB,EAApB,IAAoB;YAApB,0BAAoB;;QACvC,OAAO,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;IACjE,CAAC;IAED;;;;;;QAMa,IAAI,GAAG,UAAC,IAAY,IAAK,OAAA,UAAC,GAAQ,IAAK,OAAA,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAA,IAAC;IAErE;;;;;;;QAOa,MAAM,GAAG,KAAK,CAAC,UAAC,IAAY,EAAE,IAAS,EAAE,GAAQ,IAAK,OAAA,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,GAAA,EAAE;IAE9F;;;;;;;;QAQa,KAAK,GAAG,UAAC,IAAY,IAAK,OAAA,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAC;IAEnF;;;;QAIa,GAAG,GAA2C,UAAC,EAAkB,IAAK,OAAA;QAAC,cAAc;aAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;YAAd,yBAAc;;QAChG,OAAA,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;IAArB,CAAqB,IAAC;IAExB;;;;aAIgB,GAAG,CAAC,GAAmB,EAAE,GAAmB;QAC1D,OAAO;YAAC,cAAc;iBAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;gBAAd,yBAAc;;YAAK,OAAA,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;SAAA,CAAC;IAC5E,CAAC;IAED;;;;aAIgB,EAAE,CAAC,GAAmB,EAAE,GAAmB;QACzD,OAAO;YAAC,cAAc;iBAAd,UAAc,EAAd,qBAAc,EAAd,IAAc;gBAAd,yBAAc;;YAAK,OAAA,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC;SAAA,CAAC;IAC5E,CAAC;IAED;;;;;;QAMa,GAAG,GAAG,UAAC,GAAmB,IAAK,OAAA,UAAC,GAAU,IAAK,OAAA,GAAG,CAAC,MAAM,CAAC,UAAC,CAAC,EAAE,CAAC,IAAK,OAAA,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAA,EAAE,IAAI,CAAY,GAAA,IAAC;IAEjH;QACa,GAAG,GAAG,UAAC,GAAmB,IAAK,OAAA,UAAC,GAAU,IAAK,OAAA,GAAG,CAAC,MAAM,CAAC,UAAC,CAAC,EAAE,CAAC,IAAK,OAAA,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAA,EAAE,KAAK,CAAY,GAAA,IAAC;IAElH;QACa,EAAE,GAAG,UAAI,IAA0B,IAAK,OAAA,UAAC,GAAQ;QAC5D,OAAA,CAAC,GAAG,IAAI,IAAI,IAAI,GAAG,CAAC,WAAW,KAAK,IAAI,KAAK,GAAG,YAAY,IAAI;IAAhE,CAAgE,IAAC;IAEnE;QACa,EAAE,GAAkC,UAAC,KAAU,IAAK,OAAA,UAAC,KAAU,IAAK,OAAA,KAAK,KAAK,KAAK,GAAA,IAAC;IAEjG;QACa,GAAG,GAAG,UAAI,CAAI,IAAK,OAAA,cAAM,OAAA,CAAC,GAAA,IAAC;aAIxB,MAAM,CAAC,MAAc,EAAE,IAAY;QACjD,OAAO,UAAC,GAAQ,IAAK,OAAA,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,GAAA,CAAC;IACpD,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAwCgB,OAAO,CAAC,MAAoB;QAC1C,OAAO,UAAU,CAAM;YACrB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACtC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBAAE,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;aAC7C;SACF,CAAC;IACJ;;IClNA;;;;;;;;IAYA,IAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC;IACxC,IAAM,GAAG,GAAG,UAAC,CAAS,IAAK,OAAA,UAAC,CAAM,IAAK,OAAA,OAAO,CAAC,KAAK,CAAC,GAAA,GAAA,CAAC;QACzC,WAAW,GAAG,GAAG,CAAC,WAAW,EAAE;QAC/B,SAAS,GAAG,GAAG,CAAC,WAAW,EAAE;QAC7B,MAAM,GAAG,UAAC,CAAM,IAAK,OAAA,CAAC,KAAK,IAAI,IAAC;QAChC,iBAAiB,GAAG,EAAE,CAAC,MAAM,EAAE,WAAW,EAAE;QAC5C,UAAU,GAAmC,GAAG,CAAC,UAAU,EAAE;QAC7D,QAAQ,GAAiC,GAAG,CAAC,QAAQ,EAAE;QACvD,QAAQ,GAA4B,GAAG,CAAC,QAAQ,EAAE;QAClD,QAAQ,GAAG,UAAC,CAAM,IAAK,OAAA,CAAC,KAAK,IAAI,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAC;QAC3D,OAAO,GAAG,KAAK,CAAC,QAAQ;QACxB,MAAM,IAAgC,UAAC,CAAM,IAAK,OAAA,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,eAAe,GAAA,EAAE;QACrF,QAAQ,IAAkC,UAAC,CAAM,IAAK,OAAA,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,iBAAiB,GAAA,EAAE;IAExG;;;;;;aAMgB,YAAY,CAAC,GAAQ;QACnC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,EAAE;YAC9B,IAAM,IAAI,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAC3B,IAAI,GAAG,G
2017-10-19 08:14:42 +02:00
}