@nuxt/kit 3.0.0-rc.1 → 3.0.0-rc.11

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +66 -18
  2. package/dist/index.mjs +191 -96
  3. package/package.json +14 -14
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
- import { Nuxt, ModuleContainer, ModuleOptions, ModuleDefinition, NuxtModule, NuxtConfig, NuxtOptions, NuxtCompatibility, NuxtCompatibilityIssues, ComponentsDir, Component, NuxtHooks, NuxtPlugin, NuxtPluginTemplate, NuxtTemplate } from '@nuxt/schema';
1
+ import { Nuxt, ModuleContainer, ModuleOptions, ModuleDefinition, NuxtModule, NuxtConfig, NuxtOptions, ImportPresetWithDeprecation, NuxtCompatibility, NuxtCompatibilityIssues, ComponentsDir, Component, NuxtTemplate, NuxtHooks, NuxtPlugin, NuxtPluginTemplate, ResolvedNuxtTemplate } from '@nuxt/schema';
2
2
  import { LoadConfigOptions } from 'c12';
3
3
  import { Import } from 'unimport';
4
4
  import { Configuration, WebpackPluginInstance } from 'webpack';
5
5
  import { UserConfig, Plugin } from 'vite';
6
6
  import * as unctx from 'unctx';
7
7
  import { Middleware } from 'h3';
