All files / src/router index.ts

79.31% Statements 69/87
95.34% Branches 41/43
60.97% Functions 25/41
77.77% Lines 63/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339                        52x 52x   52x             6x         2x                                                         17x               3x           4x                       6x           2x           1x                       2x             1x                             2x                                       1x                               1x           1x           1x                       1x           3x                                                                                       2x                         2x       41x 41x   41x 17x 22x 17x 2x 3x   17x 1x             16x 16x 16x       24x 24x 41x 41x 19x 19x 2x   17x     52x 56x       56x 7x 7x       56x 28x 28x       56x 18x 18x         18x     56x 41x 41x       48x 2x     46x 6x       40x            
// @implements UC-AUTH-005.1
import { createRouter, createWebHistory, type RouteLocationNormalized } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useFlowsStore } from '@/stores/flows'
import {
  defaultFlow,
  flowRoute,
  flowRouteOfFlowless,
  isFlowRoute,
  rememberLastFlow
} from './flowRoutes'
 
let userLoaded = false
let flowsLoaded = false
 
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // Public routes (no layout)
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginPage.vue')
    },
    {
      path: '/signup',
      name: 'signup',
      component: () => import('@/views/SignupPage.vue')
    },
    {
      path: '/forgot-password',
      name: 'forgot-password',
      component: () => import('@/views/ForgotPasswordPage.vue')
    },
    // A flow's public space: readable by anyone, signed in or not
    // (see docs/architecture/FLOW_SPACE.md)
    {
      path: '/space/:slug',
      name: 'space',
      component: () => import('@/views/SpacePage.vue')
    },
    // Its join form: public too, step 1 being to sign up or in (UC-SPACE-004.1)
    {
      path: '/space/:slug/join',
      name: 'space-join',
      component: () => import('@/views/SpaceJoinPage.vue')
    },
    // A published page of the space (UC-SPACE-010.1); `join` above is matched first
    {
      path: '/space/:slug/:pageSlug',
      name: 'space-page',
      component: () => import('@/views/SpacePage.vue')
    },
    // Authenticated routes — FlowsLayout persists across all children
    {
      path: '/',
      component: () => import('@/components/FlowsLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          // Opens the default flow (see the guard below); shown as is only to
          // a user with no flow, who is invited to create or join one
          path: '',
          name: 'root',
          component: () => import('@/views/HomePage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'flows',
          name: 'flows',
          component: () => import('@/views/FlowsPage.vue'),
          meta: { requiresAuth: true }
        },
        // A flow's pages: the active flow of the tab is the one in the URL
        // (see router/flowRoutes.ts)
        {
          path: 'flows/:flowSlug',
          meta: { requiresAuth: true },
          children: [
            {
              path: '',
              name: 'home',
              component: () => import('@/views/HomePage.vue'),
              meta: { requiresAuth: true }
            },
            {
              path: 'entities',
              name: 'entities',
              component: () => import('@/views/EntitiesPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              path: 'entities/:entityId',
              name: 'entity-items',
              component: () => import('@/views/EntityItemsPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              path: 'catalog',
              name: 'catalog',
              component: () => import('@/views/CatalogPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              path: 'store',
              name: 'store',
              component: () => import('@/views/StorePage.vue'),
              meta: { requiresAuth: true }
            },
            {
              // A pack opens over the Store: older links and notifications land there
              path: 'store/:packId',
              name: 'store-pack',
              redirect: (to) => ({
                name: 'store',
                params: { flowSlug: to.params.flowSlug },
                query: { ...to.query, pack: String(to.params.packId) }
              })
            },
            {
              path: 'exports',
              name: 'exports',
              component: () => import('@/views/ExportsPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              path: 'members',
              name: 'members',
              component: () => import('@/views/MembersPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              // The pages of the flow's public space (UC-SPACE-009.1)
              path: 'space-pages',
              name: 'space-pages',
              component: () => import('@/views/SpacePagesPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              // The same list, with the page's edit sidebar open over it
              path: 'space-pages/:pageSlug',
              name: 'space-page-editor',
              component: () => import('@/views/SpacePagesPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              path: 'roles',
              name: 'roles',
              component: () => import('@/views/RolesPage.vue'),
              meta: { requiresAuth: true }
            },
            {
              path: 'api-keys',
              name: 'api-keys',
              component: () => import('@/views/ApiKeysPage.vue'),
              meta: { requiresAuth: true }
            }
          ]
        },
        // The Catalog and Store of a user with no flow yet (UC-CATALOG-006.1,
        // UC-STORE); a user with one is sent to their flow's (see the guard below)
        {
          path: 'catalog',
          name: 'flowless-catalog',
          component: () => import('@/views/CatalogPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'catalog/:entityId',
          name: 'flowless-entity-items',
          component: () => import('@/views/EntityItemsPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'store',
          name: 'flowless-store',
          component: () => import('@/views/StorePage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'moderation',
          name: 'moderation',
          component: () => import('@/views/ModerationPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'invitations',
          name: 'invitations',
          component: () => import('@/views/InvitationsPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'profile',
          name: 'profile',
          component: () => import('@/views/UserProfilePage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'users/:userId',
          name: 'user-profile',
          component: () => import('@/views/UserProfilePublicPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'messages',
          name: 'inbox',
          component: () => import('@/views/InboxPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'messages/:conversationId',
          name: 'conversation',
          component: () => import('@/views/ConversationPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'notifications',
          name: 'notifications',
          component: () => import('@/views/NotificationsPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'credits',
          name: 'credits',
          component: () => import('@/views/CreditsPage.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'admin',
          name: 'admin',
          component: () => import('@/views/AdminPage.vue'),
          meta: { requiresAuth: true, requiresPlatformAdmin: true }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('@/views/NotFoundPage.vue')
    }
  ]
})
 
/**
 * Makes the tab's active flow follow the URL. A flow page activates the flow
 * of its slug (reloading the memberships once for a flow joined since, e.g.
 * in another tab) or shows Not Found for a flow the user is not in; "/"
 * opens the default flow, as does the flowless Catalog; any other page keeps the tab's last flow, or the
 * default one, as the sidebar's context.
 */
function stringParams(params: RouteLocationNormalized['params']): Record<string, string> {
  return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, String(value)]))
}
 
async function activateFlowOf(to: RouteLocationNormalized) {
  const authStore = useAuthStore()
  const flowsStore = useFlowsStore()
 
  if (isFlowRoute(to)) {
    const slug = String(to.params.flowSlug)
    let flow = flowsStore.myFlows.find((f) => f.flowSlug === slug)
    if (!flow) {
      await flowsStore.refreshMyFlows()
      flow = flowsStore.myFlows.find((f) => f.flowSlug === slug)
    }
    if (!flow) {
      return {
        name: 'not-found',
        params: { pathMatch: to.path.substring(1).split('/') },
        query: to.query,
        hash: to.hash
      }
    }
    authStore.currentFlow = flow.flowId
    rememberLastFlow(flow.flowId)
    return undefined
  }
 
  // The tab's flow may have been left or deleted since
  const current = flowsStore.myFlows.find((f) => f.flowId === authStore.currentFlow)
  const fallback = current ?? defaultFlow(flowsStore.myFlows)
  authStore.currentFlow = fallback?.flowId ?? null
  if (to.name === 'root' && fallback) return flowRoute(fallback.flowSlug, 'home')
  const flowName = flowRouteOfFlowless(to.name)
  if (flowName && fallback) {
    return flowRoute(fallback.flowSlug, flowName, stringParams(to.params), to.query)
  }
  return undefined
}
 
router.beforeEach(async (to) => {
  const authStore = useAuthStore()
 
  // Reset state flags when user goes to login (e.g. after logout),
  // so subsequent logins re-run loadUser + fetchMyFlows
  if (to.name === 'login') {
    userLoaded = false
    flowsLoaded = false
  }
 
  // Load user only once on first navigation
  if (!userLoaded) {
    await authStore.loadUser()
    userLoaded = true
  }
 
  // Load flows once after user is loaded and authenticated
  if (authStore.isAuthenticated && !flowsLoaded) {
    try {
      await useFlowsStore().fetchMyFlows()
    } catch (err) {
      console.error('[router] fetchMyFlows failed:', err)
      // fetchMyFlows failing should not block navigation
    }
    flowsLoaded = true
  }
 
  if (authStore.isAuthenticated) {
    const redirect = await activateFlowOf(to)
    if (redirect) return redirect
  }
 
  // If going to login/signup but already authenticated, redirect to the default flow
  if ((to.name === 'login' || to.name === 'signup') && authStore.isAuthenticated) {
    return { name: 'root' }
  }
  // If route requires auth and not authenticated, redirect to login
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    return { name: 'login' }
  }
  // @implements UC-ADMIN-001.1
  // Platform-admin-only routes (e.g. /admin) redirect non-admins home
  Iif (to.meta.requiresPlatformAdmin && !authStore.isPlatformAdmin) {
    return { name: 'root' }
  }
})
 
export default router