import { createApp } from 'vue' import './style.css' import App from './App.vue' import router from './router' import i18n from './i18n' import { config } from './config' import { refreshAccessToken, getAuthToken } from './utils/auth' // Set document title from config document.title = config.appTitle || 'AI工作台'; // Global 401 interceptor for API calls. const _rawFetch = window.fetch.bind(window); window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise => { // Keep original request closure so we can retry with a refreshed token. const runFetch = (nextInit?: RequestInit) => _rawFetch(input, nextInit); let reqInit = init; let res = await runFetch(reqInit); try { const url = typeof input === 'string' ? input : (input instanceof URL ? input.toString() : input.url); const isApi = url.includes('/api/'); const isRefreshApi = url.includes('/api/user/casdoor/refresh'); if (res.status === 401 && isApi && !isRefreshApi) { // First unauthorized response: try silent refresh once. const refreshed = await refreshAccessToken(); if (refreshed) { const mergedHeaders = new Headers((reqInit && reqInit.headers) || {}); mergedHeaders.set('Authorization', `Bearer ${getAuthToken()}`); reqInit = { ...(reqInit || {}), headers: mergedHeaders }; // Retry original request exactly once with the renewed access token. res = await runFetch(reqInit); } } if (res.status === 401 && isApi) { // Still unauthorized after retry (or no refresh token): force global logout UX. window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } })); } } catch { // no-op } return res; }; createApp(App) .use(router) .use(i18n) .mount('#app') if (import.meta.env.PROD && 'serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/sw.js').catch((err) => { console.error('Service worker registration failed:', err); }); }); }