penambahan web socket

This commit is contained in:
2025-09-18 19:01:22 +07:00
parent 1d053646a9
commit d7bb2eb5bb
15070 changed files with 2402916 additions and 0 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env node
import nodeModule from 'node:module'
import process from 'node:process'
import { fileURLToPath } from 'node:url'
// https://nodejs.org/api/module.html#moduleenablecompilecachecachedir
// https://github.com/nodejs/node/pull/54501
if (nodeModule.enableCompileCache && !process.env.NODE_DISABLE_COMPILE_CACHE) {
try {
const { directory } = nodeModule.enableCompileCache()
if (directory) {
// allow child process to share the same cache directory
process.env.NODE_COMPILE_CACHE ||= directory
}
}
catch {
// Ignore errors
}
}
globalThis.__nuxt_cli__ = {
startTime: Date.now(),
entry: fileURLToPath(import.meta.url),
devEntry: fileURLToPath(new URL('../dist/dev/index.mjs', import.meta.url)),
}
// eslint-disable-next-line antfu/no-top-level-await
const { runMain } = await import('../dist/index.mjs')
runMain()
@@ -0,0 +1,330 @@
import * as fs from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import process from 'node:process';
import { updateConfig } from 'c12/update';
import { defineCommand } from 'citty';
import { colors } from 'consola/utils';
import { addDependency } from 'nypm';
import { $fetch } from 'ofetch';
import { resolve } from 'pathe';
import { readPackageJSON } from 'pkg-types';
import { satisfies } from 'semver';
import { joinURL } from 'ufo';
import { r as runCommand } from '../shared/cli.vXg4eLNu.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { g as getNuxtVersion } from '../shared/cli.DHenkA1C.mjs';
import { a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import { f as fetchModules, c as checkNuxtCompatibility, g as getRegistryFromContent } from '../shared/cli.Cr-OCgdO.mjs';
import 'node:url';
import 'node:crypto';
import 'std-env';
import '../shared/cli.DhJ3cH8w.mjs';
import 'consola';
import 'confbox';
const add = defineCommand({
meta: {
name: "add",
description: "Add Nuxt modules"
},
args: {
...cwdArgs,
...logLevelArgs,
moduleName: {
type: "positional",
description: "Specify one or more modules to install by name, separated by spaces"
},
skipInstall: {
type: "boolean",
description: "Skip npm install"
},
skipConfig: {
type: "boolean",
description: "Skip nuxt.config.ts update"
},
dev: {
type: "boolean",
description: "Install modules as dev dependencies"
}
},
async setup(ctx) {
const cwd = resolve(ctx.args.cwd);
const modules = ctx.args._.map((e) => e.trim()).filter(Boolean);
const projectPkg = await readPackageJSON(cwd).catch(() => ({}));
if (!projectPkg.dependencies?.nuxt && !projectPkg.devDependencies?.nuxt) {
logger.warn(`No \`nuxt\` dependency detected in \`${cwd}\`.`);
const shouldContinue = await logger.prompt(
`Do you want to continue anyway?`,
{
type: "confirm",
initial: false,
cancel: "default"
}
);
if (shouldContinue !== true) {
process.exit(1);
}
}
const maybeResolvedModules = await Promise.all(modules.map((moduleName) => resolveModule(moduleName, cwd)));
const resolvedModules = maybeResolvedModules.filter((x) => x != null);
logger.info(`Resolved \`${resolvedModules.map((x) => x.pkgName).join("`, `")}\`, adding module${resolvedModules.length > 1 ? "s" : ""}...`);
await addModules(resolvedModules, { ...ctx.args, cwd }, projectPkg);
if (!ctx.args.skipInstall) {
const args = Object.entries(ctx.args).filter(([k]) => k in cwdArgs || k in logLevelArgs).map(([k, v]) => `--${k}=${v}`);
await runCommand("prepare", args);
}
}
});
async function addModules(modules, { skipInstall, skipConfig, cwd, dev }, projectPkg) {
if (!skipInstall) {
const installedModules = [];
const notInstalledModules = [];
const dependencies = /* @__PURE__ */ new Set([
...Object.keys(projectPkg.dependencies || {}),
...Object.keys(projectPkg.devDependencies || {})
]);
for (const module of modules) {
if (dependencies.has(module.pkgName)) {
installedModules.push(module);
} else {
notInstalledModules.push(module);
}
}
if (installedModules.length > 0) {
const installedModulesList = installedModules.map((module) => module.pkgName).join("`, `");
const are = installedModules.length > 1 ? "are" : "is";
logger.info(`\`${installedModulesList}\` ${are} already installed`);
}
if (notInstalledModules.length > 0) {
const isDev = Boolean(projectPkg.devDependencies?.nuxt) || dev;
const notInstalledModulesList = notInstalledModules.map((module) => module.pkg).join("`, `");
const dependency = notInstalledModules.length > 1 ? "dependencies" : "dependency";
const a = notInstalledModules.length > 1 ? "" : " a";
logger.info(`Installing \`${notInstalledModulesList}\` as${a}${isDev ? " development" : ""} ${dependency}`);
const res = await addDependency(notInstalledModules.map((module) => module.pkg), {
cwd,
dev: isDev,
installPeerDependencies: true
}).then(() => true).catch(
(error) => {
logger.error(error);
const failedModulesList = notInstalledModules.map((module) => colors.cyan(module.pkg)).join("`, `");
const s = notInstalledModules.length > 1 ? "s" : "";
return logger.prompt(`Install failed for \`${failedModulesList}\`. Do you want to continue adding the module${s} to ${colors.cyan("nuxt.config")}?`, {
type: "confirm",
initial: false,
cancel: "default"
});
}
);
if (res !== true) {
return;
}
}
}
if (!skipConfig) {
await updateConfig({
cwd,
configFile: "nuxt.config",
async onCreate() {
logger.info(`Creating \`nuxt.config.ts\``);
return getDefaultNuxtConfig();
},
async onUpdate(config) {
if (!config.modules) {
config.modules = [];
}
for (const resolved of modules) {
if (config.modules.includes(resolved.pkgName)) {
logger.info(`\`${resolved.pkgName}\` is already in the \`modules\``);
continue;
}
logger.info(`Adding \`${resolved.pkgName}\` to the \`modules\``);
config.modules.push(resolved.pkgName);
}
}
}).catch((error) => {
logger.error(`Failed to update \`nuxt.config\`: ${error.message}`);
logger.error(`Please manually add \`${modules.map((module) => module.pkgName).join("`, `")}\` to the \`modules\` in \`nuxt.config.ts\``);
return null;
});
}
}
function getDefaultNuxtConfig() {
return `
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
modules: []
})`;
}
const packageRegex = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?([a-z0-9-~][a-z0-9-._~]*)(@[^@]+)?$/;
async function resolveModule(moduleName, cwd) {
let pkgName = moduleName;
let pkgVersion;
const reMatch = moduleName.match(packageRegex);
if (reMatch) {
if (reMatch[3]) {
pkgName = `${reMatch[1] || ""}${reMatch[2] || ""}`;
pkgVersion = reMatch[3].slice(1);
}
} else {
logger.error(`Invalid package name \`${pkgName}\`.`);
return false;
}
const modulesDB = await fetchModules().catch((err) => {
logger.warn(`Cannot search in the Nuxt Modules database: ${err}`);
return [];
});
const matchedModule = modulesDB.find(
(module) => module.name === moduleName || pkgVersion && module.name === pkgName || module.npm === pkgName || module.aliases?.includes(pkgName)
);
if (matchedModule?.npm) {
pkgName = matchedModule.npm;
}
if (matchedModule && matchedModule.compatibility.nuxt) {
const nuxtVersion = await getNuxtVersion(cwd);
if (!checkNuxtCompatibility(matchedModule, nuxtVersion)) {
logger.warn(
`The module \`${pkgName}\` is not compatible with Nuxt \`${nuxtVersion}\` (requires \`${matchedModule.compatibility.nuxt}\`)`
);
const shouldContinue = await logger.prompt(
"Do you want to continue installing incompatible version?",
{
type: "confirm",
initial: false,
cancel: "default"
}
);
if (!shouldContinue) {
return false;
}
}
const versionMap = matchedModule.compatibility.versionMap;
if (versionMap) {
for (const [_nuxtVersion, _moduleVersion] of Object.entries(versionMap)) {
if (satisfies(nuxtVersion, _nuxtVersion)) {
if (!pkgVersion) {
pkgVersion = _moduleVersion;
} else {
logger.warn(
`Recommended version of \`${pkgName}\` for Nuxt \`${nuxtVersion}\` is \`${_moduleVersion}\` but you have requested \`${pkgVersion}\``
);
pkgVersion = await logger.prompt("Choose a version:", {
type: "select",
options: [_moduleVersion, pkgVersion],
cancel: "undefined"
});
if (!pkgVersion) {
return false;
}
}
break;
}
}
}
}
let version = pkgVersion || "latest";
const pkgScope = pkgName.startsWith("@") ? pkgName.split("/")[0] : null;
const meta = await detectNpmRegistry(pkgScope);
const headers = {};
if (meta.authToken) {
headers.Authorization = `Bearer ${meta.authToken}`;
}
const pkgDetails = await $fetch(joinURL(meta.registry, `${pkgName}`), { headers });
if (pkgDetails["dist-tags"]?.[version]) {
version = pkgDetails["dist-tags"][version];
} else {
version = Object.keys(pkgDetails.versions)?.findLast((v) => satisfies(v, version)) || version;
}
const pkg = pkgDetails.versions[version];
const pkgDependencies = Object.assign(
pkg.dependencies || {},
pkg.devDependencies || {}
);
if (!pkgDependencies.nuxt && !pkgDependencies["nuxt-edge"] && !pkgDependencies["@nuxt/kit"]) {
logger.warn(`It seems that \`${pkgName}\` is not a Nuxt module.`);
const shouldContinue = await logger.prompt(
`Do you want to continue installing ${colors.cyan(pkgName)} anyway?`,
{
type: "confirm",
initial: false,
cancel: "default"
}
);
if (!shouldContinue) {
return false;
}
}
return {
nuxtModule: matchedModule,
pkg: `${pkgName}@${version}`,
pkgName,
pkgVersion: version
};
}
function getNpmrcPaths() {
const userNpmrcPath = join(homedir(), ".npmrc");
const cwdNpmrcPath = join(process.cwd(), ".npmrc");
return [cwdNpmrcPath, userNpmrcPath];
}
async function getAuthToken(registry) {
const paths = getNpmrcPaths();
const authTokenRegex = new RegExp(`^//${registry.replace(/^https?:\/\//, "").replace(/\/$/, "")}/:_authToken=(.+)$`, "m");
for (const npmrcPath of paths) {
let fd;
try {
fd = await fs.promises.open(npmrcPath, "r");
if (await fd.stat().then((r) => r.isFile())) {
const npmrcContent = await fd.readFile("utf-8");
const authTokenMatch = npmrcContent.match(authTokenRegex)?.[1];
if (authTokenMatch) {
return authTokenMatch.trim();
}
}
} catch {
} finally {
await fd?.close();
}
}
return null;
}
async function detectNpmRegistry(scope) {
const registry = await getRegistry(scope);
const authToken = await getAuthToken(registry);
return {
registry,
authToken
};
}
async function getRegistry(scope) {
if (process.env.COREPACK_NPM_REGISTRY) {
return process.env.COREPACK_NPM_REGISTRY;
}
const registry = await getRegistryFromFile(getNpmrcPaths(), scope);
if (registry) {
process.env.COREPACK_NPM_REGISTRY = registry;
}
return registry || "https://registry.npmjs.org";
}
async function getRegistryFromFile(paths, scope) {
for (const npmrcPath of paths) {
let fd;
try {
fd = await fs.promises.open(npmrcPath, "r");
if (await fd.stat().then((r) => r.isFile())) {
const npmrcContent = await fd.readFile("utf-8");
const registry = getRegistryFromContent(npmrcContent, scope);
if (registry) {
return registry;
}
}
} catch {
} finally {
await fd?.close();
}
}
return null;
}
export { add as default };
@@ -0,0 +1,319 @@
import { existsSync, promises } from 'node:fs';
import process from 'node:process';
import { defineCommand } from 'citty';
import { resolve, extname, dirname } from 'pathe';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { pascalCase, camelCase } from 'scule';
import { a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'exsolve';
import 'consola';
import 'node:path';
import 'std-env';
const httpMethods = [
"connect",
"delete",
"get",
"head",
"options",
"post",
"put",
"trace",
"patch"
];
const api = ({ name, args, nuxtOptions }) => {
return {
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, `api/${name}${applySuffix(args, httpMethods, "method")}.ts`),
contents: `
export default defineEventHandler(event => {
return 'Hello ${name}'
})
`
};
};
const app = ({ args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, "app.vue"),
contents: args.pages ? `
<script setup lang="ts"><\/script>
<template>
<div>
<NuxtLayout>
<NuxtPage/>
</NuxtLayout>
</div>
</template>
<style scoped></style>
` : `
<script setup lang="ts"><\/script>
<template>
<div>
<h1>Hello World!</h1>
</div>
</template>
<style scoped></style>
`
});
const appConfig = ({ nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, "app.config.ts"),
contents: `
export default defineAppConfig({})
`
});
const component = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, `components/${name}${applySuffix(
args,
["client", "server"],
"mode"
)}.vue`),
contents: `
<script setup lang="ts"><\/script>
<template>
<div>
Component: ${name}
</div>
</template>
<style scoped></style>
`
});
const composable = ({ name, nuxtOptions }) => {
const nameWithoutUsePrefix = name.replace(/^use-?/, "");
const nameWithUsePrefix = `use${pascalCase(nameWithoutUsePrefix)}`;
return {
path: resolve(nuxtOptions.srcDir, `composables/${name}.ts`),
contents: `
export const ${nameWithUsePrefix} = () => {
return ref()
}
`
};
};
const error = ({ nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, "error.vue"),
contents: `
<script setup lang="ts">
import type { NuxtError } from '#app'
const props = defineProps({
error: Object as () => NuxtError
})
<\/script>
<template>
<div>
<h1>{{ error.statusCode }}</h1>
<NuxtLink to="/">Go back home</NuxtLink>
</div>
</template>
<style scoped></style>
`
});
const layer = ({ name, nuxtOptions }) => {
return {
path: resolve(nuxtOptions.rootDir, `layers/${name}/nuxt.config.ts`),
contents: `
export default defineNuxtConfig({})
`
};
};
const layout = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.layouts, `${name}.vue`),
contents: `
<script setup lang="ts"><\/script>
<template>
<div>
Layout: ${name}
<slot />
</div>
</template>
<style scoped></style>
`
});
const middleware = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.middleware, `${name}${applySuffix(args, ["global"])}.ts`),
contents: `
export default defineNuxtRouteMiddleware((to, from) => {})
`
});
const module = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.rootDir, "modules", `${name}.ts`),
contents: `
import { defineNuxtModule } from 'nuxt/kit'
export default defineNuxtModule({
meta: {
name: '${name}'
},
setup () {}
})
`
});
const page = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.pages, `${name}.vue`),
contents: `
<script setup lang="ts"><\/script>
<template>
<div>
Page: ${name}
</div>
</template>
<style scoped></style>
`
});
const plugin = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.plugins, `${name}${applySuffix(args, ["client", "server"], "mode")}.ts`),
contents: `
export default defineNuxtPlugin(nuxtApp => {})
`
});
const serverMiddleware = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, "middleware", `${name}.ts`),
contents: `
export default defineEventHandler(event => {})
`
});
const serverPlugin = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, "plugins", `${name}.ts`),
contents: `
export default defineNitroPlugin(nitroApp => {})
`
});
const serverRoute = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, args.api ? "api" : "routes", `${name}.ts`),
contents: `
export default defineEventHandler(event => {})
`
});
const serverUtil = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, "utils", `${name}.ts`),
contents: `
export function ${camelCase(name)}() {}
`
});
const templates = {
"api": api,
"app": app,
"app-config": appConfig,
"component": component,
"composable": composable,
"error": error,
"layer": layer,
"layout": layout,
"middleware": middleware,
"module": module,
"page": page,
"plugin": plugin,
"server-middleware": serverMiddleware,
"server-plugin": serverPlugin,
"server-route": serverRoute,
"server-util": serverUtil
};
function applySuffix(args, suffixes, unwrapFrom) {
let suffix = "";
for (const s of suffixes) {
if (args[s]) {
suffix += `.${s}`;
}
}
if (unwrapFrom && args[unwrapFrom] && suffixes.includes(args[unwrapFrom])) {
suffix += `.${args[unwrapFrom]}`;
}
return suffix;
}
const templateNames = Object.keys(templates);
const add = defineCommand({
meta: {
name: "add",
description: "Create a new template file."
},
args: {
...cwdArgs,
...logLevelArgs,
force: {
type: "boolean",
description: "Force override file if it already exists",
default: false
},
template: {
type: "positional",
required: true,
valueHint: templateNames.join("|"),
description: `Specify which template to generate`
},
name: {
type: "positional",
required: true,
description: "Specify name of the generated file"
}
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd);
const templateName = ctx.args.template;
if (!templateNames.includes(templateName)) {
logger.error(
`Template ${templateName} is not supported. Possible values: ${Object.keys(
templates
).join(", ")}`
);
process.exit(1);
}
const ext = extname(ctx.args.name);
const name = ext === ".vue" || ext === ".ts" ? ctx.args.name.replace(ext, "") : ctx.args.name;
if (!name) {
logger.error("name argument is missing!");
process.exit(1);
}
const kit = await loadKit(cwd);
const config = await kit.loadNuxtConfig({ cwd });
const template = templates[templateName];
const res = template({ name, args: ctx.args, nuxtOptions: config });
if (!ctx.args.force && existsSync(res.path)) {
logger.error(
`File exists: ${res.path} . Use --force to override or use a different name.`
);
process.exit(1);
}
const parentDir = dirname(res.path);
if (!existsSync(parentDir)) {
logger.info("Creating directory", parentDir);
if (templateName === "page") {
logger.info("This enables vue-router functionality!");
}
await promises.mkdir(parentDir, { recursive: true });
}
await promises.writeFile(res.path, `${res.contents.trim()}
`);
logger.info(`\u{1FA84} Generated a new ${templateName} in ${res.path}`);
}
});
export { add as default };
@@ -0,0 +1,139 @@
import { promises } from 'node:fs';
import process from 'node:process';
import { defineCommand } from 'citty';
import { defu } from 'defu';
import { createApp, lazyEventHandler, eventHandler, toNodeListener } from 'h3';
import { listen } from 'listhen';
import { resolve, join } from 'pathe';
import { o as overrideEnv } from '../shared/cli.BEUGgaW4.mjs';
import { c as clearDir } from '../shared/cli.pLQ0oPGc.mjs';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { e as extendsArgs, d as dotEnvArgs, l as legacyRootDirArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'exsolve';
import 'consola';
import 'node:path';
import 'std-env';
const analyze = defineCommand({
meta: {
name: "analyze",
description: "Build nuxt and analyze production bundle (experimental)"
},
args: {
...cwdArgs,
...logLevelArgs,
...legacyRootDirArgs,
...dotEnvArgs,
...extendsArgs,
name: {
type: "string",
description: "Name of the analysis",
default: "default",
valueHint: "name"
},
serve: {
type: "boolean",
description: "Serve the analysis results",
negativeDescription: "Skip serving the analysis results",
default: true
}
},
async run(ctx) {
overrideEnv("production");
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const name = ctx.args.name || "default";
const slug = name.trim().replace(/[^\w-]/g, "_");
const startTime = Date.now();
const { loadNuxt, buildNuxt } = await loadKit(cwd);
const nuxt = await loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv
},
overrides: defu(ctx.data?.overrides, {
...ctx.args.extends && { extends: ctx.args.extends },
build: {
analyze: {
enabled: true
}
},
vite: {
build: {
rollupOptions: {
output: {
chunkFileNames: "_nuxt/[name].js",
entryFileNames: "_nuxt/[name].js"
}
}
}
},
logLevel: ctx.args.logLevel
})
});
const analyzeDir = nuxt.options.analyzeDir;
const buildDir = nuxt.options.buildDir;
const outDir = nuxt.options.nitro.output?.dir || join(nuxt.options.rootDir, ".output");
nuxt.options.build.analyze = defu(nuxt.options.build.analyze, {
filename: join(analyzeDir, "client.html")
});
await clearDir(analyzeDir);
await buildNuxt(nuxt);
const endTime = Date.now();
const meta = {
name,
slug,
startTime,
endTime,
analyzeDir,
buildDir,
outDir
};
await nuxt.callHook("build:analyze:done", meta);
await promises.writeFile(
join(analyzeDir, "meta.json"),
JSON.stringify(meta, null, 2),
"utf-8"
);
logger.info(`Analyze results are available at: \`${analyzeDir}\``);
logger.warn("Do not deploy analyze results! Use `nuxi build` before deploying.");
if (ctx.args.serve !== false && !process.env.CI) {
const app = createApp();
const serveFile = (filePath) => lazyEventHandler(async () => {
const contents = await promises.readFile(filePath, "utf-8");
return eventHandler((event) => {
event.node.res.end(contents);
});
});
logger.info("Starting stats server...");
app.use("/client", serveFile(join(analyzeDir, "client.html")));
app.use("/nitro", serveFile(join(analyzeDir, "nitro.html")));
app.use(
eventHandler(
() => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Nuxt Bundle Stats (experimental)</title>
</head>
<h1>Nuxt Bundle Stats (experimental)</h1>
<ul>
<li>
<a href="/nitro">Nitro server bundle stats</a>
</li>
<li>
<a href="/client">Client bundle stats</a>
</li>
</ul>
</html>
`
)
);
await listen(toNodeListener(app));
}
}
});
export { analyze as default };
@@ -0,0 +1,92 @@
import process from 'node:process';
import { defineCommand } from 'citty';
import { resolve, relative } from 'pathe';
import { s as showVersions } from '../shared/cli.Dz2be-Ai.mjs';
import { o as overrideEnv } from '../shared/cli.BEUGgaW4.mjs';
import { a as clearBuildDir } from '../shared/cli.pLQ0oPGc.mjs';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { l as legacyRootDirArgs, e as extendsArgs, b as envNameArgs, d as dotEnvArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:fs';
import 'consola/utils';
import 'exsolve';
import 'node:url';
import 'consola';
import 'node:path';
import 'std-env';
const buildCommand = defineCommand({
meta: {
name: "build",
description: "Build Nuxt for production deployment"
},
args: {
...cwdArgs,
...logLevelArgs,
prerender: {
type: "boolean",
description: "Build Nuxt and prerender static routes"
},
preset: {
type: "string",
description: "Nitro server preset"
},
...dotEnvArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
overrideEnv("production");
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
showVersions(cwd);
const kit = await loadKit(cwd);
const nuxt = await kit.loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv
},
envName: ctx.args.envName,
// c12 will fall back to NODE_ENV
overrides: {
logLevel: ctx.args.logLevel,
// TODO: remove in 3.8
_generate: ctx.args.prerender,
nitro: {
static: ctx.args.prerender,
preset: ctx.args.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET
},
...ctx.args.extends && { extends: ctx.args.extends },
...ctx.data?.overrides
}
});
let nitro;
try {
nitro = kit.useNitro?.();
logger.info(`Building for Nitro preset: \`${nitro.options.preset}\``);
} catch {
}
await clearBuildDir(nuxt.options.buildDir);
await kit.writeTypes(nuxt);
nuxt.hook("build:error", (err) => {
logger.error("Nuxt Build Error:", err);
process.exit(1);
});
await kit.buildNuxt(nuxt);
if (ctx.args.prerender) {
if (!nuxt.options.ssr) {
logger.warn(
"HTML content not prerendered because `ssr: false` was set. You can read more in `https://nuxt.com/docs/getting-started/deployment#static-hosting`."
);
}
const dir = nitro?.options.output.publicDir;
const publicDir = dir ? relative(process.cwd(), dir) : ".output/public";
logger.success(
`You can now deploy \`${publicDir}\` to any static hosting!`
);
}
}
});
export { buildCommand as default };
@@ -0,0 +1,34 @@
import { defineCommand } from 'citty';
import { resolve } from 'pathe';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { c as cleanupNuxtDirs } from '../shared/cli.At9IMXtr.mjs';
import { l as legacyRootDirArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'exsolve';
import 'node:fs';
import 'ohash';
import '../shared/cli.B9AmABr3.mjs';
import 'consola';
import '../shared/cli.pLQ0oPGc.mjs';
import 'node:path';
import 'node:process';
import 'std-env';
const cleanup = defineCommand({
meta: {
name: "cleanup",
description: "Clean up generated Nuxt files and caches"
},
args: {
...cwdArgs,
...legacyRootDirArgs
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { loadNuxtConfig } = await loadKit(cwd);
const nuxtOptions = await loadNuxtConfig({ cwd, overrides: { dev: true } });
await cleanupNuxtDirs(nuxtOptions.rootDir, nuxtOptions.buildDir);
}
});
export { cleanup as default };
@@ -0,0 +1,38 @@
import process from 'node:process';
import { defineCommand } from 'citty';
import { resolve } from 'pathe';
import { isTest } from 'std-env';
import { l as legacyRootDirArgs, d as dotEnvArgs, b as envNameArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:path';
import 'consola';
import '../shared/cli.B9AmABr3.mjs';
import 'node:url';
const devChild = defineCommand({
meta: {
name: "_dev",
description: "Run Nuxt development server (internal command to start child process)"
},
args: {
...cwdArgs,
...logLevelArgs,
...envNameArgs,
...dotEnvArgs,
...legacyRootDirArgs,
clear: {
type: "boolean",
description: "Clear console on restart",
negativeDescription: "Disable clear console on restart"
}
},
async run(ctx) {
if (!process.send && !isTest) {
console.warn("`nuxi _dev` is an internal command and should not be used directly. Please use `nuxi dev` instead.");
}
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { initialize } = await import('./index.mjs').then(function (n) { return n.c; });
await initialize({ cwd, args: ctx.args }, ctx);
}
});
export { devChild as default };
@@ -0,0 +1,376 @@
import { fork } from 'node:child_process';
import process from 'node:process';
import { defineCommand } from 'citty';
import { isSocketSupported } from 'get-port-please';
import { createProxyServer } from 'httpxy';
import { listen } from 'listhen';
import { getArgs, parseArgs } from 'listhen/cli';
import { resolve } from 'pathe';
import { satisfies } from 'semver';
import { isTest, isBun, isDeno } from 'std-env';
import { i as initialize, r as resolveLoadingTemplate, a as renderError, b as isSocketURL, p as parseSocketURL } from './index.mjs';
import { s as showVersions } from '../shared/cli.Dz2be-Ai.mjs';
import { o as overrideEnv } from '../shared/cli.BEUGgaW4.mjs';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { e as extendsArgs, b as envNameArgs, l as legacyRootDirArgs, d as dotEnvArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'defu';
import 'node:http';
import 'node:events';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'exsolve';
import 'h3';
import 'perfect-debounce';
import 'ufo';
import '../shared/cli.pLQ0oPGc.mjs';
import '../shared/cli.At9IMXtr.mjs';
import 'ohash';
import 'youch';
import 'consola/utils';
import 'consola';
import 'node:path';
const startTime = Date.now();
const forkSupported = !isTest && (!isBun || isBunForkSupported());
const listhenArgs = getArgs();
const command = defineCommand({
meta: {
name: "dev",
description: "Run Nuxt development server"
},
args: {
...cwdArgs,
...logLevelArgs,
...dotEnvArgs,
...legacyRootDirArgs,
...envNameArgs,
...extendsArgs,
clear: {
type: "boolean",
description: "Clear console on restart",
negativeDescription: "Disable clear console on restart"
},
fork: {
type: "boolean",
description: forkSupported ? "Disable forked mode" : "Enable forked mode",
negativeDescription: "Disable forked mode",
default: forkSupported,
alias: ["f"]
},
...{
...listhenArgs,
"port": {
...listhenArgs.port,
description: "Port to listen on (default: `NUXT_PORT || NITRO_PORT || PORT || nuxtOptions.devServer.port`)",
alias: ["p"]
},
"open": {
...listhenArgs.open,
alias: ["o"],
default: false
},
"host": {
...listhenArgs.host,
alias: ["h"],
description: "Host to listen on (default: `NUXT_HOST || NITRO_HOST || HOST || nuxtOptions.devServer?.host`)"
},
"clipboard": { ...listhenArgs.clipboard, default: false },
"https.domains": {
...listhenArgs["https.domains"],
description: "Comma separated list of domains and IPs, the autogenerated certificate should be valid for (https: true)"
}
},
sslCert: {
type: "string",
description: "(DEPRECATED) Use `--https.cert` instead."
},
sslKey: {
type: "string",
description: "(DEPRECATED) Use `--https.key` instead."
}
},
async run(ctx) {
overrideEnv("development");
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
showVersions(cwd);
const { loadNuxtConfig } = await loadKit(cwd);
const nuxtOptions = await loadNuxtConfig({
cwd,
dotenv: { cwd, fileName: ctx.args.dotenv },
envName: ctx.args.envName,
// c12 will fall back to NODE_ENV
overrides: {
dev: true,
logLevel: ctx.args.logLevel,
...ctx.args.extends && { extends: ctx.args.extends },
...ctx.data?.overrides
}
});
const listenOptions = resolveListenOptions(nuxtOptions, ctx.args);
if (!ctx.args.fork) {
const { listener, close: close2 } = await initialize({
cwd,
args: ctx.args,
hostname: listenOptions.hostname,
public: listenOptions.public,
publicURLs: void 0,
proxy: {
https: listenOptions.https
}
}, { data: ctx.data }, listenOptions);
return {
listener,
async close() {
await close2();
await listener.close();
}
};
}
const devProxy = await createDevProxy(cwd, nuxtOptions, listenOptions);
const nuxtSocketEnv = process.env.NUXT_SOCKET ? process.env.NUXT_SOCKET === "1" : void 0;
const useSocket = nuxtSocketEnv ?? (nuxtOptions._majorVersion === 4 && await isSocketSupported());
const urls = await devProxy.listener.getURLs();
const { onRestart, onReady, close } = await initialize({
cwd,
args: ctx.args,
hostname: listenOptions.hostname,
public: listenOptions.public,
publicURLs: urls.map((r) => r.url),
proxy: {
url: devProxy.listener.url,
urls,
https: devProxy.listener.https,
addr: devProxy.listener.address
}
// if running with nuxt v4 or `NUXT_SOCKET=1`, we use the socket listener
// otherwise pass 'true' to listen on a random port instead
}, {}, useSocket ? void 0 : true);
onReady((address) => devProxy.setAddress(address));
const fork2 = startSubprocess(cwd, ctx.args, ctx.rawArgs, listenOptions);
onRestart(async (devServer) => {
const [subprocess] = await Promise.all([
fork2,
devServer.close().catch(() => {
})
]);
await subprocess.initialize(devProxy, useSocket);
});
return {
listener: devProxy.listener,
async close() {
await close();
const subprocess = await fork2;
subprocess.kill(0);
await devProxy.listener.close();
}
};
}
});
async function createDevProxy(cwd, nuxtOptions, listenOptions) {
let loadingMessage = "Nuxt dev server is starting...";
let error;
let address;
let loadingTemplate = nuxtOptions.devServer.loadingTemplate;
const proxy = createProxyServer({});
proxy.on("proxyReq", (proxyReq, req) => {
if (!proxyReq.hasHeader("x-forwarded-for")) {
const address2 = req.socket.remoteAddress;
if (address2) {
proxyReq.appendHeader("x-forwarded-for", address2);
}
}
if (!proxyReq.hasHeader("x-forwarded-port")) {
const localPort = req?.socket?.localPort;
if (localPort) {
proxyReq.setHeader("x-forwarded-port", req.socket.localPort);
}
}
if (!proxyReq.hasHeader("x-forwarded-Proto")) {
const encrypted = req?.connection?.encrypted;
proxyReq.setHeader("x-forwarded-proto", encrypted ? "https" : "http");
}
});
const listener = await listen((req, res) => {
if (error) {
renderError(req, res, error);
return;
}
if (!address) {
res.statusCode = 503;
res.setHeader("Content-Type", "text/html");
res.setHeader("Cache-Control", "no-store");
if (loadingTemplate) {
res.end(loadingTemplate({ loading: loadingMessage }));
return;
}
async function resolveLoadingMessage() {
loadingTemplate = await resolveLoadingTemplate(cwd);
res.end(loadingTemplate({ loading: loadingMessage }));
}
return resolveLoadingMessage();
}
const target = isSocketURL(address) ? parseSocketURL(address) : address;
proxy.web(req, res, { target });
}, listenOptions);
listener.server.on("upgrade", (req, socket, head) => {
if (!address) {
if (!socket.destroyed) {
socket.end();
}
return;
}
const target = isSocketURL(address) ? parseSocketURL(address) : address;
return proxy.ws(req, socket, { target, xfwd: true }, head).catch(() => {
if (!socket.destroyed) {
socket.end();
}
});
});
return {
listener,
setAddress: (_addr) => {
address = _addr;
},
setLoadingMessage: (_msg) => {
loadingMessage = _msg;
},
setError: (_error) => {
error = _error;
},
clearError() {
error = void 0;
}
};
}
async function startSubprocess(cwd, args, rawArgs, listenOptions) {
let childProc;
let devProxy;
let ready;
const kill = (signal) => {
if (childProc) {
childProc.kill(signal === 0 && isDeno ? "SIGTERM" : signal);
childProc = void 0;
}
};
async function initialize2(proxy, socket) {
devProxy = proxy;
const urls = await devProxy.listener.getURLs();
await ready;
childProc.send({
type: "nuxt:internal:dev:context",
socket,
context: {
cwd,
args,
hostname: listenOptions.hostname,
public: listenOptions.public,
publicURLs: urls.map((r) => r.url),
proxy: {
url: devProxy.listener.url,
urls,
https: devProxy.listener.https
}
}
});
}
async function restart() {
devProxy?.clearError();
if (process.platform === "win32") {
kill("SIGTERM");
} else {
kill("SIGHUP");
}
childProc = fork(globalThis.__nuxt_cli__.devEntry, rawArgs, {
execArgv: ["--enable-source-maps", process.argv.find((a) => a.includes("--inspect"))].filter(Boolean),
env: {
...process.env,
__NUXT__FORK: "true"
}
});
childProc.on("close", (errorCode) => {
if (errorCode) {
process.exit(errorCode);
}
});
ready = new Promise((resolve2, reject) => {
childProc.on("error", reject);
childProc.on("message", (message) => {
if (message.type === "nuxt:internal:dev:fork-ready") {
resolve2();
} else if (message.type === "nuxt:internal:dev:ready") {
devProxy.setAddress(message.address);
if (startTime) {
logger.debug(`Dev server ready for connections in ${Date.now() - startTime}ms`);
}
} else if (message.type === "nuxt:internal:dev:loading") {
devProxy.setAddress(void 0);
devProxy.setLoadingMessage(message.message);
devProxy.clearError();
} else if (message.type === "nuxt:internal:dev:loading:error") {
devProxy.setAddress(void 0);
devProxy.setError(message.error);
} else if (message.type === "nuxt:internal:dev:restart") {
restart();
} else if (message.type === "nuxt:internal:dev:rejection") {
logger.info(`Restarting Nuxt due to error: \`${message.message}\``);
restart();
}
});
});
}
for (const signal of [
"exit",
"SIGTERM",
"SIGINT",
"SIGQUIT"
]) {
process.once(signal, () => {
kill(signal === "exit" ? 0 : signal);
});
}
await restart();
return {
initialize: initialize2,
restart,
kill
};
}
function resolveListenOptions(nuxtOptions, args) {
const _port = args.port ?? args.p ?? process.env.NUXT_PORT ?? process.env.NITRO_PORT ?? process.env.PORT ?? nuxtOptions.devServer.port;
const _hostname = typeof args.host === "string" ? args.host : args.host === true ? "" : process.env.NUXT_HOST ?? process.env.NITRO_HOST ?? process.env.HOST ?? (nuxtOptions.devServer?.host || void 0) ?? void 0;
const _public = args.public ?? (_hostname && !["localhost", "127.0.0.1", "::1"].includes(_hostname)) ? true : void 0;
const _httpsCert = args["https.cert"] || args.sslCert || process.env.NUXT_SSL_CERT || process.env.NITRO_SSL_CERT || typeof nuxtOptions.devServer.https !== "boolean" && nuxtOptions.devServer.https && "cert" in nuxtOptions.devServer.https && nuxtOptions.devServer.https.cert || "";
const _httpsKey = args["https.key"] || args.sslKey || process.env.NUXT_SSL_KEY || process.env.NITRO_SSL_KEY || typeof nuxtOptions.devServer.https !== "boolean" && nuxtOptions.devServer.https && "key" in nuxtOptions.devServer.https && nuxtOptions.devServer.https.key || "";
const _httpsPfx = args["https.pfx"] || typeof nuxtOptions.devServer.https !== "boolean" && nuxtOptions.devServer.https && "pfx" in nuxtOptions.devServer.https && nuxtOptions.devServer.https.pfx || "";
const _httpsPassphrase = args["https.passphrase"] || typeof nuxtOptions.devServer.https !== "boolean" && nuxtOptions.devServer.https && "passphrase" in nuxtOptions.devServer.https && nuxtOptions.devServer.https.passphrase || "";
const httpsEnabled = !!(args.https ?? nuxtOptions.devServer.https);
const _listhenOptions = parseArgs({
...args,
"open": args.o || args.open,
"https": httpsEnabled,
"https.cert": _httpsCert,
"https.key": _httpsKey,
"https.pfx": _httpsPfx,
"https.passphrase": _httpsPassphrase
});
const httpsOptions = httpsEnabled && {
...nuxtOptions.devServer.https,
..._listhenOptions.https
};
return {
..._listhenOptions,
port: _port,
hostname: _hostname,
public: _public,
https: httpsOptions,
baseURL: nuxtOptions.app.baseURL.startsWith("./") ? nuxtOptions.app.baseURL.slice(1) : nuxtOptions.app.baseURL
};
}
function isBunForkSupported() {
const bunVersion = globalThis.Bun.version;
return satisfies(bunVersion, ">=1.2");
}
export { command as default };
@@ -0,0 +1,46 @@
import process from 'node:process';
import { defineCommand } from 'citty';
import { resolve } from 'pathe';
import { x } from 'tinyexec';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { l as legacyRootDirArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'consola';
import 'node:path';
import 'std-env';
import 'node:url';
const devtools = defineCommand({
meta: {
name: "devtools",
description: "Enable or disable devtools in a Nuxt project"
},
args: {
...cwdArgs,
command: {
type: "positional",
description: "Command to run",
valueHint: "enable|disable"
},
...legacyRootDirArgs
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
if (!["enable", "disable"].includes(ctx.args.command)) {
logger.error(`Unknown command \`${ctx.args.command}\`.`);
process.exit(1);
}
await x(
"npx",
["@nuxt/devtools-wizard@latest", ctx.args.command, cwd],
{
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
}
);
}
});
export { devtools as default };
@@ -0,0 +1,45 @@
import { defineCommand } from 'citty';
import { l as legacyRootDirArgs, e as extendsArgs, b as envNameArgs, d as dotEnvArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import buildCommand from './build.mjs';
import 'node:path';
import 'node:process';
import 'std-env';
import 'consola';
import '../shared/cli.B9AmABr3.mjs';
import 'node:url';
import 'pathe';
import '../shared/cli.Dz2be-Ai.mjs';
import 'node:fs';
import 'consola/utils';
import 'exsolve';
import '../shared/cli.qKvs7FJ2.mjs';
import '../shared/cli.BEUGgaW4.mjs';
import '../shared/cli.pLQ0oPGc.mjs';
const generate = defineCommand({
meta: {
name: "generate",
description: "Build Nuxt and prerender all routes"
},
args: {
...cwdArgs,
...logLevelArgs,
preset: {
type: "string",
description: "Nitro server preset"
},
...dotEnvArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
ctx.args.prerender = true;
await buildCommand.run(
// @ts-expect-error types do not match
ctx
);
}
});
export { generate as default };
@@ -0,0 +1,466 @@
import process from 'node:process';
import defu from 'defu';
import { listen } from 'listhen';
import { Server } from 'node:http';
import { getSocketAddress, cleanSocket } from 'get-port-please';
import EventEmitter from 'node:events';
import { watch, existsSync } from 'node:fs';
import { mkdir } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
import { resolveModulePath } from 'exsolve';
import { toNodeListener } from 'h3';
import { resolve } from 'pathe';
import { debounce } from 'perfect-debounce';
import { provider } from 'std-env';
import { joinURL } from 'ufo';
import { a as clearBuildDir } from '../shared/cli.pLQ0oPGc.mjs';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as loadNuxtManifest, r as resolveNuxtManifest, w as writeNuxtManifest } from '../shared/cli.At9IMXtr.mjs';
import { Youch } from 'youch';
function formatSocketURL(socketPath, ssl = false) {
const protocol = ssl ? "https" : "http";
const encodedPath = process.platform === "win32" ? encodeURIComponent(socketPath) : socketPath.replace(/\//g, "%2F");
return `${protocol}+unix://${encodedPath}`;
}
function isSocketURL(url) {
return url.startsWith("http+unix://") || url.startsWith("https+unix://");
}
function parseSocketURL(url) {
if (!isSocketURL(url)) {
throw new Error(`Invalid socket URL: ${url}`);
}
const ssl = url.startsWith("https+unix://");
const path = url.slice(ssl ? "https+unix://".length : "http+unix://".length);
const socketPath = decodeURIComponent(path.replace(/%2F/g, "/"));
return { socketPath, protocol: ssl ? "https" : "http" };
}
async function createSocketListener(handler, proxyAddress) {
const socketPath = getSocketAddress({
name: "nuxt-dev",
random: true
});
const server = new Server(handler);
await cleanSocket(socketPath);
await new Promise((resolve) => server.listen({ path: socketPath }, resolve));
const url = formatSocketURL(socketPath);
return {
url,
address: { address: "localhost", port: 3e3, ...proxyAddress, socketPath },
async close() {
try {
server.removeAllListeners();
await new Promise((resolve, reject) => server.close((err) => err ? reject(err) : resolve()));
} finally {
await cleanSocket(socketPath);
}
},
getURLs: async () => [{ url, type: "network" }],
https: false,
server
};
}
async function renderError(req, res, error) {
const youch = new Youch();
res.statusCode = 500;
res.setHeader("Content-Type", "text/html");
const html = await youch.toHTML(error, {
request: {
url: req.url,
method: req.method,
headers: req.headers
}
});
res.end(html);
}
const RESTART_RE = /^(?:nuxt\.config\.[a-z0-9]+|\.nuxtignore|\.nuxtrc|\.config\/nuxt(?:\.config)?\.[a-z0-9]+)$/;
class NuxtDevServer extends EventEmitter {
constructor(options) {
super();
this.options = options;
this.loadDebounced = debounce(this.load);
let _initResolve;
const _initPromise = new Promise((resolve2) => {
_initResolve = resolve2;
});
this.once("ready", () => {
_initResolve();
});
this.cwd = options.cwd;
this.handler = async (req, res) => {
if (this._loadingError) {
this._renderError(req, res);
return;
}
await _initPromise;
if (this._handler) {
this._handler(req, res);
} else {
this._renderLoadingScreen(req, res);
}
};
this.listener = void 0;
}
_handler;
_distWatcher;
_configWatcher;
_currentNuxt;
_loadingMessage;
_loadingError;
cwd;
loadDebounced;
handler;
listener;
_renderError(req, res) {
renderError(req, res, this._loadingError);
}
async _renderLoadingScreen(req, res) {
res.statusCode = 503;
res.setHeader("Content-Type", "text/html");
const loadingTemplate = this.options.loadingTemplate || this._currentNuxt?.options.devServer.loadingTemplate || await resolveLoadingTemplate(this.cwd);
res.end(
loadingTemplate({
loading: this._loadingMessage || "Loading..."
})
);
}
async init() {
await this.load();
this._watchConfig();
}
closeWatchers() {
this._distWatcher?.close();
this._configWatcher?.();
}
async load(reload, reason) {
try {
await this._load(reload, reason);
this._loadingError = void 0;
} catch (error) {
console.error(`Cannot ${reload ? "restart" : "start"} nuxt: `, error);
this._handler = void 0;
this._loadingError = error;
this._loadingMessage = "Error while loading Nuxt. Please check console and fix errors.";
this.emit("loading:error", error);
}
}
async close() {
if (this._currentNuxt) {
await this._currentNuxt.close();
}
}
async _load(reload, reason) {
const action = reload ? "Restarting" : "Starting";
this._loadingMessage = `${reason ? `${reason}. ` : ""}${action} Nuxt...`;
this._handler = void 0;
this.emit("loading", this._loadingMessage);
if (reload) {
console.info(this._loadingMessage);
}
await this.close();
const kit = await loadKit(this.options.cwd);
const devServerDefaults = resolveDevServerDefaults({}, await this.listener.getURLs().then((r) => r.map((r2) => r2.url)));
this._currentNuxt = await kit.loadNuxt({
cwd: this.options.cwd,
dev: true,
ready: false,
envName: this.options.envName,
dotenv: {
cwd: this.options.cwd,
fileName: this.options.dotenv.fileName
},
defaults: defu(this.options.defaults, devServerDefaults),
overrides: {
logLevel: this.options.logLevel,
...this.options.overrides,
vite: {
clearScreen: this.options.clear,
...this.options.overrides.vite
}
}
});
if (!process.env.NUXI_DISABLE_VITE_HMR) {
this._currentNuxt.hooks.hook("vite:extend", ({ config }) => {
if (config.server) {
config.server.hmr = {
protocol: void 0,
...config.server.hmr,
port: void 0,
host: void 0,
server: this.listener.server
};
}
});
}
this._currentNuxt.hooks.hookOnce("close", () => {
this.listener.server.removeAllListeners("upgrade");
});
if (!reload) {
const previousManifest = await loadNuxtManifest(this._currentNuxt.options.buildDir);
const newManifest = resolveNuxtManifest(this._currentNuxt);
const promise = writeNuxtManifest(this._currentNuxt, newManifest);
this._currentNuxt.hooks.hookOnce("ready", async () => {
await promise;
});
if (previousManifest && newManifest && previousManifest._hash !== newManifest._hash) {
await clearBuildDir(this._currentNuxt.options.buildDir);
}
}
await this._currentNuxt.ready();
const unsub = this._currentNuxt.hooks.hook("restart", async (options) => {
unsub();
if (options?.hard) {
this.emit("restart");
return;
}
await this.load(true);
});
if (this._currentNuxt.server && "upgrade" in this._currentNuxt.server) {
this.listener.server.on("upgrade", (req, socket, head) => {
const nuxt = this._currentNuxt;
if (!nuxt || !nuxt.server)
return;
const viteHmrPath = joinURL(
nuxt.options.app.baseURL.startsWith("./") ? nuxt.options.app.baseURL.slice(1) : nuxt.options.app.baseURL,
nuxt.options.app.buildAssetsDir
);
if (req.url?.startsWith(viteHmrPath)) {
return;
}
nuxt.server.upgrade(req, socket, head);
});
}
await this._currentNuxt.hooks.callHook("listen", this.listener.server, this.listener);
const addr = this.listener.address;
this._currentNuxt.options.devServer.host = addr.address;
this._currentNuxt.options.devServer.port = addr.port;
this._currentNuxt.options.devServer.url = getAddressURL(addr, !!this.listener.https);
this._currentNuxt.options.devServer.https = this.options.devContext.proxy?.https;
if (this.listener.https && !process.env.NODE_TLS_REJECT_UNAUTHORIZED) {
console.warn("You might need `NODE_TLS_REJECT_UNAUTHORIZED=0` environment variable to make https work.");
}
await Promise.all([
kit.writeTypes(this._currentNuxt).catch(console.error),
kit.buildNuxt(this._currentNuxt)
]);
if (!this._currentNuxt.server) {
throw new Error("Nitro server has not been initialized.");
}
const distDir = resolve(this._currentNuxt.options.buildDir, "dist");
await mkdir(distDir, { recursive: true });
this._distWatcher = watch(distDir);
this._distWatcher.on("change", () => {
this.loadDebounced(true, ".nuxt/dist directory has been removed");
});
this._handler = toNodeListener(this._currentNuxt.server.app);
this.emit("ready", "socketPath" in addr ? formatSocketURL(addr.socketPath, !!this.listener.https) : `http://127.0.0.1:${addr.port}`);
}
_watchConfig() {
this._configWatcher = createConfigWatcher(
this.cwd,
this.options.dotenv.fileName,
() => this.emit("restart"),
(file) => this.loadDebounced(true, `${file} updated`)
);
}
}
function getAddressURL(addr, https) {
const proto = https ? "https" : "http";
let host = addr.address.includes(":") ? `[${addr.address}]` : addr.address;
if (host === "[::]") {
host = "localhost";
}
const port = addr.port || 3e3;
return `${proto}://${host}:${port}/`;
}
function resolveDevServerOverrides(listenOptions) {
if (listenOptions.public || provider === "codesandbox") {
return {
devServer: { cors: { origin: "*" } },
vite: { server: { allowedHosts: true } }
};
}
return {};
}
function resolveDevServerDefaults(listenOptions, urls = []) {
const defaultConfig = {};
if (urls) {
defaultConfig.vite = {
server: {
allowedHosts: urls.filter((u) => !isSocketURL(u)).map((u) => new URL(u).hostname)
}
};
}
if (listenOptions.hostname) {
const protocol = listenOptions.https ? "https" : "http";
defaultConfig.devServer = { cors: { origin: [`${protocol}://${listenOptions.hostname}`, ...urls] } };
defaultConfig.vite = defu(defaultConfig.vite, { server: { allowedHosts: [listenOptions.hostname] } });
}
return defaultConfig;
}
function createConfigWatcher(cwd, dotenvFileName = ".env", onRestart, onReload) {
const configWatcher = watch(cwd);
let configDirWatcher = existsSync(resolve(cwd, ".config")) ? createConfigDirWatcher(cwd, onReload) : void 0;
const dotenvFileNames = new Set(Array.isArray(dotenvFileName) ? dotenvFileName : [dotenvFileName]);
configWatcher.on("change", (_event, file) => {
if (dotenvFileNames.has(file)) {
onRestart();
}
if (RESTART_RE.test(file)) {
onReload(file);
}
if (file === ".config") {
configDirWatcher ||= createConfigDirWatcher(cwd, onReload);
}
});
return () => {
configWatcher.close();
configDirWatcher?.();
};
}
function createConfigDirWatcher(cwd, onReload) {
const configDir = resolve(cwd, ".config");
const configDirWatcher = watch(configDir);
configDirWatcher.on("change", (_event, file) => {
if (RESTART_RE.test(file)) {
onReload(file);
}
});
return () => configDirWatcher.close();
}
async function resolveLoadingTemplate(cwd) {
const nuxtPath = resolveModulePath("nuxt", { from: cwd, try: true });
const uiTemplatesPath = resolveModulePath("@nuxt/ui-templates", { from: nuxtPath || cwd });
const r = await import(pathToFileURL(uiTemplatesPath).href);
return r.loading || ((params) => `<h2>${params.loading}</h2>`);
}
const start = Date.now();
process.env.NODE_ENV = "development";
class IPC {
enabled = !!process.send && !process.title?.includes("vitest") && process.env.__NUXT__FORK;
constructor() {
if (this.enabled) {
process.once("unhandledRejection", (reason) => {
this.send({ type: "nuxt:internal:dev:rejection", message: reason instanceof Error ? reason.toString() : "Unhandled Rejection" });
process.exit();
});
}
process.on("message", (message) => {
if (message.type === "nuxt:internal:dev:context") {
initialize(message.context, {}, message.socket ? void 0 : true);
}
});
this.send({ type: "nuxt:internal:dev:fork-ready" });
}
send(message) {
if (this.enabled) {
process.send?.(message);
}
}
}
const ipc = new IPC();
async function initialize(devContext, ctx = {}, _listenOptions) {
const devServerOverrides = resolveDevServerOverrides({
public: devContext.public
});
const devServerDefaults = resolveDevServerDefaults({
hostname: devContext.hostname,
https: devContext.proxy?.https
}, devContext.publicURLs);
const devServer = new NuxtDevServer({
cwd: devContext.cwd,
overrides: defu(
ctx.data?.overrides,
{ extends: devContext.args.extends },
devServerOverrides
),
defaults: devServerDefaults,
logLevel: devContext.args.logLevel,
clear: !!devContext.args.clear,
dotenv: { cwd: devContext.cwd, fileName: devContext.args.dotenv },
envName: devContext.args.envName,
devContext: {
proxy: devContext.proxy
}
});
const listenOptions = _listenOptions === true || process.env._PORT ? { port: process.env._PORT ?? 0, hostname: "127.0.0.1", showURL: false } : _listenOptions;
devServer.listener = listenOptions ? await listen(devServer.handler, listenOptions) : await createSocketListener(devServer.handler, devContext.proxy?.addr);
if (process.env.DEBUG) {
console.debug(`Using ${listenOptions ? "network" : "socket"} listener for Nuxt dev server.`);
}
devServer.listener._url = devServer.listener.url;
if (devContext.proxy?.url) {
devServer.listener.url = devContext.proxy.url;
}
if (devContext.proxy?.urls) {
const _getURLs = devServer.listener.getURLs.bind(devServer.listener);
devServer.listener.getURLs = async () => Array.from(/* @__PURE__ */ new Set([...devContext.proxy?.urls || [], ...await _getURLs()]));
}
let address;
if (ipc.enabled) {
devServer.on("loading:error", (_error) => {
ipc.send({
type: "nuxt:internal:dev:loading:error",
error: {
message: _error.message,
stack: _error.stack,
name: _error.name,
code: "code" in _error ? _error.code : void 0
}
});
});
devServer.on("loading", (message) => {
ipc.send({ type: "nuxt:internal:dev:loading", message });
});
devServer.on("restart", () => {
ipc.send({ type: "nuxt:internal:dev:restart" });
});
devServer.on("ready", (payload) => {
ipc.send({ type: "nuxt:internal:dev:ready", address: payload });
});
} else {
devServer.on("ready", (payload) => {
address = payload;
});
}
await devServer.init();
if (process.env.DEBUG) {
console.debug(`Dev server (internal) initialized in ${Date.now() - start}ms`);
}
return {
listener: devServer.listener,
close: async () => {
devServer.closeWatchers();
await devServer.close();
},
onReady: (callback) => {
if (address) {
callback(address);
} else {
devServer.once("ready", (payload) => callback(payload));
}
},
onRestart: (callback) => {
let restarted = false;
function restart() {
if (!restarted) {
restarted = true;
callback(devServer);
}
}
devServer.once("restart", restart);
process.once("uncaughtException", restart);
process.once("unhandledRejection", restart);
}
};
}
const index = {
__proto__: null,
initialize: initialize
};
export { renderError as a, isSocketURL as b, index as c, initialize as i, parseSocketURL as p, resolveLoadingTemplate as r };
@@ -0,0 +1,15 @@
import { defineCommand } from 'citty';
const index = defineCommand({
meta: {
name: "module",
description: "Manage Nuxt modules"
},
args: {},
subCommands: {
add: () => import('./add.mjs').then((r) => r.default || r),
search: () => import('./search.mjs').then((r) => r.default || r)
}
});
export { index as default };
@@ -0,0 +1,149 @@
import os from 'node:os';
import process from 'node:process';
import { defineCommand } from 'citty';
import clipboardy from 'clipboardy';
import { detectPackageManager } from 'nypm';
import { resolve } from 'pathe';
import { readPackageJSON } from 'pkg-types';
import { splitByCase } from 'scule';
import { isMinimal } from 'std-env';
import { v as version } from '../shared/cli.DhJ3cH8w.mjs';
import { t as tryResolveNuxt } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { g as getPackageManagerVersion } from '../shared/cli.BSm0_9Hr.mjs';
import { l as legacyRootDirArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'exsolve';
import 'consola';
import 'node:child_process';
import 'node:path';
const info = defineCommand({
meta: {
name: "info",
description: "Get information about Nuxt project"
},
args: {
...cwdArgs,
...legacyRootDirArgs
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const nuxtConfig = await getNuxtConfig(cwd);
const { dependencies = {}, devDependencies = {} } = await readPackageJSON(cwd).catch(() => ({}));
const nuxtPath = tryResolveNuxt(cwd);
async function getDepVersion(name) {
for (const url of [cwd, nuxtPath]) {
if (!url) {
continue;
}
const pkg = await readPackageJSON(name, { url }).catch(() => null);
if (pkg) {
return pkg.version;
}
}
return dependencies[name] || devDependencies[name];
}
async function listModules(arr = []) {
const info = [];
for (let m of arr) {
if (Array.isArray(m)) {
m = m[0];
}
const name = normalizeConfigModule(m, cwd);
if (name) {
const npmName = name.split("/").splice(0, 2).join("/");
const v = await getDepVersion(npmName);
info.push(`\`${v ? `${name}@${v}` : name}\``);
}
}
return info.join(", ");
}
const nuxtVersion = await getDepVersion("nuxt") || await getDepVersion("nuxt-nightly") || await getDepVersion("nuxt-edge") || await getDepVersion("nuxt3") || "-";
const isLegacy = nuxtVersion.startsWith("2");
const builder = !isLegacy ? nuxtConfig.builder || "-" : nuxtConfig.bridge?.vite ? "vite" : nuxtConfig.buildModules?.includes("nuxt-vite") ? "vite" : "webpack";
let packageManager = (await detectPackageManager(cwd))?.name;
if (packageManager) {
packageManager += `@${getPackageManagerVersion(packageManager)}`;
}
const infoObj = {
OperatingSystem: os.type(),
NodeVersion: process.version,
NuxtVersion: nuxtVersion,
CLIVersion: version,
NitroVersion: await getDepVersion("nitropack"),
PackageManager: packageManager ?? "unknown",
Builder: typeof builder === "string" ? builder : "custom",
UserConfig: Object.keys(nuxtConfig).map((key) => `\`${key}\``).join(", "),
RuntimeModules: await listModules(nuxtConfig.modules),
BuildModules: await listModules(nuxtConfig.buildModules || [])
};
logger.log("Working directory:", cwd);
let maxLength = 0;
const entries = Object.entries(infoObj).map(([key, val]) => {
const label = splitByCase(key).join(" ");
if (label.length > maxLength) {
maxLength = label.length;
}
return [label, val || "-"];
});
let infoStr = "";
for (const [label, value] of entries) {
infoStr += `- ${`${label}: `.padEnd(maxLength + 2)}${value.includes("`") ? value : `\`${value}\``}
`;
}
const copied = !isMinimal && await clipboardy.write(infoStr).then(() => true).catch(() => false);
const isNuxt3 = !isLegacy;
const isBridge = !isNuxt3 && infoObj.BuildModules.includes("bridge");
const repo = isBridge ? "nuxt/bridge" : "nuxt/nuxt";
const log = [
(isNuxt3 || isBridge) && `\u{1F449} Report an issue: https://github.com/${repo}/issues/new?template=bug-report.yml`,
(isNuxt3 || isBridge) && `\u{1F449} Suggest an improvement: https://github.com/${repo}/discussions/new`,
`\u{1F449} Read documentation: ${isNuxt3 || isBridge ? "https://nuxt.com" : "https://v2.nuxt.com"}`
].filter(Boolean).join("\n");
const splitter = "------------------------------";
logger.log(`Nuxt project info: ${copied ? "(copied to clipboard)" : ""}
${splitter}
${infoStr}${splitter}
${log}
`);
}
});
function normalizeConfigModule(module, rootDir) {
if (!module) {
return null;
}
if (typeof module === "string") {
return module.split(rootDir).pop().split("node_modules").pop().replace(/^\//, "");
}
if (typeof module === "function") {
return `${module.name}()`;
}
if (Array.isArray(module)) {
return normalizeConfigModule(module[0], rootDir);
}
return null;
}
async function getNuxtConfig(rootDir) {
try {
const { createJiti } = await import('jiti');
const jiti = createJiti(rootDir, {
interopDefault: true,
// allow using `~` and `@` in `nuxt.config`
alias: {
"~": rootDir,
"@": rootDir
}
});
globalThis.defineNuxtConfig = (c) => c;
const result = await jiti.import("./nuxt.config", { default: true });
delete globalThis.defineNuxtConfig;
return result;
} catch {
return {};
}
}
export { info as default };
@@ -0,0 +1,388 @@
import { existsSync } from 'node:fs';
import process from 'node:process';
import { defineCommand } from 'citty';
import { colors } from 'consola/utils';
import { downloadTemplate, startShell } from 'giget';
import { installDependencies } from 'nypm';
import { $fetch } from 'ofetch';
import { resolve, relative, join } from 'pathe';
import { readPackageJSON, writePackageJSON } from 'pkg-types';
import { hasTTY } from 'std-env';
import { x } from 'tinyexec';
import { r as runCommand } from '../shared/cli.vXg4eLNu.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'node:crypto';
import 'node:path';
import '../shared/cli.DhJ3cH8w.mjs';
import 'consola';
const themeColor = "\x1B[38;2;0;220;130m";
const icon = [
` .d$b.`,
` i$$A$$L .d$b`,
` .$$F\` \`$$L.$$A$$.`,
` j$$' \`4$$:\` \`$$.`,
` j$$' .4$: \`$$.`,
` j$$\` .$$: \`4$L`,
` :$$:____.d$$: _____.:$$:`,
` \`4$$$$$$$$P\` .i$$$$$$$$P\``
];
const nuxtIcon = icon.map((line) => line.split("").join(themeColor)).join("\n");
const DEFAULT_REGISTRY = "https://raw.githubusercontent.com/nuxt/starter/templates/templates";
const DEFAULT_TEMPLATE_NAME = "v4";
const pms = {
npm: void 0,
pnpm: void 0,
yarn: void 0,
bun: void 0,
deno: void 0
};
const packageManagerOptions = Object.keys(pms);
async function getModuleDependencies(moduleName) {
try {
const response = await $fetch(`https://registry.npmjs.org/${moduleName}/latest`);
const dependencies = response.dependencies || {};
return Object.keys(dependencies);
} catch (err) {
logger.warn(`Could not get dependencies for ${moduleName}: ${err}`);
return [];
}
}
function filterModules(modules, allDependencies) {
const result = {
toInstall: [],
skipped: []
};
for (const module of modules) {
const isDependency = modules.some((otherModule) => {
if (otherModule === module)
return false;
const deps = allDependencies[otherModule] || [];
return deps.includes(module);
});
if (isDependency) {
result.skipped.push(module);
} else {
result.toInstall.push(module);
}
}
return result;
}
async function getTemplateDependencies(templateDir) {
try {
const packageJsonPath = join(templateDir, "package.json");
if (!existsSync(packageJsonPath)) {
return [];
}
const packageJson = await import(packageJsonPath);
const directDeps = {
...packageJson.dependencies,
...packageJson.devDependencies
};
const directDepNames = Object.keys(directDeps);
const allDeps = new Set(directDepNames);
const transitiveDepsResults = await Promise.all(
directDepNames.map((dep) => getModuleDependencies(dep))
);
transitiveDepsResults.forEach((deps) => {
deps.forEach((dep) => allDeps.add(dep));
});
return Array.from(allDeps);
} catch (err) {
logger.warn(`Could not read template dependencies: ${err}`);
return [];
}
}
const init = defineCommand({
meta: {
name: "init",
description: "Initialize a fresh project"
},
args: {
...cwdArgs,
...logLevelArgs,
dir: {
type: "positional",
description: "Project directory",
default: ""
},
template: {
type: "string",
alias: "t",
description: "Template name"
},
force: {
type: "boolean",
alias: "f",
description: "Override existing directory"
},
offline: {
type: "boolean",
description: "Force offline mode"
},
preferOffline: {
type: "boolean",
description: "Prefer offline mode"
},
install: {
type: "boolean",
default: true,
description: "Skip installing dependencies"
},
gitInit: {
type: "boolean",
description: "Initialize git repository"
},
shell: {
type: "boolean",
description: "Start shell after installation in project directory"
},
packageManager: {
type: "string",
description: "Package manager choice (npm, pnpm, yarn, bun)"
},
modules: {
type: "string",
required: false,
description: "Nuxt modules to install (comma separated without spaces)",
negativeDescription: "Skip module installation prompt",
alias: "M"
},
nightly: {
type: "string",
description: "Use Nuxt nightly release channel (3x or latest)"
}
},
async run(ctx) {
if (hasTTY) {
process.stdout.write(`
${nuxtIcon}
`);
}
logger.info(colors.bold(`Welcome to Nuxt!`.split("").map((m) => `${themeColor}${m}`).join("")));
if (ctx.args.dir === "") {
ctx.args.dir = await logger.prompt("Where would you like to create your project?", {
placeholder: "./nuxt-app",
type: "text",
default: "nuxt-app",
cancel: "reject"
}).catch(() => process.exit(1));
}
const cwd = resolve(ctx.args.cwd);
let templateDownloadPath = resolve(cwd, ctx.args.dir);
logger.info(`Creating a new project in ${colors.cyan(relative(cwd, templateDownloadPath) || templateDownloadPath)}.`);
const templateName = ctx.args.template || DEFAULT_TEMPLATE_NAME;
if (typeof templateName !== "string") {
logger.error("Please specify a template!");
process.exit(1);
}
let shouldForce = Boolean(ctx.args.force);
const shouldVerify = !shouldForce && existsSync(templateDownloadPath);
if (shouldVerify) {
const selectedAction = await logger.prompt(
`The directory ${colors.cyan(templateDownloadPath)} already exists. What would you like to do?`,
{
type: "select",
options: ["Override its contents", "Select different directory", "Abort"]
}
);
switch (selectedAction) {
case "Override its contents":
shouldForce = true;
break;
case "Select different directory": {
templateDownloadPath = resolve(cwd, await logger.prompt("Please specify a different directory:", {
type: "text",
cancel: "reject"
}).catch(() => process.exit(1)));
break;
}
// 'Abort' or Ctrl+C
default:
process.exit(1);
}
}
let template;
try {
template = await downloadTemplate(templateName, {
dir: templateDownloadPath,
force: shouldForce,
offline: Boolean(ctx.args.offline),
preferOffline: Boolean(ctx.args.preferOffline),
registry: process.env.NUXI_INIT_REGISTRY || DEFAULT_REGISTRY
});
} catch (err) {
if (process.env.DEBUG) {
throw err;
}
logger.error(err.toString());
process.exit(1);
}
if (ctx.args.nightly !== void 0 && !ctx.args.offline && !ctx.args.preferOffline) {
const response = await $fetch("https://registry.npmjs.org/nuxt-nightly");
const nightlyChannelTag = ctx.args.nightly || "latest";
const nightlyChannelVersion = response["dist-tags"][nightlyChannelTag];
if (!nightlyChannelVersion) {
logger.error(`Nightly channel version for tag '${nightlyChannelTag}' not found.`);
process.exit(1);
}
const nightlyNuxtPackageJsonVersion = `npm:nuxt-nightly@${nightlyChannelVersion}`;
const packageJsonPath = resolve(cwd, ctx.args.dir);
const packageJson = await readPackageJSON(packageJsonPath);
if (packageJson.dependencies && "nuxt" in packageJson.dependencies) {
packageJson.dependencies.nuxt = nightlyNuxtPackageJsonVersion;
} else if (packageJson.devDependencies && "nuxt" in packageJson.devDependencies) {
packageJson.devDependencies.nuxt = nightlyNuxtPackageJsonVersion;
}
await writePackageJSON(join(packageJsonPath, "package.json"), packageJson);
}
function detectCurrentPackageManager() {
const userAgent = process.env.npm_config_user_agent;
if (!userAgent) {
return;
}
const [name] = userAgent.split("/");
if (packageManagerOptions.includes(name)) {
return name;
}
}
const currentPackageManager = detectCurrentPackageManager();
const packageManagerArg = ctx.args.packageManager;
const packageManagerSelectOptions = packageManagerOptions.map((pm) => ({
label: pm,
value: pm,
hint: currentPackageManager === pm ? "current" : void 0
}));
const selectedPackageManager = packageManagerOptions.includes(packageManagerArg) ? packageManagerArg : await logger.prompt("Which package manager would you like to use?", {
type: "select",
options: packageManagerSelectOptions,
initial: currentPackageManager,
cancel: "reject"
}).catch(() => process.exit(1));
if (ctx.args.install === false) {
logger.info("Skipping install dependencies step.");
} else {
logger.start("Installing dependencies...");
try {
await installDependencies({
cwd: template.dir,
packageManager: {
name: selectedPackageManager,
command: selectedPackageManager
}
});
} catch (err) {
if (process.env.DEBUG) {
throw err;
}
logger.error(err.toString());
process.exit(1);
}
logger.success("Installation completed.");
}
if (ctx.args.gitInit === void 0) {
ctx.args.gitInit = await logger.prompt("Initialize git repository?", {
type: "confirm",
cancel: "reject"
}).catch(() => process.exit(1));
}
if (ctx.args.gitInit) {
logger.info("Initializing git repository...\n");
try {
await x("git", ["init", template.dir], {
throwOnError: true,
nodeOptions: {
stdio: "inherit"
}
});
} catch (err) {
logger.warn(`Failed to initialize git repository: ${err}`);
}
}
const modulesToAdd = [];
if (ctx.args.modules !== void 0) {
modulesToAdd.push(
...(ctx.args.modules || "").split(",").map((module) => module.trim()).filter(Boolean)
);
} else if (!ctx.args.offline && !ctx.args.preferOffline) {
const modulesPromise = $fetch("https://api.nuxt.com/modules");
const wantsUserModules = await logger.prompt(
`Would you like to install any of the official modules?`,
{
type: "confirm",
cancel: "reject"
}
).catch(() => process.exit(1));
if (wantsUserModules) {
const [response, templateDeps] = await Promise.all([
modulesPromise,
getTemplateDependencies(template.dir)
]);
const officialModules = response.modules.filter((module) => module.type === "official" && module.npm !== "@nuxt/devtools").filter((module) => !templateDeps.includes(module.npm));
if (officialModules.length === 0) {
logger.info("All official modules are already included in this template.");
} else {
const selectedOfficialModules = await logger.prompt(
"Pick the modules to install:",
{
type: "multiselect",
options: officialModules.map((module) => ({
label: `${colors.bold(colors.greenBright(module.npm))} \u2013 ${module.description.replace(/\.$/, "")}`,
value: module.npm
})),
required: false
}
);
if (selectedOfficialModules === void 0) {
process.exit(1);
}
if (selectedOfficialModules.length > 0) {
const modules = selectedOfficialModules;
const allDependencies = Object.fromEntries(
await Promise.all(modules.map(
async (module) => [module, await getModuleDependencies(module)]
))
);
const { toInstall, skipped } = filterModules(modules, allDependencies);
if (skipped.length) {
logger.info(`The following modules are already included as dependencies of another module and will not be installed: ${skipped.map((m) => colors.cyan(m)).join(", ")}`);
}
modulesToAdd.push(...toInstall);
}
}
}
}
if (modulesToAdd.length > 0) {
const args = [
"add",
...modulesToAdd,
`--cwd=${templateDownloadPath}`,
ctx.args.install ? "" : "--skipInstall",
ctx.args.logLevel ? `--logLevel=${ctx.args.logLevel}` : ""
].filter(Boolean);
await runCommand("module", args);
}
logger.log(
`
\u2728 Nuxt project has been created with the \`${template.name}\` template. Next steps:`
);
const relativeTemplateDir = relative(process.cwd(), template.dir) || ".";
const runCmd = selectedPackageManager === "deno" ? "task" : "run";
const nextSteps = [
!ctx.args.shell && relativeTemplateDir.length > 1 && `\`cd ${relativeTemplateDir}\``,
`Start development server with \`${selectedPackageManager} ${runCmd} dev\``
].filter(Boolean);
for (const step of nextSteps) {
logger.log(` \u203A ${step}`);
}
if (ctx.args.shell) {
startShell(template.dir);
}
}
});
export { init as default };
@@ -0,0 +1,57 @@
import process from 'node:process';
import { defineCommand } from 'citty';
import { resolve, relative } from 'pathe';
import { a as clearBuildDir } from '../shared/cli.pLQ0oPGc.mjs';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { l as legacyRootDirArgs, e as extendsArgs, b as envNameArgs, a as logLevelArgs, c as cwdArgs, d as dotEnvArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:fs';
import 'node:url';
import 'exsolve';
import 'consola';
import 'node:path';
import 'std-env';
const prepare = defineCommand({
meta: {
name: "prepare",
description: "Prepare Nuxt for development/build"
},
args: {
...dotEnvArgs,
...cwdArgs,
...logLevelArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "production";
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { loadNuxt, buildNuxt, writeTypes } = await loadKit(cwd);
const nuxt = await loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv
},
envName: ctx.args.envName,
// c12 will fall back to NODE_ENV
overrides: {
_prepare: true,
logLevel: ctx.args.logLevel,
...ctx.args.extends && { extends: ctx.args.extends },
...ctx.data?.overrides
}
});
await clearBuildDir(nuxt.options.buildDir);
await buildNuxt(nuxt);
await writeTypes(nuxt);
logger.success(
"Types generated in",
relative(process.cwd(), nuxt.options.buildDir)
);
}
});
export { prepare as default };
@@ -0,0 +1,131 @@
import { existsSync, promises } from 'node:fs';
import { dirname, relative } from 'node:path';
import process from 'node:process';
import { setupDotenv } from 'c12';
import { defineCommand } from 'citty';
import { box, colors } from 'consola/utils';
import { getArgs } from 'listhen/cli';
import { resolve } from 'pathe';
import { x } from 'tinyexec';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { d as dotEnvArgs, l as legacyRootDirArgs, e as extendsArgs, b as envNameArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'exsolve';
import 'consola';
import 'std-env';
const command = defineCommand({
meta: {
name: "preview",
description: "Launches Nitro server for local testing after `nuxi build`."
},
args: {
...cwdArgs,
...logLevelArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs,
port: getArgs().port,
...dotEnvArgs
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "production";
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { loadNuxt } = await loadKit(cwd);
const resolvedOutputDir = await new Promise((res) => {
loadNuxt({
cwd,
envName: ctx.args.envName,
// c12 will fall back to NODE_ENV
ready: true,
overrides: {
...ctx.args.extends && { extends: ctx.args.extends },
modules: [
function(_, nuxt) {
nuxt.hook("nitro:init", (nitro) => {
res(resolve(nuxt.options.srcDir || cwd, nitro.options.output.dir || ".output", "nitro.json"));
});
}
]
}
}).then((nuxt) => nuxt.close()).catch(() => "");
});
const defaultOutput = resolve(cwd, ".output", "nitro.json");
const nitroJSONPaths = [resolvedOutputDir, defaultOutput].filter(Boolean);
const nitroJSONPath = nitroJSONPaths.find((p) => existsSync(p));
if (!nitroJSONPath) {
logger.error(
"Cannot find `nitro.json`. Did you run `nuxi build` first? Search path:\n",
nitroJSONPaths
);
process.exit(1);
}
const outputPath = dirname(nitroJSONPath);
const nitroJSON = JSON.parse(await promises.readFile(nitroJSONPath, "utf-8"));
if (!nitroJSON.commands.preview) {
logger.error("Preview is not supported for this build.");
process.exit(1);
}
const info = [
["Node.js:", `v${process.versions.node}`],
["Nitro Preset:", nitroJSON.preset],
["Working directory:", relative(process.cwd(), outputPath)]
];
const _infoKeyLen = Math.max(...info.map(([label]) => label.length));
logger.log(
box(
[
"You are running Nuxt production build in preview mode.",
`For production deployments, please directly use ${colors.cyan(
nitroJSON.commands.preview
)} command.`,
"",
...info.map(
([label, value]) => `${label.padEnd(_infoKeyLen, " ")} ${colors.cyan(value)}`
)
].join("\n"),
{
title: colors.yellow("Preview Mode"),
style: {
borderColor: "yellow"
}
}
)
);
const envFileName = ctx.args.dotenv || ".env";
const envExists = existsSync(resolve(cwd, envFileName));
if (envExists) {
logger.info(
`Loading \`${envFileName}\`. This will not be loaded when running the server in production.`
);
await setupDotenv({ cwd, fileName: envFileName });
} else if (ctx.args.dotenv) {
logger.error(`Cannot find \`${envFileName}\`.`);
}
const { port } = _resolveListenOptions(ctx.args);
logger.info(`Starting preview command: \`${nitroJSON.commands.preview}\``);
const [command2, ...commandArgs] = nitroJSON.commands.preview.split(" ");
logger.log("");
await x(command2, commandArgs, {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd: outputPath,
env: {
...process.env,
NUXT_PORT: port,
NITRO_PORT: port
}
}
});
}
});
function _resolveListenOptions(args) {
const _port = args.port ?? args.p ?? process.env.NUXT_PORT ?? process.env.NITRO_PORT ?? process.env.PORT;
return {
port: _port
};
}
export { command as default };
@@ -0,0 +1,114 @@
import { defineCommand } from 'citty';
import { colors } from 'consola/utils';
import Fuse from 'fuse.js';
import { upperFirst, kebabCase } from 'scule';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { g as getNuxtVersion } from '../shared/cli.DHenkA1C.mjs';
import { c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import { f as fetchModules, c as checkNuxtCompatibility } from '../shared/cli.Cr-OCgdO.mjs';
import 'consola';
import 'pkg-types';
import 'semver';
import 'node:path';
import 'node:process';
import 'std-env';
import 'node:url';
import 'confbox';
import 'ofetch';
const { format: formatNumber } = Intl.NumberFormat("en-GB", {
notation: "compact",
maximumFractionDigits: 1
});
const search = defineCommand({
meta: {
name: "search",
description: "Search in Nuxt modules"
},
args: {
...cwdArgs,
query: {
type: "positional",
description: "keywords to search for",
required: true
},
nuxtVersion: {
type: "string",
description: "Filter by Nuxt version and list compatible modules only (auto detected by default)",
required: false,
valueHint: "2|3"
}
},
async setup(ctx) {
const nuxtVersion = await getNuxtVersion(ctx.args.cwd);
return findModuleByKeywords(ctx.args._.join(" "), nuxtVersion);
}
});
async function findModuleByKeywords(query, nuxtVersion) {
const allModules = await fetchModules();
const compatibleModules = allModules.filter(
(m) => checkNuxtCompatibility(m, nuxtVersion)
);
const fuse = new Fuse(compatibleModules, {
threshold: 0.1,
keys: [
{ name: "name", weight: 1 },
{ name: "npm", weight: 1 },
{ name: "repo", weight: 1 },
{ name: "tags", weight: 1 },
{ name: "category", weight: 1 },
{ name: "description", weight: 0.5 },
{ name: "maintainers.name", weight: 0.5 },
{ name: "maintainers.github", weight: 0.5 }
]
});
const { bold, green, magenta, cyan, gray, yellow } = colors;
const results = fuse.search(query).map((result) => {
const res = {
name: bold(result.item.name),
homepage: cyan(result.item.website),
compatibility: `nuxt: ${result.item.compatibility?.nuxt || "*"}`,
repository: gray(result.item.github),
description: gray(result.item.description),
package: gray(result.item.npm),
install: cyan(`npx nuxi module add ${result.item.name}`),
stars: yellow(formatNumber(result.item.stats.stars)),
monthlyDownloads: yellow(formatNumber(result.item.stats.downloads))
};
if (result.item.github === result.item.website) {
delete res.homepage;
}
if (result.item.name === result.item.npm) {
delete res.packageName;
}
return res;
});
if (!results.length) {
logger.info(
`No Nuxt modules found matching query ${magenta(query)} for Nuxt ${cyan(nuxtVersion)}`
);
return;
}
logger.success(
`Found ${results.length} Nuxt ${results.length > 1 ? "modules" : "module"} matching ${cyan(query)} ${nuxtVersion ? `for Nuxt ${cyan(nuxtVersion)}` : ""}:
`
);
for (const foundModule of results) {
let maxLength = 0;
const entries = Object.entries(foundModule).map(([key, val]) => {
const label = upperFirst(kebabCase(key)).replace(/-/g, " ");
if (label.length > maxLength) {
maxLength = label.length;
}
return [label, val || "-"];
});
let infoStr = "";
for (const [label, value] of entries) {
infoStr += `${bold(label === "Install" ? "\u2192 " : "- ") + green(label.padEnd(maxLength + 2)) + value}
`;
}
logger.log(infoStr);
}
}
export { search as default };
@@ -0,0 +1,62 @@
import process from 'node:process';
import { defineCommand } from 'citty';
import { resolve } from 'pathe';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { l as legacyRootDirArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'consola';
import 'node:path';
import 'std-env';
import 'node:url';
const test = defineCommand({
meta: {
name: "test",
description: "Run tests"
},
args: {
...cwdArgs,
...logLevelArgs,
...legacyRootDirArgs,
dev: {
type: "boolean",
description: "Run in dev mode"
},
watch: {
type: "boolean",
description: "Watch mode"
}
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "test";
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { runTests } = await importTestUtils();
await runTests({
rootDir: cwd,
dev: ctx.args.dev,
watch: ctx.args.watch,
...{}
});
}
});
async function importTestUtils() {
let err;
for (const pkg of [
"@nuxt/test-utils-nightly",
"@nuxt/test-utils-edge",
"@nuxt/test-utils"
]) {
try {
const exports = await import(pkg);
if (!exports.runTests) {
throw new Error("Invalid version of `@nuxt/test-utils` is installed!");
}
return exports;
} catch (_err) {
err = _err;
}
}
logger.error(err);
throw new Error("`@nuxt/test-utils` seems missing. Run `npm i -D @nuxt/test-utils` or `yarn add -D @nuxt/test-utils` to install.");
}
export { test as default };
@@ -0,0 +1,85 @@
import process from 'node:process';
import { defineCommand } from 'citty';
import { resolveModulePath } from 'exsolve';
import { resolve } from 'pathe';
import { readTSConfig } from 'pkg-types';
import { isBun } from 'std-env';
import { x } from 'tinyexec';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as legacyRootDirArgs, e as extendsArgs, d as dotEnvArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'node:path';
import 'consola';
import '../shared/cli.B9AmABr3.mjs';
const typecheck = defineCommand({
meta: {
name: "typecheck",
description: "Runs `vue-tsc` to check types throughout your app."
},
args: {
...cwdArgs,
...logLevelArgs,
...dotEnvArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "production";
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const [supportsProjects, resolvedTypeScript, resolvedVueTsc] = await Promise.all([
readTSConfig(cwd).then((r) => !!r.references?.length),
// Prefer local install if possible
resolveModulePath("typescript", { try: true }),
resolveModulePath("vue-tsc/bin/vue-tsc.js", { try: true }),
writeTypes(cwd, ctx.args.dotenv, ctx.args.logLevel, {
...ctx.data?.overrides,
...ctx.args.extends && { extends: ctx.args.extends }
})
]);
const typeCheckArgs = supportsProjects ? ["-b", "--noEmit"] : ["--noEmit"];
if (resolvedTypeScript && resolvedVueTsc) {
return await x(resolvedVueTsc, typeCheckArgs, {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
}
if (isBun) {
await x("bun", ["install", "typescript", "vue-tsc", "--global", "--silent"], {
throwOnError: true,
nodeOptions: { stdio: "inherit", cwd }
});
return await x("bunx", ["vue-tsc", ...typeCheckArgs], {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
}
await x("npx", ["-p", "vue-tsc", "-p", "typescript", "vue-tsc", ...typeCheckArgs], {
throwOnError: true,
nodeOptions: { stdio: "inherit", cwd }
});
}
});
async function writeTypes(cwd, dotenv, logLevel, overrides) {
const { loadNuxt, buildNuxt, writeTypes: writeTypes2 } = await loadKit(cwd);
const nuxt = await loadNuxt({
cwd,
dotenv: { cwd, fileName: dotenv },
overrides: {
_prepare: true,
logLevel,
...overrides
}
});
await writeTypes2(nuxt);
await buildNuxt(nuxt);
await nuxt.close();
}
export { typecheck as default };
@@ -0,0 +1,200 @@
import { existsSync } from 'node:fs';
import process from 'node:process';
import { defineCommand } from 'citty';
import { colors } from 'consola/utils';
import { detectPackageManager, addDependency, dedupeDependencies } from 'nypm';
import { resolve } from 'pathe';
import { readPackageJSON } from 'pkg-types';
import { l as loadKit } from '../shared/cli.qKvs7FJ2.mjs';
import { l as logger } from '../shared/cli.B9AmABr3.mjs';
import { c as cleanupNuxtDirs, n as nuxtVersionToGitIdentifier } from '../shared/cli.At9IMXtr.mjs';
import { g as getPackageManagerVersion } from '../shared/cli.BSm0_9Hr.mjs';
import { g as getNuxtVersion } from '../shared/cli.DHenkA1C.mjs';
import { l as legacyRootDirArgs, a as logLevelArgs, c as cwdArgs } from '../shared/cli.CTXRG5Cu.mjs';
import 'node:url';
import 'exsolve';
import 'consola';
import 'ohash';
import '../shared/cli.pLQ0oPGc.mjs';
import 'node:child_process';
import 'semver';
import 'node:path';
import 'std-env';
function checkNuxtDependencyType(pkg) {
if (pkg.dependencies?.nuxt) {
return "dependencies";
}
if (pkg.devDependencies?.nuxt) {
return "devDependencies";
}
return "dependencies";
}
const nuxtVersionTags = {
"3.x": "3x",
"4.x": "latest"
};
async function getNightlyVersion(packageNames) {
const nuxtVersion = await logger.prompt(
"Which nightly Nuxt release channel do you want to install? (3.x or 4.x)",
{
type: "select",
options: ["3.x", "4.x"],
default: "4.x",
cancel: "reject"
}
).catch(() => process.exit(1));
const npmPackages = packageNames.map((p) => `${p}@npm:${p}-nightly@${nuxtVersionTags[nuxtVersion]}`);
return { npmPackages, nuxtVersion };
}
async function getRequiredNewVersion(packageNames, channel) {
if (channel === "nightly") {
return getNightlyVersion(packageNames);
}
return { npmPackages: packageNames.map((p) => `${p}@latest`), nuxtVersion: "4" };
}
const upgrade = defineCommand({
meta: {
name: "upgrade",
description: "Upgrade Nuxt"
},
args: {
...cwdArgs,
...logLevelArgs,
...legacyRootDirArgs,
dedupe: {
type: "boolean",
description: "Dedupe dependencies after upgrading"
},
force: {
type: "boolean",
alias: "f",
description: "Force upgrade to recreate lockfile and node_modules"
},
channel: {
type: "string",
alias: "ch",
default: "stable",
description: "Specify a channel to install from (default: stable)",
valueHint: "stable|nightly"
}
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const packageManager = await detectPackageManager(cwd);
if (!packageManager) {
logger.error(
`Unable to determine the package manager used by this project.
No lock files found in \`${cwd}\`, and no \`packageManager\` field specified in \`package.json\`.
Please either add the \`packageManager\` field to \`package.json\` or execute the installation command for your package manager. For example, you can use \`pnpm i\`, \`npm i\`, \`bun i\`, or \`yarn i\`, and then try again.`
);
process.exit(1);
}
const { name: packageManagerName, lockFile: lockFileCandidates } = packageManager;
const packageManagerVersion = getPackageManagerVersion(packageManagerName);
logger.info("Package manager:", packageManagerName, packageManagerVersion);
const currentVersion = await getNuxtVersion(cwd, false) || "[unknown]";
logger.info("Current Nuxt version:", currentVersion);
const pkg = await readPackageJSON(cwd).catch(() => null);
const nuxtDependencyType = pkg ? checkNuxtDependencyType(pkg) : "dependencies";
const corePackages = ["@nuxt/kit", "@nuxt/schema", "@nuxt/vite-builder", "@nuxt/webpack-builder", "@nuxt/rspack-builder"];
const packagesToUpdate = pkg ? corePackages.filter((p) => pkg.dependencies?.[p] || pkg.devDependencies?.[p]) : [];
const { npmPackages, nuxtVersion } = await getRequiredNewVersion(["nuxt", ...packagesToUpdate], ctx.args.channel);
const toRemove = ["node_modules"];
const lockFile = normaliseLockFile(cwd, lockFileCandidates);
if (lockFile) {
toRemove.push(lockFile);
}
const forceRemovals = toRemove.map((p) => colors.cyan(p)).join(" and ");
let method = ctx.args.force ? "force" : ctx.args.dedupe ? "dedupe" : void 0;
method ||= await logger.prompt(
`Would you like to dedupe your lockfile (recommended) or recreate ${forceRemovals}? This can fix problems with hoisted dependency versions and ensure you have the most up-to-date dependencies.`,
{
type: "select",
initial: "dedupe",
cancel: "reject",
options: [
{
label: "dedupe lockfile",
value: "dedupe",
hint: "recommended"
},
{
label: `recreate ${forceRemovals}`,
value: "force"
},
{
label: "skip",
value: "skip"
}
]
}
).catch(() => process.exit(1));
const versionType = ctx.args.channel === "nightly" ? "nightly" : "latest stable";
logger.info(`Installing ${versionType} Nuxt ${nuxtVersion} release...`);
await addDependency(npmPackages, {
cwd,
packageManager,
dev: nuxtDependencyType === "devDependencies"
});
if (method === "force") {
logger.info(
`Recreating ${forceRemovals}. If you encounter any issues, revert the changes and try with \`--no-force\``
);
await dedupeDependencies({ recreateLockfile: true });
}
if (method === "dedupe") {
logger.info("Try deduping dependencies...");
await dedupeDependencies();
}
let buildDir = ".nuxt";
try {
const { loadNuxtConfig } = await loadKit(cwd);
const nuxtOptions = await loadNuxtConfig({ cwd });
buildDir = nuxtOptions.buildDir;
} catch {
}
await cleanupNuxtDirs(cwd, buildDir);
const upgradedVersion = await getNuxtVersion(cwd, false) || "[unknown]";
logger.info("Upgraded Nuxt version:", upgradedVersion);
if (upgradedVersion === "[unknown]") {
return;
}
if (upgradedVersion === currentVersion) {
logger.success("You're using the latest version of Nuxt.");
} else {
logger.success(
"Successfully upgraded Nuxt from",
currentVersion,
"to",
upgradedVersion
);
if (currentVersion === "[unknown]") {
return;
}
const commitA = nuxtVersionToGitIdentifier(currentVersion);
const commitB = nuxtVersionToGitIdentifier(upgradedVersion);
if (commitA && commitB) {
logger.info(
"Changelog:",
`https://github.com/nuxt/nuxt/compare/${commitA}...${commitB}`
);
}
}
}
});
function normaliseLockFile(cwd, lockFiles) {
if (typeof lockFiles === "string") {
lockFiles = [lockFiles];
}
const lockFile = lockFiles?.find((file) => existsSync(resolve(cwd, file)));
if (lockFile === void 0) {
logger.error(`Unable to find any lock files in ${cwd}`);
return void 0;
}
return lockFile;
}
export { upgrade as default };
@@ -0,0 +1,93 @@
import * as net from 'net';
import * as listhen from 'listhen';
import { ListenURL, HTTPSOptions, Listener, ListenOptions } from 'listhen';
import { NuxtConfig } from '@nuxt/schema';
import { DotenvOptions } from 'c12';
import { RequestListener, IncomingMessage, ServerResponse } from 'node:http';
import { AddressInfo } from 'node:net';
import EventEmitter from 'node:events';
interface NuxtDevContext {
cwd: string;
public?: boolean;
hostname?: string;
publicURLs?: string[];
args: {
clear: boolean;
logLevel: string;
dotenv: string;
envName: string;
extends?: string;
};
proxy?: {
url?: string;
urls?: ListenURL[];
https?: boolean | HTTPSOptions;
addr?: AddressInfo;
};
}
interface NuxtDevServerOptions {
cwd: string;
logLevel?: 'silent' | 'info' | 'verbose';
dotenv: DotenvOptions;
envName?: string;
clear?: boolean;
defaults: NuxtConfig;
overrides: NuxtConfig;
loadingTemplate?: ({ loading }: {
loading: string;
}) => string;
devContext: Pick<NuxtDevContext, 'proxy'>;
}
interface DevServerEventMap {
'loading:error': [error: Error];
'loading': [loadingMessage: string];
'ready': [address: string];
'restart': [];
}
declare class NuxtDevServer extends EventEmitter<DevServerEventMap> {
private options;
private _handler?;
private _distWatcher?;
private _configWatcher?;
private _currentNuxt?;
private _loadingMessage?;
private _loadingError?;
private cwd;
loadDebounced: (reload?: boolean, reason?: string) => void;
handler: RequestListener;
listener: Pick<Listener, 'server' | 'getURLs' | 'https' | 'url' | 'close'> & {
_url?: string;
address: Omit<AddressInfo, 'family'> & {
socketPath: string;
} | AddressInfo;
};
constructor(options: NuxtDevServerOptions);
_renderError(req: IncomingMessage, res: ServerResponse): void;
_renderLoadingScreen(req: IncomingMessage, res: ServerResponse): Promise<void>;
init(): Promise<void>;
closeWatchers(): void;
load(reload?: boolean, reason?: string): Promise<void>;
close(): Promise<void>;
_load(reload?: boolean, reason?: string): Promise<void>;
_watchConfig(): void;
}
interface InitializeOptions {
data?: {
overrides?: NuxtConfig;
};
}
declare function initialize(devContext: NuxtDevContext, ctx?: InitializeOptions, _listenOptions?: true | Partial<ListenOptions>): Promise<{
listener: Pick<listhen.Listener, "https" | "server" | "url" | "getURLs" | "close"> & {
_url?: string;
address: (Omit<net.AddressInfo, "family"> & {
socketPath: string;
}) | net.AddressInfo;
};
close: () => Promise<void>;
onReady: (callback: (address: string) => void) => void;
onRestart: (callback: (devServer: NuxtDevServer) => void) => void;
}>;
export { initialize };
@@ -0,0 +1,93 @@
import * as net from 'net';
import * as listhen from 'listhen';
import { ListenURL, HTTPSOptions, Listener, ListenOptions } from 'listhen';
import { NuxtConfig } from '@nuxt/schema';
import { DotenvOptions } from 'c12';
import { RequestListener, IncomingMessage, ServerResponse } from 'node:http';
import { AddressInfo } from 'node:net';
import EventEmitter from 'node:events';
interface NuxtDevContext {
cwd: string;
public?: boolean;
hostname?: string;
publicURLs?: string[];
args: {
clear: boolean;
logLevel: string;
dotenv: string;
envName: string;
extends?: string;
};
proxy?: {
url?: string;
urls?: ListenURL[];
https?: boolean | HTTPSOptions;
addr?: AddressInfo;
};
}
interface NuxtDevServerOptions {
cwd: string;
logLevel?: 'silent' | 'info' | 'verbose';
dotenv: DotenvOptions;
envName?: string;
clear?: boolean;
defaults: NuxtConfig;
overrides: NuxtConfig;
loadingTemplate?: ({ loading }: {
loading: string;
}) => string;
devContext: Pick<NuxtDevContext, 'proxy'>;
}
interface DevServerEventMap {
'loading:error': [error: Error];
'loading': [loadingMessage: string];
'ready': [address: string];
'restart': [];
}
declare class NuxtDevServer extends EventEmitter<DevServerEventMap> {
private options;
private _handler?;
private _distWatcher?;
private _configWatcher?;
private _currentNuxt?;
private _loadingMessage?;
private _loadingError?;
private cwd;
loadDebounced: (reload?: boolean, reason?: string) => void;
handler: RequestListener;
listener: Pick<Listener, 'server' | 'getURLs' | 'https' | 'url' | 'close'> & {
_url?: string;
address: Omit<AddressInfo, 'family'> & {
socketPath: string;
} | AddressInfo;
};
constructor(options: NuxtDevServerOptions);
_renderError(req: IncomingMessage, res: ServerResponse): void;
_renderLoadingScreen(req: IncomingMessage, res: ServerResponse): Promise<void>;
init(): Promise<void>;
closeWatchers(): void;
load(reload?: boolean, reason?: string): Promise<void>;
close(): Promise<void>;
_load(reload?: boolean, reason?: string): Promise<void>;
_watchConfig(): void;
}
interface InitializeOptions {
data?: {
overrides?: NuxtConfig;
};
}
declare function initialize(devContext: NuxtDevContext, ctx?: InitializeOptions, _listenOptions?: true | Partial<ListenOptions>): Promise<{
listener: Pick<listhen.Listener, "https" | "server" | "url" | "getURLs" | "close"> & {
_url?: string;
address: (Omit<net.AddressInfo, "family"> & {
socketPath: string;
}) | net.AddressInfo;
};
close: () => Promise<void>;
onReady: (callback: (address: string) => void) => void;
onRestart: (callback: (devServer: NuxtDevServer) => void) => void;
}>;
export { initialize };
@@ -0,0 +1,23 @@
export { i as initialize } from '../chunks/index.mjs';
import 'node:process';
import 'defu';
import 'listhen';
import 'node:http';
import 'get-port-please';
import 'node:events';
import 'node:fs';
import 'node:fs/promises';
import 'node:url';
import 'exsolve';
import 'h3';
import 'pathe';
import 'perfect-debounce';
import 'std-env';
import 'ufo';
import '../shared/cli.pLQ0oPGc.mjs';
import '../shared/cli.B9AmABr3.mjs';
import 'consola';
import '../shared/cli.qKvs7FJ2.mjs';
import '../shared/cli.At9IMXtr.mjs';
import 'ohash';
import 'youch';
@@ -0,0 +1,23 @@
import * as citty from 'citty';
declare const main: citty.CommandDef<{
command: {
type: "positional";
required: false;
};
cwd: {
readonly type: "string";
readonly description: "Specify the working directory";
readonly valueHint: "directory";
readonly default: ".";
};
}>;
declare const runMain: () => Promise<void>;
declare function runCommand(name: string, argv?: string[], data?: {
overrides?: Record<string, any>;
}): Promise<{
result: unknown;
}>;
export { main, runCommand, runMain };
+23
View File
@@ -0,0 +1,23 @@
import * as citty from 'citty';
declare const main: citty.CommandDef<{
command: {
type: "positional";
required: false;
};
cwd: {
readonly type: "string";
readonly description: "Specify the working directory";
readonly valueHint: "directory";
readonly default: ".";
};
}>;
declare const runMain: () => Promise<void>;
declare function runCommand(name: string, argv?: string[], data?: {
overrides?: Record<string, any>;
}): Promise<{
result: unknown;
}>;
export { main, runCommand, runMain };
@@ -0,0 +1,8 @@
export { m as main, r as runCommand, h as runMain } from './shared/cli.CTXRG5Cu.mjs';
import 'node:path';
import 'node:process';
import 'citty';
import 'std-env';
import 'consola';
import './shared/cli.B9AmABr3.mjs';
import 'node:url';
@@ -0,0 +1,51 @@
import { promises } from 'node:fs';
import { hash } from 'ohash';
import { resolve, dirname } from 'pathe';
import { l as logger } from './cli.B9AmABr3.mjs';
import { r as rmRecursive } from './cli.pLQ0oPGc.mjs';
async function cleanupNuxtDirs(rootDir, buildDir) {
logger.info("Cleaning up generated Nuxt files and caches...");
await rmRecursive(
[
buildDir,
".output",
"dist",
"node_modules/.vite",
"node_modules/.cache"
].map((dir) => resolve(rootDir, dir))
);
}
function nuxtVersionToGitIdentifier(version) {
const id = /\.([0-9a-f]{7,8})$/.exec(version);
if (id?.[1]) {
return id[1];
}
return `v${version}`;
}
function resolveNuxtManifest(nuxt) {
const manifest = {
_hash: null,
project: {
rootDir: nuxt.options.rootDir
},
versions: {
nuxt: nuxt._version
}
};
manifest._hash = hash(manifest);
return manifest;
}
async function writeNuxtManifest(nuxt, manifest = resolveNuxtManifest(nuxt)) {
const manifestPath = resolve(nuxt.options.buildDir, "nuxt.json");
await promises.mkdir(dirname(manifestPath), { recursive: true });
await promises.writeFile(manifestPath, JSON.stringify(manifest, null, 2), "utf-8");
return manifest;
}
async function loadNuxtManifest(buildDir) {
const manifestPath = resolve(buildDir, "nuxt.json");
const manifest = await promises.readFile(manifestPath, "utf-8").then((data) => JSON.parse(data)).catch(() => null);
return manifest;
}
export { cleanupNuxtDirs as c, loadNuxtManifest as l, nuxtVersionToGitIdentifier as n, resolveNuxtManifest as r, writeNuxtManifest as w };
@@ -0,0 +1,5 @@
import { consola } from 'consola';
const logger = consola.withTag("nuxi");
export { logger as l };
@@ -0,0 +1,14 @@
import process from 'node:process';
import { l as logger } from './cli.B9AmABr3.mjs';
function overrideEnv(targetEnv) {
const currentEnv = process.env.NODE_ENV;
if (currentEnv && currentEnv !== targetEnv) {
logger.warn(
`Changing \`NODE_ENV\` from \`${currentEnv}\` to \`${targetEnv}\`, to avoid unintended behavior.`
);
}
process.env.NODE_ENV = targetEnv;
}
export { overrideEnv as o };
@@ -0,0 +1,7 @@
import { execSync } from 'node:child_process';
function getPackageManagerVersion(name) {
return execSync(`${name} --version`).toString("utf8").trim();
}
export { getPackageManagerVersion as g };
@@ -0,0 +1,204 @@
import { resolve } from 'node:path';
import process from 'node:process';
import { defineCommand, runMain as runMain$1, runCommand as runCommand$1 } from 'citty';
import { provider } from 'std-env';
import { consola } from 'consola';
import { l as logger } from './cli.B9AmABr3.mjs';
import { fileURLToPath } from 'node:url';
const _rDefault = (r) => r.default || r;
const commands = {
add: () => import('../chunks/add2.mjs').then(_rDefault),
analyze: () => import('../chunks/analyze.mjs').then(_rDefault),
build: () => import('../chunks/build.mjs').then(_rDefault),
cleanup: () => import('../chunks/cleanup.mjs').then(_rDefault),
_dev: () => import('../chunks/dev-child.mjs').then(_rDefault),
dev: () => import('../chunks/dev.mjs').then(_rDefault),
devtools: () => import('../chunks/devtools.mjs').then(_rDefault),
generate: () => import('../chunks/generate.mjs').then(_rDefault),
info: () => import('../chunks/info.mjs').then(_rDefault),
init: () => import('../chunks/init.mjs').then(_rDefault),
module: () => import('../chunks/index2.mjs').then(_rDefault),
prepare: () => import('../chunks/prepare.mjs').then(_rDefault),
preview: () => import('../chunks/preview.mjs').then(_rDefault),
start: () => import('../chunks/preview.mjs').then(_rDefault),
test: () => import('../chunks/test.mjs').then(_rDefault),
typecheck: () => import('../chunks/typecheck.mjs').then(_rDefault),
upgrade: () => import('../chunks/upgrade.mjs').then(_rDefault)
};
const cwdArgs = {
cwd: {
type: "string",
description: "Specify the working directory",
valueHint: "directory",
default: "."
}
};
const logLevelArgs = {
logLevel: {
type: "string",
description: "Specify build-time log level",
valueHint: "silent|info|verbose"
}
};
const envNameArgs = {
envName: {
type: "string",
description: "The environment to use when resolving configuration overrides (default is `production` when building, and `development` when running the dev server)"
}
};
const dotEnvArgs = {
dotenv: {
type: "string",
description: "Path to `.env` file to load, relative to the root directory"
}
};
const extendsArgs = {
extends: {
type: "string",
description: "Extend from a Nuxt layer",
valueHint: "layer-name",
alias: ["e"]
}
};
const legacyRootDirArgs = {
// cwd falls back to rootDir's default (indirect default)
cwd: {
...cwdArgs.cwd,
description: "Specify the working directory, this takes precedence over ROOTDIR (default: `.`)",
default: void 0
},
rootDir: {
type: "positional",
description: "Specifies the working directory (default: `.`)",
required: false,
default: "."
}
};
function wrapReporter(reporter) {
return {
log(logObj, ctx) {
if (!logObj.args || !logObj.args.length) {
return;
}
const msg = logObj.args[0];
if (typeof msg === "string" && !process.env.DEBUG) {
if (msg.startsWith(
"[Vue Router warn]: No match found for location with path"
)) {
return;
}
if (msg.includes(
"ExperimentalWarning: The Fetch API is an experimental feature"
)) {
return;
}
if (msg.startsWith("Sourcemap") && msg.includes("node_modules")) {
return;
}
}
return reporter.log(logObj, ctx);
}
};
}
function setupGlobalConsole(opts = {}) {
consola.options.reporters = consola.options.reporters.map(wrapReporter);
if (opts.dev) {
consola.wrapAll();
} else {
consola.wrapConsole();
}
process.on("unhandledRejection", (err) => consola.error("[unhandledRejection]", err));
process.on("uncaughtException", (err) => consola.error("[uncaughtException]", err));
}
async function checkEngines() {
const satisfies = await import('semver/functions/satisfies.js').then(
(r) => r.default || r
);
const currentNode = process.versions.node;
const nodeRange = ">= 18.0.0";
if (!satisfies(currentNode, nodeRange)) {
logger.warn(
`Current version of Node.js (\`${currentNode}\`) is unsupported and might cause issues.
Please upgrade to a compatible version \`${nodeRange}\`.`
);
}
}
const name = "@nuxt/cli";
const version = "3.28.0";
const description = "Nuxt CLI";
const main = defineCommand({
meta: {
name: name.endsWith("nightly") ? name : "nuxi",
version,
description
},
args: {
...cwdArgs,
command: {
type: "positional",
required: false
}
},
subCommands: commands,
async setup(ctx) {
const command = ctx.args._[0];
const dev = command === "dev";
setupGlobalConsole({ dev });
let backgroundTasks;
if (command !== "_dev" && provider !== "stackblitz") {
backgroundTasks = Promise.all([
checkEngines()
]).catch((err) => logger.error(err));
}
if (command === "init") {
await backgroundTasks;
}
if (ctx.args.command && !(ctx.args.command in commands)) {
const cwd = resolve(ctx.args.cwd);
try {
const { x } = await import('tinyexec');
await x(`nuxt-${ctx.args.command}`, ctx.rawArgs.slice(1), {
nodeOptions: { stdio: "inherit", cwd },
throwOnError: true
});
} catch (err) {
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
return;
}
}
process.exit();
}
}
});
globalThis.__nuxt_cli__ = globalThis.__nuxt_cli__ || {
// Programmatic usage fallback
startTime: Date.now(),
entry: fileURLToPath(
new URL("../../bin/nuxi.mjs", import.meta.url)
),
devEntry: fileURLToPath(
new URL("../dev/index.mjs", import.meta.url)
)
};
const runMain = () => runMain$1(main);
async function runCommand(name, argv = process.argv.slice(2), data = {}) {
argv.push("--no-clear");
if (!(name in commands)) {
throw new Error(`Invalid command ${name}`);
}
return await runCommand$1(await commands[name](), {
rawArgs: argv,
data: {
overrides: data.overrides || {}
}
});
}
export { logLevelArgs as a, envNameArgs as b, cwdArgs as c, dotEnvArgs as d, extendsArgs as e, commands as f, checkEngines as g, runMain as h, legacyRootDirArgs as l, main as m, runCommand as r, setupGlobalConsole as s };
@@ -0,0 +1,37 @@
import { parseINI } from 'confbox';
import { $fetch } from 'ofetch';
import { satisfies } from 'semver';
async function fetchModules() {
const { modules } = await $fetch(
`https://api.nuxt.com/modules?version=all`
);
return modules;
}
function checkNuxtCompatibility(module, nuxtVersion) {
if (!module.compatibility?.nuxt) {
return true;
}
return satisfies(nuxtVersion, module.compatibility.nuxt, {
includePrerelease: true
});
}
function getRegistryFromContent(content, scope) {
try {
const npmConfig = parseINI(content);
if (scope) {
const scopeKey = `${scope}:registry`;
if (npmConfig[scopeKey]) {
return npmConfig[scopeKey].trim();
}
}
if (npmConfig.registry) {
return npmConfig.registry.trim();
}
return null;
} catch {
return null;
}
}
export { checkNuxtCompatibility as c, fetchModules as f, getRegistryFromContent as g };
@@ -0,0 +1,14 @@
import { readPackageJSON } from 'pkg-types';
import { coerce } from 'semver';
async function getNuxtVersion(cwd, cache = true) {
const nuxtPkg = await readPackageJSON("nuxt", { url: cwd, try: true, cache });
if (nuxtPkg) {
return nuxtPkg.version;
}
const pkg = await readPackageJSON(cwd);
const pkgDep = pkg?.dependencies?.nuxt || pkg?.devDependencies?.nuxt;
return pkgDep && coerce(pkgDep)?.version || "3.0.0";
}
export { getNuxtVersion as g };
@@ -0,0 +1,5 @@
const name = "nuxi";
const version = "3.28.0";
const description = "Nuxt CLI";
export { description as d, name as n, version as v };
@@ -0,0 +1,27 @@
import { readFileSync } from 'node:fs';
import { colors } from 'consola/utils';
import { resolveModulePath } from 'exsolve';
import { t as tryResolveNuxt } from './cli.qKvs7FJ2.mjs';
import { l as logger } from './cli.B9AmABr3.mjs';
function showVersions(cwd) {
const { bold, gray, green } = colors;
const nuxtDir = tryResolveNuxt(cwd);
function getPkgVersion(pkg) {
for (const url of [cwd, nuxtDir]) {
if (!url) {
continue;
}
const p = resolveModulePath(`${pkg}/package.json`, { from: url, try: true });
if (p) {
return JSON.parse(readFileSync(p, "utf-8")).version;
}
}
return "";
}
const nuxtVersion = getPkgVersion("nuxt") || getPkgVersion("nuxt-nightly") || getPkgVersion("nuxt3") || getPkgVersion("nuxt-edge");
const nitroVersion = getPkgVersion("nitropack") || getPkgVersion("nitropack-nightly") || getPkgVersion("nitropack-edge");
logger.log(gray(green(`Nuxt ${bold(nuxtVersion)}`) + (nitroVersion ? ` with Nitro ${bold(nitroVersion)}` : "")));
}
export { showVersions as s };
@@ -0,0 +1,33 @@
import { promises, existsSync } from 'node:fs';
import { join } from 'pathe';
import { l as logger } from './cli.B9AmABr3.mjs';
async function clearDir(path, exclude) {
if (!exclude) {
await promises.rm(path, { recursive: true, force: true });
} else if (existsSync(path)) {
const files = await promises.readdir(path);
await Promise.all(
files.map(async (name) => {
if (!exclude.includes(name)) {
await promises.rm(join(path, name), { recursive: true, force: true });
}
})
);
}
await promises.mkdir(path, { recursive: true });
}
function clearBuildDir(path) {
return clearDir(path, ["cache", "analyze", "nuxt.json"]);
}
async function rmRecursive(paths) {
await Promise.all(
paths.filter((p) => typeof p === "string").map(async (path) => {
logger.debug("Removing recursive path", path);
await promises.rm(path, { recursive: true, force: true }).catch(() => {
});
})
);
}
export { clearBuildDir as a, clearDir as c, rmRecursive as r };
@@ -0,0 +1,36 @@
import { pathToFileURL } from 'node:url';
import { resolveModulePath } from 'exsolve';
async function loadKit(rootDir) {
try {
const kitPath = resolveModulePath("@nuxt/kit", { from: tryResolveNuxt(rootDir) || rootDir });
let kit = await import(pathToFileURL(kitPath).href);
if (!kit.writeTypes) {
kit = {
...kit,
writeTypes: () => {
throw new Error("`writeTypes` is not available in this version of `@nuxt/kit`. Please upgrade to v3.7 or newer.");
}
};
}
return kit;
} catch (e) {
if (e.toString().includes("Cannot find module '@nuxt/kit'")) {
throw new Error(
"nuxi requires `@nuxt/kit` to be installed in your project. Try installing `nuxt` v3+ or `@nuxt/bridge` first."
);
}
throw e;
}
}
function tryResolveNuxt(rootDir) {
for (const pkg of ["nuxt-nightly", "nuxt", "nuxt3", "nuxt-edge"]) {
const path = resolveModulePath(pkg, { from: rootDir, try: true });
if (path) {
return path;
}
}
return null;
}
export { loadKit as l, tryResolveNuxt as t };
@@ -0,0 +1,83 @@
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { defineCommand, runCommand as runCommand$1 } from 'citty';
import { f as commands, c as cwdArgs, s as setupGlobalConsole, g as checkEngines } from './cli.CTXRG5Cu.mjs';
import nodeCrypto from 'node:crypto';
import { resolve } from 'node:path';
import { provider } from 'std-env';
import { d as description, v as version, n as name } from './cli.DhJ3cH8w.mjs';
import { l as logger } from './cli.B9AmABr3.mjs';
if (!globalThis.crypto) {
globalThis.crypto = nodeCrypto.webcrypto;
}
defineCommand({
meta: {
name: name.endsWith("nightly") ? name : "nuxi",
version,
description
},
args: {
...cwdArgs,
command: {
type: "positional",
required: false
}
},
subCommands: commands,
async setup(ctx) {
const command = ctx.args._[0];
logger.debug(`Running \`nuxt ${command}\` command`);
const dev = command === "dev";
setupGlobalConsole({ dev });
let backgroundTasks;
if (command !== "_dev" && provider !== "stackblitz") {
backgroundTasks = Promise.all([
checkEngines()
]).catch((err) => logger.error(err));
}
if (command === "init") {
await backgroundTasks;
}
if (ctx.args.command && !(ctx.args.command in commands)) {
const cwd = resolve(ctx.args.cwd);
try {
const { x } = await import('tinyexec');
await x(`nuxt-${ctx.args.command}`, ctx.rawArgs.slice(1), {
nodeOptions: { stdio: "inherit", cwd },
throwOnError: true
});
} catch (err) {
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
return;
}
}
process.exit();
}
}
});
globalThis.__nuxt_cli__ = globalThis.__nuxt_cli__ || {
// Programmatic usage fallback
startTime: Date.now(),
entry: fileURLToPath(
new URL("../../bin/nuxi.mjs", import.meta.url)
),
devEntry: fileURLToPath(
new URL("../dev/index.mjs", import.meta.url)
)
};
async function runCommand(name, argv = process.argv.slice(2), data = {}) {
argv.push("--no-clear");
if (!(name in commands)) {
throw new Error(`Invalid command ${name}`);
}
return await runCommand$1(await commands[name](), {
rawArgs: argv,
data: {
overrides: data.overrides || {}
}
});
}
export { runCommand as r };
+75
View File
@@ -0,0 +1,75 @@
{
"name": "@nuxt/cli",
"type": "module",
"version": "3.28.0",
"description": "Nuxt CLI",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/cli.git",
"directory": "packages/nuxt-cli"
},
"exports": {
".": "./dist/index.mjs",
"./cli": "./bin/nuxi.mjs"
},
"types": "./dist/index.d.ts",
"bin": {
"nuxi": "bin/nuxi.mjs",
"nuxi-ng": "bin/nuxi.mjs",
"nuxt": "bin/nuxi.mjs",
"nuxt-cli": "bin/nuxi.mjs"
},
"files": [
"bin",
"dist"
],
"engines": {
"node": "^16.10.0 || >=18.0.0"
},
"scripts": {
"build": "unbuild",
"dev:prepare": "unbuild --stub",
"prepack": "unbuild"
},
"dependencies": {
"c12": "^3.2.0",
"citty": "^0.1.6",
"clipboardy": "^4.0.0",
"confbox": "^0.2.2",
"consola": "^3.4.2",
"defu": "^6.1.4",
"exsolve": "^1.0.7",
"fuse.js": "^7.1.0",
"get-port-please": "^3.2.0",
"giget": "^2.0.0",
"h3": "^1.15.4",
"httpxy": "^0.1.7",
"jiti": "^2.5.1",
"listhen": "^1.9.0",
"nypm": "^0.6.1",
"ofetch": "^1.4.1",
"ohash": "^2.0.11",
"pathe": "^2.0.3",
"perfect-debounce": "^1.0.0",
"pkg-types": "^2.2.0",
"scule": "^1.3.0",
"semver": "^7.7.2",
"std-env": "^3.9.0",
"tinyexec": "^1.0.1",
"ufo": "^1.6.1",
"youch": "^4.1.0-beta.11"
},
"devDependencies": {
"@nuxt/kit": "^4.0.3",
"@nuxt/schema": "^4.0.3",
"@types/node": "^22.17.0",
"rollup": "^4.46.2",
"rollup-plugin-visualizer": "^6.0.3",
"typescript": "^5.9.2",
"unbuild": "^3.6.0",
"unplugin-purge-polyfills": "^0.1.0",
"vitest": "^3.2.4",
"youch": "^4.1.0-beta.11"
}
}
+7
View File
@@ -0,0 +1,7 @@
Copyright (c) 2018-19 [these people](https://github.com/nuxt-contrib/devalue/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+146
View File
@@ -0,0 +1,146 @@
# @nuxt/devalue
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![codecov][codecov-src]][codecov-href]
[![package phobia][package-phobia-src]][package-phobia-href]
[![bundle phobia][bundle-phobia-src]][bundle-phobia-href]
> Forked from [devalue](https://github.com/Rich-Harris/devalue) to log errors on non-serializable properties rather than throwing `Error`.
Like `JSON.stringify`, but handles
* cyclical references (`obj.self = obj`)
* repeated references (`[value, value]`)
* `undefined`, `Infinity`, `NaN`, `-0`
* regular expressions
* dates
* `Map` and `Set`
* `.toJSON()` method for non-POJOs
Try it out on [runkit.com](https://npm.runkit.com/@nuxt/devalue).
## Goals:
* Performance
* Security (see [XSS mitigation](#xss-mitigation))
* Compact output
## Non-goals:
* Human-readable output
* Stringifying functions or arbritary non-POJOs
## Usage
```js
import devalue from '@nuxt/devalue';
let obj = { a: 1, b: 2 };
obj.c = 3;
devalue(obj); // '{a:1,b:2,c:3}'
obj.self = obj;
devalue(obj); // '(function(a){a.a=1;a.b=2;a.c=3;a.self=a;return a}({}))'
```
If `devalue` encounters a function or a non-POJO, it will throw an error.
## XSS mitigation
Say you're server-rendering a page and want to serialize some state, which could include user input. `JSON.stringify` doesn't protect against XSS attacks:
```js
const state = {
userinput: `</script><script src='https://evil.com/mwahaha.js'>`
};
const template = `
<script>
// NEVER DO THIS
var preloaded = ${JSON.stringify(state)};
</script>`;
```
Which would result in this:
```html
<script>
// NEVER DO THIS
var preloaded = {"userinput":"</script><script src='https://evil.com/mwahaha.js'>"};
</script>
```
Using `devalue`, we're protected against that attack:
```js
const template = `
<script>
var preloaded = ${devalue(state)};
</script>`;
```
```html
<script>
var preloaded = {userinput:"\\u003C\\u002Fscript\\u003E\\u003Cscript src=\'https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js\'\\u003E"};
</script>
```
This, along with the fact that `devalue` bails on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by `devalue` can be safely deserialized with `eval` or `new Function`:
```js
const value = (0,eval)('(' + str + ')');
```
## Other security considerations
While `devalue` prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, **you should not send user data from client to server** using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed `devalue` would have access to your system.
When using `eval`, ensure that you call it *indirectly* so that the evaluated code doesn't have access to the surrounding scope:
```js
{
const sensitiveData = 'Setec Astronomy';
eval('sendToEvilServer(sensitiveData)'); // pwned :(
(0,eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
}
```
Using `new Function(code)` is akin to using indirect eval.
## See also
* [lave](https://github.com/jed/lave) by Jed Schmidt
* [arson](https://github.com/benjamn/arson) by Ben Newman
* [tosource](https://github.com/marcello3d/node-tosource) by Marcello Bastéa-Forte
* [serialize-javascript](https://github.com/yahoo/serialize-javascript) by Eric Ferraiuolo
## License
[MIT](LICENSE)
<!-- Refs -->
[npm-version-src]: https://flat.badgen.net/npm/v/@nuxt/devalue/latest
[npm-version-href]: https://www.npmjs.com/package/@nuxt/devalue
[npm-downloads-src]: https://flat.badgen.net/npm/dm/@nuxt/devalue
[npm-downloads-href]: https://www.npmjs.com/package/@nuxt/devalue
[circleci-src]: https://flat.badgen.net/circleci/github/nuxt-contrib/devalue
[circleci-href]: https://circleci.com/gh/nuxt-contrib/devalue
[package-phobia-src]: https://flat.badgen.net/packagephobia/install/@nuxt/devalue
[package-phobia-href]: https://packagephobia.now.sh/result?p=@nuxt/devalue
[bundle-phobia-src]: https://flat.badgen.net/bundlephobia/minzip/@nuxt/devalue
[bundle-phobia-href]: https://bundlephobia.com/result?p=@nuxt/devalue
[codecov-src]: https://flat.badgen.net/codecov/c/github/nuxt-contrib/devalue/master
[codecov-href]: https://codecov.io/gh/nuxt-contrib/devalue
@@ -0,0 +1,236 @@
'use strict';
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = /* @__PURE__ */ new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = /* @__PURE__ */ new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
module.exports = devalue;
@@ -0,0 +1,234 @@
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = /* @__PURE__ */ new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = /* @__PURE__ */ new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
export { devalue as default };
@@ -0,0 +1,3 @@
declare function devalue(value: any): string;
export { devalue as default };
@@ -0,0 +1,39 @@
{
"name": "@nuxt/devalue",
"version": "2.0.2",
"description": "Gets the job done when JSON.stringify can't",
"repository": "nuxt/devalue",
"license": "MIT",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/devalue.js",
"import": "./dist/devalue.mjs"
}
},
"main": "./dist/devalue.js",
"module": "./dist/devalue.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"prepack": "yarn build",
"lint": "eslint --ext .ts,.js .",
"test": "yarn lint && jest",
"release": "yarn test && standard-version && git push --follow-tags && npm publish"
},
"devDependencies": {
"@nuxtjs/eslint-config-typescript": "^6.0.0",
"@types/jest": "^26.0.23",
"@types/mocha": "^8.2.2",
"@types/node": "^15.3.0",
"eslint": "^7.26.0",
"jest": "^26.6.3",
"standard-version": "^9.3.0",
"ts-jest": "^26.5.6",
"typescript": "^4.2.4",
"unbuild": "^1.2.1"
}
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-PRESENT Nuxt Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,110 @@
'use strict';
const kit = require('@nuxt/kit');
const execa = require('execa');
function addCustomTab(tab, nuxt = kit.useNuxt()) {
nuxt.hook("devtools:customTabs", async (tabs) => {
if (typeof tab === "function")
tab = await tab();
tabs.push(tab);
});
}
function refreshCustomTabs(nuxt = kit.useNuxt()) {
return nuxt.callHook("devtools:customTabs:refresh");
}
function startSubprocess(execaOptions, tabOptions, nuxt = kit.useNuxt()) {
const id = tabOptions.id;
let restarting = false;
function start() {
const process2 = execa.execa(
execaOptions.command,
execaOptions.args,
{
reject: false,
...execaOptions,
env: {
COLORS: "true",
FORCE_COLOR: "true",
...execaOptions.env,
// Force disable Nuxi CLI override
__CLI_ARGV__: void 0
}
}
);
nuxt.callHook("devtools:terminal:write", { id, data: `> ${[execaOptions.command, ...execaOptions.args || []].join(" ")}
` });
process2.stdout.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.stderr.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.on("exit", (code) => {
if (!restarting) {
nuxt.callHook("devtools:terminal:write", { id, data: `
> process terminalated with ${code}
` });
nuxt.callHook("devtools:terminal:exit", { id, code: code || 0 });
}
});
return process2;
}
register();
nuxt.hook("close", () => {
terminate();
});
let process = start();
function restart() {
restarting = true;
process?.kill();
clear();
process = start();
restarting = false;
}
function clear() {
tabOptions.buffer = "";
register();
}
function terminate() {
restarting = false;
try {
process?.kill();
} catch {
}
nuxt.callHook("devtools:terminal:remove", { id });
}
function register() {
nuxt.callHook("devtools:terminal:register", {
onActionRestart: tabOptions.restartable === false ? void 0 : restart,
onActionTerminate: tabOptions.terminatable === false ? void 0 : terminate,
isTerminated: false,
...tabOptions
});
}
return {
getProcess: () => process,
terminate,
restart,
clear
};
}
function extendServerRpc(namespace, functions, nuxt = kit.useNuxt()) {
const ctx = _getContext(nuxt);
if (!ctx)
throw new Error("Failed to get devtools context.");
return ctx.extendServerRpc(namespace, functions);
}
function onDevToolsInitialized(fn, nuxt = kit.useNuxt()) {
nuxt.hook("devtools:initialized", fn);
}
function _getContext(nuxt = kit.useNuxt()) {
return nuxt?.devtools;
}
exports.addCustomTab = addCustomTab;
exports.extendServerRpc = extendServerRpc;
exports.onDevToolsInitialized = onDevToolsInitialized;
exports.refreshCustomTabs = refreshCustomTabs;
exports.startSubprocess = startSubprocess;
@@ -0,0 +1,35 @@
import * as _nuxt_schema from '@nuxt/schema';
import { BirpcGroup } from 'birpc';
import { ExecaChildProcess } from 'execa';
import { M as ModuleCustomTab, S as SubprocessOptions, T as TerminalState, N as NuxtDevtoolsInfo } from './shared/devtools-kit.BMivX6Xf.cjs';
import 'vue';
import 'nuxt/schema';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
/**
* Hooks to extend a custom tab in devtools.
*
* Provide a function to pass a factory that can be updated dynamically.
*/
declare function addCustomTab(tab: ModuleCustomTab | (() => ModuleCustomTab | Promise<ModuleCustomTab>), nuxt?: _nuxt_schema.Nuxt): void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
declare function refreshCustomTabs(nuxt?: _nuxt_schema.Nuxt): Promise<any>;
/**
* Create a subprocess that handled by the DevTools.
*/
declare function startSubprocess(execaOptions: SubprocessOptions, tabOptions: TerminalState, nuxt?: _nuxt_schema.Nuxt): {
getProcess: () => ExecaChildProcess<string>;
terminate: () => void;
restart: () => void;
clear: () => void;
};
declare function extendServerRpc<ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(namespace: string, functions: ServerFunctions, nuxt?: _nuxt_schema.Nuxt): BirpcGroup<ClientFunctions, ServerFunctions>;
declare function onDevToolsInitialized(fn: (info: NuxtDevtoolsInfo) => void, nuxt?: _nuxt_schema.Nuxt): void;
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };
@@ -0,0 +1,35 @@
import * as _nuxt_schema from '@nuxt/schema';
import { BirpcGroup } from 'birpc';
import { ExecaChildProcess } from 'execa';
import { M as ModuleCustomTab, S as SubprocessOptions, T as TerminalState, N as NuxtDevtoolsInfo } from './shared/devtools-kit.BMivX6Xf.mjs';
import 'vue';
import 'nuxt/schema';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
/**
* Hooks to extend a custom tab in devtools.
*
* Provide a function to pass a factory that can be updated dynamically.
*/
declare function addCustomTab(tab: ModuleCustomTab | (() => ModuleCustomTab | Promise<ModuleCustomTab>), nuxt?: _nuxt_schema.Nuxt): void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
declare function refreshCustomTabs(nuxt?: _nuxt_schema.Nuxt): Promise<any>;
/**
* Create a subprocess that handled by the DevTools.
*/
declare function startSubprocess(execaOptions: SubprocessOptions, tabOptions: TerminalState, nuxt?: _nuxt_schema.Nuxt): {
getProcess: () => ExecaChildProcess<string>;
terminate: () => void;
restart: () => void;
clear: () => void;
};
declare function extendServerRpc<ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(namespace: string, functions: ServerFunctions, nuxt?: _nuxt_schema.Nuxt): BirpcGroup<ClientFunctions, ServerFunctions>;
declare function onDevToolsInitialized(fn: (info: NuxtDevtoolsInfo) => void, nuxt?: _nuxt_schema.Nuxt): void;
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };
@@ -0,0 +1,35 @@
import * as _nuxt_schema from '@nuxt/schema';
import { BirpcGroup } from 'birpc';
import { ExecaChildProcess } from 'execa';
import { M as ModuleCustomTab, S as SubprocessOptions, T as TerminalState, N as NuxtDevtoolsInfo } from './shared/devtools-kit.BMivX6Xf.js';
import 'vue';
import 'nuxt/schema';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
/**
* Hooks to extend a custom tab in devtools.
*
* Provide a function to pass a factory that can be updated dynamically.
*/
declare function addCustomTab(tab: ModuleCustomTab | (() => ModuleCustomTab | Promise<ModuleCustomTab>), nuxt?: _nuxt_schema.Nuxt): void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
declare function refreshCustomTabs(nuxt?: _nuxt_schema.Nuxt): Promise<any>;
/**
* Create a subprocess that handled by the DevTools.
*/
declare function startSubprocess(execaOptions: SubprocessOptions, tabOptions: TerminalState, nuxt?: _nuxt_schema.Nuxt): {
getProcess: () => ExecaChildProcess<string>;
terminate: () => void;
restart: () => void;
clear: () => void;
};
declare function extendServerRpc<ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(namespace: string, functions: ServerFunctions, nuxt?: _nuxt_schema.Nuxt): BirpcGroup<ClientFunctions, ServerFunctions>;
declare function onDevToolsInitialized(fn: (info: NuxtDevtoolsInfo) => void, nuxt?: _nuxt_schema.Nuxt): void;
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };
@@ -0,0 +1,104 @@
import { useNuxt } from '@nuxt/kit';
import { execa } from 'execa';
function addCustomTab(tab, nuxt = useNuxt()) {
nuxt.hook("devtools:customTabs", async (tabs) => {
if (typeof tab === "function")
tab = await tab();
tabs.push(tab);
});
}
function refreshCustomTabs(nuxt = useNuxt()) {
return nuxt.callHook("devtools:customTabs:refresh");
}
function startSubprocess(execaOptions, tabOptions, nuxt = useNuxt()) {
const id = tabOptions.id;
let restarting = false;
function start() {
const process2 = execa(
execaOptions.command,
execaOptions.args,
{
reject: false,
...execaOptions,
env: {
COLORS: "true",
FORCE_COLOR: "true",
...execaOptions.env,
// Force disable Nuxi CLI override
__CLI_ARGV__: void 0
}
}
);
nuxt.callHook("devtools:terminal:write", { id, data: `> ${[execaOptions.command, ...execaOptions.args || []].join(" ")}
` });
process2.stdout.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.stderr.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.on("exit", (code) => {
if (!restarting) {
nuxt.callHook("devtools:terminal:write", { id, data: `
> process terminalated with ${code}
` });
nuxt.callHook("devtools:terminal:exit", { id, code: code || 0 });
}
});
return process2;
}
register();
nuxt.hook("close", () => {
terminate();
});
let process = start();
function restart() {
restarting = true;
process?.kill();
clear();
process = start();
restarting = false;
}
function clear() {
tabOptions.buffer = "";
register();
}
function terminate() {
restarting = false;
try {
process?.kill();
} catch {
}
nuxt.callHook("devtools:terminal:remove", { id });
}
function register() {
nuxt.callHook("devtools:terminal:register", {
onActionRestart: tabOptions.restartable === false ? void 0 : restart,
onActionTerminate: tabOptions.terminatable === false ? void 0 : terminate,
isTerminated: false,
...tabOptions
});
}
return {
getProcess: () => process,
terminate,
restart,
clear
};
}
function extendServerRpc(namespace, functions, nuxt = useNuxt()) {
const ctx = _getContext(nuxt);
if (!ctx)
throw new Error("Failed to get devtools context.");
return ctx.extendServerRpc(namespace, functions);
}
function onDevToolsInitialized(fn, nuxt = useNuxt()) {
nuxt.hook("devtools:initialized", fn);
}
function _getContext(nuxt = useNuxt()) {
return nuxt?.devtools;
}
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };
@@ -0,0 +1,4 @@
import type { NuxtDevtoolsHostClient } from '@nuxt/devtools-kit/types';
import type { Ref } from 'vue';
export declare function onDevtoolsHostClientConnected(fn: (client: NuxtDevtoolsHostClient) => void): (() => void) | undefined;
export declare function useDevtoolsHostClient(): Ref<NuxtDevtoolsHostClient | undefined>;
@@ -0,0 +1,34 @@
import { shallowRef } from "vue";
let clientRef;
const fns = [];
export function onDevtoolsHostClientConnected(fn) {
fns.push(fn);
if (typeof window === "undefined")
return;
if (window.__NUXT_DEVTOOLS_HOST__) {
fns.forEach((fn2) => fn2(window.__NUXT_DEVTOOLS_HOST__));
}
Object.defineProperty(window, "__NUXT_DEVTOOLS_HOST__", {
set(value) {
if (value)
fns.forEach((fn2) => fn2(value));
},
get() {
return clientRef.value;
},
configurable: true
});
return () => {
fns.splice(fns.indexOf(fn), 1);
};
}
export function useDevtoolsHostClient() {
if (!clientRef) {
clientRef = shallowRef();
onDevtoolsHostClientConnected(setup);
}
function setup(client) {
clientRef.value = client;
}
return clientRef;
}
@@ -0,0 +1,4 @@
import type { Ref } from 'vue';
import type { NuxtDevtoolsIframeClient } from '../types';
export declare function onDevtoolsClientConnected(fn: (client: NuxtDevtoolsIframeClient) => void): (() => void) | undefined;
export declare function useDevtoolsClient(): Ref<NuxtDevtoolsIframeClient | undefined, NuxtDevtoolsIframeClient | undefined>;
@@ -0,0 +1,44 @@
import { shallowRef, triggerRef } from "vue";
let clientRef;
const hasSetup = false;
const fns = [];
export function onDevtoolsClientConnected(fn) {
fns.push(fn);
if (hasSetup)
return;
if (typeof window === "undefined")
return;
if (window.__NUXT_DEVTOOLS__) {
fns.forEach((fn2) => fn2(window.__NUXT_DEVTOOLS__));
}
Object.defineProperty(window, "__NUXT_DEVTOOLS__", {
set(value) {
if (value)
fns.forEach((fn2) => fn2(value));
},
get() {
return clientRef.value;
},
configurable: true
});
return () => {
fns.splice(fns.indexOf(fn), 1);
};
}
export function useDevtoolsClient() {
if (!clientRef) {
clientRef = shallowRef();
onDevtoolsClientConnected(setup);
}
function onUpdateReactivity() {
if (clientRef) {
triggerRef(clientRef);
}
}
function setup(client) {
clientRef.value = client;
if (client.host)
client.host.hooks.hook("host:update:reactivity", onUpdateReactivity);
}
return clientRef;
}
@@ -0,0 +1,783 @@
import { VNode, MaybeRefOrGetter } from 'vue';
import { BirpcGroup } from 'birpc';
import { Component, NuxtOptions, NuxtPage, NuxtLayout, NuxtApp, NuxtDebugModuleMutationRecord, Nuxt } from 'nuxt/schema';
import { Import, UnimportMeta } from 'unimport';
import { RouteRecordNormalized } from 'vue-router';
import { Nitro, StorageMounts } from 'nitropack';
import { StorageValue } from 'unstorage';
import { ResolvedConfig } from 'vite';
import { NuxtAnalyzeMeta } from '@nuxt/schema';
import { Options } from 'execa';
type TabCategory = 'pinned' | 'app' | 'vue-devtools' | 'analyze' | 'server' | 'modules' | 'documentation' | 'advanced';
interface ModuleCustomTab {
/**
* The name of the tab, must be unique
*/
name: string;
/**
* Icon of the tab, support any Iconify icons, or a url to an image
*/
icon?: string;
/**
* Title of the tab
*/
title: string;
/**
* Main view of the tab
*/
view: ModuleView;
/**
* Category of the tab
* @default 'app'
*/
category?: TabCategory;
/**
* Insert static vnode to the tab entry
*
* Advanced options. You don't usually need this.
*/
extraTabVNode?: VNode;
/**
* Require local authentication to access the tab
* It's highly recommended to enable this if the tab have sensitive information or have access to the OS
*
* @default false
*/
requireAuth?: boolean;
}
interface ModuleLaunchView {
/**
* A view for module to lazy launch some actions
*/
type: 'launch';
title?: string;
icon?: string;
description: string;
/**
* Action buttons
*/
actions: ModuleLaunchAction[];
}
interface ModuleIframeView {
/**
* Iframe view
*/
type: 'iframe';
/**
* Url of the iframe
*/
src: string;
/**
* Persist the iframe instance even if the tab is not active
*
* @default true
*/
persistent?: boolean;
}
interface ModuleVNodeView {
/**
* Vue's VNode view
*/
type: 'vnode';
/**
* Send vnode to the client, they must be static and serializable
*
* Call `nuxt.hook('devtools:customTabs:refresh')` to trigger manual refresh
*/
vnode: VNode;
}
interface ModuleLaunchAction {
/**
* Label of the action button
*/
label: string;
/**
* Additional HTML attributes to the action button
*/
attrs?: Record<string, string>;
/**
* Indicate if the action is pending, will show a loading indicator and disable the button
*/
pending?: boolean;
/**
* Function to handle the action, this is executed on the server side.
* Will automatically refresh the tabs after the action is resolved.
*/
handle?: () => void | Promise<void>;
/**
* Treat the action as a link, will open the link in a new tab
*/
src?: string;
}
type ModuleView = ModuleIframeView | ModuleLaunchView | ModuleVNodeView;
interface ModuleIframeTabLazyOptions {
description?: string;
onLoad?: () => Promise<void>;
}
interface ModuleBuiltinTab {
name: string;
icon?: string;
title?: string;
path?: string;
category?: TabCategory;
show?: () => MaybeRefOrGetter<any>;
badge?: () => MaybeRefOrGetter<number | string | undefined>;
onClick?: () => void;
}
type ModuleTabInfo = ModuleCustomTab | ModuleBuiltinTab;
type CategorizedTabs = [TabCategory, (ModuleCustomTab | ModuleBuiltinTab)[]][];
interface HookInfo {
name: string;
start: number;
end?: number;
duration?: number;
listeners: number;
executions: number[];
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface PackageUpdateInfo {
name: string;
current: string;
latest: string;
needsUpdate: boolean;
}
type PackageManagerName = 'npm' | 'yarn' | 'pnpm' | 'bun';
type NpmCommandType = 'install' | 'uninstall' | 'update';
interface NpmCommandOptions {
dev?: boolean;
global?: boolean;
}
interface AutoImportsWithMetadata {
imports: Import[];
metadata?: UnimportMeta;
dirs: string[];
}
interface RouteInfo extends Pick<RouteRecordNormalized, 'name' | 'path' | 'meta' | 'props' | 'children'> {
file?: string;
}
interface ServerRouteInfo {
route: string;
filepath: string;
method?: string;
type: 'api' | 'route' | 'runtime' | 'collection';
routes?: ServerRouteInfo[];
}
type ServerRouteInputType = 'string' | 'number' | 'boolean' | 'file' | 'date' | 'time' | 'datetime-local';
interface ServerRouteInput {
active: boolean;
key: string;
value: any;
type?: ServerRouteInputType;
}
interface Payload {
url: string;
time: number;
data?: Record<string, any>;
state?: Record<string, any>;
functions?: Record<string, any>;
}
interface ServerTaskInfo {
name: string;
handler: string;
description: string;
type: 'collection' | 'task';
tasks?: ServerTaskInfo[];
}
interface ScannedNitroTasks {
tasks: {
[name: string]: {
handler: string;
description: string;
};
};
scheduledTasks: {
[cron: string]: string[];
};
}
interface PluginInfoWithMetic {
src: string;
mode?: 'client' | 'server' | 'all';
ssr?: boolean;
metric?: PluginMetric;
}
interface PluginMetric {
src: string;
start: number;
end: number;
duration: number;
}
interface LoadingTimeMetric {
ssrStart?: number;
appInit?: number;
appLoad?: number;
pageStart?: number;
pageEnd?: number;
pluginInit?: number;
hmrStart?: number;
hmrEnd?: number;
}
interface BasicModuleInfo {
entryPath?: string;
meta?: {
name?: string;
};
}
interface InstalledModuleInfo {
name?: string;
isPackageModule: boolean;
isUninstallable: boolean;
info?: ModuleStaticInfo;
entryPath?: string;
timings?: Record<string, number | undefined>;
meta?: {
name?: string;
};
}
interface ModuleStaticInfo {
name: string;
description: string;
repo: string;
npm: string;
icon?: string;
github: string;
website: string;
learn_more: string;
category: string;
type: ModuleType;
stats: ModuleStats;
maintainers: MaintainerInfo[];
contributors: GitHubContributor[];
compatibility: ModuleCompatibility;
}
interface ModuleCompatibility {
nuxt: string;
requires: {
bridge?: boolean | 'optional';
};
}
interface ModuleStats {
downloads: number;
stars: number;
publishedAt: number;
createdAt: number;
}
type CompatibilityStatus = 'working' | 'wip' | 'unknown' | 'not-working';
type ModuleType = 'community' | 'official' | '3rd-party';
interface MaintainerInfo {
name: string;
github: string;
twitter?: string;
}
interface GitHubContributor {
login: string;
name?: string;
avatar_url?: string;
}
interface VueInspectorClient {
enabled: boolean;
position: {
x: number;
y: number;
};
linkParams: {
file: string;
line: number;
column: number;
};
enable: () => void;
disable: () => void;
toggleEnabled: () => void;
openInEditor: (url: URL) => void;
onUpdated: () => void;
}
type VueInspectorData = VueInspectorClient['linkParams'] & Partial<VueInspectorClient['position']>;
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
filePath: string;
size: number;
mtime: number;
layer?: string;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ComponentRelationship {
id: string;
deps: string[];
}
interface ComponentWithRelationships {
component: Component;
dependencies?: string[];
dependents?: string[];
}
interface CodeServerOptions {
codeBinary: string;
launchArg: string;
licenseTermsArg: string;
connectionTokenArg: string;
}
type CodeServerType = 'ms-code-cli' | 'ms-code-server' | 'coder-code-server';
interface ModuleOptions {
/**
* Enable DevTools
*
* @default true
*/
enabled?: boolean;
/**
* Custom tabs
*
* This is in static format, for dynamic injection, call `nuxt.hook('devtools:customTabs')` instead
*/
customTabs?: ModuleCustomTab[];
/**
* VS Code Server integration options.
*/
vscode?: VSCodeIntegrationOptions;
/**
* Enable Vue Component Inspector
*
* @default true
*/
componentInspector?: boolean;
/**
* Enable Vue DevTools integration
*/
vueDevTools?: boolean;
/**
* Enable vite-plugin-inspect
*
* @default true
*/
viteInspect?: boolean;
/**
* Disable dev time authorization check.
*
* **NOT RECOMMENDED**, only use this if you know what you are doing.
*
* @see https://github.com/nuxt/devtools/pull/257
* @default false
*/
disableAuthorization?: boolean;
/**
* Props for the iframe element, useful for environment with stricter CSP
*/
iframeProps?: Record<string, string | boolean>;
/**
* Experimental features
*/
experimental?: {
/**
* Timeline tab
* @deprecated Use `timeline.enable` instead
*/
timeline?: boolean;
};
/**
* Options for the timeline tab
*/
timeline?: {
/**
* Enable timeline tab
*
* @default false
*/
enabled?: boolean;
/**
* Track on function calls
*/
functions?: {
include?: (string | RegExp | ((item: Import) => boolean))[];
/**
* Include from specific modules
*
* @default ['#app', '@unhead/vue']
*/
includeFrom?: string[];
exclude?: (string | RegExp | ((item: Import) => boolean))[];
};
};
/**
* Options for assets tab
*/
assets?: {
/**
* Allowed file extensions for assets tab to upload.
* To security concern.
*
* Set to '*' to disbale this limitation entirely
*
* @default Common media and txt files
*/
uploadExtensions?: '*' | string[];
};
/**
* Enable anonymous telemetry, helping us improve Nuxt DevTools.
*
* By default it will respect global Nuxt telemetry settings.
*/
telemetry?: boolean;
}
interface ModuleGlobalOptions {
/**
* List of projects to enable devtools for. Only works when devtools is installed globally.
*/
projects?: string[];
}
interface VSCodeIntegrationOptions {
/**
* Enable VS Code Server integration
*/
enabled?: boolean;
/**
* Start VS Code Server on boot
*
* @default false
*/
startOnBoot?: boolean;
/**
* Port to start VS Code Server
*
* @default 3080
*/
port?: number;
/**
* Reuse existing server if available (same port)
*/
reuseExistingServer?: boolean;
/**
* Determine whether to use code-server or vs code tunnel
*
* @default 'local-serve'
*/
mode?: 'local-serve' | 'tunnel';
/**
* Options for VS Code tunnel
*/
tunnel?: VSCodeTunnelOptions;
/**
* Determines which binary and arguments to use for VS Code.
*
* By default, uses the MS Code Server (ms-code-server).
* Can alternatively use the open source Coder code-server (coder-code-server),
* or the MS VS Code CLI (ms-code-cli)
* @default 'ms-code-server'
*/
codeServer?: CodeServerType;
/**
* Host address to listen on. Unspecified by default.
*/
host?: string;
}
interface VSCodeTunnelOptions {
/**
* the machine name for port forwarding service
*
* default: device hostname
*/
name?: string;
}
interface NuxtDevToolsOptions {
behavior: {
telemetry: boolean | null;
openInEditor: string | undefined;
};
ui: {
componentsGraphShowGlobalComponents: boolean;
componentsGraphShowLayouts: boolean;
componentsGraphShowNodeModules: boolean;
componentsGraphShowPages: boolean;
componentsGraphShowWorkspace: boolean;
componentsView: 'list' | 'graph';
hiddenTabCategories: string[];
hiddenTabs: string[];
interactionCloseOnOutsideClick: boolean;
minimizePanelInactive: number;
pinnedTabs: string[];
scale: number;
showExperimentalFeatures: boolean;
showHelpButtons: boolean;
showPanel: boolean | null;
sidebarExpanded: boolean;
sidebarScrollable: boolean;
};
serverRoutes: {
selectedRoute: ServerRouteInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
sendFrom: 'app' | 'devtools';
};
serverTasks: {
enabled: boolean;
selectedTask: ServerTaskInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
};
assets: {
view: 'grid' | 'list';
};
}
interface AnalyzeBuildMeta extends NuxtAnalyzeMeta {
features: {
bundleClient: boolean;
bundleNitro: boolean;
viteInspect: boolean;
};
size: {
clientBundle?: number;
nitroBundle?: number;
};
}
interface AnalyzeBuildsInfo {
isBuilding: boolean;
builds: AnalyzeBuildMeta[];
}
interface TerminalBase {
id: string;
name: string;
description?: string;
icon?: string;
}
type TerminalAction = 'restart' | 'terminate' | 'clear' | 'remove';
interface SubprocessOptions extends Options {
command: string;
args?: string[];
}
interface TerminalInfo extends TerminalBase {
/**
* Whether the terminal can be restarted
*/
restartable?: boolean;
/**
* Whether the terminal can be terminated
*/
terminatable?: boolean;
/**
* Whether the terminal is terminated
*/
isTerminated?: boolean;
/**
* Content buffer
*/
buffer?: string;
}
interface TerminalState extends TerminalInfo {
/**
* User action to restart the terminal, when not provided, this action will be disabled
*/
onActionRestart?: () => Promise<void> | void;
/**
* User action to terminate the terminal, when not provided, this action will be disabled
*/
onActionTerminate?: () => Promise<void> | void;
}
interface WizardFunctions {
enablePages: (nuxt: any) => Promise<void>;
}
type WizardActions = keyof WizardFunctions;
type GetWizardArgs<T extends WizardActions> = WizardFunctions[T] extends (nuxt: any, ...args: infer A) => any ? A : never;
interface ServerFunctions {
getServerConfig: () => NuxtOptions;
getServerDebugContext: () => Promise<ServerDebugContext | undefined>;
getServerData: (token: string) => Promise<NuxtServerData>;
getServerRuntimeConfig: () => Record<string, any>;
getModuleOptions: () => ModuleOptions;
getComponents: () => Component[];
getComponentsRelationships: () => Promise<ComponentRelationship[]>;
getAutoImports: () => AutoImportsWithMetadata;
getServerPages: () => NuxtPage[];
getCustomTabs: () => ModuleCustomTab[];
getServerHooks: () => HookInfo[];
getServerLayouts: () => NuxtLayout[];
getStaticAssets: () => Promise<AssetInfo[]>;
getServerRoutes: () => ServerRouteInfo[];
getServerTasks: () => ScannedNitroTasks | null;
getServerApp: () => NuxtApp | undefined;
getOptions: <T extends keyof NuxtDevToolsOptions>(tab: T) => Promise<NuxtDevToolsOptions[T]>;
updateOptions: <T extends keyof NuxtDevToolsOptions>(tab: T, settings: Partial<NuxtDevToolsOptions[T]>) => Promise<void>;
clearOptions: () => Promise<void>;
checkForUpdateFor: (name: string) => Promise<PackageUpdateInfo | undefined>;
getNpmCommand: (command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<string[] | undefined>;
runNpmCommand: (token: string, command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<{
processId: string;
} | undefined>;
getTerminals: () => TerminalInfo[];
getTerminalDetail: (token: string, id: string) => Promise<TerminalInfo | undefined>;
runTerminalAction: (token: string, id: string, action: TerminalAction) => Promise<boolean>;
getStorageMounts: () => Promise<StorageMounts>;
getStorageKeys: (base?: string) => Promise<string[]>;
getStorageItem: (token: string, key: string) => Promise<StorageValue>;
setStorageItem: (token: string, key: string, value: StorageValue) => Promise<void>;
removeStorageItem: (token: string, key: string) => Promise<void>;
getAnalyzeBuildInfo: () => Promise<AnalyzeBuildsInfo>;
generateAnalyzeBuildName: () => Promise<string>;
startAnalyzeBuild: (token: string, name: string) => Promise<string>;
clearAnalyzeBuilds: (token: string, names?: string[]) => Promise<void>;
getImageMeta: (token: string, filepath: string) => Promise<ImageMeta | undefined>;
getTextAssetContent: (token: string, filepath: string, limit?: number) => Promise<string | undefined>;
writeStaticAssets: (token: string, file: AssetEntry[], folder: string) => Promise<string[]>;
deleteStaticAsset: (token: string, filepath: string) => Promise<void>;
renameStaticAsset: (token: string, oldPath: string, newPath: string) => Promise<void>;
telemetryEvent: (payload: object, immediate?: boolean) => void;
customTabAction: (name: string, action: number) => Promise<boolean>;
runWizard: <T extends WizardActions>(token: string, name: T, ...args: GetWizardArgs<T>) => Promise<void>;
openInEditor: (filepath: string) => Promise<boolean>;
restartNuxt: (token: string, hard?: boolean) => Promise<void>;
installNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
uninstallNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
enableTimeline: (dry: boolean) => Promise<[string, string]>;
requestForAuth: (info?: string, origin?: string) => Promise<void>;
verifyAuthToken: (token: string) => Promise<boolean>;
}
interface ClientFunctions {
refresh: (event: ClientUpdateEvent) => void;
callHook: (hook: string, ...args: any[]) => Promise<void>;
navigateTo: (path: string) => void;
onTerminalData: (_: {
id: string;
data: string;
}) => void;
onTerminalExit: (_: {
id: string;
code?: number;
}) => void;
}
interface NuxtServerData {
nuxt: NuxtOptions;
nitro?: Nitro['options'];
vite: {
server?: ResolvedConfig;
client?: ResolvedConfig;
};
}
type ClientUpdateEvent = keyof ServerFunctions;
/**
* @internal
*/
interface NuxtDevtoolsServerContext {
nuxt: Nuxt;
options: ModuleOptions;
rpc: BirpcGroup<ClientFunctions, ServerFunctions>;
/**
* Hook to open file in editor
*/
openInEditorHooks: ((filepath: string) => boolean | void | Promise<boolean | void>)[];
/**
* Invalidate client cache for a function and ask for re-fetching
*/
refresh: (event: keyof ServerFunctions) => void;
/**
* Ensure dev auth token is valid, throw if not
*/
ensureDevAuthToken: (token: string) => Promise<void>;
extendServerRpc: <ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>;
}
interface NuxtDevtoolsInfo {
version: string;
packagePath: string;
isGlobalInstall: boolean;
}
interface InstallModuleReturn {
configOriginal: string;
configGenerated: string;
commands: string[];
processId: string;
}
type ServerDebugModuleMutationRecord = (Omit<NuxtDebugModuleMutationRecord, 'module'> & {
name: string;
});
interface ServerDebugContext {
moduleMutationRecords: ServerDebugModuleMutationRecord[];
}
declare module '@nuxt/schema' {
interface NuxtHooks {
/**
* Called before devtools starts. Useful to detect if devtools is enabled.
*/
'devtools:before': () => void;
/**
* Called after devtools is initialized.
*/
'devtools:initialized': (info: NuxtDevtoolsInfo) => void;
/**
* Hooks to extend devtools tabs.
*/
'devtools:customTabs': (tabs: ModuleCustomTab[]) => void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
'devtools:customTabs:refresh': () => void;
/**
* Register a terminal.
*/
'devtools:terminal:register': (terminal: TerminalState) => void;
/**
* Write to a terminal.
*
* Returns true if terminal is found.
*/
'devtools:terminal:write': (_: {
id: string;
data: string;
}) => void;
/**
* Remove a terminal from devtools.
*
* Returns true if terminal is found and deleted.
*/
'devtools:terminal:remove': (_: {
id: string;
}) => void;
/**
* Mark a terminal as terminated.
*/
'devtools:terminal:exit': (_: {
id: string;
code?: number;
}) => void;
}
}
declare module '@nuxt/schema' {
/**
* Runtime Hooks
*/
interface RuntimeNuxtHooks {
/**
* On terminal data.
*/
'devtools:terminal:data': (payload: {
id: string;
data: string;
}) => void;
}
}
export type { CodeServerType as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleCompatibility as D, ModuleStats as E, CompatibilityStatus as F, ModuleType as G, HookInfo as H, ImageMeta as I, MaintainerInfo as J, GitHubContributor as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, VueInspectorData as O, PluginMetric as P, AssetType as Q, RouteInfo as R, SubprocessOptions as S, TerminalState as T, AssetInfo as U, VueInspectorClient as V, AssetEntry as W, CodeSnippet as X, ComponentRelationship as Y, ComponentWithRelationships as Z, CodeServerOptions as _, ServerFunctions as a, ModuleOptions as a0, ModuleGlobalOptions as a1, VSCodeIntegrationOptions as a2, VSCodeTunnelOptions as a3, NuxtDevToolsOptions as a4, NuxtServerData as a5, ClientUpdateEvent as a6, NuxtDevtoolsServerContext as a7, InstallModuleReturn as a8, ServerDebugModuleMutationRecord as a9, ServerDebugContext as aa, TerminalBase as ab, TerminalAction as ac, TerminalInfo as ad, WizardFunctions as ae, WizardActions as af, GetWizardArgs as ag, AnalyzeBuildsInfo as b, TabCategory as c, ModuleLaunchView as d, ModuleIframeView as e, ModuleVNodeView as f, ModuleLaunchAction as g, ModuleView as h, ModuleIframeTabLazyOptions as i, ModuleBuiltinTab as j, ModuleTabInfo as k, CategorizedTabs as l, PackageUpdateInfo as m, PackageManagerName as n, NpmCommandType as o, NpmCommandOptions as p, AutoImportsWithMetadata as q, ServerRouteInfo as r, ServerRouteInputType as s, ServerRouteInput as t, Payload as u, ServerTaskInfo as v, ScannedNitroTasks as w, PluginInfoWithMetic as x, InstalledModuleInfo as y, ModuleStaticInfo as z };
@@ -0,0 +1,783 @@
import { VNode, MaybeRefOrGetter } from 'vue';
import { BirpcGroup } from 'birpc';
import { Component, NuxtOptions, NuxtPage, NuxtLayout, NuxtApp, NuxtDebugModuleMutationRecord, Nuxt } from 'nuxt/schema';
import { Import, UnimportMeta } from 'unimport';
import { RouteRecordNormalized } from 'vue-router';
import { Nitro, StorageMounts } from 'nitropack';
import { StorageValue } from 'unstorage';
import { ResolvedConfig } from 'vite';
import { NuxtAnalyzeMeta } from '@nuxt/schema';
import { Options } from 'execa';
type TabCategory = 'pinned' | 'app' | 'vue-devtools' | 'analyze' | 'server' | 'modules' | 'documentation' | 'advanced';
interface ModuleCustomTab {
/**
* The name of the tab, must be unique
*/
name: string;
/**
* Icon of the tab, support any Iconify icons, or a url to an image
*/
icon?: string;
/**
* Title of the tab
*/
title: string;
/**
* Main view of the tab
*/
view: ModuleView;
/**
* Category of the tab
* @default 'app'
*/
category?: TabCategory;
/**
* Insert static vnode to the tab entry
*
* Advanced options. You don't usually need this.
*/
extraTabVNode?: VNode;
/**
* Require local authentication to access the tab
* It's highly recommended to enable this if the tab have sensitive information or have access to the OS
*
* @default false
*/
requireAuth?: boolean;
}
interface ModuleLaunchView {
/**
* A view for module to lazy launch some actions
*/
type: 'launch';
title?: string;
icon?: string;
description: string;
/**
* Action buttons
*/
actions: ModuleLaunchAction[];
}
interface ModuleIframeView {
/**
* Iframe view
*/
type: 'iframe';
/**
* Url of the iframe
*/
src: string;
/**
* Persist the iframe instance even if the tab is not active
*
* @default true
*/
persistent?: boolean;
}
interface ModuleVNodeView {
/**
* Vue's VNode view
*/
type: 'vnode';
/**
* Send vnode to the client, they must be static and serializable
*
* Call `nuxt.hook('devtools:customTabs:refresh')` to trigger manual refresh
*/
vnode: VNode;
}
interface ModuleLaunchAction {
/**
* Label of the action button
*/
label: string;
/**
* Additional HTML attributes to the action button
*/
attrs?: Record<string, string>;
/**
* Indicate if the action is pending, will show a loading indicator and disable the button
*/
pending?: boolean;
/**
* Function to handle the action, this is executed on the server side.
* Will automatically refresh the tabs after the action is resolved.
*/
handle?: () => void | Promise<void>;
/**
* Treat the action as a link, will open the link in a new tab
*/
src?: string;
}
type ModuleView = ModuleIframeView | ModuleLaunchView | ModuleVNodeView;
interface ModuleIframeTabLazyOptions {
description?: string;
onLoad?: () => Promise<void>;
}
interface ModuleBuiltinTab {
name: string;
icon?: string;
title?: string;
path?: string;
category?: TabCategory;
show?: () => MaybeRefOrGetter<any>;
badge?: () => MaybeRefOrGetter<number | string | undefined>;
onClick?: () => void;
}
type ModuleTabInfo = ModuleCustomTab | ModuleBuiltinTab;
type CategorizedTabs = [TabCategory, (ModuleCustomTab | ModuleBuiltinTab)[]][];
interface HookInfo {
name: string;
start: number;
end?: number;
duration?: number;
listeners: number;
executions: number[];
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface PackageUpdateInfo {
name: string;
current: string;
latest: string;
needsUpdate: boolean;
}
type PackageManagerName = 'npm' | 'yarn' | 'pnpm' | 'bun';
type NpmCommandType = 'install' | 'uninstall' | 'update';
interface NpmCommandOptions {
dev?: boolean;
global?: boolean;
}
interface AutoImportsWithMetadata {
imports: Import[];
metadata?: UnimportMeta;
dirs: string[];
}
interface RouteInfo extends Pick<RouteRecordNormalized, 'name' | 'path' | 'meta' | 'props' | 'children'> {
file?: string;
}
interface ServerRouteInfo {
route: string;
filepath: string;
method?: string;
type: 'api' | 'route' | 'runtime' | 'collection';
routes?: ServerRouteInfo[];
}
type ServerRouteInputType = 'string' | 'number' | 'boolean' | 'file' | 'date' | 'time' | 'datetime-local';
interface ServerRouteInput {
active: boolean;
key: string;
value: any;
type?: ServerRouteInputType;
}
interface Payload {
url: string;
time: number;
data?: Record<string, any>;
state?: Record<string, any>;
functions?: Record<string, any>;
}
interface ServerTaskInfo {
name: string;
handler: string;
description: string;
type: 'collection' | 'task';
tasks?: ServerTaskInfo[];
}
interface ScannedNitroTasks {
tasks: {
[name: string]: {
handler: string;
description: string;
};
};
scheduledTasks: {
[cron: string]: string[];
};
}
interface PluginInfoWithMetic {
src: string;
mode?: 'client' | 'server' | 'all';
ssr?: boolean;
metric?: PluginMetric;
}
interface PluginMetric {
src: string;
start: number;
end: number;
duration: number;
}
interface LoadingTimeMetric {
ssrStart?: number;
appInit?: number;
appLoad?: number;
pageStart?: number;
pageEnd?: number;
pluginInit?: number;
hmrStart?: number;
hmrEnd?: number;
}
interface BasicModuleInfo {
entryPath?: string;
meta?: {
name?: string;
};
}
interface InstalledModuleInfo {
name?: string;
isPackageModule: boolean;
isUninstallable: boolean;
info?: ModuleStaticInfo;
entryPath?: string;
timings?: Record<string, number | undefined>;
meta?: {
name?: string;
};
}
interface ModuleStaticInfo {
name: string;
description: string;
repo: string;
npm: string;
icon?: string;
github: string;
website: string;
learn_more: string;
category: string;
type: ModuleType;
stats: ModuleStats;
maintainers: MaintainerInfo[];
contributors: GitHubContributor[];
compatibility: ModuleCompatibility;
}
interface ModuleCompatibility {
nuxt: string;
requires: {
bridge?: boolean | 'optional';
};
}
interface ModuleStats {
downloads: number;
stars: number;
publishedAt: number;
createdAt: number;
}
type CompatibilityStatus = 'working' | 'wip' | 'unknown' | 'not-working';
type ModuleType = 'community' | 'official' | '3rd-party';
interface MaintainerInfo {
name: string;
github: string;
twitter?: string;
}
interface GitHubContributor {
login: string;
name?: string;
avatar_url?: string;
}
interface VueInspectorClient {
enabled: boolean;
position: {
x: number;
y: number;
};
linkParams: {
file: string;
line: number;
column: number;
};
enable: () => void;
disable: () => void;
toggleEnabled: () => void;
openInEditor: (url: URL) => void;
onUpdated: () => void;
}
type VueInspectorData = VueInspectorClient['linkParams'] & Partial<VueInspectorClient['position']>;
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
filePath: string;
size: number;
mtime: number;
layer?: string;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ComponentRelationship {
id: string;
deps: string[];
}
interface ComponentWithRelationships {
component: Component;
dependencies?: string[];
dependents?: string[];
}
interface CodeServerOptions {
codeBinary: string;
launchArg: string;
licenseTermsArg: string;
connectionTokenArg: string;
}
type CodeServerType = 'ms-code-cli' | 'ms-code-server' | 'coder-code-server';
interface ModuleOptions {
/**
* Enable DevTools
*
* @default true
*/
enabled?: boolean;
/**
* Custom tabs
*
* This is in static format, for dynamic injection, call `nuxt.hook('devtools:customTabs')` instead
*/
customTabs?: ModuleCustomTab[];
/**
* VS Code Server integration options.
*/
vscode?: VSCodeIntegrationOptions;
/**
* Enable Vue Component Inspector
*
* @default true
*/
componentInspector?: boolean;
/**
* Enable Vue DevTools integration
*/
vueDevTools?: boolean;
/**
* Enable vite-plugin-inspect
*
* @default true
*/
viteInspect?: boolean;
/**
* Disable dev time authorization check.
*
* **NOT RECOMMENDED**, only use this if you know what you are doing.
*
* @see https://github.com/nuxt/devtools/pull/257
* @default false
*/
disableAuthorization?: boolean;
/**
* Props for the iframe element, useful for environment with stricter CSP
*/
iframeProps?: Record<string, string | boolean>;
/**
* Experimental features
*/
experimental?: {
/**
* Timeline tab
* @deprecated Use `timeline.enable` instead
*/
timeline?: boolean;
};
/**
* Options for the timeline tab
*/
timeline?: {
/**
* Enable timeline tab
*
* @default false
*/
enabled?: boolean;
/**
* Track on function calls
*/
functions?: {
include?: (string | RegExp | ((item: Import) => boolean))[];
/**
* Include from specific modules
*
* @default ['#app', '@unhead/vue']
*/
includeFrom?: string[];
exclude?: (string | RegExp | ((item: Import) => boolean))[];
};
};
/**
* Options for assets tab
*/
assets?: {
/**
* Allowed file extensions for assets tab to upload.
* To security concern.
*
* Set to '*' to disbale this limitation entirely
*
* @default Common media and txt files
*/
uploadExtensions?: '*' | string[];
};
/**
* Enable anonymous telemetry, helping us improve Nuxt DevTools.
*
* By default it will respect global Nuxt telemetry settings.
*/
telemetry?: boolean;
}
interface ModuleGlobalOptions {
/**
* List of projects to enable devtools for. Only works when devtools is installed globally.
*/
projects?: string[];
}
interface VSCodeIntegrationOptions {
/**
* Enable VS Code Server integration
*/
enabled?: boolean;
/**
* Start VS Code Server on boot
*
* @default false
*/
startOnBoot?: boolean;
/**
* Port to start VS Code Server
*
* @default 3080
*/
port?: number;
/**
* Reuse existing server if available (same port)
*/
reuseExistingServer?: boolean;
/**
* Determine whether to use code-server or vs code tunnel
*
* @default 'local-serve'
*/
mode?: 'local-serve' | 'tunnel';
/**
* Options for VS Code tunnel
*/
tunnel?: VSCodeTunnelOptions;
/**
* Determines which binary and arguments to use for VS Code.
*
* By default, uses the MS Code Server (ms-code-server).
* Can alternatively use the open source Coder code-server (coder-code-server),
* or the MS VS Code CLI (ms-code-cli)
* @default 'ms-code-server'
*/
codeServer?: CodeServerType;
/**
* Host address to listen on. Unspecified by default.
*/
host?: string;
}
interface VSCodeTunnelOptions {
/**
* the machine name for port forwarding service
*
* default: device hostname
*/
name?: string;
}
interface NuxtDevToolsOptions {
behavior: {
telemetry: boolean | null;
openInEditor: string | undefined;
};
ui: {
componentsGraphShowGlobalComponents: boolean;
componentsGraphShowLayouts: boolean;
componentsGraphShowNodeModules: boolean;
componentsGraphShowPages: boolean;
componentsGraphShowWorkspace: boolean;
componentsView: 'list' | 'graph';
hiddenTabCategories: string[];
hiddenTabs: string[];
interactionCloseOnOutsideClick: boolean;
minimizePanelInactive: number;
pinnedTabs: string[];
scale: number;
showExperimentalFeatures: boolean;
showHelpButtons: boolean;
showPanel: boolean | null;
sidebarExpanded: boolean;
sidebarScrollable: boolean;
};
serverRoutes: {
selectedRoute: ServerRouteInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
sendFrom: 'app' | 'devtools';
};
serverTasks: {
enabled: boolean;
selectedTask: ServerTaskInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
};
assets: {
view: 'grid' | 'list';
};
}
interface AnalyzeBuildMeta extends NuxtAnalyzeMeta {
features: {
bundleClient: boolean;
bundleNitro: boolean;
viteInspect: boolean;
};
size: {
clientBundle?: number;
nitroBundle?: number;
};
}
interface AnalyzeBuildsInfo {
isBuilding: boolean;
builds: AnalyzeBuildMeta[];
}
interface TerminalBase {
id: string;
name: string;
description?: string;
icon?: string;
}
type TerminalAction = 'restart' | 'terminate' | 'clear' | 'remove';
interface SubprocessOptions extends Options {
command: string;
args?: string[];
}
interface TerminalInfo extends TerminalBase {
/**
* Whether the terminal can be restarted
*/
restartable?: boolean;
/**
* Whether the terminal can be terminated
*/
terminatable?: boolean;
/**
* Whether the terminal is terminated
*/
isTerminated?: boolean;
/**
* Content buffer
*/
buffer?: string;
}
interface TerminalState extends TerminalInfo {
/**
* User action to restart the terminal, when not provided, this action will be disabled
*/
onActionRestart?: () => Promise<void> | void;
/**
* User action to terminate the terminal, when not provided, this action will be disabled
*/
onActionTerminate?: () => Promise<void> | void;
}
interface WizardFunctions {
enablePages: (nuxt: any) => Promise<void>;
}
type WizardActions = keyof WizardFunctions;
type GetWizardArgs<T extends WizardActions> = WizardFunctions[T] extends (nuxt: any, ...args: infer A) => any ? A : never;
interface ServerFunctions {
getServerConfig: () => NuxtOptions;
getServerDebugContext: () => Promise<ServerDebugContext | undefined>;
getServerData: (token: string) => Promise<NuxtServerData>;
getServerRuntimeConfig: () => Record<string, any>;
getModuleOptions: () => ModuleOptions;
getComponents: () => Component[];
getComponentsRelationships: () => Promise<ComponentRelationship[]>;
getAutoImports: () => AutoImportsWithMetadata;
getServerPages: () => NuxtPage[];
getCustomTabs: () => ModuleCustomTab[];
getServerHooks: () => HookInfo[];
getServerLayouts: () => NuxtLayout[];
getStaticAssets: () => Promise<AssetInfo[]>;
getServerRoutes: () => ServerRouteInfo[];
getServerTasks: () => ScannedNitroTasks | null;
getServerApp: () => NuxtApp | undefined;
getOptions: <T extends keyof NuxtDevToolsOptions>(tab: T) => Promise<NuxtDevToolsOptions[T]>;
updateOptions: <T extends keyof NuxtDevToolsOptions>(tab: T, settings: Partial<NuxtDevToolsOptions[T]>) => Promise<void>;
clearOptions: () => Promise<void>;
checkForUpdateFor: (name: string) => Promise<PackageUpdateInfo | undefined>;
getNpmCommand: (command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<string[] | undefined>;
runNpmCommand: (token: string, command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<{
processId: string;
} | undefined>;
getTerminals: () => TerminalInfo[];
getTerminalDetail: (token: string, id: string) => Promise<TerminalInfo | undefined>;
runTerminalAction: (token: string, id: string, action: TerminalAction) => Promise<boolean>;
getStorageMounts: () => Promise<StorageMounts>;
getStorageKeys: (base?: string) => Promise<string[]>;
getStorageItem: (token: string, key: string) => Promise<StorageValue>;
setStorageItem: (token: string, key: string, value: StorageValue) => Promise<void>;
removeStorageItem: (token: string, key: string) => Promise<void>;
getAnalyzeBuildInfo: () => Promise<AnalyzeBuildsInfo>;
generateAnalyzeBuildName: () => Promise<string>;
startAnalyzeBuild: (token: string, name: string) => Promise<string>;
clearAnalyzeBuilds: (token: string, names?: string[]) => Promise<void>;
getImageMeta: (token: string, filepath: string) => Promise<ImageMeta | undefined>;
getTextAssetContent: (token: string, filepath: string, limit?: number) => Promise<string | undefined>;
writeStaticAssets: (token: string, file: AssetEntry[], folder: string) => Promise<string[]>;
deleteStaticAsset: (token: string, filepath: string) => Promise<void>;
renameStaticAsset: (token: string, oldPath: string, newPath: string) => Promise<void>;
telemetryEvent: (payload: object, immediate?: boolean) => void;
customTabAction: (name: string, action: number) => Promise<boolean>;
runWizard: <T extends WizardActions>(token: string, name: T, ...args: GetWizardArgs<T>) => Promise<void>;
openInEditor: (filepath: string) => Promise<boolean>;
restartNuxt: (token: string, hard?: boolean) => Promise<void>;
installNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
uninstallNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
enableTimeline: (dry: boolean) => Promise<[string, string]>;
requestForAuth: (info?: string, origin?: string) => Promise<void>;
verifyAuthToken: (token: string) => Promise<boolean>;
}
interface ClientFunctions {
refresh: (event: ClientUpdateEvent) => void;
callHook: (hook: string, ...args: any[]) => Promise<void>;
navigateTo: (path: string) => void;
onTerminalData: (_: {
id: string;
data: string;
}) => void;
onTerminalExit: (_: {
id: string;
code?: number;
}) => void;
}
interface NuxtServerData {
nuxt: NuxtOptions;
nitro?: Nitro['options'];
vite: {
server?: ResolvedConfig;
client?: ResolvedConfig;
};
}
type ClientUpdateEvent = keyof ServerFunctions;
/**
* @internal
*/
interface NuxtDevtoolsServerContext {
nuxt: Nuxt;
options: ModuleOptions;
rpc: BirpcGroup<ClientFunctions, ServerFunctions>;
/**
* Hook to open file in editor
*/
openInEditorHooks: ((filepath: string) => boolean | void | Promise<boolean | void>)[];
/**
* Invalidate client cache for a function and ask for re-fetching
*/
refresh: (event: keyof ServerFunctions) => void;
/**
* Ensure dev auth token is valid, throw if not
*/
ensureDevAuthToken: (token: string) => Promise<void>;
extendServerRpc: <ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>;
}
interface NuxtDevtoolsInfo {
version: string;
packagePath: string;
isGlobalInstall: boolean;
}
interface InstallModuleReturn {
configOriginal: string;
configGenerated: string;
commands: string[];
processId: string;
}
type ServerDebugModuleMutationRecord = (Omit<NuxtDebugModuleMutationRecord, 'module'> & {
name: string;
});
interface ServerDebugContext {
moduleMutationRecords: ServerDebugModuleMutationRecord[];
}
declare module '@nuxt/schema' {
interface NuxtHooks {
/**
* Called before devtools starts. Useful to detect if devtools is enabled.
*/
'devtools:before': () => void;
/**
* Called after devtools is initialized.
*/
'devtools:initialized': (info: NuxtDevtoolsInfo) => void;
/**
* Hooks to extend devtools tabs.
*/
'devtools:customTabs': (tabs: ModuleCustomTab[]) => void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
'devtools:customTabs:refresh': () => void;
/**
* Register a terminal.
*/
'devtools:terminal:register': (terminal: TerminalState) => void;
/**
* Write to a terminal.
*
* Returns true if terminal is found.
*/
'devtools:terminal:write': (_: {
id: string;
data: string;
}) => void;
/**
* Remove a terminal from devtools.
*
* Returns true if terminal is found and deleted.
*/
'devtools:terminal:remove': (_: {
id: string;
}) => void;
/**
* Mark a terminal as terminated.
*/
'devtools:terminal:exit': (_: {
id: string;
code?: number;
}) => void;
}
}
declare module '@nuxt/schema' {
/**
* Runtime Hooks
*/
interface RuntimeNuxtHooks {
/**
* On terminal data.
*/
'devtools:terminal:data': (payload: {
id: string;
data: string;
}) => void;
}
}
export type { CodeServerType as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleCompatibility as D, ModuleStats as E, CompatibilityStatus as F, ModuleType as G, HookInfo as H, ImageMeta as I, MaintainerInfo as J, GitHubContributor as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, VueInspectorData as O, PluginMetric as P, AssetType as Q, RouteInfo as R, SubprocessOptions as S, TerminalState as T, AssetInfo as U, VueInspectorClient as V, AssetEntry as W, CodeSnippet as X, ComponentRelationship as Y, ComponentWithRelationships as Z, CodeServerOptions as _, ServerFunctions as a, ModuleOptions as a0, ModuleGlobalOptions as a1, VSCodeIntegrationOptions as a2, VSCodeTunnelOptions as a3, NuxtDevToolsOptions as a4, NuxtServerData as a5, ClientUpdateEvent as a6, NuxtDevtoolsServerContext as a7, InstallModuleReturn as a8, ServerDebugModuleMutationRecord as a9, ServerDebugContext as aa, TerminalBase as ab, TerminalAction as ac, TerminalInfo as ad, WizardFunctions as ae, WizardActions as af, GetWizardArgs as ag, AnalyzeBuildsInfo as b, TabCategory as c, ModuleLaunchView as d, ModuleIframeView as e, ModuleVNodeView as f, ModuleLaunchAction as g, ModuleView as h, ModuleIframeTabLazyOptions as i, ModuleBuiltinTab as j, ModuleTabInfo as k, CategorizedTabs as l, PackageUpdateInfo as m, PackageManagerName as n, NpmCommandType as o, NpmCommandOptions as p, AutoImportsWithMetadata as q, ServerRouteInfo as r, ServerRouteInputType as s, ServerRouteInput as t, Payload as u, ServerTaskInfo as v, ScannedNitroTasks as w, PluginInfoWithMetic as x, InstalledModuleInfo as y, ModuleStaticInfo as z };
@@ -0,0 +1,783 @@
import { VNode, MaybeRefOrGetter } from 'vue';
import { BirpcGroup } from 'birpc';
import { Component, NuxtOptions, NuxtPage, NuxtLayout, NuxtApp, NuxtDebugModuleMutationRecord, Nuxt } from 'nuxt/schema';
import { Import, UnimportMeta } from 'unimport';
import { RouteRecordNormalized } from 'vue-router';
import { Nitro, StorageMounts } from 'nitropack';
import { StorageValue } from 'unstorage';
import { ResolvedConfig } from 'vite';
import { NuxtAnalyzeMeta } from '@nuxt/schema';
import { Options } from 'execa';
type TabCategory = 'pinned' | 'app' | 'vue-devtools' | 'analyze' | 'server' | 'modules' | 'documentation' | 'advanced';
interface ModuleCustomTab {
/**
* The name of the tab, must be unique
*/
name: string;
/**
* Icon of the tab, support any Iconify icons, or a url to an image
*/
icon?: string;
/**
* Title of the tab
*/
title: string;
/**
* Main view of the tab
*/
view: ModuleView;
/**
* Category of the tab
* @default 'app'
*/
category?: TabCategory;
/**
* Insert static vnode to the tab entry
*
* Advanced options. You don't usually need this.
*/
extraTabVNode?: VNode;
/**
* Require local authentication to access the tab
* It's highly recommended to enable this if the tab have sensitive information or have access to the OS
*
* @default false
*/
requireAuth?: boolean;
}
interface ModuleLaunchView {
/**
* A view for module to lazy launch some actions
*/
type: 'launch';
title?: string;
icon?: string;
description: string;
/**
* Action buttons
*/
actions: ModuleLaunchAction[];
}
interface ModuleIframeView {
/**
* Iframe view
*/
type: 'iframe';
/**
* Url of the iframe
*/
src: string;
/**
* Persist the iframe instance even if the tab is not active
*
* @default true
*/
persistent?: boolean;
}
interface ModuleVNodeView {
/**
* Vue's VNode view
*/
type: 'vnode';
/**
* Send vnode to the client, they must be static and serializable
*
* Call `nuxt.hook('devtools:customTabs:refresh')` to trigger manual refresh
*/
vnode: VNode;
}
interface ModuleLaunchAction {
/**
* Label of the action button
*/
label: string;
/**
* Additional HTML attributes to the action button
*/
attrs?: Record<string, string>;
/**
* Indicate if the action is pending, will show a loading indicator and disable the button
*/
pending?: boolean;
/**
* Function to handle the action, this is executed on the server side.
* Will automatically refresh the tabs after the action is resolved.
*/
handle?: () => void | Promise<void>;
/**
* Treat the action as a link, will open the link in a new tab
*/
src?: string;
}
type ModuleView = ModuleIframeView | ModuleLaunchView | ModuleVNodeView;
interface ModuleIframeTabLazyOptions {
description?: string;
onLoad?: () => Promise<void>;
}
interface ModuleBuiltinTab {
name: string;
icon?: string;
title?: string;
path?: string;
category?: TabCategory;
show?: () => MaybeRefOrGetter<any>;
badge?: () => MaybeRefOrGetter<number | string | undefined>;
onClick?: () => void;
}
type ModuleTabInfo = ModuleCustomTab | ModuleBuiltinTab;
type CategorizedTabs = [TabCategory, (ModuleCustomTab | ModuleBuiltinTab)[]][];
interface HookInfo {
name: string;
start: number;
end?: number;
duration?: number;
listeners: number;
executions: number[];
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface PackageUpdateInfo {
name: string;
current: string;
latest: string;
needsUpdate: boolean;
}
type PackageManagerName = 'npm' | 'yarn' | 'pnpm' | 'bun';
type NpmCommandType = 'install' | 'uninstall' | 'update';
interface NpmCommandOptions {
dev?: boolean;
global?: boolean;
}
interface AutoImportsWithMetadata {
imports: Import[];
metadata?: UnimportMeta;
dirs: string[];
}
interface RouteInfo extends Pick<RouteRecordNormalized, 'name' | 'path' | 'meta' | 'props' | 'children'> {
file?: string;
}
interface ServerRouteInfo {
route: string;
filepath: string;
method?: string;
type: 'api' | 'route' | 'runtime' | 'collection';
routes?: ServerRouteInfo[];
}
type ServerRouteInputType = 'string' | 'number' | 'boolean' | 'file' | 'date' | 'time' | 'datetime-local';
interface ServerRouteInput {
active: boolean;
key: string;
value: any;
type?: ServerRouteInputType;
}
interface Payload {
url: string;
time: number;
data?: Record<string, any>;
state?: Record<string, any>;
functions?: Record<string, any>;
}
interface ServerTaskInfo {
name: string;
handler: string;
description: string;
type: 'collection' | 'task';
tasks?: ServerTaskInfo[];
}
interface ScannedNitroTasks {
tasks: {
[name: string]: {
handler: string;
description: string;
};
};
scheduledTasks: {
[cron: string]: string[];
};
}
interface PluginInfoWithMetic {
src: string;
mode?: 'client' | 'server' | 'all';
ssr?: boolean;
metric?: PluginMetric;
}
interface PluginMetric {
src: string;
start: number;
end: number;
duration: number;
}
interface LoadingTimeMetric {
ssrStart?: number;
appInit?: number;
appLoad?: number;
pageStart?: number;
pageEnd?: number;
pluginInit?: number;
hmrStart?: number;
hmrEnd?: number;
}
interface BasicModuleInfo {
entryPath?: string;
meta?: {
name?: string;
};
}
interface InstalledModuleInfo {
name?: string;
isPackageModule: boolean;
isUninstallable: boolean;
info?: ModuleStaticInfo;
entryPath?: string;
timings?: Record<string, number | undefined>;
meta?: {
name?: string;
};
}
interface ModuleStaticInfo {
name: string;
description: string;
repo: string;
npm: string;
icon?: string;
github: string;
website: string;
learn_more: string;
category: string;
type: ModuleType;
stats: ModuleStats;
maintainers: MaintainerInfo[];
contributors: GitHubContributor[];
compatibility: ModuleCompatibility;
}
interface ModuleCompatibility {
nuxt: string;
requires: {
bridge?: boolean | 'optional';
};
}
interface ModuleStats {
downloads: number;
stars: number;
publishedAt: number;
createdAt: number;
}
type CompatibilityStatus = 'working' | 'wip' | 'unknown' | 'not-working';
type ModuleType = 'community' | 'official' | '3rd-party';
interface MaintainerInfo {
name: string;
github: string;
twitter?: string;
}
interface GitHubContributor {
login: string;
name?: string;
avatar_url?: string;
}
interface VueInspectorClient {
enabled: boolean;
position: {
x: number;
y: number;
};
linkParams: {
file: string;
line: number;
column: number;
};
enable: () => void;
disable: () => void;
toggleEnabled: () => void;
openInEditor: (url: URL) => void;
onUpdated: () => void;
}
type VueInspectorData = VueInspectorClient['linkParams'] & Partial<VueInspectorClient['position']>;
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
filePath: string;
size: number;
mtime: number;
layer?: string;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ComponentRelationship {
id: string;
deps: string[];
}
interface ComponentWithRelationships {
component: Component;
dependencies?: string[];
dependents?: string[];
}
interface CodeServerOptions {
codeBinary: string;
launchArg: string;
licenseTermsArg: string;
connectionTokenArg: string;
}
type CodeServerType = 'ms-code-cli' | 'ms-code-server' | 'coder-code-server';
interface ModuleOptions {
/**
* Enable DevTools
*
* @default true
*/
enabled?: boolean;
/**
* Custom tabs
*
* This is in static format, for dynamic injection, call `nuxt.hook('devtools:customTabs')` instead
*/
customTabs?: ModuleCustomTab[];
/**
* VS Code Server integration options.
*/
vscode?: VSCodeIntegrationOptions;
/**
* Enable Vue Component Inspector
*
* @default true
*/
componentInspector?: boolean;
/**
* Enable Vue DevTools integration
*/
vueDevTools?: boolean;
/**
* Enable vite-plugin-inspect
*
* @default true
*/
viteInspect?: boolean;
/**
* Disable dev time authorization check.
*
* **NOT RECOMMENDED**, only use this if you know what you are doing.
*
* @see https://github.com/nuxt/devtools/pull/257
* @default false
*/
disableAuthorization?: boolean;
/**
* Props for the iframe element, useful for environment with stricter CSP
*/
iframeProps?: Record<string, string | boolean>;
/**
* Experimental features
*/
experimental?: {
/**
* Timeline tab
* @deprecated Use `timeline.enable` instead
*/
timeline?: boolean;
};
/**
* Options for the timeline tab
*/
timeline?: {
/**
* Enable timeline tab
*
* @default false
*/
enabled?: boolean;
/**
* Track on function calls
*/
functions?: {
include?: (string | RegExp | ((item: Import) => boolean))[];
/**
* Include from specific modules
*
* @default ['#app', '@unhead/vue']
*/
includeFrom?: string[];
exclude?: (string | RegExp | ((item: Import) => boolean))[];
};
};
/**
* Options for assets tab
*/
assets?: {
/**
* Allowed file extensions for assets tab to upload.
* To security concern.
*
* Set to '*' to disbale this limitation entirely
*
* @default Common media and txt files
*/
uploadExtensions?: '*' | string[];
};
/**
* Enable anonymous telemetry, helping us improve Nuxt DevTools.
*
* By default it will respect global Nuxt telemetry settings.
*/
telemetry?: boolean;
}
interface ModuleGlobalOptions {
/**
* List of projects to enable devtools for. Only works when devtools is installed globally.
*/
projects?: string[];
}
interface VSCodeIntegrationOptions {
/**
* Enable VS Code Server integration
*/
enabled?: boolean;
/**
* Start VS Code Server on boot
*
* @default false
*/
startOnBoot?: boolean;
/**
* Port to start VS Code Server
*
* @default 3080
*/
port?: number;
/**
* Reuse existing server if available (same port)
*/
reuseExistingServer?: boolean;
/**
* Determine whether to use code-server or vs code tunnel
*
* @default 'local-serve'
*/
mode?: 'local-serve' | 'tunnel';
/**
* Options for VS Code tunnel
*/
tunnel?: VSCodeTunnelOptions;
/**
* Determines which binary and arguments to use for VS Code.
*
* By default, uses the MS Code Server (ms-code-server).
* Can alternatively use the open source Coder code-server (coder-code-server),
* or the MS VS Code CLI (ms-code-cli)
* @default 'ms-code-server'
*/
codeServer?: CodeServerType;
/**
* Host address to listen on. Unspecified by default.
*/
host?: string;
}
interface VSCodeTunnelOptions {
/**
* the machine name for port forwarding service
*
* default: device hostname
*/
name?: string;
}
interface NuxtDevToolsOptions {
behavior: {
telemetry: boolean | null;
openInEditor: string | undefined;
};
ui: {
componentsGraphShowGlobalComponents: boolean;
componentsGraphShowLayouts: boolean;
componentsGraphShowNodeModules: boolean;
componentsGraphShowPages: boolean;
componentsGraphShowWorkspace: boolean;
componentsView: 'list' | 'graph';
hiddenTabCategories: string[];
hiddenTabs: string[];
interactionCloseOnOutsideClick: boolean;
minimizePanelInactive: number;
pinnedTabs: string[];
scale: number;
showExperimentalFeatures: boolean;
showHelpButtons: boolean;
showPanel: boolean | null;
sidebarExpanded: boolean;
sidebarScrollable: boolean;
};
serverRoutes: {
selectedRoute: ServerRouteInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
sendFrom: 'app' | 'devtools';
};
serverTasks: {
enabled: boolean;
selectedTask: ServerTaskInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
};
assets: {
view: 'grid' | 'list';
};
}
interface AnalyzeBuildMeta extends NuxtAnalyzeMeta {
features: {
bundleClient: boolean;
bundleNitro: boolean;
viteInspect: boolean;
};
size: {
clientBundle?: number;
nitroBundle?: number;
};
}
interface AnalyzeBuildsInfo {
isBuilding: boolean;
builds: AnalyzeBuildMeta[];
}
interface TerminalBase {
id: string;
name: string;
description?: string;
icon?: string;
}
type TerminalAction = 'restart' | 'terminate' | 'clear' | 'remove';
interface SubprocessOptions extends Options {
command: string;
args?: string[];
}
interface TerminalInfo extends TerminalBase {
/**
* Whether the terminal can be restarted
*/
restartable?: boolean;
/**
* Whether the terminal can be terminated
*/
terminatable?: boolean;
/**
* Whether the terminal is terminated
*/
isTerminated?: boolean;
/**
* Content buffer
*/
buffer?: string;
}
interface TerminalState extends TerminalInfo {
/**
* User action to restart the terminal, when not provided, this action will be disabled
*/
onActionRestart?: () => Promise<void> | void;
/**
* User action to terminate the terminal, when not provided, this action will be disabled
*/
onActionTerminate?: () => Promise<void> | void;
}
interface WizardFunctions {
enablePages: (nuxt: any) => Promise<void>;
}
type WizardActions = keyof WizardFunctions;
type GetWizardArgs<T extends WizardActions> = WizardFunctions[T] extends (nuxt: any, ...args: infer A) => any ? A : never;
interface ServerFunctions {
getServerConfig: () => NuxtOptions;
getServerDebugContext: () => Promise<ServerDebugContext | undefined>;
getServerData: (token: string) => Promise<NuxtServerData>;
getServerRuntimeConfig: () => Record<string, any>;
getModuleOptions: () => ModuleOptions;
getComponents: () => Component[];
getComponentsRelationships: () => Promise<ComponentRelationship[]>;
getAutoImports: () => AutoImportsWithMetadata;
getServerPages: () => NuxtPage[];
getCustomTabs: () => ModuleCustomTab[];
getServerHooks: () => HookInfo[];
getServerLayouts: () => NuxtLayout[];
getStaticAssets: () => Promise<AssetInfo[]>;
getServerRoutes: () => ServerRouteInfo[];
getServerTasks: () => ScannedNitroTasks | null;
getServerApp: () => NuxtApp | undefined;
getOptions: <T extends keyof NuxtDevToolsOptions>(tab: T) => Promise<NuxtDevToolsOptions[T]>;
updateOptions: <T extends keyof NuxtDevToolsOptions>(tab: T, settings: Partial<NuxtDevToolsOptions[T]>) => Promise<void>;
clearOptions: () => Promise<void>;
checkForUpdateFor: (name: string) => Promise<PackageUpdateInfo | undefined>;
getNpmCommand: (command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<string[] | undefined>;
runNpmCommand: (token: string, command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<{
processId: string;
} | undefined>;
getTerminals: () => TerminalInfo[];
getTerminalDetail: (token: string, id: string) => Promise<TerminalInfo | undefined>;
runTerminalAction: (token: string, id: string, action: TerminalAction) => Promise<boolean>;
getStorageMounts: () => Promise<StorageMounts>;
getStorageKeys: (base?: string) => Promise<string[]>;
getStorageItem: (token: string, key: string) => Promise<StorageValue>;
setStorageItem: (token: string, key: string, value: StorageValue) => Promise<void>;
removeStorageItem: (token: string, key: string) => Promise<void>;
getAnalyzeBuildInfo: () => Promise<AnalyzeBuildsInfo>;
generateAnalyzeBuildName: () => Promise<string>;
startAnalyzeBuild: (token: string, name: string) => Promise<string>;
clearAnalyzeBuilds: (token: string, names?: string[]) => Promise<void>;
getImageMeta: (token: string, filepath: string) => Promise<ImageMeta | undefined>;
getTextAssetContent: (token: string, filepath: string, limit?: number) => Promise<string | undefined>;
writeStaticAssets: (token: string, file: AssetEntry[], folder: string) => Promise<string[]>;
deleteStaticAsset: (token: string, filepath: string) => Promise<void>;
renameStaticAsset: (token: string, oldPath: string, newPath: string) => Promise<void>;
telemetryEvent: (payload: object, immediate?: boolean) => void;
customTabAction: (name: string, action: number) => Promise<boolean>;
runWizard: <T extends WizardActions>(token: string, name: T, ...args: GetWizardArgs<T>) => Promise<void>;
openInEditor: (filepath: string) => Promise<boolean>;
restartNuxt: (token: string, hard?: boolean) => Promise<void>;
installNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
uninstallNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
enableTimeline: (dry: boolean) => Promise<[string, string]>;
requestForAuth: (info?: string, origin?: string) => Promise<void>;
verifyAuthToken: (token: string) => Promise<boolean>;
}
interface ClientFunctions {
refresh: (event: ClientUpdateEvent) => void;
callHook: (hook: string, ...args: any[]) => Promise<void>;
navigateTo: (path: string) => void;
onTerminalData: (_: {
id: string;
data: string;
}) => void;
onTerminalExit: (_: {
id: string;
code?: number;
}) => void;
}
interface NuxtServerData {
nuxt: NuxtOptions;
nitro?: Nitro['options'];
vite: {
server?: ResolvedConfig;
client?: ResolvedConfig;
};
}
type ClientUpdateEvent = keyof ServerFunctions;
/**
* @internal
*/
interface NuxtDevtoolsServerContext {
nuxt: Nuxt;
options: ModuleOptions;
rpc: BirpcGroup<ClientFunctions, ServerFunctions>;
/**
* Hook to open file in editor
*/
openInEditorHooks: ((filepath: string) => boolean | void | Promise<boolean | void>)[];
/**
* Invalidate client cache for a function and ask for re-fetching
*/
refresh: (event: keyof ServerFunctions) => void;
/**
* Ensure dev auth token is valid, throw if not
*/
ensureDevAuthToken: (token: string) => Promise<void>;
extendServerRpc: <ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>;
}
interface NuxtDevtoolsInfo {
version: string;
packagePath: string;
isGlobalInstall: boolean;
}
interface InstallModuleReturn {
configOriginal: string;
configGenerated: string;
commands: string[];
processId: string;
}
type ServerDebugModuleMutationRecord = (Omit<NuxtDebugModuleMutationRecord, 'module'> & {
name: string;
});
interface ServerDebugContext {
moduleMutationRecords: ServerDebugModuleMutationRecord[];
}
declare module '@nuxt/schema' {
interface NuxtHooks {
/**
* Called before devtools starts. Useful to detect if devtools is enabled.
*/
'devtools:before': () => void;
/**
* Called after devtools is initialized.
*/
'devtools:initialized': (info: NuxtDevtoolsInfo) => void;
/**
* Hooks to extend devtools tabs.
*/
'devtools:customTabs': (tabs: ModuleCustomTab[]) => void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
'devtools:customTabs:refresh': () => void;
/**
* Register a terminal.
*/
'devtools:terminal:register': (terminal: TerminalState) => void;
/**
* Write to a terminal.
*
* Returns true if terminal is found.
*/
'devtools:terminal:write': (_: {
id: string;
data: string;
}) => void;
/**
* Remove a terminal from devtools.
*
* Returns true if terminal is found and deleted.
*/
'devtools:terminal:remove': (_: {
id: string;
}) => void;
/**
* Mark a terminal as terminated.
*/
'devtools:terminal:exit': (_: {
id: string;
code?: number;
}) => void;
}
}
declare module '@nuxt/schema' {
/**
* Runtime Hooks
*/
interface RuntimeNuxtHooks {
/**
* On terminal data.
*/
'devtools:terminal:data': (payload: {
id: string;
data: string;
}) => void;
}
}
export type { CodeServerType as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleCompatibility as D, ModuleStats as E, CompatibilityStatus as F, ModuleType as G, HookInfo as H, ImageMeta as I, MaintainerInfo as J, GitHubContributor as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, VueInspectorData as O, PluginMetric as P, AssetType as Q, RouteInfo as R, SubprocessOptions as S, TerminalState as T, AssetInfo as U, VueInspectorClient as V, AssetEntry as W, CodeSnippet as X, ComponentRelationship as Y, ComponentWithRelationships as Z, CodeServerOptions as _, ServerFunctions as a, ModuleOptions as a0, ModuleGlobalOptions as a1, VSCodeIntegrationOptions as a2, VSCodeTunnelOptions as a3, NuxtDevToolsOptions as a4, NuxtServerData as a5, ClientUpdateEvent as a6, NuxtDevtoolsServerContext as a7, InstallModuleReturn as a8, ServerDebugModuleMutationRecord as a9, ServerDebugContext as aa, TerminalBase as ab, TerminalAction as ac, TerminalInfo as ad, WizardFunctions as ae, WizardActions as af, GetWizardArgs as ag, AnalyzeBuildsInfo as b, TabCategory as c, ModuleLaunchView as d, ModuleIframeView as e, ModuleVNodeView as f, ModuleLaunchAction as g, ModuleView as h, ModuleIframeTabLazyOptions as i, ModuleBuiltinTab as j, ModuleTabInfo as k, CategorizedTabs as l, PackageUpdateInfo as m, PackageManagerName as n, NpmCommandType as o, NpmCommandOptions as p, AutoImportsWithMetadata as q, ServerRouteInfo as r, ServerRouteInputType as s, ServerRouteInput as t, Payload as u, ServerTaskInfo as v, ScannedNitroTasks as w, PluginInfoWithMetic as x, InstalledModuleInfo as y, ModuleStaticInfo as z };
@@ -0,0 +1,2 @@
'use strict';
@@ -0,0 +1,181 @@
import { H as HookInfo, P as PluginMetric, L as LoadingTimeMetric, a as ServerFunctions, C as ClientFunctions } from './shared/devtools-kit.BMivX6Xf.cjs';
export { A as AnalyzeBuildMeta, b as AnalyzeBuildsInfo, W as AssetEntry, U as AssetInfo, Q as AssetType, q as AutoImportsWithMetadata, B as BasicModuleInfo, l as CategorizedTabs, a6 as ClientUpdateEvent, _ as CodeServerOptions, $ as CodeServerType, X as CodeSnippet, F as CompatibilityStatus, Y as ComponentRelationship, Z as ComponentWithRelationships, ag as GetWizardArgs, K as GitHubContributor, I as ImageMeta, a8 as InstallModuleReturn, y as InstalledModuleInfo, J as MaintainerInfo, j as ModuleBuiltinTab, D as ModuleCompatibility, M as ModuleCustomTab, a1 as ModuleGlobalOptions, i as ModuleIframeTabLazyOptions, e as ModuleIframeView, g as ModuleLaunchAction, d as ModuleLaunchView, a0 as ModuleOptions, z as ModuleStaticInfo, E as ModuleStats, k as ModuleTabInfo, G as ModuleType, f as ModuleVNodeView, h as ModuleView, p as NpmCommandOptions, o as NpmCommandType, a4 as NuxtDevToolsOptions, N as NuxtDevtoolsInfo, a7 as NuxtDevtoolsServerContext, a5 as NuxtServerData, n as PackageManagerName, m as PackageUpdateInfo, u as Payload, x as PluginInfoWithMetic, R as RouteInfo, w as ScannedNitroTasks, aa as ServerDebugContext, a9 as ServerDebugModuleMutationRecord, r as ServerRouteInfo, t as ServerRouteInput, s as ServerRouteInputType, v as ServerTaskInfo, S as SubprocessOptions, c as TabCategory, ac as TerminalAction, ab as TerminalBase, ad as TerminalInfo, T as TerminalState, a2 as VSCodeIntegrationOptions, a3 as VSCodeTunnelOptions, V as VueInspectorClient, O as VueInspectorData, af as WizardActions, ae as WizardFunctions } from './shared/devtools-kit.BMivX6Xf.cjs';
import { BirpcReturn } from 'birpc';
import { Hookable } from 'hookable';
import { NuxtApp } from 'nuxt/app';
import { AppConfig } from 'nuxt/schema';
import { $Fetch } from 'ofetch';
import { BuiltinLanguage } from 'shiki';
import { Ref } from 'vue';
import { StackFrame } from 'error-stack-parser-es';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
import '@nuxt/schema';
import 'execa';
interface TimelineEventFunction {
type: 'function';
start: number;
end?: number;
name: string;
args?: any[];
result?: any;
stacktrace?: StackFrame[];
isPromise?: boolean;
}
interface TimelineServerState {
timeSsrStart?: number;
}
interface TimelineEventRoute {
type: 'route';
start: number;
end?: number;
from: string;
to: string;
}
interface TimelineOptions {
enabled: boolean;
stacktrace: boolean;
arguments: boolean;
}
type TimelineEvent = TimelineEventFunction | TimelineEventRoute;
interface TimelineMetrics {
events: TimelineEvent[];
nonLiteralSymbol: symbol;
options: TimelineOptions;
}
interface TimelineEventNormalized<T> {
event: T;
segment: TimelineEventsSegment;
relativeStart: number;
relativeWidth: number;
layer: number;
}
interface TimelineEventsSegment {
start: number;
end: number;
events: TimelineEvent[];
functions: TimelineEventNormalized<TimelineEventFunction>[];
route?: TimelineEventNormalized<TimelineEventRoute>;
duration: number;
previousGap?: number;
}
interface DevToolsFrameState {
width: number;
height: number;
top: number;
left: number;
open: boolean;
route: string;
position: 'left' | 'right' | 'bottom' | 'top';
closeOnOutsideClick: boolean;
minimizePanelInactive: number;
}
interface NuxtDevtoolsClientHooks {
/**
* When the DevTools navigates, used for persisting the current tab
*/
'devtools:navigate': (path: string) => void;
/**
* Event emitted when the component inspector is clicked
*/
'host:inspector:click': (path: string) => void;
/**
* Event to close the component inspector
*/
'host:inspector:close': () => void;
/**
* Triggers reactivity manually, since Vue won't be reactive across frames)
*/
'host:update:reactivity': () => void;
/**
* Host action to control the DevTools navigation
*/
'host:action:navigate': (path: string) => void;
/**
* Host action to reload the DevTools
*/
'host:action:reload': () => void;
}
/**
* Host client from the App
*/
interface NuxtDevtoolsHostClient {
nuxt: NuxtApp;
hooks: Hookable<NuxtDevtoolsClientHooks>;
getIframe: () => HTMLIFrameElement | undefined;
inspector?: {
enable: () => void;
disable: () => void;
toggle: () => void;
isEnabled: Ref<boolean>;
isAvailable: Ref<boolean>;
};
devtools: {
close: () => void;
open: () => void;
toggle: () => void;
reload: () => void;
navigate: (path: string) => void;
/**
* Popup the DevTools frame into Picture-in-Picture mode
*
* Requires Chrome 111 with experimental flag enabled.
*
* Function is undefined when not supported.
*
* @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture/
*/
popup?: () => any;
};
app: {
reload: () => void;
navigate: (path: string, hard?: boolean) => void;
appConfig: AppConfig;
colorMode: Ref<'dark' | 'light'>;
frameState: Ref<DevToolsFrameState>;
$fetch: $Fetch;
};
metrics: {
clientHooks: () => HookInfo[];
clientPlugins: () => PluginMetric[] | undefined;
clientTimeline: () => TimelineMetrics | undefined;
loading: () => LoadingTimeMetric;
};
/**
* A counter to trigger reactivity updates
*/
revision: Ref<number>;
/**
* Update client
* @internal
*/
syncClient: () => NuxtDevtoolsHostClient;
}
interface CodeHighlightOptions {
grammarContextCode?: string;
}
interface NuxtDevtoolsClient {
rpc: BirpcReturn<ServerFunctions, ClientFunctions>;
renderCodeHighlight: (code: string, lang?: BuiltinLanguage, options?: CodeHighlightOptions) => {
code: string;
supported: boolean;
};
renderMarkdown: (markdown: string) => string;
colorMode: string;
extendClientRpc: <ServerFunctions = Record<string, never>, ClientFunctions = Record<string, never>>(name: string, functions: ClientFunctions) => BirpcReturn<ServerFunctions, ClientFunctions>;
}
interface NuxtDevtoolsIframeClient {
host: NuxtDevtoolsHostClient;
devtools: NuxtDevtoolsClient;
}
interface NuxtDevtoolsGlobal {
setClient: (client: NuxtDevtoolsHostClient) => void;
}
export { ClientFunctions, HookInfo, LoadingTimeMetric, PluginMetric, ServerFunctions };
export type { CodeHighlightOptions, DevToolsFrameState, NuxtDevtoolsClient, NuxtDevtoolsClientHooks, NuxtDevtoolsGlobal, NuxtDevtoolsHostClient, NuxtDevtoolsIframeClient, TimelineEvent, TimelineEventFunction, TimelineEventNormalized, TimelineEventRoute, TimelineEventsSegment, TimelineMetrics, TimelineOptions, TimelineServerState };
@@ -0,0 +1,181 @@
import { H as HookInfo, P as PluginMetric, L as LoadingTimeMetric, a as ServerFunctions, C as ClientFunctions } from './shared/devtools-kit.BMivX6Xf.mjs';
export { A as AnalyzeBuildMeta, b as AnalyzeBuildsInfo, W as AssetEntry, U as AssetInfo, Q as AssetType, q as AutoImportsWithMetadata, B as BasicModuleInfo, l as CategorizedTabs, a6 as ClientUpdateEvent, _ as CodeServerOptions, $ as CodeServerType, X as CodeSnippet, F as CompatibilityStatus, Y as ComponentRelationship, Z as ComponentWithRelationships, ag as GetWizardArgs, K as GitHubContributor, I as ImageMeta, a8 as InstallModuleReturn, y as InstalledModuleInfo, J as MaintainerInfo, j as ModuleBuiltinTab, D as ModuleCompatibility, M as ModuleCustomTab, a1 as ModuleGlobalOptions, i as ModuleIframeTabLazyOptions, e as ModuleIframeView, g as ModuleLaunchAction, d as ModuleLaunchView, a0 as ModuleOptions, z as ModuleStaticInfo, E as ModuleStats, k as ModuleTabInfo, G as ModuleType, f as ModuleVNodeView, h as ModuleView, p as NpmCommandOptions, o as NpmCommandType, a4 as NuxtDevToolsOptions, N as NuxtDevtoolsInfo, a7 as NuxtDevtoolsServerContext, a5 as NuxtServerData, n as PackageManagerName, m as PackageUpdateInfo, u as Payload, x as PluginInfoWithMetic, R as RouteInfo, w as ScannedNitroTasks, aa as ServerDebugContext, a9 as ServerDebugModuleMutationRecord, r as ServerRouteInfo, t as ServerRouteInput, s as ServerRouteInputType, v as ServerTaskInfo, S as SubprocessOptions, c as TabCategory, ac as TerminalAction, ab as TerminalBase, ad as TerminalInfo, T as TerminalState, a2 as VSCodeIntegrationOptions, a3 as VSCodeTunnelOptions, V as VueInspectorClient, O as VueInspectorData, af as WizardActions, ae as WizardFunctions } from './shared/devtools-kit.BMivX6Xf.mjs';
import { BirpcReturn } from 'birpc';
import { Hookable } from 'hookable';
import { NuxtApp } from 'nuxt/app';
import { AppConfig } from 'nuxt/schema';
import { $Fetch } from 'ofetch';
import { BuiltinLanguage } from 'shiki';
import { Ref } from 'vue';
import { StackFrame } from 'error-stack-parser-es';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
import '@nuxt/schema';
import 'execa';
interface TimelineEventFunction {
type: 'function';
start: number;
end?: number;
name: string;
args?: any[];
result?: any;
stacktrace?: StackFrame[];
isPromise?: boolean;
}
interface TimelineServerState {
timeSsrStart?: number;
}
interface TimelineEventRoute {
type: 'route';
start: number;
end?: number;
from: string;
to: string;
}
interface TimelineOptions {
enabled: boolean;
stacktrace: boolean;
arguments: boolean;
}
type TimelineEvent = TimelineEventFunction | TimelineEventRoute;
interface TimelineMetrics {
events: TimelineEvent[];
nonLiteralSymbol: symbol;
options: TimelineOptions;
}
interface TimelineEventNormalized<T> {
event: T;
segment: TimelineEventsSegment;
relativeStart: number;
relativeWidth: number;
layer: number;
}
interface TimelineEventsSegment {
start: number;
end: number;
events: TimelineEvent[];
functions: TimelineEventNormalized<TimelineEventFunction>[];
route?: TimelineEventNormalized<TimelineEventRoute>;
duration: number;
previousGap?: number;
}
interface DevToolsFrameState {
width: number;
height: number;
top: number;
left: number;
open: boolean;
route: string;
position: 'left' | 'right' | 'bottom' | 'top';
closeOnOutsideClick: boolean;
minimizePanelInactive: number;
}
interface NuxtDevtoolsClientHooks {
/**
* When the DevTools navigates, used for persisting the current tab
*/
'devtools:navigate': (path: string) => void;
/**
* Event emitted when the component inspector is clicked
*/
'host:inspector:click': (path: string) => void;
/**
* Event to close the component inspector
*/
'host:inspector:close': () => void;
/**
* Triggers reactivity manually, since Vue won't be reactive across frames)
*/
'host:update:reactivity': () => void;
/**
* Host action to control the DevTools navigation
*/
'host:action:navigate': (path: string) => void;
/**
* Host action to reload the DevTools
*/
'host:action:reload': () => void;
}
/**
* Host client from the App
*/
interface NuxtDevtoolsHostClient {
nuxt: NuxtApp;
hooks: Hookable<NuxtDevtoolsClientHooks>;
getIframe: () => HTMLIFrameElement | undefined;
inspector?: {
enable: () => void;
disable: () => void;
toggle: () => void;
isEnabled: Ref<boolean>;
isAvailable: Ref<boolean>;
};
devtools: {
close: () => void;
open: () => void;
toggle: () => void;
reload: () => void;
navigate: (path: string) => void;
/**
* Popup the DevTools frame into Picture-in-Picture mode
*
* Requires Chrome 111 with experimental flag enabled.
*
* Function is undefined when not supported.
*
* @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture/
*/
popup?: () => any;
};
app: {
reload: () => void;
navigate: (path: string, hard?: boolean) => void;
appConfig: AppConfig;
colorMode: Ref<'dark' | 'light'>;
frameState: Ref<DevToolsFrameState>;
$fetch: $Fetch;
};
metrics: {
clientHooks: () => HookInfo[];
clientPlugins: () => PluginMetric[] | undefined;
clientTimeline: () => TimelineMetrics | undefined;
loading: () => LoadingTimeMetric;
};
/**
* A counter to trigger reactivity updates
*/
revision: Ref<number>;
/**
* Update client
* @internal
*/
syncClient: () => NuxtDevtoolsHostClient;
}
interface CodeHighlightOptions {
grammarContextCode?: string;
}
interface NuxtDevtoolsClient {
rpc: BirpcReturn<ServerFunctions, ClientFunctions>;
renderCodeHighlight: (code: string, lang?: BuiltinLanguage, options?: CodeHighlightOptions) => {
code: string;
supported: boolean;
};
renderMarkdown: (markdown: string) => string;
colorMode: string;
extendClientRpc: <ServerFunctions = Record<string, never>, ClientFunctions = Record<string, never>>(name: string, functions: ClientFunctions) => BirpcReturn<ServerFunctions, ClientFunctions>;
}
interface NuxtDevtoolsIframeClient {
host: NuxtDevtoolsHostClient;
devtools: NuxtDevtoolsClient;
}
interface NuxtDevtoolsGlobal {
setClient: (client: NuxtDevtoolsHostClient) => void;
}
export { ClientFunctions, HookInfo, LoadingTimeMetric, PluginMetric, ServerFunctions };
export type { CodeHighlightOptions, DevToolsFrameState, NuxtDevtoolsClient, NuxtDevtoolsClientHooks, NuxtDevtoolsGlobal, NuxtDevtoolsHostClient, NuxtDevtoolsIframeClient, TimelineEvent, TimelineEventFunction, TimelineEventNormalized, TimelineEventRoute, TimelineEventsSegment, TimelineMetrics, TimelineOptions, TimelineServerState };
@@ -0,0 +1,181 @@
import { H as HookInfo, P as PluginMetric, L as LoadingTimeMetric, a as ServerFunctions, C as ClientFunctions } from './shared/devtools-kit.BMivX6Xf.js';
export { A as AnalyzeBuildMeta, b as AnalyzeBuildsInfo, W as AssetEntry, U as AssetInfo, Q as AssetType, q as AutoImportsWithMetadata, B as BasicModuleInfo, l as CategorizedTabs, a6 as ClientUpdateEvent, _ as CodeServerOptions, $ as CodeServerType, X as CodeSnippet, F as CompatibilityStatus, Y as ComponentRelationship, Z as ComponentWithRelationships, ag as GetWizardArgs, K as GitHubContributor, I as ImageMeta, a8 as InstallModuleReturn, y as InstalledModuleInfo, J as MaintainerInfo, j as ModuleBuiltinTab, D as ModuleCompatibility, M as ModuleCustomTab, a1 as ModuleGlobalOptions, i as ModuleIframeTabLazyOptions, e as ModuleIframeView, g as ModuleLaunchAction, d as ModuleLaunchView, a0 as ModuleOptions, z as ModuleStaticInfo, E as ModuleStats, k as ModuleTabInfo, G as ModuleType, f as ModuleVNodeView, h as ModuleView, p as NpmCommandOptions, o as NpmCommandType, a4 as NuxtDevToolsOptions, N as NuxtDevtoolsInfo, a7 as NuxtDevtoolsServerContext, a5 as NuxtServerData, n as PackageManagerName, m as PackageUpdateInfo, u as Payload, x as PluginInfoWithMetic, R as RouteInfo, w as ScannedNitroTasks, aa as ServerDebugContext, a9 as ServerDebugModuleMutationRecord, r as ServerRouteInfo, t as ServerRouteInput, s as ServerRouteInputType, v as ServerTaskInfo, S as SubprocessOptions, c as TabCategory, ac as TerminalAction, ab as TerminalBase, ad as TerminalInfo, T as TerminalState, a2 as VSCodeIntegrationOptions, a3 as VSCodeTunnelOptions, V as VueInspectorClient, O as VueInspectorData, af as WizardActions, ae as WizardFunctions } from './shared/devtools-kit.BMivX6Xf.js';
import { BirpcReturn } from 'birpc';
import { Hookable } from 'hookable';
import { NuxtApp } from 'nuxt/app';
import { AppConfig } from 'nuxt/schema';
import { $Fetch } from 'ofetch';
import { BuiltinLanguage } from 'shiki';
import { Ref } from 'vue';
import { StackFrame } from 'error-stack-parser-es';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
import '@nuxt/schema';
import 'execa';
interface TimelineEventFunction {
type: 'function';
start: number;
end?: number;
name: string;
args?: any[];
result?: any;
stacktrace?: StackFrame[];
isPromise?: boolean;
}
interface TimelineServerState {
timeSsrStart?: number;
}
interface TimelineEventRoute {
type: 'route';
start: number;
end?: number;
from: string;
to: string;
}
interface TimelineOptions {
enabled: boolean;
stacktrace: boolean;
arguments: boolean;
}
type TimelineEvent = TimelineEventFunction | TimelineEventRoute;
interface TimelineMetrics {
events: TimelineEvent[];
nonLiteralSymbol: symbol;
options: TimelineOptions;
}
interface TimelineEventNormalized<T> {
event: T;
segment: TimelineEventsSegment;
relativeStart: number;
relativeWidth: number;
layer: number;
}
interface TimelineEventsSegment {
start: number;
end: number;
events: TimelineEvent[];
functions: TimelineEventNormalized<TimelineEventFunction>[];
route?: TimelineEventNormalized<TimelineEventRoute>;
duration: number;
previousGap?: number;
}
interface DevToolsFrameState {
width: number;
height: number;
top: number;
left: number;
open: boolean;
route: string;
position: 'left' | 'right' | 'bottom' | 'top';
closeOnOutsideClick: boolean;
minimizePanelInactive: number;
}
interface NuxtDevtoolsClientHooks {
/**
* When the DevTools navigates, used for persisting the current tab
*/
'devtools:navigate': (path: string) => void;
/**
* Event emitted when the component inspector is clicked
*/
'host:inspector:click': (path: string) => void;
/**
* Event to close the component inspector
*/
'host:inspector:close': () => void;
/**
* Triggers reactivity manually, since Vue won't be reactive across frames)
*/
'host:update:reactivity': () => void;
/**
* Host action to control the DevTools navigation
*/
'host:action:navigate': (path: string) => void;
/**
* Host action to reload the DevTools
*/
'host:action:reload': () => void;
}
/**
* Host client from the App
*/
interface NuxtDevtoolsHostClient {
nuxt: NuxtApp;
hooks: Hookable<NuxtDevtoolsClientHooks>;
getIframe: () => HTMLIFrameElement | undefined;
inspector?: {
enable: () => void;
disable: () => void;
toggle: () => void;
isEnabled: Ref<boolean>;
isAvailable: Ref<boolean>;
};
devtools: {
close: () => void;
open: () => void;
toggle: () => void;
reload: () => void;
navigate: (path: string) => void;
/**
* Popup the DevTools frame into Picture-in-Picture mode
*
* Requires Chrome 111 with experimental flag enabled.
*
* Function is undefined when not supported.
*
* @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture/
*/
popup?: () => any;
};
app: {
reload: () => void;
navigate: (path: string, hard?: boolean) => void;
appConfig: AppConfig;
colorMode: Ref<'dark' | 'light'>;
frameState: Ref<DevToolsFrameState>;
$fetch: $Fetch;
};
metrics: {
clientHooks: () => HookInfo[];
clientPlugins: () => PluginMetric[] | undefined;
clientTimeline: () => TimelineMetrics | undefined;
loading: () => LoadingTimeMetric;
};
/**
* A counter to trigger reactivity updates
*/
revision: Ref<number>;
/**
* Update client
* @internal
*/
syncClient: () => NuxtDevtoolsHostClient;
}
interface CodeHighlightOptions {
grammarContextCode?: string;
}
interface NuxtDevtoolsClient {
rpc: BirpcReturn<ServerFunctions, ClientFunctions>;
renderCodeHighlight: (code: string, lang?: BuiltinLanguage, options?: CodeHighlightOptions) => {
code: string;
supported: boolean;
};
renderMarkdown: (markdown: string) => string;
colorMode: string;
extendClientRpc: <ServerFunctions = Record<string, never>, ClientFunctions = Record<string, never>>(name: string, functions: ClientFunctions) => BirpcReturn<ServerFunctions, ClientFunctions>;
}
interface NuxtDevtoolsIframeClient {
host: NuxtDevtoolsHostClient;
devtools: NuxtDevtoolsClient;
}
interface NuxtDevtoolsGlobal {
setClient: (client: NuxtDevtoolsHostClient) => void;
}
export { ClientFunctions, HookInfo, LoadingTimeMetric, PluginMetric, ServerFunctions };
export type { CodeHighlightOptions, DevToolsFrameState, NuxtDevtoolsClient, NuxtDevtoolsClientHooks, NuxtDevtoolsGlobal, NuxtDevtoolsHostClient, NuxtDevtoolsIframeClient, TimelineEvent, TimelineEventFunction, TimelineEventNormalized, TimelineEventRoute, TimelineEventsSegment, TimelineMetrics, TimelineOptions, TimelineServerState };
@@ -0,0 +1 @@
@@ -0,0 +1 @@
export * from './dist/runtime/host-client'
@@ -0,0 +1 @@
export * from './dist/runtime/host-client.mjs'
@@ -0,0 +1 @@
export * from './dist/runtime/iframe-client'
@@ -0,0 +1 @@
export * from './dist/runtime/iframe-client.mjs'
@@ -0,0 +1,61 @@
{
"name": "@nuxt/devtools-kit",
"type": "module",
"version": "2.6.3",
"license": "MIT",
"homepage": "https://devtools.nuxt.com/module/utils-kit",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/devtools.git",
"directory": "packages/devtools-kit"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./types": {
"types": "./types.d.ts",
"import": "./dist/types.mjs",
"require": "./dist/types.cjs"
},
"./iframe-client": {
"types": "./iframe-client.d.ts",
"import": "./iframe-client.mjs"
},
"./host-client": {
"types": "./host-client.d.ts",
"import": "./host-client.mjs"
}
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.ts",
"files": [
"*.cjs",
"*.d.ts",
"*.mjs",
"dist"
],
"peerDependencies": {
"vite": ">=6.0"
},
"dependencies": {
"@nuxt/kit": "^3.18.1",
"execa": "^8.0.1"
},
"devDependencies": {
"@nuxt/schema": "^3.18.1",
"birpc": "^2.5.0",
"error-stack-parser-es": "^1.0.5",
"hookable": "^5.5.3",
"unbuild": "^3.6.1",
"unimport": "^5.2.0",
"vue-router": "^4.5.1"
},
"scripts": {
"build": "unbuild",
"stub": "unbuild --stub",
"dev:prepare": "nr stub"
}
}
@@ -0,0 +1 @@
export type * from './dist/types.d.mts'
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-PRESENT Nuxt Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,2 @@
#!/usr/bin/env node
import('./dist/index.mjs')
@@ -0,0 +1,103 @@
import { existsSync } from 'node:fs';
import fsp from 'node:fs/promises';
import { relative } from 'node:path';
import { consola } from 'consola';
import { colors } from 'consola/utils';
import { diffLines } from 'diff';
import { parseModule } from 'magicast';
import { join } from 'pathe';
import prompts from 'prompts';
function findNuxtConfig(cwd) {
const names = [
"nuxt.config.ts",
"nuxt.config.js"
];
for (const name of names) {
const path = join(cwd, name);
if (existsSync(path))
return path;
}
}
function printOutManual(value) {
consola.info(colors.yellow("To manually enable Nuxt DevTools, add the following to your Nuxt config:"));
consola.info(colors.cyan(`
devtools: { enabled: ${value} }
`));
}
async function toggleConfig(cwd, value) {
const nuxtConfig = findNuxtConfig(cwd);
if (!nuxtConfig) {
consola.error(colors.red("Unable to find Nuxt config file in current directory"));
process.exitCode = 1;
printOutManual(true);
return false;
}
try {
const source = await fsp.readFile(nuxtConfig, "utf-8");
const mod = await parseModule(source, { sourceFileName: nuxtConfig });
const config = mod.exports.default.$type === "function-call" ? mod.exports.default.$args[0] : mod.exports.default;
if (config.devtools || value) {
config.devtools ||= {};
if (typeof config.devtools === "object")
config.devtools.enabled = value;
}
const generated = mod.generate().code;
if (source.trim() === generated.trim()) {
consola.info(colors.yellow(`Nuxt DevTools is already ${value ? "enabled" : "disabled"}`));
} else {
consola.log("");
consola.log("We are going to update the Nuxt config with with the following changes:");
consola.log(colors.bold(colors.green(`./${relative(cwd, nuxtConfig)}`)));
consola.log("");
printDiffToCLI(source, generated);
consola.log("");
const { confirm } = await prompts({
type: "confirm",
name: "confirm",
message: "Continue?",
initial: true
});
if (!confirm)
return false;
await fsp.writeFile(nuxtConfig, `${generated.trimEnd()}
`, "utf-8");
}
} catch {
consola.error(colors.red("Unable to update Nuxt config file automatically"));
process.exitCode = 1;
printOutManual(true);
return false;
}
return true;
}
async function enable(cwd) {
await toggleConfig(cwd, true);
}
async function disable(cwd) {
await toggleConfig(cwd, false);
}
function printDiffToCLI(from, to) {
const diffs = diffLines(from.trim(), to.trim());
let output = "";
let no = 0;
for (const diff of diffs) {
const lines = diff.value.trimEnd().split("\n");
for (const line of lines) {
if (!diff.added)
no += 1;
if (diff.added)
output += colors.green(`+ | ${line}
`);
else if (diff.removed)
output += colors.red(`-${no.toString().padStart(3, " ")} | ${line}
`);
else
output += colors.gray(`${colors.dim(`${no.toString().padStart(4, " ")} |`)} ${line}
`);
}
}
consola.log(output.trimEnd());
}
export { disable, enable };
@@ -0,0 +1,51 @@
import { consola } from 'consola';
import { colors } from 'consola/utils';
import { readPackageJSON } from 'pkg-types';
const name = "@nuxt/devtools-wizard";
const version = "2.6.3";
async function getNuxtVersion(path) {
try {
const pkg = await readPackageJSON("nuxt", { url: path });
if (!pkg.version)
consola.warn("Cannot find any installed nuxt versions in ", path);
return pkg.version || null;
} catch {
return null;
}
}
async function run() {
const args = process.argv.slice(2);
const command = args[0];
const cwd = process.cwd();
consola.log("");
consola.log(colors.bold(colors.green(" Nuxt ")));
consola.log(`${colors.inverse(colors.bold(colors.green(" DevTools ")))} ${colors.green(`v${version}`)}`);
consola.log(`
${colors.gray("Learn more at https://devtools.nuxt.com\n")}`);
if (name.endsWith("-edge") || name.endsWith("-nightly"))
throw new Error("Nightly release of Nuxt DevTools requires to be installed locally. Learn more at https://github.com/nuxt/devtools/#nightly-release-channel");
const nuxtVersion = await getNuxtVersion(cwd);
if (!nuxtVersion) {
consola.error("Unable to find any installed nuxt version in the current directory");
process.exit(1);
}
if (command === "enable") {
consola.log(colors.green("Enabling Nuxt DevTools..."));
await import('./chunks/builtin.mjs').then((r) => r.enable(cwd));
} else if (command === "disable") {
consola.log(colors.magenta("Disabling Nuxt DevTools..."));
await import('./chunks/builtin.mjs').then((r) => r.disable(cwd));
} else if (!command) {
consola.log(`npx ${name} enable|disable`);
process.exit(1);
} else {
consola.log(colors.red(`Unknown command "${command}"`));
process.exit(1);
}
}
run().catch((err) => {
consola.error(err);
process.exit(1);
});
@@ -0,0 +1,41 @@
{
"name": "@nuxt/devtools-wizard",
"type": "module",
"version": "2.6.3",
"description": "CLI Wizard to toggle Nuxt DevTools",
"license": "MIT",
"homepage": "https://devtools.nuxt.com",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/devtools.git",
"directory": "packages/devtools-wizard"
},
"main": "./dist/index.mjs",
"bin": "./cli.mjs",
"files": [
"*.cjs",
"*.d.ts",
"*.mjs",
"dist"
],
"dependencies": {
"consola": "^3.4.2",
"diff": "^8.0.2",
"execa": "^8.0.1",
"magicast": "^0.3.5",
"pathe": "^2.0.3",
"pkg-types": "^2.3.0",
"prompts": "^2.4.2",
"semver": "^7.7.2"
},
"devDependencies": {
"@types/diff": "^8.0.0",
"@types/prompts": "^2.4.9",
"unbuild": "^3.6.1"
},
"scripts": {
"build": "unbuild",
"stub": "unbuild --stub",
"dev:prepare": "nr stub"
}
}
@@ -0,0 +1,13 @@
const { join } = require('node:path')
module.exports = {
name: 'Nuxt Server Data',
basedir: join(__dirname, 'discovery'),
embed: true,
// view: {
// assets: [
// './pages/common.css',
// './pages/default.js',
// ],
// },
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-PRESENT Nuxt Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+126
View File
@@ -0,0 +1,126 @@
<a href="https://devtools.nuxt.com"><img width="1200" alt="Nuxt DevTools" src="https://github-production-user-asset-6210df.s3.amazonaws.com/904724/261577617-a10567bd-ad33-48cc-9bda-9e37dbe1929f.png"></a>
<br>
<h1>
Nuxt DevTools
</h1>
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![License][license-src]][license-href]
[![Nuxt][nuxt-src]][nuxt-href]
[![Volta][volta-src]][volta-href]
<p>
Unleash Nuxt Developer Experience.
<br>Nuxt DevTools is a set of visual tools that help you to know your app better.
</p>
<p>
<a href="https://nuxt.com/blog/nuxt-devtools-v1-0">👋 Introduction</a> |
<a href="https://github.com/nuxt/devtools/discussions/29">💡 Ideas & Suggestions</a> |
<a href="https://github.com/nuxt/devtools/discussions/31">🗺️ Project Roadmap</a> |
<a href="https://devtools.nuxt.com/">📚 Documentation</a>
</p>
<br>
## Installation
> Nuxt DevTools v2 requires **Nuxt v3.15.0 or higher**.
Nuxt DevTools is **enabled by default** in Nuxt v3.8.0. You can press <kbd>Shift</kbd> + <kbd>Alt</kbd> / <kbd>⇧ Shift</kbd> + <kbd>⌥ Option</kbd> + <kbd>D</kbd> in your app to open it up.
If you want to explicitly enable or disable Nuxt DevTools, you can update your `nuxt.config` with:
```js
export default defineNuxtConfig({
devtools: {
enabled: true // or false to disable
}
})
```
### Nightly Release Channel
Similar to [Nuxt's Nightly Channel](https://nuxt.com/docs/guide/going-further/nightly-release-channel), DevTools also offers a nightly release channel, that automatically releases for every commit to `main` branch.
You can opt-in to the nightly release channel by running:
```diff
{
"devDependencies": {
-- "@nuxt/devtools": "^0.1.0"
++ "@nuxt/devtools": "npm:@nuxt/devtools-nightly@latest"
}
}
```
Remove lockfile (`package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`) and reinstall dependencies.
### Module Options
To configure Nuxt DevTools, you can pass the `devtools` options.
```ts
// nuxt.config.ts
export default defineNuxtConfig({
devtools: {
// Enable devtools (default: true)
enabled: true,
// VS Code Server options
vscode: {},
// ...other options
}
})
```
For all options available, please refer to TSDocs in your IDE, or the [type definition file](https://github.com/nuxt/devtools/blob/main/packages/devtools-kit/src/_types/options.ts).
## Features
Read the [**Announcement Blog Post 🎊**](https://nuxt.com/blog/nuxt-devtools-v1-0) for why we built Nuxt DevTools and what it can do!
## Module Authors
Please refer to the [Module Authors Guide](https://devtools.nuxt.com/module/guide).
## Contribution Guide
Please refer to the [Contribution Guide](https://devtools.nuxt.com/development/contributing).
## Anonymous Usage Analytics
Nuxt DevTools collects anonymous telemetry data about general usage. This helps us to accurately gauge feature usage and customization across all our users. This data will let us better understand how each features in Nuxt DevTools are used, measuring improvements made (DX and performances) and their relevance. It would also help us to prioritize our efforts and focus on the features that matter the most to our users.
Nuxt DevTools' telemetry data is piped through [Nuxt Telemetry](https://github.com/nuxt/telemetry), meaning that Nuxt DevTools will respect your local and global Nuxt Telemetry settings. You can also opt-out Nuxt DevTools' telemetry in the Nuxt DevTools settings.
The data we collect is completely anonymous, not traceable to the source (using hash+seed), and only meaningful in aggregate form. No data we collect is personally identifiable or trackable.
### Events
On top of the [default Nuxt Telemetry events](https://github.com/nuxt/telemetry#events), Nuxt DevTools also collects the following events:
- Versions of Nuxt DevTools
- Navigations between tabs/feature
- This helps us to understand which features are used the most to prioritize our efforts.
- Browser and OS names and versions
- This helps us improve compatibility across different browsers and operating systems.
- Click event on some action buttons
## License
[MIT](./LICENSE)
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/@nuxt/devtools/latest.svg?style=flat&colorA=18181B&colorB=28CF8D
[npm-version-href]: https://npmjs.com/package/@nuxt/devtools
[npm-downloads-src]: https://img.shields.io/npm/dm/@nuxt/devtools.svg?style=flat&colorA=18181B&colorB=28CF8D
[npm-downloads-href]: https://npm.chart.dev/@nuxt/devtools
[license-src]: https://img.shields.io/npm/l/@nuxt/devtools.svg?style=flat&colorA=18181B&colorB=28CF8D
[license-href]: https://npmjs.com/package/@nuxt/devtools
[nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt.js
[nuxt-href]: https://nuxt.com
[volta-src]: https://user-images.githubusercontent.com/904724/209143798-32345f6c-3cf8-4e06-9659-f4ace4a6acde.svg
[volta-href]: https://volta.net/nuxt/devtools?utm_source=nuxt_devtools_readme
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
import('@nuxt/devtools-wizard')
@@ -0,0 +1,58 @@
import { addVitePlugin } from '@nuxt/kit';
import { resolve, join } from 'pathe';
import { readdir, lstat } from 'node:fs/promises';
import { createVitePluginInspect } from './vite-inspect.mjs';
import '@nuxt/devtools-kit';
async function getFolderSize(dir) {
const dirents = await readdir(dir, {
withFileTypes: true
});
if (dirents.length === 0)
return 0;
const files = [];
const directorys = [];
for (const dirent of dirents) {
if (dirent.isFile()) {
files.push(dirent);
continue;
}
if (dirent.isDirectory())
directorys.push(dirent);
}
const sizes = await Promise.all(
[
files.map(async (file) => {
const path = resolve(dir, file.name);
const { size } = await lstat(path);
return size;
}),
directorys.map((directory) => {
const path = resolve(dir, directory.name);
return getFolderSize(path);
})
].flat()
);
return sizes.reduce((total, size) => total += size, 0);
}
async function setup(nuxt, options) {
if (options.viteInspect !== false) {
addVitePlugin(
await createVitePluginInspect({
build: true,
outputDir: join(nuxt.options.analyzeDir, ".vite-inspect")
})
);
}
nuxt.hook("build:analyze:done", async (meta) => {
const _meta = meta;
_meta.size = _meta.size || {};
const dirs = [join(meta.buildDir, "dist/client"), meta.outDir];
const [clientBundleSize, nitroBundleSize] = await Promise.all(dirs.map(getFolderSize));
_meta.size.clientBundle = clientBundleSize;
_meta.size.nitroBundle = nitroBundleSize;
});
}
export { setup };
File diff suppressed because it is too large Load diff
@@ -0,0 +1,68 @@
function setup({ nuxt }) {
if (!nuxt.options.dev || nuxt.options.test)
return;
nuxt.hook("app:templates", (app) => {
app.templates.filter((i) => i.filename?.startsWith("plugins/")).forEach((i) => {
if (!i.getContents)
return;
const original = i.getContents;
i.getContents = async (...args) => {
let content = await original(...args);
const PAYLOAD_KEY = "__NUXT_DEVTOOLS_PLUGINS_METRIC__";
const WRAPPER_KEY = "__DEVTOOLS_WRAPPER__";
if (content.includes(PAYLOAD_KEY))
return content;
const snippets = `
if (!globalThis.${PAYLOAD_KEY}) {
Object.defineProperty(globalThis, '${PAYLOAD_KEY}', {
value: [],
enumerable: false,
configurable: true,
})
}
function ${WRAPPER_KEY} (plugin, src) {
if (!plugin)
return plugin
return defineNuxtPlugin({
...plugin,
async setup (...args) {
const start = performance.now()
const result = await plugin.apply(this, args)
const end = performance.now()
globalThis.${PAYLOAD_KEY}.push({
src,
start,
end,
duration: end - start,
})
return result
}
})
}
`;
const imports = Array.from(content.matchAll(/(?:\n|^)import (.*) from ['"](.*)['"]/g)).map(([, name, path]) => ({ name, path }));
content = content.replace(/\nexport default\s*\[([\s\S]*)\]/, (_, itemsRaw) => {
const items = itemsRaw.split(",").map((i2) => i2.trim()).map((i2) => {
const importItem = imports.find(({ name }) => name === i2);
if (!importItem)
return i2;
return `${WRAPPER_KEY}(${i2}, ${JSON.stringify(importItem.path)})`;
});
return `
${snippets}
export default [
${items.join(",\n")}
]
`;
});
content = `import { defineNuxtPlugin } from "#imports"
${content}`;
return content;
};
});
});
}
export { setup };
@@ -0,0 +1,73 @@
import { resolve } from 'pathe';
import semver from 'semver';
import { runtimeDir } from '../dirs.mjs';
import 'node:path';
import 'node:url';
import 'is-installed-globally';
function setup({ nuxt, options }) {
const helperPath = resolve(runtimeDir, "function-metrics-helpers");
const includeFrom = options.timeline?.functions?.includeFrom || [
"#app",
"@unhead/vue"
];
const include = options.timeline?.functions?.include || [
(i) => includeFrom.includes(i.from),
(i) => i.from.includes("composables")
];
const exclude = options.timeline?.functions?.exclude || [
/^define[A-Z]/
];
function filter(item) {
if (item.type)
return false;
const name = item.as || item.name;
if (!include.some((f) => typeof f === "function" ? f(item) : typeof f === "string" ? name === f : f.test(name)))
return false;
if (exclude.some((f) => typeof f === "function" ? f(item) : typeof f === "string" ? name === f : f.test(name)))
return false;
return true;
}
nuxt.hook("imports:context", (unimport) => {
const ctx = unimport.getInternalContext();
if (!ctx.version || !semver.gte(ctx.version, "3.1.0"))
throw new Error(`[Nuxt DevTools] The timeline feature requires \`unimport\` >= v3.1.0, but got \`${ctx.version || "(unknown)"}\`. Please upgrade using \`nuxi upgrade --force\`.`);
ctx.addons.push(
{
injectImportsResolved(imports, _code, id) {
if (id?.includes("?macro=true"))
return;
return imports.map((i) => {
if (!filter(i))
return i;
const name = i.as || i.name;
return {
...i,
meta: {
wrapperOriginalAs: name
},
as: `_$__${name}`
};
});
},
injectImportsStringified(str, imports, s, id) {
if (id?.includes("?macro=true"))
return;
const code = s.toString();
const injected = imports.filter((i) => i.meta?.wrapperOriginalAs);
if (injected.length) {
const result = [
str,
code.includes("__nuxtTimelineWrap") ? "" : `import { __nuxtTimelineWrap } from ${JSON.stringify(helperPath)}`,
...injected.map((i) => `const ${i.meta.wrapperOriginalAs} = __nuxtTimelineWrap(${JSON.stringify(i.name)}, ${i.as})`),
""
].join(";");
return result;
}
}
}
);
});
}
export { setup };
@@ -0,0 +1,61 @@
import { addCustomTab } from '@nuxt/devtools-kit';
import { addVitePlugin } from '@nuxt/kit';
async function createVitePluginInspect(options) {
return await import('vite-plugin-inspect').then((r) => r.default(options));
}
async function setup({ nuxt, rpc }) {
const plugin = await createVitePluginInspect();
addVitePlugin(plugin);
let api;
nuxt.hook("vite:serverCreated", () => {
api = plugin.api;
});
addCustomTab(() => ({
name: "builtin-vite-inspect",
title: "Inspect",
icon: "carbon-ibm-watson-discovery",
category: "advanced",
view: {
type: "iframe",
src: `${nuxt.options.app.baseURL}${nuxt.options.app.buildAssetsDir}/__inspect/`.replace(/\/\//g, "/")
}
}), nuxt);
async function getComponentsRelationships() {
const meta = await api?.rpc.getMetadata();
const modules = (meta ? await api?.rpc.getModulesList({
vite: meta?.instances[0].vite,
env: meta?.instances[0].environments[0]
}) : null) || [];
const components = await rpc.functions.getComponents() || [];
const vueModules = modules.filter((m) => {
const plainId = m.id.replace(/\?v=\w+$/, "");
if (components.some((c) => c.filePath === plainId))
return true;
return m.id.match(/\.vue($|\?v=)/);
});
const graph = vueModules.map((i) => {
function searchForVueDeps(id, seen = /* @__PURE__ */ new Set()) {
if (seen.has(id))
return [];
seen.add(id);
const module = modules.find((m) => m.id === id);
if (!module)
return [];
return module.deps.flatMap((i2) => {
if (vueModules.find((m) => m.id === i2))
return [i2];
return searchForVueDeps(i2, seen);
});
}
return {
id: i.id,
deps: searchForVueDeps(i.id)
};
});
return graph;
}
rpc.functions.getComponentsRelationships = getComponentsRelationships;
}
export { createVitePluginInspect, setup };
@@ -0,0 +1,196 @@
import { existsSync } from 'node:fs';
import fsp from 'node:fs/promises';
import { hostname } from 'node:os';
import { resolve } from 'node:path';
import { startSubprocess } from '@nuxt/devtools-kit';
import { logger } from '@nuxt/kit';
import { execa } from 'execa';
import { checkPort, getPort } from 'get-port-please';
import which from 'which';
import { L as LOG_PREFIX } from './module-main.mjs';
import 'consola/utils';
import 'pathe';
import 'sirv';
import 'vite';
import '../shared/devtools.Dlu0WIXO.mjs';
import '../dirs.mjs';
import 'node:url';
import 'is-installed-globally';
import 'ohash';
import 'birpc';
import 'structured-clone-es';
import 'simple-git';
import 'tinyglobby';
import 'image-meta';
import 'perfect-debounce';
import 'destr';
import '../../dist/runtime/shared/hooks.js';
import 'node:process';
import 'node:module';
import 'pkg-types';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'local-pkg';
import 'magicast';
import 'magicast/helpers';
import 'nypm';
import 'semver';
const codeBinaryOptions = {
"ms-code-cli": {
codeBinary: "code",
launchArg: "serve-web",
licenseTermsArg: "--accept-server-license-terms",
connectionTokenArg: "--without-connection-token"
},
"ms-code-server": {
codeBinary: "code-server",
launchArg: "serve-local",
licenseTermsArg: "--accept-server-license-terms",
connectionTokenArg: "--without-connection-token"
},
"coder-code-server": {
codeBinary: "code-server",
launchArg: "serve-local",
licenseTermsArg: "",
connectionTokenArg: ""
}
};
async function setup({ nuxt, options, openInEditorHooks, rpc }) {
const vsOptions = options?.vscode || {};
const codeServer = vsOptions?.codeServer || "ms-code-server";
const { codeBinary, launchArg, licenseTermsArg, connectionTokenArg } = codeBinaryOptions[codeServer];
const installed = !!await which(codeBinary).catch(() => null);
let port = vsOptions?.port || 3080;
let url = `http://localhost:${port}`;
const host = vsOptions?.host ? `--host=${vsOptions.host}` : "--host=127.0.0.1";
let loaded = false;
let promise = null;
const mode = vsOptions?.mode || "local-serve";
const computerHostName = vsOptions.tunnel?.name || hostname().split(".").join("");
const root = nuxt.options.rootDir;
const vscodeServerControllerFile = resolve(root, ".vscode", ".server-controller-port.log");
openInEditorHooks.push(async (file) => {
if (!existsSync(vscodeServerControllerFile))
return false;
try {
const { port: port2 } = JSON.parse(await fsp.readFile(vscodeServerControllerFile, "utf-8"));
const url2 = `http://localhost:${port2}/open?path=${encodeURIComponent(`${root}/${file}`)}`;
await fetch(url2);
rpc.broadcast.navigateTo("/modules/custom-builtin-vscode");
return true;
} catch (e) {
console.debug(`Failed to open file "${file}" in VS Code Server`);
console.debug(e);
return false;
}
});
async function startCodeServer() {
if (existsSync(vscodeServerControllerFile))
await fsp.rm(vscodeServerControllerFile, { force: true });
if (vsOptions?.reuseExistingServer && !await checkPort(port)) {
loaded = true;
url = `http://localhost:${port}/?folder=${encodeURIComponent(root)}`;
logger.info(LOG_PREFIX, `Existing VS Code Server found at port ${port}...`);
return;
}
port = await getPort({ port });
url = `http://localhost:${port}/?folder=${encodeURIComponent(root)}`;
logger.info(LOG_PREFIX, `Starting VS Code Server at ${url} ...`);
execa(codeBinary, [
"--install-extension",
"antfu.vscode-server-controller"
], { stderr: "inherit", stdout: "ignore", reject: false });
startSubprocess(
{
command: codeBinary,
args: [
launchArg,
licenseTermsArg,
connectionTokenArg,
`--port=${port}`,
host
]
},
{
id: "devtools:vscode",
name: "VS Code Server",
icon: "logos-visual-studio-code"
},
nuxt
);
for (let i = 0; i < 100; i++) {
if (await fetch(url).then((r) => r.ok).catch(() => false))
break;
await new Promise((resolve2) => setTimeout(resolve2, 500));
}
await new Promise((resolve2) => setTimeout(resolve2, 2e3));
loaded = true;
}
async function startCodeTunnel() {
const { stdout: currentDir } = await execa("pwd");
url = `https://vscode.dev/tunnel/${computerHostName}${currentDir}`;
logger.info(LOG_PREFIX, `Starting VS Code tunnel at ${url} ...`);
const command = execa("code", [
"tunnel",
"--accept-server-license-terms",
"--name",
`${computerHostName}`
]);
command.stderr?.pipe(process.stderr);
command.stdout?.pipe(process.stdout);
nuxt.hook("close", () => {
command.kill();
});
for (let i = 0; i < 100; i++) {
if (await fetch(url).then((r) => r.ok).catch(() => false))
break;
await new Promise((resolve2) => setTimeout(resolve2, 500));
}
await new Promise((resolve2) => setTimeout(resolve2, 2e3));
loaded = true;
}
async function start() {
if (mode === "tunnel")
await startCodeTunnel();
else
await startCodeServer();
}
nuxt.hook("devtools:customTabs", (tabs) => {
tabs.push({
name: "builtin-vscode",
title: "VS Code",
icon: "bxl-visual-studio",
category: "modules",
requireAuth: true,
view: !installed && !(vsOptions?.mode === "tunnel") ? {
type: "launch",
title: "Install VS Code Server",
description: `It seems you don't have code-server installed.
Learn more about it with <a href="https://code.visualstudio.com/blogs/2022/07/07/vscode-server" target="_blank">this guide</a>.
Once installed, restart Nuxt and visit this tab again.`,
actions: []
} : !loaded ? {
type: "launch",
description: "Launch VS Code right in the devtools!",
actions: [{
label: promise ? "Starting..." : "Launch",
pending: !!promise,
handle: () => {
promise = promise || start();
return promise;
}
}]
} : {
type: "iframe",
src: url
}
});
});
if (vsOptions?.startOnBoot)
promise = promise || start();
}
export { setup };
@@ -0,0 +1,19 @@
import { addPluginTemplate, resolvePath } from '@nuxt/kit';
import { join } from 'pathe';
import { runtimeDir } from '../dirs.mjs';
import 'node:path';
import 'node:url';
import 'is-installed-globally';
async function setup({ nuxt }) {
if (!nuxt.options.dev || nuxt.options.test)
return;
addPluginTemplate({
name: "vue-devtools-client",
mode: "client",
order: -1e3,
src: await resolvePath(join(runtimeDir, "vue-devtools-client"))
});
}
export { setup };
@@ -0,0 +1,14 @@
import { addVitePlugin } from '@nuxt/kit';
import { VueTracer } from 'vite-plugin-vue-tracer';
function setup({ nuxt, options }) {
if (!nuxt.options.dev || nuxt.options.test)
return;
if (!options.componentInspector)
return;
const plugin = VueTracer();
if (plugin)
addVitePlugin(plugin);
}
export { setup };
@@ -0,0 +1,29 @@
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/entry.css-ebiz9nsw.css" crossorigin>
<link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue.css-mqq5uooj.css" crossorigin>
<link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss.css-mhvipxpl.css" crossorigin>
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/e1928lvz.js">
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue-nstwj98r.js">
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/shiki-jxvjmls6.js">
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss-eh8khx5b.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/markdown-it-fvu08dbs.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/default-er15ytcq.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/full-eq6zlj3s.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/none-giyl4tlf.js">
<link rel="prefetch" as="style" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ncode-block.css-lvdc77tw.css">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/data-schema-drawer-c7c346do.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/nselect.vue-h7dqrznf.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/nswitch.vue-ihk2zmam.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ndropdown.vue-lqitnb0r.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ncode-block.vue-j1bpwykw.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/client-hkqvtzyx.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ndrawer.vue-mt6mb0ol.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/quicktype-core-o057hwfl.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/unocss-runtime-g9jktwmb.js">
<link rel="prefetch" as="style" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-404.css-z2gtwy9t.css">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-404-eq7j2f69.js">
<link rel="prefetch" as="style" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-500.css-liy0brxy.css">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-500-g4f9ioxi.js">
<script type="module" src="/__NUXT_DEVTOOLS_BASE__/_nuxt/e1928lvz.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1755823299371,false]</script>
<script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__NUXT_DEVTOOLS_BASE__/",buildId:"4d84ec87-f2c3-4b83-8664-cdcbe5c3aa91",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
@@ -0,0 +1,29 @@
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/entry.css-ebiz9nsw.css" crossorigin>
<link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue.css-mqq5uooj.css" crossorigin>
<link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss.css-mhvipxpl.css" crossorigin>
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/e1928lvz.js">
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue-nstwj98r.js">
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/shiki-jxvjmls6.js">
<link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss-eh8khx5b.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/markdown-it-fvu08dbs.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/default-er15ytcq.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/full-eq6zlj3s.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/none-giyl4tlf.js">
<link rel="prefetch" as="style" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ncode-block.css-lvdc77tw.css">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/data-schema-drawer-c7c346do.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/nselect.vue-h7dqrznf.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/nswitch.vue-ihk2zmam.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ndropdown.vue-lqitnb0r.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ncode-block.vue-j1bpwykw.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/client-hkqvtzyx.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/ndrawer.vue-mt6mb0ol.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/quicktype-core-o057hwfl.js">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/unocss-runtime-g9jktwmb.js">
<link rel="prefetch" as="style" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-404.css-z2gtwy9t.css">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-404-eq7j2f69.js">
<link rel="prefetch" as="style" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-500.css-liy0brxy.css">
<link rel="prefetch" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/error-500-g4f9ioxi.js">
<script type="module" src="/__NUXT_DEVTOOLS_BASE__/_nuxt/e1928lvz.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1755823299372,false]</script>
<script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__NUXT_DEVTOOLS_BASE__/",buildId:"4d84ec87-f2c3-4b83-8664-cdcbe5c3aa91",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
@@ -0,0 +1 @@
import{p as e,J as n,$ as t}from"./vendor/json-editor-vue-nstwj98r.js";const c={"h-screen":"","w-screen":"","bg-black":""},r=e({__name:"__blank",setup(o){return(s,_)=>(t(),n("div",c))}});export{r as default};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
img{-webkit-user-drag:none;-khtml-user-drag:none;-moz-user-drag:none;-o-user-drag:none;user-drag:none}
@@ -0,0 +1 @@
{"id":"4d84ec87-f2c3-4b83-8664-cdcbe5c3aa91","timestamp":1755823265824}
@@ -0,0 +1 @@
{"id":"4d84ec87-f2c3-4b83-8664-cdcbe5c3aa91","timestamp":1755823265824,"matcher":{"static":{},"wildcard":{},"dynamic":{}},"prerendered":[]}
@@ -0,0 +1 @@
import{n as f,O as r}from"./vendor/json-editor-vue-nstwj98r.js";let e;const n=[];function s(i){if(n.push(i),!(typeof window>"u"))return window.__NUXT_DEVTOOLS__&&n.forEach(o=>o(window.__NUXT_DEVTOOLS__)),Object.defineProperty(window,"__NUXT_DEVTOOLS__",{set(o){o&&n.forEach(t=>t(o))},get(){return e.value},configurable:!0}),()=>{n.splice(n.indexOf(i),1)}}function u(){e||(e=f(),s(o));function i(){e&&r(e)}function o(t){e.value=t,t.host&&t.host.hooks.hook("host:update:reactivity",i)}return e}const c=u();export{c as d};
@@ -0,0 +1,8 @@
import{_ as k}from"./ncode-block.vue-j1bpwykw.js";import{ao as D}from"./e1928lvz.js";import{p as I,q as T,k as j,E as y,U as q,$ as M}from"./vendor/json-editor-vue-nstwj98r.js";class z{diff(e,t,n={}){let o;typeof n=="function"?(o=n,n={}):"callback"in n&&(o=n.callback);const u=this.castInput(e,n),c=this.castInput(t,n),r=this.removeEmpty(this.tokenize(u,n)),s=this.removeEmpty(this.tokenize(c,n));return this.diffWithOptionsObj(r,s,n,o)}diffWithOptionsObj(e,t,n,o){var u;const c=d=>{if(d=this.postProcess(d,n),o){setTimeout(function(){o(d)},0);return}else return d},r=t.length,s=e.length;let l=1,i=r+s;n.maxEditLength!=null&&(i=Math.min(i,n.maxEditLength));const p=(u=n.timeout)!==null&&u!==void 0?u:1/0,f=Date.now()+p,a=[{oldPos:-1,lastComponent:void 0}];let h=this.extractCommon(a[0],t,e,0,n);if(a[0].oldPos+1>=s&&h+1>=r)return c(this.buildValues(a[0].lastComponent,t,e));let g=-1/0,w=1/0;const x=()=>{for(let d=Math.max(g,-l);d<=Math.min(w,l);d+=2){let C;const P=a[d-1],v=a[d+1];P&&(a[d-1]=void 0);let L=!1;if(v){const E=v.oldPos-d;L=v&&0<=E&&E<r}const _=P&&P.oldPos+1<s;if(!L&&!_){a[d]=void 0;continue}if(!_||L&&P.oldPos<v.oldPos?C=this.addToPath(v,!0,!1,0,n):C=this.addToPath(P,!1,!0,1,n),h=this.extractCommon(C,t,e,d,n),C.oldPos+1>=s&&h+1>=r)return c(this.buildValues(C.lastComponent,t,e))||!0;a[d]=C,C.oldPos+1>=s&&(w=Math.min(w,d-1)),h+1>=r&&(g=Math.max(g,d+1))}l++};if(o)(function d(){setTimeout(function(){if(l>i||Date.now()>f)return o(void 0);x()||d()},0)})();else for(;l<=i&&Date.now()<=f;){const d=x();if(d)return d}}addToPath(e,t,n,o,u){const c=e.lastComponent;return c&&!u.oneChangePerToken&&c.added===t&&c.removed===n?{oldPos:e.oldPos+o,lastComponent:{count:c.count+1,added:t,removed:n,previousComponent:c.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:t,removed:n,previousComponent:c}}}extractCommon(e,t,n,o,u){const c=t.length,r=n.length;let s=e.oldPos,l=s-o,i=0;for(;l+1<c&&s+1<r&&this.equals(n[s+1],t[l+1],u);)l++,s++,i++,u.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return i&&!u.oneChangePerToken&&(e.lastComponent={count:i,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,l}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){const t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){const o=[];let u;for(;e;)o.push(e),u=e.previousComponent,delete e.previousComponent,e=u;o.reverse();const c=o.length;let r=0,s=0,l=0;for(;r<c;r++){const i=o[r];if(i.removed)i.value=this.join(n.slice(l,l+i.count)),l+=i.count;else{if(!i.added&&this.useLongestToken){let p=t.slice(s,s+i.count);p=p.map(function(f,a){const h=n[l+a];return h.length>f.length?h:f}),i.value=this.join(p)}else i.value=this.join(t.slice(s,s+i.count));s+=i.count,i.added||(l+=i.count)}}return o}}class A extends z{constructor(){super(...arguments),this.tokenize=N}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
`)&&(e=e.slice(0,-1)),t.endsWith(`
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}}const V=new A;function W(m,e,t){return V.diff(m,e,t)}function N(m,e){e.stripTrailingCr&&(m=m.replace(/\r\n/g,`
`));const t=[],n=m.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(let o=0;o<n.length;o++){const u=n[o];o%2&&!e.newlineIsToken?t[t.length-1]+=u:t.push(u)}return t}const B=I({__name:"CodeDiff",props:{from:{},to:{},lang:{}},setup(m){const e=m;function t(r,s){const l=W(r.trim(),s.trim()),i=[],p=[],f=[];for(const a of l){const h=a.value.trimEnd().split(`
`);for(const g of h)a.added?(i.push(f.length),f.push(g)):(a.removed&&p.push(f.length),f.push(g))}return{added:i,removed:p,result:f.join(`
`)}}const n=T(()=>t(e.from,e.to));function o(r){let s=0;return r.replace(/class="shiki/,'class="shiki diff').replace(/class="line"/g,l=>(s++,n.value.added.includes(s-1)?'class="line line-added"':n.value.removed.includes(s-1)?'class="line line-removed"':l))}const u=j();y(c);function c(){const r=D(u);r&&r.querySelector(".line-added,.line-removed")?.scrollIntoView()}return(r,s)=>{const l=k;return M(),q(l,{ref_key:"elRef",ref:u,code:n.value.result,lang:r.lang,"transform-rendered":o,onLoaded:c},null,8,["code","lang"])}}});export{B as _};
@@ -0,0 +1 @@
import{_ as g}from"./ncode-block.vue-j1bpwykw.js";import{a as C,_ as x}from"./e1928lvz.js";import{p as S,n as w,q as B,w as N,J as n,a1 as r,$ as a,a0 as s,F as d,ag as V,a4 as i,a8 as $,X as u,U as T,V as v,ab as m,u as h}from"./vendor/json-editor-vue-nstwj98r.js";const D={key:0,relative:"","n-code-block":""},E={flex:"~ wrap","w-full":""},F=["onClick"],L={flex:"~ gap-2",px3:"",pb3:"",n:"sm primary"},U=S({__name:"CodeSnippets",props:{codeSnippets:{},eventType:{}},setup(f){const l=f,e=w(l.codeSnippets[0]),_=C(),b=B(()=>e.value?.lang||"text");return N(()=>{l.codeSnippets.includes(e.value)||(e.value=l.codeSnippets[0])}),(p,o)=>{const k=g,c=x;return p.codeSnippets.length?(a(),n("div",D,[s("div",E,[(a(!0),n(d,null,V(p.codeSnippets,(t,y)=>(a(),n("button",{key:y,px4:"",py2:"",border:"r base",hover:"bg-active",class:i(t===e.value?"":"border-b"),onClick:q=>e.value=t},[s("div",{class:i(t===e.value?"":"op30"),"font-mono":""},$(t.name),3)],10,F))),128)),o[1]||(o[1]=s("div",{border:"b base","flex-auto":""},null,-1))]),e.value?(a(),n(d,{key:0},[u(k,{code:e.value.code,lang:b.value,lines:!1,"w-full":"","of-auto":"",p3:""},null,8,["code","lang"]),s("div",L,[u(c,{icon:"carbon-copy",onClick:o[0]||(o[0]=t=>h(_)(e.value.code,p.eventType||`code-snippet-${e.value.name}`))},{default:v(()=>[...o[2]||(o[2]=[m(" Copy ",-1)])]),_:1}),e.value?.docs?(a(),T(c,{key:0,to:e.value.docs,target:"_blank",icon:"carbon-catalog"},{default:v(()=>[...o[3]||(o[3]=[m(" Docs ",-1)])]),_:1},8,["to"])):r("",!0)])],64)):r("",!0)])):r("",!0)}}});export{U as _};
@@ -0,0 +1 @@
function n(o,r=65,e=50,l=1){let t=0;for(let h=0;h<o.length;h++)t=o.charCodeAt(h)+((t<<5)-t);return`hsla(${t%360}, ${r}%, ${e}%, ${l})`}export{n as g};
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{a as $,w as U,I as E,_ as F}from"./e1928lvz.js";import{_ as j}from"./nmarkdown.vue-n5lhcplj.js";import{_ as S}from"./filepath-item.vue-kxrtauqr.js";import{k as q}from"./index-jc4yj4to.js";import{C as y}from"./constants-b32h69zq.js";import{p as z,q as r,Z as J,U as i,$ as s,V as m,a0 as a,a4 as L,J as p,a1 as l,ab as c,a8 as _,X as b,u as k,F as x,ag as M}from"./vendor/json-editor-vue-nstwj98r.js";const O={rounded:"","font-mono":""},T={key:0,"text-primary":""},W={key:0},X={title:"Vue Directive"},Z={"max-w-100":""},A={px4:"",py3:"","text-sm":""},G={flex:"~ gap2",n:"primary xs"},H={border:"t base","max-h-60":"","of-auto":"",px4:"",py3:""},K={"text-sm":""},P={"text-primary":""},Q={flex:"~ col gap-2","items-start":"",pt3:"","text-sm":"",op75:""},R={key:1,"text-sm":"",op50:""},ne=z({__name:"ComposableItem",props:{item:{},isDirective:{type:Boolean,default:!1},metadata:{},filepath:{},counter:{type:Boolean,default:!0},classes:{default:"px2 py1 text-sm bg-gray:5 "}},setup(g){const o=g,C=$(),h=U(),u=r(()=>o.item.as||o.item.name),D=r(()=>{let e=u.value;return o.isDirective&&(e[0]!=="v"&&(e=`v${e}`),e=q(e)),e}),n=r(()=>o.metadata?.injectionUsage?.[u.value]?.count||0),N=r(()=>(o.metadata?.injectionUsage?.[u.value]?.moduleIds||[]).filter(e=>!e.endsWith("?macro=true"))),v=r(()=>o.item.meta?.docsUrl?o.item.meta.docsUrl:["nuxt","#app","nuxt3"].includes(o.item.from)?y.nuxt[o.item.name]:o.item.from==="vue"?y.vue[o.item.name]:null);return(e,t)=>{const w=E,I=j,f=F,V=S,B=J("VDropdown");return s(),i(B,{disabled:!o.metadata},{popper:m(()=>[a("div",Z,[a("div",A,[e.item.meta?.description?(s(),i(I,{key:0,tag:"div",pb3:"","text-sm":"",markdown:e.item.meta.description},null,8,["markdown"])):l("",!0),a("div",G,[b(f,{icon:"carbon-copy",onClick:t[0]||(t[0]=d=>k(C)(D.value,"imports-name"))},{default:m(()=>[...t[2]||(t[2]=[c(" Copy ",-1)])]),_:1}),e.filepath?(s(),i(f,{key:0,icon:"carbon-code",onClick:t[1]||(t[1]=d=>e.filepath&&k(h)(e.filepath))},{default:m(()=>[...t[3]||(t[3]=[c(" Source ",-1)])]),_:1})):l("",!0),v.value?(s(),i(f,{key:1,icon:"carbon-catalog",to:v.value,target:"_blank"},{default:m(()=>[...t[4]||(t[4]=[c(" Docs ",-1)])]),_:1},8,["to"])):l("",!0)])]),a("div",H,[n.value?(s(),p(x,{key:0},[a("div",K,[t[5]||(t[5]=a("span",{op50:""},"It has been referenced ",-1)),a("strong",P,_(n.value),1),t[6]||(t[6]=a("span",{op50:""}," times by:",-1))]),a("div",Q,[(s(!0),p(x,null,M(N.value,d=>(s(),i(V,{key:d,filepath:d},null,8,["filepath"]))),128))])],64)):(s(),p("div",R," Not in use via auto import. "))])])]),default:m(()=>[a("button",{"hover:text-primary":"",class:L([e.metadata&&!n.value?"op30 hover:op100":"",e.classes])},[a("code",O,[c(_(u.value)+" ",1),n.value&&e.counter?(s(),p("sup",T,"x"+_(n.value),1)):l("",!0)]),e.isDirective?(s(),p("sup",W,[a("abbr",X,[b(w,{icon:"tabler:hexagon-letter-d"})])])):l("",!0)],2)]),_:1},8,["disabled"])}}});export{ne as _};
Loaded 100 of 15070 files, more files were not shown because too many files have changed in this diff. Show more