import './storageFallback'
import { StrictMode, useState, type FormEvent, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './App.css'
import { LanguageProvider, useT } from './i18n'
import { discardVault, hasVault, unlockVault } from './vault'
import {
SYNC_CATEGORIES,
accountInfo,
formatAccountNumber,
loginSyncAccount,
normalizePassword,
pullAtStartup,
resolveConflict,
startAutoSync,
syncErrorKey,
takeSyncLink,
} from './sync'
const root = createRoot(document.getElementById('root')!)
// App reads its stored identities/favorites while loading, so it's imported only after the vault is open
// and the sync account (Options -> Konto) had its chance to bring in newer data.
// After a deploy, a page (or the service worker cache) can still point at
// chunk files that no longer exist, which used to leave a black screen. One
// fresh load fixes that; the flag stops a reload loop if the server is broken.
const RELOAD_FLAG = 'ws3-chunk-reload'
function reloadOnceForStaleChunks(): boolean {
try {
if (sessionStorage.getItem(RELOAD_FLAG)) return false
sessionStorage.setItem(RELOAD_FLAG, '1')
} catch {
return false
}
location.reload()
return true
}
window.addEventListener('vite:preloadError', (event) => {
if (reloadOnceForStaleChunks()) event.preventDefault()
})
async function start() {
let App: typeof import('./App.tsx').default
try {
;({ default: App } = await import('./App.tsx'))
} catch (error) {
if (reloadOnceForStaleChunks()) return
throw error
}
try {
sessionStorage.removeItem(RELOAD_FLAG)
} catch {
// storage blocked - nothing to clear
}
startAutoSync()
root.render(
,
)
}
const dialog = (node: ReactNode) => root.render({node})
async function boot() {
const link = takeSyncLink()
if (link) return dialog()
// Don't hold the client hostage to a slow sync server.
const deadline = Date.now() + 5000
const result = await Promise.race([
pullAtStartup(deadline),
new Promise<'ok'>((resolve) => setTimeout(() => resolve('ok'), 5000)),
])
if (result === 'conflict') return dialog()
void start()
}
/** Opened through the QR code / link from Options -> Konto on another device. */
function SyncLinkDialog({ link }: { link: { number: string; password?: string; server: string } }) {
const t = useT()
const [password, setPassword] = useState(link.password ?? '')
const [askPassword, setAskPassword] = useState(false)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const submit = async (e: FormEvent) => {
e.preventDefault()
setBusy(true)
setError('')
try {
if (!password) {
const info = await accountInfo(link.number, link.server)
if (!info.exists) throw new Error('not_found')
if (info.hasPassword) {
setAskPassword(true)
setBusy(false)
return
}
}
await loginSyncAccount(link.number, password ? normalizePassword(password) : undefined, link.server, SYNC_CATEGORIES)
void start()
} catch (err) {
setError(t(syncErrorKey(err)))
setBusy(false)
}
}
return (