@hamedb89/localghost 0.1.13 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vite.ts","../src/activity.ts","../src/config.ts","../src/parse.ts","../src/context.ts","../src/port.ts","../src/tunnel.ts","../src/doctor.ts","../src/env.ts","../src/fs.ts","../src/hosts-file.ts","../src/prompt.ts","../src/state.ts","../src/caddy.ts","../src/routes.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { normalize, resolve } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { emitKeypressEvents } from \"node:readline\";\nimport type { ConfigEnv, HmrOptions, Plugin, UserConfig, ViteDevServer, WsOptions } from \"vite\";\nimport { registerLocalghostRun, registerLocalghostSetup, unregisterLocalghostRun } from \"./activity.js\";\nimport {\n getConfigFileCandidates,\n getProjectName,\n readDevHosts,\n resolveDevHostsPath,\n sanitizeProjectName,\n type ConfigPattern,\n type ReadDevHostsOptions\n} from \"./config.js\";\nimport { addDefaultWwwAliases, readLocalghostProjectConfig, resolveLocalghostContext, type LocalghostContext } from \"./context.js\";\nimport { checkCaddy } from \"./doctor.js\";\nimport { isProductionLike } from \"./env.js\";\nimport { writeTextFile } from \"./fs.js\";\nimport { getSystemHostsPath, renderHostsBlock, updateSystemHosts } from \"./hosts-file.js\";\nimport { ask, canPrompt, confirm } from \"./prompt.js\";\nimport { getLocalghostStatePath, readLocalghostState, writeLocalghostState } from \"./state.js\";\nimport { getCaddyfilePath, renderCaddyfile, validateCaddyfile, writeCaddyfile } from \"./caddy.js\";\nimport type { DevHostEntry } from \"./parse.js\";\nimport { resolveGhostTunnelConfig, type GhostTunnelOptions } from \"./tunnel.js\";\nimport { formatGhostTunnel } from \"./routes.js\";\n\nexport type LocalGhostPluginOptions = {\n cwd?: string;\n fileName?: string;\n configFiles?: string[];\n configPattern?: ConfigPattern;\n port?: number;\n https?: boolean;\n bindHost?: string | boolean;\n dynamicPort?: boolean;\n autoRepair?: boolean;\n primaryHost?: string;\n log?: boolean;\n setup?: boolean | \"prompt\";\n localghostConfig?: string | false;\n wwwAlias?: boolean;\n ghostTunnel?: GhostTunnelOptions;\n verbose?: boolean;\n};\n\ntype ServerOptions = NonNullable<UserConfig[\"server\"]>;\n\nfunction mergeAllowedHosts(current: ServerOptions[\"allowedHosts\"], hosts: string[]) {\n if (Array.isArray(current)) {\n return [...new Set([...current, ...hosts])];\n }\n\n return hosts;\n}\n\nfunction getDisplayEntries(entries: DevHostEntry[], vitePort: number | undefined) {\n if (!vitePort) {\n return entries;\n }\n\n const matchingEntries = entries.filter((entry) => entry.port === vitePort);\n return matchingEntries.length > 0 ? matchingEntries : entries;\n}\n\nfunction printLocalHosts(server: ViteDevServer, context: LocalghostContext | undefined) {\n if (!context) return;\n\n const entries = context.entries;\n const vitePort = context.port;\n const https = context.https;\n const displayEntries = getDisplayEntries(entries, vitePort);\n const protocol = https ? \"https\" : \"http\";\n const urls = displayEntries.map((entry) => `${protocol}://${entry.host}/`);\n const primaryUrl = urls[0];\n\n if (!primaryUrl) {\n return;\n }\n\n const lines = [\n \"\",\n \" localghost\",\n ` local: ${primaryUrl}`,\n ...urls.slice(1).map((url) => ` also: ${url}`),\n vitePort ? ` target: http://127.0.0.1:${vitePort}/` : undefined,\n https ? \" proxy: Caddy local HTTPS\" : undefined,\n context.ghostTunnel.enabled ? formatGhostTunnel(context.ghostTunnel, {\n color: shouldColor(),\n label: \"ready\",\n verbose: optionsVerbose(context)\n }) : undefined,\n process.stdin.isTTY && context.ghostTunnel.enabled ? \" help: press h + enter for Vite, g + enter for Localghost\" : undefined\n ].filter((line): line is string => Boolean(line));\n\n server.config.logger.info(lines.join(\"\\n\"), {\n clear: false,\n timestamp: false\n });\n}\n\nfunction shouldColor() {\n return process.stdout.isTTY && !process.env.NO_COLOR;\n}\n\nfunction optionsVerbose(context: LocalghostContext) {\n return process.env.LOCALGHOST_VERBOSE === \"1\" || process.env.LOCALGHOST_VERBOSE === \"true\" || context.ghostTunnel.displayUrls.length > 1;\n}\n\nfunction readOptionsFromPlugin(options: LocalGhostPluginOptions): ReadDevHostsOptions {\n return {\n cwd: options.cwd ?? process.cwd(),\n ...(options.fileName ? { fileName: options.fileName } : {}),\n ...(options.configFiles ? { configFiles: options.configFiles } : {}),\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n}\n\nfunction getConfigWatchFiles(options: LocalGhostPluginOptions) {\n const readOptions = readOptionsFromPlugin(options);\n const cwd = readOptions.cwd ?? process.cwd();\n const resolvedPath = resolveDevHostsPath(readOptions);\n const candidatePaths = getConfigFileCandidates(readOptions).map((fileName) => resolve(cwd, fileName));\n const projectConfigPaths = options.localghostConfig === false\n ? []\n : options.localghostConfig\n ? [resolve(cwd, options.localghostConfig)]\n : [\"localghost.config.mjs\", \"localghost.config.js\", \"localghost.config.cjs\"].map((fileName) => resolve(cwd, fileName));\n\n return [...new Set([...candidatePaths, resolvedPath.path, ...projectConfigPaths])];\n}\n\nfunction normalizeWatchPath(filePath: string) {\n return normalize(resolve(filePath));\n}\n\nfunction renderConfig(hosts: string[], port: number) {\n return [\n \"# Buh. Friendly names for local services.\",\n \"# Format: <host> <port>\",\n ...hosts.map((host) => `${host} ${port}`),\n \"\"\n ].join(\"\\n\");\n}\n\nfunction defaultHost(cwd: string) {\n const projectName = sanitizeProjectName(getProjectName(cwd).split(\"/\").pop() ?? \"app\");\n return `${projectName}.localhost`;\n}\n\nfunction getPackageOwner(cwd: string) {\n try {\n const pkg = JSON.parse(readFileSync(resolve(cwd, \"package.json\"), \"utf8\")) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.startsWith(\"@\")) {\n return pkg.name.slice(1).split(\"/\")[0];\n }\n } catch {\n return undefined;\n }\n\n return undefined;\n}\n\nfunction getLocalOwner(cwd: string) {\n return sanitizeProjectName(process.env.LOCALGHOST_OWNER ?? getPackageOwner(cwd) ?? process.env.USER ?? process.env.USERNAME ?? \"local\");\n}\n\nfunction getRouteName(primaryHost: string, fallback: string) {\n return sanitizeProjectName(primaryHost.split(\".\")[0] ?? fallback);\n}\n\nfunction readBuildEntries(options: LocalGhostPluginOptions) {\n const readOptions = readOptionsFromPlugin(options);\n const resolved = resolveDevHostsPath(readOptions);\n if (!resolved.exists) return [];\n\n try {\n return readDevHosts(readOptions);\n } catch {\n return [];\n }\n}\n\nasync function maybePrintBuildGhostTunnel(options: LocalGhostPluginOptions) {\n const cwd = options.cwd ?? process.cwd();\n const projectConfig = await readLocalghostProjectConfig({\n cwd,\n ...(typeof options.localghostConfig !== \"undefined\" ? { configFile: options.localghostConfig } : {})\n });\n const explicitGhostTunnel = typeof options.ghostTunnel !== \"undefined\" ? options.ghostTunnel : projectConfig.config.ghostTunnel;\n if (!explicitGhostTunnel) return;\n\n const entries = readBuildEntries(options);\n const projectName = sanitizeProjectName(projectConfig.config.project ?? getProjectName(cwd));\n const primaryHost = options.primaryHost ?? entries[0]?.host ?? defaultHost(cwd);\n const ghostTunnel = resolveGhostTunnelConfig(explicitGhostTunnel, {\n route: getRouteName(primaryHost, projectName),\n project: sanitizeProjectName(projectConfig.config.project ?? getProjectName(cwd)),\n owner: getLocalOwner(cwd)\n });\n\n if (!ghostTunnel.enabled) return;\n\n const formatted = formatGhostTunnel(ghostTunnel, {\n color: shouldColor(),\n label: \"configured\",\n verbose: options.verbose === true || process.env.LOCALGHOST_VERBOSE === \"1\" || process.env.LOCALGHOST_VERBOSE === \"true\"\n });\n if (formatted) console.log(formatted);\n}\n\nasync function promptForHosts(cwd: string, port: number) {\n const primaryHost = await ask(\"Primary local domain\", defaultHost(cwd));\n const hosts = [primaryHost.toLowerCase()];\n\n while (await confirm(\"Add another local domain?\", false)) {\n const host = await ask(\"Domain\");\n if (host) hosts.push(host.toLowerCase());\n }\n\n return [...new Set(addDefaultWwwAliases(hosts.map((host) => ({ host, port, target: `127.0.0.1:${port}` }))).map((entry) => entry.host))];\n}\n\nfunction hasReadySetup(cwd: string, entries: DevHostEntry[], configPath: string, https: boolean) {\n const state = readLocalghostState(cwd);\n const projectName = sanitizeProjectName(getProjectName(cwd));\n if (state?.action !== \"setup\" || state.configPath !== configPath) return false;\n\n try {\n const hosts = readFileSync(getSystemHostsPath(), \"utf8\");\n if (!hosts.includes(renderHostsBlock(projectName, entries).trimEnd())) return false;\n } catch {\n return false;\n }\n\n const caddyfilePath = getCaddyfilePath(cwd);\n return existsSync(caddyfilePath) && readFileSync(caddyfilePath, \"utf8\") === renderCaddyfile(entries, { https });\n}\n\nasync function setupProject(cwd: string, entries: DevHostEntry[], configPath: string, https: boolean) {\n const caddy = await checkCaddy();\n if (!caddy.found) {\n throw new Error([\n \"Caddy is missing.\",\n `Run: ${caddy.installHint}`,\n \"Localghost will not install it for you.\"\n ].join(\"\\n\"));\n }\n\n const projectName = sanitizeProjectName(getProjectName(cwd));\n console.log(\"Buh. macOS keeps local hostnames in /etc/hosts, so Localghost may ask for your password.\");\n console.log(\"It will only touch its managed Localghost block.\");\n const hostsResult = await updateSystemHosts(projectName, entries);\n const caddyfilePath = await writeCaddyfile(entries, cwd, { https });\n await validateCaddyfile(caddyfilePath);\n writeLocalghostState(cwd, {\n action: \"setup\",\n projectName,\n cwd,\n configPath,\n hostsPath: hostsResult.hostsPath,\n hostsChanged: hostsResult.changed,\n ...(hostsResult.tempPath ? { hostsTempPath: hostsResult.tempPath } : {}),\n caddyfilePath,\n caddyHttps: https,\n entries\n });\n registerLocalghostSetup({\n cwd,\n projectName,\n configPath,\n caddyfilePath,\n https,\n entries\n });\n}\n\nasync function ensureLocalghostContext(options: LocalGhostPluginOptions, vitePort: number, https: boolean | undefined) {\n const cwd = options.cwd ?? process.cwd();\n const readOptions = readOptionsFromPlugin(options);\n const resolved = resolveDevHostsPath(readOptions);\n\n if (!resolved.exists) {\n if (options.setup === false || !canPrompt()) {\n throw new Error(\n `No .localghost found at ${resolved.path}. Run \\`localghost init --write-scripts\\` or start Vite in an interactive terminal.`\n );\n }\n\n console.log(`No .localghost found at ${resolved.path}.`);\n if (!(await confirm(\"Create one now?\", true))) {\n throw new Error(\"Localghost setup skipped. Create .localghost before running the Vite plugin.\");\n }\n\n const hosts = await promptForHosts(cwd, vitePort);\n writeTextFile(resolved.path, renderConfig(hosts, vitePort));\n console.log(`Created ${resolved.path}`);\n }\n\n const context = await resolveLocalghostContext({\n ...options,\n cwd,\n port: vitePort,\n ...(typeof https === \"boolean\" ? { https } : {})\n });\n\n if (!hasReadySetup(cwd, context.entries, resolved.path, context.https)) {\n if (options.setup === false || !context.autoRepair) return context;\n if (options.setup === \"prompt\" && (!canPrompt() || !(await confirm(\"Repair Localghost setup now?\", true)))) return context;\n\n console.log(\"Localghost setup is stale; repairing it now.\");\n await setupProject(cwd, context.entries, resolved.path, context.https);\n console.log(`Repair complete. Setup state: ${getLocalghostStatePath(cwd)}`);\n }\n\n return context;\n}\n\nfunction isConcreteGhostUrl(url: string) {\n return !url.includes(\"*\") && !url.includes(\"<\") && /^https?:\\/\\//.test(url);\n}\n\nfunction getConcreteGhostUrls(context: LocalghostContext) {\n return context.ghostTunnel.displayUrls.filter(isConcreteGhostUrl);\n}\n\nfunction openExternalUrl(url: string) {\n const command = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"cmd\" : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n const child = spawn(command, args, {\n detached: true,\n stdio: \"ignore\"\n });\n child.unref();\n}\n\nfunction installGhostTunnelMenu(server: ViteDevServer, context: LocalghostContext | undefined) {\n if (!context?.ghostTunnel.enabled || !process.stdin.isTTY) return undefined;\n\n emitKeypressEvents(process.stdin);\n\n let active = false;\n const concreteUrls = getConcreteGhostUrls(context);\n\n const printMenu = () => {\n active = true;\n const lines = [\n \"\",\n formatGhostTunnel(context.ghostTunnel, {\n color: shouldColor(),\n label: \"ready\",\n verbose: true\n }) ?? \"localghost ghost tunnel\",\n \"\"\n ];\n\n if (concreteUrls.length === 0) {\n lines.push(\" No concrete Ghost Tunnel domain configured.\");\n lines.push(\" Add ghostTunnel.domains to localghost.config.mjs to open a URL from this menu.\");\n active = false;\n } else {\n concreteUrls.forEach((url, index) => {\n lines.push(` ${index + 1}. ${url}`);\n });\n lines.push(\"\");\n lines.push(\" Press a number to open, or escape to cancel.\");\n }\n\n server.config.logger.info(lines.join(\"\\n\"), {\n clear: false,\n timestamp: false\n });\n };\n\n const onKeypress = (_input: string, key: { name?: string; ctrl?: boolean } = {}) => {\n if (key.ctrl && key.name === \"c\") return;\n\n if (!active) {\n if (key.name === \"g\") printMenu();\n return;\n }\n\n if (key.name === \"escape\") {\n active = false;\n return;\n }\n\n const index = Number.parseInt(key.name ?? \"\", 10) - 1;\n const url = concreteUrls[index];\n if (!url) return;\n\n active = false;\n openExternalUrl(url);\n server.config.logger.info(`localghost opened ${url}`, {\n clear: false,\n timestamp: false\n });\n };\n\n process.stdin.on(\"keypress\", onKeypress);\n\n return () => {\n process.stdin.off(\"keypress\", onKeypress);\n };\n}\n\nexport function localGhostPlugin(options: LocalGhostPluginOptions = {}): Plugin {\n let resolvedEntries: DevHostEntry[] = [];\n let resolvedVitePort: number | undefined;\n let resolvedHttps = false;\n let resolvedContext: LocalghostContext | undefined;\n let restartTimer: NodeJS.Timeout | undefined;\n let activityRunId: string | undefined;\n\n return {\n name: \"localghost:vite\",\n enforce: \"pre\",\n\n async config(userConfig, configEnv: ConfigEnv): Promise<UserConfig> {\n if (configEnv.command !== \"serve\" || configEnv.mode === \"production\" || isProductionLike()) {\n await maybePrintBuildGhostTunnel(options);\n return {};\n }\n\n const existingServer = userConfig.server ?? {};\n const envVitePort = Number.parseInt(process.env.LOCALGHOST_PORT ?? process.env.VITE_PORT ?? \"\", 10);\n const requestedVitePort =\n options.port ??\n existingServer.port ??\n (Number.isInteger(envVitePort) ? envVitePort : 5173);\n const context: LocalghostContext = await ensureLocalghostContext(options, requestedVitePort, options.https);\n const entries = context.entries;\n const hosts = context.hosts;\n const primaryHost = context.primaryHost;\n\n resolvedEntries = entries;\n resolvedVitePort = context.port;\n resolvedHttps = context.https;\n resolvedContext = context;\n\n const server: ServerOptions = {\n ...existingServer,\n allowedHosts: mergeAllowedHosts(existingServer.allowedHosts, hosts),\n strictPort: existingServer.strictPort ?? true\n };\n\n if (typeof existingServer.host === \"undefined\") {\n server.host = context.bindHost;\n }\n\n if (context.port) {\n server.port = context.port;\n }\n\n if (context.https && primaryHost) {\n const existingWs = typeof server.ws === \"object\" && server.ws ? server.ws : {};\n const existingHmr = typeof existingServer.hmr === \"object\" && existingServer.hmr ? existingServer.hmr : {};\n\n server.ws = {\n ...existingWs,\n protocol: \"wss\",\n host: primaryHost,\n clientPort: 443\n } satisfies WsOptions;\n\n server.hmr = {\n ...existingHmr,\n protocol: \"wss\",\n host: primaryHost,\n clientPort: 443\n } satisfies HmrOptions;\n }\n\n return { server };\n },\n\n configureServer(server) {\n const watchFiles = getConfigWatchFiles(options);\n const watchedConfigFiles = new Set(watchFiles.map(normalizeWatchPath));\n\n server.watcher.add(watchFiles);\n\n const restartOnLocalghostConfigChange = (filePath: string) => {\n if (!watchedConfigFiles.has(normalizeWatchPath(filePath))) {\n return;\n }\n\n if (restartTimer) {\n clearTimeout(restartTimer);\n }\n\n restartTimer = setTimeout(() => {\n if (options.log !== false) {\n server.config.logger.info(\"localghost config changed; restarting Vite dev server\", {\n clear: false,\n timestamp: false\n });\n }\n\n void server.restart().catch((error: unknown) => {\n server.config.logger.error(error instanceof Error ? error.message : String(error), {\n timestamp: false\n });\n });\n }, 50);\n };\n\n server.watcher.on(\"add\", restartOnLocalghostConfigChange);\n server.watcher.on(\"change\", restartOnLocalghostConfigChange);\n server.watcher.on(\"unlink\", restartOnLocalghostConfigChange);\n\n if (options.log !== false) {\n server.printUrls = () => {\n printLocalHosts(server, resolvedContext);\n };\n }\n\n if (resolvedContext) {\n const run = registerLocalghostRun({\n id: `${resolvedContext.projectName}:vite:${process.pid}:${resolvedContext.cwd}`,\n mode: \"vite\",\n pid: process.pid,\n cwd: resolvedContext.cwd,\n projectName: resolvedContext.projectName,\n configPath: resolvedContext.configPath,\n childCommand: [\"vite\"],\n https: resolvedContext.https,\n requestedPort: resolvedContext.requestedPort,\n port: resolvedContext.port,\n dynamicPort: resolvedContext.dynamicPort,\n entries: resolvedContext.entries\n });\n activityRunId = run.id;\n }\n\n const cleanupGhostMenu = installGhostTunnelMenu(server, resolvedContext);\n\n const cleanupActivity = () => {\n if (!activityRunId) return;\n unregisterLocalghostRun(activityRunId);\n activityRunId = undefined;\n };\n\n const cleanup = () => {\n cleanupActivity();\n cleanupGhostMenu?.();\n };\n\n server.httpServer?.once(\"close\", cleanup);\n process.once(\"exit\", cleanup);\n }\n };\n}\n\nexport const localHostsPlugin = localGhostPlugin;\nexport type LocalHostsPluginOptions = LocalGhostPluginOptions;\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport const LOCALGHOST_ACTIVITY_VERSION = 1;\n\nexport type LocalghostRunMode = \"dev\" | \"run\" | \"vite\";\n\nexport type LocalghostRunRecord = {\n id: string;\n mode: LocalghostRunMode;\n pid: number;\n cwd: string;\n projectName: string;\n startedAt: string;\n updatedAt: string;\n configPath?: string;\n caddyfilePath?: string;\n caddyPid?: number;\n childPid?: number;\n childCommand?: string[];\n https?: boolean;\n requestedPort?: number;\n port?: number;\n dynamicPort?: boolean;\n entries: DevHostEntry[];\n};\n\nexport type LocalghostSetupRecord = {\n id: string;\n cwd: string;\n projectName: string;\n updatedAt: string;\n configPath?: string;\n caddyfilePath?: string;\n https?: boolean;\n entries: DevHostEntry[];\n};\n\nexport type LocalghostActivity = {\n version: typeof LOCALGHOST_ACTIVITY_VERSION;\n runs: LocalghostRunRecord[];\n setups: LocalghostSetupRecord[];\n};\n\nexport type RegisterLocalghostRunInput = Omit<LocalghostRunRecord, \"id\" | \"pid\" | \"startedAt\" | \"updatedAt\"> & {\n id?: string;\n pid?: number;\n startedAt?: string;\n};\n\nexport type RegisterLocalghostSetupInput = Omit<LocalghostSetupRecord, \"id\" | \"updatedAt\"> & {\n id?: string;\n};\n\nexport function getLocalghostActivityPath(env: NodeJS.ProcessEnv = process.env) {\n if (env.LOCALGHOST_ACTIVITY_PATH) return env.LOCALGHOST_ACTIVITY_PATH;\n\n const stateRoot = env.XDG_STATE_HOME || join(homedir(), \".local/state\");\n return join(stateRoot, \"localghost\", \"activity.json\");\n}\n\nexport function isProcessRunning(pid: number) {\n if (!Number.isInteger(pid) || pid < 1) return false;\n\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? error.code : undefined;\n return code === \"EPERM\";\n }\n}\n\nfunction emptyActivity(): LocalghostActivity {\n return { version: LOCALGHOST_ACTIVITY_VERSION, runs: [], setups: [] };\n}\n\nexport function readLocalghostActivity(path = getLocalghostActivityPath()): LocalghostActivity {\n if (!existsSync(path)) return emptyActivity();\n\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as Partial<LocalghostActivity>;\n return {\n version: LOCALGHOST_ACTIVITY_VERSION,\n runs: Array.isArray(parsed.runs) ? parsed.runs : [],\n setups: Array.isArray(parsed.setups) ? parsed.setups : []\n };\n } catch {\n return emptyActivity();\n }\n}\n\nexport function writeLocalghostActivity(activity: LocalghostActivity, path = getLocalghostActivityPath()) {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(activity, null, 2)}\\n`, \"utf8\");\n return path;\n}\n\nfunction createRunId(input: Pick<RegisterLocalghostRunInput, \"mode\" | \"cwd\" | \"projectName\">, pid: number) {\n return `${input.projectName}:${input.mode}:${pid}:${Date.now()}`;\n}\n\nfunction createSetupId(input: Pick<RegisterLocalghostSetupInput, \"cwd\" | \"projectName\" | \"configPath\">) {\n return `${input.projectName}:${input.cwd}:${input.configPath ?? \"\"}`;\n}\n\nexport function pruneLocalghostActivity(path = getLocalghostActivityPath()) {\n const activity = readLocalghostActivity(path);\n const activeRuns = activity.runs.filter((run) => isProcessRunning(run.pid));\n const pruned = activeRuns.length !== activity.runs.length;\n\n if (pruned) {\n writeLocalghostActivity({ ...activity, version: LOCALGHOST_ACTIVITY_VERSION, runs: activeRuns }, path);\n }\n\n return {\n path,\n pruned,\n runs: activeRuns,\n setups: activity.setups\n };\n}\n\nexport function listLocalghostRuns(path = getLocalghostActivityPath()) {\n return pruneLocalghostActivity(path).runs;\n}\n\nexport function listLocalghostSetups(path = getLocalghostActivityPath()) {\n return pruneLocalghostActivity(path).setups;\n}\n\nexport function registerLocalghostRun(input: RegisterLocalghostRunInput, path = getLocalghostActivityPath()) {\n const now = new Date().toISOString();\n const pid = input.pid ?? process.pid;\n const record: LocalghostRunRecord = {\n id: input.id ?? createRunId(input, pid),\n mode: input.mode,\n pid,\n cwd: input.cwd,\n projectName: input.projectName,\n startedAt: input.startedAt ?? now,\n updatedAt: now,\n ...(input.configPath ? { configPath: input.configPath } : {}),\n ...(input.caddyfilePath ? { caddyfilePath: input.caddyfilePath } : {}),\n ...(input.caddyPid ? { caddyPid: input.caddyPid } : {}),\n ...(input.childPid ? { childPid: input.childPid } : {}),\n ...(input.childCommand ? { childCommand: input.childCommand } : {}),\n ...(typeof input.https === \"boolean\" ? { https: input.https } : {}),\n ...(input.requestedPort ? { requestedPort: input.requestedPort } : {}),\n ...(input.port ? { port: input.port } : {}),\n ...(typeof input.dynamicPort === \"boolean\" ? { dynamicPort: input.dynamicPort } : {}),\n entries: input.entries\n };\n const current = pruneLocalghostActivity(path).runs.filter((run) => run.id !== record.id);\n const activity = readLocalghostActivity(path);\n writeLocalghostActivity({ version: LOCALGHOST_ACTIVITY_VERSION, runs: [...current, record], setups: activity.setups }, path);\n return record;\n}\n\nexport function registerLocalghostSetup(input: RegisterLocalghostSetupInput, path = getLocalghostActivityPath()) {\n const record: LocalghostSetupRecord = {\n id: input.id ?? createSetupId(input),\n cwd: input.cwd,\n projectName: input.projectName,\n updatedAt: new Date().toISOString(),\n ...(input.configPath ? { configPath: input.configPath } : {}),\n ...(input.caddyfilePath ? { caddyfilePath: input.caddyfilePath } : {}),\n ...(typeof input.https === \"boolean\" ? { https: input.https } : {}),\n entries: input.entries\n };\n const activity = pruneLocalghostActivity(path);\n const setups = activity.setups.filter((setup) => setup.id !== record.id);\n writeLocalghostActivity({ version: LOCALGHOST_ACTIVITY_VERSION, runs: activity.runs, setups: [...setups, record] }, path);\n return record;\n}\n\nexport function unregisterLocalghostRun(id: string, path = getLocalghostActivityPath()) {\n const activity = readLocalghostActivity(path);\n const runs = activity.runs.filter((run) => run.id !== id);\n\n if (runs.length !== activity.runs.length) {\n writeLocalghostActivity({ ...activity, version: LOCALGHOST_ACTIVITY_VERSION, runs }, path);\n }\n}\n\nexport function unregisterLocalghostSetup(options: { cwd: string; projectName?: string; configPath?: string }, path = getLocalghostActivityPath()) {\n const activity = readLocalghostActivity(path);\n const setups = activity.setups.filter((setup) => {\n if (setup.cwd !== options.cwd) return true;\n if (options.projectName && setup.projectName !== options.projectName) return true;\n if (options.configPath && setup.configPath !== options.configPath) return true;\n return false;\n });\n\n if (setups.length !== activity.setups.length) {\n writeLocalghostActivity({ ...activity, version: LOCALGHOST_ACTIVITY_VERSION, setups }, path);\n }\n}\n","import { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parseDevHosts } from \"./parse.js\";\n\nexport const LOCALGHOST_CONFIG_FILE = \".localghost\";\n\nexport type ConfigPattern = string | RegExp;\n\nexport type ReadDevHostsOptions = {\n cwd?: string;\n fileName?: string;\n configFiles?: string[];\n configPattern?: ConfigPattern;\n};\n\nexport type ResolvedDevHostsPath = {\n path: string;\n fileName: string;\n exists: boolean;\n searchedFiles: string[];\n configPattern?: ConfigPattern;\n};\n\nfunction unique(values: string[]) {\n return [...new Set(values.filter(Boolean))];\n}\n\nfunction toRegExp(pattern: ConfigPattern) {\n return typeof pattern === \"string\" ? new RegExp(pattern) : pattern;\n}\n\nfunction findPatternMatches(cwd: string, pattern: ConfigPattern) {\n const matcher = toRegExp(pattern);\n\n return readdirSync(cwd, { withFileTypes: true })\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name)\n .filter((name) => {\n matcher.lastIndex = 0;\n return matcher.test(name);\n })\n .sort();\n}\n\nexport function getConfigFileCandidates(options: ReadDevHostsOptions = {}) {\n const cwd = options.cwd ?? process.cwd();\n const exactFiles = unique([\n ...(options.fileName ? [options.fileName] : []),\n ...(options.configFiles ?? [])\n ]);\n const patternFiles = options.configPattern ? findPatternMatches(cwd, options.configPattern) : [];\n const candidates = unique([...exactFiles, ...patternFiles]);\n\n if (candidates.length > 0) return candidates;\n if (exactFiles.length > 0 || options.configPattern) return [];\n return [LOCALGHOST_CONFIG_FILE];\n}\n\nexport function resolveDevHostsPath(options: ReadDevHostsOptions = {}): ResolvedDevHostsPath {\n const cwd = options.cwd ?? process.cwd();\n const searchedFiles = getConfigFileCandidates(options);\n\n for (const fileName of searchedFiles) {\n const path = resolve(cwd, fileName);\n if (existsSync(path)) {\n return {\n path,\n fileName: basename(fileName),\n exists: true,\n searchedFiles,\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n }\n }\n\n const fileName = searchedFiles[0] ?? LOCALGHOST_CONFIG_FILE;\n\n return {\n path: resolve(cwd, fileName),\n fileName: basename(fileName),\n exists: false,\n searchedFiles,\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n}\n\nexport function getDevHostsPath(options: ReadDevHostsOptions = {}) {\n return resolveDevHostsPath(options).path;\n}\n\nfunction formatSearchedFiles(files: string[], pattern?: ConfigPattern) {\n if (files.length > 0) return files.map((file) => `\\`${file}\\``).join(\", \");\n if (pattern) return `files matching ${pattern.toString()}`;\n return `\\`${LOCALGHOST_CONFIG_FILE}\\``;\n}\n\nexport function readDevHosts(options: ReadDevHostsOptions | string = {}) {\n const resolvedOptions = typeof options === \"string\" ? { cwd: options } : options;\n const resolvedPath = resolveDevHostsPath(resolvedOptions);\n\n if (!resolvedPath.exists) {\n const cwd = resolvedOptions.cwd ?? process.cwd();\n throw new Error(\n `Missing Localghost config in ${cwd}. Looked for ${formatSearchedFiles(resolvedPath.searchedFiles, resolvedPath.configPattern)}. Run \\`localghost init\\` or pass --config/--config-pattern.`\n );\n }\n\n return parseDevHosts(readFileSync(resolvedPath.path, \"utf8\"), resolvedPath.fileName);\n}\n\nexport function getProjectName(cwd = process.cwd()) {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, \"package.json\"), \"utf8\")) as { name?: unknown };\n const name = typeof pkg.name === \"string\" && pkg.name ? pkg.name : \"app\";\n return sanitizeProjectName(name.replace(/^@/, \"\"));\n } catch {\n return \"app\";\n }\n}\n\nexport function sanitizeProjectName(value: string) {\n const projectName = value.replace(/[^\\w.-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n return projectName || \"app\";\n}\n","export type DevHostEntry = {\n host: string;\n port: number;\n target: string;\n};\n\nconst HOST_PATTERN = /^(?=.{1,253}$)(?!-)[a-z0-9-]+(\\.[a-z0-9-]+)*\\.?$/i;\n\nexport function parseDevHosts(input: string, fileName = \".localghost\"): DevHostEntry[] {\n const entries: DevHostEntry[] = [];\n\n input.split(/\\r?\\n/).forEach((rawLine, index) => {\n const line = rawLine.replace(/#.*/, \"\").trim();\n\n if (!line) {\n return;\n }\n\n const parts = line.split(/\\s+/);\n const host = parts[0];\n const portRaw = parts[1];\n\n if (!host || !portRaw || parts.length > 2) {\n throw new Error(`Invalid ${fileName} line ${index + 1}: \"${rawLine}\"`);\n }\n\n if (!HOST_PATTERN.test(host)) {\n throw new Error(`Invalid host on line ${index + 1}: \"${host}\"`);\n }\n\n const port = Number(portRaw);\n\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(`Invalid port on line ${index + 1}: \"${portRaw}\"`);\n }\n\n entries.push({\n host: host.toLowerCase().replace(/\\.$/, \"\"),\n port,\n target: `127.0.0.1:${port}`\n });\n });\n\n return entries;\n}\n\nexport function findLocalMdnsHosts(entries: DevHostEntry[]): string[] {\n return [...new Set(entries.map((entry) => entry.host).filter((host) => host.endsWith(\".local\")))];\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n getProjectName,\n readDevHosts,\n resolveDevHostsPath,\n sanitizeProjectName,\n type ConfigPattern,\n type ReadDevHostsOptions\n} from \"./config.js\";\nimport { findAvailablePort } from \"./port.js\";\nimport type { DevHostEntry } from \"./parse.js\";\nimport type { LocalghostServiceOptions } from \"./command.js\";\nimport { resolveGhostTunnelConfig, type GhostTunnelConfig, type GhostTunnelOptions } from \"./tunnel.js\";\n\nexport type LocalghostContextOptions = {\n cwd?: string;\n project?: string;\n localghostConfig?: string | false;\n fileName?: string;\n configFiles?: string[];\n configPattern?: ConfigPattern;\n port?: number;\n https?: boolean;\n bindHost?: string | boolean;\n primaryHost?: string;\n dynamicPort?: boolean;\n autoRepair?: boolean;\n command?: string[];\n services?: LocalghostServiceOptions[];\n wwwAlias?: boolean;\n ghostTunnel?: GhostTunnelOptions;\n};\n\nexport type LocalghostContext = {\n cwd: string;\n projectName: string;\n readOptions: ReadDevHostsOptions;\n configPath: string;\n configFileName: string;\n configEntries: DevHostEntry[];\n entries: DevHostEntry[];\n hosts: string[];\n requestedPort: number;\n port: number;\n dynamicPort: boolean;\n autoRepair: boolean;\n bindHost: string | boolean;\n primaryHost: string;\n https: boolean;\n wwwAlias: boolean;\n ghostTunnel: GhostTunnelConfig;\n projectConfigPath?: string;\n};\n\nexport type LocalghostProjectConfig = Omit<LocalghostContextOptions, \"cwd\" | \"localghostConfig\">;\n\nexport type LocalghostProjectConfigResult = {\n config: LocalghostProjectConfig;\n path?: string;\n};\n\nconst LOCALGHOST_PROJECT_CONFIG_FILES = [\n \"localghost.config.mjs\",\n \"localghost.config.js\",\n \"localghost.config.cjs\"\n];\n\nfunction parsePort(value: string | undefined) {\n if (!value) return undefined;\n const port = Number.parseInt(value, 10);\n return Number.isInteger(port) && port > 0 && port <= 65535 ? port : undefined;\n}\n\nfunction envPort() {\n return parsePort(process.env.LOCALGHOST_PORT) ?? parsePort(process.env.VITE_PORT);\n}\n\nfunction envDynamicPort() {\n const value = process.env.LOCALGHOST_DYNAMIC_PORT;\n if (!value) return undefined;\n return [\"1\", \"true\", \"yes\", \"on\"].includes(value.toLowerCase());\n}\n\nfunction envHttps() {\n const value = process.env.LOCALGHOST_HTTPS;\n if (!value) return undefined;\n return [\"1\", \"true\", \"yes\", \"on\"].includes(value.toLowerCase());\n}\n\nfunction getPackageName(cwd: string) {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, \"package.json\"), \"utf8\")) as { name?: unknown };\n return typeof pkg.name === \"string\" ? pkg.name : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction getPackageOwner(cwd: string) {\n const packageName = getPackageName(cwd);\n if (!packageName?.startsWith(\"@\")) return undefined;\n return packageName.slice(1).split(\"/\")[0];\n}\n\nfunction getLocalOwner(cwd: string) {\n return sanitizeProjectName(process.env.LOCALGHOST_OWNER ?? getPackageOwner(cwd) ?? process.env.USER ?? process.env.USERNAME ?? \"local\");\n}\n\nfunction getRouteName(primaryHost: string, fallback: string) {\n return sanitizeProjectName(primaryHost.split(\".\")[0] ?? fallback);\n}\n\nfunction readOptionsFromContext(options: LocalghostContextOptions): ReadDevHostsOptions {\n return {\n cwd: options.cwd ?? process.cwd(),\n ...(options.fileName ? { fileName: options.fileName } : {}),\n ...(options.configFiles ? { configFiles: options.configFiles } : {}),\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n}\n\nfunction withRuntimePort(entries: DevHostEntry[], requestedPort: number, port: number) {\n if (requestedPort === port) return entries;\n\n const hasRequestedPort = entries.some((entry) => entry.port === requestedPort);\n if (!hasRequestedPort) return entries;\n\n return entries.map((entry) => (\n entry.port === requestedPort\n ? { ...entry, port, target: `127.0.0.1:${port}` }\n : entry\n ));\n}\n\nfunction uniqueHosts(entries: DevHostEntry[]) {\n return [...new Set(entries.map((entry) => entry.host))];\n}\n\nfunction isAliasableHost(host: string) {\n return host.includes(\".\") && !host.startsWith(\"www.\") && !host.includes(\":\");\n}\n\nexport function getDefaultWwwAlias(host: string) {\n return isAliasableHost(host) ? `www.${host}` : null;\n}\n\nexport function addDefaultWwwAliases(entries: DevHostEntry[]) {\n const seen = new Set(entries.map((entry) => entry.host));\n const aliases: DevHostEntry[] = [];\n\n for (const entry of entries) {\n const alias = getDefaultWwwAlias(entry.host);\n if (alias && !seen.has(alias)) {\n aliases.push({ host: alias, port: entry.port, target: `127.0.0.1:${entry.port}` });\n seen.add(alias);\n }\n }\n\n return [...entries, ...aliases];\n}\n\nfunction defined<T extends Record<string, unknown>>(input: T) {\n return Object.fromEntries(Object.entries(input).filter(([, value]) => typeof value !== \"undefined\")) as Partial<T>;\n}\n\nexport async function readLocalghostProjectConfig(options: {\n cwd?: string;\n configFile?: string | false;\n} = {}): Promise<LocalghostProjectConfigResult> {\n const cwd = options.cwd ?? process.cwd();\n if (options.configFile === false) return { config: {} };\n\n const candidates = options.configFile ? [options.configFile] : LOCALGHOST_PROJECT_CONFIG_FILES;\n const path = candidates.map((candidate) => resolveDevHostsPath({ cwd, fileName: candidate }).path).find((candidate) => existsSync(candidate));\n if (!path) return { config: {} };\n\n const imported = await import(`${pathToFileURL(path).href}?localghost=${Date.now()}`);\n const config = (imported.default ?? imported) as LocalghostProjectConfig;\n\n return { config, path };\n}\n\nexport function defineLocalghostConfig<T extends LocalghostContextOptions>(config: T) {\n return config;\n}\n\nexport async function resolveLocalghostContext(options: LocalghostContextOptions = {}): Promise<LocalghostContext> {\n const cwd = options.cwd ?? process.cwd();\n const projectConfig = await readLocalghostProjectConfig({\n cwd,\n ...(typeof options.localghostConfig !== \"undefined\" ? { configFile: options.localghostConfig } : {})\n });\n const merged = {\n ...projectConfig.config,\n ...defined(options)\n } as LocalghostContextOptions;\n const readOptions = readOptionsFromContext({ ...merged, cwd });\n const resolvedPath = resolveDevHostsPath(readOptions);\n const configEntries = readDevHosts(readOptions);\n const requestedPort = merged.port ?? envPort() ?? configEntries[0]?.port ?? 5173;\n const dynamicPort = merged.dynamicPort ?? envDynamicPort() ?? true;\n const autoRepair = merged.autoRepair ?? true;\n const bindHost = merged.bindHost ?? \"127.0.0.1\";\n const probeHost = typeof bindHost === \"string\" ? bindHost : \"127.0.0.1\";\n const port = dynamicPort ? await findAvailablePort(requestedPort, { host: probeHost }) : requestedPort;\n const wwwAlias = merged.wwwAlias ?? true;\n const entries = wwwAlias\n ? addDefaultWwwAliases(withRuntimePort(configEntries, requestedPort, port))\n : withRuntimePort(configEntries, requestedPort, port);\n const hosts = uniqueHosts(entries);\n const primaryHost =\n merged.primaryHost ??\n entries.find((entry) => entry.port === port)?.host ??\n hosts[0] ??\n `${sanitizeProjectName(getProjectName(cwd))}.localhost`;\n const projectName = sanitizeProjectName(merged.project ?? getProjectName(cwd));\n const ghostTunnel = resolveGhostTunnelConfig(merged.ghostTunnel, {\n route: getRouteName(primaryHost, projectName),\n project: projectName,\n owner: getLocalOwner(cwd)\n });\n\n return {\n cwd,\n projectName,\n readOptions,\n configPath: resolvedPath.path,\n configFileName: resolvedPath.fileName,\n configEntries,\n entries,\n hosts,\n requestedPort,\n port,\n dynamicPort,\n autoRepair,\n bindHost,\n primaryHost,\n https: merged.https ?? envHttps() ?? false,\n wwwAlias,\n ghostTunnel,\n ...(projectConfig.path ? { projectConfigPath: projectConfig.path } : {})\n };\n}\n","import { createServer } from \"node:net\";\n\nexport type FindAvailablePortOptions = {\n host?: string;\n maxAttempts?: number;\n};\n\nexport async function isPortAvailable(port: number, host = \"127.0.0.1\") {\n return new Promise<boolean>((resolve) => {\n const server = createServer();\n\n server.once(\"error\", () => {\n resolve(false);\n });\n\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n\n server.listen(port, host);\n });\n}\n\nexport async function findAvailablePort(startPort: number, options: FindAvailablePortOptions = {}) {\n const host = options.host ?? \"127.0.0.1\";\n const maxAttempts = options.maxAttempts ?? 50;\n\n for (let offset = 0; offset < maxAttempts; offset += 1) {\n const port = startPort + offset;\n if (await isPortAvailable(port, host)) {\n return port;\n }\n }\n\n throw new Error(`No available port found from ${startPort} to ${startPort + maxAttempts - 1}.`);\n}\n","import { domainToASCII } from \"node:url\";\n\nexport type GhostTunnelNamespaceTag = \"route\" | \"project\" | \"owner\" | string;\n\nexport type GhostTunnelNamespaceOptions = readonly GhostTunnelNamespaceTag[] | {\n tags?: readonly GhostTunnelNamespaceTag[];\n separator?: string;\n spreadTag?: GhostTunnelNamespaceTag | false;\n};\n\nexport type GhostTunnelNamespaceConfig = {\n tags: GhostTunnelNamespaceTag[];\n separator: string;\n spreadTag?: GhostTunnelNamespaceTag;\n};\n\nexport type GhostTunnelNamespaceValues = Record<string, string> & {\n route?: string;\n project?: string;\n owner?: string;\n};\n\nexport type GhostTunnelPreviewOptions = {\n domain?: string;\n route: string;\n project: string;\n owner: string;\n values?: GhostTunnelNamespaceValues;\n path?: string;\n protocol?: \"http\" | \"https\";\n};\n\nexport type GhostTunnelMode = \"manual\" | \"public\";\n\nexport type GhostTunnelDomainOptions = string | readonly string[];\n\nexport type GhostTunnelAdapterProvider = \"vercel\";\nexport type GhostTunnelAdapterStrategy = \"same-project\" | \"separate-relay\";\nexport type GhostTunnelTransportKind = \"none\" | \"ip\" | \"tunnel\";\nexport type GhostTunnelAdapterTransport = GhostTunnelTransportKind;\nexport type GhostTunnelTunnelStoreProvider = \"vercel-redis\" | \"redis\";\nexport type GhostTunnelTunnelStoreEnv = \"auto\";\n\nexport type GhostTunnelTunnelStoreOptions = {\n provider?: GhostTunnelTunnelStoreProvider;\n env?: GhostTunnelTunnelStoreEnv;\n namespace?: string;\n};\n\nexport type GhostTunnelTransportOptions =\n | GhostTunnelTransportKind\n | {\n kind?: \"none\";\n }\n | {\n kind: \"ip\";\n allowPrivateNetworkAddress?: boolean;\n }\n | {\n kind: \"tunnel\";\n store?: GhostTunnelTunnelStoreOptions;\n waitMs?: number;\n pollIntervalMs?: number;\n routeTtlSeconds?: number;\n requestTtlSeconds?: number;\n maxRequestBodyBytes?: number;\n maxResponseBodyBytes?: number;\n };\n\nexport type GhostTunnelTransportConfig =\n | {\n kind: \"none\";\n }\n | {\n kind: \"ip\";\n allowPrivateNetworkAddress: boolean;\n }\n | {\n kind: \"tunnel\";\n store: Required<Pick<GhostTunnelTunnelStoreOptions, \"provider\" | \"env\" | \"namespace\">>;\n waitMs: number;\n pollIntervalMs: number;\n routeTtlSeconds: number;\n requestTtlSeconds: number;\n maxRequestBodyBytes: number;\n maxResponseBodyBytes: number;\n };\n\nexport type GhostTunnelAdapterOptions = GhostTunnelAdapterProvider | {\n provider: GhostTunnelAdapterProvider;\n strategy?: GhostTunnelAdapterStrategy;\n};\n\nexport type GhostTunnelOptions = false | GhostTunnelMode | {\n enabled?: boolean;\n mode?: GhostTunnelMode;\n domains?: GhostTunnelDomainOptions;\n subdomain?: string;\n namespace?: GhostTunnelNamespaceOptions;\n preview?: GhostTunnelPreviewOptions;\n requireHttps?: boolean;\n requireAuth?: boolean;\n adapter?: GhostTunnelAdapterOptions;\n transport?: GhostTunnelTransportOptions;\n};\n\nexport type GhostTunnelConfig = {\n enabled: boolean;\n mode: GhostTunnelMode;\n domains: string[];\n subdomain: string;\n namespace: GhostTunnelNamespaceConfig;\n preview?: GhostTunnelPreviewOptions;\n previewUrl?: string;\n displayUrl?: string;\n displayUrls: string[];\n requireHttps: boolean;\n requireAuth: boolean;\n transport: GhostTunnelTransportConfig;\n adapter?: {\n provider: GhostTunnelAdapterProvider;\n strategy: GhostTunnelAdapterStrategy;\n };\n};\n\nexport type GhostTunnelDisplayDefaults = {\n domain?: string;\n route?: string;\n project?: string;\n owner?: string;\n values?: GhostTunnelNamespaceValues;\n};\n\nexport type GhostTunnelRoute = {\n host: string;\n slug: string;\n namespace: GhostTunnelNamespaceValues;\n entryHost: string;\n wildcardHost: string;\n domain: string;\n};\n\nexport type ConstructGhostTunnelUrlInput = {\n domain: string;\n route: string;\n project: string;\n owner: string;\n values?: GhostTunnelNamespaceValues;\n path?: string;\n searchParams?: Record<string, string | number | boolean | null | undefined> | URLSearchParams;\n protocol?: \"http\" | \"https\";\n ghostTunnel?: GhostTunnelOptions | GhostTunnelConfig;\n};\n\nconst DEFAULT_GHOST_TUNNEL_SUBDOMAIN = \"ghost\";\nconst DEFAULT_GHOST_TUNNEL_NAMESPACE_TAGS = [\"route\", \"project\", \"owner\"] as const;\nconst DEFAULT_GHOST_TUNNEL_NAMESPACE_SEPARATOR = \"-\";\nconst DEFAULT_GHOST_TUNNEL_MODE: GhostTunnelMode = \"manual\";\nconst DEFAULT_GHOST_TUNNEL_ADAPTER_STRATEGY: GhostTunnelAdapterStrategy = \"same-project\";\nconst DEFAULT_GHOST_TUNNEL_TRANSPORT_KIND: GhostTunnelTransportKind = \"none\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_PROVIDER: GhostTunnelTunnelStoreProvider = \"vercel-redis\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_ENV: GhostTunnelTunnelStoreEnv = \"auto\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_NAMESPACE = \"localghost\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_WAIT_MS = 25_000;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_POLL_INTERVAL_MS = 250;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_ROUTE_TTL_SECONDS = 30;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_REQUEST_TTL_SECONDS = 60;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_REQUEST_BODY_BYTES = 1024 * 1024;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_RESPONSE_BODY_BYTES = 5 * 1024 * 1024;\n\ntype GhostTunnelLegacyAdapterOptions = {\n provider: GhostTunnelAdapterProvider;\n strategy?: GhostTunnelAdapterStrategy;\n transport?: GhostTunnelTransportOptions;\n};\n\nfunction isResolvedGhostTunnelConfig(value: GhostTunnelOptions | GhostTunnelConfig | undefined): value is GhostTunnelConfig {\n return typeof value === \"object\" && value !== null && \"enabled\" in value;\n}\n\nfunction toGhostTunnelConfig(options: GhostTunnelOptions | GhostTunnelConfig | undefined) {\n return isResolvedGhostTunnelConfig(options) ? options : resolveGhostTunnelConfig(options);\n}\n\nfunction stripHostPort(value: string) {\n const trimmed = value.trim().toLowerCase();\n if (trimmed.startsWith(\"[\") || trimmed.includes(\"/\")) return \"\";\n\n const portSeparator = trimmed.lastIndexOf(\":\");\n if (portSeparator === -1) return trimmed;\n\n const port = trimmed.slice(portSeparator + 1);\n return /^\\d+$/.test(port) ? trimmed.slice(0, portSeparator) : trimmed;\n}\n\nfunction normalizeDomain(value: string) {\n const host = stripHostPort(value.replace(/^\\*\\./, \"\"));\n const ascii = domainToASCII(host);\n if (!ascii || ascii.length > 253 || ascii.includes(\"..\")) return null;\n if (ascii.startsWith(\".\") || ascii.endsWith(\".\")) return null;\n if (ascii.includes(\"*\")) return null;\n if (!ascii.split(\".\").every(isValidHostLabel)) return null;\n return ascii;\n}\n\nfunction isValidHostLabel(value: string) {\n return value.length > 0 && value.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);\n}\n\nfunction isValidNamespaceTag(value: string) {\n return /^[a-z][a-z0-9_]*$/i.test(value);\n}\n\nfunction isNamespaceTagList(options: GhostTunnelNamespaceOptions | undefined): options is readonly GhostTunnelNamespaceTag[] {\n return Array.isArray(options);\n}\n\nfunction assertValidSubdomain(value: string) {\n if (!isValidHostLabel(value)) {\n throw new Error(`Invalid ghost tunnel subdomain: ${value}`);\n }\n}\n\nfunction normalizeDomains(domains: GhostTunnelDomainOptions | undefined) {\n const values = typeof domains === \"string\" ? [domains] : [...(domains ?? [])];\n const normalized = values.map((value) => value.trim()).filter(Boolean).map((value) => {\n const domain = normalizeDomain(value);\n if (!domain) throw new Error(`Invalid ghost tunnel domain: ${value}`);\n return domain;\n });\n\n return [...new Set(normalized)];\n}\n\nfunction parseGhostTunnelMode(value: GhostTunnelMode | undefined) {\n return value ?? DEFAULT_GHOST_TUNNEL_MODE;\n}\n\nfunction parseGhostTunnelAdapterStrategy(value: GhostTunnelAdapterStrategy | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_ADAPTER_STRATEGY;\n if (value === \"same-project\" || value === \"separate-relay\") return value;\n throw new Error(`Unsupported ghost tunnel adapter strategy: ${String(value)}`);\n}\n\nfunction parseGhostTunnelTransportKind(value: GhostTunnelTransportKind | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_TRANSPORT_KIND;\n if (value === \"none\" || value === \"ip\" || value === \"tunnel\") return value;\n throw new Error(`Unsupported ghost tunnel transport: ${String(value)}`);\n}\n\nfunction parsePositiveInteger(value: number | undefined, fallback: number, name: string) {\n if (typeof value === \"undefined\") return fallback;\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`Invalid ghost tunnel ${name}: ${value}`);\n }\n return value;\n}\n\nfunction parseTunnelStoreProvider(value: GhostTunnelTunnelStoreProvider | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_PROVIDER;\n if (value === \"vercel-redis\" || value === \"redis\") return value;\n throw new Error(`Unsupported ghost tunnel tunnel store provider: ${String(value)}`);\n}\n\nfunction parseTunnelStoreEnv(value: GhostTunnelTunnelStoreEnv | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_ENV;\n if (value === \"auto\") return value;\n throw new Error(`Unsupported ghost tunnel tunnel store env: ${String(value)}`);\n}\n\nfunction parseTunnelStoreNamespace(value: string | undefined) {\n const namespace = value ?? DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_NAMESPACE;\n if (!/^[a-z][a-z0-9:_-]{0,63}$/i.test(namespace)) {\n throw new Error(`Invalid ghost tunnel tunnel store namespace: ${namespace}`);\n }\n return namespace;\n}\n\nfunction resolveGhostTunnelAdapter(\n input: GhostTunnelAdapterOptions | GhostTunnelLegacyAdapterOptions | GhostTunnelConfig[\"adapter\"] | undefined\n): GhostTunnelConfig[\"adapter\"] {\n if (!input) return undefined;\n\n const provider = typeof input === \"string\" ? input : input.provider;\n if (provider !== \"vercel\") {\n throw new Error(`Unsupported ghost tunnel adapter provider: ${String(provider)}`);\n }\n\n return {\n provider,\n strategy: typeof input === \"string\" ? DEFAULT_GHOST_TUNNEL_ADAPTER_STRATEGY : parseGhostTunnelAdapterStrategy(input.strategy)\n };\n}\n\nfunction getLegacyGhostTunnelTransport(\n input: GhostTunnelAdapterOptions | GhostTunnelLegacyAdapterOptions | GhostTunnelConfig[\"adapter\"] | undefined\n) {\n if (!input || typeof input === \"string\" || !(\"transport\" in input)) return undefined;\n return input.transport;\n}\n\nfunction resolveGhostTunnelTransport(\n input: GhostTunnelTransportOptions | GhostTunnelTransportConfig | undefined\n): GhostTunnelTransportConfig {\n if (!input) {\n return { kind: \"none\" };\n }\n\n const kind = typeof input === \"string\"\n ? parseGhostTunnelTransportKind(input)\n : parseGhostTunnelTransportKind(input.kind);\n\n if (kind === \"ip\") {\n return {\n kind,\n allowPrivateNetworkAddress: typeof input === \"string\" ? false : input.kind === \"ip\" ? input.allowPrivateNetworkAddress ?? false : false\n };\n }\n\n if (kind === \"tunnel\") {\n const config: Extract<GhostTunnelTransportOptions, { kind: \"tunnel\" }> | Extract<GhostTunnelTransportConfig, { kind: \"tunnel\" }> | undefined =\n typeof input === \"string\" || input.kind !== \"tunnel\" ? undefined : input;\n const store = config?.store ?? {};\n return {\n kind,\n store: {\n provider: parseTunnelStoreProvider(store.provider),\n env: parseTunnelStoreEnv(store.env),\n namespace: parseTunnelStoreNamespace(store.namespace)\n },\n waitMs: parsePositiveInteger(config?.waitMs, DEFAULT_GHOST_TUNNEL_TUNNEL_WAIT_MS, \"tunnel waitMs\"),\n pollIntervalMs: parsePositiveInteger(config?.pollIntervalMs, DEFAULT_GHOST_TUNNEL_TUNNEL_POLL_INTERVAL_MS, \"tunnel pollIntervalMs\"),\n routeTtlSeconds: parsePositiveInteger(config?.routeTtlSeconds, DEFAULT_GHOST_TUNNEL_TUNNEL_ROUTE_TTL_SECONDS, \"tunnel routeTtlSeconds\"),\n requestTtlSeconds: parsePositiveInteger(config?.requestTtlSeconds, DEFAULT_GHOST_TUNNEL_TUNNEL_REQUEST_TTL_SECONDS, \"tunnel requestTtlSeconds\"),\n maxRequestBodyBytes: parsePositiveInteger(config?.maxRequestBodyBytes, DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_REQUEST_BODY_BYTES, \"tunnel maxRequestBodyBytes\"),\n maxResponseBodyBytes: parsePositiveInteger(config?.maxResponseBodyBytes, DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_RESPONSE_BODY_BYTES, \"tunnel maxResponseBodyBytes\")\n };\n }\n\n return { kind: \"none\" };\n}\n\nfunction resolveNamespaceConfig(options: GhostTunnelNamespaceOptions | undefined): GhostTunnelNamespaceConfig {\n const tags = isNamespaceTagList(options)\n ? [...options]\n : [...(options?.tags ?? DEFAULT_GHOST_TUNNEL_NAMESPACE_TAGS)];\n let separator = DEFAULT_GHOST_TUNNEL_NAMESPACE_SEPARATOR;\n let spreadTag: GhostTunnelNamespaceTag | false | undefined = tags.includes(\"project\") ? \"project\" : undefined;\n if (options && !isNamespaceTagList(options)) {\n separator = options.separator ?? DEFAULT_GHOST_TUNNEL_NAMESPACE_SEPARATOR;\n spreadTag = options.spreadTag === false ? false : options.spreadTag ?? spreadTag;\n }\n\n if (tags.length === 0) {\n throw new Error(\"Ghost tunnel namespace must include at least one tag.\");\n }\n\n for (const tag of tags) {\n if (!isValidNamespaceTag(tag)) {\n throw new Error(`Invalid ghost tunnel namespace tag: ${tag}`);\n }\n }\n\n if (spreadTag && !tags.includes(spreadTag)) {\n throw new Error(`Ghost tunnel namespace spreadTag must be listed in tags: ${spreadTag}`);\n }\n\n if (!separator || separator.length > 8 || !/^[a-z0-9-]+$/.test(separator)) {\n throw new Error(`Invalid ghost tunnel namespace separator: ${separator}`);\n }\n\n return {\n tags,\n separator,\n ...(spreadTag ? { spreadTag } : {})\n };\n}\n\nfunction normalizeNamespaceValue(tag: string, value: string, separator: string, options: { allowSeparator?: boolean } = {}) {\n const normalized = normalizeDomain(value);\n if (!normalized || normalized.includes(\".\")) {\n throw new Error(`Invalid ghost tunnel namespace value for ${tag}: ${value}`);\n }\n\n if (!options.allowSeparator && normalized.includes(separator)) {\n throw new Error(`Ghost tunnel namespace value for ${tag} cannot include separator \"${separator}\": ${value}`);\n }\n\n return normalized;\n}\n\nfunction createNamespaceSlug(config: GhostTunnelNamespaceConfig, values: GhostTunnelNamespaceValues) {\n const parts = config.tags.map((tag) => {\n const value = values[tag];\n if (!value) {\n throw new Error(`Missing ghost tunnel namespace value: ${tag}`);\n }\n\n return normalizeNamespaceValue(tag, value, config.separator, { allowSeparator: tag === config.spreadTag });\n });\n\n const slug = parts.join(config.separator);\n if (!isValidHostLabel(slug)) {\n throw new Error(`Ghost tunnel namespace is too long for a DNS label: ${slug}`);\n }\n\n return slug;\n}\n\nfunction createNamespaceDisplaySlug(config: GhostTunnelNamespaceConfig, values: GhostTunnelNamespaceValues = {}) {\n return config.tags.map((tag) => {\n const value = values[tag];\n if (!value) return `<${tag}>`;\n\n try {\n return normalizeNamespaceValue(tag, value, config.separator, { allowSeparator: tag === config.spreadTag });\n } catch {\n return `<${tag}>`;\n }\n }).join(config.separator);\n}\n\nfunction getPreviewDefaults(preview: GhostTunnelPreviewOptions | undefined, defaults: GhostTunnelDisplayDefaults | undefined) {\n return {\n domain: preview?.domain ?? defaults?.domain,\n route: preview?.route ?? defaults?.route,\n project: preview?.project ?? defaults?.project,\n owner: preview?.owner ?? defaults?.owner,\n values: {\n ...(defaults?.values ?? {}),\n ...(preview?.values ?? {})\n },\n path: preview?.path,\n protocol: preview?.protocol\n };\n}\n\nfunction getDisplayValues(input: ReturnType<typeof getPreviewDefaults>): GhostTunnelNamespaceValues {\n return {\n ...(input.route ? { route: input.route } : {}),\n ...(input.project ? { project: input.project } : {}),\n ...(input.owner ? { owner: input.owner } : {}),\n ...input.values\n };\n}\n\nfunction getDisplayDefaults(defaults?: GhostTunnelDisplayDefaults) {\n return defaults;\n}\n\nfunction createDisplayUrl(config: GhostTunnelConfig, defaults?: GhostTunnelDisplayDefaults, domain?: string) {\n const input = getPreviewDefaults(config.preview, getDisplayDefaults(defaults));\n const protocol = input.protocol ?? \"https\";\n const slug = createNamespaceDisplaySlug(config.namespace, getDisplayValues(input));\n const entryHost = domain\n ? getGhostTunnelEntryHost(domain, config)\n : input.domain\n ? getGhostTunnelEntryHost(input.domain, config)\n : `${config.subdomain}.*`;\n const url = `${protocol}://${slug}.${entryHost}/`;\n\n if (!input.path) return url;\n return `${url}${input.path.replace(/^\\/+/, \"\")}`;\n}\n\nfunction createDisplayUrls(config: GhostTunnelConfig, defaults?: GhostTunnelDisplayDefaults) {\n const displayDefaults = getDisplayDefaults(defaults);\n const domains = config.domains.length > 0\n ? config.domains\n : displayDefaults?.domain\n ? [displayDefaults.domain]\n : [];\n const urls = domains.length > 0\n ? domains.map((domain) => createDisplayUrl(config, displayDefaults, domain))\n : [createDisplayUrl(config, displayDefaults)];\n\n return [...new Set(urls)];\n}\n\nfunction maybeConstructPreviewUrl(config: GhostTunnelConfig, defaults?: GhostTunnelDisplayDefaults) {\n if (!config.preview) return undefined;\n\n const input = getPreviewDefaults(config.preview, defaults);\n if (!input.domain || !input.route || !input.project || !input.owner) return undefined;\n\n return constructGhostTunnelUrl({\n domain: input.domain,\n route: input.route,\n project: input.project,\n owner: input.owner,\n values: input.values,\n ...(input.path ? { path: input.path } : {}),\n ...(input.protocol ? { protocol: input.protocol } : {}),\n ghostTunnel: config\n });\n}\n\nfunction parseNamespaceSlug(slug: string, config: GhostTunnelNamespaceConfig): GhostTunnelNamespaceValues | null {\n const parts = slug.split(config.separator);\n if (parts.length < config.tags.length) return null;\n if (parts.length !== config.tags.length && !config.spreadTag) return null;\n\n const namespace: GhostTunnelNamespaceValues = {};\n const spreadIndex = config.spreadTag ? config.tags.indexOf(config.spreadTag) : -1;\n const spreadWidth = spreadIndex >= 0 ? parts.length - config.tags.length + 1 : 1;\n\n let partIndex = 0;\n for (const [tagIndex, tag] of config.tags.entries()) {\n const value = tagIndex === spreadIndex\n ? parts.slice(partIndex, partIndex + spreadWidth).join(config.separator)\n : parts[partIndex];\n if (!value || !isValidHostLabel(value)) return null;\n if (tagIndex !== spreadIndex && value.includes(config.separator)) return null;\n namespace[tag] = value;\n partIndex += tagIndex === spreadIndex ? spreadWidth : 1;\n }\n\n return namespace;\n}\n\nexport function resolveGhostTunnelConfig(options: GhostTunnelOptions | undefined, defaults?: GhostTunnelDisplayDefaults): GhostTunnelConfig {\n if (options === false || typeof options === \"undefined\") {\n return {\n enabled: false,\n mode: DEFAULT_GHOST_TUNNEL_MODE,\n domains: [],\n subdomain: DEFAULT_GHOST_TUNNEL_SUBDOMAIN,\n namespace: resolveNamespaceConfig(undefined),\n displayUrls: [],\n requireHttps: true,\n requireAuth: true,\n transport: resolveGhostTunnelTransport(undefined)\n };\n }\n\n const config = typeof options === \"string\"\n ? { mode: options }\n : options;\n const subdomain = config.subdomain ?? DEFAULT_GHOST_TUNNEL_SUBDOMAIN;\n assertValidSubdomain(subdomain);\n const domains = normalizeDomains(config.domains);\n const enabled = config.enabled ?? true;\n const adapter = resolveGhostTunnelAdapter(config.adapter);\n const transport = resolveGhostTunnelTransport(config.transport ?? getLegacyGhostTunnelTransport(config.adapter));\n\n const resolved: GhostTunnelConfig = {\n enabled,\n mode: parseGhostTunnelMode(config.mode),\n domains,\n subdomain,\n namespace: resolveNamespaceConfig(config.namespace),\n ...(config.preview ? { preview: config.preview } : {}),\n displayUrls: [],\n requireHttps: config.requireHttps ?? true,\n requireAuth: config.requireAuth ?? true,\n transport,\n ...(adapter ? { adapter } : {})\n };\n\n if (!enabled) {\n return resolved;\n }\n\n const previewUrl = maybeConstructPreviewUrl(resolved, defaults);\n const displayUrls = previewUrl ? [previewUrl] : createDisplayUrls(resolved, defaults);\n\n return {\n ...resolved,\n displayUrls,\n ...(displayUrls[0] ? { displayUrl: displayUrls[0] } : {}),\n ...(previewUrl ? { previewUrl } : {})\n };\n}\n\nexport function getGhostTunnelEntryHost(domain: string, options: GhostTunnelOptions | GhostTunnelConfig = {}) {\n const config = toGhostTunnelConfig(options);\n const normalizedDomain = normalizeDomain(domain);\n if (!normalizedDomain) {\n throw new Error(`Invalid ghost tunnel domain: ${domain}`);\n }\n\n return `${config.subdomain}.${normalizedDomain}`;\n}\n\nexport function getGhostTunnelWildcardHost(domain: string, options: GhostTunnelOptions | GhostTunnelConfig = {}) {\n return `*.${getGhostTunnelEntryHost(domain, options)}`;\n}\n\nexport function constructGhostTunnelHost(input: Omit<ConstructGhostTunnelUrlInput, \"path\" | \"searchParams\" | \"protocol\">) {\n const config = toGhostTunnelConfig(input.ghostTunnel ?? {});\n if (!config.enabled) {\n throw new Error(\"Ghost tunnel is not enabled.\");\n }\n\n const namespaceValues: GhostTunnelNamespaceValues = {\n route: input.route,\n project: input.project,\n owner: input.owner,\n ...(input.values ?? {})\n };\n const slug = createNamespaceSlug(config.namespace, namespaceValues);\n\n return `${slug}.${getGhostTunnelEntryHost(input.domain, config)}`;\n}\n\nexport function constructGhostTunnelUrl(input: ConstructGhostTunnelUrlInput) {\n const protocol = input.protocol ?? \"https\";\n const host = constructGhostTunnelHost(input);\n const url = new URL(`${protocol}://${host}/`);\n\n if (input.path) {\n url.pathname = `/${input.path.replace(/^\\/+/, \"\")}`;\n }\n\n if (input.searchParams instanceof URLSearchParams) {\n url.search = input.searchParams.toString();\n } else if (input.searchParams) {\n for (const [key, value] of Object.entries(input.searchParams)) {\n if (typeof value !== \"undefined\" && value !== null) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return url.toString();\n}\n\nexport const constructGhostTunnelURL = constructGhostTunnelUrl;\n\nexport function getGhostTunnelDefaultDisplayUrl(options: GhostTunnelOptions | GhostTunnelConfig = {}, defaults?: GhostTunnelDisplayDefaults) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n return createDisplayUrl(config, defaults);\n}\n\nexport function getGhostTunnelDisplayUrl(options: GhostTunnelOptions | GhostTunnelConfig | undefined, defaults?: GhostTunnelDisplayDefaults) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n return config.displayUrl ?? config.previewUrl ?? getGhostTunnelDefaultDisplayUrl(config, defaults);\n}\n\nexport function getGhostTunnelDisplayUrls(options: GhostTunnelOptions | GhostTunnelConfig | undefined, defaults?: GhostTunnelDisplayDefaults) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return [];\n if (config.displayUrls.length > 0) return config.displayUrls;\n const displayUrl = getGhostTunnelDisplayUrl(config, defaults);\n return displayUrl ? [displayUrl] : [];\n}\n\nexport function getGhostTunnelPreviewUrl(options: GhostTunnelOptions | GhostTunnelConfig | undefined) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n return config.previewUrl ?? maybeConstructPreviewUrl(config) ?? null;\n}\n\nexport function parseGhostTunnelHost(host: string, domain: string, options: GhostTunnelOptions | GhostTunnelConfig = {}): GhostTunnelRoute | null {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n\n const normalizedHost = normalizeDomain(host);\n const normalizedDomain = normalizeDomain(domain);\n if (!normalizedHost || !normalizedDomain) return null;\n\n const entryHost = getGhostTunnelEntryHost(normalizedDomain, config);\n const suffix = `.${entryHost}`;\n if (!normalizedHost.endsWith(suffix)) return null;\n\n const slug = normalizedHost.slice(0, -suffix.length);\n if (!isValidHostLabel(slug)) return null;\n const namespace = parseNamespaceSlug(slug, config.namespace);\n if (!namespace) return null;\n\n return {\n host: normalizedHost,\n slug,\n namespace,\n entryHost,\n wildcardHost: `*.${entryHost}`,\n domain: normalizedDomain\n };\n}\n\nexport function assertSecureGhostTunnelRequest(input: {\n host: string;\n domain: string;\n protocol: \"http\" | \"https\";\n ghostTunnel: GhostTunnelOptions | GhostTunnelConfig | undefined;\n authenticated?: boolean;\n}) {\n const config = toGhostTunnelConfig(input.ghostTunnel);\n\n if (!config.enabled) {\n throw new Error(\"Ghost tunnel is not enabled.\");\n }\n\n if (config.requireHttps && input.protocol !== \"https\") {\n throw new Error(\"Ghost tunnel requests must use HTTPS.\");\n }\n\n if (config.requireAuth && input.authenticated !== true) {\n throw new Error(\"Ghost tunnel requests must be authenticated.\");\n }\n\n const route = parseGhostTunnelHost(input.host, input.domain, config);\n if (!route) {\n throw new Error(`Host is not a valid ghost tunnel host for ${input.domain}.`);\n }\n\n return route;\n}\n","import { execa } from \"execa\";\n\nexport type DoctorResult = {\n ok: boolean;\n caddy: {\n found: boolean;\n version?: string;\n installHint: string;\n };\n};\n\nexport async function checkCaddy(): Promise<DoctorResult[\"caddy\"]> {\n try {\n const result = await execa(\"caddy\", [\"version\"], { reject: false });\n const version = [result.stdout, result.stderr].filter(Boolean).join(\"\\n\").trim();\n\n return {\n found: result.exitCode === 0,\n ...(version ? { version } : {}),\n installHint: \"brew install caddy\"\n };\n } catch {\n return {\n found: false,\n installHint: \"brew install caddy\"\n };\n }\n}\n\nexport async function runDoctor(): Promise<DoctorResult> {\n const caddy = await checkCaddy();\n return {\n ok: caddy.found,\n caddy\n };\n}\n","export type LocalghostEnvironment = NodeJS.ProcessEnv;\n\nconst PRODUCTION_ENV_KEYS = [\"NODE_ENV\", \"VERCEL_ENV\", \"NETLIFY\", \"CF_PAGES_BRANCH\", \"LOCALGHOST_ENV\"] as const;\n\nexport function getProductionReason(env: LocalghostEnvironment = process.env) {\n if (env.LOCALGHOST_ENV === \"production\") return \"LOCALGHOST_ENV=production\";\n if (env.NODE_ENV === \"production\") return \"NODE_ENV=production\";\n if (env.VERCEL_ENV === \"production\") return \"VERCEL_ENV=production\";\n if (env.NETLIFY === \"true\" && env.CONTEXT === \"production\") return \"NETLIFY=true and CONTEXT=production\";\n if (env.CF_PAGES_BRANCH && env.CF_PAGES_BRANCH === env.CF_PAGES_PRODUCTION_BRANCH) {\n return \"CF_PAGES_BRANCH matches CF_PAGES_PRODUCTION_BRANCH\";\n }\n\n return null;\n}\n\nexport function isProductionLike(env: LocalghostEnvironment = process.env) {\n return getProductionReason(env) !== null;\n}\n\nexport function assertLocalDevelopment(command: string, env: LocalghostEnvironment = process.env) {\n const reason = getProductionReason(env);\n if (!reason) return;\n\n throw new Error(`Localghost only runs in local development. Refusing \\`${command}\\` because ${reason}.`);\n}\n\nexport function getProductionEnvKeys() {\n return PRODUCTION_ENV_KEYS;\n}\n","import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport function readTextFile(path: string) {\n return readFileSync(path, \"utf8\");\n}\n\nexport function writeTextFile(path: string, value: string) {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, value, \"utf8\");\n return path;\n}\n","import { writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { execa } from \"execa\";\nimport { sanitizeProjectName } from \"./config.js\";\nimport { readTextFile } from \"./fs.js\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport type UpdateSystemHostsResult = {\n changed: boolean;\n hostsPath: string;\n tempPath?: string;\n};\n\nexport type RemoveSystemHostsResult = UpdateSystemHostsResult & {\n removed: boolean;\n};\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction getManagedBlockPattern(projectName: string) {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const start = `# localghost:start ${sanitizedProjectName}`;\n const end = `# localghost:end ${sanitizedProjectName}`;\n return new RegExp(`${escapeRegExp(start)}[\\\\s\\\\S]*?${escapeRegExp(end)}\\\\n?`, \"m\");\n}\n\nexport function getSystemHostsPath(env: NodeJS.ProcessEnv = process.env) {\n if (env.LOCALGHOST_HOSTS_PATH) return env.LOCALGHOST_HOSTS_PATH;\n return process.platform === \"win32\" ? \"C:\\\\Windows\\\\System32\\\\drivers\\\\etc\\\\hosts\" : \"/etc/hosts\";\n}\n\nexport function renderHostsBlock(projectName: string, entries: DevHostEntry[]) {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const hosts = [...new Set(entries.map((entry) => entry.host))].sort();\n\n return [\n `# localghost:start ${sanitizedProjectName}`,\n ...hosts.map((host) => `127.0.0.1 ${host}`),\n `# localghost:end ${sanitizedProjectName}`,\n \"\"\n ].join(\"\\n\");\n}\n\nexport function upsertManagedBlock(existing: string, projectName: string, block: string) {\n const pattern = getManagedBlockPattern(projectName);\n\n if (pattern.test(existing)) {\n return existing.replace(pattern, block);\n }\n\n return `${existing.trimEnd()}\\n\\n${block}`;\n}\n\nexport function removeManagedBlock(existing: string, projectName: string) {\n const pattern = getManagedBlockPattern(projectName);\n\n if (!pattern.test(existing)) {\n return existing;\n }\n\n return existing.replace(pattern, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trimEnd() + \"\\n\";\n}\n\nasync function writeSystemHostsFile(hostsPath: string, next: string, projectName: string) {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const tempPath = join(tmpdir(), `localghost-${sanitizedProjectName}-hosts`);\n writeFileSync(tempPath, next, \"utf8\");\n\n if (process.env.LOCALGHOST_HOSTS_PATH) {\n writeFileSync(hostsPath, next, \"utf8\");\n return tempPath;\n }\n\n if (process.platform === \"win32\") {\n throw new Error(`Windows support: run as administrator and copy ${tempPath} to ${hostsPath}.`);\n }\n\n await execa(\"sudo\", [\"cp\", tempPath, hostsPath], { stdio: \"inherit\" });\n\n return tempPath;\n}\n\nexport async function updateSystemHosts(projectName: string, entries: DevHostEntry[]): Promise<UpdateSystemHostsResult> {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const hostsPath = getSystemHostsPath();\n const existing = readTextFile(hostsPath);\n const block = renderHostsBlock(sanitizedProjectName, entries);\n const next = upsertManagedBlock(existing, sanitizedProjectName, block);\n\n if (next === existing) {\n return { changed: false, hostsPath };\n }\n\n const tempPath = await writeSystemHostsFile(hostsPath, next, sanitizedProjectName);\n\n return { changed: true, hostsPath, tempPath };\n}\n\nexport async function removeSystemHosts(projectName: string): Promise<RemoveSystemHostsResult> {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const hostsPath = getSystemHostsPath();\n const existing = readTextFile(hostsPath);\n const next = removeManagedBlock(existing, sanitizedProjectName);\n\n if (next === existing) {\n return { changed: false, removed: false, hostsPath };\n }\n\n const tempPath = await writeSystemHostsFile(hostsPath, next, sanitizedProjectName);\n\n return { changed: true, removed: true, hostsPath, tempPath };\n}\n","import { stdin as input, stdout as output } from \"node:process\";\nimport { createInterface } from \"node:readline/promises\";\n\nexport function canPrompt() {\n return Boolean(input.isTTY && output.isTTY);\n}\n\nexport async function withPrompt<T>(run: (prompt: (question: string) => Promise<string>) => Promise<T>) {\n const rl = createInterface({ input, output });\n try {\n return await run((question) => rl.question(question));\n } finally {\n rl.close();\n }\n}\n\nexport async function confirm(question: string, defaultValue = true) {\n return withPrompt(async (prompt) => {\n const suffix = defaultValue ? \" [Y/n] \" : \" [y/N] \";\n const answer = (await prompt(`${question}${suffix}`)).trim().toLowerCase();\n if (!answer) return defaultValue;\n return answer === \"y\" || answer === \"yes\";\n });\n}\n\nexport async function ask(question: string, defaultValue?: string) {\n return withPrompt(async (prompt) => {\n const suffix = defaultValue ? ` (${defaultValue}) ` : \" \";\n const answer = (await prompt(`${question}${suffix}`)).trim();\n return answer || defaultValue || \"\";\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readTextFile, writeTextFile } from \"./fs.js\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport const LOCALGHOST_STATE_FILE = \"ops/local/localghost-state.json\";\n\nexport type LocalghostStateAction = \"setup\" | \"teardown\";\n\nexport type LocalghostState = {\n version: 1;\n action: LocalghostStateAction;\n updatedAt: string;\n projectName: string;\n cwd: string;\n configPath?: string;\n hostsPath?: string;\n hostsChanged?: boolean;\n hostsTempPath?: string;\n caddyfilePath?: string;\n caddyfileRemoved?: boolean;\n caddyHttps?: boolean;\n caddyTrustedAt?: string;\n caddyTrustPromptedAt?: string;\n entries?: DevHostEntry[];\n};\n\nexport type WriteLocalghostStateInput = Omit<LocalghostState, \"version\" | \"updatedAt\">;\n\nexport function getLocalghostStatePath(cwd = process.cwd()) {\n return join(cwd, LOCALGHOST_STATE_FILE);\n}\n\nexport function readLocalghostState(cwd = process.cwd()): LocalghostState | null {\n const path = getLocalghostStatePath(cwd);\n if (!existsSync(path)) return null;\n return JSON.parse(readTextFile(path)) as LocalghostState;\n}\n\nexport function writeLocalghostState(cwd: string, state: WriteLocalghostStateInput) {\n const path = getLocalghostStatePath(cwd);\n writeTextFile(path, `${JSON.stringify({ ...state, version: 1, updatedAt: new Date().toISOString() }, null, 2)}\\n`);\n return path;\n}\n\nexport function patchLocalghostState(cwd: string, patch: Partial<WriteLocalghostStateInput>) {\n const current = readLocalghostState(cwd);\n if (!current) return null;\n return writeLocalghostState(cwd, { ...(current as unknown as WriteLocalghostStateInput), ...patch });\n}\n","import { dirname, join } from \"node:path\";\nimport { execa } from \"execa\";\nimport { writeTextFile } from \"./fs.js\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport type CaddyModeOptions = {\n https?: boolean;\n};\n\nfunction shouldShowCaddyLogs() {\n return [\"1\", \"true\", \"yes\", \"on\"].includes((process.env.LOCALGHOST_CADDY_VERBOSE ?? \"\").toLowerCase());\n}\n\nfunction caddyStdio() {\n return shouldShowCaddyLogs() ? \"inherit\" as const : \"pipe\" as const;\n}\n\nfunction groupByPort(entries: DevHostEntry[]) {\n const groups = new Map<number, DevHostEntry[]>();\n\n for (const entry of entries) {\n const group = groups.get(entry.port) ?? [];\n group.push(entry);\n groups.set(entry.port, group);\n }\n\n return groups;\n}\n\nexport function getCaddyfilePath(cwd = process.cwd()) {\n return join(cwd, \"ops/local/Caddyfile\");\n}\n\nexport function renderCaddyfile(entries: DevHostEntry[], options: CaddyModeOptions = {}) {\n const groups = groupByPort(entries);\n const https = options.https === true;\n const blocks = [...groups.entries()]\n .sort(([leftPort], [rightPort]) => leftPort - rightPort)\n .map(([port, group]) => {\n const hosts = group\n .map((entry) => (https ? entry.host : `http://${entry.host}`))\n .sort()\n .join(\", \");\n\n return `${hosts} {\n\\treverse_proxy 127.0.0.1:${port}\n}`;\n });\n\n const globalOptions = https\n ? `{\n local_certs\n}\n\n`\n : \"\";\n\n return `${globalOptions}${blocks.join(\"\\n\\n\")}\n`;\n}\n\nexport async function writeCaddyfile(entries: DevHostEntry[], cwd = process.cwd(), options: CaddyModeOptions = {}) {\n const path = getCaddyfilePath(cwd);\n writeTextFile(path, renderCaddyfile(entries, options));\n return path;\n}\n\nexport async function validateCaddyfile(path: string) {\n await execa(\"caddy\", [\"validate\", \"--config\", path], {\n cwd: dirname(path),\n stdio: caddyStdio()\n });\n}\n\nexport async function runCaddy(path: string) {\n await execa(\"caddy\", [\"run\", \"--config\", path], {\n cwd: dirname(path),\n stdio: caddyStdio()\n });\n}\n\nexport function startCaddy(path: string) {\n return execa(\"caddy\", [\"run\", \"--config\", path], {\n cwd: dirname(path),\n stdio: caddyStdio()\n });\n}\n\nexport async function trustCaddy(path: string) {\n await execa(\"caddy\", [\"trust\", \"--config\", path], {\n cwd: dirname(path),\n stdio: \"inherit\"\n });\n}\n","import type { DevHostEntry } from \"./parse.js\";\nimport type { GhostTunnelConfig } from \"./tunnel.js\";\n\nexport type DomainRoute = {\n host: string;\n port: number;\n url: string;\n upstream: string;\n};\n\nexport type DomainRouteOptions = {\n https?: boolean;\n};\n\nexport type GhostTunnelFormatOptions = {\n color?: boolean;\n label?: \"configured\" | \"expected\" | \"ready\" | \"running\";\n verbose?: boolean;\n};\n\nconst ansi = {\n cyan: \"\\u001b[36m\",\n dim: \"\\u001b[2m\",\n green: \"\\u001b[32m\",\n reset: \"\\u001b[0m\",\n yellow: \"\\u001b[33m\"\n};\n\nfunction colorize(value: string, color: string, enabled: boolean) {\n return enabled ? `${color}${value}${ansi.reset}` : value;\n}\n\nfunction colorizeUrl(value: string, enabled: boolean) {\n if (!enabled) return value;\n return colorize(value.replace(/\\*/g, `${ansi.yellow}*${ansi.cyan}`), ansi.cyan, enabled);\n}\n\nexport function getDomainRoutes(entries: DevHostEntry[], options: DomainRouteOptions = {}): DomainRoute[] {\n const protocol = options.https === true ? \"https\" : \"http\";\n\n return [...entries]\n .sort((left, right) => left.host.localeCompare(right.host) || left.port - right.port)\n .map((entry) => ({\n host: entry.host,\n port: entry.port,\n url: `${protocol}://${entry.host}/`,\n upstream: `http://${entry.target}`\n }));\n}\n\nexport function formatDomainRoutes(entries: DevHostEntry[], options: DomainRouteOptions = {}) {\n const routes = getDomainRoutes(entries, options);\n\n if (routes.length === 0) {\n return \"localghost routes\\n no routes\";\n }\n\n return [\n \"localghost routes\",\n ...routes.map((route) => ` ${route.url} -> ${route.upstream}`)\n ].join(\"\\n\");\n}\n\nexport function formatGhostTunnel(config: GhostTunnelConfig, options: GhostTunnelFormatOptions = {}) {\n if (!config.enabled) return null;\n\n const color = options.color === true;\n const label = options.label ?? \"expected\";\n const labelColor = label === \"running\" ? ansi.green : ansi.dim;\n const lines = [\n \"localghost ghost tunnel\",\n ` mode: ${config.mode}`\n ];\n const urls = config.displayUrls.length > 0\n ? config.displayUrls\n : config.displayUrl\n ? [config.displayUrl]\n : [];\n\n if (urls.length === 0) {\n lines.push(` ${label}: unavailable`);\n } else if (urls.length === 1) {\n lines.push(` ${colorize(label, labelColor, color)}: ${colorizeUrl(urls[0]!, color)}`);\n } else {\n lines.push(` ${colorize(label, labelColor, color)}:`);\n for (const url of urls) {\n lines.push(` ${colorizeUrl(url, color)}`);\n }\n }\n\n if (options.verbose) {\n lines.push(` domains: ${config.domains.length > 0 ? config.domains.join(\", \") : \"*\"}`);\n lines.push(` access: ${config.requireAuth ? \"auth required\" : \"app decides\"}`);\n lines.push(` protocol: ${config.requireHttps ? \"https required\" : \"http allowed\"}`);\n lines.push(` transport: ${config.transport.kind}`);\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAAA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,WAAW,WAAAC,gBAAe;AACnC,SAAS,aAAa;AACtB,SAAS,0BAA0B;;;ACHnC,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAGvB,IAAM,8BAA8B;AAmDpC,SAAS,0BAA0B,MAAyB,QAAQ,KAAK;AAC9E,MAAI,IAAI,yBAA0B,QAAO,IAAI;AAE7C,QAAM,YAAY,IAAI,kBAAkB,KAAK,QAAQ,GAAG,cAAc;AACtE,SAAO,KAAK,WAAW,cAAc,eAAe;AACtD;AAEO,SAAS,iBAAiB,KAAa;AAC5C,MAAI,CAAC,OAAO,UAAU,GAAG,KAAK,MAAM,EAAG,QAAO;AAE9C,MAAI;AACF,YAAQ,KAAK,KAAK,CAAC;AACnB,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO;AAC3F,WAAO,SAAS;AAAA,EAClB;AACF;AAEA,SAAS,gBAAoC;AAC3C,SAAO,EAAE,SAAS,6BAA6B,MAAM,CAAC,GAAG,QAAQ,CAAC,EAAE;AACtE;AAEO,SAAS,uBAAuB,OAAO,0BAA0B,GAAuB;AAC7F,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,cAAc;AAE5C,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AACpD,WAAO;AAAA,MACL,SAAS;AAAA,MACT,MAAM,MAAM,QAAQ,OAAO,IAAI,IAAI,OAAO,OAAO,CAAC;AAAA,MAClD,QAAQ,MAAM,QAAQ,OAAO,MAAM,IAAI,OAAO,S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A,UAC7B,YAAY,gBAAgB;AAAA,UAC5B,cAAc,CAAC,MAAM;AAAA,UACrB,OAAO,gBAAgB;AAAA,UACvB,eAAe,gBAAgB;AAAA,UAC/B,MAAM,gBAAgB;AAAA,UACtB,aAAa,gBAAgB;AAAA,UAC7B,SAAS,gBAAgB;AAAA,QAC3B,CAAC;AACD,wBAAgB,IAAI;AAAA,MACtB;AAEA,YAAM,mBAAmB,uBAAuB,QAAQ,eAAe;AAEvE,YAAM,kBAAkB,MAAM;AAC5B,YAAI,CAAC,cAAe;AACpB,gCAAwB,aAAa;AACrC,wBAAgB;AAAA,MAClB;AAEA,YAAM,UAAU,MAAM;AACpB,wBAAgB;AAChB,2BAAmB;AAAA,MACrB;AAEA,aAAO,YAAY,KAAK,SAAS,OAAO;AACxC,cAAQ,KAAK,QAAQ,OAAO;AAAA,IAC9B;AAAA,EACF;AACF;AAEO,IAAM,mBAAmB;","names":["existsSync","readFileSync","resolve","input","input","existsSync","readFileSync","join","input","fileName","existsSync","readFileSync","join","existsSync","readFileSync","join","resolve","input","input","readFileSync","join","input","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","writeFileSync","join","execa","join","writeFileSync","execa","existsSync","join","join","existsSync","dirname","join","execa","join","execa","dirname","resolve","getPackageOwner","readFileSync","getLocalOwner","getRouteName","existsSync"]}
1
+ {"version":3,"sources":["../src/vite.ts","../src/activity.ts","../src/config.ts","../src/parse.ts","../src/context.ts","../src/port.ts","../src/registry.ts","../src/tunnel.ts","../src/doctor.ts","../src/env.ts","../src/fs.ts","../src/hosts-file.ts","../src/prompt.ts","../src/state.ts","../src/caddy.ts","../src/routes.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { normalize, resolve } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { emitKeypressEvents } from \"node:readline\";\nimport type { ConfigEnv, HmrOptions, Plugin, UserConfig, ViteDevServer, WsOptions } from \"vite\";\nimport { registerLocalghostRun, registerLocalghostSetup, unregisterLocalghostRun } from \"./activity.js\";\nimport {\n getConfigFileCandidates,\n getProjectName,\n readDevHosts,\n resolveDevHostsPath,\n sanitizeProjectName,\n type ConfigPattern,\n type ReadDevHostsOptions\n} from \"./config.js\";\nimport { addDefaultWwwAliases, readLocalghostProjectConfig, resolveLocalghostContext, type LocalghostContext } from \"./context.js\";\nimport { checkCaddy } from \"./doctor.js\";\nimport { isProductionLike } from \"./env.js\";\nimport { writeTextFile } from \"./fs.js\";\nimport { getSystemHostsPath, renderHostsBlock, updateSystemHosts } from \"./hosts-file.js\";\nimport { ask, canPrompt, confirm } from \"./prompt.js\";\nimport { getLocalghostStatePath, readLocalghostState, writeLocalghostState } from \"./state.js\";\nimport { getCaddyfilePath, renderCaddyfile, validateCaddyfile, writeCaddyfile } from \"./caddy.js\";\nimport type { DevHostEntry } from \"./parse.js\";\nimport { resolveGhostTunnelConfig, type GhostTunnelOptions } from \"./tunnel.js\";\nimport { formatGhostTunnel } from \"./routes.js\";\n\nexport type LocalGhostPluginOptions = {\n cwd?: string;\n fileName?: string;\n configFiles?: string[];\n configPattern?: ConfigPattern;\n port?: number;\n https?: boolean;\n bindHost?: string | boolean;\n dynamicPort?: boolean;\n autoRepair?: boolean;\n primaryHost?: string;\n log?: boolean;\n setup?: boolean | \"prompt\";\n localghostConfig?: string | false;\n wwwAlias?: boolean;\n ghostTunnel?: GhostTunnelOptions;\n registryOwnerToken?: string;\n verbose?: boolean;\n};\n\ntype ServerOptions = NonNullable<UserConfig[\"server\"]>;\n\nfunction mergeAllowedHosts(current: ServerOptions[\"allowedHosts\"], hosts: string[]) {\n if (Array.isArray(current)) {\n return [...new Set([...current, ...hosts])];\n }\n\n return hosts;\n}\n\nfunction getDisplayEntries(entries: DevHostEntry[], vitePort: number | undefined) {\n if (!vitePort) {\n return entries;\n }\n\n const matchingEntries = entries.filter((entry) => entry.port === vitePort);\n return matchingEntries.length > 0 ? matchingEntries : entries;\n}\n\nfunction printLocalHosts(server: ViteDevServer, context: LocalghostContext | undefined) {\n if (!context) return;\n\n const entries = context.entries;\n const vitePort = context.port;\n const https = context.https;\n const displayEntries = getDisplayEntries(entries, vitePort);\n const protocol = https ? \"https\" : \"http\";\n const urls = displayEntries.map((entry) => `${protocol}://${entry.host}/`);\n const primaryUrl = urls[0];\n\n if (!primaryUrl) {\n return;\n }\n\n const lines = [\n \"\",\n \" localghost\",\n ` local: ${primaryUrl}`,\n ...urls.slice(1).map((url) => ` also: ${url}`),\n vitePort ? ` target: http://127.0.0.1:${vitePort}/` : undefined,\n https ? \" proxy: Caddy local HTTPS\" : undefined,\n context.ghostTunnel.enabled ? formatGhostTunnel(context.ghostTunnel, {\n color: shouldColor(),\n label: \"ready\",\n verbose: optionsVerbose(context)\n }) : undefined,\n process.stdin.isTTY && context.ghostTunnel.enabled ? \" help: press h + enter for Vite, g + enter for Localghost\" : undefined\n ].filter((line): line is string => Boolean(line));\n\n server.config.logger.info(lines.join(\"\\n\"), {\n clear: false,\n timestamp: false\n });\n}\n\nfunction shouldColor() {\n return process.stdout.isTTY && !process.env.NO_COLOR;\n}\n\nfunction optionsVerbose(context: LocalghostContext) {\n return process.env.LOCALGHOST_VERBOSE === \"1\" || process.env.LOCALGHOST_VERBOSE === \"true\" || context.ghostTunnel.displayUrls.length > 1;\n}\n\nfunction readOptionsFromPlugin(options: LocalGhostPluginOptions): ReadDevHostsOptions {\n return {\n cwd: options.cwd ?? process.cwd(),\n ...(options.fileName ? { fileName: options.fileName } : {}),\n ...(options.configFiles ? { configFiles: options.configFiles } : {}),\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n}\n\nfunction getConfigWatchFiles(options: LocalGhostPluginOptions) {\n const readOptions = readOptionsFromPlugin(options);\n const cwd = readOptions.cwd ?? process.cwd();\n const resolvedPath = resolveDevHostsPath(readOptions);\n const candidatePaths = getConfigFileCandidates(readOptions).map((fileName) => resolve(cwd, fileName));\n const projectConfigPaths = options.localghostConfig === false\n ? []\n : options.localghostConfig\n ? [resolve(cwd, options.localghostConfig)]\n : [\"localghost.config.mjs\", \"localghost.config.js\", \"localghost.config.cjs\"].map((fileName) => resolve(cwd, fileName));\n\n return [...new Set([...candidatePaths, resolvedPath.path, ...projectConfigPaths])];\n}\n\nfunction normalizeWatchPath(filePath: string) {\n return normalize(resolve(filePath));\n}\n\nfunction renderConfig(hosts: string[], port: number) {\n return [\n \"# Buh. Friendly names for local services.\",\n \"# Format: <host> <port>\",\n ...hosts.map((host) => `${host} ${port}`),\n \"\"\n ].join(\"\\n\");\n}\n\nfunction defaultHost(cwd: string) {\n const projectName = sanitizeProjectName(getProjectName(cwd).split(\"/\").pop() ?? \"app\");\n return `${projectName}.localhost`;\n}\n\nfunction getPackageOwner(cwd: string) {\n try {\n const pkg = JSON.parse(readFileSync(resolve(cwd, \"package.json\"), \"utf8\")) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.startsWith(\"@\")) {\n return pkg.name.slice(1).split(\"/\")[0];\n }\n } catch {\n return undefined;\n }\n\n return undefined;\n}\n\nfunction getLocalOwner(cwd: string) {\n return sanitizeProjectName(process.env.LOCALGHOST_OWNER ?? getPackageOwner(cwd) ?? process.env.USER ?? process.env.USERNAME ?? \"local\");\n}\n\nfunction getRouteName(primaryHost: string, fallback: string) {\n return sanitizeProjectName(primaryHost.split(\".\")[0] ?? fallback);\n}\n\nfunction readBuildEntries(options: LocalGhostPluginOptions) {\n const readOptions = readOptionsFromPlugin(options);\n const resolved = resolveDevHostsPath(readOptions);\n if (!resolved.exists) return [];\n\n try {\n return readDevHosts(readOptions);\n } catch {\n return [];\n }\n}\n\nasync function maybePrintBuildGhostTunnel(options: LocalGhostPluginOptions) {\n const cwd = options.cwd ?? process.cwd();\n const projectConfig = await readLocalghostProjectConfig({\n cwd,\n ...(typeof options.localghostConfig !== \"undefined\" ? { configFile: options.localghostConfig } : {})\n });\n const explicitGhostTunnel = typeof options.ghostTunnel !== \"undefined\" ? options.ghostTunnel : projectConfig.config.ghostTunnel;\n if (!explicitGhostTunnel) return;\n\n const entries = readBuildEntries(options);\n const projectName = sanitizeProjectName(projectConfig.config.project ?? getProjectName(cwd));\n const primaryHost = options.primaryHost ?? entries[0]?.host ?? defaultHost(cwd);\n const ghostTunnel = resolveGhostTunnelConfig(explicitGhostTunnel, {\n route: getRouteName(primaryHost, projectName),\n project: sanitizeProjectName(projectConfig.config.project ?? getProjectName(cwd)),\n owner: getLocalOwner(cwd)\n });\n\n if (!ghostTunnel.enabled) return;\n\n const formatted = formatGhostTunnel(ghostTunnel, {\n color: shouldColor(),\n label: \"configured\",\n verbose: options.verbose === true || process.env.LOCALGHOST_VERBOSE === \"1\" || process.env.LOCALGHOST_VERBOSE === \"true\"\n });\n if (formatted) console.log(formatted);\n}\n\nasync function promptForHosts(cwd: string, port: number) {\n const primaryHost = await ask(\"Primary local domain\", defaultHost(cwd));\n const hosts = [primaryHost.toLowerCase()];\n\n while (await confirm(\"Add another local domain?\", false)) {\n const host = await ask(\"Domain\");\n if (host) hosts.push(host.toLowerCase());\n }\n\n return [...new Set(addDefaultWwwAliases(hosts.map((host) => ({ host, port, target: `127.0.0.1:${port}` }))).map((entry) => entry.host))];\n}\n\nfunction hasReadySetup(cwd: string, entries: DevHostEntry[], configPath: string, https: boolean) {\n const state = readLocalghostState(cwd);\n const projectName = sanitizeProjectName(getProjectName(cwd));\n if (state?.action !== \"setup\" || state.configPath !== configPath) return false;\n\n try {\n const hosts = readFileSync(getSystemHostsPath(), \"utf8\");\n if (!hosts.includes(renderHostsBlock(projectName, entries).trimEnd())) return false;\n } catch {\n return false;\n }\n\n const caddyfilePath = getCaddyfilePath(cwd);\n return existsSync(caddyfilePath) && readFileSync(caddyfilePath, \"utf8\") === renderCaddyfile(entries, { https });\n}\n\nasync function setupProject(cwd: string, entries: DevHostEntry[], configPath: string, https: boolean) {\n const caddy = await checkCaddy();\n if (!caddy.found) {\n throw new Error([\n \"Caddy is missing.\",\n `Run: ${caddy.installHint}`,\n \"Localghost will not install it for you.\"\n ].join(\"\\n\"));\n }\n\n const projectName = sanitizeProjectName(getProjectName(cwd));\n console.log(\"Buh. macOS keeps local hostnames in /etc/hosts, so Localghost may ask for your password.\");\n console.log(\"It will only touch its managed Localghost block.\");\n const hostsResult = await updateSystemHosts(projectName, entries);\n const caddyfilePath = await writeCaddyfile(entries, cwd, { https });\n await validateCaddyfile(caddyfilePath);\n writeLocalghostState(cwd, {\n action: \"setup\",\n projectName,\n cwd,\n configPath,\n hostsPath: hostsResult.hostsPath,\n hostsChanged: hostsResult.changed,\n ...(hostsResult.tempPath ? { hostsTempPath: hostsResult.tempPath } : {}),\n caddyfilePath,\n caddyHttps: https,\n entries\n });\n registerLocalghostSetup({\n cwd,\n projectName,\n configPath,\n caddyfilePath,\n https,\n entries\n });\n}\n\nasync function ensureLocalghostContext(options: LocalGhostPluginOptions, vitePort: number, https: boolean | undefined) {\n const cwd = options.cwd ?? process.cwd();\n const readOptions = readOptionsFromPlugin(options);\n const resolved = resolveDevHostsPath(readOptions);\n\n if (!resolved.exists) {\n if (options.setup === false || !canPrompt()) {\n throw new Error(\n `No .localghost found at ${resolved.path}. Run \\`localghost init --write-scripts\\` or start Vite in an interactive terminal.`\n );\n }\n\n console.log(`No .localghost found at ${resolved.path}.`);\n if (!(await confirm(\"Create one now?\", true))) {\n throw new Error(\"Localghost setup skipped. Create .localghost before running the Vite plugin.\");\n }\n\n const hosts = await promptForHosts(cwd, vitePort);\n writeTextFile(resolved.path, renderConfig(hosts, vitePort));\n console.log(`Created ${resolved.path}`);\n }\n\n const wrapperManagedPort = Boolean(process.env.LOCALGHOST_PORT);\n const context = await resolveLocalghostContext({\n ...options,\n cwd,\n port: vitePort,\n reservePort: !wrapperManagedPort,\n instanceKey: \"vite\",\n registryOwnerToken: options.registryOwnerToken ?? `${process.pid}:vite:${cwd}`,\n ...(wrapperManagedPort ? { dynamicPort: false } : {}),\n ...(typeof https === \"boolean\" ? { https } : {})\n });\n\n if (!hasReadySetup(cwd, context.entries, resolved.path, context.https)) {\n if (options.setup === false || !context.autoRepair) return context;\n if (options.setup === \"prompt\" && (!canPrompt() || !(await confirm(\"Repair Localghost setup now?\", true)))) return context;\n\n console.log(\"Localghost setup is stale; repairing it now.\");\n await setupProject(cwd, context.entries, resolved.path, context.https);\n console.log(`Repair complete. Setup state: ${getLocalghostStatePath(cwd)}`);\n }\n\n return context;\n}\n\nfunction isConcreteGhostUrl(url: string) {\n return !url.includes(\"*\") && !url.includes(\"<\") && /^https?:\\/\\//.test(url);\n}\n\nfunction getConcreteGhostUrls(context: LocalghostContext) {\n return context.ghostTunnel.displayUrls.filter(isConcreteGhostUrl);\n}\n\nfunction openExternalUrl(url: string) {\n const command = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"cmd\" : \"xdg-open\";\n const args = process.platform === \"win32\" ? [\"/c\", \"start\", \"\", url] : [url];\n const child = spawn(command, args, {\n detached: true,\n stdio: \"ignore\"\n });\n child.unref();\n}\n\nfunction installGhostTunnelMenu(server: ViteDevServer, context: LocalghostContext | undefined) {\n if (!context?.ghostTunnel.enabled || !process.stdin.isTTY) return undefined;\n\n emitKeypressEvents(process.stdin);\n\n let active = false;\n const concreteUrls = getConcreteGhostUrls(context);\n\n const printMenu = () => {\n active = true;\n const lines = [\n \"\",\n formatGhostTunnel(context.ghostTunnel, {\n color: shouldColor(),\n label: \"ready\",\n verbose: true\n }) ?? \"localghost ghost tunnel\",\n \"\"\n ];\n\n if (concreteUrls.length === 0) {\n lines.push(\" No concrete Ghost Tunnel domain configured.\");\n lines.push(\" Add ghostTunnel.domains to localghost.config.mjs to open a URL from this menu.\");\n active = false;\n } else {\n concreteUrls.forEach((url, index) => {\n lines.push(` ${index + 1}. ${url}`);\n });\n lines.push(\"\");\n lines.push(\" Press a number to open, or escape to cancel.\");\n }\n\n server.config.logger.info(lines.join(\"\\n\"), {\n clear: false,\n timestamp: false\n });\n };\n\n const onKeypress = (_input: string, key: { name?: string; ctrl?: boolean } = {}) => {\n if (key.ctrl && key.name === \"c\") return;\n\n if (!active) {\n if (key.name === \"g\") printMenu();\n return;\n }\n\n if (key.name === \"escape\") {\n active = false;\n return;\n }\n\n const index = Number.parseInt(key.name ?? \"\", 10) - 1;\n const url = concreteUrls[index];\n if (!url) return;\n\n active = false;\n openExternalUrl(url);\n server.config.logger.info(`localghost opened ${url}`, {\n clear: false,\n timestamp: false\n });\n };\n\n process.stdin.on(\"keypress\", onKeypress);\n\n return () => {\n process.stdin.off(\"keypress\", onKeypress);\n };\n}\n\nexport function localGhostPlugin(options: LocalGhostPluginOptions = {}): Plugin {\n let resolvedEntries: DevHostEntry[] = [];\n let resolvedVitePort: number | undefined;\n let resolvedHttps = false;\n let resolvedContext: LocalghostContext | undefined;\n let restartTimer: NodeJS.Timeout | undefined;\n let activityRunId: string | undefined;\n\n return {\n name: \"localghost:vite\",\n enforce: \"pre\",\n\n async config(userConfig, configEnv: ConfigEnv): Promise<UserConfig> {\n if (configEnv.command !== \"serve\" || configEnv.mode === \"production\" || isProductionLike()) {\n await maybePrintBuildGhostTunnel(options);\n return {};\n }\n\n const existingServer = userConfig.server ?? {};\n const envVitePort = Number.parseInt(process.env.LOCALGHOST_PORT ?? process.env.VITE_PORT ?? \"\", 10);\n const requestedVitePort =\n options.port ??\n existingServer.port ??\n (Number.isInteger(envVitePort) ? envVitePort : 5173);\n const context: LocalghostContext = await ensureLocalghostContext(options, requestedVitePort, options.https);\n const entries = context.entries;\n const hosts = context.hosts;\n const primaryHost = context.primaryHost;\n\n resolvedEntries = entries;\n resolvedVitePort = context.port;\n resolvedHttps = context.https;\n resolvedContext = context;\n\n const server: ServerOptions = {\n ...existingServer,\n allowedHosts: mergeAllowedHosts(existingServer.allowedHosts, hosts),\n strictPort: existingServer.strictPort ?? true\n };\n\n if (typeof existingServer.host === \"undefined\") {\n server.host = context.bindHost;\n }\n\n if (context.port) {\n server.port = context.port;\n }\n\n if (context.https && primaryHost) {\n const existingWs = typeof server.ws === \"object\" && server.ws ? server.ws : {};\n const existingHmr = typeof existingServer.hmr === \"object\" && existingServer.hmr ? existingServer.hmr : {};\n\n server.ws = {\n ...existingWs,\n protocol: \"wss\",\n host: primaryHost,\n clientPort: 443\n } satisfies WsOptions;\n\n server.hmr = {\n ...existingHmr,\n protocol: \"wss\",\n host: primaryHost,\n clientPort: 443\n } satisfies HmrOptions;\n }\n\n return { server };\n },\n\n configureServer(server) {\n const watchFiles = getConfigWatchFiles(options);\n const watchedConfigFiles = new Set(watchFiles.map(normalizeWatchPath));\n\n server.watcher.add(watchFiles);\n\n const restartOnLocalghostConfigChange = (filePath: string) => {\n if (!watchedConfigFiles.has(normalizeWatchPath(filePath))) {\n return;\n }\n\n if (restartTimer) {\n clearTimeout(restartTimer);\n }\n\n restartTimer = setTimeout(() => {\n if (options.log !== false) {\n server.config.logger.info(\"localghost config changed; restarting Vite dev server\", {\n clear: false,\n timestamp: false\n });\n }\n\n void server.restart().catch((error: unknown) => {\n server.config.logger.error(error instanceof Error ? error.message : String(error), {\n timestamp: false\n });\n });\n }, 50);\n };\n\n server.watcher.on(\"add\", restartOnLocalghostConfigChange);\n server.watcher.on(\"change\", restartOnLocalghostConfigChange);\n server.watcher.on(\"unlink\", restartOnLocalghostConfigChange);\n\n if (options.log !== false) {\n server.printUrls = () => {\n printLocalHosts(server, resolvedContext);\n };\n }\n\n if (resolvedContext) {\n const run = registerLocalghostRun({\n id: `${resolvedContext.projectName}:vite:${process.pid}:${resolvedContext.cwd}`,\n mode: \"vite\",\n pid: process.pid,\n cwd: resolvedContext.cwd,\n projectName: resolvedContext.projectName,\n configPath: resolvedContext.configPath,\n childCommand: [\"vite\"],\n https: resolvedContext.https,\n requestedPort: resolvedContext.requestedPort,\n port: resolvedContext.port,\n dynamicPort: resolvedContext.dynamicPort,\n entries: resolvedContext.entries\n });\n activityRunId = run.id;\n }\n\n const cleanupGhostMenu = installGhostTunnelMenu(server, resolvedContext);\n\n const cleanupActivity = () => {\n if (!activityRunId) return;\n unregisterLocalghostRun(activityRunId);\n activityRunId = undefined;\n };\n\n const cleanup = () => {\n cleanupActivity();\n cleanupGhostMenu?.();\n void resolvedContext?.releasePort?.();\n };\n\n server.httpServer?.once(\"close\", cleanup);\n process.once(\"exit\", cleanup);\n }\n };\n}\n\nexport const localHostsPlugin = localGhostPlugin;\nexport type LocalHostsPluginOptions = LocalGhostPluginOptions;\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport const LOCALGHOST_ACTIVITY_VERSION = 1;\n\nexport type LocalghostRunMode = \"dev\" | \"run\" | \"vite\";\n\nexport type LocalghostRunRecord = {\n id: string;\n mode: LocalghostRunMode;\n pid: number;\n cwd: string;\n projectName: string;\n startedAt: string;\n updatedAt: string;\n configPath?: string;\n caddyfilePath?: string;\n caddyPid?: number;\n caddyPgid?: number;\n childPid?: number;\n childCommand?: string[];\n https?: boolean;\n requestedPort?: number;\n port?: number;\n dynamicPort?: boolean;\n entries: DevHostEntry[];\n};\n\nexport type LocalghostSetupRecord = {\n id: string;\n cwd: string;\n projectName: string;\n updatedAt: string;\n configPath?: string;\n caddyfilePath?: string;\n https?: boolean;\n entries: DevHostEntry[];\n};\n\nexport type LocalghostActivity = {\n version: typeof LOCALGHOST_ACTIVITY_VERSION;\n runs: LocalghostRunRecord[];\n setups: LocalghostSetupRecord[];\n};\n\nexport type RegisterLocalghostRunInput = Omit<LocalghostRunRecord, \"id\" | \"pid\" | \"startedAt\" | \"updatedAt\"> & {\n id?: string;\n pid?: number;\n startedAt?: string;\n};\n\nexport type RegisterLocalghostSetupInput = Omit<LocalghostSetupRecord, \"id\" | \"updatedAt\"> & {\n id?: string;\n};\n\nexport function getLocalghostActivityPath(env: NodeJS.ProcessEnv = process.env) {\n if (env.LOCALGHOST_ACTIVITY_PATH) return env.LOCALGHOST_ACTIVITY_PATH;\n\n const stateRoot = env.XDG_STATE_HOME || join(homedir(), \".local/state\");\n return join(stateRoot, \"localghost\", \"activity.json\");\n}\n\nexport function isProcessRunning(pid: number) {\n if (!Number.isInteger(pid) || pid < 1) return false;\n\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? error.code : undefined;\n return code === \"EPERM\";\n }\n}\n\nfunction emptyActivity(): LocalghostActivity {\n return { version: LOCALGHOST_ACTIVITY_VERSION, runs: [], setups: [] };\n}\n\nexport function readLocalghostActivity(path = getLocalghostActivityPath()): LocalghostActivity {\n if (!existsSync(path)) return emptyActivity();\n\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as Partial<LocalghostActivity>;\n return {\n version: LOCALGHOST_ACTIVITY_VERSION,\n runs: Array.isArray(parsed.runs) ? parsed.runs : [],\n setups: Array.isArray(parsed.setups) ? parsed.setups : []\n };\n } catch {\n return emptyActivity();\n }\n}\n\nexport function writeLocalghostActivity(activity: LocalghostActivity, path = getLocalghostActivityPath()) {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(activity, null, 2)}\\n`, \"utf8\");\n return path;\n}\n\nfunction createRunId(input: Pick<RegisterLocalghostRunInput, \"mode\" | \"cwd\" | \"projectName\">, pid: number) {\n return `${input.projectName}:${input.mode}:${pid}:${Date.now()}`;\n}\n\nfunction createSetupId(input: Pick<RegisterLocalghostSetupInput, \"cwd\" | \"projectName\" | \"configPath\">) {\n return `${input.projectName}:${input.cwd}:${input.configPath ?? \"\"}`;\n}\n\nexport function pruneLocalghostActivity(path = getLocalghostActivityPath()) {\n const activity = readLocalghostActivity(path);\n const activeRuns = activity.runs.filter((run) => isProcessRunning(run.pid));\n const pruned = activeRuns.length !== activity.runs.length;\n\n if (pruned) {\n writeLocalghostActivity({ ...activity, version: LOCALGHOST_ACTIVITY_VERSION, runs: activeRuns }, path);\n }\n\n return {\n path,\n pruned,\n runs: activeRuns,\n setups: activity.setups\n };\n}\n\nexport function listLocalghostRuns(path = getLocalghostActivityPath()) {\n return pruneLocalghostActivity(path).runs;\n}\n\nexport function listLocalghostSetups(path = getLocalghostActivityPath()) {\n return pruneLocalghostActivity(path).setups;\n}\n\nexport function registerLocalghostRun(input: RegisterLocalghostRunInput, path = getLocalghostActivityPath()) {\n const now = new Date().toISOString();\n const pid = input.pid ?? process.pid;\n const record: LocalghostRunRecord = {\n id: input.id ?? createRunId(input, pid),\n mode: input.mode,\n pid,\n cwd: input.cwd,\n projectName: input.projectName,\n startedAt: input.startedAt ?? now,\n updatedAt: now,\n ...(input.configPath ? { configPath: input.configPath } : {}),\n ...(input.caddyfilePath ? { caddyfilePath: input.caddyfilePath } : {}),\n ...(input.caddyPid ? { caddyPid: input.caddyPid } : {}),\n ...(input.caddyPgid ? { caddyPgid: input.caddyPgid } : {}),\n ...(input.childPid ? { childPid: input.childPid } : {}),\n ...(input.childCommand ? { childCommand: input.childCommand } : {}),\n ...(typeof input.https === \"boolean\" ? { https: input.https } : {}),\n ...(input.requestedPort ? { requestedPort: input.requestedPort } : {}),\n ...(input.port ? { port: input.port } : {}),\n ...(typeof input.dynamicPort === \"boolean\" ? { dynamicPort: input.dynamicPort } : {}),\n entries: input.entries\n };\n const current = pruneLocalghostActivity(path).runs.filter((run) => run.id !== record.id);\n const activity = readLocalghostActivity(path);\n writeLocalghostActivity({ version: LOCALGHOST_ACTIVITY_VERSION, runs: [...current, record], setups: activity.setups }, path);\n return record;\n}\n\nexport function registerLocalghostSetup(input: RegisterLocalghostSetupInput, path = getLocalghostActivityPath()) {\n const record: LocalghostSetupRecord = {\n id: input.id ?? createSetupId(input),\n cwd: input.cwd,\n projectName: input.projectName,\n updatedAt: new Date().toISOString(),\n ...(input.configPath ? { configPath: input.configPath } : {}),\n ...(input.caddyfilePath ? { caddyfilePath: input.caddyfilePath } : {}),\n ...(typeof input.https === \"boolean\" ? { https: input.https } : {}),\n entries: input.entries\n };\n const activity = pruneLocalghostActivity(path);\n const setups = activity.setups.filter((setup) => setup.id !== record.id);\n writeLocalghostActivity({ version: LOCALGHOST_ACTIVITY_VERSION, runs: activity.runs, setups: [...setups, record] }, path);\n return record;\n}\n\nexport function unregisterLocalghostRun(id: string, path = getLocalghostActivityPath()) {\n const activity = readLocalghostActivity(path);\n const runs = activity.runs.filter((run) => run.id !== id);\n\n if (runs.length !== activity.runs.length) {\n writeLocalghostActivity({ ...activity, version: LOCALGHOST_ACTIVITY_VERSION, runs }, path);\n }\n}\n\nexport function unregisterLocalghostSetup(options: { cwd: string; projectName?: string; configPath?: string }, path = getLocalghostActivityPath()) {\n const activity = readLocalghostActivity(path);\n const setups = activity.setups.filter((setup) => {\n if (setup.cwd !== options.cwd) return true;\n if (options.projectName && setup.projectName !== options.projectName) return true;\n if (options.configPath && setup.configPath !== options.configPath) return true;\n return false;\n });\n\n if (setups.length !== activity.setups.length) {\n writeLocalghostActivity({ ...activity, version: LOCALGHOST_ACTIVITY_VERSION, setups }, path);\n }\n}\n","import { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parseDevHosts } from \"./parse.js\";\n\nexport const LOCALGHOST_CONFIG_FILE = \".localghost\";\n\nexport type ConfigPattern = string | RegExp;\n\nexport type ReadDevHostsOptions = {\n cwd?: string;\n fileName?: string;\n configFiles?: string[];\n configPattern?: ConfigPattern;\n};\n\nexport type ResolvedDevHostsPath = {\n path: string;\n fileName: string;\n exists: boolean;\n searchedFiles: string[];\n configPattern?: ConfigPattern;\n};\n\nfunction unique(values: string[]) {\n return [...new Set(values.filter(Boolean))];\n}\n\nfunction toRegExp(pattern: ConfigPattern) {\n return typeof pattern === \"string\" ? new RegExp(pattern) : pattern;\n}\n\nfunction findPatternMatches(cwd: string, pattern: ConfigPattern) {\n const matcher = toRegExp(pattern);\n\n return readdirSync(cwd, { withFileTypes: true })\n .filter((entry) => entry.isFile())\n .map((entry) => entry.name)\n .filter((name) => {\n matcher.lastIndex = 0;\n return matcher.test(name);\n })\n .sort();\n}\n\nexport function getConfigFileCandidates(options: ReadDevHostsOptions = {}) {\n const cwd = options.cwd ?? process.cwd();\n const exactFiles = unique([\n ...(options.fileName ? [options.fileName] : []),\n ...(options.configFiles ?? [])\n ]);\n const patternFiles = options.configPattern ? findPatternMatches(cwd, options.configPattern) : [];\n const candidates = unique([...exactFiles, ...patternFiles]);\n\n if (candidates.length > 0) return candidates;\n if (exactFiles.length > 0 || options.configPattern) return [];\n return [LOCALGHOST_CONFIG_FILE];\n}\n\nexport function resolveDevHostsPath(options: ReadDevHostsOptions = {}): ResolvedDevHostsPath {\n const cwd = options.cwd ?? process.cwd();\n const searchedFiles = getConfigFileCandidates(options);\n\n for (const fileName of searchedFiles) {\n const path = resolve(cwd, fileName);\n if (existsSync(path)) {\n return {\n path,\n fileName: basename(fileName),\n exists: true,\n searchedFiles,\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n }\n }\n\n const fileName = searchedFiles[0] ?? LOCALGHOST_CONFIG_FILE;\n\n return {\n path: resolve(cwd, fileName),\n fileName: basename(fileName),\n exists: false,\n searchedFiles,\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n}\n\nexport function getDevHostsPath(options: ReadDevHostsOptions = {}) {\n return resolveDevHostsPath(options).path;\n}\n\nfunction formatSearchedFiles(files: string[], pattern?: ConfigPattern) {\n if (files.length > 0) return files.map((file) => `\\`${file}\\``).join(\", \");\n if (pattern) return `files matching ${pattern.toString()}`;\n return `\\`${LOCALGHOST_CONFIG_FILE}\\``;\n}\n\nexport function readDevHosts(options: ReadDevHostsOptions | string = {}) {\n const resolvedOptions = typeof options === \"string\" ? { cwd: options } : options;\n const resolvedPath = resolveDevHostsPath(resolvedOptions);\n\n if (!resolvedPath.exists) {\n const cwd = resolvedOptions.cwd ?? process.cwd();\n throw new Error(\n `Missing Localghost config in ${cwd}. Looked for ${formatSearchedFiles(resolvedPath.searchedFiles, resolvedPath.configPattern)}. Run \\`localghost init\\` or pass --config/--config-pattern.`\n );\n }\n\n return parseDevHosts(readFileSync(resolvedPath.path, \"utf8\"), resolvedPath.fileName);\n}\n\nexport function getProjectName(cwd = process.cwd()) {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, \"package.json\"), \"utf8\")) as { name?: unknown };\n const name = typeof pkg.name === \"string\" && pkg.name ? pkg.name : \"app\";\n return sanitizeProjectName(name.replace(/^@/, \"\"));\n } catch {\n return \"app\";\n }\n}\n\nexport function sanitizeProjectName(value: string) {\n const sanitized = value.replace(/[^\\w.-]+/g, \"-\");\n let start = 0;\n let end = sanitized.length;\n\n while (start < end && sanitized.charCodeAt(start) === 45) start += 1;\n while (end > start && sanitized.charCodeAt(end - 1) === 45) end -= 1;\n\n const projectName = sanitized.slice(start, end);\n return projectName || \"app\";\n}\n","export type DevHostEntry = {\n host: string;\n port: number;\n target: string;\n};\n\nconst HOST_PATTERN = /^(?=.{1,253}$)(?!-)[a-z0-9-]+(\\.[a-z0-9-]+)*\\.?$/i;\n\nexport function parseDevHosts(input: string, fileName = \".localghost\"): DevHostEntry[] {\n const entries: DevHostEntry[] = [];\n\n input.split(/\\r?\\n/).forEach((rawLine, index) => {\n const line = rawLine.replace(/#.*/, \"\").trim();\n\n if (!line) {\n return;\n }\n\n const parts = line.split(/\\s+/);\n const host = parts[0];\n const portRaw = parts[1];\n\n if (!host || !portRaw || parts.length > 2) {\n throw new Error(`Invalid ${fileName} line ${index + 1}: \"${rawLine}\"`);\n }\n\n if (!HOST_PATTERN.test(host)) {\n throw new Error(`Invalid host on line ${index + 1}: \"${host}\"`);\n }\n\n const port = Number(portRaw);\n\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(`Invalid port on line ${index + 1}: \"${portRaw}\"`);\n }\n\n entries.push({\n host: host.toLowerCase().replace(/\\.$/, \"\"),\n port,\n target: `127.0.0.1:${port}`\n });\n });\n\n return entries;\n}\n\nexport function findLocalMdnsHosts(entries: DevHostEntry[]): string[] {\n return [...new Set(entries.map((entry) => entry.host).filter((host) => host.endsWith(\".local\")))];\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n getProjectName,\n readDevHosts,\n resolveDevHostsPath,\n sanitizeProjectName,\n type ConfigPattern,\n type ReadDevHostsOptions\n} from \"./config.js\";\nimport { findAvailablePort } from \"./port.js\";\nimport { createLocalghostRegistry } from \"./registry.js\";\nimport type { DevHostEntry } from \"./parse.js\";\nimport type { LocalghostServiceOptions } from \"./command.js\";\nimport { resolveGhostTunnelConfig, type GhostTunnelConfig, type GhostTunnelOptions } from \"./tunnel.js\";\n\nexport type LocalghostContextOptions = {\n cwd?: string;\n project?: string;\n localghostConfig?: string | false;\n fileName?: string;\n configFiles?: string[];\n configPattern?: ConfigPattern;\n port?: number;\n https?: boolean;\n bindHost?: string | boolean;\n primaryHost?: string;\n dynamicPort?: boolean;\n reservePort?: boolean;\n instanceKey?: string;\n reservedPorts?: Iterable<number>;\n registryOwnerToken?: string;\n autoRepair?: boolean;\n command?: string[];\n services?: LocalghostServiceOptions[];\n wwwAlias?: boolean;\n ghostTunnel?: GhostTunnelOptions;\n};\n\nexport type LocalghostContext = {\n cwd: string;\n projectName: string;\n readOptions: ReadDevHostsOptions;\n configPath: string;\n configFileName: string;\n configEntries: DevHostEntry[];\n entries: DevHostEntry[];\n hosts: string[];\n requestedPort: number;\n port: number;\n dynamicPort: boolean;\n autoRepair: boolean;\n bindHost: string | boolean;\n primaryHost: string;\n https: boolean;\n wwwAlias: boolean;\n ghostTunnel: GhostTunnelConfig;\n projectConfigPath?: string;\n releasePort?: () => Promise<boolean>;\n};\n\nexport type LocalghostProjectConfig = Omit<LocalghostContextOptions, \"cwd\" | \"localghostConfig\">;\n\nexport type LocalghostProjectConfigResult = {\n config: LocalghostProjectConfig;\n path?: string;\n};\n\nconst LOCALGHOST_PROJECT_CONFIG_FILES = [\n \"localghost.config.mjs\",\n \"localghost.config.js\",\n \"localghost.config.cjs\"\n];\n\nfunction parsePort(value: string | undefined) {\n if (!value) return undefined;\n const port = Number.parseInt(value, 10);\n return Number.isInteger(port) && port > 0 && port <= 65535 ? port : undefined;\n}\n\nfunction envPort() {\n return parsePort(process.env.LOCALGHOST_PORT) ?? parsePort(process.env.VITE_PORT);\n}\n\nfunction envDynamicPort() {\n const value = process.env.LOCALGHOST_DYNAMIC_PORT;\n if (!value) return undefined;\n return [\"1\", \"true\", \"yes\", \"on\"].includes(value.toLowerCase());\n}\n\nfunction envHttps() {\n const value = process.env.LOCALGHOST_HTTPS;\n if (!value) return undefined;\n return [\"1\", \"true\", \"yes\", \"on\"].includes(value.toLowerCase());\n}\n\nfunction getPackageName(cwd: string) {\n try {\n const pkg = JSON.parse(readFileSync(join(cwd, \"package.json\"), \"utf8\")) as { name?: unknown };\n return typeof pkg.name === \"string\" ? pkg.name : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction getPackageOwner(cwd: string) {\n const packageName = getPackageName(cwd);\n if (!packageName?.startsWith(\"@\")) return undefined;\n return packageName.slice(1).split(\"/\")[0];\n}\n\nfunction getLocalOwner(cwd: string) {\n return sanitizeProjectName(process.env.LOCALGHOST_OWNER ?? getPackageOwner(cwd) ?? process.env.USER ?? process.env.USERNAME ?? \"local\");\n}\n\nfunction getRouteName(primaryHost: string, fallback: string) {\n return sanitizeProjectName(primaryHost.split(\".\")[0] ?? fallback);\n}\n\nfunction readOptionsFromContext(options: LocalghostContextOptions): ReadDevHostsOptions {\n return {\n cwd: options.cwd ?? process.cwd(),\n ...(options.fileName ? { fileName: options.fileName } : {}),\n ...(options.configFiles ? { configFiles: options.configFiles } : {}),\n ...(options.configPattern ? { configPattern: options.configPattern } : {})\n };\n}\n\nfunction withRuntimePort(entries: DevHostEntry[], requestedPort: number, port: number) {\n if (requestedPort === port) return entries;\n\n const hasRequestedPort = entries.some((entry) => entry.port === requestedPort);\n if (!hasRequestedPort) return entries;\n\n return entries.map((entry) => (\n entry.port === requestedPort\n ? { ...entry, port, target: `127.0.0.1:${port}` }\n : entry\n ));\n}\n\nfunction uniqueHosts(entries: DevHostEntry[]) {\n return [...new Set(entries.map((entry) => entry.host))];\n}\n\nfunction isAliasableHost(host: string) {\n return host.includes(\".\") && !host.startsWith(\"www.\") && !host.includes(\":\");\n}\n\nexport function getDefaultWwwAlias(host: string) {\n return isAliasableHost(host) ? `www.${host}` : null;\n}\n\nexport function addDefaultWwwAliases(entries: DevHostEntry[]) {\n const seen = new Set(entries.map((entry) => entry.host));\n const aliases: DevHostEntry[] = [];\n\n for (const entry of entries) {\n const alias = getDefaultWwwAlias(entry.host);\n if (alias && !seen.has(alias)) {\n aliases.push({ host: alias, port: entry.port, target: `127.0.0.1:${entry.port}` });\n seen.add(alias);\n }\n }\n\n return [...entries, ...aliases];\n}\n\nfunction defined<T extends Record<string, unknown>>(input: T) {\n return Object.fromEntries(Object.entries(input).filter(([, value]) => typeof value !== \"undefined\")) as Partial<T>;\n}\n\nexport async function readLocalghostProjectConfig(options: {\n cwd?: string;\n configFile?: string | false;\n} = {}): Promise<LocalghostProjectConfigResult> {\n const cwd = options.cwd ?? process.cwd();\n if (options.configFile === false) return { config: {} };\n\n const candidates = options.configFile ? [options.configFile] : LOCALGHOST_PROJECT_CONFIG_FILES;\n const path = candidates.map((candidate) => resolveDevHostsPath({ cwd, fileName: candidate }).path).find((candidate) => existsSync(candidate));\n if (!path) return { config: {} };\n\n const imported = await import(`${pathToFileURL(path).href}?localghost=${Date.now()}`);\n const config = (imported.default ?? imported) as LocalghostProjectConfig;\n\n return { config, path };\n}\n\nexport function defineLocalghostConfig<T extends LocalghostContextOptions>(config: T) {\n return config;\n}\n\nexport async function resolveLocalghostContext(options: LocalghostContextOptions = {}): Promise<LocalghostContext> {\n const cwd = options.cwd ?? process.cwd();\n const projectConfig = await readLocalghostProjectConfig({\n cwd,\n ...(typeof options.localghostConfig !== \"undefined\" ? { configFile: options.localghostConfig } : {})\n });\n const merged = {\n ...projectConfig.config,\n ...defined(options)\n } as LocalghostContextOptions;\n const readOptions = readOptionsFromContext({ ...merged, cwd });\n const resolvedPath = resolveDevHostsPath(readOptions);\n const configEntries = readDevHosts(readOptions);\n const requestedPort = merged.port ?? envPort() ?? configEntries[0]?.port ?? 5173;\n const dynamicPort = merged.dynamicPort ?? envDynamicPort() ?? true;\n const autoRepair = merged.autoRepair ?? true;\n const bindHost = merged.bindHost ?? \"127.0.0.1\";\n const probeHost = typeof bindHost === \"string\" ? bindHost : \"127.0.0.1\";\n let port = requestedPort;\n let releasePort: (() => Promise<boolean>) | undefined;\n const reservePort = merged.reservePort ?? false;\n const instanceKey = merged.instanceKey ?? \"run\";\n if (reservePort && dynamicPort) {\n const registry = createLocalghostRegistry({ cwd, ...(merged.registryOwnerToken ? { ownerToken: merged.registryOwnerToken } : {}) });\n const lease = await registry.acquirePort({\n projectCwd: cwd,\n instanceKey,\n startPort: requestedPort,\n host: probeHost,\n ...(options.reservedPorts ? { reservedPorts: options.reservedPorts } : {})\n });\n port = lease.port;\n releasePort = () => registry.releasePort({ projectCwd: cwd, instanceKey });\n } else if (dynamicPort) {\n port = await findAvailablePort(requestedPort, { host: probeHost });\n }\n const wwwAlias = merged.wwwAlias ?? true;\n const entries = wwwAlias\n ? addDefaultWwwAliases(withRuntimePort(configEntries, requestedPort, port))\n : withRuntimePort(configEntries, requestedPort, port);\n const hosts = uniqueHosts(entries);\n const primaryHost =\n merged.primaryHost ??\n entries.find((entry) => entry.port === port)?.host ??\n hosts[0] ??\n `${sanitizeProjectName(getProjectName(cwd))}.localhost`;\n const projectName = sanitizeProjectName(merged.project ?? getProjectName(cwd));\n const ghostTunnel = resolveGhostTunnelConfig(merged.ghostTunnel, {\n route: getRouteName(primaryHost, projectName),\n project: projectName,\n owner: getLocalOwner(cwd)\n });\n\n return {\n cwd,\n projectName,\n readOptions,\n configPath: resolvedPath.path,\n configFileName: resolvedPath.fileName,\n configEntries,\n entries,\n hosts,\n requestedPort,\n port,\n dynamicPort,\n autoRepair,\n bindHost,\n primaryHost,\n https: merged.https ?? envHttps() ?? false,\n wwwAlias,\n ghostTunnel,\n ...(projectConfig.path ? { projectConfigPath: projectConfig.path } : {}),\n ...(releasePort ? { releasePort } : {})\n };\n}\n","import { createServer } from \"node:net\";\n\nexport type FindAvailablePortOptions = {\n host?: string;\n maxAttempts?: number;\n};\n\nexport async function isPortAvailable(port: number, host = \"127.0.0.1\") {\n return new Promise<boolean>((resolve) => {\n const server = createServer();\n\n server.once(\"error\", () => {\n resolve(false);\n });\n\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n\n server.listen(port, host);\n });\n}\n\nexport async function findAvailablePort(startPort: number, options: FindAvailablePortOptions = {}) {\n const host = options.host ?? \"127.0.0.1\";\n const maxAttempts = options.maxAttempts ?? 50;\n\n for (let offset = 0; offset < maxAttempts; offset += 1) {\n const port = startPort + offset;\n if (await isPortAvailable(port, host)) {\n return port;\n }\n }\n\n throw new Error(`No available port found from ${startPort} to ${startPort + maxAttempts - 1}.`);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, open, readFile, rename, rm, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, normalize, resolve } from \"node:path\";\nimport { isPortAvailable } from \"./port.js\";\n\nexport const LOCALGHOST_REGISTRY_FILE = \"registry.json\";\nexport const LOCALGHOST_REGISTRY_LOCK_FILE = \"registry.lock\";\n\nexport type PortAvailabilityCheck = (port: number, host?: string) => boolean | Promise<boolean>;\n\nexport type LocalghostRegistryEntry = {\n projectCwd: string;\n instanceKey: string;\n port: number;\n updatedAt: number;\n};\n\nexport type LocalghostLease = {\n projectCwd: string;\n instanceKey: string;\n port: number;\n pid: number;\n acquiredAt: number;\n expiresAt: number;\n ownerToken: string;\n};\n\nexport type LocalghostRegistryData = {\n version: 1;\n allocations: LocalghostRegistryEntry[];\n leases: LocalghostLease[];\n};\n\nexport type LocalghostRegistryOptions = {\n stateRoot?: string;\n cwd?: string;\n pid?: number;\n ownerToken?: string;\n now?: () => number;\n isProcessRunning?: (pid: number) => boolean;\n availabilityCheck?: PortAvailabilityCheck;\n lockTimeoutMs?: number;\n lockRetryMs?: number;\n lockStaleMs?: number;\n};\n\nexport type AcquireLocalghostPortOptions = {\n projectCwd?: string;\n instanceKey: string;\n startPort?: number;\n maxAttempts?: number;\n reservedPorts?: Iterable<number>;\n leaseTtlMs?: number;\n host?: string;\n};\n\nexport type LocalghostRegistry = {\n root: string;\n registryPath: string;\n lockPath: string;\n ownerToken: string;\n acquirePort(options: AcquireLocalghostPortOptions): Promise<LocalghostLease>;\n releasePort(options: { projectCwd?: string; instanceKey: string }): Promise<boolean>;\n read(): Promise<LocalghostRegistryData>;\n prune(): Promise<{ removedLeases: number }>;\n};\n\ntype RegistryLock = { pid: number; createdAt: number; token: string };\n\nfunction defaultProcessRunning(pid: number) {\n if (pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nexport function getLocalghostRegistryRoot(env: NodeJS.ProcessEnv = process.env) {\n return resolve(env.LOCALGHOST_HOME || join(homedir(), \".localghost\"));\n}\n\nexport function canonicalizeLocalghostProjectCwd(cwd = process.cwd()) {\n return normalize(resolve(cwd));\n}\n\nfunction emptyRegistry(): LocalghostRegistryData {\n return { version: 1, allocations: [], leases: [] };\n}\n\nfunction leaseKey(projectCwd: string, instanceKey: string) {\n return `${projectCwd}\\u0000${instanceKey}`;\n}\n\nfunction validRegistry(value: unknown): value is LocalghostRegistryData {\n if (!value || typeof value !== \"object\") return false;\n const candidate = value as Partial<LocalghostRegistryData>;\n return candidate.version === 1 && Array.isArray(candidate.allocations) && Array.isArray(candidate.leases);\n}\n\nfunction pruneRegistry(registry: LocalghostRegistryData, now: number, isRunning: (pid: number) => boolean) {\n registry.leases = registry.leases.filter((lease) => lease.expiresAt > now && isRunning(lease.pid));\n}\n\nasync function readJson(path: string) {\n try {\n return JSON.parse(await readFile(path, \"utf8\")) as unknown;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n return undefined;\n }\n}\n\nexport function createLocalghostRegistry(options: LocalghostRegistryOptions = {}): LocalghostRegistry {\n const root = resolve(options.stateRoot ?? getLocalghostRegistryRoot());\n const registryPath = join(root, LOCALGHOST_REGISTRY_FILE);\n const lockPath = join(root, LOCALGHOST_REGISTRY_LOCK_FILE);\n const cwd = canonicalizeLocalghostProjectCwd(options.cwd);\n const now = options.now ?? Date.now;\n const pid = options.pid ?? process.pid;\n const ownerToken = options.ownerToken ?? randomUUID();\n const isRunning = options.isProcessRunning ?? defaultProcessRunning;\n const availabilityCheck = options.availabilityCheck ?? isPortAvailable;\n const lockTimeoutMs = options.lockTimeoutMs ?? 5000;\n const lockRetryMs = options.lockRetryMs ?? 25;\n const lockStaleMs = options.lockStaleMs ?? 30000;\n\n async function readRegistry() {\n const value = await readJson(registryPath);\n return validRegistry(value) ? value : emptyRegistry();\n }\n\n async function writeRegistry(registry: LocalghostRegistryData) {\n await mkdir(root, { recursive: true });\n const temporaryPath = join(root, `.registry.${process.pid}.${randomUUID()}.tmp`);\n await writeFile(temporaryPath, `${JSON.stringify(registry, null, 2)}\\n`, { mode: 0o600 });\n await rename(temporaryPath, registryPath);\n }\n\n async function lock() {\n await mkdir(root, { recursive: true });\n const deadline = now() + lockTimeoutMs;\n const token = randomUUID();\n while (true) {\n try {\n const handle = await open(lockPath, \"wx\", 0o600);\n await handle.writeFile(`${JSON.stringify({ pid, createdAt: now(), token } satisfies RegistryLock)}\\n`);\n await handle.close();\n return async () => {\n const current = await readJson(lockPath);\n if ((current as RegistryLock | undefined)?.token === token) await unlink(lockPath).catch(() => undefined);\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n const lockInfo = await readJson(lockPath) as RegistryLock | undefined;\n let stale = false;\n if (lockInfo && typeof lockInfo.pid === \"number\") {\n stale = !isRunning(lockInfo.pid) && now() - lockInfo.createdAt >= 0;\n } else {\n try {\n stale = now() - (await stat(lockPath)).mtimeMs > lockStaleMs;\n } catch {\n continue;\n }\n }\n if (stale) {\n await rm(lockPath, { force: true }).catch(() => undefined);\n continue;\n }\n if (now() >= deadline) throw new Error(`Timed out waiting for Localghost registry lock: ${lockPath}`);\n await new Promise((resolveDelay) => setTimeout(resolveDelay, lockRetryMs));\n }\n }\n }\n\n async function withLock<T>(operation: (registry: LocalghostRegistryData) => Promise<T>) {\n const releaseLock = await lock();\n try {\n const registry = await readRegistry();\n pruneRegistry(registry, now(), isRunning);\n return await operation(registry);\n } finally {\n await releaseLock();\n }\n }\n\n return {\n root,\n registryPath,\n lockPath,\n ownerToken,\n read: readRegistry,\n async prune() {\n const releaseLock = await lock();\n try {\n const registry = await readRegistry();\n const before = registry.leases.length;\n pruneRegistry(registry, now(), isRunning);\n await writeRegistry(registry);\n return { removedLeases: before - registry.leases.length };\n } finally {\n await releaseLock();\n }\n },\n async acquirePort(acquireOptions) {\n const projectCwd = canonicalizeLocalghostProjectCwd(acquireOptions.projectCwd ?? cwd);\n if (!acquireOptions.instanceKey) throw new Error(\"instanceKey is required\");\n return withLock(async (registry) => {\n const key = leaseKey(projectCwd, acquireOptions.instanceKey);\n const existing = registry.allocations.find((entry) => leaseKey(entry.projectCwd, entry.instanceKey) === key);\n const reserved = new Set(acquireOptions.reservedPorts ?? []);\n const activePorts = new Set(registry.leases.map((lease) => lease.port));\n const port = existing?.port;\n const ownsActiveLease = registry.leases.some((lease) => lease.port === port && leaseKey(lease.projectCwd, lease.instanceKey) === key && lease.ownerToken === ownerToken);\n const reusable = port !== undefined && !reserved.has(port) &&\n (!activePorts.has(port) || ownsActiveLease) &&\n (ownsActiveLease || await availabilityCheck(port, acquireOptions.host));\n let selectedPort = reusable ? port : undefined;\n if (selectedPort === undefined) {\n const startPort = acquireOptions.startPort ?? 3000;\n const maxAttempts = acquireOptions.maxAttempts ?? 50;\n for (let offset = 0; offset < maxAttempts; offset += 1) {\n const candidate = startPort + offset;\n if (reserved.has(candidate) || activePorts.has(candidate)) continue;\n if (await availabilityCheck(candidate, acquireOptions.host)) {\n selectedPort = candidate;\n break;\n }\n }\n if (selectedPort === undefined) throw new Error(`No available registry port found from ${startPort} to ${startPort + maxAttempts - 1}.`);\n }\n const timestamp = now();\n const entry = existing ?? { projectCwd, instanceKey: acquireOptions.instanceKey, port: selectedPort, updatedAt: timestamp };\n entry.port = selectedPort;\n entry.updatedAt = timestamp;\n if (!existing) registry.allocations.push(entry);\n registry.leases = registry.leases.filter((lease) => leaseKey(lease.projectCwd, lease.instanceKey) !== key);\n const lease = { projectCwd, instanceKey: acquireOptions.instanceKey, port: selectedPort, pid, acquiredAt: timestamp, expiresAt: timestamp + (acquireOptions.leaseTtlMs ?? 30 * 60 * 1000), ownerToken };\n registry.leases.push(lease);\n await writeRegistry(registry);\n return lease;\n });\n },\n async releasePort(releaseOptions) {\n const projectCwd = canonicalizeLocalghostProjectCwd(releaseOptions.projectCwd ?? cwd);\n return withLock(async (registry) => {\n const key = leaseKey(projectCwd, releaseOptions.instanceKey);\n const before = registry.leases.length;\n registry.leases = registry.leases.filter((lease) => leaseKey(lease.projectCwd, lease.instanceKey) !== key || lease.ownerToken !== ownerToken);\n if (registry.leases.length !== before) await writeRegistry(registry);\n return registry.leases.length !== before;\n });\n }\n };\n}\n","import { domainToASCII } from \"node:url\";\n\nexport type GhostTunnelNamespaceTag = \"route\" | \"project\" | \"owner\" | string;\n\nexport type GhostTunnelNamespaceOptions = readonly GhostTunnelNamespaceTag[] | {\n tags?: readonly GhostTunnelNamespaceTag[];\n separator?: string;\n spreadTag?: GhostTunnelNamespaceTag | false;\n};\n\nexport type GhostTunnelNamespaceConfig = {\n tags: GhostTunnelNamespaceTag[];\n separator: string;\n spreadTag?: GhostTunnelNamespaceTag;\n};\n\nexport type GhostTunnelNamespaceValues = Record<string, string> & {\n route?: string;\n project?: string;\n owner?: string;\n};\n\nexport type GhostTunnelPreviewOptions = {\n domain?: string;\n route: string;\n project: string;\n owner: string;\n values?: GhostTunnelNamespaceValues;\n path?: string;\n protocol?: \"http\" | \"https\";\n};\n\nexport type GhostTunnelMode = \"manual\" | \"public\";\n\nexport type GhostTunnelDomainOptions = string | readonly string[];\n\nexport type GhostTunnelAdapterProvider = \"vercel\";\nexport type GhostTunnelAdapterStrategy = \"same-project\" | \"separate-relay\";\nexport type GhostTunnelTransportKind = \"none\" | \"ip\" | \"tunnel\";\nexport type GhostTunnelAdapterTransport = GhostTunnelTransportKind;\nexport type GhostTunnelTunnelStoreProvider = \"vercel-redis\" | \"redis\";\nexport type GhostTunnelTunnelStoreEnv = \"auto\";\n\nexport type GhostTunnelTunnelStoreOptions = {\n provider?: GhostTunnelTunnelStoreProvider;\n env?: GhostTunnelTunnelStoreEnv;\n namespace?: string;\n};\n\nexport type GhostTunnelTransportOptions =\n | GhostTunnelTransportKind\n | {\n kind?: \"none\";\n }\n | {\n kind: \"ip\";\n allowPrivateNetworkAddress?: boolean;\n }\n | {\n kind: \"tunnel\";\n store?: GhostTunnelTunnelStoreOptions;\n waitMs?: number;\n pollIntervalMs?: number;\n routeTtlSeconds?: number;\n requestTtlSeconds?: number;\n maxRequestBodyBytes?: number;\n maxResponseBodyBytes?: number;\n };\n\nexport type GhostTunnelTransportConfig =\n | {\n kind: \"none\";\n }\n | {\n kind: \"ip\";\n allowPrivateNetworkAddress: boolean;\n }\n | {\n kind: \"tunnel\";\n store: Required<Pick<GhostTunnelTunnelStoreOptions, \"provider\" | \"env\" | \"namespace\">>;\n waitMs: number;\n pollIntervalMs: number;\n routeTtlSeconds: number;\n requestTtlSeconds: number;\n maxRequestBodyBytes: number;\n maxResponseBodyBytes: number;\n };\n\nexport type GhostTunnelAdapterOptions = GhostTunnelAdapterProvider | {\n provider: GhostTunnelAdapterProvider;\n strategy?: GhostTunnelAdapterStrategy;\n};\n\nexport type GhostTunnelOptions = false | GhostTunnelMode | {\n enabled?: boolean;\n mode?: GhostTunnelMode;\n domains?: GhostTunnelDomainOptions;\n subdomain?: string;\n namespace?: GhostTunnelNamespaceOptions;\n preview?: GhostTunnelPreviewOptions;\n requireHttps?: boolean;\n requireAuth?: boolean;\n adapter?: GhostTunnelAdapterOptions;\n transport?: GhostTunnelTransportOptions;\n};\n\nexport type GhostTunnelConfig = {\n enabled: boolean;\n mode: GhostTunnelMode;\n domains: string[];\n subdomain: string;\n namespace: GhostTunnelNamespaceConfig;\n preview?: GhostTunnelPreviewOptions;\n previewUrl?: string;\n displayUrl?: string;\n displayUrls: string[];\n requireHttps: boolean;\n requireAuth: boolean;\n transport: GhostTunnelTransportConfig;\n adapter?: {\n provider: GhostTunnelAdapterProvider;\n strategy: GhostTunnelAdapterStrategy;\n };\n};\n\nexport type GhostTunnelDisplayDefaults = {\n domain?: string;\n route?: string;\n project?: string;\n owner?: string;\n values?: GhostTunnelNamespaceValues;\n};\n\nexport type GhostTunnelRoute = {\n host: string;\n slug: string;\n namespace: GhostTunnelNamespaceValues;\n entryHost: string;\n wildcardHost: string;\n domain: string;\n};\n\nexport type ConstructGhostTunnelUrlInput = {\n domain: string;\n route: string;\n project: string;\n owner: string;\n values?: GhostTunnelNamespaceValues;\n path?: string;\n searchParams?: Record<string, string | number | boolean | null | undefined> | URLSearchParams;\n protocol?: \"http\" | \"https\";\n ghostTunnel?: GhostTunnelOptions | GhostTunnelConfig;\n};\n\nconst DEFAULT_GHOST_TUNNEL_SUBDOMAIN = \"ghost\";\nconst DEFAULT_GHOST_TUNNEL_NAMESPACE_TAGS = [\"route\", \"project\", \"owner\"] as const;\nconst DEFAULT_GHOST_TUNNEL_NAMESPACE_SEPARATOR = \"-\";\nconst DEFAULT_GHOST_TUNNEL_MODE: GhostTunnelMode = \"manual\";\nconst DEFAULT_GHOST_TUNNEL_ADAPTER_STRATEGY: GhostTunnelAdapterStrategy = \"same-project\";\nconst DEFAULT_GHOST_TUNNEL_TRANSPORT_KIND: GhostTunnelTransportKind = \"none\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_PROVIDER: GhostTunnelTunnelStoreProvider = \"vercel-redis\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_ENV: GhostTunnelTunnelStoreEnv = \"auto\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_NAMESPACE = \"localghost\";\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_WAIT_MS = 25_000;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_POLL_INTERVAL_MS = 250;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_ROUTE_TTL_SECONDS = 30;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_REQUEST_TTL_SECONDS = 60;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_REQUEST_BODY_BYTES = 1024 * 1024;\nconst DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_RESPONSE_BODY_BYTES = 5 * 1024 * 1024;\n\ntype GhostTunnelLegacyAdapterOptions = {\n provider: GhostTunnelAdapterProvider;\n strategy?: GhostTunnelAdapterStrategy;\n transport?: GhostTunnelTransportOptions;\n};\n\nfunction isResolvedGhostTunnelConfig(value: GhostTunnelOptions | GhostTunnelConfig | undefined): value is GhostTunnelConfig {\n return typeof value === \"object\" && value !== null && \"enabled\" in value;\n}\n\nfunction toGhostTunnelConfig(options: GhostTunnelOptions | GhostTunnelConfig | undefined) {\n return isResolvedGhostTunnelConfig(options) ? options : resolveGhostTunnelConfig(options);\n}\n\nfunction stripHostPort(value: string) {\n const trimmed = value.trim().toLowerCase();\n if (trimmed.startsWith(\"[\") || trimmed.includes(\"/\")) return \"\";\n\n const portSeparator = trimmed.lastIndexOf(\":\");\n if (portSeparator === -1) return trimmed;\n\n const port = trimmed.slice(portSeparator + 1);\n return /^\\d+$/.test(port) ? trimmed.slice(0, portSeparator) : trimmed;\n}\n\nfunction normalizeDomain(value: string) {\n const host = stripHostPort(value.replace(/^\\*\\./, \"\"));\n const ascii = domainToASCII(host);\n if (!ascii || ascii.length > 253 || ascii.includes(\"..\")) return null;\n if (ascii.startsWith(\".\") || ascii.endsWith(\".\")) return null;\n if (ascii.includes(\"*\")) return null;\n if (!ascii.split(\".\").every(isValidHostLabel)) return null;\n return ascii;\n}\n\nfunction isValidHostLabel(value: string) {\n return value.length > 0 && value.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(value);\n}\n\nfunction isValidNamespaceTag(value: string) {\n return /^[a-z][a-z0-9_]*$/i.test(value);\n}\n\nfunction isNamespaceTagList(options: GhostTunnelNamespaceOptions | undefined): options is readonly GhostTunnelNamespaceTag[] {\n return Array.isArray(options);\n}\n\nfunction assertValidSubdomain(value: string) {\n if (!isValidHostLabel(value)) {\n throw new Error(`Invalid ghost tunnel subdomain: ${value}`);\n }\n}\n\nfunction normalizeDomains(domains: GhostTunnelDomainOptions | undefined) {\n const values = typeof domains === \"string\" ? [domains] : [...(domains ?? [])];\n const normalized = values.map((value) => value.trim()).filter(Boolean).map((value) => {\n const domain = normalizeDomain(value);\n if (!domain) throw new Error(`Invalid ghost tunnel domain: ${value}`);\n return domain;\n });\n\n return [...new Set(normalized)];\n}\n\nfunction parseGhostTunnelMode(value: GhostTunnelMode | undefined) {\n return value ?? DEFAULT_GHOST_TUNNEL_MODE;\n}\n\nfunction parseGhostTunnelAdapterStrategy(value: GhostTunnelAdapterStrategy | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_ADAPTER_STRATEGY;\n if (value === \"same-project\" || value === \"separate-relay\") return value;\n throw new Error(`Unsupported ghost tunnel adapter strategy: ${String(value)}`);\n}\n\nfunction parseGhostTunnelTransportKind(value: GhostTunnelTransportKind | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_TRANSPORT_KIND;\n if (value === \"none\" || value === \"ip\" || value === \"tunnel\") return value;\n throw new Error(`Unsupported ghost tunnel transport: ${String(value)}`);\n}\n\nfunction parsePositiveInteger(value: number | undefined, fallback: number, name: string) {\n if (typeof value === \"undefined\") return fallback;\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`Invalid ghost tunnel ${name}: ${value}`);\n }\n return value;\n}\n\nfunction parseTunnelStoreProvider(value: GhostTunnelTunnelStoreProvider | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_PROVIDER;\n if (value === \"vercel-redis\" || value === \"redis\") return value;\n throw new Error(`Unsupported ghost tunnel tunnel store provider: ${String(value)}`);\n}\n\nfunction parseTunnelStoreEnv(value: GhostTunnelTunnelStoreEnv | undefined) {\n if (typeof value === \"undefined\") return DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_ENV;\n if (value === \"auto\") return value;\n throw new Error(`Unsupported ghost tunnel tunnel store env: ${String(value)}`);\n}\n\nfunction parseTunnelStoreNamespace(value: string | undefined) {\n const namespace = value ?? DEFAULT_GHOST_TUNNEL_TUNNEL_STORE_NAMESPACE;\n if (!/^[a-z][a-z0-9:_-]{0,63}$/i.test(namespace)) {\n throw new Error(`Invalid ghost tunnel tunnel store namespace: ${namespace}`);\n }\n return namespace;\n}\n\nfunction resolveGhostTunnelAdapter(\n input: GhostTunnelAdapterOptions | GhostTunnelLegacyAdapterOptions | GhostTunnelConfig[\"adapter\"] | undefined\n): GhostTunnelConfig[\"adapter\"] {\n if (!input) return undefined;\n\n const provider = typeof input === \"string\" ? input : input.provider;\n if (provider !== \"vercel\") {\n throw new Error(`Unsupported ghost tunnel adapter provider: ${String(provider)}`);\n }\n\n return {\n provider,\n strategy: typeof input === \"string\" ? DEFAULT_GHOST_TUNNEL_ADAPTER_STRATEGY : parseGhostTunnelAdapterStrategy(input.strategy)\n };\n}\n\nfunction getLegacyGhostTunnelTransport(\n input: GhostTunnelAdapterOptions | GhostTunnelLegacyAdapterOptions | GhostTunnelConfig[\"adapter\"] | undefined\n) {\n if (!input || typeof input === \"string\" || !(\"transport\" in input)) return undefined;\n return input.transport;\n}\n\nfunction resolveGhostTunnelTransport(\n input: GhostTunnelTransportOptions | GhostTunnelTransportConfig | undefined\n): GhostTunnelTransportConfig {\n if (!input) {\n return { kind: \"none\" };\n }\n\n const kind = typeof input === \"string\"\n ? parseGhostTunnelTransportKind(input)\n : parseGhostTunnelTransportKind(input.kind);\n\n if (kind === \"ip\") {\n return {\n kind,\n allowPrivateNetworkAddress: typeof input === \"string\" ? false : input.kind === \"ip\" ? input.allowPrivateNetworkAddress ?? false : false\n };\n }\n\n if (kind === \"tunnel\") {\n const config: Extract<GhostTunnelTransportOptions, { kind: \"tunnel\" }> | Extract<GhostTunnelTransportConfig, { kind: \"tunnel\" }> | undefined =\n typeof input === \"string\" || input.kind !== \"tunnel\" ? undefined : input;\n const store = config?.store ?? {};\n return {\n kind,\n store: {\n provider: parseTunnelStoreProvider(store.provider),\n env: parseTunnelStoreEnv(store.env),\n namespace: parseTunnelStoreNamespace(store.namespace)\n },\n waitMs: parsePositiveInteger(config?.waitMs, DEFAULT_GHOST_TUNNEL_TUNNEL_WAIT_MS, \"tunnel waitMs\"),\n pollIntervalMs: parsePositiveInteger(config?.pollIntervalMs, DEFAULT_GHOST_TUNNEL_TUNNEL_POLL_INTERVAL_MS, \"tunnel pollIntervalMs\"),\n routeTtlSeconds: parsePositiveInteger(config?.routeTtlSeconds, DEFAULT_GHOST_TUNNEL_TUNNEL_ROUTE_TTL_SECONDS, \"tunnel routeTtlSeconds\"),\n requestTtlSeconds: parsePositiveInteger(config?.requestTtlSeconds, DEFAULT_GHOST_TUNNEL_TUNNEL_REQUEST_TTL_SECONDS, \"tunnel requestTtlSeconds\"),\n maxRequestBodyBytes: parsePositiveInteger(config?.maxRequestBodyBytes, DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_REQUEST_BODY_BYTES, \"tunnel maxRequestBodyBytes\"),\n maxResponseBodyBytes: parsePositiveInteger(config?.maxResponseBodyBytes, DEFAULT_GHOST_TUNNEL_TUNNEL_MAX_RESPONSE_BODY_BYTES, \"tunnel maxResponseBodyBytes\")\n };\n }\n\n return { kind: \"none\" };\n}\n\nfunction resolveNamespaceConfig(options: GhostTunnelNamespaceOptions | undefined): GhostTunnelNamespaceConfig {\n const tags = isNamespaceTagList(options)\n ? [...options]\n : [...(options?.tags ?? DEFAULT_GHOST_TUNNEL_NAMESPACE_TAGS)];\n let separator = DEFAULT_GHOST_TUNNEL_NAMESPACE_SEPARATOR;\n let spreadTag: GhostTunnelNamespaceTag | false | undefined = tags.includes(\"project\") ? \"project\" : undefined;\n if (options && !isNamespaceTagList(options)) {\n separator = options.separator ?? DEFAULT_GHOST_TUNNEL_NAMESPACE_SEPARATOR;\n spreadTag = options.spreadTag === false ? false : options.spreadTag ?? spreadTag;\n }\n\n if (tags.length === 0) {\n throw new Error(\"Ghost tunnel namespace must include at least one tag.\");\n }\n\n for (const tag of tags) {\n if (!isValidNamespaceTag(tag)) {\n throw new Error(`Invalid ghost tunnel namespace tag: ${tag}`);\n }\n }\n\n if (spreadTag && !tags.includes(spreadTag)) {\n throw new Error(`Ghost tunnel namespace spreadTag must be listed in tags: ${spreadTag}`);\n }\n\n if (!separator || separator.length > 8 || !/^[a-z0-9-]+$/.test(separator)) {\n throw new Error(`Invalid ghost tunnel namespace separator: ${separator}`);\n }\n\n return {\n tags,\n separator,\n ...(spreadTag ? { spreadTag } : {})\n };\n}\n\nfunction normalizeNamespaceValue(tag: string, value: string, separator: string, options: { allowSeparator?: boolean } = {}) {\n const normalized = normalizeDomain(value);\n if (!normalized || normalized.includes(\".\")) {\n throw new Error(`Invalid ghost tunnel namespace value for ${tag}: ${value}`);\n }\n\n if (!options.allowSeparator && normalized.includes(separator)) {\n throw new Error(`Ghost tunnel namespace value for ${tag} cannot include separator \"${separator}\": ${value}`);\n }\n\n return normalized;\n}\n\nfunction createNamespaceSlug(config: GhostTunnelNamespaceConfig, values: GhostTunnelNamespaceValues) {\n const parts = config.tags.map((tag) => {\n const value = values[tag];\n if (!value) {\n throw new Error(`Missing ghost tunnel namespace value: ${tag}`);\n }\n\n return normalizeNamespaceValue(tag, value, config.separator, { allowSeparator: tag === config.spreadTag });\n });\n\n const slug = parts.join(config.separator);\n if (!isValidHostLabel(slug)) {\n throw new Error(`Ghost tunnel namespace is too long for a DNS label: ${slug}`);\n }\n\n return slug;\n}\n\nfunction createNamespaceDisplaySlug(config: GhostTunnelNamespaceConfig, values: GhostTunnelNamespaceValues = {}) {\n return config.tags.map((tag) => {\n const value = values[tag];\n if (!value) return `<${tag}>`;\n\n try {\n return normalizeNamespaceValue(tag, value, config.separator, { allowSeparator: tag === config.spreadTag });\n } catch {\n return `<${tag}>`;\n }\n }).join(config.separator);\n}\n\nfunction getPreviewDefaults(preview: GhostTunnelPreviewOptions | undefined, defaults: GhostTunnelDisplayDefaults | undefined) {\n return {\n domain: preview?.domain ?? defaults?.domain,\n route: preview?.route ?? defaults?.route,\n project: preview?.project ?? defaults?.project,\n owner: preview?.owner ?? defaults?.owner,\n values: {\n ...(defaults?.values ?? {}),\n ...(preview?.values ?? {})\n },\n path: preview?.path,\n protocol: preview?.protocol\n };\n}\n\nfunction getDisplayValues(input: ReturnType<typeof getPreviewDefaults>): GhostTunnelNamespaceValues {\n return {\n ...(input.route ? { route: input.route } : {}),\n ...(input.project ? { project: input.project } : {}),\n ...(input.owner ? { owner: input.owner } : {}),\n ...input.values\n };\n}\n\nfunction getDisplayDefaults(defaults?: GhostTunnelDisplayDefaults) {\n return defaults;\n}\n\nfunction createDisplayUrl(config: GhostTunnelConfig, defaults?: GhostTunnelDisplayDefaults, domain?: string) {\n const input = getPreviewDefaults(config.preview, getDisplayDefaults(defaults));\n const protocol = input.protocol ?? \"https\";\n const slug = createNamespaceDisplaySlug(config.namespace, getDisplayValues(input));\n const entryHost = domain\n ? getGhostTunnelEntryHost(domain, config)\n : input.domain\n ? getGhostTunnelEntryHost(input.domain, config)\n : `${config.subdomain}.*`;\n const url = `${protocol}://${slug}.${entryHost}/`;\n\n if (!input.path) return url;\n return `${url}${input.path.replace(/^\\/+/, \"\")}`;\n}\n\nfunction createDisplayUrls(config: GhostTunnelConfig, defaults?: GhostTunnelDisplayDefaults) {\n const displayDefaults = getDisplayDefaults(defaults);\n const domains = config.domains.length > 0\n ? config.domains\n : displayDefaults?.domain\n ? [displayDefaults.domain]\n : [];\n const urls = domains.length > 0\n ? domains.map((domain) => createDisplayUrl(config, displayDefaults, domain))\n : [createDisplayUrl(config, displayDefaults)];\n\n return [...new Set(urls)];\n}\n\nfunction maybeConstructPreviewUrl(config: GhostTunnelConfig, defaults?: GhostTunnelDisplayDefaults) {\n if (!config.preview) return undefined;\n\n const input = getPreviewDefaults(config.preview, defaults);\n if (!input.domain || !input.route || !input.project || !input.owner) return undefined;\n\n return constructGhostTunnelUrl({\n domain: input.domain,\n route: input.route,\n project: input.project,\n owner: input.owner,\n values: input.values,\n ...(input.path ? { path: input.path } : {}),\n ...(input.protocol ? { protocol: input.protocol } : {}),\n ghostTunnel: config\n });\n}\n\nfunction parseNamespaceSlug(slug: string, config: GhostTunnelNamespaceConfig): GhostTunnelNamespaceValues | null {\n const parts = slug.split(config.separator);\n if (parts.length < config.tags.length) return null;\n if (parts.length !== config.tags.length && !config.spreadTag) return null;\n\n const namespace: GhostTunnelNamespaceValues = {};\n const spreadIndex = config.spreadTag ? config.tags.indexOf(config.spreadTag) : -1;\n const spreadWidth = spreadIndex >= 0 ? parts.length - config.tags.length + 1 : 1;\n\n let partIndex = 0;\n for (const [tagIndex, tag] of config.tags.entries()) {\n const value = tagIndex === spreadIndex\n ? parts.slice(partIndex, partIndex + spreadWidth).join(config.separator)\n : parts[partIndex];\n if (!value || !isValidHostLabel(value)) return null;\n if (tagIndex !== spreadIndex && value.includes(config.separator)) return null;\n namespace[tag] = value;\n partIndex += tagIndex === spreadIndex ? spreadWidth : 1;\n }\n\n return namespace;\n}\n\nexport function resolveGhostTunnelConfig(options: GhostTunnelOptions | undefined, defaults?: GhostTunnelDisplayDefaults): GhostTunnelConfig {\n if (options === false || typeof options === \"undefined\") {\n return {\n enabled: false,\n mode: DEFAULT_GHOST_TUNNEL_MODE,\n domains: [],\n subdomain: DEFAULT_GHOST_TUNNEL_SUBDOMAIN,\n namespace: resolveNamespaceConfig(undefined),\n displayUrls: [],\n requireHttps: true,\n requireAuth: true,\n transport: resolveGhostTunnelTransport(undefined)\n };\n }\n\n const config = typeof options === \"string\"\n ? { mode: options }\n : options;\n const subdomain = config.subdomain ?? DEFAULT_GHOST_TUNNEL_SUBDOMAIN;\n assertValidSubdomain(subdomain);\n const domains = normalizeDomains(config.domains);\n const enabled = config.enabled ?? true;\n const adapter = resolveGhostTunnelAdapter(config.adapter);\n const transport = resolveGhostTunnelTransport(config.transport ?? getLegacyGhostTunnelTransport(config.adapter));\n\n const resolved: GhostTunnelConfig = {\n enabled,\n mode: parseGhostTunnelMode(config.mode),\n domains,\n subdomain,\n namespace: resolveNamespaceConfig(config.namespace),\n ...(config.preview ? { preview: config.preview } : {}),\n displayUrls: [],\n requireHttps: config.requireHttps ?? true,\n requireAuth: config.requireAuth ?? true,\n transport,\n ...(adapter ? { adapter } : {})\n };\n\n if (!enabled) {\n return resolved;\n }\n\n const previewUrl = maybeConstructPreviewUrl(resolved, defaults);\n const displayUrls = previewUrl ? [previewUrl] : createDisplayUrls(resolved, defaults);\n\n return {\n ...resolved,\n displayUrls,\n ...(displayUrls[0] ? { displayUrl: displayUrls[0] } : {}),\n ...(previewUrl ? { previewUrl } : {})\n };\n}\n\nexport function getGhostTunnelEntryHost(domain: string, options: GhostTunnelOptions | GhostTunnelConfig = {}) {\n const config = toGhostTunnelConfig(options);\n const normalizedDomain = normalizeDomain(domain);\n if (!normalizedDomain) {\n throw new Error(`Invalid ghost tunnel domain: ${domain}`);\n }\n\n return `${config.subdomain}.${normalizedDomain}`;\n}\n\nexport function getGhostTunnelWildcardHost(domain: string, options: GhostTunnelOptions | GhostTunnelConfig = {}) {\n return `*.${getGhostTunnelEntryHost(domain, options)}`;\n}\n\nexport function constructGhostTunnelHost(input: Omit<ConstructGhostTunnelUrlInput, \"path\" | \"searchParams\" | \"protocol\">) {\n const config = toGhostTunnelConfig(input.ghostTunnel ?? {});\n if (!config.enabled) {\n throw new Error(\"Ghost tunnel is not enabled.\");\n }\n\n const namespaceValues: GhostTunnelNamespaceValues = {\n route: input.route,\n project: input.project,\n owner: input.owner,\n ...(input.values ?? {})\n };\n const slug = createNamespaceSlug(config.namespace, namespaceValues);\n\n return `${slug}.${getGhostTunnelEntryHost(input.domain, config)}`;\n}\n\nexport function constructGhostTunnelUrl(input: ConstructGhostTunnelUrlInput) {\n const protocol = input.protocol ?? \"https\";\n const host = constructGhostTunnelHost(input);\n const url = new URL(`${protocol}://${host}/`);\n\n if (input.path) {\n url.pathname = `/${input.path.replace(/^\\/+/, \"\")}`;\n }\n\n if (input.searchParams instanceof URLSearchParams) {\n url.search = input.searchParams.toString();\n } else if (input.searchParams) {\n for (const [key, value] of Object.entries(input.searchParams)) {\n if (typeof value !== \"undefined\" && value !== null) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return url.toString();\n}\n\nexport const constructGhostTunnelURL = constructGhostTunnelUrl;\n\nexport function getGhostTunnelDefaultDisplayUrl(options: GhostTunnelOptions | GhostTunnelConfig = {}, defaults?: GhostTunnelDisplayDefaults) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n return createDisplayUrl(config, defaults);\n}\n\nexport function getGhostTunnelDisplayUrl(options: GhostTunnelOptions | GhostTunnelConfig | undefined, defaults?: GhostTunnelDisplayDefaults) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n return config.displayUrl ?? config.previewUrl ?? getGhostTunnelDefaultDisplayUrl(config, defaults);\n}\n\nexport function getGhostTunnelDisplayUrls(options: GhostTunnelOptions | GhostTunnelConfig | undefined, defaults?: GhostTunnelDisplayDefaults) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return [];\n if (config.displayUrls.length > 0) return config.displayUrls;\n const displayUrl = getGhostTunnelDisplayUrl(config, defaults);\n return displayUrl ? [displayUrl] : [];\n}\n\nexport function getGhostTunnelPreviewUrl(options: GhostTunnelOptions | GhostTunnelConfig | undefined) {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n return config.previewUrl ?? maybeConstructPreviewUrl(config) ?? null;\n}\n\nexport function parseGhostTunnelHost(host: string, domain: string, options: GhostTunnelOptions | GhostTunnelConfig = {}): GhostTunnelRoute | null {\n const config = toGhostTunnelConfig(options);\n if (!config.enabled) return null;\n\n const normalizedHost = normalizeDomain(host);\n const normalizedDomain = normalizeDomain(domain);\n if (!normalizedHost || !normalizedDomain) return null;\n\n const entryHost = getGhostTunnelEntryHost(normalizedDomain, config);\n const suffix = `.${entryHost}`;\n if (!normalizedHost.endsWith(suffix)) return null;\n\n const slug = normalizedHost.slice(0, -suffix.length);\n if (!isValidHostLabel(slug)) return null;\n const namespace = parseNamespaceSlug(slug, config.namespace);\n if (!namespace) return null;\n\n return {\n host: normalizedHost,\n slug,\n namespace,\n entryHost,\n wildcardHost: `*.${entryHost}`,\n domain: normalizedDomain\n };\n}\n\nexport function assertSecureGhostTunnelRequest(input: {\n host: string;\n domain: string;\n protocol: \"http\" | \"https\";\n ghostTunnel: GhostTunnelOptions | GhostTunnelConfig | undefined;\n authenticated?: boolean;\n}) {\n const config = toGhostTunnelConfig(input.ghostTunnel);\n\n if (!config.enabled) {\n throw new Error(\"Ghost tunnel is not enabled.\");\n }\n\n if (config.requireHttps && input.protocol !== \"https\") {\n throw new Error(\"Ghost tunnel requests must use HTTPS.\");\n }\n\n if (config.requireAuth && input.authenticated !== true) {\n throw new Error(\"Ghost tunnel requests must be authenticated.\");\n }\n\n const route = parseGhostTunnelHost(input.host, input.domain, config);\n if (!route) {\n throw new Error(`Host is not a valid ghost tunnel host for ${input.domain}.`);\n }\n\n return route;\n}\n","import { execa } from \"execa\";\nimport { isPortAvailable } from \"./port.js\";\nimport { canonicalizeLocalghostProjectCwd, createLocalghostRegistry } from \"./registry.js\";\nimport { isProcessRunning } from \"./activity.js\";\nimport { resolveLocalghostContext } from \"./context.js\";\nimport type { ConfigPattern } from \"./config.js\";\n\nexport type DoctorResult = {\n ok: boolean;\n caddy: {\n found: boolean;\n version?: string;\n installHint: string;\n };\n ports: {\n configured?: number;\n available?: boolean;\n registryPath: string;\n staleLeases: Array<{ projectCwd: string; instanceKey: string; port: number; pid: number }>;\n duplicateAllocations: Array<{ port: number; projects: string[] }>;\n currentAllocation?: { projectCwd: string; instanceKey: string; port: number };\n };\n};\n\nexport type DoctorOptions = {\n cwd?: string;\n configFiles?: string[];\n configPattern?: ConfigPattern;\n};\n\nexport async function checkCaddy(): Promise<DoctorResult[\"caddy\"]> {\n try {\n const result = await execa(\"caddy\", [\"version\"], { reject: false });\n const version = [result.stdout, result.stderr].filter(Boolean).join(\"\\n\").trim();\n\n return {\n found: result.exitCode === 0,\n ...(version ? { version } : {}),\n installHint: \"brew install caddy\"\n };\n } catch {\n return {\n found: false,\n installHint: \"brew install caddy\"\n };\n }\n}\n\nexport async function runDoctor(options: DoctorOptions = {}): Promise<DoctorResult> {\n const caddy = await checkCaddy();\n const cwd = options.cwd ?? process.cwd();\n const registry = createLocalghostRegistry({ cwd });\n const data = await registry.read();\n const now = Date.now();\n const staleLeases = data.leases\n .filter((lease) => lease.expiresAt <= now || !isProcessRunning(lease.pid))\n .map(({ projectCwd, instanceKey, port, pid }) => ({ projectCwd, instanceKey, port, pid }));\n const allocationsByPort = new Map<number, string[]>();\n for (const allocation of data.allocations) {\n const projects = allocationsByPort.get(allocation.port) ?? [];\n projects.push(`${allocation.projectCwd}#${allocation.instanceKey}`);\n allocationsByPort.set(allocation.port, projects);\n }\n const duplicateAllocations = [...allocationsByPort.entries()]\n .filter(([, projects]) => projects.length > 1)\n .map(([port, projects]) => ({ port, projects }));\n let configured: number | undefined;\n let available: boolean | undefined;\n try {\n const context = await resolveLocalghostContext({\n cwd,\n ...(options.configFiles ? { configFiles: options.configFiles } : {}),\n ...(options.configPattern ? { configPattern: options.configPattern } : {}),\n dynamicPort: false\n });\n configured = context.requestedPort;\n available = await isPortAvailable(configured);\n } catch {\n // The existing Caddy check remains useful even when project config is invalid.\n }\n const currentProjectCwd = canonicalizeLocalghostProjectCwd(cwd);\n const currentAllocation = data.allocations.find((allocation) => allocation.projectCwd === currentProjectCwd);\n return {\n ok: caddy.found && available !== false && staleLeases.length === 0 && duplicateAllocations.length === 0,\n caddy,\n ports: {\n ...(configured !== undefined ? { configured } : {}),\n ...(available !== undefined ? { available } : {}),\n registryPath: registry.registryPath,\n staleLeases,\n duplicateAllocations,\n ...(currentAllocation ? {\n currentAllocation: {\n projectCwd: currentAllocation.projectCwd,\n instanceKey: currentAllocation.instanceKey,\n port: currentAllocation.port\n }\n } : {})\n }\n };\n}\n","export type LocalghostEnvironment = NodeJS.ProcessEnv;\n\nconst PRODUCTION_ENV_KEYS = [\"NODE_ENV\", \"VERCEL_ENV\", \"NETLIFY\", \"CF_PAGES_BRANCH\", \"LOCALGHOST_ENV\"] as const;\n\nexport function getProductionReason(env: LocalghostEnvironment = process.env) {\n if (env.LOCALGHOST_ENV === \"production\") return \"LOCALGHOST_ENV=production\";\n if (env.NODE_ENV === \"production\") return \"NODE_ENV=production\";\n if (env.VERCEL_ENV === \"production\") return \"VERCEL_ENV=production\";\n if (env.NETLIFY === \"true\" && env.CONTEXT === \"production\") return \"NETLIFY=true and CONTEXT=production\";\n if (env.CF_PAGES_BRANCH && env.CF_PAGES_BRANCH === env.CF_PAGES_PRODUCTION_BRANCH) {\n return \"CF_PAGES_BRANCH matches CF_PAGES_PRODUCTION_BRANCH\";\n }\n\n return null;\n}\n\nexport function isProductionLike(env: LocalghostEnvironment = process.env) {\n return getProductionReason(env) !== null;\n}\n\nexport function assertLocalDevelopment(command: string, env: LocalghostEnvironment = process.env) {\n const reason = getProductionReason(env);\n if (!reason) return;\n\n throw new Error(`Localghost only runs in local development. Refusing \\`${command}\\` because ${reason}.`);\n}\n\nexport function getProductionEnvKeys() {\n return PRODUCTION_ENV_KEYS;\n}\n","import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport function readTextFile(path: string) {\n return readFileSync(path, \"utf8\");\n}\n\nexport function writeTextFile(path: string, value: string) {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, value, \"utf8\");\n return path;\n}\n","import { writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { execa } from \"execa\";\nimport { sanitizeProjectName } from \"./config.js\";\nimport { readTextFile } from \"./fs.js\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport type UpdateSystemHostsResult = {\n changed: boolean;\n hostsPath: string;\n tempPath?: string;\n};\n\nexport type RemoveSystemHostsResult = UpdateSystemHostsResult & {\n removed: boolean;\n};\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction getManagedBlockPattern(projectName: string) {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const start = `# localghost:start ${sanitizedProjectName}`;\n const end = `# localghost:end ${sanitizedProjectName}`;\n return new RegExp(`${escapeRegExp(start)}[\\\\s\\\\S]*?${escapeRegExp(end)}\\\\n?`, \"m\");\n}\n\nexport function getSystemHostsPath(env: NodeJS.ProcessEnv = process.env) {\n if (env.LOCALGHOST_HOSTS_PATH) return env.LOCALGHOST_HOSTS_PATH;\n return process.platform === \"win32\" ? \"C:\\\\Windows\\\\System32\\\\drivers\\\\etc\\\\hosts\" : \"/etc/hosts\";\n}\n\nexport function renderHostsBlock(projectName: string, entries: DevHostEntry[]) {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const hosts = [...new Set(entries.map((entry) => entry.host))].sort();\n\n return [\n `# localghost:start ${sanitizedProjectName}`,\n ...hosts.map((host) => `127.0.0.1 ${host}`),\n `# localghost:end ${sanitizedProjectName}`,\n \"\"\n ].join(\"\\n\");\n}\n\nexport function upsertManagedBlock(existing: string, projectName: string, block: string) {\n const pattern = getManagedBlockPattern(projectName);\n\n if (pattern.test(existing)) {\n return existing.replace(pattern, block);\n }\n\n return `${existing.trimEnd()}\\n\\n${block}`;\n}\n\nexport function removeManagedBlock(existing: string, projectName: string) {\n const pattern = getManagedBlockPattern(projectName);\n\n if (!pattern.test(existing)) {\n return existing;\n }\n\n return existing.replace(pattern, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trimEnd() + \"\\n\";\n}\n\nasync function writeSystemHostsFile(hostsPath: string, next: string, projectName: string) {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const tempPath = join(tmpdir(), `localghost-${sanitizedProjectName}-hosts`);\n writeFileSync(tempPath, next, \"utf8\");\n\n if (process.env.LOCALGHOST_HOSTS_PATH) {\n writeFileSync(hostsPath, next, \"utf8\");\n return tempPath;\n }\n\n if (process.platform === \"win32\") {\n throw new Error(`Windows support: run as administrator and copy ${tempPath} to ${hostsPath}.`);\n }\n\n await execa(\"sudo\", [\"cp\", tempPath, hostsPath], { stdio: \"inherit\" });\n\n return tempPath;\n}\n\nexport async function updateSystemHosts(projectName: string, entries: DevHostEntry[]): Promise<UpdateSystemHostsResult> {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const hostsPath = getSystemHostsPath();\n const existing = readTextFile(hostsPath);\n const block = renderHostsBlock(sanitizedProjectName, entries);\n const next = upsertManagedBlock(existing, sanitizedProjectName, block);\n\n if (next === existing) {\n return { changed: false, hostsPath };\n }\n\n const tempPath = await writeSystemHostsFile(hostsPath, next, sanitizedProjectName);\n\n return { changed: true, hostsPath, tempPath };\n}\n\nexport async function removeSystemHosts(projectName: string): Promise<RemoveSystemHostsResult> {\n const sanitizedProjectName = sanitizeProjectName(projectName);\n const hostsPath = getSystemHostsPath();\n const existing = readTextFile(hostsPath);\n const next = removeManagedBlock(existing, sanitizedProjectName);\n\n if (next === existing) {\n return { changed: false, removed: false, hostsPath };\n }\n\n const tempPath = await writeSystemHostsFile(hostsPath, next, sanitizedProjectName);\n\n return { changed: true, removed: true, hostsPath, tempPath };\n}\n","import { stdin as input, stdout as output } from \"node:process\";\nimport { createInterface } from \"node:readline/promises\";\n\nexport function canPrompt() {\n return Boolean(input.isTTY && output.isTTY);\n}\n\nexport async function withPrompt<T>(run: (prompt: (question: string) => Promise<string>) => Promise<T>) {\n const rl = createInterface({ input, output });\n try {\n return await run((question) => rl.question(question));\n } finally {\n rl.close();\n }\n}\n\nexport async function confirm(question: string, defaultValue = true) {\n return withPrompt(async (prompt) => {\n const suffix = defaultValue ? \" [Y/n] \" : \" [y/N] \";\n const answer = (await prompt(`${question}${suffix}`)).trim().toLowerCase();\n if (!answer) return defaultValue;\n return answer === \"y\" || answer === \"yes\";\n });\n}\n\nexport async function ask(question: string, defaultValue?: string) {\n return withPrompt(async (prompt) => {\n const suffix = defaultValue ? ` (${defaultValue}) ` : \" \";\n const answer = (await prompt(`${question}${suffix}`)).trim();\n return answer || defaultValue || \"\";\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readTextFile, writeTextFile } from \"./fs.js\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport const LOCALGHOST_STATE_FILE = \"ops/local/localghost-state.json\";\n\nexport type LocalghostStateAction = \"setup\" | \"teardown\";\n\nexport type LocalghostState = {\n version: 1;\n action: LocalghostStateAction;\n updatedAt: string;\n projectName: string;\n cwd: string;\n configPath?: string;\n hostsPath?: string;\n hostsChanged?: boolean;\n hostsTempPath?: string;\n caddyfilePath?: string;\n caddyfileRemoved?: boolean;\n caddyHttps?: boolean;\n caddyTrustedAt?: string;\n caddyTrustPromptedAt?: string;\n entries?: DevHostEntry[];\n};\n\nexport type WriteLocalghostStateInput = Omit<LocalghostState, \"version\" | \"updatedAt\">;\n\nexport function getLocalghostStatePath(cwd = process.cwd()) {\n return join(cwd, LOCALGHOST_STATE_FILE);\n}\n\nexport function readLocalghostState(cwd = process.cwd()): LocalghostState | null {\n const path = getLocalghostStatePath(cwd);\n if (!existsSync(path)) return null;\n return JSON.parse(readTextFile(path)) as LocalghostState;\n}\n\nexport function writeLocalghostState(cwd: string, state: WriteLocalghostStateInput) {\n const path = getLocalghostStatePath(cwd);\n writeTextFile(path, `${JSON.stringify({ ...state, version: 1, updatedAt: new Date().toISOString() }, null, 2)}\\n`);\n return path;\n}\n\nexport function patchLocalghostState(cwd: string, patch: Partial<WriteLocalghostStateInput>) {\n const current = readLocalghostState(cwd);\n if (!current) return null;\n return writeLocalghostState(cwd, { ...(current as unknown as WriteLocalghostStateInput), ...patch });\n}\n","import { dirname, join } from \"node:path\";\nimport { execa } from \"execa\";\nimport { writeTextFile } from \"./fs.js\";\nimport type { DevHostEntry } from \"./parse.js\";\n\nexport type CaddyModeOptions = {\n https?: boolean;\n};\n\nexport type CaddyProcessStopResult = {\n stopped: number[];\n alreadyExited: number[];\n failed: Array<{ pid: number; error: unknown }>;\n};\n\nexport type CaddyProcessKiller = (pid: number, signal: NodeJS.Signals) => void;\n\nfunction shouldShowCaddyLogs() {\n return [\"1\", \"true\", \"yes\", \"on\"].includes((process.env.LOCALGHOST_CADDY_VERBOSE ?? \"\").toLowerCase());\n}\n\nfunction caddyStdio() {\n return shouldShowCaddyLogs() ? \"inherit\" as const : \"pipe\" as const;\n}\n\nfunction groupByPort(entries: DevHostEntry[]) {\n const groups = new Map<number, DevHostEntry[]>();\n\n for (const entry of entries) {\n const group = groups.get(entry.port) ?? [];\n group.push(entry);\n groups.set(entry.port, group);\n }\n\n return groups;\n}\n\nexport function getCaddyfilePath(cwd = process.cwd()) {\n return join(cwd, \"ops/local/Caddyfile\");\n}\n\nexport function renderCaddyfile(entries: DevHostEntry[], options: CaddyModeOptions = {}) {\n const groups = groupByPort(entries);\n const https = options.https === true;\n const blocks = [...groups.entries()]\n .sort(([leftPort], [rightPort]) => leftPort - rightPort)\n .map(([port, group]) => {\n const hosts = group\n .map((entry) => (https ? entry.host : `http://${entry.host}`))\n .sort()\n .join(\", \");\n\n return `${hosts} {\n\\treverse_proxy 127.0.0.1:${port}\n}`;\n });\n\n const globalOptions = https\n ? `{\n local_certs\n}\n\n`\n : \"\";\n\n return `${globalOptions}${blocks.join(\"\\n\\n\")}\n`;\n}\n\nexport async function writeCaddyfile(entries: DevHostEntry[], cwd = process.cwd(), options: CaddyModeOptions = {}) {\n const path = getCaddyfilePath(cwd);\n writeTextFile(path, renderCaddyfile(entries, options));\n return path;\n}\n\nexport async function validateCaddyfile(path: string) {\n await execa(\"caddy\", [\"validate\", \"--config\", path], {\n cwd: dirname(path),\n stdio: caddyStdio()\n });\n}\n\nexport async function runCaddy(path: string) {\n await execa(\"caddy\", [\"run\", \"--config\", path], {\n cwd: dirname(path),\n stdio: caddyStdio()\n });\n}\n\nexport function startCaddy(path: string) {\n return execa(\"caddy\", [\"run\", \"--config\", path], {\n cwd: dirname(path),\n stdio: caddyStdio(),\n detached: process.platform !== \"win32\"\n });\n}\n\nexport function stopCaddyProcesses(\n pids: Iterable<number>,\n killProcess: CaddyProcessKiller = (pid, signal) => process.kill(pid, signal)\n): CaddyProcessStopResult {\n const result: CaddyProcessStopResult = {\n stopped: [],\n alreadyExited: [],\n failed: []\n };\n\n for (const pid of new Set(pids)) {\n try {\n killProcess(pid, \"SIGINT\");\n result.stopped.push(pid);\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ESRCH\") {\n result.alreadyExited.push(pid);\n } else {\n result.failed.push({ pid, error });\n }\n }\n }\n\n return result;\n}\n\nexport async function trustCaddy(path: string) {\n await execa(\"caddy\", [\"trust\", \"--config\", path], {\n cwd: dirname(path),\n stdio: \"inherit\"\n });\n}\n","import type { DevHostEntry } from \"./parse.js\";\nimport type { GhostTunnelConfig } from \"./tunnel.js\";\n\nexport type DomainRoute = {\n host: string;\n port: number;\n url: string;\n upstream: string;\n};\n\nexport type DomainRouteOptions = {\n https?: boolean;\n};\n\nexport type GhostTunnelFormatOptions = {\n color?: boolean;\n label?: \"configured\" | \"expected\" | \"ready\" | \"running\";\n verbose?: boolean;\n};\n\nconst ansi = {\n cyan: \"\\u001b[36m\",\n dim: \"\\u001b[2m\",\n green: \"\\u001b[32m\",\n reset: \"\\u001b[0m\",\n yellow: \"\\u001b[33m\"\n};\n\nfunction colorize(value: string, color: string, enabled: boolean) {\n return enabled ? `${color}${value}${ansi.reset}` : value;\n}\n\nfunction colorizeUrl(value: string, enabled: boolean) {\n if (!enabled) return value;\n return colorize(value.replace(/\\*/g, `${ansi.yellow}*${ansi.cyan}`), ansi.cyan, enabled);\n}\n\nexport function getDomainRoutes(entries: DevHostEntry[], options: DomainRouteOptions = {}): DomainRoute[] {\n const protocol = options.https === true ? \"https\" : \"http\";\n\n return [...entries]\n .sort((left, right) => left.host.localeCompare(right.host) || left.port - right.port)\n .map((entry) => ({\n host: entry.host,\n port: entry.port,\n url: `${protocol}://${entry.host}/`,\n upstream: `http://${entry.target}`\n }));\n}\n\nexport function formatDomainRoutes(entries: DevHostEntry[], options: DomainRouteOptions = {}) {\n const routes = getDomainRoutes(entries, options);\n\n if (routes.length === 0) {\n return \"localghost routes\\n no routes\";\n }\n\n return [\n \"localghost routes\",\n ...routes.map((route) => ` ${route.url} -> ${route.upstream}`)\n ].join(\"\\n\");\n}\n\nexport function formatGhostTunnel(config: GhostTunnelConfig, options: GhostTunnelFormatOptions = {}) {\n if (!config.enabled) return null;\n\n const color = options.color === true;\n const label = options.label ?? \"expected\";\n const labelColor = label === \"running\" ? ansi.green : ansi.dim;\n const lines = [\n \"localghost ghost tunnel\",\n ` mode: ${config.mode}`\n ];\n const urls = config.displayUrls.length > 0\n ? config.displayUrls\n : config.displayUrl\n ? [config.displayUrl]\n : [];\n\n if (urls.length === 0) {\n lines.push(` ${label}: unavailable`);\n } else if (urls.length === 1) {\n lines.push(` ${colorize(label, labelColor, color)}: ${colorizeUrl(urls[0]!, color)}`);\n } else {\n lines.push(` ${colorize(label, labelColor, color)}:`);\n for (const url of urls) {\n lines.push(` ${colorizeUrl(url, color)}`);\n }\n }\n\n if (options.verbose) {\n lines.push(` domains: ${config.domains.length > 0 ? config.domains.join(\", \") : \"*\"}`);\n lines.push(` access: ${config.requireAuth ? \"auth required\" : \"app decides\"}`);\n lines.push(` protocol: ${config.requ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B,wBAAgB;AAChB,2BAAmB;AACnB,aAAK,iBAAiB,cAAc;AAAA,MACtC;AAEA,aAAO,YAAY,KAAK,SAAS,OAAO;AACxC,cAAQ,KAAK,QAAQ,OAAO;AAAA,IAC9B;AAAA,EACF;AACF;AAEO,IAAM,mBAAmB;","names":["existsSync","readFileSync","normalize","resolve","input","input","existsSync","readFileSync","join","input","fileName","existsSync","readFileSync","join","existsSync","readFileSync","join","resolve","homedir","join","resolve","resolve","join","homedir","entry","lease","input","input","readFileSync","join","input","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","writeFileSync","join","execa","join","writeFileSync","execa","existsSync","join","join","existsSync","dirname","join","execa","join","execa","dirname","resolve","normalize","getPackageOwner","readFileSync","getLocalOwner","getRouteName","existsSync"]}