@nuxt/kit 3.0.0-rc.13 → 3.0.0-rc.14

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 +16 -25
  2. package/dist/index.mjs +239 -362
  3. package/package.json +12 -12
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Nuxt, ModuleContainer, ModuleOptions, ModuleDefinition, NuxtModule, NuxtConfig, NuxtOptions, ImportPresetWithDeprecation, 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';
@@ -8,8 +8,6 @@ import { NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack';
8
8
  import * as consola from 'consola';
9
9
  import { genSafeVariableName } from 'knitwork';
10
10
 
11
- declare function useModuleContainer(nuxt?: Nuxt): ModuleContainer;
12
-
13
11
  /**
14
12
  * Define a Nuxt module, automatically merging defaults with user provided options, installing
15
13
  * any hooks that are provided, and calling an optional setup function for full control.
@@ -37,15 +35,7 @@ declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
37
35
  declare function buildNuxt(nuxt: Nuxt): Promise<any>;
38
36
 
39
37
  declare function addImports(imports: Import | Import[]): void;
40
- /**
41
- * @deprecated Please use `addImports` instead with nuxt>=3.0.0-rc.9
42
- */
43
- declare const addAutoImport: typeof addImports;
44
38
  declare function addImportsDir(dirs: string | string[]): void;
45
- /**
46
- * @deprecated Please use `addImportsDir` instead with nuxt>=3.0.0-rc.9
47
- */
48
- declare const addAutoImportDir: typeof addImportsDir;
49
39
  declare function addImportsSources(presets: ImportPresetWithDeprecation | ImportPresetWithDeprecation[]): void;
50
40
 
51
41
  interface ExtendConfigOptions {
@@ -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
  }
@@ -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'>>;
@@ -302,33 +285,41 @@ declare function updateTemplates(options?: {
302
285
  declare const logger: consola.Consola;
303
286
  declare function useLogger(scope?: string): consola.Consola;
304
287
 
288
+ /** @deprecated Do not use CJS utils */
305
289
  interface ResolveModuleOptions {
306
290
  paths?: string | string[];
307
291
  }
292
+ /** @deprecated Do not use CJS utils */
308
293
  interface RequireModuleOptions extends ResolveModuleOptions {
309
294
  /** Clear the require cache (force fresh require) but only if not within `node_modules` */
310
295
  clearCache?: boolean;
311
296
  /** Automatically de-default the result of requiring the module. */
312
297
  interopDefault?: boolean;
313
298
  }
299
+ /** @deprecated Do not use CJS utils */
314
300
  declare function isNodeModules(id: string): boolean;
301
+ /** @deprecated Do not use CJS utils */
315
302
  declare function clearRequireCache(id: string): void;
303
+ /** @deprecated Do not use CJS utils */
316
304
  declare function scanRequireTree(id: string, files?: Set<string>): Set<string>;
317
- /** Access the require cache by module id. */
305
+ /** @deprecated Do not use CJS utils */
318
306
  declare function getRequireCacheItem(id: string): NodeModule | undefined;
319
307
  /** Resolve the `package.json` file for a given module. */
320
308
  declare function requireModulePkg(id: string, opts?: RequireModuleOptions): any;
321
- /** Resolve the path of a module. */
309
+ /** @deprecated Do not use CJS utils */
322
310
  declare function resolveModule(id: string, opts?: ResolveModuleOptions): string;
323
- /** 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 */
324
312
  declare function tryResolveModule(path: string, opts?: ResolveModuleOptions): string | null;
325
- /** Require a module and return it. */
313
+ /** @deprecated Do not use CJS utils */
326
314
  declare function requireModule(id: string, opts?: RequireModuleOptions): any;
315
+ /** @deprecated Do not use CJS utils */
327
316
  declare function importModule(id: string, opts?: RequireModuleOptions): Promise<any>;
317
+ /** @deprecated Do not use CJS utils */
328
318
  declare function tryImportModule(id: string, opts?: RequireModuleOptions): Promise<any> | undefined;
329
- /** 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 */
330
320
  declare function tryRequireModule(id: string, opts?: RequireModuleOptions): any;
331
321
 
322
+ /** @deprecated */
332
323
  declare function compileTemplate(template: NuxtTemplate, ctx: any): Promise<string>;
333
324
  /** @deprecated */
334
325
  declare const templateUtils: {
@@ -339,4 +330,4 @@ declare const templateUtils: {
339
330
  }) => string;
340
331
  };
341
332
 
342
- export { AddComponentOptions, AddPluginOptions, ExtendConfigOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, LoadNuxtConfigOptions, LoadNuxtOptions, RequireModuleOptions, ResolveModuleOptions, ResolvePathOptions, Resolver, addAutoImport, addAutoImportDir, 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, useModuleContainer, useNitro, 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 { resolveAlias as resolveAlias$1 } 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,50 +36,6 @@ 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
- function updateTemplates(options) {
99
- return useNuxt().hooks.callHook("builder:generateApp", options);
100
- }
101
-
102
39
  async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
103
40
  const issues = [];
104
41
  if (constraints.nuxt) {
@@ -155,39 +92,122 @@ function getNuxtVersion(nuxt = useNuxt()) {
155
92
  return version;
156
93
  }
157
94
 
158
- const logger = consola;
159
- function useLogger(scope) {
160
- 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));
161
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 };
162
125
 
163
- function addLayout(template, name) {
164
- const nuxt = useNuxt();
165
- const { filename, src } = addTemplate(template);
166
- const layoutName = kebabCase(name || parse(filename).name).replace(/["']/g, "");
167
- if (isNuxt2(nuxt)) {
168
- const layout = nuxt.options.layouts[layoutName];
169
- if (layout) {
170
- return logger.warn(
171
- `Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`
172
- );
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);
173
139
  }
174
- nuxt.options.layouts[layoutName] = `./${filename}`;
175
- if (name === "error") {
176
- 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;
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);
177
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]) {
178
176
  return;
179
177
  }
180
- nuxt.hook("app:templates", (app) => {
181
- if (layoutName in app.layouts) {
182
- const relativePath = relative(nuxt.options.srcDir, app.layouts[layoutName].file);
183
- return logger.warn(
184
- `Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`
185
- );
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);
186
189
  }
187
- app.layouts[layoutName] = {
188
- file: join("#build", filename),
189
- 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
+ }
190
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
+ }
191
211
  });
192
212
  }
