2024-06-19 12:56:54 +00:00
|
|
|
import { runInNewContext } from 'node:vm'
|
2024-05-01 13:10:33 +00:00
|
|
|
import { join, resolve } from 'node:path'
|
2024-06-15 23:03:24 +00:00
|
|
|
import { fileURLToPath } from 'node:url'
|
2024-05-01 13:10:33 +00:00
|
|
|
import { promises as fsp } from 'node:fs'
|
2021-12-22 13:04:06 +00:00
|
|
|
import type { Plugin } from 'vite'
|
|
|
|
import genericMessages from '../templates/messages.json'
|
2024-06-27 14:21:53 +00:00
|
|
|
import { version } from '../../nuxt/package.json'
|
2021-12-22 13:04:06 +00:00
|
|
|
|
2024-06-15 23:03:24 +00:00
|
|
|
const templatesRoot = fileURLToPath(new URL('..', import.meta.url))
|
|
|
|
|
|
|
|
const r = (...path: string[]) => resolve(join(templatesRoot, ...path))
|
2021-12-22 13:04:06 +00:00
|
|
|
|
|
|
|
export const DevRenderingPlugin = () => {
|
|
|
|
return <Plugin>{
|
|
|
|
name: 'dev-rendering',
|
|
|
|
async transformIndexHtml (html: string, context) {
|
|
|
|
const page = context.originalUrl || '/'
|
|
|
|
|
2024-06-19 12:56:54 +00:00
|
|
|
if (page.endsWith('.png')) { return }
|
|
|
|
|
2021-12-22 13:04:06 +00:00
|
|
|
if (page === '/') {
|
|
|
|
const templateNames = await fsp.readdir(r('templates'))
|
|
|
|
const serializedData = JSON.stringify({ templateNames })
|
|
|
|
return html.replace('{{ data }}', serializedData)
|
|
|
|
}
|
|
|
|
|
|
|
|
const contents = await fsp.readFile(r(page, 'index.html'), 'utf-8')
|
|
|
|
|
|
|
|
const messages = JSON.parse(await fsp.readFile(r(page, 'messages.json'), 'utf-8'))
|
|
|
|
|
2024-06-19 12:56:54 +00:00
|
|
|
const chunks = contents.split(/\{{2,3}[^{}]+\}{2,3}/g)
|
|
|
|
let templateString = chunks.shift()
|
|
|
|
for (const expression of contents.matchAll(/\{{2,3}([^{}]+)\}{2,3}/g)) {
|
|
|
|
const value = runInNewContext(expression[1].trim(), {
|
2024-06-27 14:21:53 +00:00
|
|
|
version,
|
2024-06-19 12:56:54 +00:00
|
|
|
messages: { ...genericMessages, ...messages },
|
|
|
|
})
|
|
|
|
templateString += `${value}${chunks.shift()}`
|
|
|
|
}
|
|
|
|
if (chunks.length > 0) {
|
|
|
|
templateString += chunks.join('')
|
|
|
|
}
|
|
|
|
|
|
|
|
return templateString
|
2024-05-01 13:10:33 +00:00
|
|
|
},
|
2021-12-22 13:04:06 +00:00
|
|
|
}
|
|
|
|
}
|