@nuxt/kit 3.0.0-rc.9 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 - Nuxt Project
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.d.ts CHANGED
@@ -1,16 +1,13 @@
1
- import { Nuxt, ModuleContainer, ModuleOptions, ModuleDefinition, NuxtModule, NuxtConfig, NuxtOptions, NuxtCompatibility, NuxtCompatibilityIssues, ComponentsDir, Component, NuxtTemplate, NuxtHooks, NuxtPlugin, NuxtPluginTemplate, ResolvedNuxtTemplate } from '@nuxt/schema';
1
+ import { ModuleOptions, ModuleDefinition, NuxtModule, Nuxt, 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
- import * as unctx from 'unctx';
7
- import { Middleware } from 'h3';
8
- import { NitroEventHandler, NitroDevEventHandler } from 'nitropack';
6
+ import * as unctx_index from 'unctx/index';
7
+ import { NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack';
9
8
  import * as consola from 'consola';
10
9
  import { genSafeVariableName } from 'knitwork';
11
10
 
12
- declare function useModuleContainer(nuxt?: Nuxt): ModuleContainer;
13
-
14
11
  /**
15
12
  * Define a Nuxt module, automatically merging defaults with user provided options, installing
16
13
  * any hooks that are provided, and calling an optional setup function for full control.
@@ -38,15 +35,8 @@ declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
38
35
  declare function buildNuxt(nuxt: Nuxt): Promise<any>;
39
36
 
40
37
  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
38
  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;
39
+ declare function addImportsSources(presets: ImportPresetWithDeprecation | ImportPresetWithDeprecation[]): void;
50
40
 
51
41
  interface ExtendConfigOptions {
52
42
  /**
@@ -75,13 +65,6 @@ interface ExtendConfigOptions {
75
65
  client?: boolean;
76
66
  }
77
67
  interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
78
- /**
79
- * Install plugin on modern build
80
- *
81
- * @default true
82
- * @deprecated Nuxt 2 only
83
- */
84
- modern?: boolean;
85
68
  }
86
69
  interface ExtendViteConfigOptions extends ExtendConfigOptions {
87
70
  }
@@ -99,11 +82,11 @@ declare function extendViteConfig(fn: ((config: UserConfig) => void), options?:
99
82
  /**
100
83
  * Append Webpack plugin to the config.
101
84
  */
102
- declare function addWebpackPlugin(plugin: WebpackPluginInstance, options?: ExtendWebpackConfigOptions): void;
85
+ declare function addWebpackPlugin(plugin: WebpackPluginInstance | WebpackPluginInstance[], options?: ExtendWebpackConfigOptions): void;
103
86
  /**
104
87
  * Append Vite plugin to the config.
105
88
  */
106
- declare function addVitePlugin(plugin: Plugin, options?: ExtendViteConfigOptions): void;
89
+ declare function addVitePlugin(plugin: Plugin | Plugin[], options?: ExtendViteConfigOptions): void;
107
90
 
108
91
  /**
109
92
  * Check version constraints and return incompatibility issues as an array
@@ -136,7 +119,7 @@ declare function getNuxtVersion(nuxt?: Nuxt | any): any;
136
119
  * Requires Nuxt 2.13+
137
120
  */
138
121
  declare function addComponentsDir(dir: ComponentsDir): Promise<void>;
139
- declare type AddComponentOptions = {
122
+ type AddComponentOptions = {
140
123
  name: string;
141
124
  filePath: string;
142
125
  } & Partial<Exclude<Component, 'shortPath' | 'async' | 'level' | 'import' | 'asyncImport'>>;
@@ -148,7 +131,7 @@ declare type AddComponentOptions = {
148
131
  declare function addComponent(opts: AddComponentOptions): Promise<void>;
149
132
 
150
133
  /** Direct access to the Nuxt context - see https://github.com/unjs/unctx. */
151
- declare const nuxtCtx: unctx.UseContext<Nuxt>;
134
+ declare const nuxtCtx: unctx_index.UseContext<Nuxt>;
152
135
  /**
153
136
  * Get access to Nuxt instance.
154
137
  *
@@ -247,18 +230,6 @@ declare function resolveFiles(path: string, pattern: string | string[], opts?: {
247
230
  followSymbolicLinks?: boolean;
248
231
  }): Promise<string[]>;
249
232
 
250
- interface LegacyServerMiddleware {
251
- route?: string;
252
- path?: string;
253
- handle?: Middleware | string;
254
- handler: Middleware | string;
255
- }
256
- /**
257
- * Adds a new server middleware to the end of the server middleware array.
258
- *
259
- * @deprecated Use addServerHandler instead
260
- */
261
- declare function addServerMiddleware(middleware: LegacyServerMiddleware): void;
262
233
  /**
263
234
  * Adds a nitro server handler
264
235
  *
@@ -269,6 +240,30 @@ declare function addServerHandler(handler: NitroEventHandler): void;
269
240
  *
270
241
  */
271
242
  declare function addDevServerHandler(handler: NitroDevEventHandler): void;
243
+ /**
244
+ * Adds a Nitro plugin
245
+ */
246
+ declare function addServerPlugin(plugin: string): void;
247
+ /**
248
+ * Adds routes to be prerendered
249
+ */
250
+ declare function addPrerenderRoutes(routes: string | string[]): void;
251
+ /**
252
+ * Access to the Nitro instance
253
+ *
254
+ * **Note:** You can call `useNitro()` only after `ready` hook.
255
+ *
256
+ * **Note:** Changes to the Nitro instance configuration are not applied.
257
+ *
258
+ * @example
259
+ *
260
+ * ```ts
261
+ * nuxt.hook('ready', () => {
262
+ * console.log(useNitro())
263
+ * })
264
+ * ```
265
+ */
266
+ declare function useNitro(): Nitro;
272
267
 
273
268
  /**
274
269
  * Renders given template using lodash template during build into the project buildDir
@@ -278,37 +273,53 @@ declare function addTemplate(_template: NuxtTemplate<any> | string): ResolvedNux
278
273
  * Normalize a nuxt template object
279
274
  */
280
275
  declare function normalizeTemplate(template: NuxtTemplate<any> | string): ResolvedNuxtTemplate<any>;
276
+ /**
277
+ * Trigger rebuilding Nuxt templates
278
+ *
279
+ * You can pass a filter within the options to selectively regenerate a subset of templates.
280
+ */
281
+ declare function updateTemplates(options?: {
282
+ filter?: (template: ResolvedNuxtTemplate<any>) => boolean;
283
+ }): Promise<any>;
281
284
 
282
285
  declare const logger: consola.Consola;
283
286
  declare function useLogger(scope?: string): consola.Consola;
284
287
 
288
+ /** @deprecated Do not use CJS utils */
285
289
  interface ResolveModuleOptions {
286
290
  paths?: string | string[];
287
291
  }
292
+ /** @deprecated Do not use CJS utils */
288
293
  interface RequireModuleOptions extends ResolveModuleOptions {
289
294
  /** Clear the require cache (force fresh require) but only if not within `node_modules` */
290
295
  clearCache?: boolean;
291
296
  /** Automatically de-default the result of requiring the module. */
292
297
  interopDefault?: boolean;
293
298
  }
299
+ /** @deprecated Do not use CJS utils */
294
300
  declare function isNodeModules(id: string): boolean;
301
+ /** @deprecated Do not use CJS utils */
295
302
  declare function clearRequireCache(id: string): void;
303
+ /** @deprecated Do not use CJS utils */
296
304
  declare function scanRequireTree(id: string, files?: Set<string>): Set<string>;
297
- /** Access the require cache by module id. */
305
+ /** @deprecated Do not use CJS utils */
298
306
  declare function getRequireCacheItem(id: string): NodeModule | undefined;
299
307
  /** Resolve the `package.json` file for a given module. */
300
308
  declare function requireModulePkg(id: string, opts?: RequireModuleOptions): any;
301
- /** Resolve the path of a module. */
309
+ /** @deprecated Do not use CJS utils */
302
310
  declare function resolveModule(id: string, opts?: ResolveModuleOptions): string;
303
- /** Try to resolve the path of a module, but don't emit an error if it can't be found. */
311
+ /** @deprecated Do not use CJS utils */
304
312
  declare function tryResolveModule(path: string, opts?: ResolveModuleOptions): string | null;
305
- /** Require a module and return it. */
313
+ /** @deprecated Do not use CJS utils */
306
314
  declare function requireModule(id: string, opts?: RequireModuleOptions): any;
315
+ /** @deprecated Do not use CJS utils */
307
316
  declare function importModule(id: string, opts?: RequireModuleOptions): Promise<any>;
317
+ /** @deprecated Do not use CJS utils */
308
318
  declare function tryImportModule(id: string, opts?: RequireModuleOptions): Promise<any> | undefined;
309
- /** Try to require a module, but don't emit an error if the module can't be required. */
319
+ /** @deprecated Do not use CJS utils */
310
320
  declare function tryRequireModule(id: string, opts?: RequireModuleOptions): any;
311
321
 
322
+ /** @deprecated */
312
323
  declare function compileTemplate(template: NuxtTemplate, ctx: any): Promise<string>;
313
324
  /** @deprecated */
314
325
  declare const templateUtils: {
@@ -319,4 +330,4 @@ declare const templateUtils: {
319
330
  }) => string;
320
331
  };
321
332
 
322
- export { AddComponentOptions, AddPluginOptions, ExtendConfigOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, LegacyServerMiddleware, LoadNuxtConfigOptions, LoadNuxtOptions, RequireModuleOptions, ResolveModuleOptions, ResolvePathOptions, Resolver, addAutoImport, addAutoImportDir, addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, 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, useNuxt };
333
+ export { AddComponentOptions, AddPluginOptions, ExtendConfigOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, LoadNuxtConfigOptions, LoadNuxtOptions, RequireModuleOptions, ResolveModuleOptions, ResolvePathOptions, Resolver, addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addServerHandler, addServerPlugin, 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, updateTemplates, useLogger, useNitro, useNuxt };
package/dist/index.mjs CHANGED
@@ -1,46 +1,27 @@
1
- import { parse, basename, resolve, relative, join, normalize, isAbsolute, dirname } from 'pathe';
2
- import { existsSync, readFileSync, promises } from 'node:fs';
3
- import hash from 'hash-sum';
1
+ import { promises, existsSync, readFileSync } from 'node:fs';
2
+ import defu from 'defu';
3
+ import { applyDefaults } from 'untyped';
4
+ import { dirname, join, normalize, relative, isAbsolute, resolve, basename, parse } from 'pathe';
5
+ import consola from 'consola';
4
6
  import { getContext } from 'unctx';
5
- import { kebabCase, pascalCase } from 'scule';
6
7
  import satisfies from 'semver/functions/satisfies.js';
7
- import consola from 'consola';
8
+ import lodashTemplate from 'lodash.template';
9
+ import { genSafeVariableName, genDynamicImport, genImport } from 'knitwork';
8
10
  import { pathToFileURL, fileURLToPath } from 'node:url';
9
- import { globby } from 'globby';
10
- import { normalizeAliases } from 'pathe/utils';
11
11
  import { interopDefault } from 'mlly';
12
12
  import jiti from 'jiti';
13
+ import { globby } from 'globby';
14
+ import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
13
15
  import ignore from 'ignore';
14
- import defu from 'defu';
15
- import { applyDefaults } from 'untyped';
16
- import lodashTemplate from 'lodash.template';
17
- import { genSafeVariableName, genDynamicImport, genImport } from 'knitwork';
18
16
  import { loadConfig } from 'c12';
19
17
  import { NuxtConfigSchema } from '@nuxt/schema';
20
18
  import { resolvePackageJSON, readPackageJSON } from 'pkg-types';
19
+ import { kebabCase, pascalCase } from 'scule';
20
+ import hash from 'hash-sum';
21
21
 
22
- function chainFn(base, fn) {
23
- if (typeof fn !== "function") {
24
- return base;
25
- }
26
- return function(...args) {
27
- if (typeof base !== "function") {
28
- return fn.apply(this, args);
29
- }
30
- let baseResult = base.apply(this, args);
31
- if (baseResult === void 0) {
32
- [baseResult] = args;
33
- }
34
- const fnResult = fn.call(
35
- this,
36
- baseResult,
37
- ...Array.prototype.slice.call(args, 1)
38
- );
39
- if (fnResult === void 0) {
40
- return baseResult;
41
- }
42
- return fnResult;
43
- };
22
+ const logger = consola;
23
+ function useLogger(scope) {
24
+ return scope ? logger.withScope(scope) : logger;
44
25
  }
45
26
 
46
27
  const nuxtCtx = getContext("nuxt");
@@ -55,52 +36,11 @@ function tryUseNuxt() {
55
36
  return nuxtCtx.tryUse();
56
37
  }
57
38
 
58
- function addTemplate(_template) {
59
- const nuxt = useNuxt();
60
- const template = normalizeTemplate(_template);
61
- nuxt.options.build.templates = nuxt.options.build.templates.filter((p) => normalizeTemplate(p).filename !== template.filename);
62
- nuxt.options.build.templates.push(template);
63
- return template;
64
- }
65
- function normalizeTemplate(template) {
66
- if (!template) {
67
- throw new Error("Invalid template: " + JSON.stringify(template));
68
- }
69
- if (typeof template === "string") {
70
- template = { src: template };
71
- } else {
72
- template = { ...template };
73
- }
74
- if (template.src) {
75
- if (!existsSync(template.src)) {
76
- throw new Error("Template not found: " + template.src);
77
- }
78
- if (!template.filename) {
79
- const srcPath = parse(template.src);
80
- template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src)}${srcPath.ext}`;
81
- }
82
- }
83
- if (!template.src && !template.getContents) {
84
- throw new Error("Invalid template. Either getContents or src options should be provided: " + JSON.stringify(template));
85
- }
86
- if (!template.filename) {
87
- throw new Error("Invalid template. Either filename should be provided: " + JSON.stringify(template));
88
- }
89
- if (template.filename.endsWith(".d.ts")) {
90
- template.write = true;
91
- }
92
- if (!template.dst) {
93
- const nuxt = useNuxt();
94
- template.dst = resolve(nuxt.options.buildDir, template.filename);
95
- }
96
- return template;
97
- }
98
-
99
39
  async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
100
40
  const issues = [];
101
41
  if (constraints.nuxt) {
102
42
  const nuxtVersion = getNuxtVersion(nuxt);
103
- const nuxtSemanticVersion = nuxtVersion.replace(/-[0-9]+\.[0-9a-f]{7}/, "");
43
+ const nuxtSemanticVersion = nuxtVersion.replace(/-[0-9]+\.[0-9a-f]{7,8}/, "");
104
44
  if (!satisfies(nuxtSemanticVersion, constraints.nuxt, { includePrerelease: true })) {
105
45
  issues.push({
106
46
  name: "nuxt",
@@ -152,59 +92,125 @@ function getNuxtVersion(nuxt = useNuxt()) {
152
92
  return version;
153
93
  }
154
94
 
155
- const logger = consola;
156
- function useLogger(scope) {
157
- return scope ? logger.withScope(scope) : logger;
95
+ async function compileTemplate(template, ctx) {
96
+ const data = { ...ctx, options: template.options };
97
+ if (template.src) {
98
+ try {
99
+ const srcContents = await promises.readFile(template.src, "utf-8");
100
+ return lodashTemplate(srcContents, {})(data);
101
+ } catch (err) {
102
+ console.error("Error compiling template: ", template);
103
+ throw err;
104
+ }
105
+ }
106
+ if (template.getContents) {
107
+ return template.getContents(data);
108
+ }
109
+ throw new Error("Invalid template: " + JSON.stringify(template));
158
110
  }
111
+ const serialize = (data) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, (r) => JSON.parse(r).replace(/^{(.*)}$/, "$1"));
112
+ const importSources = (sources, { lazy = false } = {}) => {
113
+ if (!Array.isArray(sources)) {
114
+ sources = [sources];
115
+ }
116
+ return sources.map((src) => {
117
+ if (lazy) {
118
+ return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
119
+ }
120
+ return genImport(src, genSafeVariableName(src));
121
+ }).join("\n");
122
+ };
123
+ const importName = genSafeVariableName;
124
+ const templateUtils = { serialize, importName, importSources };
159
125
 
160
- function addLayout(template, name) {
161
- const nuxt = useNuxt();
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
- );
126
+ function defineNuxtModule(definition) {
127
+ if (!definition.meta) {
128
+ definition.meta = {};
129
+ }
130
+ if (definition.meta.configKey === void 0) {
131
+ definition.meta.configKey = definition.meta.name;
132
+ }
133
+ async function getOptions(inlineOptions, nuxt = useNuxt()) {
134
+ const configKey = definition.meta.configKey || definition.meta.name;
135
+ const _defaults = definition.defaults instanceof Function ? definition.defaults(nuxt) : definition.defaults;
136
+ let _options = defu(inlineOptions, nuxt.options[configKey], _defaults);
137
+ if (definition.schema) {
138
+ _options = await applyDefaults(definition.schema, _options);
170
139
  }
171
- nuxt.options.layouts[layoutName] = `./${filename}`;
172
- if (name === "error") {
173
- this.addErrorLayout(filename);
140
+ return Promise.resolve(_options);
141
+ }
142
+ async function normalizedModule(inlineOptions, nuxt) {
143
+ if (!nuxt) {
144
+ nuxt = tryUseNuxt() || this.nuxt;
145
+ }
146
+ const uniqueKey = definition.meta.name || definition.meta.configKey;
147
+ if (uniqueKey) {
148
+ nuxt.options._requiredModules = nuxt.options._requiredModules || {};
149
+ if (nuxt.options._requiredModules[uniqueKey]) {
150
+ return;
151
+ }
152
+ nuxt.options._requiredModules[uniqueKey] = true;
174
153
  }
154
+ if (definition.meta.compatibility) {
155
+ const issues = await checkNuxtCompatibility(definition.meta.compatibility, nuxt);
156
+ if (issues.length) {
157
+ logger.warn(`Module \`${definition.meta.name}\` is disabled due to incompatibility issues:
158
+ ${issues.toString()}`);
159
+ return;
160
+ }
161
+ }
162
+ nuxt2Shims(nuxt);
163
+ const _options = await getOptions(inlineOptions, nuxt);
164
+ if (definition.hooks) {
165
+ nuxt.hooks.addHooks(definition.hooks);
166
+ }
167
+ await definition.setup?.call(null, _options, nuxt);
168
+ }
169
+ normalizedModule.getMeta = () => Promise.resolve(definition.meta);
170
+ normalizedModule.getOptions = getOptions;
171
+ return normalizedModule;
172
+ }
173
+ const NUXT2_SHIMS_KEY = "__nuxt2_shims_key__";
174
+ function nuxt2Shims(nuxt) {
175
+ if (!isNuxt2(nuxt) || nuxt[NUXT2_SHIMS_KEY]) {
175
176
  return;
176
177
  }
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
- );
178
+ nuxt[NUXT2_SHIMS_KEY] = true;
179
+ nuxt.hooks = nuxt;
180
+ if (!nuxtCtx.tryUse()) {
181
+ nuxtCtx.set(nuxt);
182
+ nuxt.hook("close", () => nuxtCtx.unset());
183
+ }
184
+ let virtualTemplates;
185
+ nuxt.hook("builder:prepared", (_builder, buildOptions) => {
186
+ virtualTemplates = buildOptions.templates.filter((t) => t.getContents);
187
+ for (const template of virtualTemplates) {
188
+ buildOptions.templates.splice(buildOptions.templates.indexOf(template), 1);
183
189
  }
184
- app.layouts[layoutName] = {
185
- file: join("#build", filename),
186
- name: layoutName
190
+ });
191
+ nuxt.hook("build:templates", async (templates) => {
192
+ const context = {
193
+ nuxt,
194
+ utils: templateUtils,
195
+ app: {
196
+ dir: nuxt.options.srcDir,
197
+ extensions: nuxt.options.extensions,
198
+ plugins: nuxt.options.plugins,
199
+ templates: [
200
+ ...templates.templatesFiles,
201
+ ...virtualTemplates
202
+ ],
203
+ templateVars: templates.templateVars
204
+ }
187
205
  };
206
+ for await (const template of virtualTemplates) {
207
+ const contents = await compileTemplate({ ...template, src: "" }, context);
208
+ await promises.mkdir(dirname(template.dst), { recursive: true });
209
+ await promises.writeFile(template.dst, contents);
210
+ }
188
211
  });
189
212
  }
