Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: forked dev server #81

Merged
merged 2 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion bin/nuxi.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
#!/usr/bin/env node

import { fileURLToPath } from 'node:url'
import { runMain } from '../dist/index.mjs'

process._startTime = Date.now()
global.__nuxt_cli__ = {
startTime: Date.now(),
entry: fileURLToPath(import.meta.url),
}

runMain()
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"giget": "^1.1.2",
"h3": "^1.8.0",
"http-proxy": "^1.18.1",
"httpxy": "^0.1.0",
"jiti": "^1.19.3",
"listhen": "^1.3.0",
"magicast": "^0.2.10",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion scripts/nuxi.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
#!/usr/bin/env node
import jiti from 'jiti'
import { fileURLToPath } from 'node:url'

process._startTime = Date.now()
global.__nuxt_cli__ = {
startTime: Date.now(),
entry: fileURLToPath(import.meta.url),
}

const { runMain } = jiti(import.meta.url, {
esmResolve: true,
Expand Down
191 changes: 191 additions & 0 deletions src/commands/dev-internal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { relative, resolve } from 'pathe'
import chokidar from 'chokidar'
import type { Nuxt } from '@nuxt/schema'
import { consola } from 'consola'
import { debounce } from 'perfect-debounce'
// We are deliberately inlining this code as a backup in case user has `@nuxt/schema<3.7`
import { writeTypes as writeTypesLegacy } from '@nuxt/kit'
import { loadKit } from '../utils/kit'
import { overrideEnv } from '../utils/env'
import { loadNuxtManifest, writeNuxtManifest } from '../utils/nuxt'
import { clearBuildDir } from '../utils/fs'
import { defineCommand } from 'citty'
import { sharedArgs, legacyRootDirArgs } from './_shared'
import { RequestListener, Server } from 'http'
import { toNodeListener } from 'h3'
import { AddressInfo } from 'net'

export type NuxtDevIPCMessage =
| { type: 'nuxt:internal:dev:ready'; port: number }
| { type: 'nuxt:internal:dev:loading'; message: string }
| { type: 'nuxt:internal:dev:restart' }

const RESTART_RE = /^(nuxt\.config\.(js|ts|mjs|cjs)|\.nuxtignore|\.nuxtrc)$/

export default defineCommand({
meta: {
name: '_dev',
description: 'Run nuxt development server (internal command)',
},
args: {
...sharedArgs,
...legacyRootDirArgs,
},
async run(ctx) {
if (!process.send) {
throw new Error(
'This command is only meant to be run in a subprocess. Please use `nuxi dev`',
)
}

// Prepare
overrideEnv('development')
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir || '.')

// Load nuxt kit
const {
loadNuxt,
buildNuxt,
writeTypes = writeTypesLegacy,
} = await loadKit(cwd)

// Handler
let serverHandler: undefined | RequestListener
const server = new Server((req, res) => {
if (!serverHandler) {
// This should not be reached!
res.statusCode = 503
res.end('Nuxt is not ready yet!')
return
}
serverHandler(req, res)
})

const port = await new Promise<number>((resolve) => {
server.listen(0, () => {
resolve((server.address() as AddressInfo).port)
})
})

function sendIPCMessage<T extends NuxtDevIPCMessage>(message: T) {
if (process.send) {
process.send(message)
}
}

let currentNuxt: Nuxt
let distWatcher: chokidar.FSWatcher
async function _load(reload?: boolean, reason?: string) {
const action = reload ? 'Restarting' : 'Starting'
const message = `${reason ? reason + '. ' : ''}${action} nuxt...`
serverHandler = undefined
sendIPCMessage({
type: 'nuxt:internal:dev:loading',
message,
})
if (reload) {
consola.info(message)
}

if (currentNuxt) {
await currentNuxt.close()
danielroe marked this conversation as resolved.
Show resolved Hide resolved
}
if (distWatcher) {
await distWatcher.close()
}

currentNuxt = await loadNuxt({
rootDir: cwd,
dev: true,
ready: false,
overrides: {
logLevel: ctx.args.logLevel as 'silent' | 'info' | 'verbose',
vite: {
clearScreen: ctx.args.clear,
},
...ctx.data?.overrides,
},
})

// Write manifest and also check if we need cache invalidation
if (!reload) {
const previousManifest = await loadNuxtManifest(
currentNuxt.options.buildDir,
)
const newManifest = await writeNuxtManifest(currentNuxt)
if (
previousManifest &&
newManifest &&
previousManifest._hash !== newManifest._hash
) {
await clearBuildDir(currentNuxt.options.buildDir)
}
}

await currentNuxt.ready()

const unsub = currentNuxt.hooks.hook('restart', async (options) => {
unsub() // We use this instead of `hookOnce` for Nuxt Bridge support
if (options?.hard) {
sendIPCMessage({ type: 'nuxt:internal:dev:restart' })
return
}
await load(true)
})

await currentNuxt.hooks.callHook('listen', server, {})
currentNuxt.options.devServer.url = `http://localhost:${port}/`
currentNuxt.options.devServer.port = port
currentNuxt.options.devServer.host = 'localhost'
currentNuxt.options.devServer.https = false

await Promise.all([
writeTypes(currentNuxt).catch(console.error),
buildNuxt(currentNuxt),
])

// Watch dist directory
distWatcher = chokidar.watch(
resolve(currentNuxt.options.buildDir, 'dist'),
{ ignoreInitial: true, depth: 0 },
)
distWatcher.on('unlinkDir', () => {
loadDebounced(true, '.nuxt/dist directory has been removed')
})

serverHandler = toNodeListener(currentNuxt.server.app)
sendIPCMessage({ type: 'nuxt:internal:dev:ready', port })
}

async function load(reload?: boolean, reason?: string) {
try {
await _load(reload, reason)
} catch (error) {
consola.error(`Cannot ${reload ? 'restart' : 'start'} nuxt: `, error)
serverHandler = undefined
const message =
'Error while loading nuxt. Please check console and fix errors.'
sendIPCMessage({ type: 'nuxt:internal:dev:loading', message })
}
}

const loadDebounced = debounce(load)

// Watch for config changes
const configWatcher = chokidar.watch([cwd], {
ignoreInitial: true,
depth: 0,
})
configWatcher.on('all', (_event, _file) => {
const file = relative(cwd, _file)
if (file === (ctx.args.dotenv || '.env')) {
return sendIPCMessage({ type: 'nuxt:internal:dev:restart' })
}
if (RESTART_RE.test(file)) {
loadDebounced(true, `${file} updated`)
}
})

await load(false)
},
})
Loading