@nuxt/kit 4.3.1 → 4.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { createDefu, defu } from "defu";
3
3
  import { applyDefaults } from "untyped";
4
4
  import { consola } from "consola";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
- import { createContext, getContext } from "unctx";
6
+ import { getContext } from "unctx";
7
7
  import satisfies from "semver/functions/satisfies.js";
8
8
  import { readPackageJSON, resolvePackageJSON } from "pkg-types";
9
9
  import { existsSync, lstatSync, promises, readFileSync } from "node:fs";
@@ -26,27 +26,59 @@ import { kebabCase, pascalCase, snakeCase } from "scule";
26
26
  import { klona } from "klona";
27
27
  import { hash } from "ohash";
28
28
  import { isAbsolute as isAbsolute$1 } from "node:path";
29
+ //#region src/logger.ts
29
30
  const logger = consola;
30
31
  function useLogger(tag, options = {}) {
31
32
  return tag ? logger.create(options).withTag(tag) : logger;
32
33
  }
34
+ //#endregion
35
+ //#region src/context.ts
36
+ /**
37
+ * Direct access to the Nuxt global context - see https://github.com/unjs/unctx.
38
+ * @deprecated Use `getNuxtCtx` instead
39
+ */
33
40
  const nuxtCtx = getContext("nuxt");
