@vizejs/nuxt 0.577.0 → 0.579.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,14 +4,14 @@ import * as fs$1 from "node:fs";
4
4
  import { existsSync, lstatSync, realpathSync } from "node:fs";
5
5
  import * as path$1 from "node:path";
6
6
  import path, { dirname, extname, isAbsolute, join, relative, sep } from "node:path";
7
- import { spawn } from "node:child_process";
8
7
  import { glob, lstat, mkdir, mkdtemp, open, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
9
8
  import { fileURLToPath, pathToFileURL } from "node:url";
10
- import { Worker, isMainThread, parentPort } from "node:worker_threads";
11
9
  import { randomBytes, randomUUID } from "node:crypto";
12
10
  import { buildNuxtLintPlan, collectNuxtLintDirs, resolveNuxtLintFeatures } from "@vizejs/nuxt-lint-config";
13
11
  import { tmpdir } from "node:os";
14
12
  import { createServer } from "node:http";
13
+ import { spawn } from "node:child_process";
14
+ import { Worker, isMainThread, parentPort } from "node:worker_threads";
15
15
  //#region src/builder.ts
16
16
  function getDetectedNuxtMajor(nuxt) {
17
17
  const nuxtLike = nuxt;
@@ -47,1989 +47,2011 @@ function getDetectedNuxtBuilderKind(nuxt) {
47
47
  return nuxt.options.bridge && nuxt.options.bridge.vite === true ? "vite" : "webpack";
48
48
  }
49
49
  //#endregion
50
- //#region src/lint/checker/options.ts
50
+ //#region src/lint/addons.ts
51
+ /** Hook other Nuxt modules use to extend Vize's generated lint config. */
52
+ const VIZE_NUXT_LINT_CONFIG_ADDONS_HOOK = "vize:lint:config:addons";
53
+ function autoImportEnabled(imports) {
54
+ if (imports === false) return false;
55
+ return imports?.autoImport !== false;
56
+ }
57
+ function asImportContext(value) {
58
+ if (value == null || typeof value !== "object" || !("getImports" in value)) return;
59
+ return typeof value.getImports === "function" ? value : void 0;
60
+ }
61
+ function nitroImportContext(value) {
62
+ if (value == null || typeof value !== "object" || !("unimport" in value)) return;
63
+ return asImportContext(value.unimport);
64
+ }
51
65
  /**
52
- * Resolve the engine-neutral part of `@nuxt/eslint`'s checker contract.
66
+ * Capture Nuxt's client and server auto-import registries as readonly globals.
53
67
  *
54
- * `configType` and `eslintPath` intentionally do not exist: they choose an
55
- * ESLint implementation, while this checker always executes oxlint + Patina.
68
+ * Nuxt publishes both contexts after modules have begun setting up. Keeping
69
+ * their latest values in the addon means every config regeneration observes
70
+ * the current registry rather than a module-setup-time snapshot.
56
71
  */
57
- function resolveNuxtLintCheckerOptions(checker, project) {
58
- if (checker !== true && (checker === false || checker == null)) return false;
59
- const overrides = typeof checker === "object" ? checker : {};
72
+ function toPosix(value) {
73
+ return value.split(path.sep).join("/");
74
+ }
75
+ function nitroImportFiles(nuxt, options) {
76
+ const nuxtRoot = path.resolve(nuxt.options?.rootDir ?? options.rootDir ?? ".");
77
+ const lintRoot = path.resolve(options.rootDir ?? nuxtRoot);
78
+ const directories = /* @__PURE__ */ new Set();
79
+ directories.add(path.resolve(nuxtRoot, nuxt.options?.nitro?.srcDir ?? "server"));
80
+ for (const layer of nuxt.options?._layers ?? []) if (layer.config?.rootDir) directories.add(path.resolve(layer.config.rootDir, "server"));
81
+ return [...directories].map((directory) => `${toPosix(path.relative(lintRoot, directory)) || "."}/**/*.{js,ts,jsx,tsx}`).sort();
82
+ }
83
+ function createNuxtImportGlobalsAddon(nuxt, options) {
84
+ let unimport;
85
+ let nitroUnimport;
86
+ nuxt.hook("imports:context", (context) => {
87
+ unimport = asImportContext(context);
88
+ });
89
+ nuxt.hook("nitro:init", (nitro) => {
90
+ nitroUnimport = nitroImportContext(nitro);
91
+ });
60
92
  return {
61
- cache: overrides.cache ?? true,
62
- include: [...overrides.include ?? [`${project.srcDir}/**/*.{js,jsx,ts,tsx,vue}`]],
63
- exclude: [...overrides.exclude ?? ["**/node_modules/**", project.buildDir]],
64
- formatter: overrides.formatter ?? "stylish",
65
- lintOnStart: overrides.lintOnStart ?? true,
66
- emitWarning: overrides.emitWarning ?? true,
67
- emitError: overrides.emitError ?? true,
68
- fix: overrides.fix ?? false
93
+ name: "vize:lint:import-globals",
94
+ async getConfigs() {
95
+ const appAutoImports = autoImportEnabled(nuxt.options?.imports);
96
+ const imports = (appAutoImports ? await unimport?.getImports() ?? [] : []).sort((left, right) => left.from.localeCompare(right.from) || left.name.localeCompare(right.name));
97
+ const globals = Object.fromEntries(imports.map((imported) => [imported.as ?? imported.name, "readonly"]));
98
+ const nitroImports = (appAutoImports && autoImportEnabled(nuxt.options?.nitro?.imports) ? await nitroUnimport?.getImports() ?? [] : []).sort((left, right) => left.from.localeCompare(right.from) || left.name.localeCompare(right.name));
99
+ const nitroGlobals = Object.fromEntries(nitroImports.map((imported) => [imported.as ?? imported.name, "readonly"]));
100
+ return [{
101
+ name: "nuxt/import-globals",
102
+ globals
103
+ }, ...Object.keys(nitroGlobals).length > 0 ? [{
104
+ name: "nitro/import-globals",
105
+ files: nitroImportFiles(nuxt, options),
106
+ globals: nitroGlobals
107
+ }] : []];
108
+ }
69
109
  };
70
110
  }
71
- //#endregion
72
- //#region src/lint/checker/filter.ts
73
- const GLOB_TOKEN = /[*?[\]{}()]/u;
74
- function normalize(value) {
75
- const normalized = value.replaceAll("\\", "/").replace(/\/{2,}/gu, "/");
76
- if (normalized === "/" || /^[A-Za-z]:\/$/u.test(normalized)) return normalized;
77
- return normalized.replace(/\/$/u, "");
111
+ /**
112
+ * Register the built-in auto-import addon and return the generation-time
113
+ * resolver consumed by the Nuxt lint config writer.
114
+ *
115
+ * The addon array is rebuilt for every generation. This mirrors Nuxt's addon
116
+ * hook without retaining contributions across `builder:generateApp` runs.
117
+ * The Vize-namespaced hook carries engine-neutral config items instead of raw
118
+ * ESLint source, so contributors remain compatible with the oxlint emitter.
119
+ */
120
+ function setupNuxtLintConfigAddons(nuxt, options = {}) {
121
+ const defaults = [createNuxtImportGlobalsAddon(nuxt, options)];
122
+ return async () => {
123
+ const addons = [...defaults];
124
+ await nuxt.callHook(VIZE_NUXT_LINT_CONFIG_ADDONS_HOOK, addons);
125
+ const configs = [];
126
+ for (const addon of addons) {
127
+ const contributed = await addon.getConfigs();
128
+ if (contributed) configs.push(...contributed);
129
+ }
130
+ return configs;
131
+ };
78
132
  }
79
- function relativeToRoot(file, rootDir) {
80
- const root = normalize(rootDir);
81
- const absolute = normalize(file);
82
- const prefix = `${root}/`;
83
- if (absolute.startsWith(prefix)) return absolute.slice(prefix.length);
84
- const normalized = normalize(path.relative(rootDir, file));
85
- return normalized === ".." || normalized.startsWith("../") ? void 0 : normalized;
133
+ //#endregion
134
+ //#region src/lint/emitter.ts
135
+ /**
136
+ * Oxlint artifact emission for the engine-neutral Nuxt lint plan.
137
+ *
138
+ * The plan deliberately keeps eslint-compatible Patina rule ids. Oxlint loads
139
+ * Patina as the `vize` JavaScript plugin, so this boundary is the one place
140
+ * those ids gain their `vize/` prefix.
141
+ */
142
+ const PATINA_RULE_NAMESPACES = new Set([
143
+ "a11y",
144
+ "css",
145
+ "ecosystem",
146
+ "html",
147
+ "musea",
148
+ "nuxt",
149
+ "petite-vue",
150
+ "script",
151
+ "ssr",
152
+ "type",
153
+ "vapor",
154
+ "vize",
155
+ "vue"
156
+ ]);
157
+ function toOxlintRuleId(ruleId) {
158
+ const separator = ruleId.indexOf("/");
159
+ const namespace = separator < 0 ? ruleId : ruleId.slice(0, separator);
160
+ return PATINA_RULE_NAMESPACES.has(namespace) ? `vize/${ruleId}` : ruleId;
86
161
  }
87
- function matchesDirectory(candidate, pattern) {
88
- if (GLOB_TOKEN.test(pattern)) return false;
89
- return candidate === pattern || candidate.startsWith(`${pattern}/`);
162
+ function prefixVizeRules(rules) {
163
+ if (!rules) return void 0;
164
+ return Object.fromEntries(Object.entries(rules).map(([ruleId, severity]) => [toOxlintRuleId(ruleId), severity]));
90
165
  }
91
- function matchesPattern(absolute, relative, rawPattern) {
92
- const pattern = normalize(rawPattern);
93
- const candidates = path.isAbsolute(pattern) || /^[A-Za-z]:\//u.test(pattern) ? [absolute] : relative === void 0 ? [] : [relative];
94
- for (const candidate of candidates) if (matchesDirectory(candidate, pattern) || path.matchesGlob(candidate, pattern)) return true;
95
- return false;
166
+ function mergeGlobals(target, source) {
167
+ if (!source) return;
168
+ for (const [name, access] of Object.entries(source)) Object.defineProperty(target, name, {
169
+ configurable: true,
170
+ enumerable: true,
171
+ value: access,
172
+ writable: true
173
+ });
96
174
  }
97
- /** Whether one watcher path belongs to the checker include/exclude contract. */
98
- function matchesNuxtLintCheckerFile(file, rootDir, options) {
99
- const absolute = normalize(file);
100
- const relative = relativeToRoot(file, rootDir);
101
- if (options.exclude.some((pattern) => matchesPattern(absolute, relative, pattern))) return false;
102
- return options.include.some((pattern) => matchesPattern(absolute, relative, pattern));
175
+ function mergeRules(target, source) {
176
+ Object.assign(target, prefixVizeRules(source));
103
177
  }
104
- //#endregion
105
- //#region src/lint/checker/worker.ts
106
- function resolveOxlintEntrypoint() {
107
- try {
108
- const plugin = fileURLToPath(import.meta.resolve("oxlint-plugin-vize"));
109
- return path.resolve(path.dirname(plugin), "..", "bin", "oxlint-vize");
110
- } catch (error) {
111
- throw new Error("Unable to resolve oxlint-vize. Install oxlint-plugin-vize before enabling the Nuxt lint checker.", { cause: error });
178
+ /** Render the complete generated oxlint config, including its trailing newline. */
179
+ function renderNuxtOxlintConfig(items, pluginSpecifier, globBase, projectJsPlugins = []) {
180
+ if (globBase) {
181
+ const root = path.relative(globBase.configDir, globBase.rootDir);
182
+ if (root === ".." || root.startsWith(`..${path.sep}`) || path.isAbsolute(root)) throw new Error("Generated oxlint config must be in the lint root or an ancestor directory");
112
183
  }
184
+ const rebase = (glob, ignore = false) => globBase ? rebaseGlob(glob, globBase, ignore) : glob;
185
+ const ignorePatterns = [];
186
+ const globals = {};
187
+ const rules = {};
188
+ const overrides = [];
189
+ for (const item of items) {
190
+ if (item.files) {
191
+ const override = { files: item.files.map((glob) => rebase(glob)) };
192
+ if (item.ignores) override.excludeFiles = item.ignores.map((glob) => rebase(glob));
193
+ if (item.globals) override.globals = { ...item.globals };
194
+ if (item.rules || item.nativeRules) override.rules = {
195
+ ...prefixVizeRules(item.rules),
196
+ ...item.nativeRules
197
+ };
198
+ overrides.push(override);
199
+ continue;
200
+ }
201
+ if (item.ignores) ignorePatterns.push(...item.ignores.map((glob) => rebase(glob, true)));
202
+ mergeGlobals(globals, item.globals);
203
+ mergeRules(rules, item.rules);
204
+ Object.assign(rules, item.nativeRules);
205
+ }
206
+ const config = {
207
+ plugins: ["vue"],
208
+ jsPlugins: [{
209
+ name: "vize",
210
+ specifier: pluginSpecifier
211
+ }, ...projectJsPlugins.map((specifier) => rebaseJsPlugin(specifier, globBase?.configDir))],
212
+ settings: { vize: {
213
+ preset: "incremental",
214
+ ...globBase?.owner ? { generatedBy: globBase.owner } : {}
215
+ } }
216
+ };
217
+ if (ignorePatterns.length > 0) config.ignorePatterns = ignorePatterns;
218
+ if (Object.keys(globals).length > 0) config.globals = globals;
219
+ if (Object.keys(rules).length > 0) config.rules = rules;
220
+ if (overrides.length > 0) config.overrides = overrides;
221
+ return `${JSON.stringify(config, null, 2)}\n`;
113
222
  }
114
- function projectPattern(pattern, cwd) {
115
- if (!path.isAbsolute(pattern)) return pattern;
116
- const relative = path.relative(cwd, pattern);
117
- if (path.isAbsolute(relative) || relative === ".." || relative.startsWith(`..${path.sep}`)) return pattern;
118
- return relative.split(path.sep).join("/") || ".";
119
- }
120
- function expandBraces(pattern) {
121
- const match = /\{([^{}]+)\}/u.exec(pattern);
122
- if (!match || match.index === void 0) return [pattern];
123
- const before = pattern.slice(0, match.index);
124
- const after = pattern.slice(match.index + match[0].length);
125
- return match[1].split(",").flatMap((part) => expandBraces(`${before}${part}${after}`));
126
- }
127
- function oxlintPatterns(pattern, cwd) {
128
- const patterns = expandBraces(projectPattern(pattern, cwd)).flatMap((expanded) => {
129
- const shallow = expanded.replace(/(^|\/)\*\*\//gu, "$1");
130
- return shallow === expanded ? [expanded] : [expanded, shallow];
131
- });
132
- return [...new Set(patterns)];
223
+ function rebaseJsPlugin(specifier, configDir) {
224
+ if (!configDir || !path.isAbsolute(specifier)) return specifier;
225
+ const relative = path.relative(configDir, specifier).split(path.sep).join("/");
226
+ return relative.startsWith(".") ? relative : `./${relative}`;
133
227
  }
134
- async function oxlintTargets(pattern, cwd) {
135
- const rebased = projectPattern(pattern, cwd);
136
- if (rebased.endsWith("/**/*.{js,jsx,ts,tsx,vue}")) return [rebased.slice(0, -25) || "."];
137
- if (!/[*?[\]{}()]/u.test(rebased)) return [rebased];
138
- const matches = await Array.fromAsync(glob(rebased, { cwd }));
139
- return matches.length > 0 ? matches : oxlintPatterns(pattern, cwd);
228
+ function rebaseGlob(glob, base, ignore) {
229
+ const negated = glob.startsWith("!");
230
+ const body = negated ? glob.slice(1) : glob;
231
+ const target = path.resolve(base.rootDir, body);
232
+ let relative = path.relative(base.configDir, target);
233
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
234
+ if (ignore) throw new Error(`Oxlint cannot ignore a path outside its config directory: ${glob}`);
235
+ relative = target;
236
+ }
237
+ const pattern = relative.split(path.sep).join("/") || ".";
238
+ return negated ? `!${pattern}` : pattern;
140
239
  }
141
- async function checkerArgs(task) {
142
- const args = [
143
- "--config",
144
- task.configFile,
145
- "--format",
146
- "json",
147
- "--no-error-on-unmatched-pattern"
148
- ];
149
- if (task.fix) args.push("--fix");
150
- for (const pattern of task.exclude) for (const exclude of oxlintPatterns(pattern, task.cwd)) args.push("--ignore-pattern", exclude);
151
- for (const target of task.targets) args.push(...await oxlintTargets(target, task.cwd));
152
- return args;
240
+ //#endregion
241
+ //#region src/lint/nuxt-state.ts
242
+ /**
243
+ * Reduce a Nuxt instance to the project state lint config generation needs.
244
+ *
245
+ * Nuxt 2 has no `_layers`, so the project is treated as a single layer rooted
246
+ * at `srcDir` (falling back to `rootDir`). That keeps the Nuxt 2, 3 and 4 paths
247
+ * on one code path rather than branching on the detected major version.
248
+ */
249
+ function toNuxtLintProjectState(options, overrides = {}) {
250
+ const rootDir = overrides.rootDir || options.rootDir;
251
+ const layers = (options._layers ?? []).map((layer) => layer.config).filter((config) => Boolean(config)).map((config) => ({
252
+ ...config,
253
+ srcDir: config.srcDir || options.srcDir || options.rootDir
254
+ }));
255
+ return {
256
+ rootDir,
257
+ dir: options.dir ?? {},
258
+ layers: layers.length > 0 ? layers : [{ srcDir: options.srcDir || options.rootDir }]
259
+ };
153
260
  }
154
- function spawnOxlint(node, entrypoint, args, cwd) {
155
- return new Promise((resolve, reject) => {
156
- const child = spawn(node, [entrypoint, ...args], {
157
- cwd,
158
- stdio: [
159
- "ignore",
160
- "pipe",
161
- "pipe"
162
- ]
163
- });
164
- const stdout = [];
165
- const stderr = [];
166
- child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk)));
167
- child.stderr.on("data", (chunk) => stderr.push(Buffer.from(chunk)));
168
- child.on("error", (error) => {
169
- reject(new Error(`Failed to start oxlint at ${entrypoint}: ${error.message}`, { cause: error }));
170
- });
171
- child.on("close", (status) => {
172
- const output = Buffer.concat(stdout).toString("utf8");
173
- const details = Buffer.concat(stderr).toString("utf8");
174
- if (output.trim()) {
175
- resolve({
176
- stderr: details,
177
- stdout: output
178
- });
179
- return;
180
- }
181
- if (status === 0) {
182
- resolve({
183
- stderr: details,
184
- stdout: "{\"diagnostics\":[]}\n"
185
- });
186
- return;
261
+ //#endregion
262
+ //#region ../../../crates/vize_carton/src/config/loader/module-runtime.mjs
263
+ const configFailureArtifacts = /* @__PURE__ */ new WeakMap();
264
+ const configEvaluationTimings = /* @__PURE__ */ new WeakMap();
265
+ function beginConfigTiming(rows, phase, boundary) {
266
+ const start = rows ? performance.now() : void 0;
267
+ let finished = false;
268
+ if (boundary) boundary.active = true;
269
+ return () => {
270
+ if (start !== void 0 && !finished) {
271
+ const end = performance.now();
272
+ rows.push({
273
+ phase,
274
+ elapsedMs: end - start,
275
+ processId: process.pid
276
+ });
277
+ if (boundary) {
278
+ boundary.active = false;
279
+ if (boundary.resolvedAt !== void 0) {
280
+ rows.push({
281
+ phase: "public_load_until_owned_resolve",
282
+ elapsedMs: boundary.resolvedAt - start,
283
+ processId: process.pid
284
+ });
285
+ rows.push({
286
+ phase: "public_load_after_owned_resolve",
287
+ elapsedMs: end - boundary.resolvedAt,
288
+ processId: process.pid
289
+ });
290
+ }
187
291
  }
188
- reject(/* @__PURE__ */ new Error(`oxlint exited with ${String(status)} without JSON output${details.trim() ? `: ${details.trim()}` : ""}`));
189
- });
190
- });
292
+ finished = true;
293
+ }
294
+ };
191
295
  }
192
- async function executeOxlint(entrypoint, args, cwd) {
193
- if (!existsSync(entrypoint)) throw new Error(`Failed to start oxlint: entrypoint does not exist: ${entrypoint}`);
194
- const node = existsSync(process.execPath) ? process.execPath : "node";
296
+ async function beginPublicLoadProfile() {
297
+ const started = performance.now();
298
+ let session;
299
+ const close = () => {
300
+ try {
301
+ session?.disconnect();
302
+ } catch {}
303
+ };
195
304
  try {
196
- return await spawnOxlint(node, entrypoint, args, cwd);
305
+ const { Session } = await import("node:inspector/promises");
306
+ session = new Session();
307
+ session.connect();
308
+ await session.post("Profiler.enable");
309
+ await session.post("Profiler.start");
310
+ const setupMs = performance.now() - started;
311
+ return async () => {
312
+ const stopping = performance.now();
313
+ try {
314
+ const { profile } = await session.post("Profiler.stop");
315
+ return {
316
+ status: "recorded",
317
+ setupMs,
318
+ stopMs: performance.now() - stopping,
319
+ profile
320
+ };
321
+ } catch (error) {
322
+ return {
323
+ status: "unavailable",
324
+ setupMs,
325
+ reason: String(error)
326
+ };
327
+ } finally {
328
+ close();
329
+ }
330
+ };
197
331
  } catch (error) {
198
- const cause = error.cause;
199
- if (node !== "node" && cause?.code === "ENOENT") return spawnOxlint("node", entrypoint, args, cwd);
200
- throw error;
332
+ close();
333
+ return async () => ({
334
+ status: "unavailable",
335
+ reason: String(error)
336
+ });
201
337
  }
202
338
  }
203
- function diagnosticKind(diagnostic) {
204
- if (diagnostic.severity === 2 || diagnostic.severity === "error") return "error";
205
- if (diagnostic.severity === 1 || diagnostic.severity === "warn" || diagnostic.severity === "warning") return "warning";
339
+ function configModuleImportPath(configURL, windows = process.platform === "win32") {
340
+ return fileURLToPath(configURL, { windows });
206
341
  }
207
- function formatNuxtLintCheckerDiagnostics(diagnostics, formatter) {
208
- if (formatter === "json") return diagnostics.length > 0 ? `${JSON.stringify({ diagnostics })}\n` : "";
209
- const unix = formatter === "unix";
210
- const lines = diagnostics.map((diagnostic) => {
211
- const span = diagnostic.labels?.find((label) => label.span)?.span;
212
- const file = diagnostic.filename ?? diagnostic.filePath ?? "<unknown>";
213
- const line = span?.line ?? 1;
214
- const column = span?.column ?? 1;
215
- const severity = diagnosticKind(diagnostic) ?? "warning";
216
- const message = diagnostic.message ?? "lint diagnostic";
217
- const code = diagnostic.code ? ` (${diagnostic.code})` : "";
218
- return unix ? `${file}:${line}:${column}: ${message} [${severity}${code}]` : `${file}:${line}:${column} ${severity} ${message}${code}`;
219
- });
220
- return lines.length > 0 ? `${lines.join("\n")}\n` : "";
342
+ async function importConfigModule(configPath, withoutVite) {
343
+ return (await importConfigModuleWithDependencies(configPath, nodeModule.registerHooks, withoutVite)).namespace;
221
344
  }
222
- function resultFromPayload(payload, task, stderr) {
223
- const diagnostics = payload.diagnostics.filter((diagnostic) => {
224
- const kind = diagnosticKind(diagnostic);
225
- return kind === "error" && task.emitError || kind === "warning" && task.emitWarning;
226
- });
227
- const hasErrors = diagnostics.some((diagnostic) => diagnosticKind(diagnostic) === "error");
228
- const hasWarnings = diagnostics.some((diagnostic) => diagnosticKind(diagnostic) === "warning");
229
- const output = task.formatter === "json" ? diagnostics.length > 0 ? `${JSON.stringify({
230
- ...payload,
231
- diagnostics
232
- })}\n` : "" : formatNuxtLintCheckerDiagnostics(diagnostics, task.formatter);
233
- const notice = stderr.trim();
345
+ function failedConfigModuleObservation(error) {
346
+ const paths = /* @__PURE__ */ new Set();
347
+ let complete = false;
348
+ if (error?.code === "ERR_MODULE_NOT_FOUND" && typeof error.url === "string") try {
349
+ const url = new URL(error.url);
350
+ if (url.protocol === "file:") {
351
+ paths.add(fileURLToPath(url));
352
+ complete = true;
353
+ }
354
+ } catch {}
355
+ const diagnostics = Array.isArray(error?.errors) ? error.errors : [];
356
+ if (diagnostics.length) complete = true;
357
+ for (const diagnostic of diagnostics) {
358
+ let requested = false;
359
+ if (diagnostic?.code !== "UNRESOLVED_IMPORT" || typeof diagnostic.id !== "string" || !isAbsolute(diagnostic.id) || typeof diagnostic.exporter !== "string") {
360
+ complete = false;
361
+ continue;
362
+ }
363
+ paths.add(diagnostic.id);
364
+ const request = diagnostic.exporter;
365
+ if (!(isAbsolute(request) || request.startsWith("./") || request.startsWith("../"))) {
366
+ complete = false;
367
+ continue;
368
+ }
369
+ if (/[%#?]/.test(request)) {
370
+ complete = false;
371
+ continue;
372
+ }
373
+ try {
374
+ const url = isAbsolute(request) ? pathToFileURL(request) : new URL(request, pathToFileURL(diagnostic.id));
375
+ if (url.protocol === "file:" && extname(url.pathname)) {
376
+ paths.add(fileURLToPath(url));
377
+ requested = true;
378
+ }
379
+ } catch {}
380
+ complete &&= requested;
381
+ }
234
382
  return {
235
- diagnostics,
236
- diagnosticCount: diagnostics.length,
237
- hasErrors,
238
- hasWarnings,
239
- notices: notice ? [notice] : [],
240
- output
383
+ paths: [...paths],
384
+ complete
241
385
  };
242
386
  }
243
- /** Run one checker pass. This function executes inside the long-lived worker. */
244
- async function runNuxtLintCheckerTask(task) {
245
- if (!task.emitError && !task.emitWarning && !task.fix) return {
246
- diagnostics: [],
247
- diagnosticCount: 0,
248
- hasErrors: false,
249
- hasWarnings: false,
250
- notices: [],
251
- output: ""
387
+ /** Keep runtime imports observable until the optional export evaluator settles. */
388
+ async function captureConfigEvaluation(load, configPath, registerModuleHooks, evaluate, privateDirectory, observeDependencies, ownedAdapter, timings, boundary) {
389
+ const files = new Set([configPath]);
390
+ const requestedFiles = /* @__PURE__ */ new Set();
391
+ let complete = true;
392
+ let moduleGraphLoaded = false;
393
+ const owners = new Set([pathToFileURL(configPath).href]);
394
+ const isPrivate = (path) => {
395
+ if (!privateDirectory) return false;
396
+ const inside = relative(privateDirectory, path);
397
+ return inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside);
252
398
  };
253
- const execution = await executeOxlint(task.oxlintEntrypoint ?? resolveOxlintEntrypoint(), await checkerArgs(task), task.cwd);
254
- let payload;
255
- try {
256
- payload = JSON.parse(execution.stdout);
257
- } catch (error) {
258
- throw new Error(`oxlint returned invalid JSON: ${execution.stdout.slice(0, 240)}`, { cause: error });
259
- }
260
- if (!Array.isArray(payload.diagnostics)) throw new Error("oxlint JSON has no diagnostics array");
261
- return resultFromPayload(payload, task, execution.stderr);
262
- }
263
- function serializeError(error) {
264
- if (error instanceof Error) return {
265
- message: error.message,
266
- stack: error.stack
267
- };
268
- return { message: String(error) };
269
- }
270
- if (!isMainThread && parentPort) parentPort.on("message", async ({ id, task }) => {
399
+ const hooks = typeof registerModuleHooks === "function" ? registerModuleHooks({ resolve(specifier, context, nextResolve) {
400
+ const result = nextResolve(specifier, context);
401
+ if (result.url.startsWith("file:")) {
402
+ const path = fileURLToPath(result.url);
403
+ if (boundary?.active && boundary.resolvedAt === void 0 && isPrivate(path)) boundary.resolvedAt = performance.now();
404
+ if (owners.has(result.url) || owners.has(context.parentURL) || isPrivate(path)) {
405
+ owners.add(result.url);
406
+ if (!isPrivate(path)) files.add(path);
407
+ if (owners.has(context.parentURL) && (specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/") || specifier.startsWith("file:"))) try {
408
+ const requested = new URL(specifier, context.parentURL);
409
+ if (requested.protocol === "file:") {
410
+ const requestedPath = fileURLToPath(requested);
411
+ if (extname(requestedPath) && !isPrivate(requestedPath)) requestedFiles.add(requestedPath);
412
+ }
413
+ } catch {}
414
+ }
415
+ }
416
+ return result;
417
+ } }) : void 0;
271
418
  try {
272
- parentPort?.postMessage({
273
- id,
274
- result: await runNuxtLintCheckerTask(task)
275
- });
419
+ const { namespace, dependencies = [] } = await load();
420
+ for (const path of dependencies) if (!isPrivate(path)) files.add(path);
421
+ moduleGraphLoaded = true;
422
+ const finish = beginConfigTiming(timings, "export_evaluation");
423
+ let value;
424
+ try {
425
+ value = evaluate ? await evaluate(namespace) : namespace;
426
+ } finally {
427
+ finish();
428
+ }
429
+ return {
430
+ namespace,
431
+ value,
432
+ dependencies: [...files]
433
+ };
276
434
  } catch (error) {
277
- parentPort?.postMessage({
278
- error: serializeError(error),
279
- id
280
- });
281
- }
282
- });
283
- /** Persistent worker-thread client used by the Vite dev plugin. */
284
- var NuxtLintCheckerWorker = class {
285
- worker = new Worker(new URL(import.meta.url));
286
- pending = /* @__PURE__ */ new Map();
287
- nextId = 0;
288
- closed = false;
289
- constructor() {
290
- this.worker.on("message", (response) => {
291
- const pending = this.pending.get(response.id);
292
- if (!pending) return;
293
- this.pending.delete(response.id);
294
- if ("error" in response) {
295
- const error = new Error(response.error.message);
296
- error.stack = response.error.stack ?? error.stack;
297
- pending.reject(error);
298
- } else pending.resolve(response.result);
299
- });
300
- this.worker.on("error", (error) => this.rejectAll(error));
301
- this.worker.on("exit", (code) => {
302
- if (!this.closed) this.rejectAll(/* @__PURE__ */ new Error(`Nuxt lint worker exited with ${code}`));
303
- });
304
- }
305
- run(task) {
306
- if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("Nuxt lint worker is closed"));
307
- const id = ++this.nextId;
308
- return new Promise((resolve, reject) => {
309
- this.pending.set(id, {
310
- reject,
311
- resolve
312
- });
313
- this.worker.postMessage({
314
- id,
315
- task
316
- });
317
- });
318
- }
319
- async close() {
320
- if (this.closed) return;
321
- this.closed = true;
322
- this.rejectAll(/* @__PURE__ */ new Error("Nuxt lint worker closed"));
323
- await this.worker.terminate();
324
- }
325
- rejectAll(error) {
326
- for (const pending of this.pending.values()) pending.reject(error);
327
- this.pending.clear();
435
+ if (ownedAdapter && error !== null && (typeof error === "object" || typeof error === "function")) configFailureArtifacts.set(error, [
436
+ [ownedAdapter, configPath],
437
+ [pathToFileURL(ownedAdapter).href, pathToFileURL(configPath).href],
438
+ [relative(dirname(configPath), ownedAdapter), relative(dirname(configPath), configPath)]
439
+ ]);
440
+ complete = false;
441
+ try {
442
+ const observed = failedConfigModuleObservation(error);
443
+ complete = observed.complete && (privateDirectory === void 0 || moduleGraphLoaded);
444
+ for (const path of observed.paths) if (!isPrivate(path)) files.add(path);
445
+ } catch {}
446
+ throw error;
447
+ } finally {
448
+ hooks?.deregister();
449
+ observeDependencies?.([...files, ...requestedFiles], complete);
328
450
  }
329
- };
330
- //#endregion
331
- //#region src/lint/checker/vite.ts
332
- const PLUGIN_NAME$1 = "vize:nuxt-lint-checker";
333
- function overlayError(output) {
334
- return {
335
- type: "error",
336
- err: {
337
- message: "Vize lint checker found diagnostics",
338
- stack: output,
339
- plugin: PLUGIN_NAME$1
340
- }
341
- };
342
451
  }
343
- var NuxtLintChangeCollector = class {
344
- pendingFiles = /* @__PURE__ */ new Set();
345
- pendingFull = false;
346
- draining = false;
347
- closed = false;
348
- overlayVisible = false;
349
- diagnosticsByFile = /* @__PURE__ */ new Map();
350
- config;
351
- runner;
352
- server;
353
- oxlintEntrypoint;
354
- constructor(config, runner, server, oxlintEntrypoint) {
355
- this.config = config;
356
- this.runner = runner;
357
- this.server = server;
358
- this.oxlintEntrypoint = oxlintEntrypoint;
359
- }
360
- full() {
361
- if (this.closed) return;
362
- this.pendingFull = true;
363
- this.pendingFiles.clear();
364
- this.schedule();
365
- }
366
- file(file) {
367
- if (this.closed) return;
368
- if (path.resolve(file) === path.resolve(this.config.configFile)) {
369
- this.full();
370
- return;
371
- }
372
- if (!matchesNuxtLintCheckerFile(file, this.config.rootDir, this.config.options)) return;
373
- if (!this.config.options.cache) {
374
- this.full();
375
- return;
376
- }
377
- if (!this.pendingFull) this.pendingFiles.add(path.resolve(file));
378
- this.schedule();
379
- }
380
- async close() {
381
- if (this.closed) return;
382
- this.closed = true;
383
- this.pendingFiles.clear();
384
- await this.runner.close();
385
- }
386
- schedule() {
387
- if (this.draining) return;
388
- this.draining = true;
389
- queueMicrotask(() => void this.drain());
390
- }
391
- async drain() {
392
- while (!this.closed && (this.pendingFull || this.pendingFiles.size > 0)) {
393
- const full = this.pendingFull;
394
- const targets = full ? [...this.config.options.include] : [...this.pendingFiles].sort();
395
- this.pendingFull = false;
396
- this.pendingFiles.clear();
397
- try {
398
- const result = await this.runner.run(this.task(targets));
399
- if (!this.closed) this.report(result, targets, full);
400
- } catch (error) {
401
- if (!this.closed) this.reportFailure(error);
452
+ /** Await evaluate(namespace) once before sealing its graph; retain the namespace unchanged. */
453
+ async function importConfigModuleWithDependencies(configPath, registerModuleHooks = nodeModule.registerHooks, withoutVite, evaluate, observeDependencies, beforeRead) {
454
+ const timings = process.env.VIZE_TRACE_EDITOR_PREPARATION === "1" ? [] : void 0;
455
+ const boundary = timings ? {
456
+ active: false,
457
+ resolvedAt: void 0
458
+ } : void 0;
459
+ const finishTotal = beginConfigTiming(timings, "module_total");
460
+ const finishSelection = beginConfigTiming(timings, "engine_selection_with_ack");
461
+ let selectionFinished = false;
462
+ let result;
463
+ const watchInputs = new Set([configPath]);
464
+ let complete = false;
465
+ const observe = (paths, observedComplete) => {
466
+ for (const path of paths) watchInputs.add(path);
467
+ complete = observedComplete;
468
+ };
469
+ try {
470
+ const configURL = pathToFileURL(configPath);
471
+ const require = createRequire(configURL);
472
+ const engineNames = ["vite", "vite-plus"];
473
+ let candidate;
474
+ for (const engineName of engineNames) {
475
+ const searchPaths = require.resolve.paths(engineName) ?? [];
476
+ for (const directory of searchPaths.filter((path) => !globalPaths.includes(path))) {
477
+ const requested = join(directory, engineName);
478
+ watchInputs.add(requested);
479
+ await beforeRead?.([requested]);
480
+ if (lstatSync(requested, { throwIfNoEntry: false }) !== void 0) {
481
+ candidate = {
482
+ engineName,
483
+ directory: requested
484
+ };
485
+ watchInputs.add(join(candidate.directory, "package.json"));
486
+ break;
487
+ }
402
488
  }
489
+ if (candidate !== void 0) break;
403
490
  }
404
- this.draining = false;
405
- if (!this.closed && (this.pendingFull || this.pendingFiles.size > 0)) this.schedule();
406
- }
407
- task(targets) {
408
- const options = this.config.options;
409
- return {
410
- configFile: this.config.configFile,
411
- cwd: this.config.rootDir,
412
- emitError: options.emitError,
413
- emitWarning: options.emitWarning,
414
- exclude: [...options.exclude],
415
- fix: options.fix,
416
- formatter: options.formatter,
417
- oxlintEntrypoint: this.oxlintEntrypoint,
418
- targets
419
- };
420
- }
421
- diagnosticFile(diagnostic) {
422
- const file = diagnostic.filename ?? diagnostic.filePath;
423
- if (!file) return void 0;
424
- return path.resolve(this.config.rootDir, file);
425
- }
426
- report(result, targets, full) {
427
- for (const notice of result.notices) this.server.config.logger.warn(notice);
428
- if (result.output) {
429
- if (result.hasErrors) this.server.config.logger.error(result.output);
430
- else if (result.hasWarnings) this.server.config.logger.warn(result.output);
491
+ if (typeof registerModuleHooks !== "function") {
492
+ if (evaluate) throw new Error("Tracking imports while evaluating a Vite config requires Node.js 22.15 or newer. Upgrade Node.js; an installed config bundler alone cannot track runtime imports.");
493
+ if (candidate === void 0 && !withoutVite) throw new Error("Loading a Vite config without project Vite or Vite+ requires Node.js 22.15 or newer to track imported configuration files. Upgrade Node.js or install Vite or Vite+ in the project.");
431
494
  }
432
- if (full) this.diagnosticsByFile.clear();
433
- else for (const target of targets) this.diagnosticsByFile.delete(path.resolve(target));
434
- for (const diagnostic of result.diagnostics) {
435
- const file = this.diagnosticFile(diagnostic);
436
- if (!file) continue;
437
- const diagnostics = this.diagnosticsByFile.get(file) ?? [];
438
- diagnostics.push(diagnostic);
439
- this.diagnosticsByFile.set(file, diagnostics);
495
+ if (candidate === void 0) {
496
+ finishSelection();
497
+ selectionFinished = true;
498
+ await beforeRead?.([configPath]);
499
+ result = await captureConfigEvaluation(async () => ({ namespace: await (withoutVite ? withoutVite(configURL) : import(configURL.href)) }), configPath, registerModuleHooks, evaluate, void 0, observe, void 0, timings);
500
+ return result;
440
501
  }
441
- const currentDiagnostics = [...this.diagnosticsByFile.entries()].sort(([left], [right]) => left.localeCompare(right)).flatMap(([, diagnostics]) => diagnostics);
442
- if (currentDiagnostics.length > 0) {
443
- this.server.ws.send(overlayError(formatNuxtLintCheckerDiagnostics(currentDiagnostics, this.config.options.formatter)));
444
- this.overlayVisible = true;
445
- } else if (this.overlayVisible) {
446
- this.server.ws.send({
447
- type: "update",
448
- updates: []
502
+ const engineDirectory = realpathSync(candidate.directory);
503
+ watchInputs.add(join(engineDirectory, "package.json"));
504
+ await beforeRead?.([join(candidate.directory, "package.json"), join(engineDirectory, "package.json")]);
505
+ const resolvedEntry = require.resolve(candidate.engineName);
506
+ watchInputs.add(resolvedEntry);
507
+ const engineEntry = realpathSync(resolvedEntry);
508
+ watchInputs.add(engineEntry);
509
+ const entryPath = relative(engineDirectory, engineEntry);
510
+ if (entryPath === ".." || entryPath.startsWith(`..${sep}`) || isAbsolute(entryPath)) {
511
+ const engineLabel = candidate.engineName === "vite" ? "Vite" : "Vite+";
512
+ throw new Error(`Resolved loader escapes selected project ${engineLabel}: ${candidate.directory} -> ${engineEntry}`);
513
+ }
514
+ await beforeRead?.([resolvedEntry, engineEntry]);
515
+ finishSelection();
516
+ selectionFinished = true;
517
+ const finishImport = beginConfigTiming(timings, "engine_import");
518
+ let loadConfigFromFile;
519
+ try {
520
+ const engine = await import(pathToFileURL(engineEntry).href);
521
+ loadConfigFromFile = engine.loadConfigFromFile ?? engine.default?.loadConfigFromFile;
522
+ if (typeof loadConfigFromFile !== "function") throw new Error(`${candidate.engineName} does not export loadConfigFromFile`);
523
+ } finally {
524
+ finishImport();
525
+ }
526
+ const finishAdapter = beginConfigTiming(timings, "adapter_prepare");
527
+ let temporary;
528
+ try {
529
+ temporary = await realpath(await mkdtemp(join(tmpdir(), "vize-config-module-")));
530
+ } catch (error) {
531
+ finishAdapter();
532
+ throw error;
533
+ }
534
+ try {
535
+ const adapter = join(temporary, "config.mjs");
536
+ await writeFile(adapter, `import * as original from ${JSON.stringify(configModuleImportPath(configURL))};\nexport default { namespace: original };\n`, {
537
+ flag: "wx",
538
+ mode: 384
449
539
  });
450
- this.overlayVisible = false;
540
+ finishAdapter();
541
+ result = await captureConfigEvaluation(async () => {
542
+ const finishAck = beginConfigTiming(timings, "selected_before_read_ack");
543
+ try {
544
+ await beforeRead?.([configPath]);
545
+ } finally {
546
+ finishAck();
547
+ }
548
+ const finishProfile = timings ? await beginPublicLoadProfile() : void 0;
549
+ const finishLoad = beginConfigTiming(timings, "public_load", boundary);
550
+ let loaded;
551
+ try {
552
+ loaded = await loadConfigFromFile({
553
+ mode: "development",
554
+ command: "serve"
555
+ }, adapter, dirname(configPath), "silent", void 0, "bundle");
556
+ } finally {
557
+ finishLoad();
558
+ if (finishProfile) timings.find((row) => row.phase === "public_load").cpuProfile = await finishProfile();
559
+ }
560
+ if (!loaded) throw new Error(`${candidate.engineName} did not load the selected config: ${configPath}`);
561
+ return {
562
+ namespace: loaded.config.namespace,
563
+ dependencies: loaded.dependencies
564
+ };
565
+ }, configPath, registerModuleHooks, evaluate, temporary, observe, adapter, timings, boundary);
566
+ return result;
567
+ } catch (error) {
568
+ finishAdapter();
569
+ throw error;
570
+ } finally {
571
+ const finishCleanup = beginConfigTiming(timings, "adapter_cleanup");
572
+ try {
573
+ await rm(temporary, {
574
+ recursive: true,
575
+ force: true
576
+ });
577
+ } finally {
578
+ finishCleanup();
579
+ }
451
580
  }
581
+ } catch (error) {
582
+ if (timings && error !== null && (typeof error === "object" || typeof error === "function")) configEvaluationTimings.set(error, timings);
583
+ throw error;
584
+ } finally {
585
+ if (!selectionFinished) finishSelection();
586
+ finishTotal();
587
+ if (timings && result) configEvaluationTimings.set(result, timings);
588
+ observeDependencies?.([...watchInputs], complete);
452
589
  }
453
- reportFailure(error) {
454
- const message = `Nuxt lint checker failed: ${error instanceof Error ? error.message : String(error)}`;
455
- this.server.config.logger.error(message);
456
- this.server.ws.send(overlayError(message));
457
- this.overlayVisible = true;
590
+ }
591
+ JSON.parse("{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"compiler\":{\"$ref\":\"#/definitions/CompilerConfig\"},\"experimentals\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"boolean\"},{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]}},\"dialect\":{\"type\":\"string\",\"enum\":[\"vue\",\"petite-vue\"]},\"vite\":{\"$ref\":\"#/definitions/VitePluginConfig\"},\"musea\":{\"$ref\":\"#/definitions/MuseaConfig\"},\"typeChecker\":{\"$ref\":\"#/definitions/TypeCheckerConfig\"},\"linter\":{\"$ref\":\"#/definitions/LinterConfig\"},\"formatter\":{\"$ref\":\"#/definitions/FormatterConfig\"},\"languageServer\":{\"$ref\":\"#/definitions/LanguageServerConfig\"},\"globalTypes\":{\"$ref\":\"#/definitions/GlobalTypesConfig\"},\"files\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ignores\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"basePath\":{\"type\":\"string\"},\"lib\":{\"$ref\":\"#/definitions/LibConfig\"},\"compile\":{\"$ref\":\"#/definitions/CompilerConfig\"},\"typeCheck\":{\"$ref\":\"#/definitions/TypeCheckerConfig\"},\"fmt\":{\"$ref\":\"#/definitions/FormatterConfig\"},\"lint\":{\"type\":\"object\",\"required\":[\"jsPlugins\",\"plugins\",\"rules\",\"settings\"],\"properties\":{\"jsPlugins\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"plugins\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"rules\":{\"type\":\"object\",\"additionalProperties\":true},\"settings\":{\"type\":\"object\",\"additionalProperties\":true},\"ignorePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"overrides\":{\"type\":\"array\"}},\"additionalProperties\":true},\"version\":{\"$ref\":\"#/definitions/VueVersion\"},\"entries\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"basePath\":{\"type\":\"string\"},\"files\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ignores\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"compiler\":{\"$ref\":\"#/definitions/CompilerConfig\"},\"linter\":{\"$ref\":\"#/definitions/LinterConfig\"}},\"additionalProperties\":false}}},\"additionalProperties\":false,\"definitions\":{\"CompilerConfig\":{\"type\":\"object\",\"properties\":{\"mode\":{\"type\":\"string\",\"enum\":[\"module\",\"function\"]},\"vapor\":{\"type\":\"boolean\"},\"jsxMode\":{\"type\":\"string\",\"enum\":[\"vdom\",\"vapor\"]},\"jsxCompat\":{\"type\":\"string\",\"enum\":[\"native\",\"babel\"]},\"customRenderer\":{\"type\":\"boolean\"},\"customElements\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ssr\":{\"type\":\"boolean\"},\"templateSyntax\":{\"type\":\"string\",\"enum\":[\"standard\",\"strict\",\"quirks\"]},\"whitespace\":{\"type\":\"string\",\"enum\":[\"condense\",\"preserve\",\"vue2-line-breaks\",\"vue2-preserve\"]},\"sourceMap\":{\"type\":\"boolean\"},\"prefixIdentifiers\":{\"type\":\"boolean\"},\"hoistStatic\":{\"type\":\"boolean\"},\"cacheHandlers\":{\"type\":\"boolean\"},\"comments\":{\"type\":\"boolean\"},\"isTs\":{\"type\":\"boolean\"},\"scriptExt\":{\"type\":\"string\",\"enum\":[\"ts\",\"js\"]},\"runtimeModuleName\":{\"type\":\"string\"},\"runtimeGlobalName\":{\"type\":\"string\"},\"compatibility\":{\"$ref\":\"#/definitions/CompilerCompatibilityConfig\"}},\"additionalProperties\":false},\"CompilerCompatibilityConfig\":{\"type\":\"object\",\"properties\":{\"vueVersion\":{\"$ref\":\"#/definitions/VueVersion\"},\"hostCompiler\":{\"type\":\"boolean\"},\"scriptSetupInStandalone\":{\"type\":\"boolean\"},\"optionsApiVapor\":{\"type\":\"boolean\"},\"nuxtVersion\":{\"type\":\"integer\",\"enum\":[2,3,4]},\"webpackVersion\":{\"type\":\"integer\",\"enum\":[4,5]}},\"additionalProperties\":false},\"VueVersion\":{\"type\":\"string\",\"enum\":[\"3\",\"2.7\",\"2\",\"1\",\"0.11\",\"0.10\"]},\"VitePluginConfig\":{\"type\":\"object\",\"properties\":{\"include\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"exclude\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"scanPatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ignorePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"MuseaConfig\":{\"type\":\"object\",\"properties\":{\"include\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"exclude\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"basePath\":{\"type\":\"string\"},\"storybookCompat\":{\"type\":\"boolean\"},\"inlineArt\":{\"type\":\"boolean\"},\"vrt\":{\"$ref\":\"#/definitions/MuseaVrtConfig\"},\"a11y\":{\"$ref\":\"#/definitions/MuseaA11yConfig\"},\"autogen\":{\"$ref\":\"#/definitions/MuseaAutogenConfig\"}},\"additionalProperties\":false},\"MuseaVrtConfig\":{\"type\":\"object\",\"properties\":{\"threshold\":{\"type\":\"number\"},\"outDir\":{\"type\":\"string\"},\"viewports\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/MuseaViewport\"}}},\"additionalProperties\":false},\"MuseaViewport\":{\"type\":\"object\",\"properties\":{\"width\":{\"type\":\"integer\"},\"height\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"width\",\"height\"]},\"MuseaA11yConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"rules\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"boolean\"}}},\"additionalProperties\":false},\"MuseaAutogenConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"maxVariants\":{\"type\":\"integer\"}},\"additionalProperties\":false},\"TypeCheckerConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"strict\":{\"type\":\"boolean\"},\"checkProps\":{\"type\":\"boolean\"},\"checkEmits\":{\"type\":\"boolean\"},\"checkTemplateBindings\":{\"type\":\"boolean\"},\"checkReactivity\":{\"type\":\"boolean\"},\"checkSetupContext\":{\"type\":\"boolean\"},\"checkInvalidExports\":{\"type\":\"boolean\"},\"checkFallthroughAttrs\":{\"type\":\"boolean\"},\"optionsApi\":{\"type\":\"boolean\"},\"legacyVue2\":{\"type\":\"boolean\"},\"jsxTypecheck\":{\"type\":\"boolean\"},\"tsconfig\":{\"type\":\"string\"},\"corsaPath\":{\"type\":\"string\"},\"tsgoPath\":{\"type\":\"string\"},\"tsrsPath\":{\"type\":\"string\"},\"globalsFile\":{\"type\":\"string\"},\"servers\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":32},\"lspRequestTimeoutMs\":{\"type\":\"integer\",\"minimum\":1}},\"additionalProperties\":false},\"LinterConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"preset\":{\"type\":\"string\",\"enum\":[\"general-recommended\",\"general_recommended\",\"generalRecommended\",\"happy-path\",\"happy_path\",\"happy\",\"default\",\"recommended\",\"opinionated\",\"strict\",\"all\",\"essential\",\"incremental\",\"ecosystem\",\"nuxt\"]},\"typeAware\":{\"type\":\"boolean\"},\"crossFile\":{\"type\":\"boolean\"},\"crossFileTree\":{\"type\":\"boolean\"},\"crossFileComplexity\":{\"type\":\"boolean\"},\"strictReactivity\":{\"type\":\"boolean\"},\"maxWarnings\":{\"type\":\"integer\",\"minimum\":0},\"rules\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]}},\"ruleOptions\":{\"$ref\":\"#/definitions/LintRuleOptions\"},\"categories\":{\"type\":\"object\",\"properties\":{\"correctness\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"suspicious\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"style\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"perf\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"a11y\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"security\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]}},\"additionalProperties\":false}},\"additionalProperties\":false},\"LintRuleOptions\":{\"type\":\"object\",\"properties\":{\"script/define-macros-order\":{\"type\":\"object\",\"properties\":{\"order\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"minLength\":1},\"uniqueItems\":true}},\"additionalProperties\":false},\"script/define-props-destructuring\":{\"type\":\"object\",\"properties\":{\"destructure\":{\"type\":\"string\",\"enum\":[\"only-when-assigned\",\"always\",\"never\"]}},\"additionalProperties\":false},\"html/no-empty-palpable-content\":{\"type\":\"object\",\"properties\":{\"contentDirectives\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"type/strict-boolean-expressions\":{\"type\":\"object\",\"properties\":{\"allowString\":{\"type\":\"boolean\"},\"allowNumber\":{\"type\":\"boolean\"},\"allowNullableObject\":{\"type\":\"boolean\"},\"allowNullableBoolean\":{\"type\":\"boolean\"},\"allowNullableString\":{\"type\":\"boolean\"},\"allowNullableNumber\":{\"type\":\"boolean\"},\"allowNullableEnum\":{\"type\":\"boolean\"},\"allowAny\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"script/no-restricted-globals\":{\"$ref\":\"#/definitions/NoRestrictedGlobalsOptions\"},\"script/no-restricted-members\":{\"$ref\":\"#/definitions/NoRestrictedMembersOptions\"},\"vue/component-name-in-template-casing\":{\"type\":\"object\",\"properties\":{\"casing\":{\"type\":\"string\",\"enum\":[\"PascalCase\",\"kebab-case\"]},\"registeredComponentsOnly\":{\"type\":\"boolean\"},\"globals\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"script/custom-event-name-casing\":{\"type\":\"object\",\"properties\":{\"casing\":{\"type\":\"string\",\"enum\":[\"camelCase\",\"kebab-case\"]}},\"additionalProperties\":false},\"vue/no-mutating-props\":{\"type\":\"object\",\"properties\":{\"shallowOnly\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"vue/require-component-registration\":{\"type\":\"object\",\"properties\":{\"globals\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"vue/sfc-element-order\":{\"type\":\"object\",\"properties\":{\"order\":{\"type\":\"array\",\"items\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}}]}}},\"additionalProperties\":false},\"vue/html-self-closing\":{\"type\":\"object\",\"properties\":{\"html\":{\"type\":\"object\",\"properties\":{\"void\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]},\"normal\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]},\"component\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]}},\"additionalProperties\":false},\"svg\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]},\"math\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]}},\"additionalProperties\":false},\"vue/html-quotes\":{\"oneOf\":[{\"type\":\"string\",\"enum\":[\"double\",\"single\"]},{\"type\":\"object\",\"properties\":{\"style\":{\"type\":\"string\",\"enum\":[\"double\",\"single\"]},\"avoidEscape\":{\"type\":\"boolean\"}},\"additionalProperties\":false}]},\"vue/mustache-interpolation-spacing\":{\"type\":\"string\",\"enum\":[\"always\",\"never\"]},\"vue/v-on-event-hyphenation\":{\"type\":\"string\",\"enum\":[\"always\",\"never\"]},\"vue/v-bind-style\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]},\"vue/v-on-style\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]},\"vue/v-slot-style\":{\"oneOf\":[{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]},{\"type\":\"object\",\"properties\":{\"atComponent\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\",\"v-slot\"]},\"default\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\",\"v-slot\"]},\"named\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]}},\"additionalProperties\":false}]},\"vue/attribute-hyphenation\":{\"type\":\"string\",\"enum\":[\"always\",\"never\"]},\"vue/valid-v-on\":{\"type\":\"object\",\"properties\":{\"modifiers\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"vue/valid-v-slot\":{\"type\":\"object\",\"properties\":{\"allowModifiers\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"musea/prefer-design-tokens\":{\"$ref\":\"#/definitions/MuseaPreferDesignTokensOptions\"}},\"additionalProperties\":false},\"NoRestrictedGlobalsOptions\":{\"type\":\"object\",\"properties\":{\"globals\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/RestrictedGlobal\"}}},\"additionalProperties\":false},\"RestrictedGlobal\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"name\"]},\"NoRestrictedMembersOptions\":{\"type\":\"object\",\"properties\":{\"members\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/RestrictedMember\"}}},\"additionalProperties\":false},\"RestrictedMember\":{\"type\":\"object\",\"properties\":{\"object\":{\"type\":\"string\"},\"property\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"object\",\"property\"]},\"MuseaPreferDesignTokensOptions\":{\"type\":\"object\",\"properties\":{\"tokens\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/MuseaDesignToken\"}}},\"additionalProperties\":false},\"MuseaDesignToken\":{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\"},\"value\":{\"type\":\"string\"},\"tier\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"path\",\"value\"]},\"FormatterConfig\":{\"type\":\"object\",\"properties\":{\"ignorePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"preset\":{\"type\":\"string\",\"enum\":[\"vize\",\"prettier\",\"compact\",\"documentation\"]},\"sortImports\":{\"oneOf\":[{\"type\":\"boolean\",\"enum\":[false]},{\"$ref\":\"#/definitions/SortImportsConfig\"}]},\"printWidth\":{\"type\":\"integer\"},\"tabWidth\":{\"type\":\"integer\"},\"useTabs\":{\"type\":\"boolean\"},\"semi\":{\"type\":\"boolean\"},\"singleQuote\":{\"type\":\"boolean\"},\"jsxSingleQuote\":{\"type\":\"boolean\"},\"trailingComma\":{\"type\":\"string\",\"enum\":[\"all\",\"none\",\"es5\"]},\"bracketSpacing\":{\"type\":\"boolean\"},\"bracketSameLine\":{\"type\":\"boolean\"},\"arrowParens\":{\"type\":\"string\",\"enum\":[\"always\",\"avoid\"]},\"endOfLine\":{\"type\":\"string\",\"enum\":[\"lf\",\"crlf\",\"cr\",\"auto\"]},\"quoteProps\":{\"type\":\"string\",\"enum\":[\"as-needed\",\"consistent\",\"preserve\"]},\"singleAttributePerLine\":{\"type\":\"boolean\"},\"vueIndentScriptAndStyle\":{\"type\":\"boolean\"},\"sortAttributes\":{\"type\":\"boolean\"},\"attributeSortOrder\":{\"type\":\"string\",\"enum\":[\"alphabetical\",\"as-written\"]},\"mergeBindAndNonBindAttrs\":{\"type\":\"boolean\"},\"maxAttributesPerLine\":{\"type\":\"integer\"},\"attributeGroups\":{\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"normalizeDirectiveShorthands\":{\"type\":\"boolean\"},\"sortBlocks\":{\"type\":\"boolean\"},\"normalizeCssQuotes\":{\"type\":\"boolean\"},\"normalizeInlineStyles\":{\"type\":\"boolean\"},\"normalizeVForParens\":{\"type\":\"boolean\"},\"selfCloseVoidElements\":{\"type\":\"boolean\"},\"reindentPreprocessorStyles\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"SortImportsConfig\":{\"type\":\"object\",\"properties\":{\"partitionByNewline\":{\"type\":\"boolean\"},\"partitionByComment\":{\"type\":\"boolean\"},\"sortSideEffects\":{\"type\":\"boolean\"},\"order\":{\"type\":\"string\",\"enum\":[\"asc\",\"desc\"]},\"ignoreCase\":{\"type\":\"boolean\"},\"newlinesBetween\":{\"type\":\"boolean\"},\"internalPattern\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"groups\":{\"type\":\"array\",\"items\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}},{\"type\":\"object\",\"properties\":{\"newlinesBetween\":{\"type\":\"boolean\"}},\"additionalProperties\":false,\"required\":[\"newlinesBetween\"]}]}},\"customGroups\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/ImportSortCustomGroup\"}}},\"additionalProperties\":false},\"ImportSortCustomGroup\":{\"type\":\"object\",\"properties\":{\"groupName\":{\"type\":\"string\"},\"elementNamePattern\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"selector\":{\"type\":\"string\"},\"modifiers\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false,\"required\":[\"groupName\"]},\"LanguageServerConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"lint\":{\"type\":\"boolean\"},\"diagnostics\":{\"type\":\"boolean\"},\"typecheck\":{\"type\":\"boolean\"},\"editor\":{\"type\":\"boolean\"},\"ecosystem\":{\"type\":\"boolean\"},\"crossFile\":{\"type\":\"boolean\"},\"legacyVue2\":{\"type\":\"boolean\"},\"completion\":{\"type\":\"boolean\"},\"signatureHelp\":{\"type\":\"boolean\"},\"hover\":{\"type\":\"boolean\"},\"definition\":{\"type\":\"boolean\"},\"references\":{\"type\":\"boolean\"},\"documentSymbols\":{\"type\":\"boolean\"},\"workspaceSymbols\":{\"type\":\"boolean\"},\"formatting\":{\"type\":\"boolean\"},\"codeActions\":{\"type\":\"boolean\"},\"rename\":{\"type\":\"boolean\"},\"codeLens\":{\"type\":\"boolean\"},\"semanticTokens\":{\"type\":\"boolean\"},\"documentLinks\":{\"type\":\"boolean\"},\"foldingRanges\":{\"type\":\"boolean\"},\"inlayHints\":{\"type\":\"boolean\"},\"fileRename\":{\"type\":\"boolean\"},\"corsa\":{\"type\":\"boolean\"},\"tsgo\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"GlobalTypesConfig\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"string\"},{\"$ref\":\"#/definitions/GlobalTypeDeclaration\"}]}},\"GlobalTypeDeclaration\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\"},\"defaultValue\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"type\"]},\"LibConfig\":{\"type\":\"object\",\"properties\":{\"dir\":{\"type\":\"string\"},\"uiDir\":{\"type\":\"string\"},\"composableDir\":{\"type\":\"string\"},\"lockfile\":{\"type\":\"string\"},\"registries\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"object\",\"properties\":{\"source\":{\"type\":\"string\"},\"dir\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"source\"]}]},\"propertyNames\":{\"pattern\":\"^@[a-z0-9][a-z0-9._-]*$\"}}},\"additionalProperties\":false}}}");
592
+ const sourceConfigKey = Symbol.for("@vizejs/vite-plugin/vite-plus/source");
593
+ function object(value) {
594
+ if (value === null || typeof value !== "object") return false;
595
+ const prototype = Object.getPrototypeOf(value);
596
+ return prototype === Object.prototype || prototype === null;
597
+ }
598
+ async function resolveSource(value, env, parents = /* @__PURE__ */ new Set()) {
599
+ value = await value;
600
+ if (parents.has(value)) throw new Error("Circular Vue configuration source");
601
+ parents.add(value);
602
+ try {
603
+ if ((typeof value === "function" || object(value)) && sourceConfigKey in value) return await resolveSource(value[sourceConfigKey], env, parents);
604
+ const config = await (typeof value === "function" ? value(env) : value);
605
+ if (!object(config)) throw new Error("Vite config must export an object or a config function");
606
+ rejectLegacyConfig(config);
607
+ return config;
608
+ } finally {
609
+ parents.delete(value);
458
610
  }
459
- };
460
- /** Create the client-side Vite dev plugin; it has no transform/render hooks. */
461
- function createNuxtLintCheckerVitePlugin(config, dependencies = {}) {
462
- return {
463
- name: PLUGIN_NAME$1,
464
- apply: "serve",
465
- enforce: "post",
466
- configureServer(server) {
467
- const collector = new NuxtLintChangeCollector(config, dependencies.createRunner?.() ?? new NuxtLintCheckerWorker(), server, dependencies.oxlintEntrypoint);
468
- server.watcher.add(config.configFile);
469
- const changed = (file) => collector.file(file);
470
- server.watcher.on("add", changed);
471
- server.watcher.on("change", changed);
472
- server.watcher.on("unlink", changed);
473
- server.httpServer?.once("close", () => void collector.close());
474
- if (config.options.lintOnStart) collector.full();
475
- }
611
+ }
612
+ function rejectLegacyConfig(source) {
613
+ if (Object.hasOwn(source, "extends") && typeof source.extends !== "boolean") throw new Error("Custom config extends is no longer supported; use defineConfig(vpConfig).withVue(vueConfig)");
614
+ if (Object.hasOwn(source, "vize")) throw new Error("vize: configuration is no longer supported; move Vue settings to vue: in vite.config.*");
615
+ for (const key of [
616
+ "lint",
617
+ "fmt",
618
+ "pack"
619
+ ]) if ((Array.isArray(source[key]) ? source[key] : [source[key]]).some((value) => object(value) && Object.hasOwn(value, "vize"))) throw new Error(key === "lint" ? "lint.vize is no longer supported; pass { lint: false } as defineConfig's integration options to disable the Vite+ native lint task while keeping CLI lint enabled, and put shared lint settings in vue.linter" : `${key}.vize: configuration is no longer supported; move Vue settings to vue: in vite.config.*`);
620
+ }
621
+ const VITE_CONFIG_FILE_NAMES = [
622
+ "vite.config.ts",
623
+ "vite.config.js",
624
+ "vite.config.mjs",
625
+ "vite.config.cjs",
626
+ "vite.config.mts",
627
+ "vite.config.cts"
628
+ ];
629
+ /** Resolve an authored Vite export without projecting away Vite-owned task settings. */
630
+ async function resolveViteConfigSource(exported, env) {
631
+ env ??= {
632
+ mode: "development",
633
+ command: "serve"
634
+ };
635
+ if (env.command !== "build" && env.command !== "serve") env = {
636
+ ...env,
637
+ command: "serve"
476
638
  };
639
+ return resolveSource(exported, env);
477
640
  }
478
641
  //#endregion
479
- //#region src/lint/checker/webpack.ts
480
- const PLUGIN_NAME = "VizeNuxtLintChecker";
481
- function checkerError(message) {
482
- const error = new Error(message);
483
- error.name = PLUGIN_NAME;
484
- return error;
642
+ //#region src/lint/project-rules.ts
643
+ const CONFIG_PRESETS = [
644
+ "happy-path",
645
+ "opinionated",
646
+ "essential",
647
+ "incremental",
648
+ "ecosystem",
649
+ "nuxt"
650
+ ];
651
+ const RETIRED_CONFIG = /^vize\.config\.(?:pkl|[cm]?[jt]s|json)$/;
652
+ const VIZE_JS_PLUGIN_SPECIFIER = "oxlint-plugin-vize";
653
+ const CONFIG_MIGRATION = "vize.config.* is no longer supported; move Vue settings to vue: in vite.config.* and TypeScript settings to tsconfig.json";
654
+ async function readProjectLintRuleSets(rootDir, loadPreset = loadPresetRules) {
655
+ const project = await readProjectConfig(rootDir);
656
+ const linter = project.linter;
657
+ const oxlint = explicitOxlintRules(project.oxlint);
658
+ const jsPlugins = explicitOxlintJsPlugins(project.oxlint, project.oxlintConfigDir);
659
+ const oxlintOverrides = explicitOxlintOverrides(project.oxlint, project.oxlintConfigDir);
660
+ const warnings = [];
661
+ let vize;
662
+ if (linter) {
663
+ const rules = applyRuleOptions({
664
+ ...linter.preset && linter.preset !== "incremental" ? await loadPreset(linter.preset, linter.typeAware) : {},
665
+ ...linter.rules
666
+ }, linter.ruleOptions, warnings, "vue.linter");
667
+ if (Object.keys(rules).length > 0) vize = rules;
668
+ }
669
+ const entries = project.entries.map((entry, index) => {
670
+ const rules = applyRuleOptions({ ...entry.rules }, entry.ruleOptions, warnings, `vue.entries[${String(index)}].linter`, vize);
671
+ if (Object.keys(rules).length === 0) return void 0;
672
+ return {
673
+ files: entry.files,
674
+ ...entry.ignores ? { ignores: entry.ignores } : {},
675
+ ...entry.name ? { name: entry.name } : {},
676
+ rules
677
+ };
678
+ }).filter((entry) => entry !== void 0);
679
+ return {
680
+ ...entries.length > 0 ? { entries } : {},
681
+ ...jsPlugins.length > 0 ? { jsPlugins } : {},
682
+ ...vize ? { vize } : {},
683
+ ...Object.keys(oxlint).length > 0 ? { oxlint } : {},
684
+ ...oxlintOverrides.length > 0 ? { oxlintOverrides } : {},
685
+ ...warnings.length > 0 ? { warnings } : {}
686
+ };
485
687
  }
486
- function reportResult(compilation, result) {
487
- for (const notice of result.notices) compilation.warnings.push(checkerError(notice));
488
- if (result.hasErrors) compilation.errors.push(checkerError(result.output));
489
- else if (result.hasWarnings) compilation.warnings.push(checkerError(result.output));
688
+ async function readProjectConfig(rootDir) {
689
+ const loaded = await loadProjectViteConfigSource(rootDir);
690
+ if (!loaded) return { entries: [] };
691
+ const parsed = loaded.source;
692
+ const rawVue = parsed.vue && typeof parsed.vue === "object" ? parsed.vue : void 0;
693
+ const rawLinter = rawVue && "linter" in rawVue ? projectLinter(rawVue.linter) : void 0;
694
+ return {
695
+ entries: rawVue && "entries" in rawVue ? projectEntries(rawVue.entries) : [],
696
+ linter: rawLinter,
697
+ oxlint: parsed.lint,
698
+ oxlintConfigDir: loaded.configDir
699
+ };
490
700
  }
491
- function task(config, targets, oxlintEntrypoint) {
492
- const options = config.options;
701
+ function projectLinter(value) {
702
+ if (!value || typeof value !== "object") return void 0;
703
+ const raw = value;
493
704
  return {
494
- configFile: config.configFile,
495
- cwd: config.rootDir,
496
- emitError: options.emitError,
497
- emitWarning: options.emitWarning,
498
- exclude: [...options.exclude],
499
- fix: options.fix,
500
- formatter: options.formatter,
501
- oxlintEntrypoint,
502
- targets
705
+ preset: isConfigPreset(raw.preset) ? raw.preset : void 0,
706
+ ruleOptions: explicitRuleOptions(raw.ruleOptions),
707
+ typeAware: raw.typeAware === true,
708
+ rules: explicitRules(raw.rules)
503
709
  };
504
710
  }
505
- function changedTargets(compiler, config, initial) {
506
- const modified = compiler.modifiedFiles;
507
- if (initial && config.options.lintOnStart) return [...config.options.include];
508
- if (!modified || modified.size === 0) return void 0;
509
- if (!config.options.cache) return [...config.options.include];
510
- const configFile = path.resolve(config.configFile);
511
- if ([...modified].some((file) => path.resolve(file) === configFile)) return [...config.options.include];
512
- const files = [...modified].filter((file) => matchesNuxtLintCheckerFile(file, config.rootDir, config.options)).map((file) => path.resolve(file)).sort();
513
- return files.length > 0 ? files : void 0;
514
- }
515
- /**
516
- * Create Nuxt 2's webpack adapter.
517
- *
518
- * The worker starts at `watchRun`, concurrently with compilation; only the
519
- * final diagnostic handoff happens at `afterCompile`, where webpack can feed
520
- * the result to its existing terminal and browser overlays.
521
- */
522
- function createNuxtLintCheckerWebpackPlugin(config, dependencies = {}) {
523
- return { apply(compiler) {
524
- const runner = dependencies.createRunner?.() ?? new NuxtLintCheckerWorker();
525
- let initial = true;
526
- let pending;
527
- compiler.hooks.watchRun.tap(PLUGIN_NAME, (nextCompiler) => {
528
- const targets = changedTargets(nextCompiler, config, initial);
529
- initial = false;
530
- pending = targets ? runner.run(task(config, targets, dependencies.oxlintEntrypoint)) : void 0;
531
- });
532
- compiler.hooks.afterCompile.tapPromise(PLUGIN_NAME, async (compilation) => {
533
- compilation.fileDependencies.add(config.configFile);
534
- if (!pending) return;
535
- const current = pending;
536
- pending = void 0;
537
- try {
538
- reportResult(compilation, await current);
539
- } catch (error) {
540
- compilation.errors.push(checkerError(`Nuxt lint checker failed: ${error instanceof Error ? error.message : String(error)}`));
541
- }
542
- });
543
- compiler.hooks.watchClose.tap(PLUGIN_NAME, () => void runner.close());
544
- } };
545
- }
546
- //#endregion
547
- //#region src/lint/checker/setup.ts
548
- function registerNuxt2Checker(nuxt, builder, plugin) {
549
- if (!nuxt.hook) throw new Error("Nuxt 2 checker registration requires the host hook API.");
550
- if (builder === "webpack") nuxt.hook("webpack:config", (value) => {
551
- for (const config of value) if (config.name === "client") (config.plugins ??= []).push(plugin);
711
+ function projectEntries(value) {
712
+ if (!Array.isArray(value)) return [];
713
+ return value.flatMap((candidate) => {
714
+ if (!candidate || typeof candidate !== "object") return [];
715
+ const raw = candidate;
716
+ const linter = projectLinter(raw.linter);
717
+ const files = scopedGlobs(raw.files, raw.basePath);
718
+ if (!linter || files.length === 0) return [];
719
+ const ignores = scopedGlobs(raw.ignores, raw.basePath);
720
+ return [{
721
+ ...linter,
722
+ files,
723
+ ...ignores.length > 0 ? { ignores } : {},
724
+ ...typeof raw.name === "string" && raw.name ? { name: raw.name } : {}
725
+ }];
552
726
  });
553
- else nuxt.hook("vite:extendConfig", (value, context) => {
554
- if (context?.isServer) return;
555
- const config = value;
556
- (config.plugins ??= []).push(plugin);
727
+ }
728
+ function scopedGlobs(value, basePath) {
729
+ if (!Array.isArray(value)) return [];
730
+ const base = typeof basePath === "string" && basePath ? basePath : void 0;
731
+ return value.flatMap((glob) => {
732
+ if (typeof glob !== "string" || !glob) return [];
733
+ return [base && !path$1.isAbsolute(glob) ? path$1.join(base, glob) : glob];
557
734
  });
558
735
  }
559
- async function addVitePlugin(plugin) {
560
- (await import("@nuxt/kit")).addVitePlugin(plugin, { server: false });
736
+ async function loadProjectViteConfigSource(rootDir) {
737
+ let directory = path$1.resolve(rootDir);
738
+ while (true) {
739
+ for (const name of VITE_CONFIG_FILE_NAMES) {
740
+ const filePath = path$1.join(directory, name);
741
+ if (!fs$1.existsSync(filePath)) continue;
742
+ const module = await importConfigModule(filePath);
743
+ if (module === null) throw new Error("Unable to load Vite configuration at " + filePath);
744
+ return {
745
+ configDir: directory,
746
+ source: await resolveViteConfigSource(module.default ?? module, {
747
+ command: "lint",
748
+ mode: "development"
749
+ })
750
+ };
751
+ }
752
+ if (fs$1.existsSync(directory) && fs$1.readdirSync(directory).some((name) => RETIRED_CONFIG.test(name))) throw new Error(CONFIG_MIGRATION);
753
+ if ([
754
+ "package.json",
755
+ "tsconfig.json",
756
+ "jsconfig.json"
757
+ ].some((name) => fs$1.existsSync(path$1.join(directory, name)))) return null;
758
+ const parent = path$1.dirname(directory);
759
+ if (parent === directory) return null;
760
+ directory = parent;
761
+ }
561
762
  }
562
- async function addWebpackPlugin(plugin) {
563
- (await import("@nuxt/kit")).addWebpackPlugin(plugin, { server: false });
763
+ const OXLINT_SEVERITIES = new Map([
764
+ ["off", "off"],
765
+ ["allow", "off"],
766
+ [0, "off"],
767
+ ["warn", "warn"],
768
+ [1, "warn"],
769
+ ["error", "error"],
770
+ ["deny", "error"],
771
+ [2, "error"]
772
+ ]);
773
+ function explicitOxlintRules(value) {
774
+ if (!value || typeof value !== "object") return {};
775
+ return oxlintRules("rules" in value ? value.rules : void 0);
564
776
  }
565
- /** Register the dev-only adapter over Phase 3's generated config artifact. */
566
- async function setupNuxtLintChecker(checker, nuxt, generation, dependencies = {}) {
567
- if (checker !== true && (checker === false || checker == null)) return void 0;
568
- if (nuxt.options.dev !== true) return void 0;
569
- if (!generation) throw new Error("The Nuxt lint checker requires lint config generation; enable `vize.lint`.");
570
- const options = resolveNuxtLintCheckerOptions(checker, {
571
- buildDir: nuxt.options.buildDir,
572
- srcDir: nuxt.options.srcDir ?? nuxt.options.rootDir
573
- });
574
- if (options === false) return void 0;
575
- const rootDir = path.resolve(nuxt.options.rootDir);
576
- const config = {
577
- configFile: generation.configFile,
578
- options,
579
- rootDir
580
- };
581
- const builder = getDetectedNuxtBuilderKind(nuxt);
582
- if (builder === "vite") {
583
- const plugin = createNuxtLintCheckerVitePlugin(config);
584
- if (!dependencies.addVitePlugin && getDetectedNuxtMajor(nuxt) === 2) registerNuxt2Checker(nuxt, builder, plugin);
585
- else await (dependencies.addVitePlugin ?? addVitePlugin)(plugin);
586
- } else if (builder === "webpack") {
587
- const plugin = createNuxtLintCheckerWebpackPlugin(config);
588
- if (!dependencies.addWebpackPlugin && getDetectedNuxtMajor(nuxt) === 2) registerNuxt2Checker(nuxt, builder, plugin);
589
- else await (dependencies.addWebpackPlugin ?? addWebpackPlugin)(plugin);
590
- } else {
591
- const label = typeof nuxt.options.builder === "string" ? nuxt.options.builder : "unknown";
592
- (dependencies.warn ?? console.warn)(`Unsupported Nuxt builder ${label}; Vize lint checker is disabled.`);
777
+ /** Oxlint's `severity` and `[severity, ...options]` forms, with severity aliases normalized. */
778
+ function oxlintRules(value) {
779
+ if (!value || typeof value !== "object") return {};
780
+ const result = {};
781
+ for (const [id, config] of Object.entries(value)) {
782
+ const severity = OXLINT_SEVERITIES.get(Array.isArray(config) ? config[0] : config);
783
+ if (!severity) continue;
784
+ result[id] = Array.isArray(config) ? [severity, ...config.slice(1)] : severity;
593
785
  }
594
- return {
595
- builder,
596
- configFile: generation.configFile,
597
- options
598
- };
786
+ return result;
599
787
  }
600
- //#endregion
601
- //#region src/lint/addons.ts
602
- /** Hook other Nuxt modules use to extend Vize's generated lint config. */
603
- const VIZE_NUXT_LINT_CONFIG_ADDONS_HOOK = "vize:lint:config:addons";
604
- function autoImportEnabled(imports) {
605
- if (imports === false) return false;
606
- return imports?.autoImport !== false;
788
+ function explicitOxlintOverrides(value, configDir) {
789
+ if (!value || typeof value !== "object" || !configDir) return [];
790
+ const overrides = "overrides" in value ? value.overrides : void 0;
791
+ if (!Array.isArray(overrides)) return [];
792
+ return overrides.flatMap((candidate) => {
793
+ if (!candidate || typeof candidate !== "object") return [];
794
+ const raw = candidate;
795
+ const files = Array.isArray(raw.files) ? raw.files.flatMap((glob) => {
796
+ if (typeof glob !== "string" || !glob) return [];
797
+ const negated = glob.startsWith("!");
798
+ const resolved = path$1.resolve(configDir, negated ? glob.slice(1) : glob);
799
+ return [negated ? `!${resolved}` : resolved];
800
+ }) : [];
801
+ const rules = oxlintRules(raw.rules);
802
+ return files.length > 0 && Object.keys(rules).length > 0 ? [{
803
+ files,
804
+ rules
805
+ }] : [];
806
+ });
607
807
  }
608
- function asImportContext(value) {
609
- if (value == null || typeof value !== "object" || !("getImports" in value)) return;
610
- return typeof value.getImports === "function" ? value : void 0;
808
+ function explicitOxlintJsPlugins(value, configDir) {
809
+ if (!value || typeof value !== "object") return [];
810
+ const jsPlugins = "jsPlugins" in value ? value.jsPlugins : void 0;
811
+ if (!Array.isArray(jsPlugins)) return [];
812
+ const seen = /* @__PURE__ */ new Set();
813
+ const result = [];
814
+ for (const specifier of jsPlugins) {
815
+ if (typeof specifier !== "string" || specifier.length === 0 || specifier === VIZE_JS_PLUGIN_SPECIFIER) continue;
816
+ const resolved = configDir && (specifier.startsWith("./") || specifier.startsWith("../")) ? path$1.resolve(configDir, specifier) : specifier;
817
+ if (seen.has(resolved)) continue;
818
+ seen.add(resolved);
819
+ result.push(resolved);
820
+ }
821
+ return result;
611
822
  }
612
- function nitroImportContext(value) {
613
- if (value == null || typeof value !== "object" || !("unimport" in value)) return;
614
- return asImportContext(value.unimport);
823
+ async function loadPresetRules(preset, typeAware) {
824
+ const { createVizeRuleConfig } = await import("oxlint-plugin-vize");
825
+ const generated = createVizeRuleConfig({
826
+ includeTypeAware: typeAware,
827
+ preset
828
+ });
829
+ const rules = {};
830
+ for (const [id, severity] of Object.entries(generated)) {
831
+ if (!isSeverity(severity)) continue;
832
+ const bare = id.startsWith("vize/") ? id.slice(5) : id;
833
+ if (bare.length > 0) rules[bare] = severity;
834
+ }
835
+ return rules;
615
836
  }
616
- /**
617
- * Capture Nuxt's client and server auto-import registries as readonly globals.
618
- *
619
- * Nuxt publishes both contexts after modules have begun setting up. Keeping
620
- * their latest values in the addon means every config regeneration observes
621
- * the current registry rather than a module-setup-time snapshot.
622
- */
623
- function toPosix(value) {
624
- return value.split(path.sep).join("/");
837
+ function explicitRules(value) {
838
+ if (!value || typeof value !== "object") return {};
839
+ const rules = {};
840
+ for (const [id, severity] of Object.entries(value)) {
841
+ if (!isSeverity(severity)) continue;
842
+ const bare = id.startsWith("vize/") ? id.slice(5) : id;
843
+ if (bare.length > 0) rules[bare] = severity;
844
+ }
845
+ return rules;
625
846
  }
626
- function nitroImportFiles(nuxt, options) {
627
- const nuxtRoot = path.resolve(nuxt.options?.rootDir ?? options.rootDir ?? ".");
628
- const lintRoot = path.resolve(options.rootDir ?? nuxtRoot);
629
- const directories = /* @__PURE__ */ new Set();
630
- directories.add(path.resolve(nuxtRoot, nuxt.options?.nitro?.srcDir ?? "server"));
631
- for (const layer of nuxt.options?._layers ?? []) if (layer.config?.rootDir) directories.add(path.resolve(layer.config.rootDir, "server"));
632
- return [...directories].map((directory) => `${toPosix(path.relative(lintRoot, directory)) || "."}/**/*.{js,ts,jsx,tsx}`).sort();
847
+ function explicitRuleOptions(value) {
848
+ if (!value || typeof value !== "object") return {};
849
+ const options = {};
850
+ for (const [id, option] of Object.entries(value)) {
851
+ const bare = id.startsWith("vize/") ? id.slice(5) : id;
852
+ if (bare.length > 0) options[bare] = option;
853
+ }
854
+ return options;
633
855
  }
634
- function createNuxtImportGlobalsAddon(nuxt, options) {
635
- let unimport;
636
- let nitroUnimport;
637
- nuxt.hook("imports:context", (context) => {
638
- unimport = asImportContext(context);
639
- });
640
- nuxt.hook("nitro:init", (nitro) => {
641
- nitroUnimport = nitroImportContext(nitro);
642
- });
643
- return {
644
- name: "vize:lint:import-globals",
645
- async getConfigs() {
646
- const appAutoImports = autoImportEnabled(nuxt.options?.imports);
647
- const imports = (appAutoImports ? await unimport?.getImports() ?? [] : []).sort((left, right) => left.from.localeCompare(right.from) || left.name.localeCompare(right.name));
648
- const globals = Object.fromEntries(imports.map((imported) => [imported.as ?? imported.name, "readonly"]));
649
- const nitroImports = (appAutoImports && autoImportEnabled(nuxt.options?.nitro?.imports) ? await nitroUnimport?.getImports() ?? [] : []).sort((left, right) => left.from.localeCompare(right.from) || left.name.localeCompare(right.name));
650
- const nitroGlobals = Object.fromEntries(nitroImports.map((imported) => [imported.as ?? imported.name, "readonly"]));
651
- return [{
652
- name: "nuxt/import-globals",
653
- globals
654
- }, ...Object.keys(nitroGlobals).length > 0 ? [{
655
- name: "nitro/import-globals",
656
- files: nitroImportFiles(nuxt, options),
657
- globals: nitroGlobals
658
- }] : []];
659
- }
660
- };
661
- }
662
- /**
663
- * Register the built-in auto-import addon and return the generation-time
664
- * resolver consumed by the Nuxt lint config writer.
665
- *
666
- * The addon array is rebuilt for every generation. This mirrors Nuxt's addon
667
- * hook without retaining contributions across `builder:generateApp` runs.
668
- * The Vize-namespaced hook carries engine-neutral config items instead of raw
669
- * ESLint source, so contributors remain compatible with the oxlint emitter.
670
- */
671
- function setupNuxtLintConfigAddons(nuxt, options = {}) {
672
- const defaults = [createNuxtImportGlobalsAddon(nuxt, options)];
673
- return async () => {
674
- const addons = [...defaults];
675
- await nuxt.callHook(VIZE_NUXT_LINT_CONFIG_ADDONS_HOOK, addons);
676
- const configs = [];
677
- for (const addon of addons) {
678
- const contributed = await addon.getConfigs();
679
- if (contributed) configs.push(...contributed);
680
- }
681
- return configs;
682
- };
683
- }
684
- //#endregion
685
- //#region src/lint/emitter.ts
686
- /**
687
- * Oxlint artifact emission for the engine-neutral Nuxt lint plan.
688
- *
689
- * The plan deliberately keeps eslint-compatible Patina rule ids. Oxlint loads
690
- * Patina as the `vize` JavaScript plugin, so this boundary is the one place
691
- * those ids gain their `vize/` prefix.
692
- */
693
- const PATINA_RULE_NAMESPACES = new Set([
694
- "a11y",
695
- "css",
696
- "ecosystem",
697
- "html",
698
- "musea",
699
- "nuxt",
700
- "petite-vue",
701
- "script",
702
- "ssr",
703
- "type",
704
- "vapor",
705
- "vize",
706
- "vue"
707
- ]);
708
- function toOxlintRuleId(ruleId) {
709
- const separator = ruleId.indexOf("/");
710
- const namespace = separator < 0 ? ruleId : ruleId.slice(0, separator);
711
- return PATINA_RULE_NAMESPACES.has(namespace) ? `vize/${ruleId}` : ruleId;
712
- }
713
- function prefixVizeRules(rules) {
714
- if (!rules) return void 0;
715
- return Object.fromEntries(Object.entries(rules).map(([ruleId, severity]) => [toOxlintRuleId(ruleId), severity]));
716
- }
717
- function mergeGlobals(target, source) {
718
- if (!source) return;
719
- for (const [name, access] of Object.entries(source)) Object.defineProperty(target, name, {
720
- configurable: true,
721
- enumerable: true,
722
- value: access,
723
- writable: true
724
- });
725
- }
726
- function mergeRules(target, source) {
727
- Object.assign(target, prefixVizeRules(source));
728
- }
729
- /** Render the complete generated oxlint config, including its trailing newline. */
730
- function renderNuxtOxlintConfig(items, pluginSpecifier, globBase, projectJsPlugins = []) {
731
- if (globBase) {
732
- const root = path.relative(globBase.configDir, globBase.rootDir);
733
- if (root === ".." || root.startsWith(`..${path.sep}`) || path.isAbsolute(root)) throw new Error("Generated oxlint config must be in the lint root or an ancestor directory");
734
- }
735
- const rebase = (glob, ignore = false) => globBase ? rebaseGlob(glob, globBase, ignore) : glob;
736
- const ignorePatterns = [];
737
- const globals = {};
738
- const rules = {};
739
- const overrides = [];
740
- for (const item of items) {
741
- if (item.files) {
742
- const override = { files: item.files.map((glob) => rebase(glob)) };
743
- if (item.ignores) override.excludeFiles = item.ignores.map((glob) => rebase(glob));
744
- if (item.globals) override.globals = { ...item.globals };
745
- if (item.rules || item.nativeRules) override.rules = {
746
- ...prefixVizeRules(item.rules),
747
- ...item.nativeRules
748
- };
749
- overrides.push(override);
856
+ function applyRuleOptions(source, options, warnings, scope, fallback = {}) {
857
+ const rules = { ...source };
858
+ for (const [ruleId, option] of Object.entries(options)) {
859
+ const configured = rules[ruleId] ?? fallback[ruleId];
860
+ const severity = Array.isArray(configured) ? configured[0] : configured;
861
+ if (!isSeverity(severity)) {
862
+ warnings.push(`${scope}.ruleOptions[${JSON.stringify(ruleId)}] has no enabled rule severity to attach to`);
750
863
  continue;
751
864
  }
752
- if (item.ignores) ignorePatterns.push(...item.ignores.map((glob) => rebase(glob, true)));
753
- mergeGlobals(globals, item.globals);
754
- mergeRules(rules, item.rules);
755
- Object.assign(rules, item.nativeRules);
865
+ rules[ruleId] = [severity, option];
756
866
  }
757
- const config = {
758
- plugins: ["vue"],
759
- jsPlugins: [{
760
- name: "vize",
761
- specifier: pluginSpecifier
762
- }, ...projectJsPlugins.map((specifier) => rebaseJsPlugin(specifier, globBase?.configDir))],
763
- settings: { vize: {
764
- preset: "incremental",
765
- ...globBase?.owner ? { generatedBy: globBase.owner } : {}
766
- } }
767
- };
768
- if (ignorePatterns.length > 0) config.ignorePatterns = ignorePatterns;
769
- if (Object.keys(globals).length > 0) config.globals = globals;
770
- if (Object.keys(rules).length > 0) config.rules = rules;
771
- if (overrides.length > 0) config.overrides = overrides;
772
- return `${JSON.stringify(config, null, 2)}\n`;
773
- }
774
- function rebaseJsPlugin(specifier, configDir) {
775
- if (!configDir || !path.isAbsolute(specifier)) return specifier;
776
- const relative = path.relative(configDir, specifier).split(path.sep).join("/");
777
- return relative.startsWith(".") ? relative : `./${relative}`;
867
+ return rules;
778
868
  }
779
- function rebaseGlob(glob, base, ignore) {
780
- const negated = glob.startsWith("!");
781
- const body = negated ? glob.slice(1) : glob;
782
- const target = path.resolve(base.rootDir, body);
783
- let relative = path.relative(base.configDir, target);
784
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
785
- if (ignore) throw new Error(`Oxlint cannot ignore a path outside its config directory: ${glob}`);
786
- relative = target;
787
- }
788
- const pattern = relative.split(path.sep).join("/") || ".";
789
- return negated ? `!${pattern}` : pattern;
869
+ function isConfigPreset(value) {
870
+ return typeof value === "string" && CONFIG_PRESETS.includes(value);
790
871
  }
791
- //#endregion
792
- //#region src/lint/nuxt-state.ts
793
- /**
794
- * Reduce a Nuxt instance to the project state lint config generation needs.
795
- *
796
- * Nuxt 2 has no `_layers`, so the project is treated as a single layer rooted
797
- * at `srcDir` (falling back to `rootDir`). That keeps the Nuxt 2, 3 and 4 paths
798
- * on one code path rather than branching on the detected major version.
799
- */
800
- function toNuxtLintProjectState(options, overrides = {}) {
801
- const rootDir = overrides.rootDir || options.rootDir;
802
- const layers = (options._layers ?? []).map((layer) => layer.config).filter((config) => Boolean(config)).map((config) => ({
803
- ...config,
804
- srcDir: config.srcDir || options.srcDir || options.rootDir
805
- }));
806
- return {
807
- rootDir,
808
- dir: options.dir ?? {},
809
- layers: layers.length > 0 ? layers : [{ srcDir: options.srcDir || options.rootDir }]
810
- };
872
+ function isSeverity(value) {
873
+ return value === "off" || value === "warn" || value === "error";
811
874
  }
812
875
  //#endregion
813
- //#region ../../../crates/vize_carton/src/config/loader/module-runtime.mjs
814
- const configFailureArtifacts = /* @__PURE__ */ new WeakMap();
815
- const configEvaluationTimings = /* @__PURE__ */ new WeakMap();
816
- function beginConfigTiming(rows, phase, boundary) {
817
- const start = rows ? performance.now() : void 0;
818
- let finished = false;
819
- if (boundary) boundary.active = true;
820
- return () => {
821
- if (start !== void 0 && !finished) {
822
- const end = performance.now();
823
- rows.push({
824
- phase,
825
- elapsedMs: end - start,
826
- processId: process.pid
827
- });
828
- if (boundary) {
829
- boundary.active = false;
830
- if (boundary.resolvedAt !== void 0) {
831
- rows.push({
832
- phase: "public_load_until_owned_resolve",
833
- elapsedMs: boundary.resolvedAt - start,
834
- processId: process.pid
835
- });
836
- rows.push({
837
- phase: "public_load_after_owned_resolve",
838
- elapsedMs: end - boundary.resolvedAt,
839
- processId: process.pid
840
- });
841
- }
842
- }
843
- finished = true;
844
- }
845
- };
846
- }
847
- async function beginPublicLoadProfile() {
848
- const started = performance.now();
849
- let session;
850
- const close = () => {
851
- try {
852
- session?.disconnect();
853
- } catch {}
854
- };
876
+ //#region src/lint/owned-config.ts
877
+ /** Keep the module's reserved root file from replacing an authored config. */
878
+ async function writeOwnedNuxtConfig(file, content, writeChanged) {
855
879
  try {
856
- const { Session } = await import("node:inspector/promises");
857
- session = new Session();
858
- session.connect();
859
- await session.post("Profiler.enable");
860
- await session.post("Profiler.start");
861
- const setupMs = performance.now() - started;
862
- return async () => {
863
- const stopping = performance.now();
864
- try {
865
- const { profile } = await session.post("Profiler.stop");
866
- return {
867
- status: "recorded",
868
- setupMs,
869
- stopMs: performance.now() - stopping,
870
- profile
871
- };
872
- } catch (error) {
873
- return {
874
- status: "unavailable",
875
- setupMs,
876
- reason: String(error)
877
- };
878
- } finally {
879
- close();
880
- }
881
- };
880
+ const handle = await open(file, "wx");
881
+ try {
882
+ await handle.writeFile(content, "utf8");
883
+ } finally {
884
+ await handle.close();
885
+ }
886
+ return true;
882
887
  } catch (error) {
883
- close();
884
- return async () => ({
885
- status: "unavailable",
886
- reason: String(error)
887
- });
888
- }
889
- }
890
- function configModuleImportPath(configURL, windows = process.platform === "win32") {
891
- return fileURLToPath(configURL, { windows });
892
- }
893
- async function importConfigModule(configPath, withoutVite) {
894
- return (await importConfigModuleWithDependencies(configPath, nodeModule.registerHooks, withoutVite)).namespace;
895
- }
896
- function failedConfigModuleObservation(error) {
897
- const paths = /* @__PURE__ */ new Set();
898
- let complete = false;
899
- if (error?.code === "ERR_MODULE_NOT_FOUND" && typeof error.url === "string") try {
900
- const url = new URL(error.url);
901
- if (url.protocol === "file:") {
902
- paths.add(fileURLToPath(url));
903
- complete = true;
904
- }
905
- } catch {}
906
- const diagnostics = Array.isArray(error?.errors) ? error.errors : [];
907
- if (diagnostics.length) complete = true;
908
- for (const diagnostic of diagnostics) {
909
- let requested = false;
910
- if (diagnostic?.code !== "UNRESOLVED_IMPORT" || typeof diagnostic.id !== "string" || !isAbsolute(diagnostic.id) || typeof diagnostic.exporter !== "string") {
911
- complete = false;
912
- continue;
913
- }
914
- paths.add(diagnostic.id);
915
- const request = diagnostic.exporter;
916
- if (!(isAbsolute(request) || request.startsWith("./") || request.startsWith("../"))) {
917
- complete = false;
918
- continue;
919
- }
920
- if (/[%#?]/.test(request)) {
921
- complete = false;
922
- continue;
923
- }
924
- try {
925
- const url = isAbsolute(request) ? pathToFileURL(request) : new URL(request, pathToFileURL(diagnostic.id));
926
- if (url.protocol === "file:" && extname(url.pathname)) {
927
- paths.add(fileURLToPath(url));
928
- requested = true;
929
- }
930
- } catch {}
931
- complete &&= requested;
888
+ if (error.code !== "EEXIST") throw error;
932
889
  }
933
- return {
934
- paths: [...paths],
935
- complete
936
- };
937
- }
938
- /** Keep runtime imports observable until the optional export evaluator settles. */
939
- async function captureConfigEvaluation(load, configPath, registerModuleHooks, evaluate, privateDirectory, observeDependencies, ownedAdapter, timings, boundary) {
940
- const files = new Set([configPath]);
941
- const requestedFiles = /* @__PURE__ */ new Set();
942
- let complete = true;
943
- let moduleGraphLoaded = false;
944
- const owners = new Set([pathToFileURL(configPath).href]);
945
- const isPrivate = (path) => {
946
- if (!privateDirectory) return false;
947
- const inside = relative(privateDirectory, path);
948
- return inside !== ".." && !inside.startsWith(`..${sep}`) && !isAbsolute(inside);
949
- };
950
- const hooks = typeof registerModuleHooks === "function" ? registerModuleHooks({ resolve(specifier, context, nextResolve) {
951
- const result = nextResolve(specifier, context);
952
- if (result.url.startsWith("file:")) {
953
- const path = fileURLToPath(result.url);
954
- if (boundary?.active && boundary.resolvedAt === void 0 && isPrivate(path)) boundary.resolvedAt = performance.now();
955
- if (owners.has(result.url) || owners.has(context.parentURL) || isPrivate(path)) {
956
- owners.add(result.url);
957
- if (!isPrivate(path)) files.add(path);
958
- if (owners.has(context.parentURL) && (specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/") || specifier.startsWith("file:"))) try {
959
- const requested = new URL(specifier, context.parentURL);
960
- if (requested.protocol === "file:") {
961
- const requestedPath = fileURLToPath(requested);
962
- if (extname(requestedPath) && !isPrivate(requestedPath)) requestedFiles.add(requestedPath);
963
- }
964
- } catch {}
965
- }
966
- }
967
- return result;
968
- } }) : void 0;
890
+ const metadata = await lstat(file);
891
+ if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error(`Generated oxlint config must be a regular file: ${file}`);
892
+ let owner;
969
893
  try {
970
- const { namespace, dependencies = [] } = await load();
971
- for (const path of dependencies) if (!isPrivate(path)) files.add(path);
972
- moduleGraphLoaded = true;
973
- const finish = beginConfigTiming(timings, "export_evaluation");
974
- let value;
975
- try {
976
- value = evaluate ? await evaluate(namespace) : namespace;
977
- } finally {
978
- finish();
979
- }
980
- return {
981
- namespace,
982
- value,
983
- dependencies: [...files]
984
- };
985
- } catch (error) {
986
- if (ownedAdapter && error !== null && (typeof error === "object" || typeof error === "function")) configFailureArtifacts.set(error, [
987
- [ownedAdapter, configPath],
988
- [pathToFileURL(ownedAdapter).href, pathToFileURL(configPath).href],
989
- [relative(dirname(configPath), ownedAdapter), relative(dirname(configPath), configPath)]
990
- ]);
991
- complete = false;
992
- try {
993
- const observed = failedConfigModuleObservation(error);
994
- complete = observed.complete && (privateDirectory === void 0 || moduleGraphLoaded);
995
- for (const path of observed.paths) if (!isPrivate(path)) files.add(path);
996
- } catch {}
997
- throw error;
998
- } finally {
999
- hooks?.deregister();
1000
- observeDependencies?.([...files, ...requestedFiles], complete);
1001
- }
894
+ owner = JSON.parse(await readFile(file, "utf8"))?.settings?.vize?.generatedBy;
895
+ } catch {}
896
+ if (owner !== "@vizejs/nuxt") throw new Error(`Refusing to replace authored ${file}; choose a different lint.configFile`);
897
+ return writeChanged(file, content);
1002
898
  }
1003
- /** Await evaluate(namespace) once before sealing its graph; retain the namespace unchanged. */
1004
- async function importConfigModuleWithDependencies(configPath, registerModuleHooks = nodeModule.registerHooks, withoutVite, evaluate, observeDependencies, beforeRead) {
1005
- const timings = process.env.VIZE_TRACE_EDITOR_PREPARATION === "1" ? [] : void 0;
1006
- const boundary = timings ? {
1007
- active: false,
1008
- resolvedAt: void 0
1009
- } : void 0;
1010
- const finishTotal = beginConfigTiming(timings, "module_total");
1011
- const finishSelection = beginConfigTiming(timings, "engine_selection_with_ack");
1012
- let selectionFinished = false;
1013
- let result;
1014
- const watchInputs = new Set([configPath]);
1015
- let complete = false;
1016
- const observe = (paths, observedComplete) => {
1017
- for (const path of paths) watchInputs.add(path);
1018
- complete = observedComplete;
1019
- };
1020
- try {
1021
- const configURL = pathToFileURL(configPath);
1022
- const require = createRequire(configURL);
1023
- const engineNames = ["vite", "vite-plus"];
1024
- let candidate;
1025
- for (const engineName of engineNames) {
1026
- const searchPaths = require.resolve.paths(engineName) ?? [];
1027
- for (const directory of searchPaths.filter((path) => !globalPaths.includes(path))) {
1028
- const requested = join(directory, engineName);
1029
- watchInputs.add(requested);
1030
- await beforeRead?.([requested]);
1031
- if (lstatSync(requested, { throwIfNoEntry: false }) !== void 0) {
1032
- candidate = {
1033
- engineName,
1034
- directory: requested
1035
- };
1036
- watchInputs.add(join(candidate.directory, "package.json"));
1037
- break;
1038
- }
1039
- }
1040
- if (candidate !== void 0) break;
1041
- }
1042
- if (typeof registerModuleHooks !== "function") {
1043
- if (evaluate) throw new Error("Tracking imports while evaluating a Vite config requires Node.js 22.15 or newer. Upgrade Node.js; an installed config bundler alone cannot track runtime imports.");
1044
- if (candidate === void 0 && !withoutVite) throw new Error("Loading a Vite config without project Vite or Vite+ requires Node.js 22.15 or newer to track imported configuration files. Upgrade Node.js or install Vite or Vite+ in the project.");
1045
- }
1046
- if (candidate === void 0) {
1047
- finishSelection();
1048
- selectionFinished = true;
1049
- await beforeRead?.([configPath]);
1050
- result = await captureConfigEvaluation(async () => ({ namespace: await (withoutVite ? withoutVite(configURL) : import(configURL.href)) }), configPath, registerModuleHooks, evaluate, void 0, observe, void 0, timings);
1051
- return result;
1052
- }
1053
- const engineDirectory = realpathSync(candidate.directory);
1054
- watchInputs.add(join(engineDirectory, "package.json"));
1055
- await beforeRead?.([join(candidate.directory, "package.json"), join(engineDirectory, "package.json")]);
1056
- const resolvedEntry = require.resolve(candidate.engineName);
1057
- watchInputs.add(resolvedEntry);
1058
- const engineEntry = realpathSync(resolvedEntry);
1059
- watchInputs.add(engineEntry);
1060
- const entryPath = relative(engineDirectory, engineEntry);
1061
- if (entryPath === ".." || entryPath.startsWith(`..${sep}`) || isAbsolute(entryPath)) {
1062
- const engineLabel = candidate.engineName === "vite" ? "Vite" : "Vite+";
1063
- throw new Error(`Resolved loader escapes selected project ${engineLabel}: ${candidate.directory} -> ${engineEntry}`);
1064
- }
1065
- await beforeRead?.([resolvedEntry, engineEntry]);
1066
- finishSelection();
1067
- selectionFinished = true;
1068
- const finishImport = beginConfigTiming(timings, "engine_import");
1069
- let loadConfigFromFile;
1070
- try {
1071
- const engine = await import(pathToFileURL(engineEntry).href);
1072
- loadConfigFromFile = engine.loadConfigFromFile ?? engine.default?.loadConfigFromFile;
1073
- if (typeof loadConfigFromFile !== "function") throw new Error(`${candidate.engineName} does not export loadConfigFromFile`);
1074
- } finally {
1075
- finishImport();
1076
- }
1077
- const finishAdapter = beginConfigTiming(timings, "adapter_prepare");
1078
- let temporary;
899
+ //#endregion
900
+ //#region src/lint/inspector-view.ts
901
+ /** Render the dependency-free UI served by the in-process lint-plan inspector. */
902
+ function renderNuxtLintInspectorHtml(nonce) {
903
+ return `<!doctype html>
904
+ <html lang="en">
905
+ <head>
906
+ <meta charset="utf-8">
907
+ <meta name="viewport" content="width=device-width,initial-scale=1">
908
+ <title>Vize Nuxt Lint Plan</title>
909
+ <style nonce="${nonce}">
910
+ :root { color-scheme: light dark; font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; }
911
+ * { box-sizing: border-box; }
912
+ body { margin: 0; background: #0d1117; color: #e6edf3; }
913
+ header { position: sticky; top: 0; z-index: 1; padding: 16px 20px; background: #161b22; border-bottom: 1px solid #30363d; }
914
+ h1 { margin: 0 0 12px; font-size: 18px; }
915
+ h2 { margin: 24px 0 10px; font-size: 16px; }
916
+ form { display: flex; gap: 8px; flex-wrap: wrap; }
917
+ input { flex: 1 1 320px; min-width: 180px; padding: 8px 10px; color: inherit; background: #0d1117; border: 1px solid #484f58; border-radius: 6px; }
918
+ button { padding: 8px 12px; color: #fff; background: #238636; border: 0; border-radius: 6px; cursor: pointer; }
919
+ button.secondary { background: #30363d; }
920
+ button:disabled { opacity: .6; cursor: wait; }
921
+ main { max-width: 1100px; margin: 0 auto; padding: 0 20px 32px; }
922
+ #status { min-height: 22px; margin-top: 8px; color: #8c959f; }
923
+ #status.error { color: #ff7b72; }
924
+ .card { margin: 8px 0; padding: 12px; background: #161b22; border: 1px solid #30363d; border-radius: 8px; }
925
+ .meta { color: #8c959f; overflow-wrap: anywhere; }
926
+ .badge { display: inline-block; margin: 2px 4px 2px 0; padding: 1px 6px; border-radius: 10px; background: #30363d; }
927
+ .severity-error { color: #ff7b72; } .severity-warn { color: #d29922; } .severity-off { color: #8c959f; }
928
+ table { width: 100%; border-collapse: collapse; }
929
+ th, td { padding: 7px 8px; text-align: left; border-bottom: 1px solid #30363d; overflow-wrap: anywhere; }
930
+ th { color: #8c959f; font-weight: 600; }
931
+ code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
932
+ </style>
933
+ </head>
934
+ <body>
935
+ <header>
936
+ <h1>Vize Nuxt Lint Plan</h1>
937
+ <form id="inspect-form">
938
+ <input id="file" name="file" autocomplete="off" placeholder="app/pages/index.vue" aria-label="Project-relative file">
939
+ <button type="submit">Inspect file</button>
940
+ <button id="refresh" class="secondary" type="button">Refresh plan</button>
941
+ </form>
942
+ <div id="status" role="status" aria-live="polite"></div>
943
+ </header>
944
+ <main>
945
+ <section><h2>Effective rules</h2><div id="effective"></div></section>
946
+ <section><h2>Ordered config items</h2><div id="items"></div></section>
947
+ </main>
948
+ <script nonce="${nonce}">
949
+ const fileInput = document.getElementById("file");
950
+ const form = document.getElementById("inspect-form");
951
+ const refresh = document.getElementById("refresh");
952
+ const status = document.getElementById("status");
953
+ const effective = document.getElementById("effective");
954
+ const items = document.getElementById("items");
955
+ const buttons = Array.from(document.querySelectorAll("button"));
956
+
957
+ function node(tag, text, className) {
958
+ const value = document.createElement(tag);
959
+ if (text !== undefined) value.textContent = String(text);
960
+ if (className) value.className = className;
961
+ return value;
962
+ }
963
+
964
+ function badges(values) {
965
+ const wrapper = node("div");
966
+ for (const value of values || []) wrapper.append(node("span", value, "badge"));
967
+ return wrapper;
968
+ }
969
+
970
+ function renderItems(payload) {
971
+ items.replaceChildren();
972
+ for (const item of payload.items || []) {
973
+ const card = node("article", undefined, "card");
974
+ card.append(node("strong", item.name || "unnamed"));
975
+ if (item.globalIgnore) card.append(node("span", " global ignore", "meta"));
976
+ if (item.basePath) card.append(node("div", "base: " + item.basePath, "meta"));
977
+ if (item.files) card.append(node("div", "files", "meta"), badges(item.files));
978
+ if (item.ignores && item.ignores.length) card.append(node("div", "ignores", "meta"), badges(item.ignores));
979
+ const rules = Object.entries(item.rules || {});
980
+ if (rules.length) card.append(badges(rules.map(([name, severity]) => name + ": " + severity)));
981
+ items.append(card);
982
+ }
983
+ }
984
+
985
+ function renderEffective(payload) {
986
+ effective.replaceChildren();
987
+ const file = payload.files && payload.files[0];
988
+ if (!file) {
989
+ effective.append(node("p", "Enter a project-relative file to explain its effective rules.", "meta"));
990
+ return;
991
+ }
992
+ const summary = node("div", undefined, "card");
993
+ summary.append(node("strong", file.path));
994
+ if (file.ignored) summary.append(node("div", "Ignored by: " + (file.ignoredBy || []).join(", "), "severity-warn"));
995
+ else summary.append(node("div", "Matched: " + (file.matchedItems || []).join(" → "), "meta"));
996
+ effective.append(summary);
997
+ if (!file.rules || !file.rules.length) return;
998
+ const table = node("table");
999
+ const head = node("tr");
1000
+ for (const label of ["Rule", "Severity", "Set by"]) head.append(node("th", label));
1001
+ const thead = node("thead"); thead.append(head); table.append(thead);
1002
+ const tbody = node("tbody");
1003
+ for (const rule of file.rules) {
1004
+ const row = node("tr");
1005
+ row.append(node("td", rule.name), node("td", rule.severity, "severity-" + rule.severity), node("td", rule.setBy));
1006
+ tbody.append(row);
1007
+ }
1008
+ table.append(tbody); effective.append(table);
1009
+ }
1010
+
1011
+ async function load(fresh) {
1012
+ const url = new URL("api", location.href);
1013
+ const file = fileInput.value.trim();
1014
+ if (file) url.searchParams.set("file", file);
1015
+ if (fresh) url.searchParams.set("fresh", "1");
1016
+ buttons.forEach(button => { button.disabled = true; });
1017
+ status.className = ""; status.textContent = fresh ? "Refreshing…" : "Loading…";
1018
+ try {
1019
+ const response = await fetch(url, { headers: { accept: "application/json" } });
1020
+ const payload = await response.json();
1021
+ if (!response.ok) throw new Error(payload.error || "Inspector request failed");
1022
+ renderEffective(payload); renderItems(payload);
1023
+ status.textContent = "Resolved " + (payload.items || []).length + " config items";
1024
+ } catch (error) {
1025
+ status.className = "error";
1026
+ status.textContent = error instanceof Error ? error.message : String(error);
1027
+ } finally {
1028
+ buttons.forEach(button => { button.disabled = false; });
1029
+ }
1030
+ }
1031
+
1032
+ form.addEventListener("submit", event => { event.preventDefault(); void load(false); });
1033
+ refresh.addEventListener("click", () => { void load(true); });
1034
+ void load(false);
1035
+ <\/script>
1036
+ </body>
1037
+ </html>`;
1038
+ }
1039
+ //#endregion
1040
+ //#region src/lint/inspector-devtools.ts
1041
+ const MAX_URL_BYTES = 8 * 1024;
1042
+ const MAX_FILES = 128;
1043
+ const MAX_FILE_BYTES = 4 * 1024;
1044
+ const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
1045
+ function resolveNuxtLintDevtoolsOptions(options) {
1046
+ const enabled = options?.enabled ?? "lazy";
1047
+ const port = options?.port;
1048
+ if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new RangeError("Nuxt lint inspector port must be an integer from 1 to 65535");
1049
+ return {
1050
+ enabled,
1051
+ port
1052
+ };
1053
+ }
1054
+ async function setupNuxtLintDevtools(options, nuxt, provider) {
1055
+ const resolved = resolveNuxtLintDevtoolsOptions(options);
1056
+ if (resolved.enabled === false) return void 0;
1057
+ const controller = createController(resolved.port, provider, nuxt);
1058
+ nuxt.hook("devtools:customTabs", (...args) => {
1059
+ args[0].push(controller.tab());
1060
+ });
1061
+ nuxt.hook("close", () => controller.close());
1062
+ if (resolved.enabled === true) try {
1063
+ await controller.start();
1064
+ } catch (error) {
1065
+ console.warn(`[vize] Nuxt lint inspector failed to start: ${error instanceof Error ? error.message : String(error)}`);
1066
+ }
1067
+ return controller;
1068
+ }
1069
+ function createController(requestedPort, provider, nuxt) {
1070
+ const token = randomBytes(18).toString("base64url");
1071
+ const nonce = randomBytes(18).toString("base64url");
1072
+ const server = createServer((request, response) => {
1073
+ handleRequest(request, response, provider, token, nonce, server);
1074
+ });
1075
+ let closed = false;
1076
+ let startPromise;
1077
+ let viewerUrl;
1078
+ const start = async () => {
1079
+ if (closed) throw new Error("Nuxt lint inspector is closed");
1080
+ if (viewerUrl) return;
1081
+ startPromise ||= listen(server, requestedPort).then(async (port) => {
1082
+ viewerUrl = `http://127.0.0.1:${port}/${token}/`;
1083
+ await nuxt.callHook?.("devtools:customTabs:refresh");
1084
+ });
1079
1085
  try {
1080
- temporary = await realpath(await mkdtemp(join(tmpdir(), "vize-config-module-")));
1086
+ await startPromise;
1081
1087
  } catch (error) {
1082
- finishAdapter();
1088
+ startPromise = void 0;
1083
1089
  throw error;
1084
1090
  }
1085
- try {
1086
- const adapter = join(temporary, "config.mjs");
1087
- await writeFile(adapter, `import * as original from ${JSON.stringify(configModuleImportPath(configURL))};\nexport default { namespace: original };\n`, {
1088
- flag: "wx",
1089
- mode: 384
1091
+ };
1092
+ return {
1093
+ async close() {
1094
+ closed = true;
1095
+ try {
1096
+ await startPromise;
1097
+ } catch {}
1098
+ if (!server.listening) return;
1099
+ await new Promise((resolve, reject) => {
1100
+ server.close((error) => error ? reject(error) : resolve());
1101
+ server.closeAllConnections();
1090
1102
  });
1091
- finishAdapter();
1092
- result = await captureConfigEvaluation(async () => {
1093
- const finishAck = beginConfigTiming(timings, "selected_before_read_ack");
1094
- try {
1095
- await beforeRead?.([configPath]);
1096
- } finally {
1097
- finishAck();
1098
- }
1099
- const finishProfile = timings ? await beginPublicLoadProfile() : void 0;
1100
- const finishLoad = beginConfigTiming(timings, "public_load", boundary);
1101
- let loaded;
1102
- try {
1103
- loaded = await loadConfigFromFile({
1104
- mode: "development",
1105
- command: "serve"
1106
- }, adapter, dirname(configPath), "silent", void 0, "bundle");
1107
- } finally {
1108
- finishLoad();
1109
- if (finishProfile) timings.find((row) => row.phase === "public_load").cpuProfile = await finishProfile();
1103
+ viewerUrl = void 0;
1104
+ startPromise = void 0;
1105
+ },
1106
+ start,
1107
+ tab() {
1108
+ return {
1109
+ name: "vize-nuxt-lint-plan",
1110
+ title: "Vize Nuxt Lint Plan",
1111
+ icon: "carbon:rule",
1112
+ requireAuth: true,
1113
+ view: viewerUrl ? {
1114
+ type: "iframe",
1115
+ src: viewerUrl,
1116
+ persistent: true
1117
+ } : {
1118
+ type: "launch",
1119
+ description: "Inspect the effective Vize lint rules for any Nuxt source file.",
1120
+ actions: [{
1121
+ label: "Launch",
1122
+ pending: startPromise !== void 0,
1123
+ handle: start
1124
+ }]
1110
1125
  }
1111
- if (!loaded) throw new Error(`${candidate.engineName} did not load the selected config: ${configPath}`);
1112
- return {
1113
- namespace: loaded.config.namespace,
1114
- dependencies: loaded.dependencies
1115
- };
1116
- }, configPath, registerModuleHooks, evaluate, temporary, observe, adapter, timings, boundary);
1117
- return result;
1118
- } catch (error) {
1119
- finishAdapter();
1120
- throw error;
1121
- } finally {
1122
- const finishCleanup = beginConfigTiming(timings, "adapter_cleanup");
1123
- try {
1124
- await rm(temporary, {
1125
- recursive: true,
1126
- force: true
1127
- });
1128
- } finally {
1129
- finishCleanup();
1130
- }
1131
- }
1132
- } catch (error) {
1133
- if (timings && error !== null && (typeof error === "object" || typeof error === "function")) configEvaluationTimings.set(error, timings);
1134
- throw error;
1135
- } finally {
1136
- if (!selectionFinished) finishSelection();
1137
- finishTotal();
1138
- if (timings && result) configEvaluationTimings.set(result, timings);
1139
- observeDependencies?.([...watchInputs], complete);
1126
+ };
1127
+ },
1128
+ url: () => viewerUrl
1129
+ };
1130
+ }
1131
+ function listen(server, port) {
1132
+ return new Promise((resolve, reject) => {
1133
+ const onError = (error) => {
1134
+ server.off("listening", onListening);
1135
+ reject(error);
1136
+ };
1137
+ const onListening = () => {
1138
+ server.off("error", onError);
1139
+ resolve(server.address().port);
1140
+ };
1141
+ server.once("error", onError);
1142
+ server.once("listening", onListening);
1143
+ server.listen({
1144
+ host: "127.0.0.1",
1145
+ port: port ?? 0,
1146
+ exclusive: true
1147
+ });
1148
+ });
1149
+ }
1150
+ async function handleRequest(request, response, provider, token, nonce, server) {
1151
+ if (Buffer.byteLength(request.url ?? "") > MAX_URL_BYTES) {
1152
+ sendJson(response, 414, { error: "request_uri_too_long" });
1153
+ return;
1154
+ }
1155
+ const port = server.address()?.port;
1156
+ if (!port || ![`127.0.0.1:${port}`, `localhost:${port}`].includes(request.headers.host ?? "")) {
1157
+ sendJson(response, 421, { error: "misdirected_request" });
1158
+ return;
1159
+ }
1160
+ if (request.method !== "GET" && request.method !== "HEAD") {
1161
+ response.setHeader("allow", "GET, HEAD");
1162
+ sendJson(response, 405, { error: "method_not_allowed" });
1163
+ return;
1164
+ }
1165
+ let url;
1166
+ try {
1167
+ url = new URL(request.url ?? "", "http://localhost");
1168
+ } catch {
1169
+ sendJson(response, 400, { error: "invalid_url" }, request.method === "HEAD");
1170
+ return;
1171
+ }
1172
+ const rootPath = `/${token}/`;
1173
+ if (url.pathname === rootPath && url.search === "") {
1174
+ sendHtml(response, renderNuxtLintInspectorHtml(nonce), nonce, request.method === "HEAD");
1175
+ return;
1176
+ }
1177
+ if (url.pathname !== `${rootPath}api`) {
1178
+ sendJson(response, 404, { error: "not_found" }, request.method === "HEAD");
1179
+ return;
1180
+ }
1181
+ const parsed = parseApiRequest(url);
1182
+ if ("error" in parsed) {
1183
+ sendJson(response, parsed.status, { error: parsed.error }, request.method === "HEAD");
1184
+ return;
1185
+ }
1186
+ try {
1187
+ sendJson(response, 200, await provider(parsed.request), request.method === "HEAD");
1188
+ } catch {
1189
+ sendJson(response, 500, { error: "inspector_lint_plan_failed" }, request.method === "HEAD");
1190
+ }
1191
+ }
1192
+ function parseApiRequest(url) {
1193
+ for (const key of url.searchParams.keys()) if (key !== "file" && key !== "fresh") return {
1194
+ status: 400,
1195
+ error: "invalid_query"
1196
+ };
1197
+ const fresh = url.searchParams.getAll("fresh");
1198
+ if (fresh.length > 1 || fresh[0] !== void 0 && fresh[0] !== "1") return {
1199
+ status: 400,
1200
+ error: "invalid_fresh"
1201
+ };
1202
+ const requested = url.searchParams.getAll("file");
1203
+ if (requested.length > MAX_FILES) return {
1204
+ status: 413,
1205
+ error: "too_many_files"
1206
+ };
1207
+ const files = [...new Set(requested)];
1208
+ if (files.some((file) => !isSafeFile(file))) return {
1209
+ status: 400,
1210
+ error: "invalid_file"
1211
+ };
1212
+ return { request: {
1213
+ files,
1214
+ fresh: fresh[0] === "1"
1215
+ } };
1216
+ }
1217
+ function isSafeFile(file) {
1218
+ return file.length > 0 && Buffer.byteLength(file) <= MAX_FILE_BYTES && !file.includes("\0") && !file.includes("\\") && !file.startsWith("/") && !/^[A-Za-z]:/u.test(file) && !file.split("/").some((part) => part.length === 0 || part === "..");
1219
+ }
1220
+ function setCommonHeaders(response, resourcePolicy) {
1221
+ response.setHeader("cache-control", "no-store");
1222
+ response.setHeader("cross-origin-resource-policy", resourcePolicy);
1223
+ response.setHeader("referrer-policy", "no-referrer");
1224
+ response.setHeader("x-content-type-options", "nosniff");
1225
+ }
1226
+ function sendHtml(response, body, nonce, headOnly) {
1227
+ response.statusCode = 200;
1228
+ setCommonHeaders(response, "cross-origin");
1229
+ response.setHeader("content-security-policy", `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; frame-ancestors http://localhost:* http://127.0.0.1:*`);
1230
+ response.setHeader("content-type", "text/html; charset=utf-8");
1231
+ response.setHeader("content-length", Buffer.byteLength(body));
1232
+ response.end(headOnly ? void 0 : body);
1233
+ }
1234
+ function sendJson(response, status, payload, headOnly = false) {
1235
+ let body = JSON.stringify(payload);
1236
+ if (body === void 0) {
1237
+ status = 500;
1238
+ body = JSON.stringify({ error: "inspector_lint_plan_failed" });
1239
+ }
1240
+ if (Buffer.byteLength(body) > MAX_RESPONSE_BYTES) {
1241
+ status = 413;
1242
+ body = JSON.stringify({ error: "inspector_response_too_large" });
1140
1243
  }
1244
+ response.statusCode = status;
1245
+ setCommonHeaders(response, "same-origin");
1246
+ response.setHeader("content-security-policy", "default-src 'none'");
1247
+ response.setHeader("content-type", "application/json; charset=utf-8");
1248
+ response.setHeader("content-length", Buffer.byteLength(body));
1249
+ response.end(headOnly ? void 0 : body);
1141
1250
  }
1142
- JSON.parse("{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"compiler\":{\"$ref\":\"#/definitions/CompilerConfig\"},\"experimentals\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"boolean\"},{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]}},\"dialect\":{\"type\":\"string\",\"enum\":[\"vue\",\"petite-vue\"]},\"vite\":{\"$ref\":\"#/definitions/VitePluginConfig\"},\"musea\":{\"$ref\":\"#/definitions/MuseaConfig\"},\"typeChecker\":{\"$ref\":\"#/definitions/TypeCheckerConfig\"},\"linter\":{\"$ref\":\"#/definitions/LinterConfig\"},\"formatter\":{\"$ref\":\"#/definitions/FormatterConfig\"},\"languageServer\":{\"$ref\":\"#/definitions/LanguageServerConfig\"},\"globalTypes\":{\"$ref\":\"#/definitions/GlobalTypesConfig\"},\"files\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ignores\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"basePath\":{\"type\":\"string\"},\"lib\":{\"$ref\":\"#/definitions/LibConfig\"},\"compile\":{\"$ref\":\"#/definitions/CompilerConfig\"},\"typeCheck\":{\"$ref\":\"#/definitions/TypeCheckerConfig\"},\"fmt\":{\"$ref\":\"#/definitions/FormatterConfig\"},\"lint\":{\"type\":\"object\",\"required\":[\"jsPlugins\",\"plugins\",\"rules\",\"settings\"],\"properties\":{\"jsPlugins\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"plugins\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"rules\":{\"type\":\"object\",\"additionalProperties\":true},\"settings\":{\"type\":\"object\",\"additionalProperties\":true},\"ignorePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"overrides\":{\"type\":\"array\"}},\"additionalProperties\":true},\"version\":{\"$ref\":\"#/definitions/VueVersion\"},\"entries\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"basePath\":{\"type\":\"string\"},\"files\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ignores\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"compiler\":{\"$ref\":\"#/definitions/CompilerConfig\"},\"linter\":{\"$ref\":\"#/definitions/LinterConfig\"}},\"additionalProperties\":false}}},\"additionalProperties\":false,\"definitions\":{\"CompilerConfig\":{\"type\":\"object\",\"properties\":{\"mode\":{\"type\":\"string\",\"enum\":[\"module\",\"function\"]},\"vapor\":{\"type\":\"boolean\"},\"jsxMode\":{\"type\":\"string\",\"enum\":[\"vdom\",\"vapor\"]},\"jsxCompat\":{\"type\":\"string\",\"enum\":[\"native\",\"babel\"]},\"customRenderer\":{\"type\":\"boolean\"},\"customElements\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ssr\":{\"type\":\"boolean\"},\"templateSyntax\":{\"type\":\"string\",\"enum\":[\"standard\",\"strict\",\"quirks\"]},\"whitespace\":{\"type\":\"string\",\"enum\":[\"condense\",\"preserve\",\"vue2-line-breaks\",\"vue2-preserve\"]},\"sourceMap\":{\"type\":\"boolean\"},\"prefixIdentifiers\":{\"type\":\"boolean\"},\"hoistStatic\":{\"type\":\"boolean\"},\"cacheHandlers\":{\"type\":\"boolean\"},\"isTs\":{\"type\":\"boolean\"},\"scriptExt\":{\"type\":\"string\",\"enum\":[\"ts\",\"js\"]},\"runtimeModuleName\":{\"type\":\"string\"},\"runtimeGlobalName\":{\"type\":\"string\"},\"compatibility\":{\"$ref\":\"#/definitions/CompilerCompatibilityConfig\"}},\"additionalProperties\":false},\"CompilerCompatibilityConfig\":{\"type\":\"object\",\"properties\":{\"vueVersion\":{\"$ref\":\"#/definitions/VueVersion\"},\"hostCompiler\":{\"type\":\"boolean\"},\"scriptSetupInStandalone\":{\"type\":\"boolean\"},\"optionsApiVapor\":{\"type\":\"boolean\"},\"nuxtVersion\":{\"type\":\"integer\",\"enum\":[2,3,4]},\"webpackVersion\":{\"type\":\"integer\",\"enum\":[4,5]}},\"additionalProperties\":false},\"VueVersion\":{\"type\":\"string\",\"enum\":[\"3\",\"2.7\",\"2\",\"1\",\"0.11\",\"0.10\"]},\"VitePluginConfig\":{\"type\":\"object\",\"properties\":{\"include\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"exclude\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"scanPatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"ignorePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"MuseaConfig\":{\"type\":\"object\",\"properties\":{\"include\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"exclude\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"basePath\":{\"type\":\"string\"},\"storybookCompat\":{\"type\":\"boolean\"},\"inlineArt\":{\"type\":\"boolean\"},\"vrt\":{\"$ref\":\"#/definitions/MuseaVrtConfig\"},\"a11y\":{\"$ref\":\"#/definitions/MuseaA11yConfig\"},\"autogen\":{\"$ref\":\"#/definitions/MuseaAutogenConfig\"}},\"additionalProperties\":false},\"MuseaVrtConfig\":{\"type\":\"object\",\"properties\":{\"threshold\":{\"type\":\"number\"},\"outDir\":{\"type\":\"string\"},\"viewports\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/MuseaViewport\"}}},\"additionalProperties\":false},\"MuseaViewport\":{\"type\":\"object\",\"properties\":{\"width\":{\"type\":\"integer\"},\"height\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"width\",\"height\"]},\"MuseaA11yConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"rules\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"boolean\"}}},\"additionalProperties\":false},\"MuseaAutogenConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"maxVariants\":{\"type\":\"integer\"}},\"additionalProperties\":false},\"TypeCheckerConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"strict\":{\"type\":\"boolean\"},\"checkProps\":{\"type\":\"boolean\"},\"checkEmits\":{\"type\":\"boolean\"},\"checkTemplateBindings\":{\"type\":\"boolean\"},\"checkReactivity\":{\"type\":\"boolean\"},\"checkSetupContext\":{\"type\":\"boolean\"},\"checkInvalidExports\":{\"type\":\"boolean\"},\"checkFallthroughAttrs\":{\"type\":\"boolean\"},\"optionsApi\":{\"type\":\"boolean\"},\"legacyVue2\":{\"type\":\"boolean\"},\"jsxTypecheck\":{\"type\":\"boolean\"},\"tsconfig\":{\"type\":\"string\"},\"corsaPath\":{\"type\":\"string\"},\"tsgoPath\":{\"type\":\"string\"},\"tsrsPath\":{\"type\":\"string\"},\"globalsFile\":{\"type\":\"string\"},\"servers\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":32},\"lspRequestTimeoutMs\":{\"type\":\"integer\",\"minimum\":1}},\"additionalProperties\":false},\"LinterConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"preset\":{\"type\":\"string\",\"enum\":[\"general-recommended\",\"general_recommended\",\"generalRecommended\",\"happy-path\",\"happy_path\",\"happy\",\"default\",\"recommended\",\"opinionated\",\"strict\",\"all\",\"essential\",\"incremental\",\"ecosystem\",\"nuxt\"]},\"typeAware\":{\"type\":\"boolean\"},\"crossFile\":{\"type\":\"boolean\"},\"crossFileTree\":{\"type\":\"boolean\"},\"crossFileComplexity\":{\"type\":\"boolean\"},\"strictReactivity\":{\"type\":\"boolean\"},\"maxWarnings\":{\"type\":\"integer\",\"minimum\":0},\"rules\":{\"type\":\"object\",\"additionalProperties\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]}},\"ruleOptions\":{\"$ref\":\"#/definitions/LintRuleOptions\"},\"categories\":{\"type\":\"object\",\"properties\":{\"correctness\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"suspicious\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"style\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"perf\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"a11y\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]},\"security\":{\"type\":\"string\",\"enum\":[\"off\",\"warn\",\"error\"]}},\"additionalProperties\":false}},\"additionalProperties\":false},\"LintRuleOptions\":{\"type\":\"object\",\"properties\":{\"script/define-macros-order\":{\"type\":\"object\",\"properties\":{\"order\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"minLength\":1},\"uniqueItems\":true}},\"additionalProperties\":false},\"script/define-props-destructuring\":{\"type\":\"object\",\"properties\":{\"destructure\":{\"type\":\"string\",\"enum\":[\"only-when-assigned\",\"always\",\"never\"]}},\"additionalProperties\":false},\"html/no-empty-palpable-content\":{\"type\":\"object\",\"properties\":{\"contentDirectives\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"type/strict-boolean-expressions\":{\"type\":\"object\",\"properties\":{\"allowString\":{\"type\":\"boolean\"},\"allowNumber\":{\"type\":\"boolean\"},\"allowNullableObject\":{\"type\":\"boolean\"},\"allowNullableBoolean\":{\"type\":\"boolean\"},\"allowNullableString\":{\"type\":\"boolean\"},\"allowNullableNumber\":{\"type\":\"boolean\"},\"allowNullableEnum\":{\"type\":\"boolean\"},\"allowAny\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"script/no-restricted-globals\":{\"$ref\":\"#/definitions/NoRestrictedGlobalsOptions\"},\"script/no-restricted-members\":{\"$ref\":\"#/definitions/NoRestrictedMembersOptions\"},\"vue/component-name-in-template-casing\":{\"type\":\"object\",\"properties\":{\"casing\":{\"type\":\"string\",\"enum\":[\"PascalCase\",\"kebab-case\"]},\"registeredComponentsOnly\":{\"type\":\"boolean\"},\"globals\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"script/custom-event-name-casing\":{\"type\":\"object\",\"properties\":{\"casing\":{\"type\":\"string\",\"enum\":[\"camelCase\",\"kebab-case\"]}},\"additionalProperties\":false},\"vue/no-mutating-props\":{\"type\":\"object\",\"properties\":{\"shallowOnly\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"vue/require-component-registration\":{\"type\":\"object\",\"properties\":{\"globals\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"vue/sfc-element-order\":{\"type\":\"object\",\"properties\":{\"order\":{\"type\":\"array\",\"items\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}}]}}},\"additionalProperties\":false},\"vue/html-self-closing\":{\"type\":\"object\",\"properties\":{\"html\":{\"type\":\"object\",\"properties\":{\"void\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]},\"normal\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]},\"component\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]}},\"additionalProperties\":false},\"svg\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]},\"math\":{\"type\":\"string\",\"enum\":[\"always\",\"never\",\"any\"]}},\"additionalProperties\":false},\"vue/html-quotes\":{\"oneOf\":[{\"type\":\"string\",\"enum\":[\"double\",\"single\"]},{\"type\":\"object\",\"properties\":{\"style\":{\"type\":\"string\",\"enum\":[\"double\",\"single\"]},\"avoidEscape\":{\"type\":\"boolean\"}},\"additionalProperties\":false}]},\"vue/mustache-interpolation-spacing\":{\"type\":\"string\",\"enum\":[\"always\",\"never\"]},\"vue/v-on-event-hyphenation\":{\"type\":\"string\",\"enum\":[\"always\",\"never\"]},\"vue/v-bind-style\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]},\"vue/v-on-style\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]},\"vue/v-slot-style\":{\"oneOf\":[{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]},{\"type\":\"object\",\"properties\":{\"atComponent\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\",\"v-slot\"]},\"default\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\",\"v-slot\"]},\"named\":{\"type\":\"string\",\"enum\":[\"shorthand\",\"longform\"]}},\"additionalProperties\":false}]},\"vue/attribute-hyphenation\":{\"type\":\"string\",\"enum\":[\"always\",\"never\"]},\"vue/valid-v-on\":{\"type\":\"object\",\"properties\":{\"modifiers\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false},\"vue/valid-v-slot\":{\"type\":\"object\",\"properties\":{\"allowModifiers\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"musea/prefer-design-tokens\":{\"$ref\":\"#/definitions/MuseaPreferDesignTokensOptions\"}},\"additionalProperties\":false},\"NoRestrictedGlobalsOptions\":{\"type\":\"object\",\"properties\":{\"globals\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/RestrictedGlobal\"}}},\"additionalProperties\":false},\"RestrictedGlobal\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"name\"]},\"NoRestrictedMembersOptions\":{\"type\":\"object\",\"properties\":{\"members\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/RestrictedMember\"}}},\"additionalProperties\":false},\"RestrictedMember\":{\"type\":\"object\",\"properties\":{\"object\":{\"type\":\"string\"},\"property\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"object\",\"property\"]},\"MuseaPreferDesignTokensOptions\":{\"type\":\"object\",\"properties\":{\"tokens\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/MuseaDesignToken\"}}},\"additionalProperties\":false},\"MuseaDesignToken\":{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\"},\"value\":{\"type\":\"string\"},\"tier\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"path\",\"value\"]},\"FormatterConfig\":{\"type\":\"object\",\"properties\":{\"ignorePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"preset\":{\"type\":\"string\",\"enum\":[\"vize\",\"prettier\",\"compact\",\"documentation\"]},\"sortImports\":{\"oneOf\":[{\"type\":\"boolean\",\"enum\":[false]},{\"$ref\":\"#/definitions/SortImportsConfig\"}]},\"printWidth\":{\"type\":\"integer\"},\"tabWidth\":{\"type\":\"integer\"},\"useTabs\":{\"type\":\"boolean\"},\"semi\":{\"type\":\"boolean\"},\"singleQuote\":{\"type\":\"boolean\"},\"jsxSingleQuote\":{\"type\":\"boolean\"},\"trailingComma\":{\"type\":\"string\",\"enum\":[\"all\",\"none\",\"es5\"]},\"bracketSpacing\":{\"type\":\"boolean\"},\"bracketSameLine\":{\"type\":\"boolean\"},\"arrowParens\":{\"type\":\"string\",\"enum\":[\"always\",\"avoid\"]},\"endOfLine\":{\"type\":\"string\",\"enum\":[\"lf\",\"crlf\",\"cr\",\"auto\"]},\"quoteProps\":{\"type\":\"string\",\"enum\":[\"as-needed\",\"consistent\",\"preserve\"]},\"singleAttributePerLine\":{\"type\":\"boolean\"},\"vueIndentScriptAndStyle\":{\"type\":\"boolean\"},\"sortAttributes\":{\"type\":\"boolean\"},\"attributeSortOrder\":{\"type\":\"string\",\"enum\":[\"alphabetical\",\"as-written\"]},\"mergeBindAndNonBindAttrs\":{\"type\":\"boolean\"},\"maxAttributesPerLine\":{\"type\":\"integer\"},\"attributeGroups\":{\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"normalizeDirectiveShorthands\":{\"type\":\"boolean\"},\"sortBlocks\":{\"type\":\"boolean\"},\"normalizeCssQuotes\":{\"type\":\"boolean\"},\"normalizeInlineStyles\":{\"type\":\"boolean\"},\"normalizeVForParens\":{\"type\":\"boolean\"},\"selfCloseVoidElements\":{\"type\":\"boolean\"},\"reindentPreprocessorStyles\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"SortImportsConfig\":{\"type\":\"object\",\"properties\":{\"partitionByNewline\":{\"type\":\"boolean\"},\"partitionByComment\":{\"type\":\"boolean\"},\"sortSideEffects\":{\"type\":\"boolean\"},\"order\":{\"type\":\"string\",\"enum\":[\"asc\",\"desc\"]},\"ignoreCase\":{\"type\":\"boolean\"},\"newlinesBetween\":{\"type\":\"boolean\"},\"internalPattern\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"groups\":{\"type\":\"array\",\"items\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"array\",\"items\":{\"type\":\"string\"}},{\"type\":\"object\",\"properties\":{\"newlinesBetween\":{\"type\":\"boolean\"}},\"additionalProperties\":false,\"required\":[\"newlinesBetween\"]}]}},\"customGroups\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/ImportSortCustomGroup\"}}},\"additionalProperties\":false},\"ImportSortCustomGroup\":{\"type\":\"object\",\"properties\":{\"groupName\":{\"type\":\"string\"},\"elementNamePattern\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"selector\":{\"type\":\"string\"},\"modifiers\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"additionalProperties\":false,\"required\":[\"groupName\"]},\"LanguageServerConfig\":{\"type\":\"object\",\"properties\":{\"enabled\":{\"type\":\"boolean\"},\"lint\":{\"type\":\"boolean\"},\"diagnostics\":{\"type\":\"boolean\"},\"typecheck\":{\"type\":\"boolean\"},\"editor\":{\"type\":\"boolean\"},\"ecosystem\":{\"type\":\"boolean\"},\"crossFile\":{\"type\":\"boolean\"},\"legacyVue2\":{\"type\":\"boolean\"},\"completion\":{\"type\":\"boolean\"},\"signatureHelp\":{\"type\":\"boolean\"},\"hover\":{\"type\":\"boolean\"},\"definition\":{\"type\":\"boolean\"},\"references\":{\"type\":\"boolean\"},\"documentSymbols\":{\"type\":\"boolean\"},\"workspaceSymbols\":{\"type\":\"boolean\"},\"formatting\":{\"type\":\"boolean\"},\"codeActions\":{\"type\":\"boolean\"},\"rename\":{\"type\":\"boolean\"},\"codeLens\":{\"type\":\"boolean\"},\"semanticTokens\":{\"type\":\"boolean\"},\"documentLinks\":{\"type\":\"boolean\"},\"foldingRanges\":{\"type\":\"boolean\"},\"inlayHints\":{\"type\":\"boolean\"},\"fileRename\":{\"type\":\"boolean\"},\"corsa\":{\"type\":\"boolean\"},\"tsgo\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"GlobalTypesConfig\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"string\"},{\"$ref\":\"#/definitions/GlobalTypeDeclaration\"}]}},\"GlobalTypeDeclaration\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\"},\"defaultValue\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"type\"]},\"LibConfig\":{\"type\":\"object\",\"properties\":{\"dir\":{\"type\":\"string\"},\"uiDir\":{\"type\":\"string\"},\"composableDir\":{\"type\":\"string\"},\"lockfile\":{\"type\":\"string\"},\"registries\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"object\",\"properties\":{\"source\":{\"type\":\"string\"},\"dir\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"source\"]}]},\"propertyNames\":{\"pattern\":\"^@[a-z0-9][a-z0-9._-]*$\"}}},\"additionalProperties\":false}}}");
1143
- const sourceConfigKey = Symbol.for("@vizejs/vite-plugin/vite-plus/source");
1144
- function object(value) {
1145
- if (value === null || typeof value !== "object") return false;
1146
- const prototype = Object.getPrototypeOf(value);
1147
- return prototype === Object.prototype || prototype === null;
1251
+ //#endregion
1252
+ //#region src/lint/inspector.ts
1253
+ function createNuxtLintInspectorProvider(generation, dependencies = {}) {
1254
+ const inspect = dependencies.inspectLintPlan ?? inspectWithNative;
1255
+ return async (request) => {
1256
+ const items = await generation.resolvePlan(request.fresh);
1257
+ const serialized = await inspect(JSON.stringify({ items }), generation.root, request.files);
1258
+ const payload = JSON.parse(serialized);
1259
+ if (!isLintPlanPayload(payload)) throw new Error("Native lint-plan inspector returned an invalid payload");
1260
+ return payload;
1261
+ };
1148
1262
  }
1149
- async function resolveSource(value, env, parents = /* @__PURE__ */ new Set()) {
1150
- value = await value;
1151
- if (parents.has(value)) throw new Error("Circular Vue configuration source");
1152
- parents.add(value);
1153
- try {
1154
- if ((typeof value === "function" || object(value)) && sourceConfigKey in value) return await resolveSource(value[sourceConfigKey], env, parents);
1155
- const config = await (typeof value === "function" ? value(env) : value);
1156
- if (!object(config)) throw new Error("Vite config must export an object or a config function");
1157
- rejectLegacyConfig(config);
1158
- return config;
1159
- } finally {
1160
- parents.delete(value);
1263
+ async function setupLintInspector(lint, nuxt, compiler, generation, enabled) {
1264
+ if (enabled === false || !generation) return;
1265
+ const provider = createNuxtLintInspectorProvider(generation);
1266
+ if (compiler !== false) {
1267
+ compiler.inspector ||= {};
1268
+ compiler.inspector.lintPlan ||= provider;
1161
1269
  }
1270
+ await setupNuxtLintDevtools(typeof lint === "object" && lint !== null ? lint.devtools : void 0, nuxt, compiler === false ? provider : compiler.inspector.lintPlan);
1162
1271
  }
1163
- function rejectLegacyConfig(source) {
1164
- if (Object.hasOwn(source, "extends") && typeof source.extends !== "boolean") throw new Error("Custom config extends is no longer supported; use defineConfig(vpConfig).withVue(vueConfig)");
1165
- if (Object.hasOwn(source, "vize")) throw new Error("vize: configuration is no longer supported; move Vue settings to vue: in vite.config.*");
1166
- for (const key of [
1167
- "lint",
1168
- "fmt",
1169
- "pack"
1170
- ]) if ((Array.isArray(source[key]) ? source[key] : [source[key]]).some((value) => object(value) && Object.hasOwn(value, "vize"))) throw new Error(key === "lint" ? "lint.vize is no longer supported; pass { lint: false } as defineConfig's integration options to disable the Vite+ native lint task while keeping CLI lint enabled, and put shared lint settings in vue.linter" : `${key}.vize: configuration is no longer supported; move Vue settings to vue: in vite.config.*`);
1272
+ async function inspectWithNative(plan, root, files) {
1273
+ const { inspectLintPlan } = await import("@vizejs/native");
1274
+ return inspectLintPlan(plan, root, files);
1171
1275
  }
1172
- const VITE_CONFIG_FILE_NAMES = [
1173
- "vite.config.ts",
1276
+ function isLintPlanPayload(value) {
1277
+ return value !== null && typeof value === "object" && !Array.isArray(value) && value.schema === "vize.inspector.lint-plan" && value.version === 1 && typeof value.root === "string" && Array.isArray(value.items) && Array.isArray(value.files);
1278
+ }
1279
+ //#endregion
1280
+ //#region src/lint/generation.ts
1281
+ /** Nuxt module wiring for generated oxlint configuration. */
1282
+ const GENERATED_CONFIG_NAME = ".oxlint.vize.json";
1283
+ /** Shown when lint is skipped because the optional plugin peer is absent. */
1284
+ const MISSING_LINT_PLUGIN_WARNING = "@vizejs/nuxt: lint skipped; oxlint-plugin-vize is not installed. Run `vp install -D oxlint-plugin-vize` to enable it.";
1285
+ /** Root config names supported by oxlint's config discovery. */
1286
+ const ROOT_OXLINT_CONFIG_NAMES = [
1287
+ ".oxlintrc.json",
1288
+ ".oxlintrc.jsonc",
1289
+ "oxlint.config.ts",
1290
+ "oxlint.config.mts"
1291
+ ];
1292
+ const ROOT_LINT_CONFIG_NAMES = [
1293
+ ...ROOT_OXLINT_CONFIG_NAMES,
1174
1294
  "vite.config.js",
1175
1295
  "vite.config.mjs",
1296
+ "vite.config.ts",
1176
1297
  "vite.config.cjs",
1177
1298
  "vite.config.mts",
1178
1299
  "vite.config.cts"
1179
1300
  ];
1180
- /** Resolve an authored Vite export without projecting away Vite-owned task settings. */
1181
- async function resolveViteConfigSource(exported, env) {
1182
- env ??= {
1183
- mode: "development",
1184
- command: "serve"
1185
- };
1186
- if (env.command !== "build" && env.command !== "serve") env = {
1187
- ...env,
1188
- command: "serve"
1189
- };
1190
- return resolveSource(exported, env);
1301
+ function isNotFound(error) {
1302
+ return error.code === "ENOENT";
1191
1303
  }
1192
- //#endregion
1193
- //#region src/lint/project-rules.ts
1194
- const CONFIG_PRESETS = [
1195
- "happy-path",
1196
- "opinionated",
1197
- "essential",
1198
- "incremental",
1199
- "ecosystem",
1200
- "nuxt"
1201
- ];
1202
- const RETIRED_CONFIG = /^vize\.config\.(?:pkl|[cm]?[jt]s|json)$/;
1203
- const VIZE_JS_PLUGIN_SPECIFIER = "oxlint-plugin-vize";
1204
- const CONFIG_MIGRATION = "vize.config.* is no longer supported; move Vue settings to vue: in vite.config.* and TypeScript settings to tsconfig.json";
1205
- async function readProjectLintRuleSets(rootDir, loadPreset = loadPresetRules) {
1206
- const project = await readProjectConfig(rootDir);
1207
- const linter = project.linter;
1208
- const oxlint = explicitOxlintRules(project.oxlint);
1209
- const jsPlugins = explicitOxlintJsPlugins(project.oxlint, project.oxlintConfigDir);
1210
- const oxlintOverrides = explicitOxlintOverrides(project.oxlint, project.oxlintConfigDir);
1211
- const warnings = [];
1212
- let vize;
1213
- if (linter) {
1214
- const rules = applyRuleOptions({
1215
- ...linter.preset && linter.preset !== "incremental" ? await loadPreset(linter.preset, linter.typeAware) : {},
1216
- ...linter.rules
1217
- }, linter.ruleOptions, warnings, "vue.linter");
1218
- if (Object.keys(rules).length > 0) vize = rules;
1304
+ /**
1305
+ * Write bytes only when they differ from the current regular file.
1306
+ *
1307
+ * The length fast path mirrors Canon's materializer. A full byte comparison is
1308
+ * still required before skipping so equal-size edits are never mistaken for a
1309
+ * cache hit. Symlinks are rejected instead of followed.
1310
+ */
1311
+ async function writeFileIfChanged(file, content) {
1312
+ await mkdir(path.dirname(file), { recursive: true });
1313
+ try {
1314
+ const metadata = await lstat(file);
1315
+ if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error(`Generated oxlint config must be a regular file: ${file}`);
1316
+ if (metadata.size === Buffer.byteLength(content)) {
1317
+ if ((await readFile(file)).equals(Buffer.from(content))) return false;
1318
+ }
1319
+ } catch (error) {
1320
+ if (!isNotFound(error)) throw error;
1219
1321
  }
1220
- const entries = project.entries.map((entry, index) => {
1221
- const rules = applyRuleOptions({ ...entry.rules }, entry.ruleOptions, warnings, `vue.entries[${String(index)}].linter`, vize);
1222
- if (Object.keys(rules).length === 0) return void 0;
1223
- return {
1224
- files: entry.files,
1225
- ...entry.ignores ? { ignores: entry.ignores } : {},
1226
- ...entry.name ? { name: entry.name } : {},
1227
- rules
1228
- };
1229
- }).filter((entry) => entry !== void 0);
1230
- return {
1231
- ...entries.length > 0 ? { entries } : {},
1232
- ...jsPlugins.length > 0 ? { jsPlugins } : {},
1233
- ...vize ? { vize } : {},
1234
- ...Object.keys(oxlint).length > 0 ? { oxlint } : {},
1235
- ...oxlintOverrides.length > 0 ? { oxlintOverrides } : {},
1236
- ...warnings.length > 0 ? { warnings } : {}
1237
- };
1322
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
1323
+ try {
1324
+ await writeFile(temporary, content, { flag: "wx" });
1325
+ await rename(temporary, file);
1326
+ } finally {
1327
+ await unlink(temporary).catch((error) => {
1328
+ if (!isNotFound(error)) throw error;
1329
+ });
1330
+ }
1331
+ return true;
1238
1332
  }
1239
- async function readProjectConfig(rootDir) {
1240
- const loaded = await loadProjectViteConfigSource(rootDir);
1241
- if (!loaded) return { entries: [] };
1242
- const parsed = loaded.source;
1243
- const rawVue = parsed.vue && typeof parsed.vue === "object" ? parsed.vue : void 0;
1244
- const rawLinter = rawVue && "linter" in rawVue ? projectLinter(rawVue.linter) : void 0;
1245
- return {
1246
- entries: rawVue && "entries" in rawVue ? projectEntries(rawVue.entries) : [],
1247
- linter: rawLinter,
1248
- oxlint: parsed.lint,
1249
- oxlintConfigDir: loaded.configDir
1250
- };
1333
+ function hasTypeScript(rootDir) {
1334
+ try {
1335
+ createRequire(path.join(rootDir, "package.json")).resolve("typescript");
1336
+ return true;
1337
+ } catch {
1338
+ return false;
1339
+ }
1251
1340
  }
1252
- function projectLinter(value) {
1253
- if (!value || typeof value !== "object") return void 0;
1254
- const raw = value;
1255
- return {
1256
- preset: isConfigPreset(raw.preset) ? raw.preset : void 0,
1257
- ruleOptions: explicitRuleOptions(raw.ruleOptions),
1258
- typeAware: raw.typeAware === true,
1259
- rules: explicitRules(raw.rules)
1260
- };
1341
+ function relativeSpecifier(from, target) {
1342
+ const relative = path.relative(from, target);
1343
+ if (path.isAbsolute(relative)) return pathToFileURL(target).href;
1344
+ const normalized = relative.split(path.sep).join("/");
1345
+ return normalized.startsWith("./") || normalized.startsWith("../") ? normalized : `./${normalized}`;
1261
1346
  }
1262
- function projectEntries(value) {
1263
- if (!Array.isArray(value)) return [];
1264
- return value.flatMap((candidate) => {
1265
- if (!candidate || typeof candidate !== "object") return [];
1266
- const raw = candidate;
1267
- const linter = projectLinter(raw.linter);
1268
- const files = scopedGlobs(raw.files, raw.basePath);
1269
- if (!linter || files.length === 0) return [];
1270
- const ignores = scopedGlobs(raw.ignores, raw.basePath);
1271
- return [{
1272
- ...linter,
1273
- files,
1274
- ...ignores.length > 0 ? { ignores } : {},
1275
- ...typeof raw.name === "string" && raw.name ? { name: raw.name } : {}
1276
- }];
1277
- });
1347
+ function resolveVizePluginSpecifier(configDir) {
1348
+ let entry;
1349
+ try {
1350
+ entry = fileURLToPath(import.meta.resolve("oxlint-plugin-vize"));
1351
+ } catch (error) {
1352
+ if (error.code === "ERR_MODULE_NOT_FOUND") return void 0;
1353
+ throw error;
1354
+ }
1355
+ return relativeSpecifier(configDir, entry);
1278
1356
  }
1279
- function scopedGlobs(value, basePath) {
1280
- if (!Array.isArray(value)) return [];
1281
- const base = typeof basePath === "string" && basePath ? basePath : void 0;
1282
- return value.flatMap((glob) => {
1283
- if (typeof glob !== "string" || !glob) return [];
1284
- return [base && !path$1.isAbsolute(glob) ? path$1.join(base, glob) : glob];
1285
- });
1357
+ async function exists(file) {
1358
+ try {
1359
+ await lstat(file);
1360
+ return true;
1361
+ } catch (error) {
1362
+ if (isNotFound(error)) return false;
1363
+ throw error;
1364
+ }
1286
1365
  }
1287
- async function loadProjectViteConfigSource(rootDir) {
1288
- let directory = path$1.resolve(rootDir);
1366
+ async function findRootLintConfig(rootDir) {
1367
+ let directory = path.resolve(rootDir);
1289
1368
  while (true) {
1290
- for (const name of VITE_CONFIG_FILE_NAMES) {
1291
- const filePath = path$1.join(directory, name);
1292
- if (!fs$1.existsSync(filePath)) continue;
1293
- const module = await importConfigModule(filePath);
1294
- if (module === null) throw new Error("Unable to load Vite configuration at " + filePath);
1295
- return {
1296
- configDir: directory,
1297
- source: await resolveViteConfigSource(module.default ?? module, {
1298
- command: "lint",
1299
- mode: "development"
1300
- })
1301
- };
1302
- }
1303
- if (fs$1.existsSync(directory) && fs$1.readdirSync(directory).some((name) => RETIRED_CONFIG.test(name))) throw new Error(CONFIG_MIGRATION);
1304
- if ([
1305
- "package.json",
1306
- "tsconfig.json",
1307
- "jsconfig.json"
1308
- ].some((name) => fs$1.existsSync(path$1.join(directory, name)))) return null;
1309
- const parent = path$1.dirname(directory);
1310
- if (parent === directory) return null;
1369
+ for (const name of ROOT_LINT_CONFIG_NAMES) {
1370
+ const candidate = path.join(directory, name);
1371
+ try {
1372
+ const metadata = await lstat(candidate);
1373
+ if (metadata.isFile() || metadata.isSymbolicLink()) return candidate;
1374
+ } catch (error) {
1375
+ if (!isNotFound(error)) throw error;
1376
+ }
1377
+ }
1378
+ const parent = path.dirname(directory);
1379
+ if (parent === directory) return void 0;
1311
1380
  directory = parent;
1312
1381
  }
1313
1382
  }
1314
- const OXLINT_SEVERITIES = new Map([
1315
- ["off", "off"],
1316
- ["allow", "off"],
1317
- [0, "off"],
1318
- ["warn", "warn"],
1319
- [1, "warn"],
1320
- ["error", "error"],
1321
- ["deny", "error"],
1322
- [2, "error"]
1323
- ]);
1324
- function explicitOxlintRules(value) {
1325
- if (!value || typeof value !== "object") return {};
1326
- return oxlintRules("rules" in value ? value.rules : void 0);
1383
+ function renderRootOxlintConfig(rootDir, generatedConfig) {
1384
+ const specifier = relativeSpecifier(rootDir, generatedConfig);
1385
+ return [
1386
+ "// Generated by @vizejs/nuxt.",
1387
+ "import { readFileSync } from \"node:fs\";",
1388
+ "",
1389
+ "type OxlintJsPlugin = string | { name?: string; specifier: string };",
1390
+ "",
1391
+ `const generatedUrl = new URL(${JSON.stringify(specifier)}, import.meta.url);`,
1392
+ "const config = JSON.parse(readFileSync(generatedUrl, \"utf8\"));",
1393
+ "config.jsPlugins = config.jsPlugins.map((plugin: OxlintJsPlugin) =>",
1394
+ " typeof plugin === \"string\"",
1395
+ " ? new URL(plugin, generatedUrl).href",
1396
+ " : { ...plugin, specifier: new URL(plugin.specifier, generatedUrl).href },",
1397
+ ");",
1398
+ "",
1399
+ "export default config;",
1400
+ ""
1401
+ ].join("\n");
1327
1402
  }
1328
- /** Oxlint's `severity` and `[severity, ...options]` forms, with severity aliases normalized. */
1329
- function oxlintRules(value) {
1330
- if (!value || typeof value !== "object") return {};
1331
- const result = {};
1332
- for (const [id, config] of Object.entries(value)) {
1333
- const severity = OXLINT_SEVERITIES.get(Array.isArray(config) ? config[0] : config);
1334
- if (!severity) continue;
1335
- result[id] = Array.isArray(config) ? [severity, ...config.slice(1)] : severity;
1403
+ async function initRootOxlintConfig(rootDir, generatedConfig, previousDefault) {
1404
+ const existing = await findRootLintConfig(rootDir);
1405
+ if (existing) {
1406
+ if (existing === path.join(rootDir, "oxlint.config.mts") && previousDefault && (await lstat(existing)).isFile() && await readFile(existing, "utf8") === renderRootOxlintConfig(rootDir, previousDefault)) await writeFileIfChanged(existing, renderRootOxlintConfig(rootDir, generatedConfig));
1407
+ return;
1336
1408
  }
1337
- return result;
1338
- }
1339
- function explicitOxlintOverrides(value, configDir) {
1340
- if (!value || typeof value !== "object" || !configDir) return [];
1341
- const overrides = "overrides" in value ? value.overrides : void 0;
1342
- if (!Array.isArray(overrides)) return [];
1343
- return overrides.flatMap((candidate) => {
1344
- if (!candidate || typeof candidate !== "object") return [];
1345
- const raw = candidate;
1346
- const files = Array.isArray(raw.files) ? raw.files.flatMap((glob) => {
1347
- if (typeof glob !== "string" || !glob) return [];
1348
- const negated = glob.startsWith("!");
1349
- const resolved = path$1.resolve(configDir, negated ? glob.slice(1) : glob);
1350
- return [negated ? `!${resolved}` : resolved];
1351
- }) : [];
1352
- const rules = oxlintRules(raw.rules);
1353
- return files.length > 0 && Object.keys(rules).length > 0 ? [{
1354
- files,
1355
- rules
1356
- }] : [];
1409
+ if (path.dirname(generatedConfig) !== rootDir) throw new Error("Set lint.autoInit to false when lint.configFile is outside the Nuxt root");
1410
+ const handle = await open(path.join(rootDir, "oxlint.config.mts"), "wx").catch((error) => {
1411
+ if (error.code === "EEXIST") return void 0;
1412
+ throw error;
1357
1413
  });
1358
- }
1359
- function explicitOxlintJsPlugins(value, configDir) {
1360
- if (!value || typeof value !== "object") return [];
1361
- const jsPlugins = "jsPlugins" in value ? value.jsPlugins : void 0;
1362
- if (!Array.isArray(jsPlugins)) return [];
1363
- const seen = /* @__PURE__ */ new Set();
1364
- const result = [];
1365
- for (const specifier of jsPlugins) {
1366
- if (typeof specifier !== "string" || specifier.length === 0 || specifier === VIZE_JS_PLUGIN_SPECIFIER) continue;
1367
- const resolved = configDir && (specifier.startsWith("./") || specifier.startsWith("../")) ? path$1.resolve(configDir, specifier) : specifier;
1368
- if (seen.has(resolved)) continue;
1369
- seen.add(resolved);
1370
- result.push(resolved);
1414
+ if (!handle) return;
1415
+ try {
1416
+ await handle.writeFile(renderRootOxlintConfig(rootDir, generatedConfig), "utf8");
1417
+ } finally {
1418
+ await handle.close();
1371
1419
  }
1372
- return result;
1373
1420
  }
1374
- async function loadPresetRules(preset, typeAware) {
1375
- const { createVizeRuleConfig } = await import("oxlint-plugin-vize");
1376
- const generated = createVizeRuleConfig({
1377
- includeTypeAware: typeAware,
1378
- preset
1379
- });
1380
- const rules = {};
1381
- for (const [id, severity] of Object.entries(generated)) {
1382
- if (!isSeverity(severity)) continue;
1383
- const bare = id.startsWith("vize/") ? id.slice(5) : id;
1384
- if (bare.length > 0) rules[bare] = severity;
1421
+ /**
1422
+ * Generate the initial config and register the Nuxt regeneration hook.
1423
+ *
1424
+ * Addons are resolved inside `regenerate`, not at setup time, so Nuxt's import
1425
+ * registry and third-party module hooks can change between generateApp passes.
1426
+ */
1427
+ async function setupNuxtLintConfigGeneration(lint, nuxt, dependencies = {}) {
1428
+ if (lint === false) return void 0;
1429
+ const { autoInit = true, configFile: configuredFile, rootDir: configuredRoot, ...featureOptions } = typeof lint === "object" && lint !== null ? lint : {};
1430
+ const nuxtRoot = path.resolve(nuxt.options.rootDir);
1431
+ const planRoot = configuredRoot ? path.resolve(nuxtRoot, configuredRoot) : nuxtRoot;
1432
+ const configFile = path.resolve(nuxtRoot, configuredFile ?? GENERATED_CONFIG_NAME);
1433
+ const ownsReservedConfig = configFile === path.join(nuxtRoot, GENERATED_CONFIG_NAME);
1434
+ const hasTypeScriptProbe = dependencies.hasTypeScript ?? hasTypeScript;
1435
+ const pluginSpecifier = (dependencies.resolvePluginSpecifier ?? resolveVizePluginSpecifier)(path.dirname(configFile));
1436
+ if (pluginSpecifier === void 0) {
1437
+ if (dependencies.reportMissingPlugin || await exists(configFile)) (dependencies.warn ?? console.warn)(MISSING_LINT_PLUGIN_WARNING);
1438
+ return;
1385
1439
  }
1386
- return rules;
1440
+ const resolveAddons = dependencies.resolveAddons ?? ("callHook" in nuxt ? setupNuxtLintConfigAddons(nuxt, { rootDir: planRoot }) : void 0);
1441
+ const resolveProjectRuleSets = dependencies.resolveProjectLintRules ? async (rootDir) => {
1442
+ const rules = await dependencies.resolveProjectLintRules?.(rootDir);
1443
+ return rules && Object.keys(rules).length > 0 ? { vize: rules } : {};
1444
+ } : readProjectLintRuleSets;
1445
+ let currentPlan = [];
1446
+ const emittedWarnings = /* @__PURE__ */ new Set();
1447
+ const regenerate = async () => {
1448
+ const plan = buildNuxtLintPlan(resolveNuxtLintFeatures(featureOptions, () => hasTypeScriptProbe(planRoot)), collectNuxtLintDirs(toNuxtLintProjectState(nuxt.options, { rootDir: planRoot })), getDetectedNuxtMajor(nuxt) ?? 3);
1449
+ const addons = await resolveAddons?.() ?? [];
1450
+ const projectRules = await resolveProjectRuleSets(planRoot);
1451
+ const projectItems = [];
1452
+ if (projectRules.vize) projectItems.push({
1453
+ name: "project/preset",
1454
+ rules: projectRules.vize
1455
+ });
1456
+ if (projectRules.oxlint) projectItems.push({
1457
+ name: "project/oxlint",
1458
+ nativeRules: projectRules.oxlint
1459
+ });
1460
+ for (const [index, entry] of (projectRules.entries ?? []).entries()) projectItems.push({
1461
+ name: entry.name ? `project/${entry.name}` : `project/entry-${String(index + 1)}`,
1462
+ files: entry.files,
1463
+ ...entry.ignores ? { ignores: entry.ignores } : {},
1464
+ rules: entry.rules
1465
+ });
1466
+ for (const [index, override] of (projectRules.oxlintOverrides ?? []).entries()) projectItems.push({
1467
+ name: `project/oxlint-override-${String(index + 1)}`,
1468
+ files: override.files,
1469
+ nativeRules: override.rules
1470
+ });
1471
+ for (const warning of projectRules.warnings ?? []) {
1472
+ if (emittedWarnings.has(warning)) continue;
1473
+ emittedWarnings.add(warning);
1474
+ (dependencies.warn ?? console.warn)(`@vizejs/nuxt lint config: ${warning}`);
1475
+ }
1476
+ const nextPlan = [
1477
+ ...projectItems,
1478
+ ...plan,
1479
+ ...addons
1480
+ ];
1481
+ const artifact = renderNuxtOxlintConfig(nextPlan, pluginSpecifier, {
1482
+ rootDir: planRoot,
1483
+ configDir: path.dirname(configFile),
1484
+ owner: ownsReservedConfig ? "@vizejs/nuxt" : void 0
1485
+ }, projectRules.jsPlugins);
1486
+ const changed = ownsReservedConfig ? await writeOwnedNuxtConfig(configFile, artifact, writeFileIfChanged) : await writeFileIfChanged(configFile, artifact);
1487
+ currentPlan = nextPlan;
1488
+ return changed;
1489
+ };
1490
+ const resolvePlan = async (fresh = false) => {
1491
+ if (fresh) await regenerate();
1492
+ return currentPlan;
1493
+ };
1494
+ await regenerate();
1495
+ nuxt.hook("builder:generateApp", regenerate);
1496
+ if (getDetectedNuxtMajor(nuxt) === 2) nuxt.hook("build:templates", regenerate);
1497
+ if (autoInit) await initRootOxlintConfig(nuxtRoot, configFile, ownsReservedConfig ? path.resolve(nuxtRoot, nuxt.options.buildDir, "oxlint.config.json") : void 0);
1498
+ return {
1499
+ configFile,
1500
+ root: planRoot,
1501
+ regenerate,
1502
+ resolvePlan
1503
+ };
1387
1504
  }
1388
- function explicitRules(value) {
1389
- if (!value || typeof value !== "object") return {};
1390
- const rules = {};
1391
- for (const [id, severity] of Object.entries(value)) {
1392
- if (!isSeverity(severity)) continue;
1393
- const bare = id.startsWith("vize/") ? id.slice(5) : id;
1394
- if (bare.length > 0) rules[bare] = severity;
1395
- }
1396
- return rules;
1505
+ //#endregion
1506
+ //#region src/lint/checker/options.ts
1507
+ /**
1508
+ * Resolve the engine-neutral part of `@nuxt/eslint`'s checker contract.
1509
+ *
1510
+ * `configType` and `eslintPath` intentionally do not exist: they choose an
1511
+ * ESLint implementation, while this checker always executes oxlint + Patina.
1512
+ */
1513
+ function resolveNuxtLintCheckerOptions(checker, project) {
1514
+ if (checker !== true && (checker === false || checker == null)) return false;
1515
+ const overrides = typeof checker === "object" ? checker : {};
1516
+ return {
1517
+ cache: overrides.cache ?? true,
1518
+ include: [...overrides.include ?? [`${project.srcDir}/**/*.{js,jsx,ts,tsx,vue}`]],
1519
+ exclude: [...overrides.exclude ?? ["**/node_modules/**", project.buildDir]],
1520
+ formatter: overrides.formatter ?? "stylish",
1521
+ lintOnStart: overrides.lintOnStart ?? true,
1522
+ emitWarning: overrides.emitWarning ?? true,
1523
+ emitError: overrides.emitError ?? true,
1524
+ fix: overrides.fix ?? false
1525
+ };
1397
1526
  }
1398
- function explicitRuleOptions(value) {
1399
- if (!value || typeof value !== "object") return {};
1400
- const options = {};
1401
- for (const [id, option] of Object.entries(value)) {
1402
- const bare = id.startsWith("vize/") ? id.slice(5) : id;
1403
- if (bare.length > 0) options[bare] = option;
1404
- }
1405
- return options;
1527
+ //#endregion
1528
+ //#region src/lint/checker/filter.ts
1529
+ const GLOB_TOKEN = /[*?[\]{}()]/u;
1530
+ function normalize(value) {
1531
+ const normalized = value.replaceAll("\\", "/").replace(/\/{2,}/gu, "/");
1532
+ if (normalized === "/" || /^[A-Za-z]:\/$/u.test(normalized)) return normalized;
1533
+ return normalized.replace(/\/$/u, "");
1406
1534
  }
1407
- function applyRuleOptions(source, options, warnings, scope, fallback = {}) {
1408
- const rules = { ...source };
1409
- for (const [ruleId, option] of Object.entries(options)) {
1410
- const configured = rules[ruleId] ?? fallback[ruleId];
1411
- const severity = Array.isArray(configured) ? configured[0] : configured;
1412
- if (!isSeverity(severity)) {
1413
- warnings.push(`${scope}.ruleOptions[${JSON.stringify(ruleId)}] has no enabled rule severity to attach to`);
1414
- continue;
1415
- }
1416
- rules[ruleId] = [severity, option];
1417
- }
1418
- return rules;
1535
+ function relativeToRoot(file, rootDir) {
1536
+ const root = normalize(rootDir);
1537
+ const absolute = normalize(file);
1538
+ const prefix = `${root}/`;
1539
+ if (absolute.startsWith(prefix)) return absolute.slice(prefix.length);
1540
+ const normalized = normalize(path.relative(rootDir, file));
1541
+ return normalized === ".." || normalized.startsWith("../") ? void 0 : normalized;
1419
1542
  }
1420
- function isConfigPreset(value) {
1421
- return typeof value === "string" && CONFIG_PRESETS.includes(value);
1543
+ function matchesDirectory(candidate, pattern) {
1544
+ if (GLOB_TOKEN.test(pattern)) return false;
1545
+ return candidate === pattern || candidate.startsWith(`${pattern}/`);
1546
+ }
1547
+ function matchesPattern(absolute, relative, rawPattern) {
1548
+ const pattern = normalize(rawPattern);
1549
+ const candidates = path.isAbsolute(pattern) || /^[A-Za-z]:\//u.test(pattern) ? [absolute] : relative === void 0 ? [] : [relative];
1550
+ for (const candidate of candidates) if (matchesDirectory(candidate, pattern) || path.matchesGlob(candidate, pattern)) return true;
1551
+ return false;
1422
1552
  }
1423
- function isSeverity(value) {
1424
- return value === "off" || value === "warn" || value === "error";
1553
+ /** Whether one watcher path belongs to the checker include/exclude contract. */
1554
+ function matchesNuxtLintCheckerFile(file, rootDir, options) {
1555
+ const absolute = normalize(file);
1556
+ const relative = relativeToRoot(file, rootDir);
1557
+ if (options.exclude.some((pattern) => matchesPattern(absolute, relative, pattern))) return false;
1558
+ return options.include.some((pattern) => matchesPattern(absolute, relative, pattern));
1425
1559
  }
1426
1560
  //#endregion
1427
- //#region src/lint/owned-config.ts
1428
- /** Keep the module's reserved root file from replacing an authored config. */
1429
- async function writeOwnedNuxtConfig(file, content, writeChanged) {
1561
+ //#region src/lint/checker/worker.ts
1562
+ function resolveOxlintEntrypoint() {
1430
1563
  try {
1431
- const handle = await open(file, "wx");
1432
- try {
1433
- await handle.writeFile(content, "utf8");
1434
- } finally {
1435
- await handle.close();
1436
- }
1437
- return true;
1564
+ const plugin = fileURLToPath(import.meta.resolve("oxlint-plugin-vize"));
1565
+ return path.resolve(path.dirname(plugin), "..", "bin", "oxlint-vize");
1438
1566
  } catch (error) {
1439
- if (error.code !== "EEXIST") throw error;
1567
+ throw new Error("Unable to resolve oxlint-vize. Install oxlint-plugin-vize before enabling the Nuxt lint checker.", { cause: error });
1440
1568
  }
1441
- const metadata = await lstat(file);
1442
- if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error(`Generated oxlint config must be a regular file: ${file}`);
1443
- let owner;
1444
- try {
1445
- owner = JSON.parse(await readFile(file, "utf8"))?.settings?.vize?.generatedBy;
1446
- } catch {}
1447
- if (owner !== "@vizejs/nuxt") throw new Error(`Refusing to replace authored ${file}; choose a different lint.configFile`);
1448
- return writeChanged(file, content);
1449
1569
  }
1450
- //#endregion
1451
- //#region src/lint/inspector-view.ts
1452
- /** Render the dependency-free UI served by the in-process lint-plan inspector. */
1453
- function renderNuxtLintInspectorHtml(nonce) {
1454
- return `<!doctype html>
1455
- <html lang="en">
1456
- <head>
1457
- <meta charset="utf-8">
1458
- <meta name="viewport" content="width=device-width,initial-scale=1">
1459
- <title>Vize Nuxt Lint Plan</title>
1460
- <style nonce="${nonce}">
1461
- :root { color-scheme: light dark; font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; }
1462
- * { box-sizing: border-box; }
1463
- body { margin: 0; background: #0d1117; color: #e6edf3; }
1464
- header { position: sticky; top: 0; z-index: 1; padding: 16px 20px; background: #161b22; border-bottom: 1px solid #30363d; }
1465
- h1 { margin: 0 0 12px; font-size: 18px; }
1466
- h2 { margin: 24px 0 10px; font-size: 16px; }
1467
- form { display: flex; gap: 8px; flex-wrap: wrap; }
1468
- input { flex: 1 1 320px; min-width: 180px; padding: 8px 10px; color: inherit; background: #0d1117; border: 1px solid #484f58; border-radius: 6px; }
1469
- button { padding: 8px 12px; color: #fff; background: #238636; border: 0; border-radius: 6px; cursor: pointer; }
1470
- button.secondary { background: #30363d; }
1471
- button:disabled { opacity: .6; cursor: wait; }
1472
- main { max-width: 1100px; margin: 0 auto; padding: 0 20px 32px; }
1473
- #status { min-height: 22px; margin-top: 8px; color: #8c959f; }
1474
- #status.error { color: #ff7b72; }
1475
- .card { margin: 8px 0; padding: 12px; background: #161b22; border: 1px solid #30363d; border-radius: 8px; }
1476
- .meta { color: #8c959f; overflow-wrap: anywhere; }
1477
- .badge { display: inline-block; margin: 2px 4px 2px 0; padding: 1px 6px; border-radius: 10px; background: #30363d; }
1478
- .severity-error { color: #ff7b72; } .severity-warn { color: #d29922; } .severity-off { color: #8c959f; }
1479
- table { width: 100%; border-collapse: collapse; }
1480
- th, td { padding: 7px 8px; text-align: left; border-bottom: 1px solid #30363d; overflow-wrap: anywhere; }
1481
- th { color: #8c959f; font-weight: 600; }
1482
- code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
1483
- </style>
1484
- </head>
1485
- <body>
1486
- <header>
1487
- <h1>Vize Nuxt Lint Plan</h1>
1488
- <form id="inspect-form">
1489
- <input id="file" name="file" autocomplete="off" placeholder="app/pages/index.vue" aria-label="Project-relative file">
1490
- <button type="submit">Inspect file</button>
1491
- <button id="refresh" class="secondary" type="button">Refresh plan</button>
1492
- </form>
1493
- <div id="status" role="status" aria-live="polite"></div>
1494
- </header>
1495
- <main>
1496
- <section><h2>Effective rules</h2><div id="effective"></div></section>
1497
- <section><h2>Ordered config items</h2><div id="items"></div></section>
1498
- </main>
1499
- <script nonce="${nonce}">
1500
- const fileInput = document.getElementById("file");
1501
- const form = document.getElementById("inspect-form");
1502
- const refresh = document.getElementById("refresh");
1503
- const status = document.getElementById("status");
1504
- const effective = document.getElementById("effective");
1505
- const items = document.getElementById("items");
1506
- const buttons = Array.from(document.querySelectorAll("button"));
1507
-
1508
- function node(tag, text, className) {
1509
- const value = document.createElement(tag);
1510
- if (text !== undefined) value.textContent = String(text);
1511
- if (className) value.className = className;
1512
- return value;
1513
- }
1514
-
1515
- function badges(values) {
1516
- const wrapper = node("div");
1517
- for (const value of values || []) wrapper.append(node("span", value, "badge"));
1518
- return wrapper;
1519
- }
1520
-
1521
- function renderItems(payload) {
1522
- items.replaceChildren();
1523
- for (const item of payload.items || []) {
1524
- const card = node("article", undefined, "card");
1525
- card.append(node("strong", item.name || "unnamed"));
1526
- if (item.globalIgnore) card.append(node("span", " global ignore", "meta"));
1527
- if (item.basePath) card.append(node("div", "base: " + item.basePath, "meta"));
1528
- if (item.files) card.append(node("div", "files", "meta"), badges(item.files));
1529
- if (item.ignores && item.ignores.length) card.append(node("div", "ignores", "meta"), badges(item.ignores));
1530
- const rules = Object.entries(item.rules || {});
1531
- if (rules.length) card.append(badges(rules.map(([name, severity]) => name + ": " + severity)));
1532
- items.append(card);
1533
- }
1534
- }
1535
-
1536
- function renderEffective(payload) {
1537
- effective.replaceChildren();
1538
- const file = payload.files && payload.files[0];
1539
- if (!file) {
1540
- effective.append(node("p", "Enter a project-relative file to explain its effective rules.", "meta"));
1541
- return;
1542
- }
1543
- const summary = node("div", undefined, "card");
1544
- summary.append(node("strong", file.path));
1545
- if (file.ignored) summary.append(node("div", "Ignored by: " + (file.ignoredBy || []).join(", "), "severity-warn"));
1546
- else summary.append(node("div", "Matched: " + (file.matchedItems || []).join(" → "), "meta"));
1547
- effective.append(summary);
1548
- if (!file.rules || !file.rules.length) return;
1549
- const table = node("table");
1550
- const head = node("tr");
1551
- for (const label of ["Rule", "Severity", "Set by"]) head.append(node("th", label));
1552
- const thead = node("thead"); thead.append(head); table.append(thead);
1553
- const tbody = node("tbody");
1554
- for (const rule of file.rules) {
1555
- const row = node("tr");
1556
- row.append(node("td", rule.name), node("td", rule.severity, "severity-" + rule.severity), node("td", rule.setBy));
1557
- tbody.append(row);
1558
- }
1559
- table.append(tbody); effective.append(table);
1560
- }
1561
-
1562
- async function load(fresh) {
1563
- const url = new URL("api", location.href);
1564
- const file = fileInput.value.trim();
1565
- if (file) url.searchParams.set("file", file);
1566
- if (fresh) url.searchParams.set("fresh", "1");
1567
- buttons.forEach(button => { button.disabled = true; });
1568
- status.className = ""; status.textContent = fresh ? "Refreshing…" : "Loading…";
1569
- try {
1570
- const response = await fetch(url, { headers: { accept: "application/json" } });
1571
- const payload = await response.json();
1572
- if (!response.ok) throw new Error(payload.error || "Inspector request failed");
1573
- renderEffective(payload); renderItems(payload);
1574
- status.textContent = "Resolved " + (payload.items || []).length + " config items";
1575
- } catch (error) {
1576
- status.className = "error";
1577
- status.textContent = error instanceof Error ? error.message : String(error);
1578
- } finally {
1579
- buttons.forEach(button => { button.disabled = false; });
1580
- }
1581
- }
1582
-
1583
- form.addEventListener("submit", event => { event.preventDefault(); void load(false); });
1584
- refresh.addEventListener("click", () => { void load(true); });
1585
- void load(false);
1586
- <\/script>
1587
- </body>
1588
- </html>`;
1570
+ function projectPattern(pattern, cwd) {
1571
+ if (!path.isAbsolute(pattern)) return pattern;
1572
+ const relative = path.relative(cwd, pattern);
1573
+ if (path.isAbsolute(relative) || relative === ".." || relative.startsWith(`..${path.sep}`)) return pattern;
1574
+ return relative.split(path.sep).join("/") || ".";
1575
+ }
1576
+ function expandBraces(pattern) {
1577
+ const match = /\{([^{}]+)\}/u.exec(pattern);
1578
+ if (!match || match.index === void 0) return [pattern];
1579
+ const before = pattern.slice(0, match.index);
1580
+ const after = pattern.slice(match.index + match[0].length);
1581
+ return match[1].split(",").flatMap((part) => expandBraces(`${before}${part}${after}`));
1582
+ }
1583
+ function oxlintPatterns(pattern, cwd) {
1584
+ const patterns = expandBraces(projectPattern(pattern, cwd)).flatMap((expanded) => {
1585
+ const shallow = expanded.replace(/(^|\/)\*\*\//gu, "$1");
1586
+ return shallow === expanded ? [expanded] : [expanded, shallow];
1587
+ });
1588
+ return [...new Set(patterns)];
1589
+ }
1590
+ async function oxlintTargets(pattern, cwd) {
1591
+ const rebased = projectPattern(pattern, cwd);
1592
+ if (rebased.endsWith("/**/*.{js,jsx,ts,tsx,vue}")) return [rebased.slice(0, -25) || "."];
1593
+ if (!/[*?[\]{}()]/u.test(rebased)) return [rebased];
1594
+ const matches = await Array.fromAsync(glob(rebased, { cwd }));
1595
+ return matches.length > 0 ? matches : oxlintPatterns(pattern, cwd);
1596
+ }
1597
+ async function checkerArgs(task) {
1598
+ const args = [
1599
+ "--config",
1600
+ task.configFile,
1601
+ "--format",
1602
+ "json",
1603
+ "--no-error-on-unmatched-pattern"
1604
+ ];
1605
+ if (task.fix) args.push("--fix");
1606
+ for (const pattern of task.exclude) for (const exclude of oxlintPatterns(pattern, task.cwd)) args.push("--ignore-pattern", exclude);
1607
+ for (const target of task.targets) args.push(...await oxlintTargets(target, task.cwd));
1608
+ return args;
1609
+ }
1610
+ function spawnOxlint(node, entrypoint, args, cwd) {
1611
+ return new Promise((resolve, reject) => {
1612
+ const child = spawn(node, [entrypoint, ...args], {
1613
+ cwd,
1614
+ stdio: [
1615
+ "ignore",
1616
+ "pipe",
1617
+ "pipe"
1618
+ ]
1619
+ });
1620
+ const stdout = [];
1621
+ const stderr = [];
1622
+ child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk)));
1623
+ child.stderr.on("data", (chunk) => stderr.push(Buffer.from(chunk)));
1624
+ child.on("error", (error) => {
1625
+ reject(new Error(`Failed to start oxlint at ${entrypoint}: ${error.message}`, { cause: error }));
1626
+ });
1627
+ child.on("close", (status) => {
1628
+ const output = Buffer.concat(stdout).toString("utf8");
1629
+ const details = Buffer.concat(stderr).toString("utf8");
1630
+ if (output.trim()) {
1631
+ resolve({
1632
+ stderr: details,
1633
+ stdout: output
1634
+ });
1635
+ return;
1636
+ }
1637
+ if (status === 0) {
1638
+ resolve({
1639
+ stderr: details,
1640
+ stdout: "{\"diagnostics\":[]}\n"
1641
+ });
1642
+ return;
1643
+ }
1644
+ reject(/* @__PURE__ */ new Error(`oxlint exited with ${String(status)} without JSON output${details.trim() ? `: ${details.trim()}` : ""}`));
1645
+ });
1646
+ });
1647
+ }
1648
+ async function executeOxlint(entrypoint, args, cwd) {
1649
+ if (!existsSync(entrypoint)) throw new Error(`Failed to start oxlint: entrypoint does not exist: ${entrypoint}`);
1650
+ const node = existsSync(process.execPath) ? process.execPath : "node";
1651
+ try {
1652
+ return await spawnOxlint(node, entrypoint, args, cwd);
1653
+ } catch (error) {
1654
+ const cause = error.cause;
1655
+ if (node !== "node" && cause?.code === "ENOENT") return spawnOxlint("node", entrypoint, args, cwd);
1656
+ throw error;
1657
+ }
1589
1658
  }
1590
- //#endregion
1591
- //#region src/lint/inspector-devtools.ts
1592
- const MAX_URL_BYTES = 8 * 1024;
1593
- const MAX_FILES = 128;
1594
- const MAX_FILE_BYTES = 4 * 1024;
1595
- const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
1596
- function resolveNuxtLintDevtoolsOptions(options) {
1597
- const enabled = options?.enabled ?? "lazy";
1598
- const port = options?.port;
1599
- if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new RangeError("Nuxt lint inspector port must be an integer from 1 to 65535");
1659
+ function diagnosticKind(diagnostic) {
1660
+ if (diagnostic.severity === 2 || diagnostic.severity === "error") return "error";
1661
+ if (diagnostic.severity === 1 || diagnostic.severity === "warn" || diagnostic.severity === "warning") return "warning";
1662
+ }
1663
+ function formatNuxtLintCheckerDiagnostics(diagnostics, formatter) {
1664
+ if (formatter === "json") return diagnostics.length > 0 ? `${JSON.stringify({ diagnostics })}\n` : "";
1665
+ const unix = formatter === "unix";
1666
+ const lines = diagnostics.map((diagnostic) => {
1667
+ const span = diagnostic.labels?.find((label) => label.span)?.span;
1668
+ const file = diagnostic.filename ?? diagnostic.filePath ?? "<unknown>";
1669
+ const line = span?.line ?? 1;
1670
+ const column = span?.column ?? 1;
1671
+ const severity = diagnosticKind(diagnostic) ?? "warning";
1672
+ const message = diagnostic.message ?? "lint diagnostic";
1673
+ const code = diagnostic.code ? ` (${diagnostic.code})` : "";
1674
+ return unix ? `${file}:${line}:${column}: ${message} [${severity}${code}]` : `${file}:${line}:${column} ${severity} ${message}${code}`;
1675
+ });
1676
+ return lines.length > 0 ? `${lines.join("\n")}\n` : "";
1677
+ }
1678
+ function resultFromPayload(payload, task, stderr) {
1679
+ const diagnostics = payload.diagnostics.filter((diagnostic) => {
1680
+ const kind = diagnosticKind(diagnostic);
1681
+ return kind === "error" && task.emitError || kind === "warning" && task.emitWarning;
1682
+ });
1683
+ const hasErrors = diagnostics.some((diagnostic) => diagnosticKind(diagnostic) === "error");
1684
+ const hasWarnings = diagnostics.some((diagnostic) => diagnosticKind(diagnostic) === "warning");
1685
+ const output = task.formatter === "json" ? diagnostics.length > 0 ? `${JSON.stringify({
1686
+ ...payload,
1687
+ diagnostics
1688
+ })}\n` : "" : formatNuxtLintCheckerDiagnostics(diagnostics, task.formatter);
1689
+ const notice = stderr.trim();
1600
1690
  return {
1601
- enabled,
1602
- port
1691
+ diagnostics,
1692
+ diagnosticCount: diagnostics.length,
1693
+ hasErrors,
1694
+ hasWarnings,
1695
+ notices: notice ? [notice] : [],
1696
+ output
1603
1697
  };
1604
1698
  }
1605
- async function setupNuxtLintDevtools(options, nuxt, provider) {
1606
- const resolved = resolveNuxtLintDevtoolsOptions(options);
1607
- if (resolved.enabled === false) return void 0;
1608
- const controller = createController(resolved.port, provider, nuxt);
1609
- nuxt.hook("devtools:customTabs", (...args) => {
1610
- args[0].push(controller.tab());
1611
- });
1612
- nuxt.hook("close", () => controller.close());
1613
- if (resolved.enabled === true) try {
1614
- await controller.start();
1699
+ /** Run one checker pass. This function executes inside the long-lived worker. */
1700
+ async function runNuxtLintCheckerTask(task) {
1701
+ if (!task.emitError && !task.emitWarning && !task.fix) return {
1702
+ diagnostics: [],
1703
+ diagnosticCount: 0,
1704
+ hasErrors: false,
1705
+ hasWarnings: false,
1706
+ notices: [],
1707
+ output: ""
1708
+ };
1709
+ const execution = await executeOxlint(task.oxlintEntrypoint ?? resolveOxlintEntrypoint(), await checkerArgs(task), task.cwd);
1710
+ let payload;
1711
+ try {
1712
+ payload = JSON.parse(execution.stdout);
1615
1713
  } catch (error) {
1616
- console.warn(`[vize] Nuxt lint inspector failed to start: ${error instanceof Error ? error.message : String(error)}`);
1714
+ throw new Error(`oxlint returned invalid JSON: ${execution.stdout.slice(0, 240)}`, { cause: error });
1617
1715
  }
1618
- return controller;
1716
+ if (!Array.isArray(payload.diagnostics)) throw new Error("oxlint JSON has no diagnostics array");
1717
+ return resultFromPayload(payload, task, execution.stderr);
1619
1718
  }
1620
- function createController(requestedPort, provider, nuxt) {
1621
- const token = randomBytes(18).toString("base64url");
1622
- const nonce = randomBytes(18).toString("base64url");
1623
- const server = createServer((request, response) => {
1624
- handleRequest(request, response, provider, token, nonce, server);
1625
- });
1626
- let closed = false;
1627
- let startPromise;
1628
- let viewerUrl;
1629
- const start = async () => {
1630
- if (closed) throw new Error("Nuxt lint inspector is closed");
1631
- if (viewerUrl) return;
1632
- startPromise ||= listen(server, requestedPort).then(async (port) => {
1633
- viewerUrl = `http://127.0.0.1:${port}/${token}/`;
1634
- await nuxt.callHook?.("devtools:customTabs:refresh");
1635
- });
1636
- try {
1637
- await startPromise;
1638
- } catch (error) {
1639
- startPromise = void 0;
1640
- throw error;
1641
- }
1642
- };
1643
- return {
1644
- async close() {
1645
- closed = true;
1646
- try {
1647
- await startPromise;
1648
- } catch {}
1649
- if (!server.listening) return;
1650
- await new Promise((resolve, reject) => {
1651
- server.close((error) => error ? reject(error) : resolve());
1652
- server.closeAllConnections();
1653
- });
1654
- viewerUrl = void 0;
1655
- startPromise = void 0;
1656
- },
1657
- start,
1658
- tab() {
1659
- return {
1660
- name: "vize-nuxt-lint-plan",
1661
- title: "Vize Nuxt Lint Plan",
1662
- icon: "carbon:rule",
1663
- requireAuth: true,
1664
- view: viewerUrl ? {
1665
- type: "iframe",
1666
- src: viewerUrl,
1667
- persistent: true
1668
- } : {
1669
- type: "launch",
1670
- description: "Inspect the effective Vize lint rules for any Nuxt source file.",
1671
- actions: [{
1672
- label: "Launch",
1673
- pending: startPromise !== void 0,
1674
- handle: start
1675
- }]
1676
- }
1677
- };
1678
- },
1679
- url: () => viewerUrl
1719
+ function serializeError(error) {
1720
+ if (error instanceof Error) return {
1721
+ message: error.message,
1722
+ stack: error.stack
1680
1723
  };
1724
+ return { message: String(error) };
1681
1725
  }
1682
- function listen(server, port) {
1683
- return new Promise((resolve, reject) => {
1684
- const onError = (error) => {
1685
- server.off("listening", onListening);
1686
- reject(error);
1687
- };
1688
- const onListening = () => {
1689
- server.off("error", onError);
1690
- resolve(server.address().port);
1691
- };
1692
- server.once("error", onError);
1693
- server.once("listening", onListening);
1694
- server.listen({
1695
- host: "127.0.0.1",
1696
- port: port ?? 0,
1697
- exclusive: true
1726
+ if (!isMainThread && parentPort) parentPort.on("message", async ({ id, task }) => {
1727
+ try {
1728
+ parentPort?.postMessage({
1729
+ id,
1730
+ result: await runNuxtLintCheckerTask(task)
1731
+ });
1732
+ } catch (error) {
1733
+ parentPort?.postMessage({
1734
+ error: serializeError(error),
1735
+ id
1698
1736
  });
1699
- });
1700
- }
1701
- async function handleRequest(request, response, provider, token, nonce, server) {
1702
- if (Buffer.byteLength(request.url ?? "") > MAX_URL_BYTES) {
1703
- sendJson(response, 414, { error: "request_uri_too_long" });
1704
- return;
1705
1737
  }
1706
- const port = server.address()?.port;
1707
- if (!port || ![`127.0.0.1:${port}`, `localhost:${port}`].includes(request.headers.host ?? "")) {
1708
- sendJson(response, 421, { error: "misdirected_request" });
1709
- return;
1738
+ });
1739
+ /** Persistent worker-thread client used by the Vite dev plugin. */
1740
+ var NuxtLintCheckerWorker = class {
1741
+ worker = new Worker(new URL(import.meta.url));
1742
+ pending = /* @__PURE__ */ new Map();
1743
+ nextId = 0;
1744
+ closed = false;
1745
+ constructor() {
1746
+ this.worker.on("message", (response) => {
1747
+ const pending = this.pending.get(response.id);
1748
+ if (!pending) return;
1749
+ this.pending.delete(response.id);
1750
+ if ("error" in response) {
1751
+ const error = new Error(response.error.message);
1752
+ error.stack = response.error.stack ?? error.stack;
1753
+ pending.reject(error);
1754
+ } else pending.resolve(response.result);
1755
+ });
1756
+ this.worker.on("error", (error) => this.rejectAll(error));
1757
+ this.worker.on("exit", (code) => {
1758
+ if (!this.closed) this.rejectAll(/* @__PURE__ */ new Error(`Nuxt lint worker exited with ${code}`));
1759
+ });
1710
1760
  }
1711
- if (request.method !== "GET" && request.method !== "HEAD") {
1712
- response.setHeader("allow", "GET, HEAD");
1713
- sendJson(response, 405, { error: "method_not_allowed" });
1714
- return;
1761
+ run(task) {
1762
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("Nuxt lint worker is closed"));
1763
+ const id = ++this.nextId;
1764
+ return new Promise((resolve, reject) => {
1765
+ this.pending.set(id, {
1766
+ reject,
1767
+ resolve
1768
+ });
1769
+ this.worker.postMessage({
1770
+ id,
1771
+ task
1772
+ });
1773
+ });
1715
1774
  }
1716
- let url;
1717
- try {
1718
- url = new URL(request.url ?? "", "http://localhost");
1719
- } catch {
1720
- sendJson(response, 400, { error: "invalid_url" }, request.method === "HEAD");
1721
- return;
1775
+ async close() {
1776
+ if (this.closed) return;
1777
+ this.closed = true;
1778
+ this.rejectAll(/* @__PURE__ */ new Error("Nuxt lint worker closed"));
1779
+ await this.worker.terminate();
1780
+ }
1781
+ rejectAll(error) {
1782
+ for (const pending of this.pending.values()) pending.reject(error);
1783
+ this.pending.clear();
1784
+ }
1785
+ };
1786
+ //#endregion
1787
+ //#region src/lint/checker/vite.ts
1788
+ const PLUGIN_NAME$1 = "vize:nuxt-lint-checker";
1789
+ function overlayError(output) {
1790
+ return {
1791
+ type: "error",
1792
+ err: {
1793
+ message: "Vize lint checker found diagnostics",
1794
+ stack: output,
1795
+ plugin: PLUGIN_NAME$1
1796
+ }
1797
+ };
1798
+ }
1799
+ var NuxtLintChangeCollector = class {
1800
+ pendingFiles = /* @__PURE__ */ new Set();
1801
+ pendingFull = false;
1802
+ draining = false;
1803
+ closed = false;
1804
+ overlayVisible = false;
1805
+ diagnosticsByFile = /* @__PURE__ */ new Map();
1806
+ config;
1807
+ runner;
1808
+ server;
1809
+ oxlintEntrypoint;
1810
+ constructor(config, runner, server, oxlintEntrypoint) {
1811
+ this.config = config;
1812
+ this.runner = runner;
1813
+ this.server = server;
1814
+ this.oxlintEntrypoint = oxlintEntrypoint;
1722
1815
  }
1723
- const rootPath = `/${token}/`;
1724
- if (url.pathname === rootPath && url.search === "") {
1725
- sendHtml(response, renderNuxtLintInspectorHtml(nonce), nonce, request.method === "HEAD");
1726
- return;
1816
+ full() {
1817
+ if (this.closed) return;
1818
+ this.pendingFull = true;
1819
+ this.pendingFiles.clear();
1820
+ this.schedule();
1727
1821
  }
1728
- if (url.pathname !== `${rootPath}api`) {
1729
- sendJson(response, 404, { error: "not_found" }, request.method === "HEAD");
1730
- return;
1822
+ file(file) {
1823
+ if (this.closed) return;
1824
+ if (path.resolve(file) === path.resolve(this.config.configFile)) {
1825
+ this.full();
1826
+ return;
1827
+ }
1828
+ if (!matchesNuxtLintCheckerFile(file, this.config.rootDir, this.config.options)) return;
1829
+ if (!this.config.options.cache) {
1830
+ this.full();
1831
+ return;
1832
+ }
1833
+ if (!this.pendingFull) this.pendingFiles.add(path.resolve(file));
1834
+ this.schedule();
1731
1835
  }
1732
- const parsed = parseApiRequest(url);
1733
- if ("error" in parsed) {
1734
- sendJson(response, parsed.status, { error: parsed.error }, request.method === "HEAD");
1735
- return;
1836
+ async close() {
1837
+ if (this.closed) return;
1838
+ this.closed = true;
1839
+ this.pendingFiles.clear();
1840
+ await this.runner.close();
1736
1841
  }
1737
- try {
1738
- sendJson(response, 200, await provider(parsed.request), request.method === "HEAD");
1739
- } catch {
1740
- sendJson(response, 500, { error: "inspector_lint_plan_failed" }, request.method === "HEAD");
1842
+ schedule() {
1843
+ if (this.draining) return;
1844
+ this.draining = true;
1845
+ queueMicrotask(() => void this.drain());
1741
1846
  }
1742
- }
1743
- function parseApiRequest(url) {
1744
- for (const key of url.searchParams.keys()) if (key !== "file" && key !== "fresh") return {
1745
- status: 400,
1746
- error: "invalid_query"
1747
- };
1748
- const fresh = url.searchParams.getAll("fresh");
1749
- if (fresh.length > 1 || fresh[0] !== void 0 && fresh[0] !== "1") return {
1750
- status: 400,
1751
- error: "invalid_fresh"
1752
- };
1753
- const requested = url.searchParams.getAll("file");
1754
- if (requested.length > MAX_FILES) return {
1755
- status: 413,
1756
- error: "too_many_files"
1757
- };
1758
- const files = [...new Set(requested)];
1759
- if (files.some((file) => !isSafeFile(file))) return {
1760
- status: 400,
1761
- error: "invalid_file"
1762
- };
1763
- return { request: {
1764
- files,
1765
- fresh: fresh[0] === "1"
1766
- } };
1767
- }
1768
- function isSafeFile(file) {
1769
- return file.length > 0 && Buffer.byteLength(file) <= MAX_FILE_BYTES && !file.includes("\0") && !file.includes("\\") && !file.startsWith("/") && !/^[A-Za-z]:/u.test(file) && !file.split("/").some((part) => part.length === 0 || part === "..");
1770
- }
1771
- function setCommonHeaders(response, resourcePolicy) {
1772
- response.setHeader("cache-control", "no-store");
1773
- response.setHeader("cross-origin-resource-policy", resourcePolicy);
1774
- response.setHeader("referrer-policy", "no-referrer");
1775
- response.setHeader("x-content-type-options", "nosniff");
1776
- }
1777
- function sendHtml(response, body, nonce, headOnly) {
1778
- response.statusCode = 200;
1779
- setCommonHeaders(response, "cross-origin");
1780
- response.setHeader("content-security-policy", `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; frame-ancestors http://localhost:* http://127.0.0.1:*`);
1781
- response.setHeader("content-type", "text/html; charset=utf-8");
1782
- response.setHeader("content-length", Buffer.byteLength(body));
1783
- response.end(headOnly ? void 0 : body);
1784
- }
1785
- function sendJson(response, status, payload, headOnly = false) {
1786
- let body = JSON.stringify(payload);
1787
- if (body === void 0) {
1788
- status = 500;
1789
- body = JSON.stringify({ error: "inspector_lint_plan_failed" });
1847
+ async drain() {
1848
+ while (!this.closed && (this.pendingFull || this.pendingFiles.size > 0)) {
1849
+ const full = this.pendingFull;
1850
+ const targets = full ? [...this.config.options.include] : [...this.pendingFiles].sort();
1851
+ this.pendingFull = false;
1852
+ this.pendingFiles.clear();
1853
+ try {
1854
+ const result = await this.runner.run(this.task(targets));
1855
+ if (!this.closed) this.report(result, targets, full);
1856
+ } catch (error) {
1857
+ if (!this.closed) this.reportFailure(error);
1858
+ }
1859
+ }
1860
+ this.draining = false;
1861
+ if (!this.closed && (this.pendingFull || this.pendingFiles.size > 0)) this.schedule();
1790
1862
  }
1791
- if (Buffer.byteLength(body) > MAX_RESPONSE_BYTES) {
1792
- status = 413;
1793
- body = JSON.stringify({ error: "inspector_response_too_large" });
1863
+ task(targets) {
1864
+ const options = this.config.options;
1865
+ return {
1866
+ configFile: this.config.configFile,
1867
+ cwd: this.config.rootDir,
1868
+ emitError: options.emitError,
1869
+ emitWarning: options.emitWarning,
1870
+ exclude: [...options.exclude],
1871
+ fix: options.fix,
1872
+ formatter: options.formatter,
1873
+ oxlintEntrypoint: this.oxlintEntrypoint,
1874
+ targets
1875
+ };
1794
1876
  }
1795
- response.statusCode = status;
1796
- setCommonHeaders(response, "same-origin");
1797
- response.setHeader("content-security-policy", "default-src 'none'");
1798
- response.setHeader("content-type", "application/json; charset=utf-8");
1799
- response.setHeader("content-length", Buffer.byteLength(body));
1800
- response.end(headOnly ? void 0 : body);
1801
- }
1802
- //#endregion
1803
- //#region src/lint/inspector.ts
1804
- function createNuxtLintInspectorProvider(generation, dependencies = {}) {
1805
- const inspect = dependencies.inspectLintPlan ?? inspectWithNative;
1806
- return async (request) => {
1807
- const items = await generation.resolvePlan(request.fresh);
1808
- const serialized = await inspect(JSON.stringify({ items }), generation.root, request.files);
1809
- const payload = JSON.parse(serialized);
1810
- if (!isLintPlanPayload(payload)) throw new Error("Native lint-plan inspector returned an invalid payload");
1811
- return payload;
1812
- };
1813
- }
1814
- async function setupLintInspector(lint, nuxt, compiler, generation, enabled) {
1815
- if (enabled === false || !generation) return;
1816
- const provider = createNuxtLintInspectorProvider(generation);
1817
- if (compiler !== false) {
1818
- compiler.inspector ||= {};
1819
- compiler.inspector.lintPlan ||= provider;
1877
+ diagnosticFile(diagnostic) {
1878
+ const file = diagnostic.filename ?? diagnostic.filePath;
1879
+ if (!file) return void 0;
1880
+ return path.resolve(this.config.rootDir, file);
1820
1881
  }
1821
- await setupNuxtLintDevtools(typeof lint === "object" && lint !== null ? lint.devtools : void 0, nuxt, compiler === false ? provider : compiler.inspector.lintPlan);
1822
- }
1823
- async function inspectWithNative(plan, root, files) {
1824
- const { inspectLintPlan } = await import("@vizejs/native");
1825
- return inspectLintPlan(plan, root, files);
1826
- }
1827
- function isLintPlanPayload(value) {
1828
- return value !== null && typeof value === "object" && !Array.isArray(value) && value.schema === "vize.inspector.lint-plan" && value.version === 1 && typeof value.root === "string" && Array.isArray(value.items) && Array.isArray(value.files);
1829
- }
1830
- //#endregion
1831
- //#region src/lint/generation.ts
1832
- /** Nuxt module wiring for generated oxlint configuration. */
1833
- const GENERATED_CONFIG_NAME = ".oxlint.vize.json";
1834
- /** Root config names supported by oxlint's config discovery. */
1835
- const ROOT_OXLINT_CONFIG_NAMES = [
1836
- ".oxlintrc.json",
1837
- ".oxlintrc.jsonc",
1838
- "oxlint.config.ts",
1839
- "oxlint.config.mts"
1840
- ];
1841
- const ROOT_LINT_CONFIG_NAMES = [
1842
- ...ROOT_OXLINT_CONFIG_NAMES,
1843
- "vite.config.js",
1844
- "vite.config.mjs",
1845
- "vite.config.ts",
1846
- "vite.config.cjs",
1847
- "vite.config.mts",
1848
- "vite.config.cts"
1849
- ];
1850
- function isNotFound(error) {
1851
- return error.code === "ENOENT";
1852
- }
1853
- /**
1854
- * Write bytes only when they differ from the current regular file.
1855
- *
1856
- * The length fast path mirrors Canon's materializer. A full byte comparison is
1857
- * still required before skipping so equal-size edits are never mistaken for a
1858
- * cache hit. Symlinks are rejected instead of followed.
1859
- */
1860
- async function writeFileIfChanged(file, content) {
1861
- await mkdir(path.dirname(file), { recursive: true });
1862
- try {
1863
- const metadata = await lstat(file);
1864
- if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error(`Generated oxlint config must be a regular file: ${file}`);
1865
- if (metadata.size === Buffer.byteLength(content)) {
1866
- if ((await readFile(file)).equals(Buffer.from(content))) return false;
1882
+ report(result, targets, full) {
1883
+ for (const notice of result.notices) this.server.config.logger.warn(notice);
1884
+ if (result.output) {
1885
+ if (result.hasErrors) this.server.config.logger.error(result.output);
1886
+ else if (result.hasWarnings) this.server.config.logger.warn(result.output);
1887
+ }
1888
+ if (full) this.diagnosticsByFile.clear();
1889
+ else for (const target of targets) this.diagnosticsByFile.delete(path.resolve(target));
1890
+ for (const diagnostic of result.diagnostics) {
1891
+ const file = this.diagnosticFile(diagnostic);
1892
+ if (!file) continue;
1893
+ const diagnostics = this.diagnosticsByFile.get(file) ?? [];
1894
+ diagnostics.push(diagnostic);
1895
+ this.diagnosticsByFile.set(file, diagnostics);
1896
+ }
1897
+ const currentDiagnostics = [...this.diagnosticsByFile.entries()].sort(([left], [right]) => left.localeCompare(right)).flatMap(([, diagnostics]) => diagnostics);
1898
+ if (currentDiagnostics.length > 0) {
1899
+ this.server.ws.send(overlayError(formatNuxtLintCheckerDiagnostics(currentDiagnostics, this.config.options.formatter)));
1900
+ this.overlayVisible = true;
1901
+ } else if (this.overlayVisible) {
1902
+ this.server.ws.send({
1903
+ type: "update",
1904
+ updates: []
1905
+ });
1906
+ this.overlayVisible = false;
1867
1907
  }
1868
- } catch (error) {
1869
- if (!isNotFound(error)) throw error;
1870
- }
1871
- const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
1872
- try {
1873
- await writeFile(temporary, content, { flag: "wx" });
1874
- await rename(temporary, file);
1875
- } finally {
1876
- await unlink(temporary).catch((error) => {
1877
- if (!isNotFound(error)) throw error;
1878
- });
1879
1908
  }
1880
- return true;
1881
- }
1882
- function hasTypeScript(rootDir) {
1883
- try {
1884
- createRequire(path.join(rootDir, "package.json")).resolve("typescript");
1885
- return true;
1886
- } catch {
1887
- return false;
1909
+ reportFailure(error) {
1910
+ const message = `Nuxt lint checker failed: ${error instanceof Error ? error.message : String(error)}`;
1911
+ this.server.config.logger.error(message);
1912
+ this.server.ws.send(overlayError(message));
1913
+ this.overlayVisible = true;
1888
1914
  }
1915
+ };
1916
+ /** Create the client-side Vite dev plugin; it has no transform/render hooks. */
1917
+ function createNuxtLintCheckerVitePlugin(config, dependencies = {}) {
1918
+ return {
1919
+ name: PLUGIN_NAME$1,
1920
+ apply: "serve",
1921
+ enforce: "post",
1922
+ configureServer(server) {
1923
+ const collector = new NuxtLintChangeCollector(config, dependencies.createRunner?.() ?? new NuxtLintCheckerWorker(), server, dependencies.oxlintEntrypoint);
1924
+ server.watcher.add(config.configFile);
1925
+ const changed = (file) => collector.file(file);
1926
+ server.watcher.on("add", changed);
1927
+ server.watcher.on("change", changed);
1928
+ server.watcher.on("unlink", changed);
1929
+ server.httpServer?.once("close", () => void collector.close());
1930
+ if (config.options.lintOnStart) collector.full();
1931
+ }
1932
+ };
1889
1933
  }
1890
- function relativeSpecifier(from, target) {
1891
- const relative = path.relative(from, target);
1892
- if (path.isAbsolute(relative)) return pathToFileURL(target).href;
1893
- const normalized = relative.split(path.sep).join("/");
1894
- return normalized.startsWith("./") || normalized.startsWith("../") ? normalized : `./${normalized}`;
1895
- }
1896
- function resolveVizePluginSpecifier(configDir) {
1897
- return relativeSpecifier(configDir, fileURLToPath(import.meta.resolve("oxlint-plugin-vize")));
1934
+ //#endregion
1935
+ //#region src/lint/checker/webpack.ts
1936
+ const PLUGIN_NAME = "VizeNuxtLintChecker";
1937
+ function checkerError(message) {
1938
+ const error = new Error(message);
1939
+ error.name = PLUGIN_NAME;
1940
+ return error;
1898
1941
  }
1899
- async function findRootLintConfig(rootDir) {
1900
- let directory = path.resolve(rootDir);
1901
- while (true) {
1902
- for (const name of ROOT_LINT_CONFIG_NAMES) {
1903
- const candidate = path.join(directory, name);
1904
- try {
1905
- const metadata = await lstat(candidate);
1906
- if (metadata.isFile() || metadata.isSymbolicLink()) return candidate;
1907
- } catch (error) {
1908
- if (!isNotFound(error)) throw error;
1909
- }
1910
- }
1911
- const parent = path.dirname(directory);
1912
- if (parent === directory) return void 0;
1913
- directory = parent;
1914
- }
1942
+ function reportResult(compilation, result) {
1943
+ for (const notice of result.notices) compilation.warnings.push(checkerError(notice));
1944
+ if (result.hasErrors) compilation.errors.push(checkerError(result.output));
1945
+ else if (result.hasWarnings) compilation.warnings.push(checkerError(result.output));
1915
1946
  }
1916
- function renderRootOxlintConfig(rootDir, generatedConfig) {
1917
- const specifier = relativeSpecifier(rootDir, generatedConfig);
1918
- return [
1919
- "// Generated by @vizejs/nuxt.",
1920
- "import { readFileSync } from \"node:fs\";",
1921
- "",
1922
- "type OxlintJsPlugin = string | { name?: string; specifier: string };",
1923
- "",
1924
- `const generatedUrl = new URL(${JSON.stringify(specifier)}, import.meta.url);`,
1925
- "const config = JSON.parse(readFileSync(generatedUrl, \"utf8\"));",
1926
- "config.jsPlugins = config.jsPlugins.map((plugin: OxlintJsPlugin) =>",
1927
- " typeof plugin === \"string\"",
1928
- " ? new URL(plugin, generatedUrl).href",
1929
- " : { ...plugin, specifier: new URL(plugin.specifier, generatedUrl).href },",
1930
- ");",
1931
- "",
1932
- "export default config;",
1933
- ""
1934
- ].join("\n");
1947
+ function task(config, targets, oxlintEntrypoint) {
1948
+ const options = config.options;
1949
+ return {
1950
+ configFile: config.configFile,
1951
+ cwd: config.rootDir,
1952
+ emitError: options.emitError,
1953
+ emitWarning: options.emitWarning,
1954
+ exclude: [...options.exclude],
1955
+ fix: options.fix,
1956
+ formatter: options.formatter,
1957
+ oxlintEntrypoint,
1958
+ targets
1959
+ };
1935
1960
  }
1936
- async function initRootOxlintConfig(rootDir, generatedConfig, previousDefault) {
1937
- const existing = await findRootLintConfig(rootDir);
1938
- if (existing) {
1939
- if (existing === path.join(rootDir, "oxlint.config.mts") && previousDefault && (await lstat(existing)).isFile() && await readFile(existing, "utf8") === renderRootOxlintConfig(rootDir, previousDefault)) await writeFileIfChanged(existing, renderRootOxlintConfig(rootDir, generatedConfig));
1940
- return;
1941
- }
1942
- if (path.dirname(generatedConfig) !== rootDir) throw new Error("Set lint.autoInit to false when lint.configFile is outside the Nuxt root");
1943
- const handle = await open(path.join(rootDir, "oxlint.config.mts"), "wx").catch((error) => {
1944
- if (error.code === "EEXIST") return void 0;
1945
- throw error;
1946
- });
1947
- if (!handle) return;
1948
- try {
1949
- await handle.writeFile(renderRootOxlintConfig(rootDir, generatedConfig), "utf8");
1950
- } finally {
1951
- await handle.close();
1952
- }
1961
+ function changedTargets(compiler, config, initial) {
1962
+ const modified = compiler.modifiedFiles;
1963
+ if (initial && config.options.lintOnStart) return [...config.options.include];
1964
+ if (!modified || modified.size === 0) return void 0;
1965
+ if (!config.options.cache) return [...config.options.include];
1966
+ const configFile = path.resolve(config.configFile);
1967
+ if ([...modified].some((file) => path.resolve(file) === configFile)) return [...config.options.include];
1968
+ const files = [...modified].filter((file) => matchesNuxtLintCheckerFile(file, config.rootDir, config.options)).map((file) => path.resolve(file)).sort();
1969
+ return files.length > 0 ? files : void 0;
1953
1970
  }
1954
1971
  /**
1955
- * Generate the initial config and register the Nuxt regeneration hook.
1972
+ * Create Nuxt 2's webpack adapter.
1956
1973
  *
1957
- * Addons are resolved inside `regenerate`, not at setup time, so Nuxt's import
1958
- * registry and third-party module hooks can change between generateApp passes.
1974
+ * The worker starts at `watchRun`, concurrently with compilation; only the
1975
+ * final diagnostic handoff happens at `afterCompile`, where webpack can feed
1976
+ * the result to its existing terminal and browser overlays.
1959
1977
  */
1960
- async function setupNuxtLintConfigGeneration(lint, nuxt, dependencies = {}) {
1961
- if (lint === false) return void 0;
1962
- const { autoInit = true, configFile: configuredFile, rootDir: configuredRoot, ...featureOptions } = typeof lint === "object" && lint !== null ? lint : {};
1963
- const nuxtRoot = path.resolve(nuxt.options.rootDir);
1964
- const planRoot = configuredRoot ? path.resolve(nuxtRoot, configuredRoot) : nuxtRoot;
1965
- const configFile = path.resolve(nuxtRoot, configuredFile ?? GENERATED_CONFIG_NAME);
1966
- const ownsReservedConfig = configFile === path.join(nuxtRoot, GENERATED_CONFIG_NAME);
1967
- const hasTypeScriptProbe = dependencies.hasTypeScript ?? hasTypeScript;
1968
- const resolvePluginSpecifier = dependencies.resolvePluginSpecifier ?? resolveVizePluginSpecifier;
1969
- const resolveAddons = dependencies.resolveAddons ?? ("callHook" in nuxt ? setupNuxtLintConfigAddons(nuxt, { rootDir: planRoot }) : void 0);
1970
- const resolveProjectRuleSets = dependencies.resolveProjectLintRules ? async (rootDir) => {
1971
- const rules = await dependencies.resolveProjectLintRules?.(rootDir);
1972
- return rules && Object.keys(rules).length > 0 ? { vize: rules } : {};
1973
- } : readProjectLintRuleSets;
1974
- let currentPlan = [];
1975
- const emittedWarnings = /* @__PURE__ */ new Set();
1976
- const regenerate = async () => {
1977
- const plan = buildNuxtLintPlan(resolveNuxtLintFeatures(featureOptions, () => hasTypeScriptProbe(planRoot)), collectNuxtLintDirs(toNuxtLintProjectState(nuxt.options, { rootDir: planRoot })), getDetectedNuxtMajor(nuxt) ?? 3);
1978
- const addons = await resolveAddons?.() ?? [];
1979
- const projectRules = await resolveProjectRuleSets(planRoot);
1980
- const projectItems = [];
1981
- if (projectRules.vize) projectItems.push({
1982
- name: "project/preset",
1983
- rules: projectRules.vize
1984
- });
1985
- if (projectRules.oxlint) projectItems.push({
1986
- name: "project/oxlint",
1987
- nativeRules: projectRules.oxlint
1988
- });
1989
- for (const [index, entry] of (projectRules.entries ?? []).entries()) projectItems.push({
1990
- name: entry.name ? `project/${entry.name}` : `project/entry-${String(index + 1)}`,
1991
- files: entry.files,
1992
- ...entry.ignores ? { ignores: entry.ignores } : {},
1993
- rules: entry.rules
1978
+ function createNuxtLintCheckerWebpackPlugin(config, dependencies = {}) {
1979
+ return { apply(compiler) {
1980
+ const runner = dependencies.createRunner?.() ?? new NuxtLintCheckerWorker();
1981
+ let initial = true;
1982
+ let pending;
1983
+ compiler.hooks.watchRun.tap(PLUGIN_NAME, (nextCompiler) => {
1984
+ const targets = changedTargets(nextCompiler, config, initial);
1985
+ initial = false;
1986
+ pending = targets ? runner.run(task(config, targets, dependencies.oxlintEntrypoint)) : void 0;
1994
1987
  });
1995
- for (const [index, override] of (projectRules.oxlintOverrides ?? []).entries()) projectItems.push({
1996
- name: `project/oxlint-override-${String(index + 1)}`,
1997
- files: override.files,
1998
- nativeRules: override.rules
1988
+ compiler.hooks.afterCompile.tapPromise(PLUGIN_NAME, async (compilation) => {
1989
+ compilation.fileDependencies.add(config.configFile);
1990
+ if (!pending) return;
1991
+ const current = pending;
1992
+ pending = void 0;
1993
+ try {
1994
+ reportResult(compilation, await current);
1995
+ } catch (error) {
1996
+ compilation.errors.push(checkerError(`Nuxt lint checker failed: ${error instanceof Error ? error.message : String(error)}`));
1997
+ }
1999
1998
  });
2000
- for (const warning of projectRules.warnings ?? []) {
2001
- if (emittedWarnings.has(warning)) continue;
2002
- emittedWarnings.add(warning);
2003
- (dependencies.warn ?? console.warn)(`@vizejs/nuxt lint config: ${warning}`);
2004
- }
2005
- const nextPlan = [
2006
- ...projectItems,
2007
- ...plan,
2008
- ...addons
2009
- ];
2010
- const artifact = renderNuxtOxlintConfig(nextPlan, resolvePluginSpecifier(path.dirname(configFile)), {
2011
- rootDir: planRoot,
2012
- configDir: path.dirname(configFile),
2013
- owner: ownsReservedConfig ? "@vizejs/nuxt" : void 0
2014
- }, projectRules.jsPlugins);
2015
- const changed = ownsReservedConfig ? await writeOwnedNuxtConfig(configFile, artifact, writeFileIfChanged) : await writeFileIfChanged(configFile, artifact);
2016
- currentPlan = nextPlan;
2017
- return changed;
2018
- };
2019
- const resolvePlan = async (fresh = false) => {
2020
- if (fresh) await regenerate();
2021
- return currentPlan;
1999
+ compiler.hooks.watchClose.tap(PLUGIN_NAME, () => void runner.close());
2000
+ } };
2001
+ }
2002
+ //#endregion
2003
+ //#region src/lint/checker/setup.ts
2004
+ function registerNuxt2Checker(nuxt, builder, plugin) {
2005
+ if (!nuxt.hook) throw new Error("Nuxt 2 checker registration requires the host hook API.");
2006
+ if (builder === "webpack") nuxt.hook("webpack:config", (value) => {
2007
+ for (const config of value) if (config.name === "client") (config.plugins ??= []).push(plugin);
2008
+ });
2009
+ else nuxt.hook("vite:extendConfig", (value, context) => {
2010
+ if (context?.isServer) return;
2011
+ const config = value;
2012
+ (config.plugins ??= []).push(plugin);
2013
+ });
2014
+ }
2015
+ async function addVitePlugin(plugin) {
2016
+ (await import("@nuxt/kit")).addVitePlugin(plugin, { server: false });
2017
+ }
2018
+ async function addWebpackPlugin(plugin) {
2019
+ (await import("@nuxt/kit")).addWebpackPlugin(plugin, { server: false });
2020
+ }
2021
+ /** Register the dev-only adapter over Phase 3's generated config artifact. */
2022
+ async function setupNuxtLintChecker(checker, nuxt, generation, dependencies = {}) {
2023
+ if (checker !== true && (checker === false || checker == null)) return void 0;
2024
+ if (nuxt.options.dev !== true) return void 0;
2025
+ if (!generation) throw new Error("The Nuxt lint checker requires lint config generation; enable `vize.lint`.");
2026
+ const options = resolveNuxtLintCheckerOptions(checker, {
2027
+ buildDir: nuxt.options.buildDir,
2028
+ srcDir: nuxt.options.srcDir ?? nuxt.options.rootDir
2029
+ });
2030
+ if (options === false) return void 0;
2031
+ const rootDir = path.resolve(nuxt.options.rootDir);
2032
+ const config = {
2033
+ configFile: generation.configFile,
2034
+ options,
2035
+ rootDir
2022
2036
  };
2023
- await regenerate();
2024
- nuxt.hook("builder:generateApp", regenerate);
2025
- if (getDetectedNuxtMajor(nuxt) === 2) nuxt.hook("build:templates", regenerate);
2026
- if (autoInit) await initRootOxlintConfig(nuxtRoot, configFile, ownsReservedConfig ? path.resolve(nuxtRoot, nuxt.options.buildDir, "oxlint.config.json") : void 0);
2037
+ const builder = getDetectedNuxtBuilderKind(nuxt);
2038
+ if (builder === "vite") {
2039
+ const plugin = createNuxtLintCheckerVitePlugin(config);
2040
+ if (!dependencies.addVitePlugin && getDetectedNuxtMajor(nuxt) === 2) registerNuxt2Checker(nuxt, builder, plugin);
2041
+ else await (dependencies.addVitePlugin ?? addVitePlugin)(plugin);
2042
+ } else if (builder === "webpack") {
2043
+ const plugin = createNuxtLintCheckerWebpackPlugin(config);
2044
+ if (!dependencies.addWebpackPlugin && getDetectedNuxtMajor(nuxt) === 2) registerNuxt2Checker(nuxt, builder, plugin);
2045
+ else await (dependencies.addWebpackPlugin ?? addWebpackPlugin)(plugin);
2046
+ } else {
2047
+ const label = typeof nuxt.options.builder === "string" ? nuxt.options.builder : "unknown";
2048
+ (dependencies.warn ?? console.warn)(`Unsupported Nuxt builder ${label}; Vize lint checker is disabled.`);
2049
+ }
2027
2050
  return {
2028
- configFile,
2029
- root: planRoot,
2030
- regenerate,
2031
- resolvePlan
2051
+ builder,
2052
+ configFile: generation.configFile,
2053
+ options
2032
2054
  };
2033
2055
  }
2034
2056
  //#endregion
2035
- export { toNuxtLintProjectState as a, setupNuxtLintConfigAddons as c, createNuxtLintCheckerVitePlugin as d, resolveNuxtLintCheckerOptions as f, setupLintInspector as i, setupNuxtLintChecker as l, hasNuxtViteCompilerSupport as m, setupNuxtLintConfigGeneration as n, renderNuxtOxlintConfig as o, getDetectedNuxtMajor as p, writeFileIfChanged as r, VIZE_NUXT_LINT_CONFIG_ADDONS_HOOK as s, ROOT_OXLINT_CONFIG_NAMES as t, createNuxtLintCheckerWebpackPlugin as u };
2057
+ export { ROOT_OXLINT_CONFIG_NAMES as a, setupLintInspector as c, VIZE_NUXT_LINT_CONFIG_ADDONS_HOOK as d, setupNuxtLintConfigAddons as f, resolveNuxtLintCheckerOptions as i, toNuxtLintProjectState as l, hasNuxtViteCompilerSupport as m, createNuxtLintCheckerWebpackPlugin as n, setupNuxtLintConfigGeneration as o, getDetectedNuxtMajor as p, createNuxtLintCheckerVitePlugin as r, writeFileIfChanged as s, setupNuxtLintChecker as t, renderNuxtOxlintConfig as u };