8
+ import { NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack';
8
9
  import * as consola from 'consola';
10
+ import { genSafeVariableName } from 'knitwork';
9
11
 
10
12
  declare function useModuleContainer(nuxt?: Nuxt): ModuleContainer;
11
13
 
@@ -35,8 +37,17 @@ interface LoadNuxtOptions extends LoadNuxtConfigOptions {
35
37
  declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
36
38
  declare function buildNuxt(nuxt: Nuxt): Promise<any>;
37
39
 
38
- declare function addAutoImport(imports: Import | Import[]): void;
39
- declare function addAutoImportDir(_autoImportDirs: string | string[]): void;
40
+ declare function addImports(imports: Import | Import[]): void;
41
+ /**
42
+ * @deprecated Please use `addImports` instead with nuxt>=3.0.0-rc.9
43
+ */
44
+ declare const addAutoImport: typeof addImports;
45
+ declare function addImportsDir(dirs: string | string[]): void;
46
+ /**
47
+ * @deprecated Please use `addImportsDir` instead with nuxt>=3.0.0-rc.9
48
+ */
49
+ declare const addAutoImportDir: typeof addImportsDir;
50
+ declare function addImportsSources(presets: ImportPresetWithDeprecation | ImportPresetWithDeprecation[]): void;
40
51
 
41
52
  interface ExtendConfigOptions {
42
53
  /**
@@ -51,8 +62,6 @@ interface ExtendConfigOptions {
51
62
  * @default true
52
63
  */
53
64
  build?: boolean;
54
- }
55
- interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
56
65
  /**
57
66
  * Install plugin on server side
58
67
  *
@@ -65,6 +74,8 @@ interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
65
74
  * @default true
66
75
  */
67
76
  client?: boolean;
77
+ }
78
+ interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
68
79
  /**
69
80
  * Install plugin on modern build
70
81
  *
@@ -85,7 +96,7 @@ declare function extendWebpackConfig(fn: ((config: Configuration) => void), opti
85
96
  /**
86
97
  * Extend Vite config
87
98
  */
88
- declare function extendViteConfig(fn: ((config: UserConfig) => void), options?: ExtendViteConfigOptions): void;
99
+ declare function extendViteConfig(fn: ((config: UserConfig) => void), options?: ExtendViteConfigOptions): (() => void) | undefined;
89
100
  /**
90
101
  * Append Webpack plugin to the config.
91
102
  */
@@ -170,6 +181,8 @@ declare function tryUseNuxt(): Nuxt | null;
170
181
  */
171
182
  declare function isIgnored(pathname: string): boolean;
172
183
 
184
+ declare function addLayout(this: any, template: NuxtTemplate, name?: string): void;
185
+
173
186
  declare function extendPages(cb: NuxtHooks['pages:extend']): void;
174
187
 
175
188
  /**
@@ -224,30 +237,64 @@ declare function findPath(paths: string | string[], opts?: ResolvePathOptions, p
224
237
  */
225
238
  declare function resolveAlias(path: string, alias?: Record<string, string>): string;
226
239
  interface Resolver {
227
- resolve(...path: any[]): string;
240
+ resolve(...path: string[]): string;
228
241
  resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
229
242
  }
230
243
  /**
231
244
  * Create a relative resolver
232
245
  */
233
246
  declare function createResolver(base: string | URL): Resolver;
234
- declare function resolveFiles(path: string, pattern: string | string[]): Promise<string[]>;
247
+ declare function resolveFiles(path: string, pattern: string | string[], opts?: {
248
+ followSymbolicLinks?: boolean;
249
+ }): Promise<string[]>;
235
250
 
236
- interface ServerMiddleware {
251
+ interface LegacyServerMiddleware {
237
252
  route?: string;
253
+ path?: string;
254
+ handle?: Middleware | string;
238
255
  handler: Middleware | string;
239
256
  }
240
- /** Adds a new server middleware to the end of the server middleware array. */
241
- declare function addServerMiddleware(middleware: ServerMiddleware): void;
257
+ /**
258
+ * Adds a new server middleware to the end of the server middleware array.
259
+ *
260
+ * @deprecated Use addServerHandler instead
261
+ */
262
+ declare function addServerMiddleware(middleware: LegacyServerMiddleware): void;
263
+ /**
264
+ * Adds a nitro server handler
265
+ *
266
+ */
267
+ declare function addServerHandler(handler: NitroEventHandler): void;
268
+ /**
269
+ * Adds a nitro server handler for development-only
270
+ *
271
+ */
272
+ declare function addDevServerHandler(handler: NitroDevEventHandler): void;
273
+ /**
274
+ * Access to the Nitro instance
275
+ *
276
+ * **Note:** You can call `useNitro()` only after `ready` hook.
277
+ *
278
+ * **Note:** Changes to the Nitro instance configuration are not applied.
279
+ *
280
+ * @example
281
+ *
282
+ * ```ts
283
+ * nuxt.hook('ready', () => {
284
+ * console.log(useNitro())
285
+ * })
286
+ * ```
287
+ */
288
+ declare function useNitro(): Nitro;
242
289
 
243
290
  /**
244
291
  * Renders given template using lodash template during build into the project buildDir
245
292
  */
246
- declare function addTemplate(_template: NuxtTemplate | string): NuxtTemplate;
293
+ declare function addTemplate(_template: NuxtTemplate<any> | string): ResolvedNuxtTemplate<any>;
247
294
  /**
248
295
  * Normalize a nuxt template object
249
296
  */
250
- declare function normalizeTemplate(template: NuxtTemplate | string): NuxtTemplate;
297
+ declare function normalizeTemplate(template: NuxtTemplate<any> | string): ResolvedNuxtTemplate<any>;
251
298
 
252
299
  declare const logger: consola.Consola;
253
300
  declare function useLogger(scope?: string): consola.Consola;
@@ -265,7 +312,7 @@ declare function isNodeModules(id: string): boolean;
265
312
  declare function clearRequireCache(id: string): void;
266
313
  declare function scanRequireTree(id: string, files?: Set<string>): Set<string>;
267
314
  /** Access the require cache by module id. */
268
- declare function getRequireCacheItem(id: string): NodeModule;
315
+ declare function getRequireCacheItem(id: string): NodeModule | undefined;
269
316
  /** Resolve the `package.json` file for a given module. */
270
317
  declare function requireModulePkg(id: string, opts?: RequireModuleOptions): any;
271
318
  /** Resolve the path of a module. */
@@ -275,17 +322,18 @@ declare function tryResolveModule(path: string, opts?: ResolveModuleOptions): st
275
322
  /** Require a module and return it. */
276
323
  declare function requireModule(id: string, opts?: RequireModuleOptions): any;
277
324
  declare function importModule(id: string, opts?: RequireModuleOptions): Promise<any>;
278
- declare function tryImportModule(id: string, opts?: RequireModuleOptions): Promise<any>;
325
+ declare function tryImportModule(id: string, opts?: RequireModuleOptions): Promise<any> | undefined;
279
326
  /** Try to require a module, but don't emit an error if the module can't be required. */
280
327
  declare function tryRequireModule(id: string, opts?: RequireModuleOptions): any;
281
328
 
282
329
  declare function compileTemplate(template: NuxtTemplate, ctx: any): Promise<string>;
330
+ /** @deprecated */
283
331
  declare const templateUtils: {
284
332
  serialize: (data: any) => string;
285
- importName: (src: string) => string;
333
+ importName: typeof genSafeVariableName;
286
334
  importSources: (sources: string | string[], { lazy }?: {
287
- lazy?: boolean;
335
+ lazy?: boolean | undefined;
288
336
  }) => string;
289
337
  };
290
338
 
291
- export { AddComponentOptions, AddPluginOptions, ExtendConfigOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, LoadNuxtConfigOptions, LoadNuxtOptions, RequireModuleOptions, ResolveModuleOptions, ResolvePathOptions, Resolver, ServerMiddleware, addAutoImport, addAutoImportDir, addComponent, addComponentsDir, addPlugin, addPluginTemplate, addServerMiddleware, addTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, clearRequireCache, compileTemplate, createResolver, defineNuxtModule, extendPages, extendViteConfig, extendWebpackConfig, findPath, getNuxtVersion, getRequireCacheItem, hasNuxtCompatibility, importModule, installModule, isIgnored, isNodeModules, isNuxt2, isNuxt3, loadNuxt, loadNuxtConfig, logger, normalizePlugin, normalizeTemplate, nuxtCtx, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, useLogger, useModuleContainer, useNuxt };
339
+ export { AddComponentOptions, AddPluginOptions, ExtendConfigOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, LegacyServerMiddleware, LoadNuxtConfigOptions, LoadNuxtOptions, RequireModuleOptions, ResolveModuleOptions, ResolvePathOptions, Resolver, addAutoImport, addAutoImportDir, addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addServerHandler, addServerMiddleware, addTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, clearRequireCache, compileTemplate, createResolver, defineNuxtModule, extendPages, extendViteConfig, extendWebpackConfig, findPath, getNuxtVersion, getRequireCacheItem, hasNuxtCompatibility, importModule, installModule, isIgnored, isNodeModules, isNuxt2, isNuxt3, loadNuxt, loadNuxtConfig, logger, normalizePlugin, normalizeTemplate, nuxtCtx, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, useLogger, useModuleContainer, useNitro, useNuxt };
package/dist/index.mjs CHANGED
@@ -1,28 +1,24 @@
1
- import { parse, basename, resolve, normalize, join, relative, isAbsolute, dirname, extname } from 'pathe';
2
- import consola from 'consola';
1
+ import { parse, basename, resolve, relative, join, normalize, isAbsolute, dirname } from 'pathe';
3
2
  import { existsSync, readFileSync, promises } from 'node:fs';
4
3
  import hash from 'hash-sum';
5
4
  import { getContext } from 'unctx';
5
+ import { kebabCase, pascalCase } from 'scule';
6
6
  import satisfies from 'semver/functions/satisfies.js';
7
+ import consola from 'consola';
7
8
  import { pathToFileURL, fileURLToPath } from 'node:url';
9
+ import { globby } from 'globby';
10
+ import { normalizeAliases } from 'pathe/utils';
8
11
  import { interopDefault } from 'mlly';
9
12
  import jiti from 'jiti';
10
- import { globby } from 'globby';
11
13
  import ignore from 'ignore';
12
14
  import defu from 'defu';
13
15
  import { applyDefaults } from 'untyped';
14
16
  import lodashTemplate from 'lodash.template';
15
- import { camelCase, kebabCase, pascalCase } from 'scule';
16
- import { genDynamicImport, genImport } from 'knitwork';
17
+ import { genSafeVariableName, genDynamicImport, genImport } from 'knitwork';
17
18
  import { loadConfig } from 'c12';
18
19
  import { NuxtConfigSchema } from '@nuxt/schema';
19
20
  import { resolvePackageJSON, readPackageJSON } from 'pkg-types';
20
21
 
21
- const logger = consola;
22
- function useLogger(scope) {
23
- return scope ? logger.withScope(scope) : logger;
24
- }
25
-
26
22
  function chainFn(base, fn) {
27
23
  if (typeof fn !== "function") {
28
24
  return base;
@@ -35,7 +31,11 @@ function chainFn(base, fn) {
35
31
  if (baseResult === void 0) {
36
32
  [baseResult] = args;
37
33
  }
38
- const fnResult = fn.call(this, baseResult, ...Array.prototype.slice.call(args, 1));
34
+ const fnResult = fn.call(
35
+ this,
36
+ baseResult,
37
+ ...Array.prototype.slice.call(args, 1)
38
+ );
39
39
  if (fnResult === void 0) {
40
40
  return baseResult;
41
41
  }
@@ -45,14 +45,14 @@ function chainFn(base, fn) {
45
45
 
46
46
  const nuxtCtx = getContext("nuxt");
47
47
  function useNuxt() {
48
- const instance = nuxtCtx.use();
48
+ const instance = nuxtCtx.tryUse();
49
49
  if (!instance) {
50
50
  throw new Error("Nuxt instance is unavailable!");
51
51
  }
52
52
  return instance;
53
53
  }
54
54
  function tryUseNuxt() {
55
- return nuxtCtx.use();
55
+ return nuxtCtx.tryUse();
56
56
  }
57
57
 
58
58
  function addTemplate(_template) {
@@ -96,16 +96,12 @@ function normalizeTemplate(template) {
96
96
  return template;
97
97
  }
98
98
 
99
- function addServerMiddleware(middleware) {
100
- useNuxt().options.serverMiddleware.push(middleware);
101
- }
102
-
103
99
  async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
104
100
  const issues = [];
105
101
  if (constraints.nuxt) {
106
102
  const nuxtVersion = getNuxtVersion(nuxt);
107
- const nuxtSemanticVersion = nuxtVersion.split("-").shift();
108
- if (!satisfies(nuxtSemanticVersion, constraints.nuxt)) {
103
+ const nuxtSemanticVersion = nuxtVersion.replace(/-[0-9]+\.[0-9a-f]{7,8}/, "");
104
+ if (!satisfies(nuxtSemanticVersion, constraints.nuxt, { includePrerelease: true })) {
109
105
  issues.push({
110
106
  name: "nuxt",
111
107
  message: `Nuxt version \`${constraints.nuxt}\` is required but currently using \`${nuxtVersion}\``
@@ -113,7 +109,7 @@ async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
113
109
  }
114
110
  }
115
111
  if (isNuxt2(nuxt)) {
116
- const bridgeRequirement = constraints?.bridge;
112
+ const bridgeRequirement = constraints.bridge;
117
113
  const hasBridge = !!nuxt.options.bridge;
118
114
  if (bridgeRequirement === true && !hasBridge) {
119
115
  issues.push({
@@ -151,43 +147,72 @@ function isNuxt3(nuxt = useNuxt()) {
151
147
  function getNuxtVersion(nuxt = useNuxt()) {
152
148
  const version = (nuxt?._version || nuxt?.version || nuxt?.constructor?.version || "").replace(/^v/g, "");
153
149
  if (!version) {
154
- throw new Error("Cannot determine nuxt version! Is currect instance passed?");
150
+ throw new Error("Cannot determine nuxt version! Is current instance passed?");
155
151
  }
156
152
  return version;
157
153
  }
158
154
 
159
- function normalizePlugin(plugin) {
160
- if (typeof plugin === "string") {
161
- plugin = { src: plugin };
162
- } else {
163
- plugin = { ...plugin };
164
- }
165
- if (!plugin.src) {
166
- throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
167
- }
168
- plugin.src = normalize(plugin.src);
169
- if (plugin.ssr) {
170
- plugin.mode = "server";
171
- }
172
- if (!plugin.mode) {
173
- const [, mode = "all"] = plugin.src.match(/\.(server|client)(\.\w+)*$/) || [];
174
- plugin.mode = mode;
175
- }
176
- return plugin;
155
+ const logger = consola;
156
+ function useLogger(scope) {
157
+ return scope ? logger.withScope(scope) : logger;
177
158
  }
178
- function addPlugin(_plugin, opts = {}) {
159
+
160
+ function addLayout(template, name) {
179
161
  const nuxt = useNuxt();
180
- const plugin = normalizePlugin(_plugin);
181
- nuxt.options.plugins = nuxt.options.plugins.filter((p) => normalizePlugin(p).src !== plugin.src);
182
- nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
183
- return plugin;
162
+ const { filename, src } = addTemplate(template);
163
+ const layoutName = kebabCase(name || parse(filename).name).replace(/["']/g, "");
164
+ if (isNuxt2(nuxt)) {
165
+ const layout = nuxt.options.layouts[layoutName];
166
+ if (layout) {
167
+ return logger.warn(
168
+ `Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`
169
+ );
170
+ }
171
+ nuxt.options.layouts[layoutName] = `./${filename}`;
172
+ if (name === "error") {
173
+ this.addErrorLayout(filename);
174
+ }
175
+ return;
176
+ }
177
+ nuxt.hook("app:templates", (app) => {
178
+ if (layoutName in app.layouts) {
179
+ const relativePath = relative(nuxt.options.srcDir, app.layouts[layoutName].file);
180
+ return logger.warn(
181
+ `Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`
182
+ );
183
+ }
184
+ app.layouts[layoutName] = {
185
+ file: join("#build", filename),
186
+ name: layoutName
187
+ };
188
+ });
184
189
  }
185
- function addPluginTemplate(plugin, opts = {}) {
186
- const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
187
- return addPlugin(normalizedPlugin, opts);
190
+
191
+ function normalizeHandlerMethod(handler) {
192
+ const [, method = void 0] = handler.handler.match(/\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/) || [];
193
+ return {
194
+ method,
195
+ ...handler
196
+ };
197
+ }
198
+ function addServerMiddleware(middleware) {
199
+ useNuxt().options.serverMiddleware.push(middleware);
200
+ }
201
+ function addServerHandler(handler) {
202
+ useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler));
203
+ }
204
+ function addDevServerHandler(handler) {
205
+ useNuxt().options.devServerHandlers.push(handler);
206
+ }
207
+ function useNitro() {
208
+ const nuxt = useNuxt();
209
+ if (!nuxt._nitro) {
210
+ throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
211
+ }
212
+ return nuxt._nitro;
188
213
  }
189
214
 
190
- const _require = jiti(process.cwd(), { interopDefault: true });
215
+ const _require = jiti(process.cwd(), { interopDefault: true, esmResolve: true });
191
216
  function isNodeModules(id) {
192
217
  return /[/\\]node_modules[/\\]/.test(id);
193
218
  }
@@ -234,14 +259,19 @@ function requireModulePkg(id, opts = {}) {
234
259
  }
235
260
  function resolveModule(id, opts = {}) {
236
261
  return normalize(_require.resolve(id, {
237
- paths: [].concat(global.__NUXT_PREPATHS__, opts.paths, process.cwd(), global.__NUXT_PATHS__).filter(Boolean)
262
+ paths: [].concat(
263
+ global.__NUXT_PREPATHS__,
264
+ opts.paths || [],
265
+ process.cwd(),
266
+ global.__NUXT_PATHS__
267
+ ).filter(Boolean)
238
268
  }));
239
269
  }
240
270
  function tryResolveModule(path, opts = {}) {
241
271
  try {
242
272
  return resolveModule(path, opts);
243
273
  } catch (error) {
244
- if (error.code !== "MODULE_NOT_FOUND") {
274
+ if (error?.code !== "MODULE_NOT_FOUND") {
245
275
  throw error;
246
276
  }
247
277
  }
@@ -278,7 +308,7 @@ function tryRequireModule(id, opts = {}) {
278
308
  function isIgnored(pathname) {
279
309
  const nuxt = tryUseNuxt();
280
310
  if (!nuxt) {
281
- return null;
311
+ return false;
282
312
  }
283
313
  if (!nuxt._ignore) {
284
314
  nuxt._ignore = ignore(nuxt.options.ignoreOptions);
@@ -292,13 +322,13 @@ function isIgnored(pathname) {
292
322
  if (relativePath.startsWith("..")) {
293
323
  return false;
294
324
  }
295
- return relativePath && nuxt._ignore.ignores(relativePath);
325
+ return !!(relativePath && nuxt._ignore.ignores(relativePath));
296
326
  }
297
327
 
298
328
  async function resolvePath(path, opts = {}) {
299
329
  const _path = path;
300
330
  path = normalize(path);
301
- if (isAbsolute(path) && existsSync(path)) {
331
+ if (isAbsolute(path) && existsSync(path) && !await isDirectory(path)) {
302
332
  return path;
303
333
  }
304
334
  const nuxt = useNuxt();
@@ -309,10 +339,10 @@ async function resolvePath(path, opts = {}) {
309
339
  if (!isAbsolute(path)) {
310
340
  path = resolve(cwd, path);
311
341
  }
312
- let isDirectory = false;
342
+ let _isDir = false;
313
343
  if (existsSync(path)) {
314
- isDirectory = (await promises.lstat(path)).isDirectory();
315
- if (!isDirectory) {
344
+ _isDir = await isDirectory(path);
345
+ if (!_isDir) {
316
346
  return path;
317
347
  }
318
348
  }
@@ -322,7 +352,7 @@ async function resolvePath(path, opts = {}) {
322
352
  return pathWithExt;
323
353
  }
324
354
  const pathWithIndex = join(path, "index" + ext);
325
- if (isDirectory && existsSync(pathWithIndex)) {
355
+ if (_isDir && existsSync(pathWithIndex)) {
326
356
  return pathWithIndex;
327
357
  }
328
358
  }
@@ -339,8 +369,8 @@ async function findPath(paths, opts, pathType = "file") {
339
369
  for (const path of paths) {
340
370
  const rPath = await resolvePath(path, opts);
341
371
  if (await existsSensitive(rPath)) {
342
- const isDirectory = (await promises.lstat(rPath)).isDirectory();
343
- if (!pathType || pathType === "file" && !isDirectory || pathType === "dir" && isDirectory) {
372
+ const _isDir = await isDirectory(rPath);
373
+ if (!pathType || pathType === "file" && !_isDir || pathType === "dir" && _isDir) {
344
374
  return rPath;
345
375
  }
346
376
  }
@@ -351,7 +381,7 @@ function resolveAlias(path, alias) {
351
381
  if (!alias) {
352
382
  alias = tryUseNuxt()?.options.alias || {};
353
383
  }
354
- for (const key in alias) {
384
+ for (const key in normalizeAliases(alias)) {
355
385
  if (key === "@" && !path.startsWith("@/")) {
356
386
  continue;
357
387
  }
@@ -381,15 +411,53 @@ async function existsSensitive(path) {
381
411
  const dirFiles = await promises.readdir(dirname(path));
382
412
  return dirFiles.includes(basename(path));
383
413
  }
384
- async function resolveFiles(path, pattern) {
385
- const files = await globby(pattern, { cwd: path, followSymbolicLinks: true });
386
- return files.filter((p) => !isIgnored(p)).map((p) => resolve(path, p));
414
+ async function isDirectory(path) {
415
+ return (await promises.lstat(path)).isDirectory();
416
+ }
417
+ async function resolveFiles(path, pattern, opts = {}) {
418
+ const files = await globby(pattern, { cwd: path, followSymbolicLinks: opts.followSymbolicLinks ?? true });
419
+ return files.map((p) => resolve(path, p)).filter((p) => !isIgnored(p)).sort();
420
+ }
421
+
422
+ function normalizePlugin(plugin) {
423
+ if (typeof plugin === "string") {
424
+ plugin = { src: plugin };
425
+ } else {
426
+ plugin = { ...plugin };
427
+ }
428
+ if (!plugin.src) {
429
+ throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
430
+ }
431
+ plugin.src = normalize(resolveAlias(plugin.src));
432
+ if (plugin.ssr) {
433
+ plugin.mode = "server";
434
+ }
435
+ if (!plugin.mode) {
436
+ const [, mode = "all"] = plugin.src.match(/\.(server|client)(\.\w+)*$/) || [];
437
+ plugin.mode = mode;
438
+ }
439
+ return plugin;
440
+ }
441
+ function addPlugin(_plugin, opts = {}) {
442
+ const nuxt = useNuxt();
443
+ const plugin = normalizePlugin(_plugin);
444
+ nuxt.options.plugins = nuxt.options.plugins.filter((p) => normalizePlugin(p).src !== plugin.src);
445
+ nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
446
+ return plugin;
447
+ }
448
+ function addPluginTemplate(plugin, opts = {}) {
449
+ const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
450
+ return addPlugin(normalizedPlugin, opts);
387
451
  }
388
452
 
389
453
  async function installModule(moduleToInstall, _inlineOptions, _nuxt) {
390
454
  const nuxt = useNuxt();
391
455
  const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions);
392
- await nuxtModule.call(useModuleContainer(), inlineOptions, nuxt);
456
+ await nuxtModule.call(
457
+ useModuleContainer(),
458
+ inlineOptions,
459
+ nuxt
460
+ );
393
461
  nuxt.options._installedModules = nuxt.options._installedModules || [];
394
462
  nuxt.options._installedModules.push({
395
463
  meta: await nuxtModule.getMeta?.(),
@@ -436,7 +504,7 @@ function useModuleContainer(nuxt = useNuxt()) {
436
504
  }
437
505
  await installModule(src, inlineOptions);
438
506
  }
439
- nuxt[MODULE_CONTAINER_KEY] = {
507
+ const container = {
440
508
  nuxt,
441
509
  options: nuxt.options,
442
510
  ready() {
@@ -460,16 +528,7 @@ function useModuleContainer(nuxt = useNuxt()) {
460
528
  return addPluginTemplate(pluginTemplate);
461
529
  },
462
530
  addLayout(tmpl, name) {
463
- const { filename, src } = addTemplate(tmpl);
464
- const layoutName = name || parse(src).name;
465
- const layout = nuxt.options.layouts[layoutName];
466
- if (layout) {
467
- logger.warn(`Duplicate layout registration, "${layoutName}" has been registered as "${layout}"`);
468
- }
469
- nuxt.options.layouts[layoutName] = `./${filename}`;
470
- if (name === "error") {
471
- this.addErrorLayout(filename);
472
- }
531
+ return addLayout(tmpl, name);
473
532
  },
474
533
  addErrorLayout(dst) {
475
534
  const relativeBuildDir = relative(nuxt.options.rootDir, nuxt.options.buildDir);
@@ -494,6 +553,7 @@ function useModuleContainer(nuxt = useNuxt()) {
494
553
  }
495
554
  }
496
555
  };
556
+ nuxt[MODULE_CONTAINER_KEY] = container;
497
557
  return nuxt[MODULE_CONTAINER_KEY];
498
558
  }
499
559
 
@@ -514,18 +574,18 @@ async function compileTemplate(template, ctx) {
514
574
  throw new Error("Invalid template: " + JSON.stringify(template));
515
575
  }
516
576
  const serialize = (data) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, (r) => JSON.parse(r).replace(/^{(.*)}$/, "$1"));
517
- const importName = (src) => `${camelCase(basename(src, extname(src))).replace(/[^a-zA-Z?\d\s:]/g, "")}_${hash(src)}`;
518
577
  const importSources = (sources, { lazy = false } = {}) => {
519
578
  if (!Array.isArray(sources)) {
520
579
  sources = [sources];
521
580
  }
522
581
  return sources.map((src) => {
523
582
  if (lazy) {
524
- return `const ${importName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
583
+ return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
525
584
  }
526
- return genImport(src, importName(src));
585
+ return genImport(src, genSafeVariableName(src));
527
586
  }).join("\n");
528
587
  };
588
+ const importName = genSafeVariableName;
529
589
  const templateUtils = { serialize, importName, importSources };
530
590
 
531
591
  function defineNuxtModule(definition) {
@@ -538,14 +598,14 @@ function defineNuxtModule(definition) {
538
598
  }
539
599
  if (!definition.meta.configKey) {
540
600
  definition.meta.name = definition.meta.name || definition.name;
541
- definition.meta.configKey = definition.meta.configKey || definition.configKey || definition.meta.name;
601
+ definition.meta.configKey = definition.configKey || definition.meta.name;
542
602
  }
543
- function getOptions(inlineOptions, nuxt = useNuxt()) {
603
+ async function getOptions(inlineOptions, nuxt = useNuxt()) {
544
604
  const configKey = definition.meta.configKey || definition.meta.name;
545
605
  const _defaults = definition.defaults instanceof Function ? definition.defaults(nuxt) : definition.defaults;
546
606
  let _options = defu(inlineOptions, nuxt.options[configKey], _defaults);
547
607
  if (definition.schema) {
548
- _options = applyDefaults(definition.schema, _options);
608
+ _options = await applyDefaults(definition.schema, _options);
549
609
  }
550
610
  return Promise.resolve(_options);
551
611
  }
@@ -587,7 +647,7 @@ function nuxt2Shims(nuxt) {
587
647
  }
588
648
  nuxt[NUXT2_SHIMS_KEY] = true;
589
649
  nuxt.hooks = nuxt;
590
- if (!nuxtCtx.use()) {
650
+ if (!nuxtCtx.tryUse()) {
591
651
  nuxtCtx.set(nuxt);
592
652
  nuxt.hook("close", () => nuxtCtx.unset());
593
653
  }
@@ -622,23 +682,38 @@ function nuxt2Shims(nuxt) {
622
682
  }
623
683
 
624
684
  async function loadNuxtConfig(opts) {
625
- const { config: nuxtConfig, configFile, layers, cwd } = await loadConfig({
685
+ globalThis.defineNuxtConfig = (c) => c;
686
+ const result = await loadConfig({
626
687
  name: "nuxt",
627
688
  configFile: "nuxt.config",
628
689
  rcFile: ".nuxtrc",
690
+ extend: { extendKey: ["theme", "extends"] },
629
691
  dotenv: true,
630
692
  globalRc: true,
631
693
  ...opts
632
694
  });
695
+ delete globalThis.defineNuxtConfig;
696
+ const { configFile, layers = [], cwd } = result;
697
+ const nuxtConfig = result.config;
633
698
  nuxtConfig.rootDir = nuxtConfig.rootDir || cwd;
634
699
  nuxtConfig._nuxtConfigFile = configFile;
635
700
  nuxtConfig._nuxtConfigFiles = [configFile];
636
701
  for (const layer of layers) {
702
+ layer.config = layer.config || {};
637
703
  layer.config.rootDir = layer.config.rootDir ?? layer.cwd;
638
704
  layer.config.srcDir = resolve(layer.config.rootDir, layer.config.srcDir);
639
705
  }
640
706
  nuxtConfig._layers = layers.filter((layer) => layer.configFile && !layer.configFile.endsWith(".nuxtrc"));
641
- return applyDefaults(NuxtConfigSchema, nuxtConfig);
707
+ if (!nuxtConfig._layers.length) {
708
+ nuxtConfig._layers.push({
709
+ cwd,
710
+ config: {
711
+ rootDir: cwd,
712
+ srcDir: cwd
713
+ }
714
+ });
715
+ }
716
+ return await applyDefaults(NuxtConfigSchema, nuxtConfig);
642
717
  }
643
718
 
644
719
  async function loadNuxt(opts) {
@@ -677,19 +752,29 @@ async function buildNuxt(nuxt) {
677
752
  return build(nuxt);
678
753
  }
679
754
 
680
- function addAutoImport(imports) {
755
+ function addImports(imports) {
681
756
  assertNuxtCompatibility({ bridge: true });
682
- useNuxt().hook("autoImports:extend", (autoImports) => {
683
- autoImports.push(...Array.isArray(imports) ? imports : [imports]);
684
- });
757
+ useNuxt().hook("autoImports:extend", (_imports) => {
758
+ _imports.push(...Array.isArray(imports) ? imports : [imports]);
759
+ }, { allowDeprecated: true });
685
760
  }
686
- function addAutoImportDir(_autoImportDirs) {
761
+ const addAutoImport = addImports;
762
+ function addImportsDir(dirs) {
687
763
  assertNuxtCompatibility({ bridge: true });
688
- useNuxt().hook("autoImports:dirs", (autoImportDirs) => {
689
- for (const dir of Array.isArray(_autoImportDirs) ? _autoImportDirs : [_autoImportDirs]) {
690
- autoImportDirs.push(dir);
764
+ useNuxt().hook("autoImports:dirs", (_dirs) => {
765
+ for (const dir of Array.isArray(dirs) ? dirs : [dirs]) {
766
+ _dirs.push(dir);
691
767
  }
692
- });
768
+ }, { allowDeprecated: true });
769
+ }
770
+ const addAutoImportDir = addImportsDir;
771
+ function addImportsSources(presets) {
772
+ assertNuxtCompatibility({ bridge: true });
773
+ useNuxt().hook("autoImports:sources", (_presets) => {
774
+ for (const preset of Array.isArray(presets) ? presets : [presets]) {
775
+ _presets.push(preset);
776
+ }
777
+ }, { allowDeprecated: true });
693
778
  }
694
779
 
695
780
  function extendWebpackConfig(fn, options = {}) {
@@ -729,7 +814,17 @@ function extendViteConfig(fn, options = {}) {
729
814
  if (options.build === false && nuxt.options.build) {
730
815
  return;
731
816
  }
732
- nuxt.hook("vite:extend", ({ config }) => fn(config));
817
+ if (options.server !== false && options.client !== false) {
818
+ return nuxt.hook("vite:extend", ({ config }) => fn(config));
819
+ }
820
+ nuxt.hook("vite:extendConfig", (config, { isClient, isServer }) => {
821
+ if (options.server !== false && isServer) {
822
+ return fn(config);
823
+ }
824
+ if (options.client !== false && isClient) {
825
+ return fn(config);
826
+ }
827
+ });
733
828
  }
734
829
  function addWebpackPlugin(plugin, options) {
735
830
  extendWebpackConfig((config) => {
@@ -773,7 +868,7 @@ async function addComponent(opts) {
773
868
  ...opts
774
869
  };
775
870
  nuxt.hook("components:extend", (components) => {
776
- const existingComponent = components.find((c) => c.pascalName === component.pascalName || c.kebabName === component.kebabName);
871
+ const existingComponent = components.find((c) => (c.pascalName === component.pascalName || c.kebabName === component.kebabName) && c.mode === component.mode);
777
872
  if (existingComponent) {
778
873
  const name = existingComponent.pascalName || existingComponent.kebabName;
779
874
  console.warn(`Overriding ${name} component.`);
@@ -793,4 +888,4 @@ function extendPages(cb) {
793
888
  }
794
889
  }
795
890
 
796
- export { addAutoImport, addAutoImportDir, addComponent, addComponentsDir, addPlugin, addPluginTemplate, addServerMiddleware, addTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, clearRequireCache, compileTemplate, createResolver, defineNuxtModule, extendPages, extendViteConfig, extendWebpackConfig, findPath, getNuxtVersion, getRequireCacheItem, hasNuxtCompatibility, importModule, installModule, isIgnored, isNodeModules, isNuxt2, isNuxt3, loadNuxt, loadNuxtConfig, logger, normalizePlugin, normalizeTemplate, nuxtCtx, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, useLogger, useModuleContainer, useNuxt };
891
+ export { addAutoImport, addAutoImportDir, addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addServerHandler, addServerMiddleware, addTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, clearRequireCache, compileTemplate, createResolver, defineNuxtModule, extendPages, extendViteConfig, extendWebpackConfig, findPath, getNuxtVersion, getRequireCacheItem, hasNuxtCompatibility, importModule, installModule, isIgnored, isNodeModules, isNuxt2, isNuxt3, loadNuxt, loadNuxtConfig, logger, normalizePlugin, normalizeTemplate, nuxtCtx, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, useLogger, useModuleContainer, useNitro, useNuxt };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/kit",
3
- "version": "3.0.0-rc.1",
3
+ "version": "3.0.0-rc.11",
4
4
  "repository": "nuxt/framework",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -13,24 +13,24 @@
13
13
  "prepack": "unbuild"
14
14
  },
15
15
  "dependencies": {
16
- "@nuxt/schema": "^3.0.0-rc.1",
17
- "c12": "^0.2.7",
16
+ "@nuxt/schema": "3.0.0-rc.11",
17
+ "c12": "^0.2.13",
18
18
  "consola": "^2.15.3",
19
- "defu": "^6.0.0",
20
- "globby": "^13.1.1",
19
+ "defu": "^6.1.0",
20
+ "globby": "^13.1.2",
21
21
  "hash-sum": "^2.0.0",
22
22
  "ignore": "^5.2.0",
23
- "jiti": "^1.13.0",
24
- "knitwork": "^0.1.1",
23
+ "jiti": "^1.16.0",
24
+ "knitwork": "^0.1.2",
25
25
  "lodash.template": "^4.5.0",
26
- "mlly": "^0.5.2",
27
- "pathe": "^0.2.0",
28
- "pkg-types": "^0.3.2",
29
- "scule": "^0.2.1",
26
+ "mlly": "^0.5.16",
27
+ "pathe": "^0.3.8",
28
+ "pkg-types": "^0.3.5",
29
+ "scule": "^0.3.2",
30
30
  "semver": "^7.3.7",
31
- "unctx": "^1.1.4",
32
- "unimport": "^0.1.6",
33
- "untyped": "^0.4.4"
31
+ "unctx": "^2.0.2",
32
+ "unimport": "^0.6.7",
33
+ "untyped": "^0.5.0"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@types/lodash.template": "^4",