34
- const asyncNuxtStorage = createContext({
41
+ /** async local storage for the name of the current nuxt instance */
42
+ const asyncNuxtStorage = getContext("asyncNuxtStorage", {
35
43
  asyncContext: true,
36
44
  AsyncLocalStorage
37
45
  });
46
+ /** Direct access to the Nuxt context with asyncLocalStorage - see https://github.com/unjs/unctx. */
38
47
  const getNuxtCtx = () => asyncNuxtStorage.tryUse();
48
+ /**
49
+ * Get access to Nuxt instance.
50
+ *
51
+ * Throws an error if Nuxt instance is unavailable.
52
+ * @example
53
+ * ```js
54
+ * const nuxt = useNuxt()
55
+ * ```
56
+ */
39
57
  function useNuxt() {
40
58
  const instance = asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
41
59
  if (!instance) throw new Error("Nuxt instance is unavailable!");
42
60
  return instance;
43
61
  }
62
+ /**
63
+ * Get access to Nuxt instance.
64
+ *
65
+ * Returns null if Nuxt instance is unavailable.
66
+ * @example
67
+ * ```js
68
+ * const nuxt = tryUseNuxt()
69
+ * if (nuxt) {
70
+ * // Do something
71
+ * }
72
+ * ```
73
+ */
44
74
  function tryUseNuxt() {
45
75
  return asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
46
76
  }
47
77
  function runWithNuxtContext(nuxt, fn) {
48
78
  return asyncNuxtStorage.call(nuxt, fn);
49
79
  }
80
+ //#endregion
81
+ //#region src/compatibility.ts
50
82
  const SEMANTIC_VERSION_RE = /-\d+\.[0-9a-f]+/;
51
83
  function normalizeSemanticVersion(version) {
52
84
  return version.replace(SEMANTIC_VERSION_RE, "");
@@ -59,6 +91,9 @@ const builderMap = {
59
91
  function checkNuxtVersion(version, nuxt = useNuxt()) {
60
92
  return satisfies(normalizeSemanticVersion(getNuxtVersion(nuxt)), version, { includePrerelease: true });
61
93
  }
94
+ /**
95
+ * Check version constraints and return incompatibility issues as an array
96
+ */
62
97
  async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
63
98
  const issues = [];
64
99
  if (constraints.nuxt) {
@@ -96,30 +131,50 @@ async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
96
131
  issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
97
132
  return issues;
98
133
  }
134
+ /**
135
+ * Check version constraints and throw a detailed error if has any, otherwise returns true
136
+ */
99
137
  async function assertNuxtCompatibility(constraints, nuxt = useNuxt()) {
100
138
  const issues = await checkNuxtCompatibility(constraints, nuxt);
101
139
  if (issues.length) throw new Error("Nuxt compatibility issues found:\n" + issues.toString());
102
140
  return true;
103
141
  }
142
+ /**
143
+ * Check version constraints and return true if passed, otherwise returns false
144
+ */
104
145
  async function hasNuxtCompatibility(constraints, nuxt = useNuxt()) {
105
146
  return !(await checkNuxtCompatibility(constraints, nuxt)).length;
106
147
  }
148
+ /**
149
+ * Check if current Nuxt instance is of specified major version
150
+ */
107
151
  function isNuxtMajorVersion(majorVersion, nuxt = useNuxt()) {
108
152
  const version = getNuxtVersion(nuxt);
109
153
  return version[0] === majorVersion.toString() && version[1] === ".";
110
154
  }
155
+ /**
156
+ * @deprecated Use `isNuxtMajorVersion(2, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
157
+ */
111
158
  function isNuxt2(nuxt = useNuxt()) {
112
159
  return isNuxtMajorVersion(2, nuxt);
113
160
  }
161
+ /**
162
+ * @deprecated Use `isNuxtMajorVersion(3, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
163
+ */
114
164
  function isNuxt3(nuxt = useNuxt()) {
115
165
  return isNuxtMajorVersion(3, nuxt);
116
166
  }
117
167
  const NUXT_VERSION_RE = /^v/g;
168
+ /**
169
+ * Get nuxt version
170
+ */
118
171
  function getNuxtVersion(nuxt = useNuxt()) {
119
172
  const rawVersion = nuxt?._version || nuxt?.version || nuxt?.constructor?.version;
120
173
  if (typeof rawVersion !== "string") throw new TypeError("Cannot determine nuxt version! Is current instance passed?");
121
174
  return rawVersion.replace(NUXT_VERSION_RE, "");
122
175
  }
176
+ //#endregion
177
+ //#region src/module/define.ts
123
178
  function defineNuxtModule(definition) {
124
179
  if (definition) return _defineNuxtModule(definition);
125
180
  return { with: (definition) => _defineNuxtModule(definition) };
@@ -161,12 +216,19 @@ function _defineNuxtModule(definition) {
161
216
  }
162
217
  const _options = await getOptions(inlineOptions, nuxt);
163
218
  if (module.hooks) nuxt.hooks.addHooks(module.hooks);
219
+ const moduleName = uniqueKey || module.meta.name || "<no name>";
220
+ nuxt._perf?.startPhase(`module:${moduleName}`);
164
221
  const start = performance.now();
165
- const res = await module.setup?.call(null, _options, nuxt) ?? {};
222
+ let res = {};
223
+ try {
224
+ res = await module.setup?.call(null, _options, nuxt) ?? {};
225
+ } finally {
226
+ nuxt._perf?.endPhase(`module:${moduleName}`);
227
+ }
166
228
  const perf = performance.now() - start;
167
229
  const setupTime = Math.round(perf * 100) / 100;
168
- if (setupTime > 5e3 && uniqueKey !== "@nuxt/telemetry") logger.warn(`Slow module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
169
- else if (nuxt.options.debug && nuxt.options.debug.modules) logger.info(`Module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
230
+ if (setupTime > 5e3 && uniqueKey !== "@nuxt/telemetry") logger.warn(`Slow module \`${moduleName}\` took \`${setupTime}ms\` to setup.`);
231
+ else if (nuxt.options.debug && nuxt.options.debug.modules) logger.info(`Module \`${moduleName}\` took \`${setupTime}ms\` to setup.`);
170
232
  if (res === false) return false;
171
233
  return defu(res, { timings: { setup: setupTime } });
172
234
  }
@@ -177,6 +239,8 @@ function _defineNuxtModule(definition) {
177
239
  normalizedModule.onUpgrade = module.onUpgrade;
178
240
  return normalizedModule;
179
241
  }
242
+ //#endregion
243
+ //#region src/internal/trace.ts
180
244
  const distURL = import.meta.url.replace(/\/dist\/.*$/, "/");
181
245
  function getUserCaller() {
182
246
  if (!import.meta.dev) return null;
@@ -195,7 +259,20 @@ function warn(warning) {
195
259
  warnings.add(warning);
196
260
  }
197
261
  }
262
+ //#endregion
263
+ //#region src/layers.ts
198
264
  const layerMap = /* @__PURE__ */ new WeakMap();
265
+ /**
266
+ * Get the resolved directory paths for all layers in a Nuxt application.
267
+ *
268
+ * Returns an array of LayerDirectories objects, ordered by layer priority:
269
+ * - The first layer is the user/project layer (highest priority)
270
+ * - Earlier layers override later layers in the array
271
+ * - Base layers appear last in the array (lowest priority)
272
+ *
273
+ * @param nuxt - The Nuxt instance to get layers from. Defaults to the current Nuxt context.
274
+ * @returns Array of LayerDirectories objects, ordered by priority (user layer first)
275
+ */
199
276
  function getLayerDirectories(nuxt = useNuxt()) {
200
277
  return nuxt.options._layers.map((layer) => {
201
278
  if (layerMap.has(layer)) return layerMap.get(layer);
@@ -221,9 +298,14 @@ function getLayerDirectories(nuxt = useNuxt()) {
221
298
  function withTrailingSlash$2(dir) {
222
299
  return dir.replace(/[^/]$/, "$&/");
223
300
  }
301
+ //#endregion
302
+ //#region src/ignore.ts
224
303
  function createIsIgnored(nuxt = tryUseNuxt()) {
225
304
  return (pathname, stats) => isIgnored(pathname, stats, nuxt);
226
305
  }
306
+ /**
307
+ * Return a filter function to filter an array of paths
308
+ */
227
309
  function isIgnored(pathname, _stats, nuxt = tryUseNuxt()) {
228
310
  if (!nuxt) return false;
229
311
  if (!nuxt._ignore) {
@@ -251,6 +333,13 @@ function resolveIgnorePatterns(relativePath) {
251
333
  });
252
334
  return ignorePatterns;
253
335
  }
336
+ /**
337
+ * This function turns string containing groups '**\/*.{spec,test}.{js,ts}' into an array of strings.
338
+ * For example will '**\/*.{spec,test}.{js,ts}' be resolved to:
339
+ * ['**\/*.spec.js', '**\/*.spec.ts', '**\/*.test.js', '**\/*.test.ts']
340
+ * @param group string containing the group syntax
341
+ * @returns {string[]} array of strings without the group syntax
342
+ */
254
343
  function resolveGroupSyntax(group) {
255
344
  let groups = [group];
256
345
  while (groups.some((group) => group.includes("{"))) groups = groups.flatMap((group) => {
@@ -263,15 +352,32 @@ function resolveGroupSyntax(group) {
263
352
  });
264
353
  return groups;
265
354
  }
355
+ //#endregion
356
+ //#region src/utils.ts
357
+ /** @since 3.9.0 */
266
358
  function toArray(value) {
267
359
  return Array.isArray(value) ? value : [value];
268
360
  }
361
+ /**
362
+ * Filter out items from an array in place. This function mutates the array.
363
+ * `predicate` get through the array from the end to the start for performance.
364
+ *
365
+ * This function should be faster than `Array.prototype.filter` on large arrays.
366
+ */
269
367
  function filterInPlace(array, predicate) {
270
368
  for (let i = array.length; i--;) if (!predicate(array[i], i, array)) array.splice(i, 1);
271
369
  return array;
272
370
  }
273
371
  const MODE_RE = /\.(server|client)(\.\w+)*$/;
274
372
  const distDirURL = new URL(".", import.meta.url);
373
+ //#endregion
374
+ //#region src/resolve.ts
375
+ /**
376
+ * Resolve the full path to a file or a directory (based on the provided type), respecting Nuxt alias and extensions options.
377
+ *
378
+ * If a path cannot be resolved, normalized input will be returned unless the `fallbackToOriginal` option is set to `true`,
379
+ * in which case the original input path will be returned.
380
+ */
275
381
  async function resolvePath(path, opts = {}) {
276
382
  const { type = "file" } = opts;
277
383
  const res = await _resolvePathGranularly(path, {
@@ -281,6 +387,9 @@ async function resolvePath(path, opts = {}) {
281
387
  if (res.type === type) return res.path;
282
388
  return opts.fallbackToOriginal ? path : res.path;
283
389
  }
390
+ /**
391
+ * Try to resolve first existing file in paths
392
+ */
284
393
  async function findPath(paths, opts, pathType = "file") {
285
394
  for (const path of toArray(paths)) {
286
395
  const res = await _resolvePathGranularly(path, {
@@ -292,10 +401,16 @@ async function findPath(paths, opts, pathType = "file") {
292
401
  }
293
402
  return null;
294
403
  }
404
+ /**
405
+ * Resolve path aliases respecting Nuxt alias options
406
+ */
295
407
  function resolveAlias(path, alias) {
296
408
  alias ||= tryUseNuxt()?.options.alias || {};
297
409
  return resolveAlias$1(path, alias);
298
410
  }
411
+ /**
412
+ * Create a relative resolver
413
+ */
299
414
  function createResolver(base) {
300
415
  if (!base) throw new Error("`base` argument is missing for createResolver(base)!");
301
416
  base = base.toString();
@@ -398,6 +513,15 @@ function existsInVFS(path, nuxt = tryUseNuxt()) {
398
513
  if (path in nuxt.vfs) return true;
399
514
  return (nuxt.apps.default?.templates ?? nuxt.options.build.templates).some((template) => template.dst === path);
400
515
  }
516
+ /**
517
+ * Resolve absolute file paths in the provided directory with respect to `.nuxtignore` and return them sorted.
518
+ * @param path path to the directory to resolve files in
519
+ * @param pattern glob pattern or an array of glob patterns to match files
520
+ * @param opts options for globbing
521
+ * @param opts.followSymbolicLinks whether to follow symbolic links, default is `true`
522
+ * @param opts.ignore additional glob patterns to ignore
523
+ * @returns sorted array of absolute file paths
524
+ */
401
525
  async function resolveFiles(path, pattern, opts = {}) {
402
526
  const files = [];
403
527
  for (const p of await glob(pattern, {
@@ -408,6 +532,8 @@ async function resolveFiles(path, pattern, opts = {}) {
408
532
  })) if (!isIgnored(p)) files.push(p);
409
533
  return files.sort();
410
534
  }
535
+ //#endregion
536
+ //#region src/internal/esm.ts
411
537
  function directoryToURL(dir) {
412
538
  return pathToFileURL(dir + "/");
413
539
  }
@@ -439,17 +565,25 @@ function tryImportModule(id, opts) {
439
565
  return importModule(id, opts).catch(() => void 0);
440
566
  } catch {}
441
567
  }
568
+ /**
569
+ * @deprecated Please use `importModule` instead.
570
+ */
442
571
  function requireModule(id, opts) {
443
572
  const caller = getUserCaller();
444
573
  warn(`[@nuxt/kit] \`requireModule\` is deprecated${caller ? ` (used at \`${resolveAlias(caller.source)}:${caller.line}:${caller.column}\`)` : ""}. Please use \`importModule\` instead.`);
445
574
  const resolvedPath = resolveModule(id, opts);
446
575
  return createJiti(import.meta.url, { interopDefault: opts?.interopDefault !== false })(pathToFileURL(resolvedPath).href);
447
576
  }
577
+ /**
578
+ * @deprecated Please use `tryImportModule` instead.
579
+ */
448
580
  function tryRequireModule(id, opts) {
449
581
  try {
450
582
  return requireModule(id, opts);
451
583
  } catch {}
452
584
  }
585
+ //#endregion
586
+ //#region src/module/install.ts
453
587
  const NODE_MODULES_RE = /[/\\]node_modules[/\\]/;
454
588
  const ignoredConfigKeys = new Set([
455
589
  "components",
@@ -458,6 +592,10 @@ const ignoredConfigKeys = new Set([
458
592
  "devtools",
459
593
  "telemetry"
460
594
  ]);
595
+ /**
596
+ * Installs a set of modules on a Nuxt instance.
597
+ * @internal
598
+ */
461
599
  async function installModules(modulesToInstall, resolvedModulePaths, nuxt = useNuxt()) {
462
600
  const localLayerModuleDirs = [];
463
601
  for (const l of nuxt.options._layers) {
@@ -529,12 +667,12 @@ async function installModules(modulesToInstall, resolvedModulePaths, nuxt = useN
529
667
  if (error) throw error;
530
668
  for (const { nuxtModule, meta = {}, moduleToInstall, buildTimeModuleMeta, resolvedModulePath, inlineOptions } of resolvedModules) {
531
669
  const configKey = meta.configKey;
532
- const optionsFns = [
670
+ const optionsFns = new Set([
533
671
  ...nuxt._moduleOptionsFunctions.get(moduleToInstall) || [],
534
672
  ...meta?.name ? nuxt._moduleOptionsFunctions.get(meta.name) || [] : [],
535
673
  ...configKey ? nuxt._moduleOptionsFunctions.get(configKey) || [] : []
536
- ];
537
- if (optionsFns.length > 0) {
674
+ ]);
675
+ if (optionsFns.size > 0) {
538
676
  const overrides = [];
539
677
  const defaults = [];
540
678
  for (const fn of optionsFns) {
@@ -556,6 +694,10 @@ async function installModules(modulesToInstall, resolvedModulePaths, nuxt = useN
556
694
  }
557
695
  delete nuxt._moduleOptionsFunctions;
558
696
  }
697
+ /**
698
+ * Installs a module on a Nuxt instance.
699
+ * @deprecated Use module dependencies.
700
+ */
559
701
  async function installModule(moduleToInstall, inlineOptions, nuxt = useNuxt()) {
560
702
  const { nuxtModule, buildTimeModuleMeta, resolvedModulePath } = await loadNuxtModuleInstance(moduleToInstall, nuxt);
561
703
  const localLayerModuleDirs = [];
@@ -730,19 +872,35 @@ async function callModule(nuxt, nuxtModule, moduleOptions = {}, options) {
730
872
  entryPath
731
873
  });
732
874
  }
875
+ //#endregion
876
+ //#region src/module/compatibility.ts
733
877
  function resolveNuxtModuleEntryName(m) {
734
878
  if (typeof m === "object" && !Array.isArray(m)) return m.name;
735
879
  if (Array.isArray(m)) return resolveNuxtModuleEntryName(m[0]);
736
880
  return m || false;
737
881
  }
882
+ /**
883
+ * Check if a Nuxt module is installed by name.
884
+ *
885
+ * This will check both the installed modules and the modules to be installed. Note
886
+ * that it cannot detect if a module is _going to be_ installed programmatically by another module.
887
+ */
738
888
  function hasNuxtModule(moduleName, nuxt = useNuxt()) {
739
889
  return nuxt.options._installedModules.some(({ meta }) => meta.name === moduleName) || nuxt.options.modules.some((m) => moduleName === resolveNuxtModuleEntryName(m));
740
890
  }
891
+ /**
892
+ * Checks if a Nuxt module is compatible with a given semver version.
893
+ */
741
894
  async function hasNuxtModuleCompatibility(module, semverVersion, nuxt = useNuxt()) {
742
895
  const version = await getNuxtModuleVersion(module, nuxt);
743
896
  if (!version) return false;
744
897
  return satisfies(normalizeSemanticVersion(version), semverVersion, { includePrerelease: true });
745
898
  }
899
+ /**
900
+ * Get the version of a Nuxt module.
901
+ *
902
+ * Scans installed modules for the version, if it's not found it will attempt to load the module instance and get the version from there.
903
+ */
746
904
  async function getNuxtModuleVersion(module, nuxt = useNuxt()) {
747
905
  const moduleMeta = (typeof module === "string" ? { name: module } : await module.getMeta?.()) || {};
748
906
  if (moduleMeta.version) return moduleMeta.version;
@@ -754,6 +912,8 @@ async function getNuxtModuleVersion(module, nuxt = useNuxt()) {
754
912
  }
755
913
  return false;
756
914
  }
915
+ //#endregion
916
+ //#region src/loader/config.ts
757
917
  const merger = createDefu((obj, key, value) => {
758
918
  if (Array.isArray(obj[key]) && Array.isArray(value)) {
759
919
  obj[key] = obj[key].concat(value);
@@ -834,7 +994,7 @@ async function loadNuxtConfig(opts) {
834
994
  });
835
995
  return await applyDefaults(NuxtConfigSchema, nuxtConfig);
836
996
  }
837
- async function loadNuxtSchema(cwd) {
997
+ function loadNuxtSchema(cwd) {
838
998
  const url = directoryToURL(cwd);
839
999
  const urls = [url];
840
1000
  const nuxtPath = resolveModuleURL("nuxt", {
@@ -845,7 +1005,7 @@ async function loadNuxtSchema(cwd) {
845
1005
  from: url
846
1006
  });
847
1007
  if (nuxtPath) urls.unshift(nuxtPath);
848
- return await import(resolveModuleURL("@nuxt/schema", {
1008
+ return import(resolveModuleURL("@nuxt/schema", {
849
1009
  try: true,
850
1010
  from: urls
851
1011
  }) ?? "@nuxt/schema").then((r) => r.NuxtConfigSchema);
@@ -865,11 +1025,15 @@ async function withDefineNuxtConfig(fn) {
865
1025
  if (!globalSelf[key].count) delete globalSelf[key];
866
1026
  }
867
1027
  }
1028
+ //#endregion
1029
+ //#region src/loader/schema.ts
868
1030
  function extendNuxtSchema(def) {
869
1031
  useNuxt().hook("schema:extend", (schemas) => {
870
1032
  schemas.push(typeof def === "function" ? def() : def);
871
1033
  });
872
1034
  }
1035
+ //#endregion
1036
+ //#region src/loader/nuxt.ts
873
1037
  async function loadNuxt(opts) {
874
1038
  opts.cwd = resolve(opts.cwd || opts.rootDir || ".");
875
1039
  opts.overrides ||= opts.config || {};
@@ -890,10 +1054,14 @@ async function buildNuxt(nuxt) {
890
1054
  const { build } = await tryImportModule("nuxt-nightly", { url: rootURL }) || await importModule("nuxt", { url: rootURL });
891
1055
  return runWithNuxtContext(nuxt, () => build(nuxt));
892
1056
  }
1057
+ //#endregion
1058
+ //#region src/head.ts
893
1059
  function setGlobalHead(head) {
894
1060
  const nuxt = useNuxt();
895
1061
  nuxt.options.app.head = defu(head, nuxt.options.app.head);
896
1062
  }
1063
+ //#endregion
1064
+ //#region src/imports.ts
897
1065
  function addImports(imports) {
898
1066
  useNuxt().hook("imports:extend", (_imports) => {
899
1067
  _imports.push(...toArray(imports));
@@ -909,7 +1077,13 @@ function addImportsSources(presets) {
909
1077
  for (const preset of toArray(presets)) _presets.push(preset);
910
1078
  });
911
1079
  }
1080
+ //#endregion
1081
+ //#region src/nitro.ts
912
1082
  const HANDLER_METHOD_RE = /\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/;
1083
+ /**
1084
+ * normalize handler object
1085
+ *
1086
+ */
913
1087
  function normalizeHandlerMethod(handler) {
914
1088
  const [, method = void 0] = handler.handler.match(HANDLER_METHOD_RE) || [];
915
1089
  return {
@@ -918,17 +1092,31 @@ function normalizeHandlerMethod(handler) {
918
1092
  handler: normalize(handler.handler)
919
1093
  };
920
1094
  }
1095
+ /**
1096
+ * Adds a nitro server handler
1097
+ *
1098
+ */
921
1099
  function addServerHandler(handler) {
922
1100
  useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler));
923
1101
  }
1102
+ /**
1103
+ * Adds a nitro server handler for development-only
1104
+ *
1105
+ */
924
1106
  function addDevServerHandler(handler) {
925
1107
  useNuxt().options.devServerHandlers.push(handler);
926
1108
  }
1109
+ /**
1110
+ * Adds a Nitro plugin
1111
+ */
927
1112
  function addServerPlugin(plugin) {
928
1113
  const nuxt = useNuxt();
929
1114
  nuxt.options.nitro.plugins ||= [];
930
1115
  nuxt.options.nitro.plugins.push(normalize(plugin));
931
1116
  }
1117
+ /**
1118
+ * Adds routes to be prerendered
1119
+ */
932
1120
  function addPrerenderRoutes(routes) {
933
1121
  const nuxt = useNuxt();
934
1122
  routes = toArray(routes).filter(Boolean);
@@ -937,11 +1125,28 @@ function addPrerenderRoutes(routes) {
937
1125
  for (const route of routes) ctx.routes.add(route);
938
1126
  });
939
1127
  }
1128
+ /**
1129
+ * Access to the Nitro instance
1130
+ *
1131
+ * **Note:** You can call `useNitro()` only after `ready` hook.
1132
+ *
1133
+ * **Note:** Changes to the Nitro instance configuration are not applied.
1134
+ * @example
1135
+ *
1136
+ * ```ts
1137
+ * nuxt.hook('ready', () => {
1138
+ * console.log(useNitro())
1139
+ * })
1140
+ * ```
1141
+ */
940
1142
  function useNitro() {
941
1143
  const nuxt = useNuxt();
942
1144
  if (!nuxt._nitro) throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
943
1145
  return nuxt._nitro;
944
1146
  }
1147
+ /**
1148
+ * Add server imports to be auto-imported by Nitro
1149
+ */
945
1150
  function addServerImports(imports) {
946
1151
  const nuxt = useNuxt();
947
1152
  const _imports = toArray(imports);
@@ -951,6 +1156,9 @@ function addServerImports(imports) {
951
1156
  config.imports.imports.push(..._imports);
952
1157
  });
953
1158
  }
1159
+ /**
1160
+ * Add directories to be scanned for auto-imports by Nitro
1161
+ */
954
1162
  function addServerImportsDir(dirs, opts = {}) {
955
1163
  const nuxt = useNuxt();
956
1164
  const _dirs = toArray(dirs);
@@ -960,12 +1168,23 @@ function addServerImportsDir(dirs, opts = {}) {
960
1168
  config.imports.dirs[opts.prepend ? "unshift" : "push"](..._dirs);
961
1169
  });
962
1170
  }
1171
+ /**
1172
+ * Add directories to be scanned by Nitro. It will check for subdirectories,
1173
+ * which will be registered just like the `~~/server` folder is.
1174
+ */
963
1175
  function addServerScanDir(dirs, opts = {}) {
964
1176
  useNuxt().hook("nitro:config", (config) => {
965
1177
  config.scanDirs ||= [];
966
1178
  for (const dir of toArray(dirs)) config.scanDirs[opts.prepend ? "unshift" : "push"](dir);
967
1179
  });
968
1180
  }
1181
+ //#endregion
1182
+ //#region src/runtime-config.ts
1183
+ /**
1184
+ * Access 'resolved' Nuxt runtime configuration, with values updated from environment.
1185
+ *
1186
+ * This mirrors the runtime behavior of Nitro.
1187
+ */
969
1188
  function useRuntimeConfig() {
970
1189
  const nuxt = useNuxt();
971
1190
  return applyEnv(klona(nuxt.options.nitro.runtimeConfig), {
@@ -974,6 +1193,9 @@ function useRuntimeConfig() {
974
1193
  envExpansion: nuxt.options.nitro.experimental?.envExpansion ?? !!process.env.NITRO_ENV_EXPANSION
975
1194
  });
976
1195
  }
1196
+ /**
1197
+ * Update Nuxt runtime configuration.
1198
+ */
977
1199
  function updateRuntimeConfig(runtimeConfig) {
978
1200
  const nuxt = useNuxt();
979
1201
  Object.assign(nuxt.options.nitro.runtimeConfig, defu(runtimeConfig, nuxt.options.nitro.runtimeConfig));
@@ -1011,6 +1233,8 @@ function _expandFromEnv(value, env = process.env) {
1011
1233
  return env[key] || match;
1012
1234
  });
1013
1235
  }
1236
+ //#endregion
1237
+ //#region src/build.ts
1014
1238
  const extendWebpackCompatibleConfig = (builder) => (fn, options = {}) => {
1015
1239
  const nuxt = useNuxt();
1016
1240
  if (options.dev === false && nuxt.options.dev) return;
@@ -1026,8 +1250,23 @@ const extendWebpackCompatibleConfig = (builder) => (fn, options = {}) => {
1026
1250
  }
1027
1251
  });
1028
1252
  };
1253
+ /**
1254
+ * Extend webpack config
1255
+ *
1256
+ * The fallback function might be called multiple times
1257
+ * when applying to both client and server builds.
1258
+ */
1029
1259
  const extendWebpackConfig = extendWebpackCompatibleConfig("webpack");
1260
+ /**
1261
+ * Extend rspack config
1262
+ *
1263
+ * The fallback function might be called multiple times
1264
+ * when applying to both client and server builds.
1265
+ */
1030
1266
  const extendRspackConfig = extendWebpackCompatibleConfig("rspack");
1267
+ /**
1268
+ * Extend Vite config
1269
+ */
1031
1270
  function extendViteConfig(fn, options = {}) {
1032
1271
  const nuxt = useNuxt();
1033
1272
  if (options.dev === false && nuxt.options.dev) return;
@@ -1038,6 +1277,9 @@ function extendViteConfig(fn, options = {}) {
1038
1277
  }
1039
1278
  return nuxt.hook("vite:extend", ({ config }) => fn(config));
1040
1279
  }
1280
+ /**
1281
+ * Append webpack plugin to the config.
1282
+ */
1041
1283
  function addWebpackPlugin(pluginOrGetter, options) {
1042
1284
  extendWebpackConfig(async (config) => {
1043
1285
  const method = options?.prepend ? "unshift" : "push";
@@ -1046,6 +1288,9 @@ function addWebpackPlugin(pluginOrGetter, options) {
1046
1288
  config.plugins[method](...toArray(plugin));
1047
1289
  }, options);
1048
1290
  }
1291
+ /**
1292
+ * Append rspack plugin to the config.
1293
+ */
1049
1294
  function addRspackPlugin(pluginOrGetter, options) {
1050
1295
  extendRspackConfig(async (config) => {
1051
1296
  const method = options?.prepend ? "unshift" : "push";
@@ -1054,6 +1299,9 @@ function addRspackPlugin(pluginOrGetter, options) {
1054
1299
  config.plugins[method](...toArray(plugin));
1055
1300
  }, options);
1056
1301
  }
1302
+ /**
1303
+ * Append Vite plugin to the config.
1304
+ */
1057
1305
  function addVitePlugin(pluginOrGetter, options = {}) {
1058
1306
  const nuxt = useNuxt();
1059
1307
  if (options.dev === false && nuxt.options.dev) return;
@@ -1094,6 +1342,11 @@ function addBuildPlugin(pluginFactory, options) {
1094
1342
  if (pluginFactory.webpack) addWebpackPlugin(pluginFactory.webpack, options);
1095
1343
  if (pluginFactory.rspack) addRspackPlugin(pluginFactory.rspack, options);
1096
1344
  }
1345
+ //#endregion
1346
+ //#region src/components.ts
1347
+ /**
1348
+ * Register a directory to be scanned for components and imported only when used.
1349
+ */
1097
1350
  function addComponentsDir(dir, opts = {}) {
1098
1351
  const nuxt = useNuxt();
1099
1352
  nuxt.options.components ||= [];
@@ -1102,6 +1355,9 @@ function addComponentsDir(dir, opts = {}) {
1102
1355
  dirs[opts.prepend ? "unshift" : "push"](dir);
1103
1356
  });
1104
1357
  }
1358
+ /**
1359
+ * This utility takes a file path or npm package that is scanned for named exports, which are get added automatically
1360
+ */
1105
1361
  function addComponentExports(opts) {
1106
1362
  const nuxt = useNuxt();
1107
1363
  const components = [];
@@ -1116,6 +1372,9 @@ function addComponentExports(opts) {
1116
1372
  });
1117
1373
  addComponents(components);
1118
1374
  }
1375
+ /**
1376
+ * Register a component by its name and filePath.
1377
+ */
1119
1378
  function addComponent(opts) {
1120
1379
  addComponents([normalizeComponent(opts)]);
1121
1380
  }
@@ -1159,6 +1418,11 @@ function normalizeComponent(opts) {
1159
1418
  ...opts
1160
1419
  };
1161
1420
  }
1421
+ //#endregion
1422
+ //#region src/template.ts
1423
+ /**
1424
+ * Renders given template during build into the virtual file system (and optionally to disk in the project `buildDir`)
1425
+ */
1162
1426
  function addTemplate(_template) {
1163
1427
  const nuxt = useNuxt();
1164
1428
  const template = normalizeTemplate(_template);
@@ -1174,12 +1438,23 @@ function addTemplate(_template) {
1174
1438
  nuxt.options.build.templates.push(template);
1175
1439
  return template;
1176
1440
  }
1441
+ /**
1442
+ * Adds a virtual file that can be used within the Nuxt Nitro server build.
1443
+ */
1177
1444
  function addServerTemplate(template) {
1178
1445
  const nuxt = useNuxt();
1179
1446
  nuxt.options.nitro.virtual ||= {};
1180
1447
  nuxt.options.nitro.virtual[template.filename] = template.getContents;
1181
1448
  return template;
1182
1449
  }
1450
+ /**
1451
+ * Renders given types during build to disk in the project `buildDir`
1452
+ * and register them as types.
1453
+ *
1454
+ * You can pass a second context object to specify in which context the type should be added.
1455
+ *
1456
+ * If no context object is passed, then it will only be added to the nuxt context.
1457
+ */
1183
1458
  function addTypeTemplate(_template, context) {
1184
1459
  const nuxt = useNuxt();
1185
1460
  const template = addTemplate(_template);
@@ -1203,6 +1478,9 @@ function addTypeTemplate(_template, context) {
1203
1478
  });
1204
1479
  return template;
1205
1480
  }
1481
+ /**
1482
+ * Normalize a nuxt template object
1483
+ */
1206
1484
  function normalizeTemplate(template, buildDir) {
1207
1485
  if (!template) throw new Error("Invalid template: " + JSON.stringify(template));
1208
1486
  if (typeof template === "string") template = { src: template };
@@ -1220,8 +1498,13 @@ function normalizeTemplate(template, buildDir) {
1220
1498
  template.dst ||= resolve(buildDir ?? useNuxt().options.buildDir, template.filename);
1221
1499
  return template;
1222
1500
  }
1501
+ /**
1502
+ * Trigger rebuilding Nuxt templates
1503
+ *
1504
+ * You can pass a filter within the options to selectively regenerate a subset of templates.
1505
+ */
1223
1506
  async function updateTemplates(options) {
1224
- return await tryUseNuxt()?.hooks.callHook("builder:generateApp", options);
1507
+ await tryUseNuxt()?.hooks.callHook("builder:generateApp", options);
1225
1508
  }
1226
1509
  function resolveLayerPaths(dirs, projectBuildDir) {
1227
1510
  const relativeRootDir = relativeWithDot(projectBuildDir, dirs.root);
@@ -1594,6 +1877,8 @@ function relativeWithDot(from, to) {
1594
1877
  function withTrailingSlash$1(dir) {
1595
1878
  return dir.replace(/[^/]$/, "$&/");
1596
1879
  }
1880
+ //#endregion
1881
+ //#region src/layout.ts
1597
1882
  const LAYOUT_RE = /["']/g;
1598
1883
  function addLayout(template, name) {
1599
1884
  const nuxt = useNuxt();
@@ -1617,6 +1902,8 @@ const strippedAtAliases = {
1617
1902
  "@": "",
1618
1903
  "@@": ""
1619
1904
  };
1905
+ //#endregion
1906
+ //#region src/pages.ts
1620
1907
  function extendPages(cb) {
1621
1908
  useNuxt().hook("pages:extend", cb);
1622
1909
  }
@@ -1643,6 +1930,11 @@ function addRouteMiddleware(input, options = {}) {
1643
1930
  }
1644
1931
  });
1645
1932
  }
1933
+ //#endregion
1934
+ //#region src/plugin.ts
1935
+ /**
1936
+ * Normalize a nuxt plugin object
1937
+ */
1646
1938
  const pluginSymbol = Symbol.for("nuxt plugin");
1647
1939
  function normalizePlugin(plugin) {
1648
1940
  if (typeof plugin === "string") plugin = { src: plugin };
@@ -1676,10 +1968,14 @@ function addPlugin(_plugin, opts = {}) {
1676
1968
  nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
1677
1969
  return plugin;
1678
1970
  }
1971
+ /**
1972
+ * Adds a template and registers as a nuxt plugin.
1973
+ */
1679
1974
  function addPluginTemplate(plugin, opts = {}) {
1680
1975
  return addPlugin(typeof plugin === "string" ? { src: plugin } : {
1681
1976
  ...plugin,
1682
1977
  src: addTemplate(plugin).dst
1683
1978
  }, opts);
1684
1979
  }
1980
+ //#endregion
1685
1981
  export { addBuildPlugin, addComponent, addComponentExports, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addRouteMiddleware, addRspackPlugin, addServerHandler, addServerImports, addServerImportsDir, addServerPlugin, addServerScanDir, addServerTemplate, addTemplate, addTypeTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, createIsIgnored, createResolver, defineNuxtModule, directoryToURL, extendNuxtSchema, extendPages, extendRouteRules, extendRspackConfig, extendViteConfig, extendWebpackConfig, findPath, getDirectory, getLayerDirectories, getNuxtCtx, getNuxtModuleVersion, getNuxtVersion, hasNuxtCompatibility, hasNuxtModule, hasNuxtModuleCompatibility, importModule, installModule, installModules, isIgnored, isNuxt2, isNuxt3, isNuxtMajorVersion, loadNuxt, loadNuxtConfig, loadNuxtModuleInstance, logger, normalizeModuleTranspilePath, normalizePlugin, normalizeSemanticVersion, normalizeTemplate, nuxtCtx, requireModule, resolveAlias, resolveFiles, resolveIgnorePatterns, resolveModule, resolveModuleWithOptions, resolveNuxtModule, resolvePath, runWithNuxtContext, setGlobalHead, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateRuntimeConfig, updateTemplates, useLogger, useNitro, useNuxt, useRuntimeConfig, writeTypes };