193
213
 
@@ -390,45 +410,13 @@ async function resolveFiles(path, pattern, opts = {}) {
390
410
  return files.map((p) => resolve(path, p)).filter((p) => !isIgnored(p)).sort();
391
411
  }
392
412
 
393
- function normalizePlugin(plugin) {
394
- if (typeof plugin === "string") {
395
- plugin = { src: plugin };
396
- } else {
397
- plugin = { ...plugin };
398
- }
399
- if (!plugin.src) {
400
- throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
401
- }
402
- plugin.src = normalize(resolveAlias(plugin.src));
403
- if (plugin.ssr) {
404
- plugin.mode = "server";
405
- }
406
- if (!plugin.mode) {
407
- const [, mode = "all"] = plugin.src.match(/\.(server|client)(\.\w+)*$/) || [];
408
- plugin.mode = mode;
409
- }
410
- return plugin;
411
- }
412
- function addPlugin(_plugin, opts = {}) {
413
- const nuxt = useNuxt();
414
- const plugin = normalizePlugin(_plugin);
415
- nuxt.options.plugins = nuxt.options.plugins.filter((p) => normalizePlugin(p).src !== plugin.src);
416
- nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
417
- return plugin;
418
- }
419
- function addPluginTemplate(plugin, opts = {}) {
420
- const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
421
- return addPlugin(normalizedPlugin, opts);
422
- }
423
-
424
413
  async function installModule(moduleToInstall, _inlineOptions, _nuxt) {
425
414
  const nuxt = useNuxt();
426
415
  const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions);
427
- await nuxtModule.call(
428
- useModuleContainer(),
429
- inlineOptions,
430
- nuxt
431
- );
416
+ await nuxtModule(inlineOptions, nuxt);
417
+ if (typeof moduleToInstall === "string") {
418
+ nuxt.options.build.transpile.push(moduleToInstall);
419
+ }
432
420
  nuxt.options._installedModules = nuxt.options._installedModules || [];
