Skip to content
Open
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
56 changes: 51 additions & 5 deletions packages/nuxi/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { isBun, isTest } from 'std-env'

import { initialize } from '../dev'
import { ForkPool } from '../dev/pool'
import { ensurePortlessAvailable, registerPortlessAlias, registerPortlessExitCleanup, removePortlessAlias, resolvePortlessAliasName, resolvePortlessName, resolvePortlessURL } from '../dev/portless'
import { debug, logger } from '../utils/logger'
import { cwdArgs, dotEnvArgs, envNameArgs, extendsArgs, legacyRootDirArgs, logLevelArgs, profileArgs } from './_shared'

Expand Down Expand Up @@ -61,6 +62,11 @@ const command = defineCommand({
description: 'Host to listen on (default: `NUXT_HOST || NITRO_HOST || HOST || nuxtOptions.devServer?.host`)',
},
clipboard: { ...listhenArgs.clipboard, default: false },
portless: {
type: 'boolean',
description: 'Expose the dev server with the external `portless` CLI (https://portless.sh). Disables forked mode.',
default: false,
},
},
...profileArgs,
sslCert: {
Expand All @@ -76,7 +82,19 @@ const command = defineCommand({
// Prepare
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir)

const listenOverrides = resolveListenOverrides(ctx.args)
if (ctx.args.portless && ctx.args.tunnel) {
throw new Error('`--portless` cannot be used with `--tunnel`.')
}

const portlessName = ctx.args.portless ? await resolvePortlessName(cwd) : undefined
if (ctx.args.portless) {
await ensurePortlessAvailable(cwd)
}

const portlessURL = ctx.args.portless ? await resolvePortlessURL(cwd, portlessName!) : undefined
const portlessAliasName = portlessURL ? resolvePortlessAliasName(portlessURL) : undefined
const listenOverrides = resolveListenOverrides(ctx.args, portlessURL)
let closePortless: (() => Promise<void>) | undefined

// Start the initial dev server in-process with listener
const { listener, close, onRestart, onReady } = await initialize({ cwd, args: ctx.args }, {
Expand All @@ -85,11 +103,36 @@ const command = defineCommand({
showBanner: true,
})

// Disable forking when profiling to capture all activity in one process
if (!ctx.args.fork || ctx.args.profile) {
if (ctx.args.portless) {
const unregisterPortlessExitCleanup = registerPortlessExitCleanup(cwd, portlessAliasName!)
try {
await registerPortlessAlias(cwd, portlessAliasName!, listener.address.port)
closePortless = async () => {
unregisterPortlessExitCleanup()
await removePortlessAlias(cwd, portlessAliasName!).catch((error) => {
logger.warn((error as Error).message)
})
}
await listener.showURL()
}
catch (error) {
unregisterPortlessExitCleanup()
await removePortlessAlias(cwd, portlessAliasName!).catch(() => {})
await close()
throw error
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

const closeDevServer = async () => {
await closePortless?.()
await close()
}

if (ctx.args.portless || !ctx.args.fork || ctx.args.profile) {
// Disable forking when profiling or using portless to keep lifecycle local.
return {
listener,
close,
close: closeDevServer,
}
}

Expand Down Expand Up @@ -144,6 +187,7 @@ const command = defineCommand({
return {
async close() {
cleanupCurrentFork?.()
await closePortless?.()
await Promise.all([
listener.close(),
close(),
Expand All @@ -162,7 +206,7 @@ type ArgsT = Exclude<
undefined | ((...args: unknown[]) => unknown)
>

function resolveListenOverrides(args: ParsedArgs<ArgsT>) {
function resolveListenOverrides(args: ParsedArgs<ArgsT>, publicURL?: string) {
// _PORT is used by `@nuxt/test-utils` to launch the dev server on a specific port
if (process.env._PORT) {
return {
Expand Down Expand Up @@ -195,6 +239,8 @@ function resolveListenOverrides(args: ParsedArgs<ArgsT>) {

return {
...options,
publicURL,
showURL: !args.portless,
// if the https flag is not present, https.xxx arguments are ignored.
// override if https is enabled in devServer config.
_https: args.https,
Expand Down
141 changes: 141 additions & 0 deletions packages/nuxi/src/dev/portless.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { spawnSync } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import { basename, join } from 'node:path'
import process from 'node:process'

import { x } from 'tinyexec'

const DEFAULT_PORTLESS_NAME = 'nuxt-app'

export async function ensurePortlessAvailable(cwd: string) {
try {
await runPortless(cwd, ['--version'])
}
catch (error) {
if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {
throw new Error('Portless is required for `--portless`. Install it from https://portless.sh')
}

throw createPortlessError('check portless availability', error)
}
}

export async function resolvePortlessURL(cwd: string, name: string) {
try {
await runPortless(cwd, ['proxy', 'start'])
const result = await runPortless(cwd, ['get', name])
const url = result.stdout.trim()

if (!url) {
throw new Error('Portless returned an empty URL')
}

return new URL(url).toString().replace(/\/$/, '')
}
catch (error) {
throw createPortlessError('resolve the portless URL', error)
}
}

export function resolvePortlessAliasName(url: string) {
const aliasName = new URL(url).hostname.replace(/\.[^.]+$/, '')
if (!aliasName) {
throw new Error('Portless returned an invalid hostname')
}
return aliasName
}

export async function registerPortlessAlias(cwd: string, name: string, port: number) {
try {
await runPortless(cwd, ['alias', name, `${port}`, '--force'])
}
catch (error) {
throw createPortlessError(`register the portless alias for port ${port}`, error)
}
}

export async function removePortlessAlias(cwd: string, name: string) {
try {
await runPortless(cwd, ['alias', '--remove', name])
}
catch (error) {
throw createPortlessError(`remove the portless alias for ${name}`, error)
}
}

export function registerPortlessExitCleanup(cwd: string, name: string) {
let disposed = false

const cleanup = () => {
if (disposed) {
return
}

disposed = true
process.off('exit', cleanup)
const result = runPortlessSync(cwd, ['alias', '--remove', name])
if (result.error || result.status) {
const message = result.stderr?.trim() || result.error?.message || `portless exited with code ${result.status}`
process.stderr.write(`Failed to remove the portless alias for ${name}: ${message}\n`)
}
}

process.on('exit', cleanup)

return () => {
disposed = true
process.off('exit', cleanup)
}
}

function createPortlessError(action: string, error: unknown) {
const message = typeof error === 'object' && error && 'stderr' in error && typeof error.stderr === 'string' && error.stderr.trim()
? error.stderr.trim()
: error instanceof Error && error.message
? error.message
: 'Unknown portless error'

return new Error(`Failed to ${action}: ${message}`)
}

export async function resolvePortlessName(cwd: string) {
const configuredName = await readNameFromFile(cwd, 'portless.json')
|| await readNameFromFile(cwd, 'package.json')
|| basename(cwd)
return normalizePortlessName(configuredName)
}

function normalizePortlessName(value: string) {
const normalizedValue = value
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '')

return normalizedValue || DEFAULT_PORTLESS_NAME
}

function readNameFromFile(cwd: string, filename: string) {
return readFile(join(cwd, filename), 'utf8')
.then(contents => JSON.parse(contents))
.then(config => typeof config.name === 'string' ? config.name : undefined)
.catch(() => undefined)
}
Comment on lines +118 to +123
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Only ignore missing files when resolving the Portless name.

readNameFromFile() currently swallows parse and permission errors as well as missing-file cases. A malformed portless.json/package.json will silently fall back to basename(cwd), which can expose the dev server under the wrong Portless hostname.

Suggested fix
 function readNameFromFile(cwd: string, filename: string) {
   return readFile(join(cwd, filename), 'utf8')
     .then(contents => JSON.parse(contents))
     .then(config => typeof config.name === 'string' ? config.name : undefined)
-    .catch(() => undefined)
+    .catch((error) => {
+      if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
+        return undefined
+      }
+      throw error
+    })
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/nuxi/src/dev/portless.ts` around lines 118 - 123, readNameFromFile
currently swallows all errors (parse, permission, etc.) and should only ignore
missing files; update the readNameFromFile function so that its promise
rejection handler returns undefined only when the error indicates a missing file
(error.code === 'ENOENT' or equivalent), and rethrow any other errors (so
JSON.parse and permission errors bubble up); keep the existing JSON.parse and
type-check logic but replace the blanket .catch(() => undefined) with
conditional error handling that references readNameFromFile.


function runPortless(cwd: string, args: string[]) {
return x('portless', args, {
throwOnError: true,
nodeOptions: {
cwd,
stdio: 'pipe',
},
})
}

function runPortlessSync(cwd: string, args: string[]) {
return spawnSync('portless', args, {
cwd,
encoding: 'utf8',
stdio: 'pipe',
})
}
70 changes: 70 additions & 0 deletions packages/nuxi/test/unit/dev/portless-exit.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it, vi } from 'vitest'

import { registerPortlessExitCleanup } from '../../../src/dev/portless'

const { spawnSync } = vi.hoisted(() => {
return {
spawnSync: vi.fn(),
}
})

vi.mock('node:child_process', () => {
return {
spawnSync,
}
})

describe('registerPortlessExitCleanup', () => {
const stderrWrite = vi.spyOn(process.stderr, 'write').mockImplementation(() => true)

afterEach(() => {
spawnSync.mockReset()
stderrWrite.mockClear()
})

it('removes the alias on process exit', () => {
spawnSync.mockReturnValue({ status: 0, stderr: '', error: undefined })
const existingListeners = new Set(process.listeners('exit'))
const dispose = registerPortlessExitCleanup('/tmp/fixtures-dev', 'fixtures-dev')
const cleanup = process.listeners('exit').find(listener => !existingListeners.has(listener))

expect(cleanup).toBeTypeOf('function')

cleanup?.(0)

expect(spawnSync).toHaveBeenCalledWith('portless', ['alias', '--remove', 'fixtures-dev'], {
cwd: '/tmp/fixtures-dev',
encoding: 'utf8',
stdio: 'pipe',
})
expect(stderrWrite).not.toHaveBeenCalled()

dispose()
})

it('does nothing after the cleanup is disposed', () => {
const existingListeners = new Set(process.listeners('exit'))
const dispose = registerPortlessExitCleanup('/tmp/fixtures-dev', 'fixtures-dev')
const cleanup = process.listeners('exit').find(listener => !existingListeners.has(listener))

dispose()
cleanup?.(0)

expect(spawnSync).not.toHaveBeenCalled()
})

it('reports cleanup failures on process exit', () => {
spawnSync.mockReturnValue({ status: 1, stderr: 'permission denied\n', error: undefined })
const existingListeners = new Set(process.listeners('exit'))
const dispose = registerPortlessExitCleanup('/tmp/fixtures-dev', 'fixtures-dev')
const cleanup = process.listeners('exit').find(listener => !existingListeners.has(listener))

cleanup?.(0)

expect(stderrWrite).toHaveBeenCalledWith(
'Failed to remove the portless alias for fixtures-dev: permission denied\n',
)

dispose()
})
})
Loading
Loading