2022-08-04 11:13:12 +00:00
|
|
|
import { performance } from 'node:perf_hooks'
|
2022-04-12 10:04:55 +00:00
|
|
|
import { ViteNodeRunner } from 'vite-node/client'
|
|
|
|
import { $fetch } from 'ohmyfetch'
|
2022-08-04 11:13:12 +00:00
|
|
|
import consola from 'consola'
|
2022-04-12 10:04:55 +00:00
|
|
|
import { getViteNodeOptions } from './vite-node-shared.mjs'
|
|
|
|
|
|
|
|
const viteNodeOptions = getViteNodeOptions()
|
|
|
|
|
|
|
|
const runner = new ViteNodeRunner({
|
2022-08-12 09:11:09 +00:00
|
|
|
root: viteNodeOptions.root, // Equals to Nuxt `srcDir`
|
2022-04-12 10:04:55 +00:00
|
|
|
base: viteNodeOptions.base,
|
|
|
|
async fetchModule (id) {
|
|
|
|
return await $fetch('/module/' + encodeURI(id), {
|
|
|
|
baseURL: viteNodeOptions.baseURL
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
let render
|
|
|
|
|
|
|
|
export default async (ssrContext) => {
|
|
|
|
// Workaround for stub mode
|
|
|
|
// https://github.com/nuxt/framework/pull/3983
|
|
|
|
process.server = true
|
2022-08-04 10:03:46 +00:00
|
|
|
|
|
|
|
// Invalidate cache for files changed since last rendering
|
|
|
|
const invalidates = await $fetch('/invalidates', {
|
|
|
|
baseURL: viteNodeOptions.baseURL
|
|
|
|
})
|
2022-08-04 11:13:12 +00:00
|
|
|
const updates = new Set()
|
2022-08-04 10:03:46 +00:00
|
|
|
for (const key of invalidates) {
|
2022-08-04 11:13:12 +00:00
|
|
|
if (runner.moduleCache.delete(key)) {
|
|
|
|
updates.add(key)
|
|
|
|
}
|
2022-08-04 10:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Execute SSR bundle on demand
|
2022-08-04 11:13:12 +00:00
|
|
|
const start = performance.now()
|
2022-04-12 10:04:55 +00:00
|
|
|
render = render || (await runner.executeFile(viteNodeOptions.entryPath)).default
|
2022-08-04 11:13:12 +00:00
|
|
|
if (updates.size) {
|
|
|
|
const time = Math.round((performance.now() - start) * 1000) / 1000
|
|
|
|
consola.success(`Vite server hmr ${updates.size} files`, time ? `in ${time}ms` : '')
|
|
|
|
}
|
|
|
|
|
2022-04-12 10:04:55 +00:00
|
|
|
const result = await render(ssrContext)
|
|
|
|
return result
|
|
|
|
}
|