1.0
longz
2026-06-24 e45e74e5ae207f7642be9a88ed99b593de89fb3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/// <reference types="@uni-helper/vite-plugin-uni-pages/client" />
import { pages, subPackages } from 'virtual:uni-pages'
import { fetchMiniMe } from '@/api/auth'
import { setUnauthorizedRedirectHandler } from './authRedirect'
import { clearMiniAuthSession, getPersistedAuthState, showMiniLoginPrompt, updateMiniAuthProfile } from '@/store/auth'
import { normalizeMeProfile } from '@/types/auth'
 
function generateRoutes() {
  const routes = pages.map((page) => {
    const newPath = `/${page.path}`
    return { ...page, path: newPath }
  })
  if (subPackages && subPackages.length > 0) {
    subPackages.forEach((subPackage) => {
      const subRoutes = subPackage.pages.map((page: any) => {
        const newPath = `/${subPackage.root}/${page.path}`
        return { ...page, path: newPath }
      })
      routes.push(...subRoutes)
    })
  }
  return routes
}
 
const router = createRouter({
  routes: generateRoutes(),
})
 
setUnauthorizedRedirectHandler(() => {
  showMiniLoginPrompt('登录已失效,请重新登录')
  router.replaceAll({ name: 'home' })
})
 
const PUBLIC_ROUTE_NAMES = new Set(['home', 'login', 'visitorCode'])
const HOME_ROUTE_NAME = 'home'
 
function isPublicRoute(name?: string) {
  return Boolean(name && PUBLIC_ROUTE_NAMES.has(name))
}
 
router.beforeEach((to, from, next) => {
  const state = getPersistedAuthState()
  const hasToken = Boolean(state.token)
  const hasProfile = Boolean(state.profile)
  const publicRoute = isPublicRoute(to.name)
 
  if (!hasToken) {
    if (publicRoute) {
      next()
      return
    }
    showMiniLoginPrompt('您还未登录,请先登录')
    next({ name: HOME_ROUTE_NAME })
    return
  }
 
  const ensureProfile = async () => {
    if (hasProfile) {
      return true
    }
    try {
      const profile = await fetchMiniMe()
      updateMiniAuthProfile(normalizeMeProfile(profile))
      return true
    }
    catch (error) {
      console.warn('mini auth guard fetch /me failed', error)
      clearMiniAuthSession()
      showMiniLoginPrompt('登录已失效,请重新登录')
      return false
    }
  }
 
  return Promise.resolve(ensureProfile()).then((ok) => {
    if (!ok) {
      next({ name: HOME_ROUTE_NAME })
      return
    }
    if (to.name === 'login') {
      next({ name: HOME_ROUTE_NAME })
      return
    }
    next()
  })
})
 
router.afterEach((to, from) => {
  if (import.meta.env.MODE === 'development' && to.path) {
    console.log(`📄 页面切换完成: ${from.path || '-'} -> ${to.path}`)
  }
})
 
export default router