190
213
 
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
-
208
214
  const _require = jiti(process.cwd(), { interopDefault: true, esmResolve: true });
209
215
  function isNodeModules(id) {
210
216
  return /[/\\]node_modules[/\\]/.test(id);
@@ -324,7 +330,7 @@ async function resolvePath(path, opts = {}) {
324
330
  if (isAbsolute(path) && existsSync(path) && !await isDirectory(path)) {
325
331
  return path;
326
332
  }
327
- const nuxt = useNuxt();
333
+ const nuxt = tryUseNuxt();
328
334
  const cwd = opts.cwd || (nuxt ? nuxt.options.rootDir : process.cwd());
329
335
  const extensions = opts.extensions || (nuxt ? nuxt.options.extensions : [".ts", ".mjs", ".cjs", ".json"]);
330
336
  const modulesDir = nuxt ? nuxt.options.modulesDir : [];
@@ -374,15 +380,7 @@ function resolveAlias(path, alias) {
374
380
  if (!alias) {
375
381
  alias = tryUseNuxt()?.options.alias || {};
376
382
  }
377
- for (const key in normalizeAliases(alias)) {
378
- if (key === "@" && !path.startsWith("@/")) {
379
- continue;
380
- }
381
- if (path.startsWith(key)) {
382
- path = alias[key] + path.slice(key.length);
383
- }
384
- }
385
- return path;
383
+ return resolveAlias$1(path, alias);
386
384
  }
387
385
  function createResolver(base) {
388
386
  if (!base) {
@@ -412,45 +410,13 @@ async function resolveFiles(path, pattern, opts = {}) {
412
410
  return files.map((p) => resolve(path, p)).filter((p) => !isIgnored(p)).sort();
413
411
  }
414
412
 
415
- function normalizePlugin(plugin) {
416
- if (typeof plugin === "string") {
417
- plugin = { src: plugin };
418
- } else {
419
- plugin = { ...plugin };
420
- }
421
- if (!plugin.src) {
422
- throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
423
- }
424
- plugin.src = normalize(resolveAlias(plugin.src));
425
- if (plugin.ssr) {
426
- plugin.mode = "server";
427
- }
428
- if (!plugin.mode) {
429
- const [, mode = "all"] = plugin.src.match(/\.(server|client)(\.\w+)*$/) || [];
430
- plugin.mode = mode;
431
- }
432
- return plugin;
433
- }
434
- function addPlugin(_plugin, opts = {}) {
435
- const nuxt = useNuxt();
436
- const plugin = normalizePlugin(_plugin);
437
- nuxt.options.plugins = nuxt.options.plugins.filter((p) => normalizePlugin(p).src !== plugin.src);
438
- nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
439
- return plugin;
440
- }
441
- function addPluginTemplate(plugin, opts = {}) {
442
- const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
443
- return addPlugin(normalizedPlugin, opts);
444
- }
445
-
446
413
  async function installModule(moduleToInstall, _inlineOptions, _nuxt) {
447
414
  const nuxt = useNuxt();
448
415
  const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions);
449
- await nuxtModule.call(
450
- useModuleContainer(),
451
- inlineOptions,
452
- nuxt
453
- );
416
+ await nuxtModule(inlineOptions, nuxt);
417
+ if (typeof moduleToInstall === "string") {
418
+ nuxt.options.build.transpile.push(moduleToInstall);
419
+ }
454
420
  nuxt.options._installedModules = nuxt.options._installedModules || [];
455
421
  nuxt.options._installedModules.push({
456
422
  meta: await nuxtModule.getMeta?.(),
@@ -459,14 +425,15 @@ async function installModule(moduleToInstall, _inlineOptions, _nuxt) {
459
425
  }
460
426
  async function normalizeModule(nuxtModule, inlineOptions) {
461
427
  const nuxt = useNuxt();
462
- if (nuxtModule?._version || nuxtModule?.version || nuxtModule?.constructor?.version || "") {
463
- [nuxtModule, inlineOptions] = [inlineOptions, {}];
464
- console.warn(new Error("`installModule` is being called with old signature!"));
465
- }
466
428
  if (typeof nuxtModule === "string") {
467
429
  const _src = resolveModule(resolveAlias(nuxtModule), { paths: nuxt.options.modulesDir });
468
430
  const isESM = _src.endsWith(".mjs");
469
- nuxtModule = isESM ? await importModule(_src) : requireModule(_src);
431
+ try {
432
+ nuxtModule = isESM ? await importModule(_src) : requireModule(_src);
433
+ } catch (error) {
434
+ console.error(`Error while requiring module \`${nuxtModule}\`: ${error}`);
435
+ throw error;
436
+ }
470
437
  }
471
438
  if (typeof nuxtModule !== "function") {
472
439
  throw new TypeError("Nuxt module should be a function: " + nuxtModule);
@@ -474,207 +441,8 @@ async function normalizeModule(nuxtModule, inlineOptions) {
474
441
  return { nuxtModule, inlineOptions };
475
442
  }
476
443
 
477
- const MODULE_CONTAINER_KEY = "__module_container__";
478
- function useModuleContainer(nuxt = useNuxt()) {
479
- if (nuxt[MODULE_CONTAINER_KEY]) {
480
- return nuxt[MODULE_CONTAINER_KEY];
481
- }
482
- async function requireModule(moduleOpts) {
483
- let src, inlineOptions;
484
- if (typeof moduleOpts === "string") {
485
- src = moduleOpts;
486
- } else if (Array.isArray(moduleOpts)) {
487
- [src, inlineOptions] = moduleOpts;
488
- } else if (typeof moduleOpts === "object") {
489
- if (moduleOpts.src || moduleOpts.handler) {
490
- src = moduleOpts.src || moduleOpts.handler;
491
- inlineOptions = moduleOpts.options;
492
- } else {
493
- src = moduleOpts;
494
- }
495
- } else {
496
- src = moduleOpts;
497
- }
498
- await installModule(src, inlineOptions);
499
- }
500
- const container = {
501
- nuxt,
502
- options: nuxt.options,
503
- ready() {
504
- return Promise.resolve();
505
- },
506
- addVendor() {
507
- },
508
- requireModule,
509
- addModule: requireModule,
510
- addServerMiddleware,
511
- addTemplate(template) {
512
- if (typeof template === "string") {
513
- template = { src: template };
514
- }
515
- if (template.write === void 0) {
516
- template.write = true;
517
- }
518
- return addTemplate(template);
519
- },
520
- addPlugin(pluginTemplate) {
521
- return addPluginTemplate(pluginTemplate);
522
- },
523
- addLayout(tmpl, name) {
524
- return addLayout(tmpl, name);
525
- },
526
- addErrorLayout(dst) {
527
- const relativeBuildDir = relative(nuxt.options.rootDir, nuxt.options.buildDir);
528
- nuxt.options.ErrorPage = `~/${relativeBuildDir}/${dst}`;
529
- },
530
- extendBuild(fn) {
531
- nuxt.options.build.extend = chainFn(nuxt.options.build.extend, fn);
532
- if (!isNuxt2(nuxt)) {
533
- console.warn("[kit] [compat] Using `extendBuild` in Nuxt 3 has no effect. Instead call extendWebpackConfig and extendViteConfig.");
534
- }
535
- },
536
- extendRoutes(fn) {
537
- if (isNuxt2(nuxt)) {
538
- nuxt.options.router.extendRoutes = chainFn(nuxt.options.router.extendRoutes, fn);
539
- } else {
540
- nuxt.hook("pages:extend", async (pages, ...args) => {
541
- const maybeRoutes = await fn(pages, ...args);
542
- if (maybeRoutes) {
543
- console.warn("[kit] [compat] Using `extendRoutes` in Nuxt 3 needs to directly modify first argument instead of returning updated routes. Skipping extended routes.");
544
- }
545
- });
546
- }
547
- }
548
- };
549
- nuxt[MODULE_CONTAINER_KEY] = container;
550
- return nuxt[MODULE_CONTAINER_KEY];
551
- }
552
-
553
- async function compileTemplate(template, ctx) {
554
- const data = { ...ctx, options: template.options };
555
- if (template.src) {
556
- try {
557
- const srcContents = await promises.readFile(template.src, "utf-8");
558
- return lodashTemplate(srcContents, {})(data);
559
- } catch (err) {
560
- console.error("Error compiling template: ", template);
561
- throw err;
562
- }
563
- }
564
- if (template.getContents) {
565
- return template.getContents(data);
566
- }
567
- throw new Error("Invalid template: " + JSON.stringify(template));
568
- }
569
- const serialize = (data) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, (r) => JSON.parse(r).replace(/^{(.*)}$/, "$1"));
570
- const importSources = (sources, { lazy = false } = {}) => {
571
- if (!Array.isArray(sources)) {
572
- sources = [sources];
573
- }
574
- return sources.map((src) => {
575
- if (lazy) {
576
- return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
577
- }
578
- return genImport(src, genSafeVariableName(src));
579
- }).join("\n");
580
- };
581
- const importName = genSafeVariableName;
582
- const templateUtils = { serialize, importName, importSources };
583
-
584
- function defineNuxtModule(definition) {
585
- if (typeof definition === "function") {
586
- definition = definition(useNuxt());
587
- logger.warn("Module definition as function is deprecated and will be removed in the future versions", definition);
588
- }
589
- if (!definition.meta) {
590
- definition.meta = {};
591
- }
592
- if (!definition.meta.configKey) {
593
- definition.meta.name = definition.meta.name || definition.name;
594
- definition.meta.configKey = definition.configKey || definition.meta.name;
595
- }
596
- function getOptions(inlineOptions, nuxt = useNuxt()) {
597
- const configKey = definition.meta.configKey || definition.meta.name;
598
- const _defaults = definition.defaults instanceof Function ? definition.defaults(nuxt) : definition.defaults;
599
- let _options = defu(inlineOptions, nuxt.options[configKey], _defaults);
600
- if (definition.schema) {
601
- _options = applyDefaults(definition.schema, _options);
602
- }
603
- return Promise.resolve(_options);
604
- }
605
- async function normalizedModule(inlineOptions, nuxt) {
606
- if (!nuxt) {
607
- nuxt = tryUseNuxt() || this.nuxt;
608
- }
609
- const uniqueKey = definition.meta.name || definition.meta.configKey;
610
- if (uniqueKey) {
611
- nuxt.options._requiredModules = nuxt.options._requiredModules || {};
612
- if (nuxt.options._requiredModules[uniqueKey]) {
613
- return;
614
- }
615
- nuxt.options._requiredModules[uniqueKey] = true;
616
- }
617
- if (definition.meta.compatibility) {
618
- const issues = await checkNuxtCompatibility(definition.meta.compatibility, nuxt);
619
- if (issues.length) {
620
- logger.warn(`Module \`${definition.meta.name}\` is disabled due to incompatibility issues:
621
- ${issues.toString()}`);
622
- return;
623
- }
624
- }
625
- nuxt2Shims(nuxt);
626
- const _options = await getOptions(inlineOptions, nuxt);
627
- if (definition.hooks) {
628
- nuxt.hooks.addHooks(definition.hooks);
629
- }
630
- await definition.setup?.call(null, _options, nuxt);
631
- }
632
- normalizedModule.getMeta = () => Promise.resolve(definition.meta);
633
- normalizedModule.getOptions = getOptions;
634
- return normalizedModule;
635
- }
636
- const NUXT2_SHIMS_KEY = "__nuxt2_shims_key__";
637
- function nuxt2Shims(nuxt) {
638
- if (!isNuxt2(nuxt) || nuxt[NUXT2_SHIMS_KEY]) {
639
- return;
640
- }
641
- nuxt[NUXT2_SHIMS_KEY] = true;
642
- nuxt.hooks = nuxt;
643
- if (!nuxtCtx.tryUse()) {
644
- nuxtCtx.set(nuxt);
645
- nuxt.hook("close", () => nuxtCtx.unset());
646
- }
647
- let virtualTemplates;
648
- nuxt.hook("builder:prepared", (_builder, buildOptions) => {
649
- virtualTemplates = buildOptions.templates.filter((t) => t.getContents);
650
- for (const template of virtualTemplates) {
651
- buildOptions.templates.splice(buildOptions.templates.indexOf(template), 1);
652
- }
653
- });
654
- nuxt.hook("build:templates", async (templates) => {
655
- const context = {
656
- nuxt,
657
- utils: templateUtils,
658
- app: {
659
- dir: nuxt.options.srcDir,
660
- extensions: nuxt.options.extensions,
661
- plugins: nuxt.options.plugins,
662
- templates: [
663
- ...templates.templatesFiles,
664
- ...virtualTemplates
665
- ],
666
- templateVars: templates.templateVars
667
- }
668
- };
669
- for await (const template of virtualTemplates) {
670
- const contents = await compileTemplate({ ...template, src: "" }, context);
671
- await promises.mkdir(dirname(template.dst), { recursive: true });
672
- await promises.writeFile(template.dst, contents);
673
- }
674
- });
675
- }
676
-
677
444
  async function loadNuxtConfig(opts) {
445
+ globalThis.defineNuxtConfig = (c) => c;
678
446
  const result = await loadConfig({
679
447
  name: "nuxt",
680
448
  configFile: "nuxt.config",
@@ -684,6 +452,7 @@ async function loadNuxtConfig(opts) {
684
452
  globalRc: true,
685
453
  ...opts
686
454
  });
455
+ delete globalThis.defineNuxtConfig;
687
456
  const { configFile, layers = [], cwd } = result;
688
457
  const nuxtConfig = result.config;
689
458
  nuxtConfig.rootDir = nuxtConfig.rootDir || cwd;
@@ -694,8 +463,18 @@ async function loadNuxtConfig(opts) {
694
463
  layer.config.rootDir = layer.config.rootDir ?? layer.cwd;
695
464
  layer.config.srcDir = resolve(layer.config.rootDir, layer.config.srcDir);
696
465
  }
697
- nuxtConfig._layers = layers.filter((layer) => layer.configFile && !layer.configFile.endsWith(".nuxtrc"));
698
- return applyDefaults(NuxtConfigSchema, nuxtConfig);
466
+ const _layers = layers.filter((layer) => layer.configFile && !layer.configFile.endsWith(".nuxtrc"));
467
+ nuxtConfig._layers = _layers;
468
+ if (!_layers.length) {
469
+ _layers.push({
470
+ cwd,
471
+ config: {
472
+ rootDir: cwd,
473
+ srcDir: cwd
474
+ }
475
+ });
476
+ }
477
+ return await applyDefaults(NuxtConfigSchema, nuxtConfig);
699
478
  }
700
479
 
701
480
  async function loadNuxt(opts) {
@@ -736,20 +515,26 @@ async function buildNuxt(nuxt) {
736
515
 
737
516
  function addImports(imports) {
738
517
  assertNuxtCompatibility({ bridge: true });
739
- useNuxt().hook("autoImports:extend", (_imports) => {
518
+ useNuxt().hook("imports:extend", (_imports) => {
740
519
  _imports.push(...Array.isArray(imports) ? imports : [imports]);
741
- }, { allowDeprecated: true });
520
+ });
742
521
  }
743
- const addAutoImport = addImports;
744
522
  function addImportsDir(dirs) {
745
523
  assertNuxtCompatibility({ bridge: true });
746
- useNuxt().hook("autoImports:dirs", (_dirs) => {
524
+ useNuxt().hook("imports:dirs", (_dirs) => {
747
525
  for (const dir of Array.isArray(dirs) ? dirs : [dirs]) {
748
526
  _dirs.push(dir);
749
527
  }
750
- }, { allowDeprecated: true });
528
+ });
529
+ }
530
+ function addImportsSources(presets) {
531
+ assertNuxtCompatibility({ bridge: true });
532
+ useNuxt().hook("imports:sources", (_presets) => {
533
+ for (const preset of Array.isArray(presets) ? presets : [presets]) {
534
+ _presets.push(preset);
535
+ }
536
+ });
751
537
  }
752
- const addAutoImportDir = addImportsDir;
753
538
 
754
539
  function extendWebpackConfig(fn, options = {}) {
755
540
  const nuxt = useNuxt();
@@ -772,12 +557,6 @@ function extendWebpackConfig(fn, options = {}) {
772
557
  fn(config);
773
558
  }
774
559
  }
775
- if (options.modern !== false) {
776
- const config = configs.find((i) => i.name === "modern");
777
- if (config) {
778
- fn(config);
779
- }
780
- }
781
560
  });
782
561
  }
783
562
  function extendViteConfig(fn, options = {}) {
@@ -803,13 +582,21 @@ function extendViteConfig(fn, options = {}) {
803
582
  function addWebpackPlugin(plugin, options) {
804
583
  extendWebpackConfig((config) => {
805
584
  config.plugins = config.plugins || [];
806
- config.plugins.push(plugin);
585
+ if (Array.isArray(plugin)) {
586
+ config.plugins.push(...plugin);
587
+ } else {
588
+ config.plugins.push(plugin);
589
+ }
807
590
  }, options);
808
591
  }
809
592
  function addVitePlugin(plugin, options) {
810
593
  extendViteConfig((config) => {
811
594
  config.plugins = config.plugins || [];
812
- config.plugins.push(plugin);
595
+ if (Array.isArray(plugin)) {
596
+ config.plugins.push(...plugin);
597
+ } else {
598
+ config.plugins.push(plugin);
599
+ }
813
600
  }, options);
814
601
  }
815
602
 
@@ -835,10 +622,6 @@ async function addComponent(opts) {
835
622
  preload: false,
836
623
  mode: "all",
837
624
  shortPath: opts.filePath,
838
- async: false,
839
- level: 0,
840
- asyncImport: `${genDynamicImport(opts.filePath)}.then(r => r['${opts.export || "default"}'])`,
841
- import: `require(${JSON.stringify(opts.filePath)})['${opts.export || "default"}']`,
842
625
  ...opts
843
626
  };
844
627
  nuxt.hook("components:extend", (components) => {
@@ -853,6 +636,81 @@ async function addComponent(opts) {
853
636
  });
854
637
  }
855
638
 
639
+ function addTemplate(_template) {
640
+ const nuxt = useNuxt();
641
+ const template = normalizeTemplate(_template);
642
+ nuxt.options.build.templates = nuxt.options.build.templates.filter((p) => normalizeTemplate(p).filename !== template.filename);
643
+ nuxt.options.build.templates.push(template);
644
+ return template;
645
+ }
646
+ function normalizeTemplate(template) {
647
+ if (!template) {
648
+ throw new Error("Invalid template: " + JSON.stringify(template));
649
+ }
650
+ if (typeof template === "string") {
651
+ template = { src: template };
652
+ } else {
653
+ template = { ...template };
654
+ }
655
+ if (template.src) {
656
+ if (!existsSync(template.src)) {
657
+ throw new Error("Template not found: " + template.src);
658
+ }
659
+ if (!template.filename) {
660
+ const srcPath = parse(template.src);
661
+ template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src)}${srcPath.ext}`;
662
+ }
663
+ }
664
+ if (!template.src && !template.getContents) {
665
+ throw new Error("Invalid template. Either getContents or src options should be provided: " + JSON.stringify(template));
666
+ }
667
+ if (!template.filename) {
668
+ throw new Error("Invalid template. Either filename should be provided: " + JSON.stringify(template));
669
+ }
670
+ if (template.filename.endsWith(".d.ts")) {
671
+ template.write = true;
672
+ }
673
+ if (!template.dst) {
674
+ const nuxt = useNuxt();
675
+ template.dst = resolve(nuxt.options.buildDir, template.filename);
676
+ }
677
+ return template;
678
+ }
679
+ function updateTemplates(options) {
680
+ return useNuxt().hooks.callHook("builder:generateApp", options);
681
+ }
682
+
683
+ function addLayout(template, name) {
684
+ const nuxt = useNuxt();
685
+ const { filename, src } = addTemplate(template);
686
+ const layoutName = kebabCase(name || parse(filename).name).replace(/["']/g, "");
687
+ if (isNuxt2(nuxt)) {
688
+ const layout = nuxt.options.layouts[layoutName];
689
+ if (layout) {
690
+ return logger.warn(
691
+ `Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`
692
+ );
693
+ }
694
+ nuxt.options.layouts[layoutName] = `./${filename}`;
695
+ if (name === "error") {
696
+ this.addErrorLayout(filename);
697
+ }
698
+ return;
699
+ }
700
+ nuxt.hook("app:templates", (app) => {
701
+ if (layoutName in app.layouts) {
702
+ const relativePath = relative(nuxt.options.srcDir, app.layouts[layoutName].file);
703
+ return logger.warn(
704
+ `Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`
705
+ );
706
+ }
707
+ app.layouts[layoutName] = {
708
+ file: join("#build", filename),
709
+ name: layoutName
710
+ };
711
+ });
712
+ }
713
+
856
714
  function extendPages(cb) {
857
715
  const nuxt = useNuxt();
858
716
  if (isNuxt2(nuxt)) {
@@ -862,4 +720,77 @@ function extendPages(cb) {
862
720
  }
863
721
  }
864
722
 
865
- export { addAutoImport, addAutoImportDir, addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, 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, useNuxt };
723
+ function normalizePlugin(plugin) {
724
+ if (typeof plugin === "string") {
725
+ plugin = { src: plugin };
726
+ } else {
727
+ plugin = { ...plugin };
728
+ }
729
+ if (!plugin.src) {
730
+ throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
731
+ }
732
+ plugin.src = normalize(resolveAlias(plugin.src));
733
+ if (plugin.ssr) {
734
+ plugin.mode = "server";
735
+ }
736
+ if (!plugin.mode) {
737
+ const [, mode = "all"] = plugin.src.match(/\.(server|client)(\.\w+)*$/) || [];
738
+ plugin.mode = mode;
739
+ }
740
+ return plugin;
741
+ }
742
+ function addPlugin(_plugin, opts = {}) {
743
+ const nuxt = useNuxt();
744
+ const plugin = normalizePlugin(_plugin);
745
+ nuxt.options.plugins = nuxt.options.plugins.filter((p) => normalizePlugin(p).src !== plugin.src);
746
+ nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
747
+ return plugin;
748
+ }
749
+ function addPluginTemplate(plugin, opts = {}) {
750
+ const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
751
+ return addPlugin(normalizedPlugin, opts);
752
+ }
753
+
754
+ function normalizeHandlerMethod(handler) {
755
+ const [, method = void 0] = handler.handler.match(/\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/) || [];
756
+ return {
757
+ method,
758
+ ...handler,
759
+ handler: normalize(handler.handler)
760
+ };
761
+ }
762
+ function addServerHandler(handler) {
763
+ useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler));
764
+ }
765
+ function addDevServerHandler(handler) {
766
+ useNuxt().options.devServerHandlers.push(handler);
767
+ }
768
+ function addServerPlugin(plugin) {
769
+ const nuxt = useNuxt();
770
+ nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
771
+ nuxt.options.nitro.plugins.push(normalize(plugin));
772
+ }
773
+ function addPrerenderRoutes(routes) {
774
+ const nuxt = useNuxt();
775
+ if (!Array.isArray(routes)) {
776
+ routes = [routes];
777
+ }
778
+ routes = routes.filter(Boolean);
779
+ if (!routes.length) {
780
+ return;
781
+ }
782
+ nuxt.hook("prerender:routes", (ctx) => {
783
+ for (const route of routes) {
784
+ ctx.routes.add(route);
785
+ }
786
+ });
787
+ }
788
+ function useNitro() {
789
+ const nuxt = useNuxt();
790
+ if (!nuxt._nitro) {
791
+ throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
792
+ }
793
+ return nuxt._nitro;
794
+ }
795
+
796
+ export { addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addServerHandler, addServerPlugin, 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, updateTemplates, useLogger, useNitro, useNuxt };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/kit",
3
- "version": "3.0.0-rc.9",
3
+ "version": "3.0.0",
4
4
  "repository": "nuxt/framework",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -9,28 +9,25 @@
9
9
  "files": [
10
10
  "dist"
11
11
  ],
12
- "scripts": {
13
- "prepack": "unbuild"
14
- },
15
12
  "dependencies": {
16
- "@nuxt/schema": "3.0.0-rc.9",
17
- "c12": "^0.2.10",
13
+ "@nuxt/schema": "3.0.0",
14
+ "c12": "^1.0.1",
18
15
  "consola": "^2.15.3",
19
- "defu": "^6.1.0",
16
+ "defu": "^6.1.1",
20
17
  "globby": "^13.1.2",
21
18
  "hash-sum": "^2.0.0",
22
19
  "ignore": "^5.2.0",
23
- "jiti": "^1.14.0",
24
- "knitwork": "^0.1.2",
20
+ "jiti": "^1.16.0",
21
+ "knitwork": "^1.0.0",
25
22
  "lodash.template": "^4.5.0",
26
- "mlly": "^0.5.14",
27
- "pathe": "^0.3.5",
28
- "pkg-types": "^0.3.4",
29
- "scule": "^0.3.2",
30
- "semver": "^7.3.7",
31
- "unctx": "^2.0.2",
32
- "unimport": "^0.6.7",
33
- "untyped": "^0.4.7"
23
+ "mlly": "^1.0.0",
24
+ "pathe": "^1.0.0",
25
+ "pkg-types": "^1.0.1",
26
+ "scule": "^1.0.0",
27
+ "semver": "^7.3.8",
28
+ "unctx": "^2.1.0",
29
+ "unimport": "^1.0.1",
30
+ "untyped": "^1.0.0"
34
31
  },
35
32
  "devDependencies": {
36
33
  "@types/lodash.template": "^4",
@@ -38,6 +35,7 @@
38
35
  "unbuild": "latest"
39
36
  },
40
37
  "engines": {
41
- "node": "^14.16.0 || ^16.11.0 || ^17.0.0 || ^18.0.0"
42
- }
43
- }
38
+ "node": "^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
39
+ },
40
+ "scripts": {}
41
+ }