433
421
  nuxt.options._installedModules.push({
434
422
  meta: await nuxtModule.getMeta?.(),
@@ -437,10 +425,6 @@ async function installModule(moduleToInstall, _inlineOptions, _nuxt) {
437
425
  }
438
426
  async function normalizeModule(nuxtModule, inlineOptions) {
439
427
  const nuxt = useNuxt();
440
- if (nuxtModule?._version || nuxtModule?.version || nuxtModule?.constructor?.version || "") {
441
- [nuxtModule, inlineOptions] = [inlineOptions, {}];
442
- console.warn(new Error("`installModule` is being called with old signature!"));
443
- }
444
428
  if (typeof nuxtModule === "string") {
445
429
  const _src = resolveModule(resolveAlias(nuxtModule), { paths: nuxt.options.modulesDir });
446
430
  const isESM = _src.endsWith(".mjs");
@@ -457,207 +441,6 @@ async function normalizeModule(nuxtModule, inlineOptions) {
457
441
  return { nuxtModule, inlineOptions };
458
442
  }
459
443
 
460
- const MODULE_CONTAINER_KEY = "__module_container__";
461
- function useModuleContainer(nuxt = useNuxt()) {
462
- if (nuxt[MODULE_CONTAINER_KEY]) {
463
- return nuxt[MODULE_CONTAINER_KEY];
464
- }
465
- async function requireModule(moduleOpts) {
466
- let src, inlineOptions;
467
- if (typeof moduleOpts === "string") {
468
- src = moduleOpts;
469
- } else if (Array.isArray(moduleOpts)) {
470
- [src, inlineOptions] = moduleOpts;
471
- } else if (typeof moduleOpts === "object") {
472
- if (moduleOpts.src || moduleOpts.handler) {
473
- src = moduleOpts.src || moduleOpts.handler;
474
- inlineOptions = moduleOpts.options;
475
- } else {
476
- src = moduleOpts;
477
- }
478
- } else {
479
- src = moduleOpts;
480
- }
481
- await installModule(src, inlineOptions);
482
- }
483
- const container = {
484
- nuxt,
485
- options: nuxt.options,
486
- ready() {
487
- return Promise.resolve();
488
- },
489
- addVendor() {
490
- },
491
- requireModule,
492
- addModule: requireModule,
493
- addServerMiddleware: () => {
494
- },
495
- addTemplate(template) {
496
- if (typeof template === "string") {
497
- template = { src: template };
498
- }
499
- if (template.write === void 0) {
500
- template.write = true;
501
- }
502
- return addTemplate(template);
503
- },
504
- addPlugin(pluginTemplate) {
505
- return addPluginTemplate(pluginTemplate);
506
- },
507
- addLayout(tmpl, name) {
508
- return addLayout(tmpl, name);
509
- },
510
- addErrorLayout(dst) {
511
- const relativeBuildDir = relative(nuxt.options.rootDir, nuxt.options.buildDir);
512
- nuxt.options.ErrorPage = `~/${relativeBuildDir}/${dst}`;
513
- },
514
- extendBuild(fn) {
515
- nuxt.options.build.extend = chainFn(nuxt.options.build.extend, fn);
516
- if (!isNuxt2(nuxt)) {
517
- console.warn("[kit] [compat] Using `extendBuild` in Nuxt 3 has no effect. Instead call extendWebpackConfig and extendViteConfig.");
518
- }
519
- },
520
- extendRoutes(fn) {
521
- if (isNuxt2(nuxt)) {
522
- nuxt.options.router.extendRoutes = chainFn(nuxt.options.router.extendRoutes, fn);
523
- } else {
524
- nuxt.hook("pages:extend", async (pages, ...args) => {
525
- const maybeRoutes = await fn(pages, ...args);
526
- if (maybeRoutes) {
527
- console.warn("[kit] [compat] Using `extendRoutes` in Nuxt 3 needs to directly modify first argument instead of returning updated routes. Skipping extended routes.");
528
- }
529
- });
530
- }
531
- }
532
- };
533
- nuxt[MODULE_CONTAINER_KEY] = container;
534
- return nuxt[MODULE_CONTAINER_KEY];
535
- }
536
-
537
- async function compileTemplate(template, ctx) {
538
- const data = { ...ctx, options: template.options };
539
- if (template.src) {
540
- try {
541
- const srcContents = await promises.readFile(template.src, "utf-8");
542
- return lodashTemplate(srcContents, {})(data);
543
- } catch (err) {
544
- console.error("Error compiling template: ", template);
545
- throw err;
546
- }
547
- }
548
- if (template.getContents) {
549
- return template.getContents(data);
550
- }
551
- throw new Error("Invalid template: " + JSON.stringify(template));
552
- }
553
- const serialize = (data) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, (r) => JSON.parse(r).replace(/^{(.*)}$/, "$1"));
554
- const importSources = (sources, { lazy = false } = {}) => {
555
- if (!Array.isArray(sources)) {
556
- sources = [sources];
557
- }
558
- return sources.map((src) => {
559
- if (lazy) {
560
- return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
561
- }
562
- return genImport(src, genSafeVariableName(src));
563
- }).join("\n");
564
- };
565
- const importName = genSafeVariableName;
566
- const templateUtils = { serialize, importName, importSources };
567
-
568
- function defineNuxtModule(definition) {
569
- if (typeof definition === "function") {
570
- definition = definition(useNuxt());
571
- logger.warn("Module definition as function is deprecated and will be removed in the future versions", definition);
572
- }
573
- if (!definition.meta) {
574
- definition.meta = {};
575
- }
576
- if (!definition.meta.configKey) {
577
- definition.meta.name = definition.meta.name || definition.name;
578
- definition.meta.configKey = definition.configKey || definition.meta.name;
579
- }
580
- async function getOptions(inlineOptions, nuxt = useNuxt()) {
581
- const configKey = definition.meta.configKey || definition.meta.name;
582
- const _defaults = definition.defaults instanceof Function ? definition.defaults(nuxt) : definition.defaults;
583
- let _options = defu(inlineOptions, nuxt.options[configKey], _defaults);
584
- if (definition.schema) {
585
- _options = await applyDefaults(definition.schema, _options);
586
- }
587
- return Promise.resolve(_options);
588
- }
589
- async function normalizedModule(inlineOptions, nuxt) {
590
- if (!nuxt) {
591
- nuxt = tryUseNuxt() || this.nuxt;
592
- }
593
- const uniqueKey = definition.meta.name || definition.meta.configKey;
594
- if (uniqueKey) {
595
- nuxt.options._requiredModules = nuxt.options._requiredModules || {};
596
- if (nuxt.options._requiredModules[uniqueKey]) {
597
- return;
598
- }
599
- nuxt.options._requiredModules[uniqueKey] = true;
600
- }
601
- if (definition.meta.compatibility) {
602
- const issues = await checkNuxtCompatibility(definition.meta.compatibility, nuxt);
603
- if (issues.length) {
604
- logger.warn(`Module \`${definition.meta.name}\` is disabled due to incompatibility issues:
605
- ${issues.toString()}`);
606
- return;
607
- }
608
- }
609
- nuxt2Shims(nuxt);
610
- const _options = await getOptions(inlineOptions, nuxt);
611
- if (definition.hooks) {
612
- nuxt.hooks.addHooks(definition.hooks);
613
- }
614
- await definition.setup?.call(null, _options, nuxt);
615
- }
616
- normalizedModule.getMeta = () => Promise.resolve(definition.meta);
617
- normalizedModule.getOptions = getOptions;
618
- return normalizedModule;
619
- }
620
- const NUXT2_SHIMS_KEY = "__nuxt2_shims_key__";
621
- function nuxt2Shims(nuxt) {
622
- if (!isNuxt2(nuxt) || nuxt[NUXT2_SHIMS_KEY]) {
623
- return;
624
- }
625
- nuxt[NUXT2_SHIMS_KEY] = true;
626
- nuxt.hooks = nuxt;
627
- if (!nuxtCtx.tryUse()) {
628
- nuxtCtx.set(nuxt);
629
- nuxt.hook("close", () => nuxtCtx.unset());
630
- }
631
- let virtualTemplates;
632
- nuxt.hook("builder:prepared", (_builder, buildOptions) => {
633
- virtualTemplates = buildOptions.templates.filter((t) => t.getContents);
634
- for (const template of virtualTemplates) {
635
- buildOptions.templates.splice(buildOptions.templates.indexOf(template), 1);
636
- }
637
- });
638
- nuxt.hook("build:templates", async (templates) => {
639
- const context = {
640
- nuxt,
641
- utils: templateUtils,
642
- app: {
643
- dir: nuxt.options.srcDir,
644
- extensions: nuxt.options.extensions,
645
- plugins: nuxt.options.plugins,
646
- templates: [
647
- ...templates.templatesFiles,
648
- ...virtualTemplates
649
- ],
650
- templateVars: templates.templateVars
651
- }
652
- };
653
- for await (const template of virtualTemplates) {
654
- const contents = await compileTemplate({ ...template, src: "" }, context);
655
- await promises.mkdir(dirname(template.dst), { recursive: true });
656
- await promises.writeFile(template.dst, contents);
657
- }
658
- });
659
- }
660
-
661
444
  async function loadNuxtConfig(opts) {
662
445
  globalThis.defineNuxtConfig = (c) => c;
663
446
  const result = await loadConfig({
@@ -732,27 +515,25 @@ async function buildNuxt(nuxt) {
732
515
 
733
516
  function addImports(imports) {
734
517
  assertNuxtCompatibility({ bridge: true });
735
- useNuxt().hook("autoImports:extend", (_imports) => {
518
+ useNuxt().hook("imports:extend", (_imports) => {
736
519
  _imports.push(...Array.isArray(imports) ? imports : [imports]);
737
- }, { allowDeprecated: true });
520
+ });
738
521
  }
739
- const addAutoImport = addImports;
740
522
  function addImportsDir(dirs) {
741
523
  assertNuxtCompatibility({ bridge: true });
742
- useNuxt().hook("autoImports:dirs", (_dirs) => {
524
+ useNuxt().hook("imports:dirs", (_dirs) => {
743
525
  for (const dir of Array.isArray(dirs) ? dirs : [dirs]) {
744
526
  _dirs.push(dir);
745
527
  }
746
- }, { allowDeprecated: true });
528
+ });
747
529
  }
748
- const addAutoImportDir = addImportsDir;
749
530
  function addImportsSources(presets) {
750
531
  assertNuxtCompatibility({ bridge: true });
751
- useNuxt().hook("autoImports:sources", (_presets) => {
532
+ useNuxt().hook("imports:sources", (_presets) => {
752
533
  for (const preset of Array.isArray(presets) ? presets : [presets]) {
753
534
  _presets.push(preset);
754
535
  }
755
- }, { allowDeprecated: true });
536
+ });
756
537
  }
757
538
 
758
539
  function extendWebpackConfig(fn, options = {}) {
@@ -776,12 +557,6 @@ function extendWebpackConfig(fn, options = {}) {
776
557
  fn(config);
777
558
  }
778
559
  }
779
- if (options.modern !== false) {
780
- const config = configs.find((i) => i.name === "modern");
781
- if (config) {
782
- fn(config);
783
- }
784
- }
785
560
  });
786
561
  }
787
562
  function extendViteConfig(fn, options = {}) {
@@ -847,10 +622,6 @@ async function addComponent(opts) {
847
622
  preload: false,
848
623
  mode: "all",
849
624
  shortPath: opts.filePath,
850
- async: false,
851
- level: 0,
852
- asyncImport: `${genDynamicImport(opts.filePath)}.then(r => r['${opts.export || "default"}'])`,
853
- import: `require(${JSON.stringify(opts.filePath)})['${opts.export || "default"}']`,
854
625
  ...opts
855
626
  };
856
627
  nuxt.hook("components:extend", (components) => {
@@ -865,6 +636,81 @@ async function addComponent(opts) {
865
636
  });
866
637
  }
867
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
+
868
714
  function extendPages(cb) {
869
715
  const nuxt = useNuxt();
870
716
  if (isNuxt2(nuxt)) {
@@ -874,6 +720,37 @@ function extendPages(cb) {
874
720
  }
875
721
  }
876
722
 
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
+
877
754
  function normalizeHandlerMethod(handler) {
878
755
  const [, method = void 0] = handler.handler.match(/\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/) || [];
879
756
  return {
@@ -916,4 +793,4 @@ function useNitro() {
916
793
  return nuxt._nitro;
917
794
  }
918
795
 
919
- export { addAutoImport, addAutoImportDir, 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, useModuleContainer, useNitro, useNuxt };
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.13",
3
+ "version": "3.0.0-rc.14",
4
4
  "repository": "nuxt/framework",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -10,24 +10,24 @@
10
10
  "dist"
11
11
  ],
12
12
  "dependencies": {
13
- "@nuxt/schema": "3.0.0-rc.13",
14
- "c12": "^0.2.13",
13
+ "@nuxt/schema": "3.0.0-rc.14",
14
+ "c12": "^1.0.1",
15
15
  "consola": "^2.15.3",
16
- "defu": "^6.1.0",
16
+ "defu": "^6.1.1",
17
17
  "globby": "^13.1.2",
18
18
  "hash-sum": "^2.0.0",
19
19
  "ignore": "^5.2.0",
20
20
  "jiti": "^1.16.0",
21
- "knitwork": "^0.1.2",
21
+ "knitwork": "^1.0.0",
22
22
  "lodash.template": "^4.5.0",
23
- "mlly": "^0.5.16",
24
- "pathe": "^0.3.9",
25
- "pkg-types": "^0.3.6",
26
- "scule": "^0.3.2",
23
+ "mlly": "^1.0.0",
24
+ "pathe": "^1.0.0",
25
+ "pkg-types": "^1.0.1",
26
+ "scule": "^1.0.0",
27
27
  "semver": "^7.3.8",
28
- "unctx": "^2.0.2",
29
- "unimport": "^0.7.0",
30
- "untyped": "^0.5.0"
28
+ "unctx": "^2.1.0",
29
+ "unimport": "^1.0.0",
30
+ "untyped": "^1.0.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/lodash.template": "^4",