Skip to content

Commit fdac645

Browse files
committed
chore: improve printUrl handling
1 parent 948d303 commit fdac645

File tree

4 files changed

+55
-100
lines changed

4 files changed

+55
-100
lines changed

bun.lockb

33 KB
Binary file not shown.

docs/.vitepress/config.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import VueDevTools from 'vite-plugin-vue-devtools'
12
import { defineConfig } from 'vitepress'
23
import Local from '../../src/index'
34

@@ -35,14 +36,16 @@ export default defineConfig({
3536
plugins: [
3637
// @ts-expect-error seems to be a bug in Vitepress not being ready for Vite 6 (?)
3738
Local({
38-
domain: 'docs.local', // default: stacks.localhost
39+
domain: 'stacks.localhost', // default: stacks.localhost
3940
https: true, // Use default SSL config, pass TlsConfig options to customize
4041
cleanup: {
4142
hosts: true, // Clean up relating /etc/hosts entry
4243
certs: false, // Clean up relating SSL certificates
4344
},
4445
verbose: false, // Enable detailed logging
4546
}),
47+
48+
VueDevTools(),
4649
],
4750
},
4851
})

package.json

+3-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@
2828
"files": ["dist"],
2929
"scripts": {
3030
"build": "bun --bun build.ts",
31-
"lint": "bunx eslint --flag unstable_ts_config .",
32-
"lint:fix": "bunx eslint --flag unstable_ts_config . --fix",
31+
"lint": "bunx --bun eslint --flag unstable_ts_config .",
32+
"lint:fix": "bunx --bun eslint --flag unstable_ts_config . --fix",
3333
"fresh": "bunx rimraf node_modules/ bun.lock && bun i",
3434
"changelog": "bunx changelogen --output CHANGELOG.md",
3535
"prepublishOnly": "bun --bun run build",
@@ -51,6 +51,7 @@
5151
"simple-git-hooks": "^2.11.1",
5252
"typescript": "^5.7.2",
5353
"vite": "^6.0.3",
54+
"vite-plugin-vue-devtools": "^7.6.8",
5455
"vitepress": "^1.5.0"
5556
},
5657
"simple-git-hooks": {

src/index.ts

+48-97
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,20 @@
22
import type { Plugin, ViteDevServer } from 'vite'
33
import type { VitePluginLocalOptions } from './types'
44
import { exec, spawn } from 'node:child_process'
5-
import { readFileSync } from 'node:fs'
6-
import { join } from 'node:path'
75
import process from 'node:process'
86
import { promisify } from 'node:util'
97
// @ts-expect-error dtsx issues
108
import { checkExistingCertificates, checkHosts, cleanup, startProxies } from '@stacksjs/rpx'
11-
import { bold, cyan, dim, green } from 'picocolors'
12-
import packageJson from '../package.json'
9+
import { bold, cyan, dim, green, yellow } from 'picocolors'
1310
import { buildConfig } from './utils'
1411

15-
function getPackageVersions() {
16-
let viteVersion
17-
const vitePluginLocalVersion = packageJson.version
18-
let vitePressVersion
19-
20-
try {
21-
// Try to get VitePress version first
22-
const vitePressPath = join(process.cwd(), 'node_modules', 'vitepress', 'package.json')
23-
try {
24-
const vitePressPackage = JSON.parse(readFileSync(vitePressPath, 'utf-8'))
25-
vitePressVersion = vitePressPackage.version
26-
}
27-
catch { }
28-
29-
// Get Vite version
30-
const vitePackageJson = readFileSync(
31-
join(process.cwd(), 'node_modules', 'vite', 'package.json'),
32-
'utf-8',
33-
)
34-
viteVersion = JSON.parse(vitePackageJson).version
35-
}
36-
catch {
37-
// Fallback to package.json dependencies
38-
viteVersion = packageJson.devDependencies?.vite?.replace('^', '') || '0.0.0'
39-
}
40-
41-
return {
42-
'vitepress': vitePressVersion,
43-
'vite': viteVersion,
44-
'vite-plugin-local': vitePluginLocalVersion,
45-
}
12+
const toggleComboKeysMap = {
13+
option: process.platform === 'darwin' ? 'Option(⌥)' : 'Alt(⌥)',
14+
meta: 'Command(⌘)',
15+
shift: 'Shift(⇧)',
16+
}
17+
function normalizeComboKeyPrint(toggleComboKey: string) {
18+
return toggleComboKey.split('-').map(key => toggleComboKeysMap[key] || key[0].toUpperCase() + key.slice(1)).join(dim('+'))
4619
}
4720

4821
const execAsync = promisify(exec)
@@ -129,7 +102,6 @@ export function VitePluginLocal(options: VitePluginLocalOptions): Plugin {
129102

130103
process.stdout.write('\nSudo access required for proxy setup.\n')
131104

132-
// Get sudo access before VitePress starts
133105
hasSudoAccess = await new Promise<boolean>((resolve) => {
134106
const sudo = spawn('sudo', ['true'], {
135107
stdio: 'inherit',
@@ -226,23 +198,9 @@ export function VitePluginLocal(options: VitePluginLocalOptions): Plugin {
226198

227199
server = viteServer
228200

229-
// Override console.log immediately to prevent VitePress initial messages
230-
const originalLog = console.log
231-
console.log = (...args) => {
232-
if (typeof args[0] === 'string' && (
233-
args[0].includes('vitepress v')
234-
|| args[0].includes('press h to show help')
235-
)) {
236-
return
237-
}
238-
originalLog.apply(console, args)
239-
}
240-
241201
// Store original console for debug
242202
originalConsole = { ...console }
243203

244-
server.printUrls = () => { }
245-
246204
// Add cleanup handlers for the server
247205
server.httpServer?.on('close', () => {
248206
debug('Server closing, cleaning up...')
@@ -254,7 +212,6 @@ export function VitePluginLocal(options: VitePluginLocalOptions): Plugin {
254212
process.once('SIGTERM', () => handleSignal('SIGTERM'))
255213
process.once('beforeExit', () => handleSignal('beforeExit'))
256214
process.once('exit', async () => {
257-
// If there's a pending cleanup, wait for it
258215
if (cleanupPromise) {
259216
try {
260217
await cleanupPromise
@@ -266,60 +223,54 @@ export function VitePluginLocal(options: VitePluginLocalOptions): Plugin {
266223
}
267224
})
268225

269-
const setupProxy = async () => {
226+
const colorUrl = (url: string) =>
227+
cyan(url.replace(/:(\d+)\//, (_, port) => `:${bold(port)}/`))
228+
229+
// Store the original printUrls function
230+
const originalPrintUrls = server.printUrls
231+
232+
// Wrap the printUrls function to add our custom output while preserving other plugins' modifications
233+
server.printUrls = () => {
234+
if (!server?.resolvedUrls)
235+
return
236+
237+
// Call the original printUrls function first
238+
if (typeof originalPrintUrls === 'function') {
239+
originalPrintUrls.call(server)
240+
}
241+
else {
242+
// If no other plugin has modified printUrls, print the default local URL
243+
console.log(` ${green('➜')} ${bold('Local')}: ${colorUrl(server.resolvedUrls.local[0])}`)
244+
console.log(` ${green('➜')} ${bold('Network')}: ${dim('use --host to expose')}`)
245+
}
246+
247+
// Add our custom proxy URL information
248+
if (proxyUrl) {
249+
const protocol = options.https ? 'https' : 'http'
250+
const proxiedUrl = `${protocol}://${proxyUrl}/`
251+
console.log(` ${green('➜')} ${bold('Proxied URL')}: ${colorUrl(proxiedUrl)}`)
252+
253+
if (options.https) {
254+
console.log(` ${green('➜')} ${bold('SSL')}: ${dim('TLS 1.2/1.3, HTTP/2')}`)
255+
}
256+
}
257+
}
258+
259+
const startProxy = async () => {
270260
try {
271-
const host = typeof server!.config.server.host === 'boolean'
261+
const host = typeof server?.config.server.host === 'boolean'
272262
? 'localhost'
273-
: server!.config.server.host || 'localhost'
263+
: server?.config.server.host || 'localhost'
274264

275-
const port = server!.config.server.port || 5173
265+
const port = server?.config.server.port || 5173
276266
const serverUrl = `${host}:${port}`
277267

278268
const config = buildConfig(options, serverUrl)
279269
domains = [config.to]
280270
proxyUrl = config.to
281271

282272
debug('Starting proxies...')
283-
284273
await startProxies(config)
285-
286-
server!.printUrls = function () {
287-
const protocol = options.https ? 'https' : 'http'
288-
const port = server!.config.server.port || 5173
289-
const localUrl = `http://localhost:${port}/`
290-
const proxiedUrl = `${protocol}://${proxyUrl}/`
291-
const colorUrl = (url: string) =>
292-
cyan(url.replace(/:(\d+)\//, (_, port) => `:${bold(port)}/`))
293-
294-
const versions = getPackageVersions()
295-
if (versions.vitepress) {
296-
console.log(
297-
`\n ${bold(green('vitepress'))} ${green(`v${versions.vitepress}`)} ${dim('via')} ${bold(green('vite-plugin-local'))} ${green(`v${versions['vite-plugin-local']}`)}\n`,
298-
)
299-
}
300-
else {
301-
console.log(
302-
`\n ${bold(green('vite'))} ${green(`v${versions.vite}`)} ${dim('via')} ${bold(green('vite-plugin-local'))} ${green(`v${versions['vite-plugin-local']}`)}\n`,
303-
)
304-
}
305-
306-
console.log(` ${green('➜')} ${bold('Local')}: ${colorUrl(localUrl)}`)
307-
console.log(` ${green('➜')} ${bold('Proxied')}: ${colorUrl(proxiedUrl)}`)
308-
309-
if (options.https) {
310-
console.log(` ${green('➜')} ${bold('SSL')}: ${dim('TLS 1.2/1.3, HTTP/2')}`)
311-
}
312-
313-
console.log(
314-
dim(` ${green('➜')} ${bold('Network')}: use `)
315-
+ bold('--host')
316-
+ dim(' to expose'),
317-
)
318-
319-
console.log(`\n ${green(dim('➜'))} ${dim('press')} ${bold('h')} ${dim('to show help')}\n`)
320-
}
321-
322-
server!.printUrls()
323274
debug('Proxy setup complete')
324275
}
325276
catch (error) {
@@ -328,10 +279,10 @@ export function VitePluginLocal(options: VitePluginLocalOptions): Plugin {
328279
}
329280
}
330281

331-
server.httpServer?.once('listening', setupProxy)
282+
// Wait for the server to be ready before starting the proxy
283+
server.httpServer?.once('listening', startProxy)
332284
if (server.httpServer?.listening) {
333-
debug('Server already listening, setting up proxy immediately')
334-
await setupProxy()
285+
await startProxy()
335286
}
336287
},
337288

0 commit comments

Comments
 (0)