vite-doctor 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/cli.mjs +204 -3
- package/dist/{config-B96z9mkv.d.mts → config-BmPOr4h2.d.mts} +2 -1
- package/dist/config.d.mts +1 -1
- package/dist/{core-DXS10waH.mjs → core-xDy0T1J2.mjs} +706 -66
- package/dist/{doctor-D_fAijfx.mjs → doctor-Bg0UJqwf.mjs} +7 -7
- package/dist/{index-BZ2DY0NT.d.mts → index-Cej8hbDn.d.mts} +1 -1
- package/dist/{index-oT29pHXX.d.mts → index-DELTN2OW.d.mts} +20 -5
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{module-Cy-5RxgV.mjs → module-Bhfqw7wj.mjs} +24 -6
- package/dist/{module-D63348VO.d.mts → module-DpsQYVY7.d.mts} +2 -2
- package/dist/nitro-DP7qe6zn.mjs +2 -0
- package/dist/nuxt.d.mts +1 -1
- package/dist/nuxt.mjs +1 -1
- package/dist/{plugin-QYmdGYMa.mjs → plugin-B-mvNSii.mjs} +2 -2
- package/dist/{plugin-CWjUWdmC.d.mts → plugin-BMTLuRfv.d.mts} +2 -2
- package/dist/plugin.d.mts +1 -1
- package/dist/plugin.mjs +1 -1
- package/dist/{primitives-mLCLAmZ3.d.mts → primitives-UOE4-YE8.d.mts} +49 -1
- package/dist/rule-packs/nitro/index.d.mts +2 -2
- package/dist/rule-packs/nitro/index.mjs +3 -3
- package/dist/rule-packs/nitro/rules.d.mts +2 -2
- package/dist/rule-packs/nitro/rules.mjs +2 -2
- package/dist/rule-packs/nuxt/index.d.mts +2 -2
- package/dist/rule-packs/nuxt/index.mjs +1 -1
- package/dist/rule-packs/nuxt/module.d.mts +2 -2
- package/dist/rule-packs/nuxt/module.mjs +1 -1
- package/dist/rule-packs/nuxt/rules/index.d.mts +2 -2
- package/dist/rule-packs/nuxt/rules/index.mjs +2 -2
- package/dist/rule-packs/vite/index.d.mts +1 -1
- package/dist/rule-packs/vite/index.mjs +1 -1
- package/dist/rule-packs/vite/rules/index.d.mts +1 -1
- package/dist/rule-packs/vite/rules/index.mjs +1 -1
- package/dist/rule-packs/vue/index.d.mts +1 -1
- package/dist/rule-packs/vue/index.mjs +1 -1
- package/dist/rule-packs/vue/rules.d.mts +1 -1
- package/dist/rule-packs/vue/rules.mjs +1 -1
- package/dist/{rules-TJ8mVfH6.mjs → rules-BY3D2U9g.mjs} +1 -1
- package/dist/rules-D233rRrp.mjs +884 -0
- package/dist/{rules-BELxdqAV.d.mts → rules-D_ZBKNuF.d.mts} +1 -1
- package/dist/rules-DdChlCWs.mjs +2 -0
- package/dist/{rules-Wl3xtW3p.mjs → rules-drBDqot9.mjs} +94 -15
- package/dist/{rules-CpZKSMoL.mjs → rules-pUteKop1.mjs} +20 -10
- package/dist/rules.d.mts +1 -1
- package/dist/rules.mjs +2 -2
- package/package.json +4 -2
- package/dist/nitro-CFxa1y5r.mjs +0 -2
- package/dist/rules-8_T4dDGE.mjs +0 -2
- package/dist/rules-Ci1PkZG_.mjs +0 -529
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
import { a as codeForRuleId, d as createRule, m as doctorInternalDiagnostics, o as defineDoctorDiagnostics, p as defineRulePack, s as diagnosticForCode } from "./core-xDy0T1J2.mjs";
|
|
2
|
+
//#region src/rule-packs/nitro/diagnostics.ts
|
|
3
|
+
const nitroDiagnosticRegistry = defineDoctorDiagnostics([
|
|
4
|
+
{
|
|
5
|
+
code: "NITRO0001",
|
|
6
|
+
ruleId: "nitro/context/no-navigateto-in-nitro"
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
code: "NITRO0002",
|
|
10
|
+
ruleId: "nitro/context/no-usenuxtapp-in-nitro"
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
code: "NITRO0003",
|
|
14
|
+
ruleId: "nitro/request/prefer-assert-method"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
code: "NITRO0004",
|
|
18
|
+
ruleId: "nitro/request/prefer-get-request-ip"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
code: "NITRO0005",
|
|
22
|
+
ruleId: "nitro/request/prefer-validated-body"
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
code: "NITRO0006",
|
|
26
|
+
ruleId: "nitro/request/prefer-validated-query"
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
code: "NITRO0007",
|
|
30
|
+
ruleId: "nitro/request/prefer-validated-router-params"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
code: "NITRO0008",
|
|
34
|
+
ruleId: "nitro/runtime/require-event-runtime-config-in-server"
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
code: "NITRO0009",
|
|
38
|
+
ruleId: "nitro/server/no-browser-api"
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
code: "NITRO0010",
|
|
42
|
+
ruleId: "nitro/server/no-client-composables"
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
code: "NITRO0011",
|
|
46
|
+
ruleId: "nitro/server/prefer-event-fetch"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
code: "NITRO0012",
|
|
50
|
+
ruleId: "nitro/request/prefer-route-method-suffix"
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
code: "NITRO0013",
|
|
54
|
+
ruleId: "nitro/runtime/no-event-runtime-config-in-server"
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
code: "NITRO0014",
|
|
58
|
+
ruleId: "nitro/migration/no-v2-imports"
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
code: "NITRO0015",
|
|
62
|
+
ruleId: "nitro/h3/no-removed-send"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
code: "NITRO0016",
|
|
66
|
+
ruleId: "nitro/h3/prefer-redirect-response"
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
code: "NITRO0017",
|
|
70
|
+
ruleId: "nitro/h3/prefer-with-base"
|
|
71
|
+
}
|
|
72
|
+
]);
|
|
73
|
+
const diagnostics = nitroDiagnosticRegistry.diagnostics;
|
|
74
|
+
const diagnosticCodesByRuleId = nitroDiagnosticRegistry.codesByRuleId;
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region src/core/rule-authoring.ts
|
|
77
|
+
const FN_OR_PROG_TYPES = new Set([
|
|
78
|
+
"Program",
|
|
79
|
+
"FunctionDeclaration",
|
|
80
|
+
"FunctionExpression",
|
|
81
|
+
"ArrowFunctionExpression"
|
|
82
|
+
]);
|
|
83
|
+
function findAncestor(node, predicate) {
|
|
84
|
+
let current = node?.__doctorParent ?? node?.parent;
|
|
85
|
+
while (current) {
|
|
86
|
+
if (predicate(current)) return current;
|
|
87
|
+
current = current.__doctorParent ?? current.parent;
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
function nearestFunctionOrProgram(node) {
|
|
92
|
+
let current = node;
|
|
93
|
+
while (current) {
|
|
94
|
+
if (FN_OR_PROG_TYPES.has(current.type)) return current;
|
|
95
|
+
current = current.__doctorParent;
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
function walkScriptLocal(node, visit) {
|
|
100
|
+
if (!node || typeof node !== "object") return;
|
|
101
|
+
if (Array.isArray(node)) {
|
|
102
|
+
for (const child of node) walkScriptLocal(child, visit);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (typeof node.type === "string") visit(node);
|
|
106
|
+
for (const [key, value] of Object.entries(node)) {
|
|
107
|
+
if (key === "__doctorParent") continue;
|
|
108
|
+
if (Array.isArray(value)) for (const child of value) walkScriptLocal(child, visit);
|
|
109
|
+
else if (value && typeof value === "object") walkScriptLocal(value, visit);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function sourceForNode(node, source) {
|
|
113
|
+
const start = node.start ?? node.range?.[0];
|
|
114
|
+
const end = node.end ?? node.range?.[1];
|
|
115
|
+
return typeof start === "number" && typeof end === "number" ? source.slice(start, end) : "";
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/rule-packs/nitro/rules/shared.ts
|
|
119
|
+
const BROWSER_GLOBALS = new Set([
|
|
120
|
+
"window",
|
|
121
|
+
"document",
|
|
122
|
+
"localStorage",
|
|
123
|
+
"sessionStorage",
|
|
124
|
+
"navigator",
|
|
125
|
+
"location",
|
|
126
|
+
"ResizeObserver",
|
|
127
|
+
"IntersectionObserver"
|
|
128
|
+
]);
|
|
129
|
+
function report(ctx, node, ruleId, severity, category, message, suggestion) {
|
|
130
|
+
const code = codeForRuleId(diagnosticCodesByRuleId, ruleId);
|
|
131
|
+
if (!code) throw doctorInternalDiagnostics.DOC0013({ ruleId });
|
|
132
|
+
const diagnostic = diagnosticForCode(diagnostics, code);
|
|
133
|
+
if (!diagnostic) throw doctorInternalDiagnostics.DOC0013({
|
|
134
|
+
ruleId,
|
|
135
|
+
code
|
|
136
|
+
});
|
|
137
|
+
ctx.helpers.report(ctx, node, diagnostic({
|
|
138
|
+
why: message,
|
|
139
|
+
fix: suggestion
|
|
140
|
+
}), {
|
|
141
|
+
ruleId,
|
|
142
|
+
severity,
|
|
143
|
+
category
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function isObjectPropertyKey(node) {
|
|
147
|
+
const parent = node.parent ?? node.__doctorParent;
|
|
148
|
+
return parent?.type === "Property" && (parent.key === node && !parent.computed || parent.shorthand) || parent?.type === "MemberExpression" && parent.property === node && !parent.computed || parent?.type === "StaticMemberExpression" && parent.property === node;
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
//#region src/rule-packs/nitro/rules/no-use-nuxt-app-in-nitro.ts
|
|
152
|
+
const noUseNuxtAppInNitro = createRule({
|
|
153
|
+
meta: {
|
|
154
|
+
id: "nitro/context/no-usenuxtapp-in-nitro",
|
|
155
|
+
title: "Do not use useNuxtApp in Nitro routes",
|
|
156
|
+
description: "Nitro handlers run outside the Nuxt app runtime, so useNuxtApp() is unavailable.",
|
|
157
|
+
why: "Nitro request handlers execute in the server runtime with an event object, not inside Vue or Nuxt app setup. App composables rely on Nuxt app instance state that does not exist there.",
|
|
158
|
+
recommendedReplacement: "Use event-aware Nitro, h3, or server utilities that receive the request event.",
|
|
159
|
+
category: "server",
|
|
160
|
+
severity: "error",
|
|
161
|
+
fixable: "suggestion",
|
|
162
|
+
requires: {
|
|
163
|
+
script: true,
|
|
164
|
+
nitro: true
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
create(ctx) {
|
|
168
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
169
|
+
return { ScriptNode(node) {
|
|
170
|
+
if (ctx.helpers.isCall(node, "useNuxtApp")) report(ctx, node, "nitro/context/no-usenuxtapp-in-nitro", "error", "server", "useNuxtApp() is an app runtime composable and is not available in Nitro handlers. Use event-aware server utilities instead.", "Replace useNuxtApp() with event-aware Nitro, h3, or server utilities.");
|
|
171
|
+
} };
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
//#endregion
|
|
175
|
+
//#region src/rule-packs/nitro/rules/no-navigate-to-in-nitro.ts
|
|
176
|
+
const noNavigateToInNitro = createRule({
|
|
177
|
+
meta: {
|
|
178
|
+
id: "nitro/context/no-navigateto-in-nitro",
|
|
179
|
+
title: "Do not use navigateTo in Nitro routes",
|
|
180
|
+
description: "Nitro handlers should redirect with server response utilities instead of Nuxt app navigation.",
|
|
181
|
+
why: "navigateTo() is a Nuxt app navigation helper. Nitro handlers need to write an HTTP redirect response for the current request event.",
|
|
182
|
+
recommendedReplacement: "Return the redirect response supported by the installed H3 runtime from the Nitro handler.",
|
|
183
|
+
category: "server",
|
|
184
|
+
severity: "error",
|
|
185
|
+
fixable: "suggestion",
|
|
186
|
+
requires: {
|
|
187
|
+
script: true,
|
|
188
|
+
nitro: true
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
create(ctx) {
|
|
192
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
193
|
+
return { ScriptNode(node) {
|
|
194
|
+
if (ctx.helpers.isCall(node, "navigateTo")) {
|
|
195
|
+
const h3 = ctx.project.runtimeGraph?.packages.h3;
|
|
196
|
+
report(ctx, node, "nitro/context/no-navigateto-in-nitro", "error", "server", "navigateTo() is for Nuxt app navigation and cannot produce a Nitro server response.", h3?.state === "resolved" && Number(h3.version?.split(".")[0]) >= 2 ? "Return redirect(path) from the Nitro handler." : h3?.state === "resolved" ? "Use sendRedirect(event, path) from the Nitro handler." : "Use the redirect response API supported by the installed H3 runtime.");
|
|
197
|
+
}
|
|
198
|
+
} };
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
//#endregion
|
|
202
|
+
//#region src/rule-packs/nitro/rules/require-event-runtime-config-in-server.ts
|
|
203
|
+
const requireEventRuntimeConfigInServer = createRule({
|
|
204
|
+
meta: {
|
|
205
|
+
id: "nitro/runtime/require-event-runtime-config-in-server",
|
|
206
|
+
title: "Pass event to useRuntimeConfig in server handlers",
|
|
207
|
+
description: "Read runtime config with the Nitro event inside server handlers.",
|
|
208
|
+
why: "Passing the event lets Nitro resolve request-aware runtime config consistently in server code.",
|
|
209
|
+
recommendedReplacement: "Use useRuntimeConfig(event).",
|
|
210
|
+
category: "runtime-config",
|
|
211
|
+
severity: "warn",
|
|
212
|
+
fixable: "suggestion",
|
|
213
|
+
docsUrl: "https://nitro.build/guide/configuration#runtime-configuration",
|
|
214
|
+
requires: {
|
|
215
|
+
script: true,
|
|
216
|
+
nitro: true
|
|
217
|
+
},
|
|
218
|
+
applicability: { runtimes: { nitro: ">=2 <3" } }
|
|
219
|
+
},
|
|
220
|
+
create(ctx) {
|
|
221
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
222
|
+
return { ScriptNode(node) {
|
|
223
|
+
if (!ctx.helpers.isCall(node, "useRuntimeConfig")) return;
|
|
224
|
+
if (node.arguments?.length) return;
|
|
225
|
+
report(ctx, node, "nitro/runtime/require-event-runtime-config-in-server", "warn", "runtime-config", "Server handlers should read runtime config with the request event.", "Use useRuntimeConfig(event).");
|
|
226
|
+
} };
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
//#endregion
|
|
230
|
+
//#region src/rule-packs/nitro/rules/no-event-runtime-config-in-server.ts
|
|
231
|
+
const noEventRuntimeConfigInServer = createRule({
|
|
232
|
+
meta: {
|
|
233
|
+
id: "nitro/runtime/no-event-runtime-config-in-server",
|
|
234
|
+
title: "Remove the event argument from Nitro 3 runtime config",
|
|
235
|
+
description: "Nitro 3 reads runtime config without a request event argument.",
|
|
236
|
+
why: "Nitro 3 replaced the event-aware Nitro 2 signature with zero-argument useRuntimeConfig().",
|
|
237
|
+
recommendedReplacement: "Use useRuntimeConfig() in Nitro 3 server code.",
|
|
238
|
+
category: "runtime-config",
|
|
239
|
+
severity: "warn",
|
|
240
|
+
fixable: "suggestion",
|
|
241
|
+
docsUrl: "https://nitro.build/docs/migration",
|
|
242
|
+
requires: {
|
|
243
|
+
script: true,
|
|
244
|
+
nitro: true
|
|
245
|
+
},
|
|
246
|
+
applicability: {
|
|
247
|
+
runtimes: { nitro: ">=3.0.0-0" },
|
|
248
|
+
includePrerelease: true
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
create(ctx) {
|
|
252
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
253
|
+
return { ScriptNode(node) {
|
|
254
|
+
if (!ctx.helpers.isCall(node, "useRuntimeConfig") || !node.arguments?.length) return;
|
|
255
|
+
report(ctx, node, "nitro/runtime/no-event-runtime-config-in-server", "warn", "runtime-config", "Nitro 3 useRuntimeConfig() no longer accepts the request event.", "Remove the event argument and call useRuntimeConfig().");
|
|
256
|
+
} };
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
//#endregion
|
|
260
|
+
//#region src/rule-packs/nitro/rules/no-v2-imports.ts
|
|
261
|
+
const noV2Imports = createRule({
|
|
262
|
+
meta: {
|
|
263
|
+
id: "nitro/migration/no-v2-imports",
|
|
264
|
+
title: "Replace Nitro 2 package imports",
|
|
265
|
+
description: "Nitro 3 renamed the package and removed several Nitro 2 public subpaths.",
|
|
266
|
+
why: "Nitro 3 publishes the nitro package and a smaller public export map, so Nitro 2 package names and removed subpaths no longer resolve.",
|
|
267
|
+
recommendedReplacement: "Import from nitro and its documented Nitro 3 public subpaths. Use nitro/builder for the old builder entry points.",
|
|
268
|
+
category: "migration",
|
|
269
|
+
severity: "error",
|
|
270
|
+
fixable: "suggestion",
|
|
271
|
+
docsUrl: "https://nitro.build/docs/migration",
|
|
272
|
+
requires: {
|
|
273
|
+
script: true,
|
|
274
|
+
nitro: true
|
|
275
|
+
},
|
|
276
|
+
applicability: {
|
|
277
|
+
runtimes: { nitro: ">=3.0.0-0" },
|
|
278
|
+
includePrerelease: true
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
create(ctx) {
|
|
282
|
+
return { ImportDeclaration(node) {
|
|
283
|
+
const source = node.source?.value;
|
|
284
|
+
if (typeof source !== "string") return;
|
|
285
|
+
const replacement = v3Replacement(source, node);
|
|
286
|
+
if (!replacement) return;
|
|
287
|
+
report(ctx, node.source ?? node, "nitro/migration/no-v2-imports", "error", "migration", `${source} is not a supported Nitro 3 public import.`, replacement);
|
|
288
|
+
} };
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
function v3Replacement(source, node) {
|
|
292
|
+
if (source === "nitropack") return rootPackageReplacement(node);
|
|
293
|
+
if (source === "nitropack/config") return node.specifiers?.some((specifier) => specifier.imported?.name === "defineNitroConfig") ? "Replace defineNitroConfig with defineConfig and import it from \"nitro\"." : "Import configuration APIs from \"nitro\".";
|
|
294
|
+
if (source === "nitropack/types") return "Import types from \"nitro/types\".";
|
|
295
|
+
if (source === "nitro/rollup" || source === "nitropack/core") return "Import builder APIs from \"nitro/builder\".";
|
|
296
|
+
if (source === "nitropack/kit" || source === "nitropack/presets") return "Remove this import and migrate to a supported Nitro 3 API; this subpath has no direct replacement.";
|
|
297
|
+
if (source.startsWith("nitropack/runtime")) return "Use the documented Nitro 3 public subpath for this runtime API.";
|
|
298
|
+
if (source.startsWith("nitro/deps/")) return "Import the dependency directly; Nitro 3 removed nitro/deps subpaths.";
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
function rootPackageReplacement(node) {
|
|
302
|
+
const typeOnlyDeclaration = node.importKind === "type";
|
|
303
|
+
const typeImports = typeOnlyDeclaration || node.specifiers?.some((specifier) => specifier.importKind === "type");
|
|
304
|
+
const valueImports = !typeOnlyDeclaration && (node.specifiers?.length === 0 || node.specifiers?.some((specifier) => specifier.importKind !== "type"));
|
|
305
|
+
if (typeImports && valueImports) return "Import runtime values from \"nitro\" and types from \"nitro/types\".";
|
|
306
|
+
if (typeImports) return "Import types from \"nitro/types\".";
|
|
307
|
+
return "Import from \"nitro\".";
|
|
308
|
+
}
|
|
309
|
+
//#endregion
|
|
310
|
+
//#region src/rule-packs/nitro/rules/no-removed-h3-send.ts
|
|
311
|
+
const noRemovedH3Send = createRule({
|
|
312
|
+
meta: {
|
|
313
|
+
id: "nitro/h3/no-removed-send",
|
|
314
|
+
title: "Replace removed H3 send utilities",
|
|
315
|
+
description: "H3 v2 removes send() and sendError() in favor of returned values and thrown errors.",
|
|
316
|
+
why: "H3 v2 handlers use Web API response values and HTTPError instead of imperative send helpers.",
|
|
317
|
+
recommendedReplacement: "Return the response value from the handler, or throw an HTTPError for an error response.",
|
|
318
|
+
category: "migration",
|
|
319
|
+
severity: "error",
|
|
320
|
+
fixable: "suggestion",
|
|
321
|
+
docsUrl: "https://h3.dev/migration",
|
|
322
|
+
requires: {
|
|
323
|
+
script: true,
|
|
324
|
+
nitro: true
|
|
325
|
+
},
|
|
326
|
+
applicability: {
|
|
327
|
+
runtimes: { h3: ">=2.0.0-0" },
|
|
328
|
+
includePrerelease: true
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
create(ctx) {
|
|
332
|
+
return { ImportDeclaration(node) {
|
|
333
|
+
if (node.source?.value !== "h3" && node.source?.value !== "nitro/h3") return;
|
|
334
|
+
for (const specifier of node.specifiers ?? []) {
|
|
335
|
+
const imported = specifier.imported?.name;
|
|
336
|
+
if (imported !== "send" && imported !== "sendError") continue;
|
|
337
|
+
report(ctx, specifier, "nitro/h3/no-removed-send", "error", "migration", `H3 v2 removes ${imported}().`, imported === "send" ? "Return the response value from the handler." : "Throw an HTTPError from the handler.");
|
|
338
|
+
}
|
|
339
|
+
} };
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
//#endregion
|
|
343
|
+
//#region src/rule-packs/nitro/rules/prefer-h3-redirect-response.ts
|
|
344
|
+
const preferH3RedirectResponse = createRule({
|
|
345
|
+
meta: {
|
|
346
|
+
id: "nitro/h3/prefer-redirect-response",
|
|
347
|
+
title: "Return H3 v2 redirect responses",
|
|
348
|
+
description: "H3 v2 prefers returned redirect() responses over sendRedirect(event, ...).",
|
|
349
|
+
why: "The H3 v2 response model uses returned Web API response values while sendRedirect remains a compatibility wrapper.",
|
|
350
|
+
recommendedReplacement: "Return redirect(location, status) from the handler.",
|
|
351
|
+
category: "migration",
|
|
352
|
+
severity: "warn",
|
|
353
|
+
fixable: "suggestion",
|
|
354
|
+
docsUrl: "https://h3.dev/migration",
|
|
355
|
+
requires: {
|
|
356
|
+
script: true,
|
|
357
|
+
nitro: true
|
|
358
|
+
},
|
|
359
|
+
applicability: {
|
|
360
|
+
runtimes: { h3: ">=2.0.0-0" },
|
|
361
|
+
includePrerelease: true
|
|
362
|
+
}
|
|
363
|
+
},
|
|
364
|
+
create(ctx) {
|
|
365
|
+
return { ImportDeclaration(node) {
|
|
366
|
+
if (node.source?.value !== "h3" && node.source?.value !== "nitro/h3") return;
|
|
367
|
+
for (const specifier of node.specifiers ?? []) {
|
|
368
|
+
if (specifier.imported?.name !== "sendRedirect") continue;
|
|
369
|
+
report(ctx, specifier, "nitro/h3/prefer-redirect-response", "warn", "migration", "sendRedirect(event, ...) is an H3 v2 compatibility utility.", "Import redirect and return redirect(location, status) from the handler.");
|
|
370
|
+
}
|
|
371
|
+
} };
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/rule-packs/nitro/rules/prefer-h3-with-base.ts
|
|
376
|
+
const preferH3WithBase = createRule({
|
|
377
|
+
meta: {
|
|
378
|
+
id: "nitro/h3/prefer-with-base",
|
|
379
|
+
title: "Replace H3 v2 useBase",
|
|
380
|
+
description: "H3 v2 renamed useBase() to withBase().",
|
|
381
|
+
why: "H3 v2 documents withBase() as the handler wrapper for mounting an application under a path prefix, while useBase() remains a legacy alias.",
|
|
382
|
+
recommendedReplacement: "Import withBase and replace useBase(base, handler) with withBase(base, handler).",
|
|
383
|
+
category: "migration",
|
|
384
|
+
severity: "warn",
|
|
385
|
+
fixable: "suggestion",
|
|
386
|
+
docsUrl: "https://h3.dev/migration",
|
|
387
|
+
requires: {
|
|
388
|
+
script: true,
|
|
389
|
+
nitro: true
|
|
390
|
+
},
|
|
391
|
+
applicability: {
|
|
392
|
+
runtimes: { h3: ">=2.0.0-0" },
|
|
393
|
+
includePrerelease: true
|
|
394
|
+
}
|
|
395
|
+
},
|
|
396
|
+
create(ctx) {
|
|
397
|
+
return { ImportDeclaration(node) {
|
|
398
|
+
if (node.source?.value !== "h3" && node.source?.value !== "nitro/h3") return;
|
|
399
|
+
for (const specifier of node.specifiers ?? []) {
|
|
400
|
+
if (specifier.imported?.name !== "useBase") continue;
|
|
401
|
+
report(ctx, specifier, "nitro/h3/prefer-with-base", "warn", "migration", "H3 v2 renamed useBase() to withBase().", "Import withBase and replace useBase(base, handler) with withBase(base, handler).");
|
|
402
|
+
}
|
|
403
|
+
} };
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/rule-packs/nitro/rules/no-client-composables-in-server.ts
|
|
408
|
+
const noClientComposablesInServer = createRule({
|
|
409
|
+
meta: {
|
|
410
|
+
id: "nitro/server/no-client-composables",
|
|
411
|
+
title: "Do not use app composables in Nitro server files",
|
|
412
|
+
description: "Nuxt app composables are not available from Nitro server files.",
|
|
413
|
+
why: "Server handlers run with Nitro request context, not Vue setup context. App composables like useRoute(), useFetch(), and useHead() depend on the Nuxt app runtime.",
|
|
414
|
+
recommendedReplacement: "Use event-aware Nitro utilities in server handlers.",
|
|
415
|
+
category: "server",
|
|
416
|
+
severity: "error",
|
|
417
|
+
fixable: "suggestion",
|
|
418
|
+
docsUrl: "https://nitro.build/guide/routing#request-handler",
|
|
419
|
+
requires: {
|
|
420
|
+
script: true,
|
|
421
|
+
nitro: true
|
|
422
|
+
}
|
|
423
|
+
},
|
|
424
|
+
create(ctx) {
|
|
425
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
426
|
+
const clientComposables = new Set([
|
|
427
|
+
"useRoute",
|
|
428
|
+
"useRouter",
|
|
429
|
+
"useState",
|
|
430
|
+
"useFetch",
|
|
431
|
+
"useAsyncData",
|
|
432
|
+
"useHead",
|
|
433
|
+
"useSeoMeta"
|
|
434
|
+
]);
|
|
435
|
+
return { ScriptNode(node) {
|
|
436
|
+
const name = ctx.helpers.getCalleeName(node);
|
|
437
|
+
if (!name || !clientComposables.has(name)) return;
|
|
438
|
+
report(ctx, node, "nitro/server/no-client-composables", "error", "server", `${name}() is a Nuxt app composable and is not available in Nitro server files.`, "Use event-aware Nitro utilities in server handlers.");
|
|
439
|
+
} };
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
//#endregion
|
|
443
|
+
//#region src/rule-packs/nitro/rules/no-browser-api-in-server.ts
|
|
444
|
+
const noBrowserApiInServer = createRule({
|
|
445
|
+
meta: {
|
|
446
|
+
id: "nitro/server/no-browser-api",
|
|
447
|
+
title: "Do not use browser APIs in Nitro server files",
|
|
448
|
+
description: "Browser globals are unavailable in Nitro server runtime.",
|
|
449
|
+
why: "Nitro code can run in Node, edge, or worker runtimes where browser APIs such as window, document, and localStorage do not exist.",
|
|
450
|
+
recommendedReplacement: "Use request/event data, server utilities, or move browser work to app client code.",
|
|
451
|
+
category: "server",
|
|
452
|
+
severity: "error",
|
|
453
|
+
fixable: "suggestion",
|
|
454
|
+
docsUrl: "https://nitro.build/guide/routing#request-handler",
|
|
455
|
+
requires: {
|
|
456
|
+
script: true,
|
|
457
|
+
nitro: true
|
|
458
|
+
}
|
|
459
|
+
},
|
|
460
|
+
create(ctx) {
|
|
461
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
462
|
+
return { ScriptNode(node) {
|
|
463
|
+
if (node.type !== "Identifier" || !BROWSER_GLOBALS.has(node.name)) return;
|
|
464
|
+
if (ctx.helpers.isTypeOnlyContext(node) || isObjectPropertyKey(node) || ctx.helpers.hasLocalBindingBefore(node, ctx.file.text)) return;
|
|
465
|
+
report(ctx, node, "nitro/server/no-browser-api", "error", "server", `${node.name} is not available in Nitro server runtime.`, "Use request/event data, server utilities, or move browser work to app client code.");
|
|
466
|
+
} };
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
//#endregion
|
|
470
|
+
//#region src/rule-packs/nitro/rules/request-helpers.ts
|
|
471
|
+
function createValidatedInputRule(opts) {
|
|
472
|
+
return createRule({
|
|
473
|
+
meta: {
|
|
474
|
+
id: opts.id,
|
|
475
|
+
title: opts.title,
|
|
476
|
+
description: opts.description,
|
|
477
|
+
recommendedReplacement: `Use ${opts.validatedUtility}(event, validator) instead of ${opts.rawUtilities[0]}(event) followed by separate validation.`,
|
|
478
|
+
category: "request",
|
|
479
|
+
severity: "warn",
|
|
480
|
+
fixable: "suggestion",
|
|
481
|
+
docsUrl: opts.docsUrl,
|
|
482
|
+
requires: {
|
|
483
|
+
script: true,
|
|
484
|
+
nitro: true
|
|
485
|
+
}
|
|
486
|
+
},
|
|
487
|
+
create(ctx) {
|
|
488
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
489
|
+
return { ScriptNode(node) {
|
|
490
|
+
const match = rawInputValidatedNearby(ctx, node, opts.rawUtilities, opts.validatedUtility);
|
|
491
|
+
if (!match) return;
|
|
492
|
+
report(ctx, match.node, opts.id, "warn", "request", opts.message, opts.suggestion);
|
|
493
|
+
} };
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
function rawInputValidatedNearby(ctx, node, rawUtilities, validatedUtility) {
|
|
498
|
+
const variable = rawInputVariable(node, rawUtilities);
|
|
499
|
+
if (!variable) return null;
|
|
500
|
+
const scope = nearestFunctionOrProgram(node);
|
|
501
|
+
if (!scope || !hasValidationOfVariable(scope.body ?? scope, variable, ctx.file.text, node.start ?? 0)) return null;
|
|
502
|
+
return {
|
|
503
|
+
node,
|
|
504
|
+
variable,
|
|
505
|
+
rawUtility: rawUtilityNameFromVariableDeclarator(node),
|
|
506
|
+
validatedUtility
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
function isIpHeaderRead(node, source) {
|
|
510
|
+
if (node.type !== "CallExpression") return false;
|
|
511
|
+
const name = calleeName(node);
|
|
512
|
+
if (name !== "getHeader" && name !== "getRequestHeader") return false;
|
|
513
|
+
const header = staticString(node.arguments?.[1], source)?.toLowerCase();
|
|
514
|
+
return Boolean(header && [
|
|
515
|
+
"x-forwarded-for",
|
|
516
|
+
"x-real-ip",
|
|
517
|
+
"cf-connecting-ip",
|
|
518
|
+
"true-client-ip",
|
|
519
|
+
"x-client-ip"
|
|
520
|
+
].includes(header));
|
|
521
|
+
}
|
|
522
|
+
function isRequestSensitiveUse(ctx, node) {
|
|
523
|
+
const text = sourceForNode(nearestFunctionOrProgram(node) ?? node, ctx.file.text);
|
|
524
|
+
return /\b(?:rateLimit|rateLimiter|ipLimit|throttle|ban|blockIp|allowIp|denyIp|ipAllow|ipDeny|ipBlock|ipBan|blacklist|whitelist)\b/i.test(text);
|
|
525
|
+
}
|
|
526
|
+
function singleMethodCheck(node, source, anchor = node) {
|
|
527
|
+
if (node.type !== "BinaryExpression") return null;
|
|
528
|
+
const operator = node.operator;
|
|
529
|
+
if (operator !== "===" && operator !== "==" && operator !== "!==" && operator !== "!=") return null;
|
|
530
|
+
const leftMethod = methodExpressionName(node.left, source, anchor);
|
|
531
|
+
const rightMethod = methodExpressionName(node.right, source, anchor);
|
|
532
|
+
const method = staticString(node.left, source) ?? staticString(node.right, source);
|
|
533
|
+
if (!method || !leftMethod && !rightMethod) return null;
|
|
534
|
+
const normalized = method.toUpperCase();
|
|
535
|
+
if (!isHttpMethod(normalized)) return null;
|
|
536
|
+
return {
|
|
537
|
+
method: normalized,
|
|
538
|
+
operator,
|
|
539
|
+
isNegative: operator === "!==" || operator === "!="
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
function isSingleMethodCheck(node, source, anchor = node) {
|
|
543
|
+
return singleMethodCheck(node, source, anchor)?.method ?? null;
|
|
544
|
+
}
|
|
545
|
+
function methodChecks(node, source, anchor = node) {
|
|
546
|
+
const checks = /* @__PURE__ */ new Map();
|
|
547
|
+
walkScriptLocal(node, (child) => {
|
|
548
|
+
const check = singleMethodCheck(child, source, anchor);
|
|
549
|
+
if (check) checks.set(`${check.method}:${check.operator}`, check);
|
|
550
|
+
});
|
|
551
|
+
return [...checks.values()];
|
|
552
|
+
}
|
|
553
|
+
function isInIfStatementTest(node) {
|
|
554
|
+
let current = node;
|
|
555
|
+
while (current) {
|
|
556
|
+
const parent = current.__doctorParent;
|
|
557
|
+
if (!parent) return false;
|
|
558
|
+
if (parent.type === "IfStatement" && parent.test === current) return true;
|
|
559
|
+
current = parent;
|
|
560
|
+
}
|
|
561
|
+
return false;
|
|
562
|
+
}
|
|
563
|
+
function isNitroRouteFile(relativePath) {
|
|
564
|
+
const path = normalizePath(relativePath);
|
|
565
|
+
return /^(?:(?:app\/)?server\/)?(?:api|routes)\/.+\.[cm]?[jt]s$/.test(path);
|
|
566
|
+
}
|
|
567
|
+
function routeMethodSuffix(relativePath) {
|
|
568
|
+
const method = normalizePath(relativePath).match(/\.([a-z]+)(?:\.(?:dev|prod|prerender))?\.[cm]?[jt]s$/)?.[1]?.toUpperCase();
|
|
569
|
+
return method && isHttpMethod(method) ? method : null;
|
|
570
|
+
}
|
|
571
|
+
function routePathWithMethodSuffix(relativePath, suffix) {
|
|
572
|
+
const path = normalizePath(relativePath);
|
|
573
|
+
const existingMethod = routeMethodSuffix(path);
|
|
574
|
+
if (existingMethod) return path.replace(new RegExp(`\\.${existingMethod.toLowerCase()}(\\.(?:dev|prod|prerender))?(\\.[cm]?[jt]s)$`, "i"), `.${suffix}$1$2`);
|
|
575
|
+
return path.replace(/(\.(?:dev|prod|prerender))?(\.[cm]?[jt]s)$/, (_match, env = "", extension) => `.${suffix}${env}${extension}`);
|
|
576
|
+
}
|
|
577
|
+
function rawInputVariable(node, rawUtilities) {
|
|
578
|
+
if (node.type !== "VariableDeclarator" || node.id?.type !== "Identifier") return null;
|
|
579
|
+
const call = unwrapAwait(node.init);
|
|
580
|
+
if (call?.type !== "CallExpression") return null;
|
|
581
|
+
const name = calleeName(call);
|
|
582
|
+
return name && rawUtilities.includes(name) ? node.id.name : null;
|
|
583
|
+
}
|
|
584
|
+
function rawUtilityNameFromVariableDeclarator(node) {
|
|
585
|
+
return calleeName(unwrapAwait(node.init)) ?? "";
|
|
586
|
+
}
|
|
587
|
+
function hasValidationOfVariable(scope, variable, source, after) {
|
|
588
|
+
let found = false;
|
|
589
|
+
walkScriptLocal(scope, (node) => {
|
|
590
|
+
if (found || node.type !== "CallExpression") return;
|
|
591
|
+
if (typeof node.start === "number" && node.start <= after) return;
|
|
592
|
+
if (isDirectValidatorCall(node, variable) || isSchemaMethodValidatorCall(node, variable, source)) found = true;
|
|
593
|
+
});
|
|
594
|
+
return found;
|
|
595
|
+
}
|
|
596
|
+
function isDirectValidatorCall(node, variable) {
|
|
597
|
+
const name = calleeName(node);
|
|
598
|
+
return Boolean(name && /^(validate|validator|parse|safeParse|assert|check)\w*$/i.test(name)) && node.arguments?.some((arg) => arg.type === "Identifier" && arg.name === variable);
|
|
599
|
+
}
|
|
600
|
+
function isSchemaMethodValidatorCall(node, variable, source) {
|
|
601
|
+
const name = calleeName(node);
|
|
602
|
+
if (name !== "parse" && name !== "safeParse" && name !== "validate") return false;
|
|
603
|
+
if (!node.arguments?.some((arg) => arg.type === "Identifier" && arg.name === variable)) return false;
|
|
604
|
+
const callee = sourceForNode(node.callee, source);
|
|
605
|
+
return /\b(?:schema|validator|body|query|params|input|payload|zod|valibot|v|s)\w*\.(?:parse|safeParse|validate)$/.test(callee);
|
|
606
|
+
}
|
|
607
|
+
function methodExpressionName(node, source, anchor, seen = /* @__PURE__ */ new Set()) {
|
|
608
|
+
if (node.type === "CallExpression" && calleeName(node) === "getMethod") return "getMethod";
|
|
609
|
+
const text = sourceForNode(node, source);
|
|
610
|
+
if (/\bevent\.(?:method|req\.method|node\.req\.method)\b/.test(text)) return text;
|
|
611
|
+
if (anchor && isMemberMethodRead(node, source, anchor, seen)) return text;
|
|
612
|
+
if (node.type === "Identifier" && anchor && !seen.has(node.name) && isMethodAlias(anchor, node.name, source, seen)) return node.name;
|
|
613
|
+
return null;
|
|
614
|
+
}
|
|
615
|
+
function staticString(node, source) {
|
|
616
|
+
if (!node) return null;
|
|
617
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
618
|
+
if (node.type === "TemplateLiteral" && node.expressions?.length === 0) return node.quasis?.[0]?.value?.cooked ?? node.quasis?.[0]?.value?.raw ?? null;
|
|
619
|
+
return sourceForNode(node, source).match(/^["'`]([^"'`]+)["'`]$/)?.[1] ?? null;
|
|
620
|
+
}
|
|
621
|
+
function unwrapAwait(node) {
|
|
622
|
+
return node?.type === "AwaitExpression" ? node.argument : node;
|
|
623
|
+
}
|
|
624
|
+
function calleeName(node) {
|
|
625
|
+
return node?.callee?.type === "Identifier" ? node.callee.name : node?.callee?.property?.name ?? null;
|
|
626
|
+
}
|
|
627
|
+
function isMemberMethodRead(node, source, anchor, seen) {
|
|
628
|
+
if (!node || node.type !== "MemberExpression" && node.type !== "StaticMemberExpression") return false;
|
|
629
|
+
if (node.computed) return false;
|
|
630
|
+
if (node.property?.name !== "method") return false;
|
|
631
|
+
const object = node.object;
|
|
632
|
+
const objectText = sourceForNode(object, source);
|
|
633
|
+
if (/^event\.(?:req|node\.req)$/.test(objectText)) return true;
|
|
634
|
+
if (object?.type === "Identifier" && anchor) return isRequestAlias(anchor, object.name, source, seen);
|
|
635
|
+
return false;
|
|
636
|
+
}
|
|
637
|
+
function isRequestAlias(anchor, name, source, seen) {
|
|
638
|
+
const declaration = findVariableDeclarationBefore(anchor, name);
|
|
639
|
+
if (!declaration) return false;
|
|
640
|
+
const init = declaration.init;
|
|
641
|
+
if (!init) return false;
|
|
642
|
+
const text = sourceForNode(init, source);
|
|
643
|
+
if (/^event\.(?:req|node\.req)$/.test(text)) return true;
|
|
644
|
+
if (init?.type === "Identifier" && !seen.has(init.name)) {
|
|
645
|
+
seen.add(init.name);
|
|
646
|
+
return isRequestAlias(anchor, init.name, source, seen);
|
|
647
|
+
}
|
|
648
|
+
return false;
|
|
649
|
+
}
|
|
650
|
+
function isMethodAlias(anchor, name, source, seen) {
|
|
651
|
+
const declaration = findVariableDeclarationBefore(anchor, name);
|
|
652
|
+
if (!declaration?.init) return false;
|
|
653
|
+
seen.add(name);
|
|
654
|
+
return Boolean(methodExpressionName(declaration.init, source, anchor, seen));
|
|
655
|
+
}
|
|
656
|
+
function findVariableDeclarationBefore(anchor, name) {
|
|
657
|
+
let child = anchor;
|
|
658
|
+
let scope = child.__doctorParent;
|
|
659
|
+
while (scope) {
|
|
660
|
+
if (scope.type === "BlockStatement" || scope.type === "Program") {
|
|
661
|
+
const declaration = findDeclarationInScopeBefore(scope, child, name);
|
|
662
|
+
if (declaration) return declaration;
|
|
663
|
+
}
|
|
664
|
+
child = scope;
|
|
665
|
+
scope = scope.__doctorParent;
|
|
666
|
+
}
|
|
667
|
+
return null;
|
|
668
|
+
}
|
|
669
|
+
function findDeclarationInScopeBefore(scope, child, name) {
|
|
670
|
+
let match = null;
|
|
671
|
+
for (const statement of scope.body ?? []) {
|
|
672
|
+
if (statement === child) break;
|
|
673
|
+
if ((statement.start ?? statement.range?.[0] ?? 0) >= (child.start ?? child.range?.[0] ?? 0)) break;
|
|
674
|
+
const declaration = variableDeclarationFromStatement(statement, name);
|
|
675
|
+
if (declaration) match = declaration;
|
|
676
|
+
}
|
|
677
|
+
return match;
|
|
678
|
+
}
|
|
679
|
+
function variableDeclarationFromStatement(statement, name) {
|
|
680
|
+
if (statement.type !== "VariableDeclaration") return null;
|
|
681
|
+
return statement.declarations?.find((declaration) => declaration.id?.type === "Identifier" && declaration.id.name === name) ?? null;
|
|
682
|
+
}
|
|
683
|
+
function isHttpMethod(method) {
|
|
684
|
+
return /^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE)$/.test(method);
|
|
685
|
+
}
|
|
686
|
+
function normalizePath(path) {
|
|
687
|
+
return path.replace(/\\/g, "/");
|
|
688
|
+
}
|
|
689
|
+
//#endregion
|
|
690
|
+
//#region src/rule-packs/nitro/rules/prefer-validated-body.ts
|
|
691
|
+
const preferValidatedBody = createValidatedInputRule({
|
|
692
|
+
id: "nitro/request/prefer-validated-body",
|
|
693
|
+
title: "Use readValidatedBody for validated request bodies",
|
|
694
|
+
description: "When a Nitro handler validates a request body, read and validate it through the H3 utility.",
|
|
695
|
+
rawUtilities: ["readBody"],
|
|
696
|
+
validatedUtility: "readValidatedBody",
|
|
697
|
+
docsUrl: "https://h3.dev/utils/request#readvalidatedbodyevent-validate",
|
|
698
|
+
message: "This request body is read raw and validated separately.",
|
|
699
|
+
suggestion: "Use readValidatedBody(event, validator) so input parsing and validation stay coupled."
|
|
700
|
+
});
|
|
701
|
+
//#endregion
|
|
702
|
+
//#region src/rule-packs/nitro/rules/prefer-validated-query.ts
|
|
703
|
+
const preferValidatedQuery = createValidatedInputRule({
|
|
704
|
+
id: "nitro/request/prefer-validated-query",
|
|
705
|
+
title: "Use getValidatedQuery for validated query strings",
|
|
706
|
+
description: "When a Nitro handler validates query input, read and validate it through the H3 utility.",
|
|
707
|
+
rawUtilities: ["getQuery"],
|
|
708
|
+
validatedUtility: "getValidatedQuery",
|
|
709
|
+
docsUrl: "https://h3.dev/utils/request#getvalidatedqueryevent-validate",
|
|
710
|
+
message: "This query object is read raw and validated separately.",
|
|
711
|
+
suggestion: "Use getValidatedQuery(event, validator) so query parsing and validation stay coupled."
|
|
712
|
+
});
|
|
713
|
+
//#endregion
|
|
714
|
+
//#region src/rule-packs/nitro/rules/prefer-validated-router-params.ts
|
|
715
|
+
const preferValidatedRouterParams = createValidatedInputRule({
|
|
716
|
+
id: "nitro/request/prefer-validated-router-params",
|
|
717
|
+
title: "Use getValidatedRouterParams for validated route params",
|
|
718
|
+
description: "When a Nitro handler validates route params, read and validate them through the H3 utility.",
|
|
719
|
+
rawUtilities: ["getRouterParams", "getRouterParam"],
|
|
720
|
+
validatedUtility: "getValidatedRouterParams",
|
|
721
|
+
docsUrl: "https://h3.dev/utils/request#getvalidatedrouterparamsevent-validate",
|
|
722
|
+
message: "These route params are read raw and validated separately.",
|
|
723
|
+
suggestion: "Use getValidatedRouterParams(event, validator) so route param parsing and validation stay coupled."
|
|
724
|
+
});
|
|
725
|
+
//#endregion
|
|
726
|
+
//#region src/rule-packs/nitro/rules/prefer-assert-method.ts
|
|
727
|
+
const preferAssertMethod = createRule({
|
|
728
|
+
meta: {
|
|
729
|
+
id: "nitro/request/prefer-assert-method",
|
|
730
|
+
title: "Use assertMethod for single-method handlers",
|
|
731
|
+
description: "Single-method Nitro handlers should use the H3 method assertion helper instead of ad hoc method checks.",
|
|
732
|
+
recommendedReplacement: "Use assertMethod(event, \"POST\") for handlers that accept one HTTP method.",
|
|
733
|
+
category: "request",
|
|
734
|
+
severity: "info",
|
|
735
|
+
fixable: "suggestion",
|
|
736
|
+
docsUrl: "https://h3.dev/utils/request#assertmethodevent-expected-allowhead",
|
|
737
|
+
requires: {
|
|
738
|
+
script: true,
|
|
739
|
+
nitro: true
|
|
740
|
+
}
|
|
741
|
+
},
|
|
742
|
+
create(ctx) {
|
|
743
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
744
|
+
if (isNitroRouteFile(ctx.file.relativePath)) return;
|
|
745
|
+
return { ScriptNode(node) {
|
|
746
|
+
const method = isSingleMethodCheck(node, ctx.file.text);
|
|
747
|
+
if (!method) return;
|
|
748
|
+
report(ctx, node, "nitro/request/prefer-assert-method", "info", "request", `This handler checks for ${method} manually.`, `Use assertMethod(event, "${method}") for single-method Nitro handlers.`);
|
|
749
|
+
} };
|
|
750
|
+
}
|
|
751
|
+
});
|
|
752
|
+
//#endregion
|
|
753
|
+
//#region src/rule-packs/nitro/rules/prefer-route-method-suffix.ts
|
|
754
|
+
const RULE_ID = "nitro/request/prefer-route-method-suffix";
|
|
755
|
+
const preferRouteMethodSuffix = createRule({
|
|
756
|
+
meta: {
|
|
757
|
+
id: RULE_ID,
|
|
758
|
+
title: "Use Nitro route method suffixes",
|
|
759
|
+
description: "File-routed Nitro handlers should use HTTP method filename suffixes instead of manual request method gates.",
|
|
760
|
+
why: "Nitro's file router can bind handlers to HTTP methods before user code runs, which keeps unsupported methods out of the handler and makes the route contract visible in the filesystem.",
|
|
761
|
+
recommendedReplacement: "Use route files such as server/api/user.get.ts or server/api/user.post.ts instead of checking request.method inside the handler.",
|
|
762
|
+
examples: [{
|
|
763
|
+
title: "Move method gates into the route filename",
|
|
764
|
+
language: "ts",
|
|
765
|
+
invalid: "export default defineEventHandler((event) => {\n if (getMethod(event) !== 'POST') throw createError({ statusCode: 405 })\n return createUser(event)\n})",
|
|
766
|
+
valid: "// server/api/user.post.ts\nexport default defineEventHandler((event) => {\n return createUser(event)\n})"
|
|
767
|
+
}],
|
|
768
|
+
category: "request",
|
|
769
|
+
severity: "warn",
|
|
770
|
+
fixable: "suggestion",
|
|
771
|
+
docsUrl: "https://nitro.build/docs/routing#specific-request-method",
|
|
772
|
+
requires: {
|
|
773
|
+
script: true,
|
|
774
|
+
nitro: true
|
|
775
|
+
}
|
|
776
|
+
},
|
|
777
|
+
create(ctx) {
|
|
778
|
+
if (!isNitroRouteFile(ctx.file.relativePath)) return;
|
|
779
|
+
return { ScriptNode(node) {
|
|
780
|
+
if (node.type === "IfStatement") {
|
|
781
|
+
const checks = methodChecks(node.test, ctx.file.text, node);
|
|
782
|
+
if (!checks.length) return;
|
|
783
|
+
reportMethodCheck(node.test ?? node, checks, wholeHandlerAllowed(node, checks));
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
if (node.type !== "BinaryExpression" || isInIfStatementTest(node)) return;
|
|
787
|
+
const check = singleMethodCheck(node, ctx.file.text, node);
|
|
788
|
+
if (!check) return;
|
|
789
|
+
reportMethodCheck(node, [check], false);
|
|
790
|
+
} };
|
|
791
|
+
function reportMethodCheck(node, checks, wholeHandler) {
|
|
792
|
+
const methods = methodsFromChecks(checks);
|
|
793
|
+
const suffix = routeMethodSuffix(ctx.file.relativePath);
|
|
794
|
+
const suggestion = suffix && isRedundantSuffix(suffix, methods) ? `Remove the manual method guard; .${suffix.toLowerCase()}.ts already constrains this route.` : methodSuffixSuggestion(ctx.file.relativePath, methods, wholeHandler);
|
|
795
|
+
report(ctx, node, RULE_ID, "warn", "request", `This file-routed Nitro handler checks ${formatMethods(methods)} manually.`, suggestion);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
});
|
|
799
|
+
function formatMethods(methods) {
|
|
800
|
+
return methods.length === 1 ? methods[0] : methods.join("/");
|
|
801
|
+
}
|
|
802
|
+
function isRedundantSuffix(suffix, methods) {
|
|
803
|
+
return methods.length === 1 && methods[0] === suffix;
|
|
804
|
+
}
|
|
805
|
+
function methodSuffixSuggestion(relativePath, methods, wholeHandler) {
|
|
806
|
+
const paths = methods.map((method) => routePathWithMethodSuffix(relativePath, method.toLowerCase()));
|
|
807
|
+
if (wholeHandler && paths.length === 1) return `Move this handler to ${paths[0]} and remove the manual method guard.`;
|
|
808
|
+
if (wholeHandler) return `Split this handler into ${formatList(paths)} and remove the manual method guard.`;
|
|
809
|
+
if (paths.length === 1) return `Move the ${methods[0]}-specific branch to ${paths[0]} and keep other method behavior in method-suffixed route files.`;
|
|
810
|
+
return `Move the method-specific branches to ${formatList(paths)} and keep other method behavior in method-suffixed route files.`;
|
|
811
|
+
}
|
|
812
|
+
function formatList(items) {
|
|
813
|
+
if (items.length <= 1) return items[0] ?? "";
|
|
814
|
+
return `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
|
|
815
|
+
}
|
|
816
|
+
function methodsFromChecks(checks) {
|
|
817
|
+
return [...new Set(checks.map((check) => check.method))];
|
|
818
|
+
}
|
|
819
|
+
function wholeHandlerAllowed(node, checks) {
|
|
820
|
+
return checks.every((check) => check.isNegative) && branchExits(node.consequent);
|
|
821
|
+
}
|
|
822
|
+
function branchExits(node) {
|
|
823
|
+
if (!node) return false;
|
|
824
|
+
if (node.type === "ReturnStatement" || node.type === "ThrowStatement") return true;
|
|
825
|
+
if (node.type !== "BlockStatement") return false;
|
|
826
|
+
return branchExits(node.body?.at(-1));
|
|
827
|
+
}
|
|
828
|
+
//#endregion
|
|
829
|
+
//#region src/rule-packs/nitro/rules/prefer-get-request-ip.ts
|
|
830
|
+
const preferGetRequestIp = createRule({
|
|
831
|
+
meta: {
|
|
832
|
+
id: "nitro/request/prefer-get-request-ip",
|
|
833
|
+
title: "Use request IP utilities instead of raw IP headers",
|
|
834
|
+
description: "Request-sensitive Nitro code should not trust client-controlled forwarding headers directly.",
|
|
835
|
+
recommendedReplacement: "Use the H3/Nitro request IP utility and centralize trusted proxy handling instead of reading IP headers directly.",
|
|
836
|
+
category: "request",
|
|
837
|
+
severity: "warn",
|
|
838
|
+
fixable: "suggestion",
|
|
839
|
+
docsUrl: "https://h3.dev/utils/request#getrequestipevent",
|
|
840
|
+
requires: {
|
|
841
|
+
script: true,
|
|
842
|
+
nitro: true
|
|
843
|
+
}
|
|
844
|
+
},
|
|
845
|
+
create(ctx) {
|
|
846
|
+
if (!ctx.helpers.isNuxtServerFile(ctx.file.relativePath)) return;
|
|
847
|
+
return { ScriptNode(node) {
|
|
848
|
+
if (!isIpHeaderRead(node, ctx.file.text)) return;
|
|
849
|
+
if (!isRequestSensitiveUse(ctx, node)) return;
|
|
850
|
+
report(ctx, node, "nitro/request/prefer-get-request-ip", "warn", "request", "This request-sensitive code reads a forwarded client IP header directly.", "Use the H3/Nitro request IP utility with trusted proxy configuration.");
|
|
851
|
+
} };
|
|
852
|
+
}
|
|
853
|
+
});
|
|
854
|
+
//#endregion
|
|
855
|
+
//#region src/rule-packs/nitro/rules/index.ts
|
|
856
|
+
const rules = [
|
|
857
|
+
noUseNuxtAppInNitro,
|
|
858
|
+
noNavigateToInNitro,
|
|
859
|
+
requireEventRuntimeConfigInServer,
|
|
860
|
+
noEventRuntimeConfigInServer,
|
|
861
|
+
noV2Imports,
|
|
862
|
+
noRemovedH3Send,
|
|
863
|
+
preferH3RedirectResponse,
|
|
864
|
+
preferH3WithBase,
|
|
865
|
+
noClientComposablesInServer,
|
|
866
|
+
noBrowserApiInServer,
|
|
867
|
+
preferValidatedBody,
|
|
868
|
+
preferValidatedQuery,
|
|
869
|
+
preferValidatedRouterParams,
|
|
870
|
+
preferAssertMethod,
|
|
871
|
+
preferRouteMethodSuffix,
|
|
872
|
+
preferGetRequestIp
|
|
873
|
+
];
|
|
874
|
+
const nitroRulePack = defineRulePack({
|
|
875
|
+
name: "vite-doctor/nitro",
|
|
876
|
+
version: "0.0.0",
|
|
877
|
+
rules,
|
|
878
|
+
presets: {
|
|
879
|
+
recommended: rules.map((rule) => rule.meta.id),
|
|
880
|
+
strict: rules.map((rule) => rule.meta.id)
|
|
881
|
+
}
|
|
882
|
+
});
|
|
883
|
+
//#endregion
|
|
884
|
+
export { noUseNuxtAppInNitro as _, preferValidatedRouterParams as a, sourceForNode as b, noBrowserApiInServer as c, preferH3RedirectResponse as d, noRemovedH3Send as f, noNavigateToInNitro as g, requireEventRuntimeConfigInServer as h, preferAssertMethod as i, noClientComposablesInServer as l, noEventRuntimeConfigInServer as m, preferGetRequestIp as n, preferValidatedQuery as o, noV2Imports as p, preferRouteMethodSuffix as r, preferValidatedBody as s, nitroRulePack as t, preferH3WithBase as u, findAncestor as v, walkScriptLocal as x, nearestFunctionOrProgram as y };
|