69 lines
2.5 KiB
TypeScript
69 lines
2.5 KiB
TypeScript
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<Response> => {
|
|
// 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');
|
|
const isLoginApi =
|
|
url.includes('/api/user/login') ||
|
|
url.includes('/api/user/casdoor/password-login') ||
|
|
url.includes('/api/user/casdoor/login');
|
|
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 && !isLoginApi) {
|
|
// 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 ('serviceWorker' in navigator) {
|
|
window.addEventListener('load', async () => {
|
|
try {
|
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
await Promise.all(registrations.map((registration) => registration.unregister()));
|
|
if ('caches' in window) {
|
|
const cacheKeys = await window.caches.keys();
|
|
await Promise.all(cacheKeys.map((key) => window.caches.delete(key)));
|
|
}
|
|
} catch (err) {
|
|
console.error('Service worker cleanup failed:', err);
|
|
}
|
|
});
|
|
}
|