@ljweb/uniapp-router-next
Version:
> 一个类似于vue-router的路由器,用于uniapp(vue3),支持h5和微信小程序和app,其他小程序请自测
1,251 lines (1,226 loc) • 42.1 kB
JavaScript
;
var vue = require('vue');
function useCallbacks() {
let handlers = [];
function add(handler) {
handlers.push(handler);
return () => {
const i = handlers.indexOf(handler);
if (i > -1)
handlers.splice(i, 1);
};
}
function reset() {
handlers = [];
}
return {
add,
list: () => handlers,
reset
};
}
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 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;
function commonEncode(text) {
return encodeURI(`${text}`).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]");
}
function encodeHash(text) {
return commonEncode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
}
function encodeQueryValue(text) {
return commonEncode(text).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
}
function encodeQueryKey(text) {
return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
}
function encodePath(text) {
return commonEncode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F");
}
function encodeParam(text) {
return text == null ? "" : encodePath(text).replace(SLASH_RE, "%2F");
}
function decode(text) {
try {
return decodeURIComponent(`${text}`);
} catch (err) {
warn(`Error decoding "${text}". Using original value`);
}
return `${text}`;
}
function warn(msg, debug = false, ...args) {
debug && console.warn(`[uni-router warn]: ${msg}`, ...args);
}
function error(msg) {
throw new Error(`[uni-router warn]: ${msg}`);
}
const NavigationFailureSymbol = Symbol("navigation failure");
const ErrorTypeMessages = {
[
1
/* NavigationErrorTypes.MATCHER_NOT_FOUND */
]({ location }) {
return `Navigation ${typeof location === "string" ? location : JSON.stringify(location)} is not found`;
},
[
2
/* NavigationErrorTypes.NAVIGATION_GUARD_REDIRECT */
]({ from, to }) {
return `Redirected from "${JSON.stringify(from)}" to "${JSON.stringify(to)}" via a navigation guard.`;
},
[
4
/* NavigationErrorTypes.NAVIGATION_ABORTED */
]({ from, to }) {
return `Navigation aborted from "${JSON.stringify(from)}" to "${JSON.stringify(to)}" via a navigation guard.`;
},
[
8
/* NavigationErrorTypes.NAVIGATION_CANCELLED */
]({ from, to }) {
return `Navigation cancelled from "${JSON.stringify(from)}" to "${JSON.stringify(to)}" with a new navigation.`;
},
[
16
/* NavigationErrorTypes.NAVIGATION_DUPLICATED */
]({ from, to }) {
return `Avoided redundant navigation to current location: "${JSON.stringify(from)}".`;
}
};
function isNavigationFailure(error, type) {
return error instanceof Error && NavigationFailureSymbol in error && (type == null || !!(error.type & type));
}
function createRouterError(type, params) {
return Object.assign(new Error(ErrorTypeMessages[type](params)), {
type,
[NavigationFailureSymbol]: true
}, params);
}
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isArray = Array.isArray;
const isMap = (val) => toTypeString(val) === "[object Map]";
const isSet = (val) => toTypeString(val) === "[object Set]";
const isDate = (val) => toTypeString(val) === "[object Date]";
const isRegExp = (val) => toTypeString(val) === "[object RegExp]";
const isFunction = (val) => typeof val === "function";
const isString = (val) => typeof val === "string";
const isSymbol = (val) => typeof val === "symbol";
const isObject = (val) => val != null && typeof val === "object";
const mpPlatformReg = /(^mp-weixin$)|(^mp-baidu$)|(^mp-alipay$)|(^mp-toutiao$)|(^mp-qq$)|(^mp-360$)/g;
const uniRouterApiName = [
"navigateTo",
"redirectTo",
"reLaunch",
"switchTab",
"navigateBack"
];
exports.NavigationTypesEnums = void 0;
(function(NavigationTypesEnums2) {
NavigationTypesEnums2["navigate"] = "navigateTo";
NavigationTypesEnums2["redirect"] = "redirectTo";
NavigationTypesEnums2["reLaunch"] = "reLaunch";
NavigationTypesEnums2["switchTab"] = "switchTab";
NavigationTypesEnums2["navigateBack"] = "navigateBack";
})(exports.NavigationTypesEnums || (exports.NavigationTypesEnums = {}));
const START_LOCATION_NORMALIZED = {
path: "/",
name: "",
query: {},
fullPath: "/",
meta: {}
};
const WILDCARD = "*";
const WILDCARD_ROUTE = {
path: "*"
};
const routerKey = Symbol();
const routeLocationKey = Symbol();
function useRouter() {
return vue.inject(routerKey);
}
function useRoute() {
return vue.inject(routeLocationKey);
}
const uniRouterApi = {
navigateTo: uni.navigateTo,
redirectTo: uni.redirectTo,
reLaunch: uni.reLaunch,
switchTab: uni.switchTab,
navigateBack: uni.navigateBack
};
function rewriteUniRouterApi(router) {
uniRouterApiName.forEach((apiName) => {
uni[apiName] = function(options) {
return router[apiName](options);
};
});
}
function parseQuery(search) {
const query = {};
if (search === "" || search === "?")
return query;
const hasLeadingIM = search[0] === "?";
const searchParams = (hasLeadingIM ? search.slice(1) : search).split("&");
for (let i = 0; i < searchParams.length; ++i) {
const searchParam = searchParams[i].replace("+", " ");
const eqPos = searchParam.indexOf("=");
const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
query[key] = value;
}
return query;
}
function decodeQuery(query) {
for (const key in query) {
const value = query[key];
if (value != null) {
query[key] = decode(value);
}
}
return query;
}
function stringifyQuery(query) {
let search = "";
for (let key in query) {
const value = query[key];
key = encodeQueryValue(key);
if (value == null) {
if (value !== void 0) {
search += (search.length ? "&" : "") + key;
}
continue;
}
if (value !== void 0) {
search += (search.length ? "&" : "") + key;
if (value != null)
search += `=${encodeQueryValue(value)}`;
}
}
return search;
}
function parseURL(parseQuery, location, currentLocation = "/") {
if (location === WILDCARD) {
return {
path: location,
query: {}
};
}
let path, query = {}, searchString = "";
const searchPos = location.indexOf("?");
if (searchPos > -1) {
path = location.slice(0, searchPos);
searchString = location.slice(searchPos + 1);
query = parseQuery(searchString);
} else {
path = location;
}
path = resolveRelativePath(path != null ? path : location, currentLocation);
return {
path,
query
};
}
function stringifyURL(stringifyQuery, location) {
const query = location.query ? stringifyQuery(location.query) : "";
return location.path + (query && "?") + query;
}
function getEnterRoute(router) {
const options = uni.getLaunchOptionsSync();
return {
path: `/${options.path}`,
query: options.query || {}
};
}
function resolveRelativePath(to, from) {
if (to.startsWith("/"))
return to;
if (!from.startsWith("/")) {
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 - (toPosition === toSegments.length ? 1 : 0)).join("/")}`;
}
function createRouteMatcher(options) {
const aliasPathToRouteMap = /* @__PURE__ */ new Map();
const pathToRouteMap = /* @__PURE__ */ new Map();
const nameToRouteMap = /* @__PURE__ */ new Map();
function createRouteRecord(route) {
let { path, aliasPath, name } = route;
const routeStr = JSON.stringify(route);
if (path == null || path === void 0) {
warn(`\u5F53\u524D\u8DEF\u7531\u5BF9\u8C61route\uFF1A${routeStr}\u4E0D\u89C4\u8303\uFF0C\u5FC5\u987B\u542B\u6709\`path\``, options.debug);
}
if (path.indexOf("/") !== 0 && path !== "*") {
warn(`\u5F53\u524D\u8DEF\u7531\u5BF9\u8C61route\uFF1A${routeStr} \`path\`\u7F3A\u5C11\u524D\u7F00 \u2018/\u2019`, options.debug);
}
aliasPath = aliasPath || path;
pathToRouteMap.set(path, route);
aliasPathToRouteMap.set(aliasPath, route);
if (name) {
if (nameToRouteMap.has(name)) {
warn(`\u5F53\u524D\u8DEF\u7531\u5BF9\u8C61route\uFF1A${routeStr} \u7684\`name\`\u5DF2\u5B58\u5728\u8DEF\u7531\u8868\u4E2D\uFF0C\u5C06\u4F1A\u8986\u76D6\u65E7\u503C`, options.debug);
}
nameToRouteMap.set(name, route);
}
}
options.routes.forEach((route) => createRouteRecord(route));
function getRouteByAliasPath(aliasPath) {
return aliasPathToRouteMap.get(aliasPath);
}
function getRouteByPath(path) {
return pathToRouteMap.get(path);
}
function getRouteByName(name) {
return nameToRouteMap.get(name);
}
return {
getRouteByAliasPath,
getRouteByPath,
getRouteByName
};
}
function routeLocationNormalized(router, routeLocation) {
var _a;
let { fullPath, path, name, query, meta } = routeLocation;
const { getRouteByAliasPath, getRouteByPath } = router.routeMatcher;
const locationNormalized = Object.assign({}, START_LOCATION_NORMALIZED);
if (router.options.platform === "h5") {
const route = path === "/" ? getRouteByAliasPath(path) : getRouteByPath(path);
query = routeLocation.query = decodeQuery((_a = parseURL(router.parseQuery, fullPath)) === null || _a === void 0 ? void 0 : _a.query);
fullPath = stringifyURL(router.stringifyQuery, routeLocation);
meta = Object.assign({}, route === null || route === void 0 ? void 0 : route.meta, meta);
name = route === null || route === void 0 ? void 0 : route.name;
}
locationNormalized.fullPath = fullPath;
locationNormalized.meta = meta;
locationNormalized.path = path;
locationNormalized.name = name;
locationNormalized.query = query;
return locationNormalized;
}
function isRouteLocation(route) {
return typeof route === "string" || route && typeof route === "object";
}
function isSameRouteLocation(a, b) {
if (a.fullPath || b.fullPath) {
return a.fullPath === b.fullPath;
} else {
return false;
}
}
function createRoute404(router, to) {
const route = router.resolve(WILDCARD);
if (!route || typeof route.redirect === "undefined") {
warn("\u672A\u5339\u914D\u5230*\u901A\u914D\u7B26\u8DEF\u5F84\uFF0C\u6216\u8005*\u901A\u914D\u7B26\u5FC5\u987B\u914D\u5408 redirect \u4F7F\u7528\u3002redirect: string | Location", router.options.debug);
throw createRouterError(1, {
location: to
});
}
let redirect;
if (isFunction(route.redirect)) {
redirect = route.redirect(to);
} else {
redirect = route.redirect;
}
const targetLocation = router.resolve(redirect);
if (targetLocation === void 0) {
warn(`\u65E0\u6CD5\u89E3\u6790\u89E3\u6790\u51FAredirect\uFF1A${JSON.stringify(redirect)}\u4E2D\u7684\u5185\u5BB9\uFF0C`, router.options.debug);
throw createRouterError(1, {
location: to
});
}
return createRouterError(2, {
to: redirect,
from: to
});
}
function runGuardQueue(guards) {
return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve());
}
function guardToPromiseFn(guard, to, from) {
return () => new Promise((resolve, reject) => {
const next = (valid) => {
if (valid === false) {
reject(createRouterError(4, {
to,
from
}));
} else if (valid instanceof Error) {
reject(valid);
} else if (isRouteLocation(valid)) {
reject(createRouterError(2, {
to: valid,
from: to
}));
} else {
resolve();
}
};
const guardReturn = guard(to, from, next);
let guardCall = Promise.resolve(guardReturn);
if (typeof guardReturn === "object" && "then" in guardReturn) {
guardCall = guardCall.then(next);
} else if (guardReturn !== void 0) {
next(guardReturn);
}
guardCall.catch((err) => reject(err));
});
}
function getRouteByVueVm(vueVm, router) {
let path = vueVm.$scope.route;
path = path.startsWith("/") ? path : `/${path}`;
const query = vueVm.$scope.options || {};
return {
path,
query
};
}
var __async$3 = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
function createHook(originHook, proxyHook, vm, router) {
return (...args) => {
proxyHook.call(vm, args, (options) => {
originHook.apply(vm, options);
}, router);
};
}
function proxyPageHook(vm, router) {
console.log(vm);
if (!proxyHooksConfig$1)
return;
if (!vm.$scope)
return;
for (const proxyHookKey in proxyHooksConfig$1) {
const proxyHook = proxyHooksConfig$1[proxyHookKey];
const originHook = vm.$scope[proxyHookKey];
if (originHook) {
vm.$scope[proxyHookKey] = createHook(originHook, proxyHook, vm, router);
}
}
}
const proxyHooksConfig$1 = {
//修改onLoad拿到的参数
onLoad([options], originHook, router) {
originHook([decodeQuery(options)]);
},
onShow(options, originHook, router) {
console.log(options);
const pages = getCurrentPages();
const pagesLen = pages.length;
let toNormalized;
let fromNormalized;
if (router.fromRoute) {
toNormalized = router.currentRoute.value;
fromNormalized = router.fromRoute;
router.fromRoute = void 0;
} else {
const to = getRouteByVueVm(this);
toNormalized = routeLocationNormalized(router, router.resolve(to));
fromNormalized = router.currentRoute.value;
if (isSameRouteLocation(toNormalized, fromNormalized)) {
return originHook(options);
}
router.currentRoute.value = toNormalized;
}
const afterGuards = [];
for (const guard of router.guards.afterGuards.list()) {
afterGuards.push(() => __async$3(this, null, function* () {
guard(toNormalized, fromNormalized);
}));
}
runGuardQueue(afterGuards);
router.level = pagesLen;
originHook(options);
}
};
function getRouteByPages(pagesVm, router) {
const path = pagesVm.$page.path;
const query = pagesVm.$page.options || {};
return {
path,
query
};
}
var __async$2 = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
function proxyPageHookApp(vm, router) {
if (!proxyHooksConfig)
return;
if (!vm.$)
return;
for (const proxyHookKey in proxyHooksConfig) {
const proxyHook = proxyHooksConfig[proxyHookKey];
const originHook = vm.$[proxyHookKey];
if (isArray(originHook)) {
originHook.unshift(proxyHook.bind(vm, router));
} else {
vm.$[proxyHookKey] = [proxyHook.bind(vm, router)];
}
}
}
const proxyHooksConfig = {
onShow(router) {
const pages = getCurrentPages();
const pagesLen = pages.length;
let toNormalized;
let fromNormalized;
if (router.fromRoute) {
toNormalized = router.currentRoute.value;
fromNormalized = router.fromRoute;
router.fromRoute = void 0;
} else {
const to = getRouteByPages(this);
toNormalized = routeLocationNormalized(router, router.resolve(to));
fromNormalized = router.currentRoute.value;
if (isSameRouteLocation(toNormalized, fromNormalized)) {
return;
}
router.currentRoute.value = toNormalized;
}
const afterGuards = [];
for (const guard of router.guards.afterGuards.list()) {
afterGuards.push(() => __async$2(this, null, function* () {
guard(toNormalized, fromNormalized);
}));
}
runGuardQueue(afterGuards);
router.level = pagesLen;
}
};
function initMixins(app, router) {
const mixin = getMixinByPlatform(router);
app.mixin(mixin);
}
function getMixinByPlatform(router) {
let platform = router.options.platform;
if (mpPlatformReg.test(platform)) {
platform = "applets";
}
const mixinsMap = {
app: {
beforeCreate() {
if (this.$mpType === "page") {
proxyPageHookApp(this, router);
}
}
},
h5: {},
applets: {
beforeCreate() {
if (this.$mpType === "page") {
proxyPageHook(this, router);
}
}
}
};
return mixinsMap[platform] || {};
}
function mountVueRouter(app, router) {
const { h5: config } = router.options;
const vueRouter = app.config.globalProperties.$router;
const scrollBehavior = vueRouter.options.scrollBehavior;
Object.assign(vueRouter.options, config);
vueRouter.options.scrollBehavior = function(to, from, savedPosition) {
if (config === null || config === void 0 ? void 0 : config.scrollBehavior) {
return config === null || config === void 0 ? void 0 : config.scrollBehavior(to, from, savedPosition);
}
return scrollBehavior(to, from, savedPosition);
};
router.vueRouter = vueRouter;
for (const [guardName, guard] of Object.entries(router.guards)) {
guard.list().forEach((fn) => {
registerVueRooterGuards(router, guardName, fn);
});
}
vueRouter.afterEach((to) => {
router.currentRoute.value = routeLocationNormalized(router, to);
});
}
function registerVueRooterGuards(router, guardName, userGuard) {
var _a;
const guardHandler = {
beforeGuards: () => {
var _a2;
(_a2 = router.vueRouter) === null || _a2 === void 0 ? void 0 : _a2.beforeEach((to, from, next) => {
const toRoute = router.resolve(to);
const toNormalized = routeLocationNormalized(router, to);
const fromNormalized = routeLocationNormalized(router, from);
let failure;
if (toRoute === void 0) {
failure = createRoute404(router, toNormalized);
}
const proxyNext = (valid) => {
if (isRouteLocation(valid) && !(valid instanceof Error)) {
if (isString(valid) || !valid.navType) {
const redirect = router.resolve(valid);
if (redirect) {
next({
path: redirect.path,
query: redirect.query
});
}
} else {
const navType = valid.navType;
router.navigate(valid, navType);
}
} else {
next(valid);
}
};
if (isNavigationFailure(
failure,
2
/* NavigationErrorTypes.NAVIGATION_GUARD_REDIRECT */
)) {
router.redirectTo(failure === null || failure === void 0 ? void 0 : failure.to);
return proxyNext();
}
const guardReturn = userGuard(toNormalized, fromNormalized, proxyNext);
if (typeof guardReturn === "object" && "then" in guardReturn) {
guardReturn.then(proxyNext).catch(() => {
proxyNext(false);
});
} else if (guardReturn !== void 0) {
proxyNext(guardReturn);
}
});
},
afterGuards: () => {
var _a2;
(_a2 = router.vueRouter) === null || _a2 === void 0 ? void 0 : _a2.afterEach((to, from) => {
const toNormalized = routeLocationNormalized(router, to);
const fromNormalized = routeLocationNormalized(router, from);
userGuard(toNormalized, fromNormalized);
});
}
};
(_a = guardHandler[guardName]) === null || _a === void 0 ? void 0 : _a.call(guardHandler);
}
var __defProp$1 = Object.defineProperty;
var __defProps$1 = Object.defineProperties;
var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$1 = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp$1.call(b, prop))
__defNormalProp$1(a, prop, b[prop]);
if (__getOwnPropSymbols$1)
for (var prop of __getOwnPropSymbols$1(b)) {
if (__propIsEnum$1.call(b, prop))
__defNormalProp$1(a, prop, b[prop]);
}
return a;
};
var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
var __async$1 = (__this, __arguments, generator) => {
return new Promise((resolve2, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve2(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
function resolve$1(router, rawLocation, navType = "navigateTo") {
const { getRouteByName, getRouteByPath, getRouteByAliasPath } = router.routeMatcher;
if (isString(rawLocation)) {
rawLocation = { path: rawLocation };
}
if (Reflect.has(rawLocation, "delta") && navType === "navigateBack" || rawLocation.from === "backbutton") {
return rawLocation;
}
if (Reflect.has(rawLocation, "url")) {
rawLocation = __spreadProps$1(__spreadValues$1({}, rawLocation), {
path: rawLocation.url
});
}
const currentPath = router.currentRoute.value.path;
const currentLocation = currentPath === "/" ? getRouteByAliasPath(currentPath) : getRouteByPath(currentPath);
if (Reflect.has(rawLocation, "path")) {
const location = parseURL(router.parseQuery, rawLocation.path, currentLocation === null || currentLocation === void 0 ? void 0 : currentLocation.path);
let toRouteRecord = getRouteByPath(location.path);
if (toRouteRecord === void 0) {
toRouteRecord = getRouteByAliasPath(location.path);
}
if (toRouteRecord === void 0) {
return;
}
const query = Object.assign({}, location.query, rawLocation === null || rawLocation === void 0 ? void 0 : rawLocation.query);
const fullPath = stringifyURL(router.stringifyQuery, {
path: toRouteRecord.path,
query
});
return __spreadProps$1(__spreadValues$1({}, rawLocation), {
path: toRouteRecord.path,
meta: toRouteRecord.meta || {},
name: toRouteRecord.name,
redirect: toRouteRecord.redirect,
fullPath,
query
});
} else if (Reflect.has(rawLocation, "name")) {
let toRouteRecord = getRouteByName(rawLocation.name);
if (toRouteRecord === void 0) {
toRouteRecord = getRouteByPath(WILDCARD);
return;
}
const query = Object.assign({}, rawLocation.query);
const fullPath = stringifyURL(router.stringifyQuery, {
path: toRouteRecord.path,
query
});
return __spreadProps$1(__spreadValues$1({}, rawLocation), {
path: toRouteRecord.path,
meta: toRouteRecord.meta || {},
name: toRouteRecord.name,
redirect: toRouteRecord.redirect,
fullPath,
query
});
}
}
function mount$1(app, router) {
mountVueRouter(app, router);
}
function navigate$1(router, to, navType = "navigateTo", redirectedFrom) {
let targetLocation = router.resolve(to, navType);
let failure;
if (targetLocation === void 0) {
failure = createRoute404(router, to);
}
const from = router.currentRoute.value;
const pages = getCurrentPages();
if (navType === "navigateBack" && targetLocation.delta >= pages.length) {
targetLocation = router.resolve("/", "reLaunch");
navType = "reLaunch";
}
return (failure ? Promise.resolve(failure) : router.jump(targetLocation, navType)).catch((error) => {
return isNavigationFailure(
error,
2
/* NavigationErrorTypes.NAVIGATION_GUARD_REDIRECT */
) ? error : Promise.reject(error);
}).then((failure2) => {
if (failure2) {
if (isNavigationFailure(
failure2,
2
/* NavigationErrorTypes.NAVIGATION_GUARD_REDIRECT */
)) {
const failureTo = router.resolve(failure2 === null || failure2 === void 0 ? void 0 : failure2.to);
if (targetLocation && isSameRouteLocation(targetLocation, failureTo) && redirectedFrom && (redirectedFrom._count = redirectedFrom._count ? redirectedFrom._count + 1 : 1) > 30) {
vue.warn(`\u68C0\u6D4B\u5230\u4ECE\u201C${from.fullPath}\u201D\u5230\u201C${targetLocation.fullPath}\u201D\u65F6\u5BFC\u822A\u5B88\u536B\u4E2D\u53EF\u80FD\u5B58\u5728\u65E0\u9650\u91CD\u5B9A\u5411\u3002\u4E2D\u6B62\u4EE5\u907F\u514D\u5806\u6808\u6EA2\u51FA\u3002
\u662F\u5426\u603B\u662F\u5728\u5BFC\u822A\u9632\u62A4\u4E2D\u8FD4\u56DE\u65B0\u4F4D\u7F6E\uFF1F\u8FD9\u5C06\u5BFC\u81F4\u6B64\u9519\u8BEF\u3002\u4EC5\u5728\u91CD\u5B9A\u5411\u6216\u4E2D\u6B62\u65F6\u8FD4\u56DE\uFF0C\u8FD9\u5E94\u8BE5\u53EF\u4EE5\u89E3\u51B3\u6B64\u95EE\u9898\u3002\u5982\u679C\u672A\u4FEE\u590D\uFF0C\u8FD9\u53EF\u80FD\u4F1A\u5728\u751F\u4EA7\u4E2D\u4E2D\u65AD`, router.options.debug);
return Promise.reject(new Error("Infinite redirect in navigation guard"));
} else {
return router.navigate(failureTo, failureTo.navType, redirectedFrom || targetLocation);
}
} else {
return Promise.resolve(failure2);
}
}
});
}
function jump$1(router, toLocation, navType) {
return new Promise((resolve2, reject) => {
uniRouterApi[navType](__spreadProps$1(__spreadValues$1({}, toLocation), {
url: toLocation.fullPath,
success(res) {
var _a;
resolve2(res);
(_a = toLocation.success) === null || _a === void 0 ? void 0 : _a.call(toLocation, res);
},
fail(res) {
var _a;
reject(res);
(_a = toLocation.fail) === null || _a === void 0 ? void 0 : _a.call(toLocation, res);
},
complete(res) {
var _a;
(_a = toLocation.complete) === null || _a === void 0 ? void 0 : _a.call(toLocation, res);
}
}));
});
}
function forceGuardEach$1(router) {
return __async$1(this, null, function* () {
throw new Error(`\u5728h5\u7AEF\u4E0A\u4F7F\u7528\uFF1AforceGuardEach \u662F\u65E0\u610F\u4E49\u7684\uFF0C\u76EE\u524D forceGuardEach \u4EC5\u652F\u6301\u5728\u975Eh5\u7AEF\u4E0A\u4F7F\u7528`);
});
}
var h5Api = {
resolve: resolve$1,
mount: mount$1,
navigate: navigate$1,
jump: jump$1,
forceGuardEach: forceGuardEach$1
};
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve2, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve2(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
function resolve(router, rawLocation, navType = "navigateTo") {
const { getRouteByName, getRouteByPath, getRouteByAliasPath } = router.routeMatcher;
if (isString(rawLocation)) {
rawLocation = { path: rawLocation };
}
if (Reflect.has(rawLocation, "delta") && navType === "navigateBack" || rawLocation.from === "backbutton") {
rawLocation.delta = rawLocation.delta || 1;
const pages = getCurrentPages();
let backIndex = 0;
if (pages.length > rawLocation.delta) {
backIndex = pages.length - 1 - rawLocation.delta;
}
let toRoute;
if (router.options.platform === "app") {
toRoute = getRouteByPages(pages[backIndex]);
} else {
toRoute = getRouteByVueVm(pages[backIndex].$vm);
}
rawLocation = __spreadProps(__spreadValues(__spreadValues({}, toRoute), rawLocation), {
force: rawLocation.from === "backbutton"
});
}
if (Reflect.has(rawLocation, "url")) {
rawLocation = __spreadProps(__spreadValues({}, rawLocation), {
path: rawLocation.url
});
}
const currentPath = router.currentRoute.value.path;
const currentLocation = currentPath === "/" ? getRouteByAliasPath(currentPath) : getRouteByPath(currentPath);
if (Reflect.has(rawLocation, "path")) {
const location = parseURL(router.parseQuery, rawLocation.path, currentLocation === null || currentLocation === void 0 ? void 0 : currentLocation.path);
let toRouteRecord = getRouteByPath(location.path);
if (toRouteRecord === void 0) {
toRouteRecord = getRouteByAliasPath(location.path);
}
if (toRouteRecord === void 0) {
return;
}
const query = Object.assign({}, location.query, rawLocation === null || rawLocation === void 0 ? void 0 : rawLocation.query);
const fullPath = stringifyURL(router.stringifyQuery, {
path: toRouteRecord.path,
query
});
return __spreadProps(__spreadValues({}, rawLocation), {
path: toRouteRecord.path,
meta: toRouteRecord.meta || {},
name: toRouteRecord.name,
redirect: toRouteRecord.redirect,
fullPath,
query
});
} else if (Reflect.has(rawLocation, "name")) {
const toRouteRecord = getRouteByName(rawLocation.name);
if (toRouteRecord === void 0) {
return;
}
const query = Object.assign({}, rawLocation.query);
const fullPath = stringifyURL(router.stringifyQuery, {
path: toRouteRecord.path,
query
});
return __spreadProps(__spreadValues({}, rawLocation), {
path: toRouteRecord.path,
meta: toRouteRecord.meta || {},
name: toRouteRecord.name,
redirect: toRouteRecord.redirect,
fullPath,
query
});
}
}
function mount(app, router) {
router.forceGuardEach();
}
function navigate(router, to, navType = "navigateTo", redirectedFrom) {
try {
const targetLocation = router.resolve(to, navType);
const force = targetLocation === null || targetLocation === void 0 ? void 0 : targetLocation.force;
if (router.lock && !force)
return Promise.resolve();
router.lock = true;
const from = router.currentRoute.value;
let failure;
if (targetLocation === void 0) {
failure = createRoute404(router, to);
} else if (!force && isSameRouteLocation(targetLocation, from)) {
const toNormalized = routeLocationNormalized(router, targetLocation);
failure = createRouterError(16, {
to: toNormalized,
from
});
}
return (failure ? Promise.resolve(failure) : router.jump(targetLocation, navType)).catch((error) => {
return isNavigationFailure(
error,
2
/* NavigationErrorTypes.NAVIGATION_GUARD_REDIRECT */
) ? error : Promise.reject(error);
}).then((failure2) => {
if (failure2) {
if (isNavigationFailure(
failure2,
2
/* NavigationErrorTypes.NAVIGATION_GUARD_REDIRECT */
)) {
const failureTo = router.resolve(failure2 === null || failure2 === void 0 ? void 0 : failure2.to);
if (targetLocation && isSameRouteLocation(targetLocation, failureTo) && redirectedFrom && (redirectedFrom._count = redirectedFrom._count ? redirectedFrom._count + 1 : 1) > 30) {
warn(`\u68C0\u6D4B\u5230\u4ECE\u201C${from.fullPath}\u201D\u5230\u201C${targetLocation.fullPath}\u201D\u65F6\u5BFC\u822A\u5B88\u536B\u4E2D\u53EF\u80FD\u5B58\u5728\u65E0\u9650\u91CD\u5B9A\u5411\u3002\u4E2D\u6B62\u4EE5\u907F\u514D\u5806\u6808\u6EA2\u51FA\u3002
\u662F\u5426\u603B\u662F\u5728\u5BFC\u822A\u9632\u62A4\u4E2D\u8FD4\u56DE\u65B0\u4F4D\u7F6E\uFF1F\u8FD9\u5C06\u5BFC\u81F4\u6B64\u9519\u8BEF\u3002\u4EC5\u5728\u91CD\u5B9A\u5411\u6216\u4E2D\u6B62\u65F6\u8FD4\u56DE\uFF0C\u8FD9\u5E94\u8BE5\u53EF\u4EE5\u89E3\u51B3\u6B64\u95EE\u9898\u3002\u5982\u679C\u672A\u4FEE\u590D\uFF0C\u8FD9\u53EF\u80FD\u4F1A\u5728\u751F\u4EA7\u4E2D\u4E2D\u65AD`, router.options.debug);
return Promise.reject(new Error("Infinite redirect in navigation guard"));
} else {
router.lock = false;
return router.navigate(failureTo, failureTo.navType, redirectedFrom || targetLocation);
}
} else {
return Promise.resolve(failure2);
}
}
}).finally(() => {
router.lock = false;
});
} catch (error) {
router.lock = false;
return Promise.reject(error);
}
}
function jump(router, toLocation, navType) {
return new Promise((resolve2, reject) => {
const toNormalized = routeLocationNormalized(router, toLocation);
Promise.resolve().then(() => {
const beforeGuards = [];
for (const guard of router.guards.beforeGuards.list()) {
beforeGuards.push(guardToPromiseFn(guard, toNormalized, router.currentRoute.value));
}
return runGuardQueue(beforeGuards);
}).then(() => {
router.fromRoute = router.currentRoute.value;
router.currentRoute.value = toNormalized;
uniRouterApi[navType](__spreadProps(__spreadValues({}, toLocation), {
url: toLocation.fullPath,
success(res) {
var _a;
(_a = toLocation.success) === null || _a === void 0 ? void 0 : _a.call(toLocation, res);
resolve2(res);
},
fail(res) {
var _a;
(_a = toLocation.fail) === null || _a === void 0 ? void 0 : _a.call(toLocation, res);
reject(res);
},
complete(res) {
var _a;
(_a = toLocation.complete) === null || _a === void 0 ? void 0 : _a.call(toLocation, res);
}
}));
}).catch(reject);
});
}
function forceGuardEach(router) {
return __async(this, null, function* () {
const to = getEnterRoute();
const targetLocation = router.resolve(to);
let failure;
if (targetLocation === void 0) {
failure = createRoute404(router, to);
} else {
const toNormalized = routeLocationNormalized(router, targetLocation);
const beforeGuards = [];
for (const guard of router.guards.beforeGuards.list()) {
beforeGuards.push(guardToPromiseFn(guard, toNormalized, START_LOCATION_NORMALIZED));
}
try {
yield runGuardQueue(beforeGuards);
router.currentRoute.value = toNormalized;
const afterGuards = [];
for (const guard of router.guards.afterGuards.list()) {
afterGuards.push(() => __async(this, null, function* () {
guard(toNormalized, START_LOCATION_NORMALIZED);
}));
}
yield runGuardQueue(afterGuards);
} catch (error) {
failure = error;
}
}
if (isNavigationFailure(
failure,
2
/* NavigationErrorTypes.NAVIGATION_GUARD_REDIRECT */
)) {
return router.reLaunch(failure === null || failure === void 0 ? void 0 : failure.to);
}
});
}
var publicApi = {
resolve,
mount,
navigate,
jump,
forceGuardEach
};
function createApi(platform) {
switch (platform) {
case "h5":
return h5Api;
default:
return publicApi;
}
}
function createRouter(options) {
const guards = {
beforeGuards: useCallbacks(),
afterGuards: useCallbacks()
};
const currentRoute = vue.shallowRef(START_LOCATION_NORMALIZED);
const routeMatcher = createRouteMatcher(options);
const API = createApi(options.platform);
function resolve(rawLocation, navType = "navigateTo") {
return API.resolve(router, rawLocation, navType);
}
function jump(toLocation, navType) {
return new Promise((resolve2, reject) => {
API.jump(router, toLocation, navType).then(resolve2).catch(reject);
});
}
function navigate(to, navType = "navigateTo", redirectedFrom) {
return new Promise((resolve2, reject) => {
let options2 = {};
if (isObject(to)) {
options2 = to;
}
API.navigate(router, to, navType, redirectedFrom).then((res) => {
resolve2(res);
}).catch((error) => {
var _a, _b;
(_a = options2.fail) === null || _a === void 0 ? void 0 : _a.call(options2, error);
(_b = options2.complete) === null || _b === void 0 ? void 0 : _b.call(options2, error);
reject(error);
});
});
}
function forceGuardEach() {
return new Promise((resolve2, reject) => {
API.forceGuardEach(router).then(resolve2).catch(reject);
});
}
const router = {
level: 0,
lock: false,
currentRoute,
guards,
options,
vueRouter: null,
routeMatcher,
parseQuery: options.parseQuery || parseQuery,
stringifyQuery: options.stringifyQuery || stringifyQuery,
jump,
navigateTo(to) {
return navigate(to, "navigateTo");
},
switchTab(to) {
return navigate(to, "switchTab");
},
redirectTo(to) {
return navigate(to, "redirectTo");
},
reLaunch(to) {
return navigate(to, "reLaunch");
},
navigateBack(to = {
delta: 1
}) {
return navigate(to, "navigateBack");
},
navigate,
resolve,
forceGuardEach,
beforeEach(userGuard) {
guards.beforeGuards.add(userGuard);
},
afterEach(userGuard) {
guards.afterGuards.add(userGuard);
},
install(app) {
const reactiveRoute = {};
for (const key in START_LOCATION_NORMALIZED) {
reactiveRoute[key] = vue.computed(() => currentRoute.value[key]);
}
app.config.globalProperties.$uniRouter = router;
Object.defineProperty(app.config.globalProperties, "$uniRoute", {
enumerable: true,
get: () => vue.unref(currentRoute)
});
app.provide(routerKey, router);
app.provide(routeLocationKey, vue.reactive(reactiveRoute));
const mountApp = app.mount;
app.mount = function(...args) {
rewriteUniRouterApi(router);
API.mount(app, router);
initMixins(app, router);
console.log(`%c uni-router %c v${"1.2.7"} `, "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #606060; font-weight: bold;", "padding: 2px 1px; border-radius: 0 3px 3px 0; color: #fff; background: #42c02e; font-weight: bold;");
return mountApp(...args);
};
}
};
return router;
}
exports.PLUS_RE = PLUS_RE;
exports.START_LOCATION_NORMALIZED = START_LOCATION_NORMALIZED;
exports.WILDCARD = WILDCARD;
exports.WILDCARD_ROUTE = WILDCARD_ROUTE;
exports.createRouter = createRouter;
exports.createRouterError = createRouterError;
exports.decode = decode;
exports.decodeQuery = decodeQuery;
exports.encodeHash = encodeHash;
exports.encodeParam = encodeParam;
exports.encodePath = encodePath;
exports.encodeQueryKey = encodeQueryKey;
exports.encodeQueryValue = encodeQueryValue;
exports.error = error;
exports.getEnterRoute = getEnterRoute;
exports.guardToPromiseFn = guardToPromiseFn;
exports.isArray = isArray;
exports.isDate = isDate;
exports.isFunction = isFunction;
exports.isMap = isMap;
exports.isNavigationFailure = isNavigationFailure;
exports.isObject = isObject;
exports.isRegExp = isRegExp;
exports.isSet = isSet;
exports.isString = isString;
exports.isSymbol = isSymbol;
exports.mpPlatformReg = mpPlatformReg;
exports.objectToString = objectToString;
exports.parseQuery = parseQuery;
exports.parseURL = parseURL;
exports.resolveRelativePath = resolveRelativePath;
exports.routeLocationKey = routeLocationKey;
exports.routerKey = routerKey;
exports.runGuardQueue = runGuardQueue;
exports.stringifyQuery = stringifyQuery;
exports.stringifyURL = stringifyURL;
exports.toTypeString = toTypeString;
exports.uniRouterApiName = uniRouterApiName;
exports.useCallbacks = useCallbacks;
exports.useRoute = useRoute;
exports.useRouter = useRouter;
exports.warn = warn;