UNPKG

vue-router

Version:

> To see what versions are currently supported, please refer to the [Security Policy](./packages/router/SECURITY.md).

1,460 lines 124 kB
/*! * vue-router v5.2.0 * (c) 2026 Eduardo San Martin Morote * @license MIT */ import { AllowedComponentProps, AnchorHTMLAttributes, App, Component as Component$1, ComponentCustomProps, ComponentPublicInstance, ComputedRef, DefineComponent, EffectScope, InjectionKey, MaybeRef, Ref, ShallowRef, UnwrapRef, VNode, VNodeProps } from "vue"; //#region src/experimental/data-loaders/symbols.d.ts /** * Retrieves the internal version of loaders. * @internal */ declare const LOADER_SET_KEY: unique symbol; /** * Retrieves the internal version of loader entries. * @internal */ declare const LOADER_ENTRIES_KEY: unique symbol; /** * Added to the loaders returned by `defineLoader()` to identify them. * Allows to extract exported useData() from a component. * @internal */ declare const IS_USE_DATA_LOADER_KEY: unique symbol; /** * Symbol used to save the pending location on the router. * @internal */ declare const PENDING_LOCATION_KEY: unique symbol; /** * Symbol used to know there is no value staged for the loader and that commit should be skipped. * @internal */ declare const STAGED_NO_VALUE: unique symbol; /** * Gives access to the current app and it's `runWithContext` method. * @internal */ declare const APP_KEY: unique symbol; /** * Gives access to an AbortController that aborts when the navigation is canceled. * @internal */ declare const ABORT_CONTROLLER_KEY: unique symbol; /** * Symbol used to save the initial data on the router. * @internal */ declare const IS_SSR_KEY: unique symbol; /** * Symbol used to get the effect scope used for data loaders. * @internal */ declare const DATA_LOADERS_EFFECT_SCOPE_KEY: unique symbol; //#endregion //#region src/config.d.ts /** * Allows customizing existing types of the router that are used globally like `$router`, `<RouterLink>`, etc. **ONLY FOR INTERNAL USAGE**. * * - `Router` - swaps the public {@link Router} type (e.g. to `EXPERIMENTAL_Router`) * - `$router` - the router instance * - `$route` - the current route location * - `beforeRouteEnter` - Page component option * - `beforeRouteUpdate` - Page component option * - `beforeRouteLeave` - Page component option * - `RouterLink` - RouterLink Component * - `RouterView` - RouterView Component * * @internal */ interface TypesConfig {} //#endregion //#region src/query.d.ts /** * Possible values in normalized {@link LocationQuery}. `null` renders the query * param but without an `=`. * * @example * ``` * ?isNull&isEmpty=&other=other * gives * `{ isNull: null, isEmpty: '', other: 'other' }`. * ``` * * @internal */ type LocationQueryValue$1 = string | null; /** * Possible values when defining a query. `undefined` allows to remove a value. * * @internal */ type LocationQueryValueRaw$1 = LocationQueryValue$1 | number | undefined; /** * Normalized query object that appears in {@link RouteLocationNormalized} * * @public */ type LocationQuery$1 = Record<string, LocationQueryValue$1 | LocationQueryValue$1[]>; /** * Loose {@link LocationQuery} object that can be passed to functions like * {@link Router.push} and {@link Router.replace} or anywhere when creating a * {@link RouteLocationRaw} * * @public */ type LocationQueryRaw$1 = Record<string | number, LocationQueryValueRaw$1 | LocationQueryValueRaw$1[]>; /** * Transforms a queryString into a {@link LocationQuery} object. Accept both, a * version with the leading `?` and without Should work as URLSearchParams * @internal * * @param search - search string to parse * @returns a query object */ declare function parseQuery(search: string): LocationQuery$1; /** * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it * doesn't prepend a `?` * * @internal * * @param query - query object to stringify * @returns string version of the query without the leading `?` */ declare function stringifyQuery(query: LocationQueryRaw$1 | undefined): string; //#endregion //#region src/matcher/types.d.ts /** * Normalized version of a {@link RouteRecord | route record}. */ interface RouteRecordNormalized { /** * {@inheritDoc _RouteRecordBase.path} */ path: _RouteRecordBase['path']; /** * {@inheritDoc _RouteRecordBase.redirect} */ redirect: _RouteRecordBase['redirect'] | undefined; /** * {@inheritDoc _RouteRecordBase.name} */ name: _RouteRecordBase['name']; /** * {@inheritDoc RouteRecordMultipleViews.components} */ components: RouteRecordMultipleViews['components'] | null | undefined; /** * Contains the original modules for lazy loaded components. * @internal */ mods: Record<string, unknown>; /** * Nested route records. */ children: RouteRecordRaw[]; /** * {@inheritDoc _RouteRecordBase.meta} */ meta: Exclude<_RouteRecordBase['meta'], void>; /** * {@inheritDoc RouteRecordMultipleViews.props} */ props: Record<string, _RouteRecordProps>; /** * Registered beforeEnter guards */ beforeEnter: _RouteRecordBase['beforeEnter']; /** * Registered leave guards * * @internal */ leaveGuards: Set<NavigationGuard>; /** * Registered update guards * * @internal */ updateGuards: Set<NavigationGuard>; /** * Registered beforeRouteEnter callbacks passed to `next` or returned in guards * * @internal */ enterCallbacks: Record<string, NavigationGuardNextCallback[]>; /** * Mounted route component instances * Having the instances on the record mean beforeRouteUpdate and * beforeRouteLeave guards can only be invoked with the latest mounted app * instance if there are multiple application instances rendering the same * view, basically duplicating the content on the page, which shouldn't happen * in practice. It will work if multiple apps are rendering different named * views. */ instances: Record<string, ComponentPublicInstance | undefined | null>; /** * Defines if this record is the alias of another one. This property is * `undefined` if the record is the original one. */ aliasOf: RouteRecordNormalized | undefined; } /** * {@inheritDoc RouteRecordNormalized} */ type RouteRecord = RouteRecordNormalized; //#endregion //#region src/matcher/pathParserRanker.d.ts type PathParams = Record<string, string | string[]>; /** * A param in a url like `/users/:id` */ interface PathParserParamKey { name: string; repeatable: boolean; optional: boolean; } interface PathParser { /** * The regexp used to match a url */ re: RegExp; /** * The score of the parser */ score: Array<number[]>; /** * Keys that appeared in the path */ keys: PathParserParamKey[]; /** * Parses a url and returns the matched params or null if it doesn't match. An * optional param that isn't preset will be an empty string. A repeatable * param will be an array if there is at least one value. * * @param path - url to parse * @returns a Params object, empty if there are no params. `null` if there is * no match */ parse(path: string): PathParams | null; /** * Creates a string version of the url * * @param params - object of params * @returns a url */ stringify(params: PathParams): string; } /** * @internal */ interface _PathParserOptions { /** * Makes the RegExp case-sensitive. * * @defaultValue `false` */ sensitive?: boolean; /** * Whether to disallow a trailing slash or not. * * @defaultValue `false` */ strict?: boolean; /** * Should the RegExp match from the beginning by prepending a `^` to it. * @internal * * @defaultValue `true` */ start?: boolean; /** * Should the RegExp match until the end by appending a `$` to it. * * @deprecated this option will alsways be `true` in the future. Open a discussion in vuejs/router if you need this to be `false` * * @defaultValue `true` */ end?: boolean; } type PathParserOptions = Pick<_PathParserOptions, 'end' | 'sensitive' | 'strict'>; //#endregion //#region src/matcher/pathMatcher.d.ts interface RouteRecordMatcher extends PathParser { record: RouteRecord; parent: RouteRecordMatcher | undefined; children: RouteRecordMatcher[]; alias: RouteRecordMatcher[]; } //#endregion //#region src/matcher/index.d.ts /** * Internal RouterMatcher * * @internal */ interface RouterMatcher { addRoute: (record: RouteRecordRaw, parent?: RouteRecordMatcher) => () => void; removeRoute(matcher: RouteRecordMatcher): void; removeRoute(name: NonNullable<RouteRecordNameGeneric>): void; clearRoutes: () => void; getRoutes: () => RouteRecordMatcher[]; getRecordMatcher: (name: NonNullable<RouteRecordNameGeneric>) => RouteRecordMatcher | undefined; /** * Resolves a location. Gives access to the route record that corresponds to the actual path as well as filling the corresponding params objects * * @param location - MatcherLocationRaw to resolve to a url * @param currentLocation - MatcherLocation of the current location */ resolve: (location: MatcherLocationRaw, currentLocation: MatcherLocation) => MatcherLocation; } /** * Creates a Router Matcher. * * @internal * @param routes - array of initial routes * @param globalOptions - global route options */ declare function createRouterMatcher(routes: Readonly<RouteRecordRaw[]>, globalOptions: PathParserOptions): RouterMatcher; //#endregion //#region src/history/common.d.ts type HistoryLocation = string; /** * Allowed variables in HTML5 history state. Note that pushState clones the state * passed and does not accept everything: e.g.: it doesn't accept symbols, nor * functions as values. It also ignores Symbols as keys. * * @internal */ type HistoryStateValue = string | number | boolean | null | undefined | HistoryState | HistoryStateArray; /** * Allowed HTML history.state */ interface HistoryState { [x: number]: HistoryStateValue; [x: string]: HistoryStateValue; } /** * Allowed arrays for history.state. * * @internal */ interface HistoryStateArray extends Array<HistoryStateValue> {} declare enum NavigationType { pop = "pop", push = "push" } declare enum NavigationDirection { back = "back", forward = "forward", unknown = "" } interface NavigationInformation { type: NavigationType; direction: NavigationDirection; delta: number; } interface NavigationCallback { (to: HistoryLocation, from: HistoryLocation, information: NavigationInformation): void; } /** * Interface implemented by History implementations that can be passed to the * router as {@link Router.history} * * @alpha */ interface RouterHistory { /** * Base path that is prepended to every url. This allows hosting an SPA at a * sub-folder of a domain like `example.com/sub-folder` by having a `base` of * `/sub-folder` */ readonly base: string; /** * Current History location */ readonly location: HistoryLocation; /** * Current History state */ readonly state: HistoryState; /** * Navigates to a location. In the case of an HTML5 History implementation, * this will call `history.pushState` to effectively change the URL. * * @param to - location to push * @param data - optional {@link HistoryState} to be associated with the * navigation entry */ push(to: HistoryLocation, data?: HistoryState): void; /** * Same as {@link RouterHistory.push} but performs a `history.replaceState` * instead of `history.pushState` * * @param to - location to set * @param data - optional {@link HistoryState} to be associated with the * navigation entry */ replace(to: HistoryLocation, data?: HistoryState): void; /** * Traverses history in a given direction. * * @example * ```js * myHistory.go(-1) // equivalent to window.history.back() * myHistory.go(1) // equivalent to window.history.forward() * ``` * * @param delta - distance to travel. If delta is \< 0, it will go back, * if it's \> 0, it will go forward by that amount of entries. * @param triggerListeners - whether this should trigger listeners attached to * the history */ go(delta: number, triggerListeners?: boolean): void; /** * Attach a listener to the History implementation that is triggered when the * navigation is triggered from outside (like the Browser back and forward * buttons) or when passing `true` to {@link RouterHistory.back} and * {@link RouterHistory.forward} * * @param callback - listener to attach * @returns a callback to remove the listener */ listen(callback: NavigationCallback): () => void; /** * Generates the corresponding href to be used in an anchor tag. * * @param location - history location that should create an href */ createHref(location: HistoryLocation): string; /** * Clears any event listener attached by the history implementation. */ destroy(): void; } //#endregion //#region src/errors.d.ts /** * Flags so we can combine them when checking for multiple errors. This is the internal version of * {@link NavigationFailureType}. * * @internal */ declare const enum ErrorTypes { MATCHER_NOT_FOUND = 1, NAVIGATION_GUARD_REDIRECT = 2, NAVIGATION_ABORTED = 4, NAVIGATION_CANCELLED = 8, NAVIGATION_DUPLICATED = 16 } /** * Enumeration with all possible types for navigation failures. Can be passed to * {@link isNavigationFailure} to check for specific failures. */ declare enum NavigationFailureType { /** * An aborted navigation is a navigation that failed because a navigation * guard returned `false` or called `next(false)` */ aborted = 4, /** * A cancelled navigation is a navigation that failed because a more recent * navigation finished started (not necessarily finished). */ cancelled = 8, /** * A duplicated navigation is a navigation that failed because it was * initiated while already being at the exact same location. */ duplicated = 16 } /** * Extended Error that contains extra information regarding a failed navigation. */ interface NavigationFailure extends Error { /** * Type of the navigation. One of {@link NavigationFailureType} */ type: ErrorTypes.NAVIGATION_CANCELLED | ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED; /** * Route location we were navigating from */ from: RouteLocationNormalized; /** * Route location we were navigating to */ to: RouteLocationNormalized; } /** * Internal error used to detect a redirection. * * @internal */ interface NavigationRedirectError extends Omit<NavigationFailure, 'to' | 'type'> { type: ErrorTypes.NAVIGATION_GUARD_REDIRECT; to: RouteLocationRaw; } /** * Check if an object is a {@link NavigationFailure}. * * @param error - possible {@link NavigationFailure} * @param type - optional types to check for * * @example * ```js * import { isNavigationFailure, NavigationFailureType } from 'vue-router' * * router.afterEach((to, from, failure) => { * // Any kind of navigation failure * if (isNavigationFailure(failure)) { * // ... * } * // Only duplicated navigations * if (isNavigationFailure(failure, NavigationFailureType.duplicated)) { * // ... * } * // Aborted or canceled navigations * if (isNavigationFailure(failure, NavigationFailureType.aborted | NavigationFailureType.cancelled )) { * // ... * } * }) * ``` */ declare function isNavigationFailure(error: any, type?: ErrorTypes.NAVIGATION_GUARD_REDIRECT): error is NavigationRedirectError; declare function isNavigationFailure(error: any, type?: ErrorTypes | NavigationFailureType): error is NavigationFailure; /** * Internal type to define an ErrorHandler * * @param error - error thrown * @param to - location we were navigating to when the error happened * @param from - location we were navigating from when the error happened * @internal */ interface _ErrorListener { (error: any, to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded): any; } //#endregion //#region src/experimental/query.d.ts /** * NOTE: some types here are duplicated from ../query.ts * because they will change to always have (string | null)[] values */ /** * Possible values in normalized {@link LocationQuery}. `null` renders the query * param but without an `=`. * * @internal */ type LocationQueryValue = string | null; /** * Possible values when defining a query. `undefined` allows to remove a value. * * @internal */ type LocationQueryValueRaw = LocationQueryValue | number | undefined; /** * Normalized query object that appears in {@link RouteLocationNormalized} * * @public */ type LocationQuery = Record<string, LocationQueryValue | LocationQueryValue[]>; /** * Loose {@link LocationQuery} object that can be passed to functions like * {@link Router.push} and {@link Router.replace} or anywhere when creating a * {@link RouteLocationRaw} * * @public */ type LocationQueryRaw = Record<string | number, LocationQueryValueRaw | LocationQueryValueRaw[]>; /** * Transforms a queryString into a {@link LocationQuery} object. Accept both, a * version with the leading `?` and without. Uses `Object.create(null)` so the * returned object cannot be exploited via prototype pollution. * * @internal * * @param search - search string to parse * @returns a query object */ declare function experimental_parseQuery(search: string): LocationQuery; //#endregion //#region src/scrollBehavior.d.ts /** * Scroll position similar to * {@link https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions | `ScrollToOptions`}. * Note that not all browsers support `behavior`. */ type ScrollPositionCoordinates = { behavior?: ScrollOptions['behavior']; left?: number; top?: number; }; /** * Internal normalized version of {@link ScrollPositionCoordinates} that always * has `left` and `top` coordinates. Must be a type to be assignable to HistoryStateValue. * * @internal */ type _ScrollPositionNormalized = { behavior?: ScrollOptions['behavior']; left: number; top: number; }; /** * Type of the `scrollBehavior` option that can be passed to `createRouter`. */ interface RouterScrollBehavior { /** * @param to - Route location where we are navigating to * @param from - Route location where we are navigating from * @param savedPosition - saved position if it exists, `null` otherwise */ (to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, savedPosition: _ScrollPositionNormalized | null): Awaitable<ScrollPosition | false | void>; } interface ScrollPositionElement extends ScrollToOptions { /** * A valid CSS selector. Note some characters must be escaped in id selectors (https://mathiasbynens.be/notes/css-escapes). * @example * Here are a few examples: * * - `.title` * - `.content:first-child` * - `#marker` * - `#marker\~with\~symbols` * - `#marker.with.dot`: selects `class="with dot" id="marker"`, not `id="marker.with.dot"` * */ el: string | Element; } type ScrollPosition = ScrollPositionCoordinates | ScrollPositionElement; type Awaitable<T> = T | PromiseLike<T>; //#endregion //#region src/experimental/route-resolver/matchers/param-parsers/types.d.ts /** * Defines a parser that can read a param from the url (string-based) and * transform it into a more complex type, or vice versa. * * @param TParam - the type of the param after parsing as exposed in * `route.params` * * @param TUrlParam - this is the most permissive type that can be passed to * get and returned by set. By default it's the type of query path params * (stricter as they do not allow `null` within an array or `undefined`). By * default it allows undefined because that represents a value that can be * omitted and is different from null in query params * * @param TParamRaw - the type that can be passed as a location when * navigating: `router.push({ params: {}})` it's sometimes more permissive than * TParam, for example allowing nullish values * * @see {MatcherPattern} */ interface ParamParser<TParam = MatcherQueryParamsValue, TUrlParam = MatcherQueryParamsValue, TParamRaw = TParam> { get?: (value: NoInfer<TUrlParam>) => TParam; set?: (value: TParamRaw) => TUrlParam; } //#endregion //#region src/types/utils.d.ts /** * Creates a union type that still allows autocompletion for strings. * @internal */ type _LiteralUnion<LiteralType, BaseType extends string = string> = LiteralType | (BaseType & Record<never, never>); /** * Maybe a promise maybe not * @internal */ type _Awaitable<T> = T | PromiseLike<T>; /** * @internal */ type Simplify<T> = { [K in keyof T]: T[K]; } & {}; //#endregion //#region src/experimental/route-resolver/matchers/matcher-pattern.d.ts /** * Base interface for matcher patterns that extract params from a URL. * * @template TIn - type of the input value to match against the pattern * @template TParams - type of the output value after matching * @template TParamsRaw - type of the input value to build the input from * * In the case of the `path`, the `TIn` is a `string`, but in the case of the * query, it's the object of query params. `TParamsRaw` allows for a more permissive * type when building the value, for example allowing numbers and strings like * the old params. * * @internal this is the base interface for all matcher patterns, it shouldn't * be used directly */ interface MatcherPattern<TIn = string, TParams extends MatcherParamsFormatted = MatcherParamsFormatted, TParamsRaw extends MatcherParamsFormatted = TParams> { /** * Matches a serialized params value against the pattern. * * @param value - params value to parse * @throws {MatchMiss} if the value doesn't match * @returns parsed params object */ match(value: TIn): TParams; /** * Build a serializable value from parsed params. Should apply encoding if the * returned value is a string (e.g path and hash should be encoded but query * shouldn't). * * @param value - params value to parse * @returns serialized params value */ build(params: TParamsRaw): TIn; } /** * Handles the `path` part of a URL. It can transform a path string into an * object of params and vice versa. */ interface MatcherPatternPath<TParams extends MatcherParamsFormatted = MatcherParamsFormatted // | null // | undefined // | void // so it might be a bit more convenient , TParamsRaw extends MatcherParamsFormatted = TParams> extends MatcherPattern<string, TParams, TParamsRaw> {} /** * Allows matching a static path. * * @example * ```ts * const matcher = new MatcherPatternPathStatic('/team') * matcher.match('/team') // {} * matcher.match('/team/123') // throws MatchMiss * matcher.build() // '/team' * ``` */ declare class MatcherPatternPathStatic implements MatcherPatternPath<EmptyParams> { readonly path: string; /** * lowercase version of the path to match against. * This is used to make the matching case insensitive. */ private pathi; constructor(path: string); match(path: string): EmptyParams; build(): string; } /** * Options for param parsers in {@link MatcherPatternPathDynamic}. */ type MatcherPatternPathDynamic_ParamOptions<TUrlParam extends string | string[] | null = string | string[] | null, TParam = string | string[] | null, TParamRaw = TParam> = readonly [ /** * Param parser to use for this param. */ parser?: ParamParser<TParam, TUrlParam, TParamRaw>, /** * Is tha param a repeatable param and should be converted to an array */ repeatable?: boolean, /** * Can this parameter be omitted or empty (for repeatable params, an empty array). */ optional?: boolean]; /** * Helper type to extract the params from the options object. * * @internal */ type ExtractParamTypeFromOptions<TParamsOptions> = { [K in keyof TParamsOptions]: TParamsOptions[K] extends MatcherPatternPathDynamic_ParamOptions<any, infer TParam, any> ? TParam : never; }; /** * Helper type to extract the raw params from the options object. * * @internal */ type ExtractLocationParamTypeFromOptions<TParamsOptions> = { [K in keyof TParamsOptions]: TParamsOptions[K] extends MatcherPatternPathDynamic_ParamOptions<any, any, infer TParamRaw> ? TParamRaw : never; }; /** * Handles the `path` part of a URL with dynamic parameters. */ declare class MatcherPatternPathDynamic<TParamsOptions> implements MatcherPatternPath<ExtractParamTypeFromOptions<TParamsOptions>, ExtractLocationParamTypeFromOptions<TParamsOptions>> { readonly re: RegExp; readonly params: TParamsOptions & Record<string, MatcherPatternPathDynamic_ParamOptions<any, any>>; readonly pathParts: Array<string | number | Array<string | number>>; readonly trailingSlash: boolean | null; /** * Cached keys of the {@link params} object. */ private paramsKeys; /** * Creates a new dynamic path matcher. * * @param re - regex to match the path against * @param params - object of param parsers as {@link MatcherPatternPathDynamic_ParamOptions} * @param pathParts - array of path parts, where strings are static parts, 1 are regular params, and 0 are splat params (not encode slash) * @param trailingSlash - whether the path should end with a trailing slash, null means "do not care" (for trailing splat params) */ constructor(re: RegExp, params: TParamsOptions & Record<string, MatcherPatternPathDynamic_ParamOptions<any, any>>, pathParts: Array<string | number | Array<string | number>>, trailingSlash?: boolean | null); match(path: string): Simplify<ExtractParamTypeFromOptions<TParamsOptions>>; build(params: Simplify<ExtractLocationParamTypeFromOptions<TParamsOptions>>): string; } /** * Handles the `hash` part of a URL. It can transform a hash string into an * object of params and vice versa. */ interface MatcherPatternHash<TParams extends MatcherParamsFormatted = MatcherParamsFormatted> extends MatcherPattern<string, TParams> {} /** * Generic object of params that can be passed to a matcher. */ type MatcherParamsFormatted = Record<string, unknown>; /** * Empty object in TS. */ type EmptyParams = Record<PropertyKey, never>; /** * Possible values for query params in a matcher. */ type MatcherQueryParamsValue = string | null | undefined | Array<string | null>; type MatcherQueryParams = Record<string, MatcherQueryParamsValue>; //#endregion //#region src/location.d.ts /** * Location object returned by {@link `parseURL`}. * @internal */ interface LocationNormalized { path: string; fullPath: string; hash: string; query: LocationQuery$1; } /** * Initial route location where the router is. Can be used in navigation guards * to differentiate the initial navigation. * * @example * ```js * import { START_LOCATION } from 'vue-router' * * router.beforeEach((to, from) => { * if (from === START_LOCATION) { * // initial navigation * } * }) * ``` */ declare const START_LOCATION_NORMALIZED: RouteLocationNormalizedLoaded; //#endregion //#region src/experimental/route-resolver/resolver-abstract.d.ts /** * Allowed types for a matcher name. */ type RecordName = string | symbol; /** * Manage and resolve routes. Also handles the encoding, decoding, parsing and * serialization of params, query, and hash. * * - `TMatcherRecordRaw` represents the raw record type passed to {@link addMatcher}. * - `TMatcherRecord` represents the normalized record type returned by {@link getRoutes}. */ interface EXPERIMENTAL_Resolver_Base<TRecord> { /** * Resolves an absolute location (like `/path/to/somewhere`). * * @param absoluteLocation - The absolute location to resolve. * @param currentLocation - This value is ignored and should not be passed if the location is absolute. */ resolve(absoluteLocation: `/${string}`, currentLocation?: undefined): ResolverLocationResolved<TRecord>; /** * Resolves a string location relative to another location. A relative * location can be `./same-folder`, `../parent-folder`, `same-folder`, or * even `?page=2`. */ resolve(relativeLocation: string, currentLocation: ResolverLocationResolved<TRecord>): ResolverLocationResolved<TRecord>; /** * Resolves a location by its name. Any required params or query must be * passed in the `options` argument. */ resolve(location: ResolverLocationAsNamed, currentLocation?: undefined): ResolverLocationResolved<TRecord>; /** * Resolves a location by its absolute path (starts with `/`). Any required query must be passed. * * @param location - The location to resolve. */ resolve(location: ResolverLocationAsPathAbsolute, currentLocation?: undefined): ResolverLocationResolved<TRecord>; resolve(location: ResolverLocationAsPathRelative, currentLocation: ResolverLocationResolved<TRecord>): ResolverLocationResolved<TRecord>; /** * Resolves a location relative to another location. It reuses existing * properties in the `currentLocation` like `params`, `query`, and `hash`. */ resolve(relativeLocation: ResolverLocationAsRelative, currentLocation: ResolverLocationResolved<TRecord>): ResolverLocationResolved<TRecord>; /** * Get a list of all resolver route records. */ getRoutes(): TRecord[]; /** * Get a resolver record by its name. * Previously named `getRecordMatcher()` */ getRoute(name: RecordName): TRecord | undefined; } /** * Returned location object by {@link EXPERIMENTAL_Resolver_Base['resolve']}. * It contains the resolved name, params, query, hash, and matched records. */ interface ResolverLocationResolved<TMatched> extends LocationNormalized { /** * Name of the route record. A symbol if no name is provided. */ name: RecordName; /** * Parsed params. Already decoded and formatted. */ params: MatcherParamsFormatted; /** * Chain of route records that lead to the matched one. The last record is * the the one that matched the location. Each previous record is the parent * of the next one. */ matched: TMatched[]; } /** * Location object that can be passed to {@link * EXPERIMENTAL_Resolver_Base['resolve']} and is recognized as a `name`. * * @example * ```ts * resolver.resolve({ name: 'user', params: { id: 123 } }) * resolver.resolve({ name: 'user-search', params: {}, query: { page: 2 } }) * ``` */ interface ResolverLocationAsNamed { name: RecordName; params: MatcherParamsFormatted; query?: LocationQueryRaw; hash?: string; /** * @deprecated This is ignored when `name` is provided */ path?: undefined; } /** * Location object that can be passed to {@link EXPERIMENTAL_Resolver_Base['resolve']} * and is recognized as a relative path. * * @example * ```ts * resolver.resolve({ path: './123' }, currentLocation) * resolver.resolve({ path: '..' }, currentLocation) * ``` */ interface ResolverLocationAsPathRelative { path: string; query?: LocationQueryRaw; hash?: string; /** * @deprecated This is ignored when `path` is provided */ name?: undefined; /** * @deprecated This is ignored when `path` (instead of `name`) is provided */ params?: undefined; } /** * Location object that can be passed to {@link EXPERIMENTAL_Resolver_Base['resolve']} * and is recognized as an absolute path. * * @example * ```ts * resolver.resolve({ path: '/team/123' }) * ``` */ interface ResolverLocationAsPathAbsolute extends ResolverLocationAsPathRelative { path: `/${string}`; } /** * Relative location object that can be passed to {@link EXPERIMENTAL_Resolver_Base['resolve']} * and is recognized as a relative location, copying the `params`, `query`, and * `hash` if not provided. * * @example * ```ts * resolver.resolve({ params: { id: 123 } }, currentLocation) * resolver.resolve({ hash: '#bottom' }, currentLocation) * ``` */ interface ResolverLocationAsRelative { params?: MatcherParamsFormatted; query?: LocationQueryRaw; hash?: string; /** * @deprecated This location is relative to the next parameter. This `name` will be ignored. */ name?: undefined; /** * @deprecated This location is relative to the next parameter. This `path` will be ignored. */ path?: undefined; } //#endregion //#region src/experimental/route-resolver/matchers/param-parsers/define-param-parser.d.ts /** * Defines a param parser that works with any kind of param (path, repeatable, * optional, query, hash, ...) but requires the user to handle all cases in the * get and set functions (nullish, undefined, arrays, etc). This allows you to * have full control over the parsing logic, but it also means that you need to * handle all edge cases yourself. If possible, prefer using {@see defineParamParser} * which provides a more structured way to handle these * cases and automatically handles arrays and nullish values. * * @example * * Here is an example that allows arbitrary numbers (NaN values are filtered * out). It supports repeatable params, so it can be used both as a path param * parser and a query param parser. * * ```ts * export const parser = defineParamParserRaw<number>({ * get: value => { * if (value == null) return null * if (Array.isArray(value)) { * return value * .filter(v => v != null) * .map(Number) * .filter(v => !Number.isNaN(v)) * } * * return Number.isNaN(Number(value)) * ? miss(`"${value}" is not a valid number`) * : Number(value) * }, * * set: value => * Array.isArray(value) * ? value.map(String) * : value == null * ? null * : String(value), * }) * ``` * * @see {@link defineParamParser} */ /*! #__NO_SIDE_EFFECTS__ */ declare function defineParamParserRaw<TParam, TParamRaw = TParam, TUrlParam = MatcherQueryParamsValue>(parser: Required<ParamParser<TParam, TUrlParam, TParamRaw>>): Required<ParamParser<TParam, TUrlParam, TParamRaw>>; /** * Defines a param parser that transforms strings to another type. Handles * optional and repeatable params: * * - Optional params: become `null` if the value is nullish * - Repeatable params: the value becomes an array of the parsed type, and nullish values are filtered out * * @example * * Here is an example that allows arbitrary valid numbers (NaN values are * filtered out). It can be used in both, path, and query params. * * ```ts * import { defineParamParser, miss } from 'vue-router/experimental' * * export const parser = defineParamParser<number>({ * get: value => { * const num = Number(value) * if (Number.isNaN(num)) { * miss(`"${value}" is not a valid number`) * } * return num * }, * * set: value => String(value), * }) * ``` * * @see {@link defineParamParserRaw} */ declare function defineParamParser<TParam, TParamRaw = TParam>(parser: Required<ParamParser<TParam, string, TParamRaw>>): Required<ParamParser<TParam | TParam[] | null, MatcherQueryParamsValue, TParamRaw | TParamRaw[] | null | undefined>>; //#endregion //#region src/experimental/route-resolver/matchers/param-parsers/booleans.d.ts /** * Native Param parser for booleans. * * @internal */ declare const PARAM_PARSER_BOOL: { get: (value: NoInfer<MatcherQueryParamsValue>) => boolean | boolean[] | undefined; set: (value: boolean | boolean[] | null | undefined) => string | string[] | null | undefined; }; //#endregion //#region src/experimental/route-resolver/matchers/param-parsers/integers.d.ts /** * Native Param parser for integers. * * @internal */ declare const PARAM_PARSER_INT: { get: (value: NoInfer<MatcherQueryParamsValue>) => number | number[] | null; set: (value: number | number[] | null) => string | string[] | null; }; //#endregion //#region src/experimental/route-resolver/matchers/param-parsers/standard-schema-types.d.ts /** * Inlined subset of `@standard-schema/spec` v1.1.0 so the distributed code * has zero external type dependencies. Keep the package installed to track * upstream changes. * * @see https://github.com/standard-schema/standard-schema */ /** The Standard Schema interface. */ interface StandardSchemaV1<Input = unknown, Output = Input> { /** The Standard Schema properties. */ readonly '~standard': StandardSchemaV1.Props<Input, Output>; } declare namespace StandardSchemaV1 { /** The Standard Schema properties interface. */ interface Props<Input = unknown, Output = Input> { /** The version number of the standard. */ readonly version: 1; /** The vendor name of the schema library. */ readonly vendor: string; /** Inferred types associated with the schema. */ readonly types?: Types<Input, Output> | undefined; /** Validates unknown input values. */ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>; } /** The Standard Schema types interface. */ interface Types<Input = unknown, Output = Input> { /** The input type of the schema. */ readonly input: Input; /** The output type of the schema. */ readonly output: Output; } /** The result interface of the validate function. */ type Result<Output> = SuccessResult<Output> | FailureResult; /** The result interface if validation succeeds. */ interface SuccessResult<Output> { /** The typed output value. */ readonly value: Output; /** A falsy value for `issues` indicates success. */ readonly issues?: undefined; } /** The result interface if validation fails. */ interface FailureResult { /** The issues of failed validation. */ readonly issues: ReadonlyArray<Issue>; } /** The issue interface of the failure output. */ interface Issue { /** The error message of the issue. */ readonly message: string; /** The path of the issue, if any. */ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined; } /** The path segment interface of the issue. */ interface PathSegment { /** The key representing a path segment. */ readonly key: PropertyKey; } /** Infers the input type of a Standard Schema. */ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input']; /** Infers the output type of a Standard Schema. */ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output']; } //#endregion //#region src/experimental/route-resolver/matchers/param-parsers/standard-schema.d.ts /** * Normalizes a param parser input, converting a StandardSchema-compliant object * into a {@link ParamParser} if needed. * * @param parser - a param parser or a StandardSchema-compliant validator * * @internal */ declare function normalizeParamParser<TParam = MatcherQueryParamsValue, TUrlParam = MatcherQueryParamsValue, TParamRaw = TParam>(parser: ParamParser<TParam, TUrlParam, TParamRaw> | StandardSchemaV1<unknown, TParam>): ParamParser<TParam, TUrlParam, TParamRaw>; /** * Extracts the param type from Param Parsers or StandardSchema validators. * * @internal */ type ExtractParamParserType<PP> = PP extends ParamParser<infer T, any, any> ? T : PP extends StandardSchemaV1<unknown, infer T> ? T : unknown; //#endregion //#region src/experimental/route-resolver/matchers/matcher-pattern-query.d.ts /** * Handles the `query` part of a URL. It can transform a query object into an * object of params and vice versa. */ interface MatcherPatternQuery<TParams extends MatcherParamsFormatted = MatcherParamsFormatted> extends MatcherPattern<MatcherQueryParams, TParams> {} /** * Matcher for a specific query parameter. It will read and write the parameter */ declare class MatcherPatternQueryParam<T, ParamName extends string> implements MatcherPatternQuery<Record<ParamName, T>> { private paramName; private queryKey; private format; private parser; private defaultValue?; private required?; constructor(paramName: ParamName, queryKey: string, format: 'value' | 'array', parser?: ParamParser<T>, defaultValue?: ((() => T) | T) | undefined, required?: boolean | undefined); match(query: MatcherQueryParams): Record<ParamName, T>; build(params: Record<ParamName, T>): MatcherQueryParams; } //#endregion //#region src/experimental/route-resolver/resolver-fixed.d.ts /** * Base interface for a resolver record that can be extended. */ interface EXPERIMENTAL_ResolverRecord_Base { /** * Name of the matcher. Unique across all matchers. If missing, this record * cannot be matched. This is useful for grouping records. */ name?: RecordName; /** * {@link MatcherPattern} for the path section of the URI. */ path?: MatcherPatternPath; /** * {@link MatcherPattern} for the query section of the URI. */ query?: MatcherPatternQuery[]; /** * {@link MatcherPattern} for the hash section of the URI. */ hash?: MatcherPatternHash; /** * Parent record. The parent can be a group or a matchable record. * It will be included in the `matched` array of a resolved location. */ parent?: EXPERIMENTAL_ResolverRecord_Base | null; /** * If this record is an alias of another record, this points to the original * record. Alias records are not added to the name map and resolve to the * original record's name. */ aliasOf?: EXPERIMENTAL_ResolverRecord_Base | null; } /** * A group can contain other useful properties like `meta` defined by the router. */ interface EXPERIMENTAL_ResolverRecord_Group extends EXPERIMENTAL_ResolverRecord_Base { /** * A group route cannot be matched directly and cannot be named. */ name?: undefined; /** * A group route can **only** match the `query`. */ path?: undefined; /** * A group route can **only** match the `query`. */ hash?: undefined; } /** * A matchable record is a record that can be matched by a path, query or hash * and will resolve to a location. */ interface EXPERIMENTAL_ResolverRecord_Matchable extends EXPERIMENTAL_ResolverRecord_Base { name: RecordName; path: MatcherPatternPath; } /** * @alias EXPERIMENTAL_Resolver_Base */ interface EXPERIMENTAL_ResolverFixed<TRecord> extends EXPERIMENTAL_Resolver_Base<TRecord> {} /** * Creates a fixed resolver that must have all records defined at creation * time. * * @template TRecord - extended type of the records * @param {TRecord[]} records - Ordered array of records that will be used to resolve routes * @returns a resolver that can be passed to the router */ declare function createFixedResolver<TRecord extends EXPERIMENTAL_ResolverRecord_Matchable>(records: TRecord[]): EXPERIMENTAL_ResolverFixed<TRecord>; //#endregion //#region src/experimental/router.d.ts /** * Options to initialize a {@link Router} instance. */ interface EXPERIMENTAL_RouterOptions_Base extends PathParserOptions { /** * History implementation used by the router. Most web applications should use * `createWebHistory` but it requires the server to be properly configured. * You can also use a _hash_ based history with `createWebHashHistory` that * does not require any configuration on the server but isn't handled at all * by search engines and does poorly on SEO. * * @example * ```js * createRouter({ * history: createWebHistory(), * // other options... * }) * ``` */ history: RouterHistory; /** * Function to control scrolling when navigating between pages. Can return a * Promise to delay scrolling. * * @see {@link RouterScrollBehavior}. * * @example * ```js * function scrollBehavior(to, from, savedPosition) { * // `to` and `from` are both route locations * // `savedPosition` can be null if there isn't one * } * ``` */ scrollBehavior?: RouterScrollBehavior; /** * Custom implementation to parse a query. See its counterpart, * {@link EXPERIMENTAL_RouterOptions_Base.stringifyQuery}. * * @example * Let's say you want to use the [qs package](https://github.com/ljharb/qs) * to parse queries, you can provide both `parseQuery` and `stringifyQuery`: * ```js * import qs from 'qs' * * createRouter({ * // other options... * parseQuery: qs.parse, * stringifyQuery: qs.stringify, * }) * ``` */ parseQuery?: typeof experimental_parseQuery; /** * Custom implementation to stringify a query object. Should not prepend a leading `?`. * {@link parseQuery} counterpart to handle query parsing. */ stringifyQuery?: typeof stringifyQuery; /** * Default class applied to active {@link RouterLink}. If none is provided, * `router-link-active` will be applied. */ linkActiveClass?: string; /** * Default class applied to exact active {@link RouterLink}. If none is provided, * `router-link-exact-active` will be applied. */ linkExactActiveClass?: string; } /** * Internal type for common properties among all kind of {@link RouteRecordRaw}. */ interface EXPERIMENTAL_RouteRecord_Base extends EXPERIMENTAL_ResolverRecord_Base { /** * Where to redirect if the route is directly matched. The redirection happens * before any navigation guard and triggers a new navigation with the new * target location. */ redirect?: RouteRecordRedirectOption; /** * Before Enter guard specific to this record. Note `beforeEnter` has no * effect if the record has a `redirect` property. */ /** * Arbitrary data attached to the record. */ meta?: RouteMeta; /** * Components to display when the URL matches this route. Allow using named views. */ components?: Record<string, RawRouteComponent>; /** * Parent of this component if any */ parent?: EXPERIMENTAL_RouteRecordNormalized | null; /** * References another record if this record is an alias of it. */ aliasOf?: EXPERIMENTAL_RouteRecordNormalized | null; } interface EXPERIMENTAL_RouteRecord_Redirect extends Omit<EXPERIMENTAL_RouteRecord_Base, 'name' | 'path'>, Omit<EXPERIMENTAL_ResolverRecord_Matchable, 'parent' | 'aliasOf'> { components?: Record<string, RawRouteComponent>; redirect: RouteRecordRedirectOption; } interface EXPERIMENTAL_RouteRecord_Group extends Omit<EXPERIMENTAL_RouteRecord_Base, 'name' | 'path' | 'query' | 'hash'>, Omit<EXPERIMENTAL_ResolverRecord_Group, 'parent' | 'aliasOf'> { components?: Record<string, RawRouteComponent>; } interface EXPERIMENTAL_RouteRecord_Components extends Omit<EXPERIMENTAL_RouteRecord_Base, 'name' | 'path'>, Omit<EXPERIMENTAL_ResolverRecord_Matchable, 'parent' | 'aliasOf'> { components: Record<string, RawRouteComponent>; redirect?: never; } type EXPERIMENTAL_RouteRecord_Matchable = EXPERIMENTAL_RouteRecord_Components | EXPERIMENTAL_RouteRecord_Redirect; type EXPERIMENTAL_RouteRecordRaw = EXPERIMENTAL_RouteRecord_Matchable | EXPERIMENTAL_RouteRecord_Group; interface EXPERIMENTAL_RouteRecordNormalized_Base { /** * Contains the original modules for lazy loaded components. * * @internal */ mods: Record<string, unknown>; props: Record<string, _RouteRecordProps>; /** * Registered leave guards * * @internal */ leaveGuards: Set<NavigationGuard>; /** * Registered update guards * * @internal */ updateGuards: Set<NavigationGuard>; instances: Record<string, unknown>; } interface EXPERIMENTAL_RouteRecordNormalized_Group extends EXPERIMENTAL_RouteRecordNormalized_Base, EXPERIMENTAL_RouteRecord_Group { meta: RouteMeta; } interface EXPERIMENTAL_RouteRecordNormalized_Redirect extends EXPERIMENTAL_RouteRecordNormalized_Base, EXPERIMENTAL_RouteRecord_Redirect { meta: RouteMeta; } interface EXPERIMENTAL_RouteRecordNormalized_Components extends EXPERIMENTAL_RouteRecordNormalized_Base, EXPERIMENTAL_RouteRecord_Components { meta: RouteMeta; } type EXPERIMENTAL_RouteRecordNormalized_Matchable = EXPERIMENTAL_RouteRecordNormalized_Components | EXPERIMENTAL_RouteRecordNormalized_Redirect; type EXPERIMENTAL_RouteRecordNormalized = EXPERIMENTAL_RouteRecordNormalized_Matchable | EXPERIMENTAL_RouteRecordNormalized_Group; declare function normalizeRouteRecord(record: EXPERIMENTAL_RouteRecord_Group): EXPERIMENTAL_RouteRecordNormalized_Group; declare function normalizeRouteRecord(record: EXPERIMENTAL_RouteRecord_Matchable): EXPERIMENTAL_RouteRecordNormalized_Matchable; /** * Options to initialize an experimental {@link EXPERIMENTAL_Router} instance. * @experimental */ interface EXPERIMENTAL_RouterOptions extends EXPERIMENTAL_RouterOptions_Base { /** * Matcher to use to resolve routes. * * @experimental */ resolver: EXPERIMENTAL_ResolverFixed<EXPERIMENTAL_RouteRecordNormalized_Matchable>; } /** * Router base instance. * * @experimental This version is not stable, it's meant to replace {@link Router} in the future. */ interface EXPERIMENTAL_Router_Base<TRecord> extends DataLoaderExtensions { /** * Current {@link RouteLocationNormalized} */ readonly currentRoute: ShallowRef<RouteLocationNormalizedLoaded>; /** * Allows turning off the listening of history events. This is a low level api for micro-frontend. */ listening: boolean; /** * Checks if a route with a given name exists * * @param name - Name of the route to check */ hasRoute(name: NonNullable<RouteRecordNameGeneric>): boolean; /** * Get a full list of all the {@link RouteRecord | route records}. */ getRoutes(): TRecord[]; /** * Returns the {@link RouteLocation | normalized version} of a * {@link RouteLocationRaw | route location}. Also includes an `href` property * that includes any existing `base`. By default, the `currentLocation` used is * `router.currentRoute` and should only be overridden in advanced use cases. * * @param to - Raw route location to resolve * @param currentLocation - Optional current location to resolve against */ resolve<Name extends keyof RouteMap = keyof RouteMap>(to: RouteLocationAsRelativeTyped<RouteMap, Name>, currentLocation?: RouteLocationNormalizedLoaded): RouteLocationResolved<Name>; resolve(to: RouteLocationAsString | RouteLocationAsRelative | RouteLocationAsPath, currentLocation?: RouteLocationNormalizedLoaded): RouteLocationResolved; /** * Program