at build time.
// Most AI/answer-engine crawlers do not run JavaScript, so without this they would see
// an empty SPA shell. React's createRoot replaces the fallback on mount. The content is
// generated from the English locale so it cannot drift from the rendered page copy.
import type { Plugin } from 'vite'
import en from '../src/locales/en.json'
import { APP_STORE_URL, GOOGLE_PLAY_URL, SUPPORTED_AGENTS } from '../src/const'
const MARKER = ''
function text(html: string): string {
return html
.replace(/
/gi, ' ')
.replace(/<[^>]+>/g, '')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/\s+/g, ' ')
.trim()
}
function esc(value: string): string {
return value.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"')
}
const plain = (html: string) => esc(text(html))
type Entry = { title: string; desc: string }
const isEntry = (value: unknown): value is Entry =>
typeof value === 'object' && value !== null && 'title' in value && 'desc' in value
function render(): string {
const features = Object.entries(en.features)
.filter(([key, value]) => key !== 'agents' && isEntry(value))
.map(([, value]) => value as Entry)
const steps = [en.howItWorks.step1, en.howItWorks.step2, en.howItWorks.step3]
return `
${plain(en.showcase.title)}
${plain(en.showcase.subtitle)}
${plain(en.features.title)}
${plain(en.features.subtitle)}
${plain(en.features.agents.title)}
${plain(en.features.agents.desc)}
${SUPPORTED_AGENTS.map((agent) => `- ${esc(agent)}
`).join('')}
${plain(en.features.agents.hint)}
${features.map((f) => `${plain(f.title)}
${plain(f.desc)}
`).join('\n ')}
${plain(en.howItWorks.title)}
${steps.map((s) => `- ${plain(s.title)} ${plain(s.desc)}
`).join('')}
${plain(en.installation.title)}
- ${plain(en.installation.npm.step1)}:
npx @twsxtd/hapi hub --relay
- ${plain(en.installation.npm.step2)}:
npx @twsxtd/hapi. ${plain(en.installation.npm.step2Hint)}
- ${plain(en.installation.npm.step3)}: ${plain(en.installation.npm.step3Hint)}
${plain(en.installation.e2ee)}
`
}
export function staticFallback(): Plugin {
return {
name: 'hapi-static-fallback',
transformIndexHtml(html) {
if (!html.includes(MARKER)) throw new Error(`index.html is missing ${MARKER}`)
return html.replace(MARKER, render())
},
}
}