UNPKG

vue-router

Version:
476 lines (475 loc) • 17.6 kB
/*! * vue-router v5.5.3 * (c) 2026 Eduardo San Martin Morote * @license MIT */ import { h as isArray, m as isAbsolutePath, n as routeLocationKey, r as routerKey, s as diagnostics, y as noop } from "./injectionSymbols-CGHHjbrE.js"; import { computed, defineComponent, getCurrentInstance, h, inject, reactive, shallowReactive, unref, watchEffect } from "vue"; // src/utils/env.ts const isBrowser = typeof document !== "undefined"; // src/encoding.ts /** * Encoding Rules (␣ = Space) * - Path: ␣ " < > # ? { } * - Query: ␣ " < > # & = ' (`'` like the special-query set of new URL()) * - Hash: ␣ " < > ` * * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) * defines some extra characters to be encoded. Most browsers do not encode them * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to * also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`) * plus `-._~`. This extra safety should be applied to query by patching the * string returned by encodeURIComponent encodeURI also encodes `[\]^`. * * `\` is always encoded. In the path, browsers transform a `\` into a `/`. * In the query and hash, `new URL()` keeps it but it is not a valid URL code * point, so `%5C` keeps the URL valid. The _backtick_ (`````) should also be * encoded everywhere because some browsers like FF encode it when directly * written while others don't. Safari and IE don't encode ``"<>{}``` in hash. */ /** * NOTE: `replaceAll()` is not faster than `replace()` with a global RegExp. * Benchmarks do not show a clear benefit for these simple replacements: * https://github.com/mathiasbynens/string-prototype-replace-regexp-benchmark */ const HASH_RE = /#/g; const AMPERSAND_RE = /&/g; const SLASH_RE = /\//g; const EQUAL_RE = /=/g; const IM_RE = /\?/g; const PLUS_RE = /\+/g; const APOSTROPHE_RE = /'/g; const BACKSLASH_RE = /\\/g; /** * NOTE: queries follow application/x-www-form-urlencoded, like * `URLSearchParams`: a space is encoded as `+`, a `+` as `%2B`, and * `parseQuery()` decodes `+` as a space. Search engines (e.g. Chrome's omnibox) * create links with `+` for spaces (#561). Always writing `+` keeps the * encoding consistent and idempotent, even if `new URL()` writes `%20`. * * Resources: * - https://url.spec.whatwg.org/#urlencoded-parsing * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20 */ const ENC_BRACKET_OPEN_RE = /%5B/g; const ENC_BRACKET_CLOSE_RE = /%5D/g; const ENC_CARET_RE = /%5E/g; const ENC_BACKTICK_RE = /%60/g; const ENC_CURLY_OPEN_RE = /%7B/g; const ENC_PIPE_RE = /%7C/g; const ENC_CURLY_CLOSE_RE = /%7D/g; const ENC_SPACE_RE = /%20/g; /** * Encode characters that need to be encoded on the path, search and hash * sections of the URL. * * @internal * @param text - string to encode * @returns encoded string */ function commonEncode(text) { return text == null ? "" : encodeURI("" + text).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]"); } /** * Encode characters that need to be encoded on the hash section of the URL. * * @param text - string to encode * @returns encoded string * * @internal Exposed for integrations (e.g. Nuxt). Not covered by semver. */ function encodeHash(text) { return commonEncode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); } /** * Encode characters that need to be encoded query values on the query * section of the URL. * * @param text - string to encode * @returns encoded string * * @internal Exposed for integrations (e.g. Nuxt). Not covered by semver. */ function encodeQueryValue(text) { return commonEncode(text).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(APOSTROPHE_RE, "%27").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); } /** * Like `encodeQueryValue` but also encodes the `=` character. * * @param text - string to encode * * @internal Exposed for integrations (e.g. Nuxt). Not covered by semver. */ function encodeQueryKey(text) { return encodeQueryValue(text).replace(EQUAL_RE, "%3D"); } /** * Encode characters that need to be encoded on the path section of the URL. * * @param text - string to encode * @returns encoded string * * @internal Exposed for integrations (e.g. Nuxt). Not covered by semver. */ function encodePath(text) { return commonEncode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F"); } /** * Encode characters that need to be encoded on the path section of the URL as a * param. This function encodes everything {@link encodePath} does plus the * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty * string instead. * * @param text - string to encode * @returns encoded string * * @internal Exposed for integrations (e.g. Nuxt). Not covered by semver. */ function encodeParam(text) { return encodePath(text).replace(SLASH_RE, "%2F"); } function decode(text) { if (text == null) return null; try { return decodeURIComponent("" + text); } catch { process.env.NODE_ENV !== "production" && diagnostics.VUE_ROUTER_R0080({ text: "" + text }); } return "" + text; } // src/location.ts const TRAILING_SLASH_RE = /\/$/; const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ""); /** * Transforms a URI into a normalized history location. * * Only handles paths: a protocol and host (`https://a.com/x`) are not parsed * and end up in `path`. `path` is not decoded, `hash` is decoded. `fullPath` is * the resolved `path` plus the raw query and hash, so it does not keep a * relative input (`../a` gives `/a`). * * @internal no semver guarantee * @param parseQuery - receives the search without the leading `?` * @param location - URI to normalize * @param currentLocation - current absolute location. Allows resolving relative * paths. Must start with `/`. Defaults to `/` * @returns a normalized history location */ function parseURL(parseQuery, location, currentLocation = "/") { let path, query = {}, searchString = "", hash = ""; const hashPos = location.indexOf("#"); let searchPos = location.indexOf("?"); searchPos = hashPos >= 0 && searchPos > hashPos ? -1 : searchPos; if (searchPos >= 0) { path = location.slice(0, searchPos); searchString = location.slice(searchPos, hashPos > 0 ? hashPos : location.length); query = parseQuery(searchString.slice(1)); } if (hashPos >= 0) { path = path != null ? path : location.slice(0, hashPos); hash = location.slice(hashPos, location.length); } path = resolveRelativePath(path != null ? path : location, currentLocation); return { fullPath: path + searchString + hash, path, query, hash: decode(hash) }; } /** * Stringifies a URL object. `path` and `hash` are used as is (no encoding), * `hash` must start with `#`. * * @internal no semver guarantee * @param stringifyQuery * @param location */ function stringifyURL(stringifyQuery, location) { const query = location.query ? stringifyQuery(location.query) : ""; return location.path + (query && "?") + query + (location.hash || ""); } /** * Strips off the base from the beginning of a location.pathname in a non-case-sensitive way. * `base` must be normalized like `router.options.history.base` (no trailing slash). * * @param pathname - location.pathname * @param base - base to strip off */ function stripBase(pathname, base) { if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) return pathname; return pathname.slice(base.length) || "/"; } /** * Checks if two RouteLocation are equal. This means that both locations are * pointing towards the same {@link RouteRecord} and that all `params`, `query` * parameters and `hash` are the same * * @param stringifyQuery - A function that takes a query object of type LocationQueryRaw and returns a string representation of it. * @param a - first {@link RouteLocation} * @param b - second {@link RouteLocation} */ function isSameRouteLocation(stringifyQuery, a, b) { const aLastIndex = a.matched.length - 1; const bLastIndex = b.matched.length - 1; return aLastIndex > -1 && aLastIndex === bLastIndex && isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && isSameRouteLocationParams(a.params, b.params) && stringifyQuery(a.query) === stringifyQuery(b.query) && a.hash === b.hash; } /** * Check if two `RouteRecords` are equal. Takes into account aliases: they are * considered equal to the `RouteRecord` they are aliasing. * * @param a - first {@link RouteRecord} * @param b - second {@link RouteRecord} */ function isSameRouteRecord(a, b) { return (a.aliasOf || a) === (b.aliasOf || b); } function isSameRouteLocationParams(a, b) { if (Object.keys(a).length !== Object.keys(b).length) return false; for (var key in a) if (!isSameRouteLocationParamsValue(a[key], b[key])) return false; return true; } function isSameRouteLocationParamsValue(a, b) { return isArray(a) ? isEquivalentArray(a, b) : isArray(b) ? isEquivalentArray(b, a) : (a && a.valueOf()) === (b && b.valueOf()); } /** * Check if two arrays are the same or if an array with one single entry is the * same as another primitive value. Used to check query and parameters * * @param a - array of values * @param b - array of values or a single value */ function isEquivalentArray(a, b) { return isArray(b) ? a.length === b.length && a.every((value, i) => value === b[i]) : a.length === 1 && a[0] === b; } /** * Resolves a relative path that starts with `.`. * * @param to - path location we are resolving * @param from - currentLocation.path, should start with `/` */ function resolveRelativePath(to, from) { if (isAbsolutePath(to)) return to; if (process.env.NODE_ENV !== "production" && !isAbsolutePath(from)) { diagnostics.VUE_ROUTER_R0070({ to, from }); return to; } if (!to) return from; const fromSegments = from.split("/"); const toSegments = to.split("/"); const lastToSegment = toSegments[toSegments.length - 1]; if (lastToSegment === ".." || lastToSegment === ".") toSegments.push(""); let position = fromSegments.length - 1; let toPosition; let segment; for (toPosition = 0; toPosition < toSegments.length; toPosition++) { segment = toSegments[toPosition]; if (segment === ".") continue; if (segment === "..") { if (position > 1) position--; } else break; } return fromSegments.slice(0, position).join("/") + "/" + toSegments.slice(toPosition).join("/"); } /** * 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 * } * }) * ``` */ const START_LOCATION_NORMALIZED = { path: "/", name: void 0, params: {}, query: {}, hash: "", fullPath: "/", matched: [], meta: {}, redirectedFrom: void 0 }; /** * Creates the reactive route returned by `useRoute()` from a route ref. * * @internal */ function createReactiveRoute(routeRef) { const route = {}; for (const key in START_LOCATION_NORMALIZED) Object.defineProperty(route, key, { get: () => routeRef.value[key], enumerable: true }); return shallowReactive(route); } // src/types/typeGuards.ts function isRouteLocation(route) { return typeof route === "string" || route && typeof route === "object"; } function isRouteName(name) { return typeof name === "string" || typeof name === "symbol"; } // src/RouterLink.ts /** * Returns the internal behavior of a {@link RouterLink} without the rendering part. * * @param props - a `to` location and an optional `replace` flag */ function useLink(props) { const router = inject(routerKey); const currentRoute = inject(routeLocationKey); let hasPrevious = false; let previousTo = null; const route = computed(() => { const to = unref(props.to); if (process.env.NODE_ENV !== "production" && (!hasPrevious || to !== previousTo)) { if (!isRouteLocation(to)) diagnostics.VUE_ROUTER_R0050({ to }); previousTo = to; hasPrevious = true; } return router.resolve(to); }); const activeRecordIndex = computed(() => { const { matched } = route.value; const { length } = matched; const routeMatched = matched[length - 1]; const currentMatched = currentRoute.matched; if (!routeMatched || !currentMatched.length) return -1; const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched)); if (index > -1) return index; const parentRecordPath = getOriginalPath(matched[length - 2]); return length > 1 && getOriginalPath(routeMatched) === parentRecordPath && currentMatched[currentMatched.length - 1].path !== parentRecordPath ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) : index; }); const isActive = computed(() => activeRecordIndex.value > -1 && includesParams(currentRoute.params, route.value.params)); const isExactActive = computed(() => activeRecordIndex.value > -1 && activeRecordIndex.value === currentRoute.matched.length - 1 && isSameRouteLocationParams(currentRoute.params, route.value.params)); function navigate(e = {}) { if (shouldHandleLinkClick(e)) { e.preventDefault?.(); const p = router[unref(props.replace) ? "replace" : "push"](unref(props.to)).catch(noop); if (props.viewTransition && typeof document !== "undefined" && "startViewTransition" in document) document.startViewTransition(() => p); return p; } return Promise.resolve(); } if ((process.env.NODE_ENV !== "production" || __VUE_PROD_DEVTOOLS__) && isBrowser) { const instance = getCurrentInstance(); if (instance) { const linkContextDevtools = { route: route.value, isActive: isActive.value, isExactActive: isExactActive.value, error: null }; instance.__vrl_devtools = instance.__vrl_devtools || []; instance.__vrl_devtools.push(linkContextDevtools); watchEffect(() => { linkContextDevtools.route = route.value; linkContextDevtools.isActive = isActive.value; linkContextDevtools.isExactActive = isExactActive.value; linkContextDevtools.error = isRouteLocation(unref(props.to)) ? null : "Invalid \"to\" value"; }, { flush: "post" }); } } return { route, href: computed(() => route.value.href), isActive, isExactActive, navigate }; } /** @internal */ function preferSingleVNode(vnodes) { return vnodes.length === 1 ? vnodes[0] : vnodes; } /** * Component to render a link that triggers a navigation on click. */ const RouterLink = /* @__PURE__ */ defineComponent({ name: "RouterLink", compatConfig: { MODE: 3 }, props: { to: { type: [String, Object], required: true }, replace: Boolean, activeClass: String, exactActiveClass: String, custom: Boolean, ariaCurrentValue: { type: String, default: "page" }, viewTransition: Boolean }, useLink, setup(props, { slots }) { const link = reactive(useLink(props)); const { options } = inject(routerKey); const elClass = computed(() => ({ [getLinkClass(props.activeClass, options.linkActiveClass, "router-link-active")]: link.isActive, [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, "router-link-exact-active")]: link.isExactActive })); return () => { const children = slots.default && preferSingleVNode(slots.default(link)); return props.custom ? children : h("a", { "aria-current": link.isExactActive ? props.ariaCurrentValue : null, href: link.href, onClick: link.navigate, class: elClass.value }, children); }; } }); const BLANK_TARGET_RE = /\b_blank\b/i; /** * Checks if a click on a link should trigger a client-side navigation. Does * not call `e.preventDefault()`. * * @param e - the click event * @param el - the link element. Defaults to `e.currentTarget`. Pass it when * using event delegation. * * @internal no semver guarantee, can change in any release */ function shouldHandleLinkClick(e, el = e.currentTarget) { return !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey || e.defaultPrevented || e.button || BLANK_TARGET_RE.test(el?.getAttribute?.("target") || "")); } /** @internal */ function includesParams(outer, inner) { for (const key in inner) { const innerValue = inner[key]; const outerValue = outer[key]; if (isArray(innerValue)) { if (!isArray(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i) => value.valueOf() !== outerValue[i].valueOf())) return false; } else if (innerValue !== outerValue) return false; } return true; } /** * Get the original path value of a record by following its aliasOf * @param record */ function getOriginalPath(record) { return record ? record.aliasOf ? record.aliasOf.path : record.path : ""; } /** * Utility class to get the active class based on defaults. * @param propClass * @param globalClass * @param defaultClass */ const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null ? propClass : globalClass != null ? globalClass : defaultClass; export { encodeHash as C, encodeQueryValue as D, encodeQueryKey as E, isBrowser as O, decode as S, encodePath as T, stripBase as _, useLink as a, PLUS_RE as b, START_LOCATION_NORMALIZED as c, isSameRouteLocationParams as d, isSameRouteRecord as f, stringifyURL as g, resolveRelativePath as h, shouldHandleLinkClick as i, createReactiveRoute as l, removeTrailingSlash as m, includesParams as n, isRouteLocation as o, parseURL as p, preferSingleVNode as r, isRouteName as s, RouterLink as t, isSameRouteLocation as u, BACKSLASH_RE as v, encodeParam as w, commonEncode as x, ENC_SPACE_RE as y };