@nuxt/bridge-edge 3.0.0-27666083.80ccd51 → 3.0.0-27690335.da95eff

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.
@@ -1,1281 +1,203 @@
1
- import { createRequire } from 'module';
2
- import { useNuxt, addPluginTemplate, tryImportModule, resolvePath, addTemplate, resolveAlias, addWebpackPlugin, addVitePlugin, addPlugin, extendWebpackConfig, resolveFiles, defineNuxtModule, logger, tryResolveModule, installModule, checkNuxtCompatibility } from '@nuxt/kit';
3
- import fs, { existsSync, readdirSync, statSync, promises } from 'fs';
4
- import { fileURLToPath, pathToFileURL } from 'url';
5
- import fetch from 'node-fetch';
6
- import fse from 'fs-extra';
7
- import { withoutTrailingSlash, joinURL, stringifyQuery, withBase, parseURL, parseQuery } from 'ufo';
8
- import { dirname, join as join$1, resolve, normalize, isAbsolute, relative, parse as parse$1 } from 'pathe';
9
- import { createNitro, writeTypes, build, prepare, copyPublicAssets, prerender, createDevServer } from 'nitropack';
10
- import { dynamicEventHandler, toEventHandler } from 'h3';
11
- import { defu } from 'defu';
12
- import { join } from 'path';
13
- import { findStaticImports, resolveImports, findExports } from 'mlly';
14
- import { genDynamicImport, genString } from 'knitwork';
15
- import { generateTypes, resolveSchema } from 'untyped';
16
- import MagicString from 'magic-string';
17
- import { createUnplugin } from 'unplugin';
18
- import crypto from 'crypto';
19
- import { parse } from 'acorn';
20
- import { walk } from 'estree-walker';
21
- import { promisify } from 'util';
22
- import enhancedResolve from 'enhanced-resolve';
23
- import { defineUnimportPreset, createUnimport, toImports } from 'unimport';
24
- import { camelCase } from 'scule';
1
+ import { defineNuxtModule, logger, addPluginTemplate, addTemplate } from '@nuxt/kit';
2
+ import hash from 'hash-sum';
3
+ import { resolve } from 'pathe';
4
+ import { genImport, genObjectFromRawEntries } from 'knitwork';
25
5
 
26
- class AsyncLoadingPlugin {
27
- constructor(opts) {
28
- this.opts = opts;
29
- const _require = createRequire(import.meta.url);
30
- const TemplatePath = _require.resolve("webpack/lib/Template", { paths: [...this.opts.modulesDir] });
31
- this.Template = _require(TemplatePath);
32
- }
33
- apply(compiler) {
34
- compiler.hooks.compilation.tap("AsyncLoading", (compilation) => {
35
- const mainTemplate = compilation.mainTemplate;
36
- mainTemplate.hooks.requireEnsure.tap("AsyncLoading", (_source, chunk, hash) => {
37
- const Template = this.Template;
38
- const chunkFilename = mainTemplate.outputOptions.chunkFilename;
39
- const chunkMaps = chunk.getChunkMaps();
40
- const insertMoreModules = [
41
- "var moreModules = chunk.modules, chunkIds = chunk.ids;",
42
- "for(var moduleId in moreModules) {",
43
- Template.indent(mainTemplate.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
44
- "}"
45
- ];
46
- return Template.asString([
47
- "// Async chunk loading for Nitro",
48
- "",
49
- "var installedChunkData = installedChunks[chunkId];",
50
- 'if(installedChunkData !== 0) { // 0 means "already installed".',
51
- Template.indent([
52
- '// array of [resolve, reject, promise] means "currently loading"',
53
- "if(installedChunkData) {",
54
- Template.indent(["promises.push(installedChunkData[2]);"]),
55
- "} else {",
56
- Template.indent([
57
- "// load the chunk and return promise to it",
58
- "var promise = new Promise(function(resolve, reject) {",
59
- Template.indent([
60
- "installedChunkData = installedChunks[chunkId] = [resolve, reject];",
61
- "import(" + mainTemplate.getAssetPath(JSON.stringify(`./${chunkFilename}`), {
62
- hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
63
- hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
64
- chunk: {
65
- id: '" + chunkId + "',
66
- hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
67
- hashWithLength: (length) => {
68
- const shortChunkHashMap = {};
69
- for (const chunkId of Object.keys(chunkMaps.hash)) {
70
- if (typeof chunkMaps.hash[chunkId] === "string") {
71
- shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
72
- }
73
- }
74
- return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
75
- },
76
- contentHash: {
77
- javascript: `" + ${JSON.stringify(chunkMaps.contentHash.javascript)}[chunkId] + "`
78
- },
79
- contentHashWithLength: {
80
- javascript: (length) => {
81
- const shortContentHashMap = {};
82
- const contentHash = chunkMaps.contentHash.javascript;
83
- for (const chunkId of Object.keys(contentHash)) {
84
- if (typeof contentHash[chunkId] === "string") {
85
- shortContentHashMap[chunkId] = contentHash[chunkId].substr(0, length);
86
- }
87
- }
88
- return `" + ${JSON.stringify(shortContentHashMap)}[chunkId] + "`;
89
- }
90
- },
91
- name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
92
- },
93
- contentHashType: "javascript"
94
- }) + ").then(chunk => {",
95
- Template.indent(insertMoreModules.concat([
96
- "var callbacks = [];",
97
- "for(var i = 0; i < chunkIds.length; i++) {",
98
- Template.indent([
99
- "if(installedChunks[chunkIds[i]])",
100
- Template.indent([
101
- "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);"
102
- ]),
103
- "installedChunks[chunkIds[i]] = 0;"
104
- ]),
105
- "}",
106
- "for(i = 0; i < callbacks.length; i++)",
107
- Template.indent("callbacks[i]();")
108
- ])),
109
- "});"
110
- ]),
111
- "});",
112
- "promises.push(installedChunkData[2] = promise);"
113
- ]),
114
- "}"
115
- ]),
116
- "}"
117
- ]);
118
- });
119
- });
120
- }
121
- }
122
-
123
- let dir = dirname(fileURLToPath(import.meta.url));
124
- while (dir !== "/" && !existsSync(join(dir, "package.json"))) {
125
- dir = dirname(dir);
126
- }
127
- const pkgDir = dir;
128
- const distDir = join(pkgDir, "dist");
6
+ const version = "3.0.0-27690335.da95eff";
129
7
 
130
- function readDirRecursively(dir) {
131
- return readdirSync(dir).reduce((files, file) => {
132
- const name = join$1(dir, file);
133
- const isDirectory2 = statSync(name).isDirectory();
134
- return isDirectory2 ? [...files, ...readDirRecursively(name)] : [...files, name];
135
- }, []);
136
- }
137
- async function isDirectory(path) {
138
- try {
139
- return (await promises.stat(path)).isDirectory();
140
- } catch (_err) {
141
- return false;
142
- }
143
- }
144
-
145
- async function setupNitroBridge() {
146
- const nuxt = useNuxt();
147
- if (!nuxt.options.dev && nuxt.options.target === "static" && !nuxt.options._prepare && !nuxt.options._generate && !nuxt.options._export && !nuxt.options._legacyGenerate) {
148
- throw new Error("[nitro] Please use `nuxt generate` for static target");
149
- }
150
- nuxt.options.app.buildAssetsDir = nuxt.options.app.buildAssetsDir || nuxt.options.app.assetsPath;
151
- nuxt.options.app.assetsPath = nuxt.options.app.buildAssetsDir;
152
- nuxt.options.app.baseURL = nuxt.options.app.baseURL || nuxt.options.app.basePath;
153
- nuxt.options.app.cdnURL = nuxt.options.app.cdnURL || "";
154
- const publicConfig = nuxt.options.publicRuntimeConfig;
155
- const appConfig = { ...publicConfig._app, ...publicConfig.app };
156
- delete publicConfig.app;
157
- delete publicConfig._app;
158
- nuxt.options.runtimeConfig = defu(nuxt.options.runtimeConfig, {
159
- ...publicConfig,
160
- ...nuxt.options.privateRuntimeConfig,
161
- public: publicConfig,
162
- app: appConfig
163
- });
164
- nuxt.options.build.loadingScreen = false;
165
- nuxt.options.build.indicator = false;
166
- if (nuxt.options.build.analyze === true) {
167
- const { rootDir } = nuxt.options;
168
- nuxt.options.build.analyze = {
169
- template: "treemap",
170
- projectRoot: rootDir,
171
- filename: join$1(rootDir, ".nuxt/stats", "{name}.html")
172
- };
173
- }
174
- const _nitroConfig = nuxt.options.nitro || {};
175
- const nitroConfig = defu(_nitroConfig, {
176
- rootDir: resolve(nuxt.options.rootDir),
177
- srcDir: resolve(nuxt.options.srcDir, "server"),
178
- dev: nuxt.options.dev,
179
- preset: nuxt.options.dev ? "nitro-dev" : void 0,
180
- buildDir: resolve(nuxt.options.buildDir),
181
- scanDirs: nuxt.options._layers.map((layer) => join$1(layer.config.srcDir, "server")),
182
- renderer: resolve(distDir, "runtime/nitro/renderer"),
183
- errorHandler: resolve(distDir, "runtime/nitro/error"),
184
- nodeModulesDirs: nuxt.options.modulesDir,
185
- handlers: [],
186
- devHandlers: [],
187
- baseURL: nuxt.options.app.baseURL || "/",
188
- virtual: {},
189
- runtimeConfig: {
190
- ...nuxt.options.runtimeConfig,
191
- nitro: {
192
- envPrefix: "NUXT_",
193
- ...nuxt.options.runtimeConfig.nitro
194
- }
195
- },
196
- typescript: {
197
- generateTsConfig: false
198
- },
199
- publicAssets: [
200
- {
201
- baseURL: nuxt.options.app.buildAssetsDir,
202
- dir: resolve(nuxt.options.buildDir, "dist/client")
203
- },
204
- ...nuxt.options._layers.map((layer) => join$1(layer.config.srcDir, layer.config.dir.static)).filter((dir) => existsSync(dir)).map((dir) => ({ dir }))
205
- ],
206
- prerender: {
207
- crawlLinks: nuxt.options._generate ? nuxt.options.generate.crawler : false,
208
- routes: [].concat(nuxt.options._generate ? ["/", ...nuxt.options.generate.routes] : []).concat(nuxt.options.ssr === false ? ["/", "/200", "/404"] : [])
209
- },
210
- externals: {
211
- inline: [
212
- ...nuxt.options.dev ? [] : ["vue", "@vue/", "@nuxt/", normalize(nuxt.options.buildDir)],
213
- "@nuxt/bridge/dist",
214
- "@nuxt/bridge-edge/dist"
215
- ]
216
- },
217
- alias: {
218
- encoding: "unenv/runtime/mock/proxy",
219
- he: "unenv/runtime/mock/proxy",
220
- resolve: "unenv/runtime/mock/proxy",
221
- "source-map": "unenv/runtime/mock/proxy",
222
- "lodash.template": "unenv/runtime/mock/proxy",
223
- "serialize-javascript": "unenv/runtime/mock/proxy",
224
- "#vue-renderer": resolve(distDir, "runtime/nitro/vue2"),
225
- "#vue2-server-renderer": "vue-server-renderer/" + (nuxt.options.dev ? "build.dev.js" : "build.prod.js"),
226
- "#paths": resolve(distDir, "runtime/nitro/paths"),
227
- ...nuxt.options.alias
228
- },
229
- replace: {
230
- "process.env.NUXT_NO_SSR": nuxt.options.ssr === false
231
- },
232
- rollupConfig: {
233
- plugins: []
234
- }
235
- });
236
- if (!nuxt.options.ssr) {
237
- nitroConfig.virtual["#build/dist/server/server.mjs"] = "export default () => {}";
238
- }
239
- delete nitroConfig.alias["#build"];
240
- await nuxt.callHook("nitro:config", nitroConfig);
241
- const nitro = await createNitro(nitroConfig);
242
- await nuxt.callHook("nitro:init", nitro);
243
- nitro.vfs = nuxt.vfs = nitro.vfs || nuxt.vfs || {};
244
- nuxt.hook("close", () => nitro.hooks.callHook("close"));
245
- async function updateViteBase() {
246
- const clientDist = resolve(nuxt.options.buildDir, "dist/client");
247
- const publicDir = join$1(nuxt.options.srcDir, nuxt.options.dir.static);
248
- let publicFiles = [];
249
- if (await isDirectory(publicDir)) {
250
- publicFiles = readDirRecursively(publicDir).map((r) => r.replace(publicDir, ""));
251
- for (const file of publicFiles) {
252
- try {
253
- fse.rmSync(join$1(clientDist, file));
254
- } catch {
255
- }
256
- }
257
- }
258
- if (await isDirectory(clientDist)) {
259
- const nestedAssetsPath = withoutTrailingSlash(join$1(clientDist, nuxt.options.app.buildAssetsDir));
260
- if (await isDirectory(nestedAssetsPath)) {
261
- await fse.copy(nestedAssetsPath, clientDist, { recursive: true });
262
- await fse.remove(nestedAssetsPath);
263
- }
264
- }
265
- }
266
- nuxt.hook("generate:before", updateViteBase);
267
- nuxt.options.extensions.push("ts");
268
- nuxt.hook("webpack:config", (webpackConfigs) => {
269
- const serverConfig = webpackConfigs.find((config) => config.name === "server");
270
- if (serverConfig) {
271
- serverConfig.devtool = false;
272
- }
273
- });
274
- nuxt.hook("webpack:config", (webpackConfigs) => {
275
- const serverConfig = webpackConfigs.find((config) => config.name === "server");
276
- if (serverConfig) {
277
- serverConfig.plugins = serverConfig.plugins || [];
278
- serverConfig.plugins.push(new AsyncLoadingPlugin({
279
- modulesDir: nuxt.options.modulesDir
280
- }));
281
- }
282
- });
283
- addPluginTemplate({
284
- filename: "nitro-bridge.client.mjs",
285
- src: resolve(distDir, "runtime/nitro-bridge.client.mjs")
286
- });
287
- addPluginTemplate({
288
- filename: "nitro-bridge.server.mjs",
289
- src: resolve(distDir, "runtime/nitro-bridge.server.mjs")
290
- });
291
- nuxt.hook("webpack:config", (configs) => {
292
- for (const config of configs) {
293
- if (Array.isArray(config.resolve.alias)) {
294
- return;
8
+ const middlewareTemplate = {
9
+ filename: "middleware.js",
10
+ getContents(ctx) {
11
+ const { dir, router: { middleware }, srcDir } = ctx.nuxt.options;
12
+ const _middleware = (typeof middleware !== "undefined" && middleware || []).map((m) => {
13
+ if (typeof m === "string") {
14
+ m = { src: m };
295
15
  }
296
- config.resolve.alias.ufo = "ufo/dist/index.mjs";
297
- config.resolve.alias.ohmyfetch = "ohmyfetch/dist/index.mjs";
298
- }
299
- });
300
- nuxt.hook("build:compiled", async ({ name }) => {
301
- if (nuxt.options._prepare) {
302
- return;
303
- }
304
- if (name === "server") {
305
- const jsServerEntry = resolve(nuxt.options.buildDir, "dist/server/server.js");
306
- await promises.writeFile(jsServerEntry.replace(/.js$/, ".cjs"), 'module.exports = require("./server.js")', "utf8");
307
- await promises.writeFile(jsServerEntry.replace(/.js$/, ".mjs"), 'export { default } from "./server.cjs"', "utf8");
308
- } else if (name === "client") {
309
- const manifest = await promises.readFile(resolve(nuxt.options.buildDir, "dist/server/client.manifest.json"), "utf8");
310
- await promises.writeFile(resolve(nuxt.options.buildDir, "dist/server/client.manifest.mjs"), "export default " + manifest, "utf8");
311
- }
312
- });
313
- const devMidlewareHandler = dynamicEventHandler();
314
- nitro.options.devHandlers.unshift({ handler: devMidlewareHandler });
315
- const { handlers, devHandlers } = await resolveHandlers(nuxt);
316
- nitro.options.handlers.push(...handlers);
317
- nitro.options.devHandlers.push(...devHandlers);
318
- nitro.options.handlers.unshift({
319
- route: "/__nuxt_error",
320
- lazy: true,
321
- handler: resolve(distDir, "runtime/nitro/renderer")
322
- });
323
- if (nuxt.server) {
324
- nuxt.server.__closed = true;
325
- nuxt.server = createNuxt2DevServer(nitro);
326
- nuxt.hook("build:resources", () => {
327
- nuxt.server.reload();
328
- });
329
- }
330
- nuxt.hook("prepare:types", (opts) => {
331
- opts.references.push({ path: resolve(nuxt.options.buildDir, "types/nitro.d.ts") });
332
- });
333
- nuxt.hook("build:done", async () => {
334
- await writeTypes(nitro);
335
- });
336
- nuxt.options.build._minifyServer = false;
337
- nuxt.options.build.standalone = false;
338
- const waitUntilCompile = new Promise((resolve2) => nitro.hooks.hook("compiled", () => resolve2()));
339
- nuxt.hook("build:done", async () => {
340
- if (nuxt.options._prepare) {
341
- return;
342
- }
343
- await writeDocumentTemplate(nuxt);
344
- await nuxt.callHook("nitro:build:before", nitro);
345
- if (nuxt.options.dev) {
346
- await build(nitro);
347
- await waitUntilCompile;
348
- } else {
349
- await prepare(nitro);
350
- await copyPublicAssets(nitro);
351
- if (nuxt.options._export || nuxt.options._legacyGenerate) {
352
- return;
353
- }
354
- const useClassicGeneration = process.argv.includes("--classic") || !nuxt.options.bridge.nitroGenerator;
355
- if (useClassicGeneration && nuxt.options._generate) {
356
- const { Generator } = await tryImportModule("@nuxt/generator-edge") || await tryImportModule("@nuxt/generator");
357
- const generator = new Generator(nuxt);
358
- await generator.generate({ build: false });
359
- return;
360
- }
361
- await prerender(nitro);
362
- if (!nuxt.options._generate) {
363
- await build(nitro);
364
- } else {
365
- const distDir2 = resolve(nuxt.options.rootDir, "dist");
366
- if (!existsSync(distDir2)) {
367
- await promises.symlink(nitro.options.output.publicDir, distDir2, "junction").catch(() => {
368
- });
369
- }
370
- }
371
- }
372
- });
373
- nuxt.options.nitro = nuxt.options.nitro || {};
374
- if (!nuxt.options.dev && nuxt.options._generate) {
375
- const routes = /* @__PURE__ */ new Set();
376
- nuxt.hook("build:extendRoutes", (pages) => {
377
- routes.clear();
378
- for (const path of nuxt.options.nitro.prerender?.routes || []) {
379
- routes.add(path);
380
- }
381
- const processPages = (pages2, currentPath = "/") => {
382
- for (const page of pages2) {
383
- if (page.path.includes(":")) {
384
- continue;
385
- }
386
- const path = joinURL(currentPath, page.path);
387
- routes.add(path);
388
- if (page.children) {
389
- processPages(page.children, path);
390
- }
391
- }
16
+ return {
17
+ filePath: resolve(srcDir, dir.middleware, m.src),
18
+ id: m.name || m.src.replace(/[\\/]/g, "/").replace(/\.(js|ts)$/, "")
392
19
  };
393
- processPages(pages);
394
- });
395
- nuxt.hook("nitro:build:before", (nitro2) => {
396
- nitro2.options.prerender.routes = [...routes];
397
- });
398
- }
399
- if (nuxt.options.dev) {
400
- nuxt.hook("build:compile", ({ compiler }) => {
401
- compiler.outputFileSystem = { ...fse, join: join$1 };
402
- });
403
- nuxt.hook("server:devMiddleware", (m) => {
404
- devMidlewareHandler.set(toEventHandler(m));
405
20
  });
406
- }
407
- nuxt.options.generate.dir = nitro.options.output.publicDir;
408
- nuxt.options.generate.manifest = false;
409
- nuxt.hook("generate:cache:ignore", (ignore) => {
410
- ignore.push(nitro.options.output.dir);
411
- ignore.push(nitro.options.output.serverDir);
412
- if (nitro.options.output.publicDir) {
413
- ignore.push(nitro.options.output.publicDir);
414
- }
415
- });
416
- nuxt.hook("generate:before", async () => {
417
- await nuxt.server?.close();
418
- });
419
- nuxt.hook("generate:extendRoutes", async () => {
420
- nuxt.server = await createNuxt2Prerenderer(nitro);
421
- await nuxt.server.listen();
422
- });
423
- nuxt.hook("generate:done", async () => {
424
- await nuxt.server.close();
425
- await build(nitro);
426
- });
427
- }
428
- function createNuxt2DevServer(nitro) {
429
- const server = createDevServer(nitro);
430
- const listeners = [];
431
- async function listen(port) {
432
- const listener = await server.listen(port, {
433
- showURL: false,
434
- isProd: true
435
- });
436
- listeners.push(listener);
437
- return listener;
438
- }
439
- async function renderRoute(route = "/", renderContext = {}) {
440
- const [listener] = listeners;
441
- if (!listener) {
442
- throw new Error("There is no server listener to call `server.renderRoute()`");
443
- }
444
- const res = await fetch(joinURL(listener.url, route), {
445
- headers: { "nuxt-render-context": stringifyQuery(renderContext) }
446
- });
447
- const html = await res.text();
448
- if (!res.ok) {
449
- return { html, error: res.statusText };
450
- }
451
- return { html };
452
- }
453
- return {
454
- ...server,
455
- listeners,
456
- renderRoute,
457
- listen,
458
- serverMiddlewarePaths() {
459
- return [];
460
- },
461
- ready() {
462
- }
463
- };
464
- }
465
- async function createNuxt2Prerenderer(nitro) {
466
- const nitroRenderer = await createNitro({
467
- ...nitro.options._config,
468
- rootDir: nitro.options.rootDir,
469
- logLevel: 0,
470
- preset: "nitro-prerender"
471
- });
472
- await build(nitroRenderer);
473
- const serverEntrypoint = resolve(nitroRenderer.options.output.serverDir, "index.mjs");
474
- const { localFetch } = await import(pathToFileURL(serverEntrypoint).href);
475
- async function renderRoute(route = "/", renderContext = {}) {
476
- const res = await localFetch(withBase(route, nitro.options.baseURL), {
477
- headers: {
478
- "nuxt-render-context": stringifyQuery(renderContext)
479
- }
480
- });
481
- const html = await res.text();
482
- if (!res.ok) {
483
- return { html, error: res.statusText };
484
- }
485
- return { html };
486
- }
487
- return {
488
- ...createNuxt2DevServer(nitroRenderer),
489
- renderRoute
490
- };
491
- }
492
- async function resolveHandlers(nuxt) {
493
- const handlers = [...nuxt.options.serverHandlers || []];
494
- const devHandlers = [...nuxt.options.devServerHandlers || []];
495
- for (let m of nuxt.options.serverMiddleware) {
496
- if (typeof m === "string" || typeof m === "function") {
497
- m = { handler: m };
498
- }
499
- const route = m.path || m.route || "/";
500
- const handler = m.handler || m.handle;
501
- if (typeof handler !== "string" || typeof route !== "string") {
502
- devHandlers.push({ route, handler });
503
- } else {
504
- delete m.handler;
505
- delete m.path;
506
- handlers.push({
507
- ...m,
508
- route,
509
- handler: await resolvePath(handler)
510
- });
511
- }
512
- }
513
- return {
514
- handlers,
515
- devHandlers
516
- };
517
- }
518
- async function writeDocumentTemplate(nuxt) {
519
- const src = nuxt.options.appTemplatePath || resolve(nuxt.options.buildDir, "views/app.template.html");
520
- const dst = resolve(nuxt.options.buildDir, "views/document.template.mjs");
521
- const contents = nuxt.vfs[src] || await promises.readFile(src, "utf-8").catch(() => "");
522
- if (contents) {
523
- const compiled = `export default (params) => \`${contents.replace(/{{ (\w+) }}/g, "${params.$1}")}\``;
524
- await promises.mkdir(dirname(dst), { recursive: true });
525
- await promises.writeFile(dst, compiled, "utf8");
526
- }
527
- }
528
-
529
- const componentsTypeTemplate = {
530
- filename: "components.d.ts",
531
- getContents: ({ options }) => `// Generated by components discovery
532
- declare module 'vue' {
533
- export interface GlobalComponents {
534
- ${options.components.map((c) => ` '${c.pascalName}': typeof ${genDynamicImport(isAbsolute(c.filePath) ? relative(options.buildDir, c.filePath) : c.filePath, { wrapper: false })}['${c.export}']`).join(",\n")}
535
- ${options.components.map((c) => ` 'Lazy${c.pascalName}': typeof ${genDynamicImport(isAbsolute(c.filePath) ? relative(options.buildDir, c.filePath) : c.filePath, { wrapper: false })}['${c.export}']`).join(",\n")}
536
- }
537
- }
538
- ${options.components.map((c) => `export const ${c.pascalName}: typeof ${genDynamicImport(isAbsolute(c.filePath) ? relative(options.buildDir, c.filePath) : c.filePath, { wrapper: false })}['${c.export}']`).join("\n")}
539
- ${options.components.map((c) => `export const Lazy${c.pascalName}: typeof ${genDynamicImport(isAbsolute(c.filePath) ? relative(options.buildDir, c.filePath) : c.filePath, { wrapper: false })}['${c.export}']`).join("\n")}
540
- export const componentNames: string[]
541
- `
542
- };
543
- const adHocModules = ["router", "pages", "auto-imports", "meta", "components"];
544
- const schemaTemplate = {
545
- filename: "types/schema.d.ts",
546
- getContents: ({ nuxt }) => {
547
- const moduleInfo = nuxt.options._installedModules.map((m) => ({
548
- ...m.meta || {},
549
- importName: m.entryPath || m.meta?.name
550
- })).filter((m) => m.configKey && m.name && !adHocModules.includes(m.name));
551
- return [
552
- "import { NuxtModule } from '@nuxt/schema'",
553
- "declare module '@nuxt/schema' {",
554
- " interface NuxtConfig {",
555
- ...moduleInfo.filter(Boolean).map((meta) => ` [${genString(meta.configKey)}]?: typeof ${genDynamicImport(meta.importName, { wrapper: false })}.default extends NuxtModule<infer O> ? Partial<O> : Record<string, any>`),
556
- " }",
557
- generateTypes(resolveSchema(nuxt.options.runtimeConfig), {
558
- interfaceName: "RuntimeConfig",
559
- addExport: false,
560
- addDefaults: false,
561
- allowExtraKeys: false,
562
- indentation: 2
563
- }),
564
- "}"
565
- ].join("\n");
21
+ return `${_middleware.map((m) => genImport(m.filePath, `$${hash(m.id)}`)).join("\n")}
22
+ const middleware = ${genObjectFromRawEntries(_middleware.map((m) => [m.id, `$${hash(m.id)}`]))}
23
+ export default middleware`;
566
24
  }
567
25
  };
26
+ const storeTemplate = {
27
+ filename: "store.js",
28
+ getContents(ctx) {
29
+ const { dir, srcDir } = ctx.nuxt.options;
30
+ const { templateVars: { storeModules = [] } } = ctx.app;
31
+ const _storeModules = storeModules.map((s) => ({
32
+ filePath: resolve(srcDir, dir.store, s.src),
33
+ id: s.src.replace(/\.(js|ts)$/, "").replace(/[\\/]/g, "/").replace(/index/, "") || "root"
34
+ }));
35
+ return `import Vue from 'vue'
36
+ import Vuex from 'vuex'
37
+ ${_storeModules.map((s) => genImport(s.filePath, { name: "*", as: `$${hash(s.id)}` })).join("\n")}
38
+ Vue.use(Vuex)
568
39
 
569
- const VueCompat = createUnplugin((opts) => {
570
- return {
571
- name: "nuxt-legacy-vue-transform",
572
- enforce: "post",
573
- transformInclude(id) {
574
- if (id.includes("vue2-bridge")) {
575
- return false;
576
- }
577
- const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
578
- const query = parseQuery(search);
579
- if (pathname.endsWith(".vue") && (query.type === "script" || !search)) {
580
- return true;
581
- }
582
- if (pathname.match(/\.((c|m)?j|t)sx?/g)) {
583
- return true;
584
- }
585
- },
586
- transform(code, id) {
587
- if (id.includes("vue2-bridge")) {
588
- return;
589
- }
590
- const s = new MagicString(code);
591
- const imports = findStaticImports(code).filter((i) => i.type === "static" && vueAliases.includes(i.specifier));
592
- for (const i of imports) {
593
- s.overwrite(i.start, i.end, i.code.replace(`"${i.specifier}"`, `"${opts.src}"`).replace(`'${i.specifier}'`, `'${opts.src}'`));
594
- }
595
- if (s.hasChanged()) {
596
- return {
597
- code: s.toString(),
598
- map: s.generateMap({ source: id, includeContent: true })
599
- };
600
- }
601
- }
602
- };
603
- });
604
- const vueAliases = [
605
- "@vue/shared",
606
- "@vue/reactivity",
607
- "@vue/runtime-core",
608
- "@vue/runtime-dom"
609
- ];
610
-
611
- async function setupAppBridge(_options) {
612
- const nuxt = useNuxt();
613
- nuxt.options.alias["#app"] = resolve(distDir, "runtime/index");
614
- nuxt.options.alias["nuxt3/app"] = nuxt.options.alias["#app"];
615
- nuxt.options.alias["nuxt/app"] = nuxt.options.alias["#app"];
616
- nuxt.options.alias["#build"] = nuxt.options.buildDir;
617
- nuxt.options.build.transpile.push(resolve(distDir, "runtime").replace("dist", "src"));
618
- nuxt.options.build.transpile.push(normalize(nuxt.options.buildDir));
619
- if (nuxt.options._prepare) {
620
- nuxt.hook("builder:prepared", (builder) => {
621
- builder.bundleBuilder.build = () => Promise.resolve(builder.bundleBuilder);
622
- });
623
- }
624
- nuxt.options.build.transpile.push("vuex");
625
- nuxt.options.build.transpile.push("h3");
626
- nuxt.options.fetch.server = false;
627
- nuxt.options.fetch.client = false;
628
- const components = [];
629
- nuxt.hook("components:extend", (registeredComponents) => {
630
- components.push(...registeredComponents);
631
- });
632
- addTemplate({
633
- ...componentsTypeTemplate,
634
- options: { components, buildDir: nuxt.options.buildDir }
635
- });
636
- nuxt.hook("prepare:types", ({ references }) => {
637
- references.push({ path: resolve(nuxt.options.buildDir, "types/components.d.ts") });
638
- });
639
- nuxt.hook("modules:done", async (container) => {
640
- nuxt.options._installedModules = await Promise.all(Object.values(container.requiredModules).map(async (m) => ({
641
- meta: await m.handler.getMeta?.(),
642
- entryPath: resolveAlias(m.src, nuxt.options.alias)
643
- })));
644
- addTemplate(schemaTemplate);
645
- });
646
- nuxt.hook("prepare:types", ({ references }) => {
647
- references.push({ path: resolve(nuxt.options.buildDir, "types/schema.d.ts") });
648
- });
649
- const { dst: vueCompat } = addTemplate({ src: resolve(distDir, "runtime/vue2-bridge.mjs") });
650
- addWebpackPlugin(VueCompat.webpack({ src: vueCompat }));
651
- addVitePlugin(VueCompat.vite({ src: vueCompat }));
652
- nuxt.hook("prepare:types", ({ tsConfig }) => {
653
- tsConfig.vueCompilerOptions = {
654
- target: 2.7
655
- };
656
- });
657
- if (nuxt.options.globalName !== "nuxt") {
658
- throw new Error("Custom global name is not supported by @nuxt/bridge.");
659
- }
660
- nuxt.options.alias.defu = await resolveImports("defu", { conditions: ["import"] });
661
- nuxt.hook("webpack:config", (configs) => {
662
- for (const config of configs.filter((c) => c.module)) {
663
- const jsRule = config.module.rules.find((rule) => rule.test instanceof RegExp && rule.test.test("index.mjs"));
664
- jsRule.type = "javascript/auto";
665
- config.module.rules.unshift({
666
- test: /\.mjs$/,
667
- type: "javascript/auto",
668
- include: [/node_modules/]
669
- });
670
- }
671
- });
672
- addPlugin({
673
- src: resolve(distDir, "runtime/error.plugin.server.mjs"),
674
- mode: "server"
675
- });
676
- }
40
+ const VUEX_PROPERTIES = ['state', 'getters', 'actions', 'mutations']
677
41
 
678
- function createKey(source, method = "base64") {
679
- const hash = crypto.createHash("md5");
680
- hash.update(source);
681
- return hash.digest(method).toString();
682
- }
683
- const keyedFunctions = /(useStatic|shallowSsrRef|ssrPromise|ssrRef|reqSsrRef|useAsync)/;
684
- const KeyPlugin = createUnplugin(() => {
685
- return {
686
- name: "nuxt-legacy-capi-key-transform",
687
- enforce: "pre",
688
- transformInclude(id) {
689
- const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
690
- const query = parseQuery(search);
691
- if (id.includes("node_modules")) {
692
- return false;
693
- }
694
- if (pathname.endsWith(".vue") && (query.type === "script" || !search)) {
695
- return true;
696
- }
697
- if (pathname.match(/\.((c|m)?j|t)sx?/g)) {
698
- return true;
699
- }
700
- },
701
- transform(code, id) {
702
- if (!keyedFunctions.test(code)) {
703
- return null;
704
- }
705
- try {
706
- const { 0: script = code, index: codeIndex = 0 } = code.match(/(?<=<script[^>]*>)[\S\s.]*?(?=<\/script>)/) || [];
707
- const ast = parse(script, { ecmaVersion: 2020, sourceType: "module" });
708
- const s = new MagicString(code);
709
- walk(ast, {
710
- enter(node) {
711
- const { end } = node;
712
- const { callee, arguments: args = [] } = node;
713
- if (callee?.type === "Identifier" || callee?.property?.type === "Identifier") {
714
- let method = "base64";
715
- switch (callee.name || callee.property?.name) {
716
- case "useStatic":
717
- if (args.length > 2) {
718
- return;
719
- }
720
- if (args.length === 2) {
721
- s.prependLeft(codeIndex + end - 1, ", undefined");
722
- }
723
- method = "hex";
724
- break;
725
- case "shallowSsrRef":
726
- case "ssrPromise":
727
- case "ssrRef":
728
- case "reqSsrRef":
729
- case "useAsync":
730
- if (args.length > 1) {
731
- return;
732
- }
733
- break;
734
- default:
735
- return;
736
- }
737
- s.appendLeft(codeIndex + end - 1, ", '" + createKey(`${id}-${end}`, method) + "'");
738
- }
739
- }
740
- });
741
- return s.toString();
742
- } catch {
743
- }
744
- }
745
- };
746
- });
42
+ const storeModules = ${genObjectFromRawEntries(_storeModules.map((m) => [m.id, `$${hash(m.id)}`]))}
747
43
 
748
- function setupCAPIBridge(options) {
749
- const nuxt = useNuxt();
750
- if (nuxt.options.buildModules.find((m) => m === "@nuxtjs/composition-api" || m === "@nuxtjs/composition-api/module")) {
751
- throw new Error("Please remove `@nuxtjs/composition-api` from `buildModules` to avoid conflict with bridge.");
44
+ export function createStore() {
45
+ let store = normalizeRoot(storeModules.root || {})
46
+ delete storeModules.root
47
+ for (const id in storeModules) {
48
+ resolveStoreModules(store, storeModules[id], id)
752
49
  }
753
- const capiPluginPath = resolve(distDir, "runtime/capi.plugin.mjs");
754
- addPluginTemplate({ filename: "capi.plugin.mjs", src: capiPluginPath });
755
- const appPlugin = addPluginTemplate(resolve(distDir, "runtime/app.plugin.mjs"));
756
- nuxt.hook("modules:done", () => {
757
- nuxt.options.plugins.unshift(appPlugin);
758
- });
759
- if (options.legacy === false) {
760
- return;
50
+ if (typeof store === 'function') {
51
+ return store
761
52
  }
762
- nuxt.options.alias["@nuxtjs/composition-api"] = resolve(distDir, "runtime/capi.legacy");
763
- nuxt.options.build.transpile.push("@nuxtjs/composition-api");
764
- addVitePlugin(KeyPlugin.vite());
765
- addWebpackPlugin(KeyPlugin.webpack());
53
+ return new Vuex.Store(Object.assign({
54
+ strict: (process.env.NODE_ENV !== 'production')
55
+ }, store))
766
56
  }
767
57
 
768
- const DEFAULTS = {
769
- fileSystem: new enhancedResolve.CachedInputFileSystem(fs, 4e3),
770
- extensions: [".ts", ".tsx", ".mjs", ".cjs", ".js", ".jsx", ".json", ".vue"]
771
- };
772
- const createResolver = (resolveOptions) => {
773
- const options = defu(resolveOptions, DEFAULTS);
774
- const resolver = enhancedResolve.ResolverFactory.createResolver(options);
775
- const root = options.roots?.[0] || ".";
776
- const promisifiedResolve = promisify(resolver.resolve.bind(resolver));
777
- const resolve = (id, importer) => promisifiedResolve({}, importer || root, id, {});
778
- return { resolve, resolver };
779
- };
780
- class EnhancedResolverPlugin {
781
- constructor(options) {
782
- this.resolver = createResolver(options);
58
+ function normalizeRoot (moduleData, id) {
59
+ moduleData = moduleData.default || moduleData
60
+ if (moduleData.commit) {
61
+ throw new Error(\`[nuxt] \${id} should export a method that returns a Vuex instance.\`)
783
62
  }
784
- apply(defaultResolver) {
785
- const enhancedResolver = this.resolver;
786
- defaultResolver.getHook("resolve").tapPromise("EnhancedResolverPlugin", async (request) => {
787
- const id = request.request;
788
- if (!id || !defaultResolver.isModule(id)) {
789
- return;
790
- }
791
- if (id.includes("@babel/")) {
792
- return;
793
- }
794
- const importer = request.context?.issuer;
795
- try {
796
- const result = await enhancedResolver.resolve(id, importer);
797
- if (!result) {
798
- return;
799
- }
800
- request.path = result;
801
- return request;
802
- } catch {
803
- }
804
- });
63
+ if (typeof moduleData !== 'function') {
64
+ // Avoid TypeError: setting a property that has only a getter when overwriting top level keys
65
+ moduleData = { ...moduleData }
805
66
  }
806
- }
807
- function setupBetterResolve() {
808
- const nuxt = useNuxt();
809
- extendWebpackConfig((config) => {
810
- const isServer = config.name === "server";
811
- config.resolve = config.resolve || {};
812
- config.resolve.plugins = config.resolve.plugins || [];
813
- config.resolve.plugins.push(new EnhancedResolverPlugin({
814
- conditionNames: ["import", ...isServer ? ["node"] : []],
815
- mainFields: ["module", ...isServer ? [] : ["browser"], "main"],
816
- alias: config.resolve.alias,
817
- modules: config.resolve.modules,
818
- plugins: config.resolve.plugins,
819
- roots: config.resolve.roots || [nuxt.options.rootDir]
820
- }));
821
- });
67
+ moduleData.modules = moduleData.modules || {}
68
+ return moduleData
822
69
  }
823
70
 
824
- const TransformPlugin = createUnplugin(({ ctx, options }) => {
825
- return {
826
- name: "nuxt:auto-imports-transform",
827
- enforce: "post",
828
- transformInclude(id) {
829
- const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
830
- const { type, macro } = parseQuery(search);
831
- const exclude = options.transform?.exclude || [/[\\/]node_modules[\\/]/];
832
- if (exclude.some((pattern) => id.match(pattern))) {
833
- return false;
834
- }
835
- if (pathname.endsWith(".vue") && (type === "template" || type === "script" || macro || !search)) {
836
- return true;
837
- }
838
- if (pathname.match(/\.((c|m)?j|t)sx?$/g)) {
839
- return true;
840
- }
841
- },
842
- async transform(_code, id) {
843
- const { code, s } = await ctx.injectImports(_code);
844
- if (code === _code) {
845
- return;
846
- }
847
- return {
848
- code,
849
- map: s.generateMap({ source: id, includeContent: true })
850
- };
851
- }
852
- };
853
- });
71
+ function resolveStoreModules (store, moduleData, id) {
72
+ moduleData = moduleData.default || moduleData
854
73
 
855
- const commonPresets = [
856
- defineUnimportPreset({
857
- from: "#head",
858
- imports: [
859
- "useHead",
860
- "useMeta"
861
- ]
862
- }),
863
- defineUnimportPreset({
864
- from: "#app",
865
- imports: [
866
- "isVue2",
867
- "isVue3"
868
- ]
869
- })
870
- ];
871
- const appPreset = defineUnimportPreset({
872
- from: "#app",
873
- imports: [
874
- "useLazyAsyncData",
875
- "refreshNuxtData",
876
- "defineNuxtComponent",
877
- "useNuxtApp",
878
- "defineNuxtPlugin",
879
- "useRuntimeConfig",
880
- "useState",
881
- "useLazyFetch",
882
- "useCookie",
883
- "useRequestHeaders",
884
- "useRequestEvent",
885
- "useRouter",
886
- "useRoute",
887
- "defineNuxtRouteMiddleware",
888
- "navigateTo",
889
- "abortNavigation",
890
- "addRouteMiddleware",
891
- "useNuxt2Meta"
892
- ]
893
- });
894
- const vueKeys = [
895
- "onActivated",
896
- "onBeforeMount",
897
- "onBeforeUnmount",
898
- "onBeforeUpdate",
899
- "onDeactivated",
900
- "onErrorCaptured",
901
- "onMounted",
902
- "onRenderTracked",
903
- "onRenderTriggered",
904
- "onServerPrefetch",
905
- "onUnmounted",
906
- "onUpdated",
907
- "computed",
908
- "customRef",
909
- "isProxy",
910
- "isReactive",
911
- "isReadonly",
912
- "isRef",
913
- "markRaw",
914
- "proxyRefs",
915
- "reactive",
916
- "readonly",
917
- "ref",
918
- "shallowReactive",
919
- "shallowReadonly",
920
- "shallowRef",
921
- "toRaw",
922
- "toRef",
923
- "toRefs",
924
- "triggerRef",
925
- "unref",
926
- "watch",
927
- "watchEffect",
928
- "isShallow",
929
- "effectScope",
930
- "getCurrentScope",
931
- "onScopeDispose",
932
- "defineComponent",
933
- "defineAsyncComponent",
934
- "getCurrentInstance",
935
- "h",
936
- "inject",
937
- "nextTick",
938
- "provide",
939
- "useAttrs",
940
- "useCssModule",
941
- "useCssVars",
942
- "useSlots"
943
- ];
944
- const vuePreset = defineUnimportPreset({
945
- from: "vue",
946
- imports: vueKeys
947
- });
948
- const defaultPresets = [
949
- ...commonPresets,
950
- appPreset,
951
- vuePreset
952
- ];
74
+ const namespaces = id.split('/').filter(Boolean)
75
+ let moduleName = namespaces[namespaces.length - 1]
953
76
 
954
- async function scanForComposables(dir, ctx) {
955
- const performScan = async (entry) => {
956
- const files = await resolveFiles(entry, [
957
- "*.{ts,js,mjs,cjs,mts,cts}",
958
- "*/index.{ts,js,mjs,cjs,mts,cts}"
959
- ]);
960
- await ctx.modifyDynamicImports(async (dynamicImports) => {
961
- await Promise.all(files.map(async (path) => {
962
- filterInPlace(dynamicImports, (i) => i.from !== path);
963
- const code = await promises.readFile(path, "utf-8");
964
- const exports = findExports(code);
965
- const defaultExport = exports.find((i) => i.type === "default");
966
- if (defaultExport) {
967
- let name = parse$1(path).name;
968
- if (name === "index") {
969
- name = parse$1(path.split("/").slice(0, -1).join("/")).name;
970
- }
971
- dynamicImports.push({ name: "default", as: camelCase(name), from: path });
972
- }
973
- for (const exp of exports) {
974
- if (exp.type === "named") {
975
- for (const name of exp.names) {
976
- dynamicImports.push({ name, as: name, from: path });
977
- }
978
- } else if (exp.type === "declaration") {
979
- dynamicImports.push({ name: exp.name, as: exp.name, from: path });
980
- }
981
- }
982
- }));
983
- });
984
- };
985
- for (const entry of Array.isArray(dir) ? dir : [dir]) {
986
- if (!existsSync(entry)) {
987
- continue;
988
- }
989
- await performScan(entry);
77
+ // If src is a known Vuex property
78
+ if (VUEX_PROPERTIES.includes(moduleName)) {
79
+ const property = moduleName
80
+ const propertyStoreModule = getStoreModule(store, namespaces, { isProperty: true })
81
+ // Replace state since it's a function
82
+ mergeProperty(propertyStoreModule, moduleData, property)
83
+ return
990
84
  }
991
- }
992
- function filterInPlace(arr, predicate) {
993
- let i = arr.length;
994
- while (i--) {
995
- if (!predicate(arr[i])) {
996
- arr.splice(i, 1);
997
- }
998
- }
999
- }
1000
85
 
1001
- const autoImports = defineNuxtModule({
1002
- meta: {
1003
- name: "auto-imports",
1004
- configKey: "autoImports"
1005
- },
1006
- defaults: {
1007
- presets: defaultPresets,
1008
- global: false,
1009
- imports: [],
1010
- dirs: [],
1011
- transform: {
1012
- exclude: void 0
1013
- }
1014
- },
1015
- async setup(options, nuxt) {
1016
- await nuxt.callHook("autoImports:sources", options.presets);
1017
- options.presets.forEach((i) => {
1018
- if (typeof i !== "string" && i.names && !i.imports) {
1019
- i.imports = i.names;
1020
- logger.warn("auto-imports: presets.names is deprecated, use presets.imports instead");
1021
- }
1022
- });
1023
- const ctx = createUnimport({
1024
- presets: options.presets,
1025
- imports: options.imports
1026
- });
1027
- let composablesDirs = [];
1028
- for (const layer of nuxt.options._layers) {
1029
- composablesDirs.push(resolve(layer.config.srcDir, "composables"));
1030
- for (const dir of layer.config.autoImports?.dirs ?? []) {
1031
- composablesDirs.push(resolve(layer.config.srcDir, dir));
1032
- }
1033
- }
1034
- await nuxt.callHook("autoImports:dirs", composablesDirs);
1035
- composablesDirs = composablesDirs.map((dir) => normalize(dir));
1036
- addTemplate({
1037
- filename: "imports.mjs",
1038
- getContents: () => ctx.toExports()
1039
- });
1040
- nuxt.options.alias["#imports"] = join$1(nuxt.options.buildDir, "imports");
1041
- if (nuxt.options.dev && options.global) {
1042
- addPluginTemplate({
1043
- filename: "auto-imports.mjs",
1044
- getContents: () => {
1045
- const imports = ctx.getImports();
1046
- const importStatement = toImports(imports);
1047
- const globalThisSet = imports.map((i) => `globalThis.${i.as} = ${i.as};`).join("\n");
1048
- return `${importStatement}
86
+ const storeModule = getStoreModule(store, namespaces)
1049
87
 
1050
- ${globalThisSet}
88
+ for (const property of VUEX_PROPERTIES) {
89
+ mergeProperty(storeModule, moduleData[property], property)
90
+ }
1051
91
 
1052
- export default () => {};`;
1053
- }
1054
- });
1055
- } else {
1056
- addVitePlugin(TransformPlugin.vite({ ctx, options }));
1057
- addWebpackPlugin(TransformPlugin.webpack({ ctx, options }));
1058
- }
1059
- const regenerateAutoImports = async () => {
1060
- await scanForComposables(composablesDirs, ctx);
1061
- await ctx.modifyDynamicImports(async (imports) => {
1062
- await nuxt.callHook("autoImports:extend", imports);
1063
- });
1064
- };
1065
- await regenerateAutoImports();
1066
- addDeclarationTemplates(ctx);
1067
- nuxt.hook("prepare:types", ({ references }) => {
1068
- references.push({ path: resolve(nuxt.options.buildDir, "types/auto-imports.d.ts") });
1069
- references.push({ path: resolve(nuxt.options.buildDir, "imports.d.ts") });
1070
- });
1071
- nuxt.hook("builder:watch", async (_, path) => {
1072
- const _resolved = resolve(nuxt.options.srcDir, path);
1073
- if (composablesDirs.find((dir) => _resolved.startsWith(dir))) {
1074
- await nuxt.callHook("builder:generateApp");
1075
- }
1076
- });
1077
- nuxt.hook("builder:generateApp", async () => {
1078
- await regenerateAutoImports();
1079
- });
92
+ if (moduleData.namespaced === false) {
93
+ delete storeModule.namespaced
1080
94
  }
1081
- });
1082
- function addDeclarationTemplates(ctx) {
1083
- const nuxt = useNuxt();
1084
- const stripExtension = (path) => path.replace(/\.[a-z]+$/, "");
1085
- const resolved = {};
1086
- const r = ({ from }) => {
1087
- if (resolved[from]) {
1088
- return resolved[from];
1089
- }
1090
- let path = resolveAlias(from);
1091
- if (isAbsolute(path)) {
1092
- path = relative(join$1(nuxt.options.buildDir, "types"), path);
1093
- }
1094
- path = stripExtension(path);
1095
- resolved[from] = path;
1096
- return path;
1097
- };
1098
- addTemplate({
1099
- filename: "imports.d.ts",
1100
- getContents: () => ctx.toExports()
1101
- });
1102
- addTemplate({
1103
- filename: "types/auto-imports.d.ts",
1104
- getContents: () => "// Generated by auto imports\n" + ctx.generateTypeDeclarations({ resolvePath: r })
1105
- });
1106
95
  }
1107
96
 
1108
- const extensions = ["ts", "tsx", "cts", "mts"];
1109
- const typescriptRE = /\.[cm]?tsx?$/;
1110
- function setupTypescript() {
1111
- const nuxt = useNuxt();
1112
- nuxt.options.extensions.push(...extensions);
1113
- nuxt.options.build.additionalExtensions.push(...extensions);
1114
- nuxt.options.build.babel.plugins = nuxt.options.build.babel.plugins || [];
1115
- if (nuxt.options.buildModules.includes("@nuxt/typescript-build")) {
1116
- throw new Error("Please remove `@nuxt/typescript-build` from `buildModules` or set `bridge.typescript: false` to avoid conflict with bridge.");
97
+
98
+ function getStoreModule (storeModule, namespaces, { isProperty = false } = {}) {
99
+ // If ./mutations.js
100
+ if (!namespaces.length || (isProperty && namespaces.length === 1)) {
101
+ return storeModule
1117
102
  }
1118
- const _require = createRequire(import.meta.url);
1119
- nuxt.options.build.babel.plugins.unshift(_require.resolve("@babel/plugin-proposal-optional-chaining"), _require.resolve("@babel/plugin-proposal-nullish-coalescing-operator"), _require.resolve("@babel/plugin-transform-typescript"));
1120
- extendWebpackConfig((config) => {
1121
- config.resolve.extensions.push(...extensions.map((e) => `.${e}`));
1122
- const babelRule = config.module.rules.find((rule) => rule.test?.test("test.js"));
1123
- config.module.rules.unshift({
1124
- ...babelRule,
1125
- test: typescriptRE
1126
- });
1127
- });
103
+
104
+ const namespace = namespaces.shift()
105
+
106
+ storeModule.modules[namespace] = storeModule.modules[namespace] || {}
107
+ storeModule.modules[namespace].namespaced = true
108
+ storeModule.modules[namespace].modules = storeModule.modules[namespace].modules || {}
109
+
110
+ return getStoreModule(storeModule.modules[namespace], namespaces, { isProperty })
1128
111
  }
1129
112
 
1130
- const metaModule = defineNuxtModule({
1131
- meta: {
1132
- name: "meta"
1133
- },
1134
- defaults: {
1135
- charset: "utf-8",
1136
- viewport: "width=device-width, initial-scale=1"
1137
- },
1138
- setup(options, nuxt) {
1139
- const runtimeDir = nuxt.options.alias["#head"] || resolve(distDir, "head/runtime");
1140
- nuxt.options.build.transpile.push("@vueuse/head");
1141
- nuxt.options.alias["#head"] = runtimeDir;
1142
- const globalMeta = defu(nuxt.options.app.head, {
1143
- charset: options.charset,
1144
- viewport: options.viewport
1145
- });
1146
- addTemplate({
1147
- filename: "meta.config.mjs",
1148
- getContents: () => "export default " + JSON.stringify({ globalMeta, mixinKey: "setup" })
1149
- });
1150
- if (!tryResolveModule("@vueuse/head")) {
1151
- console.warn("[bridge] Could not find `@vueuse/head`. You may need to install it.");
1152
- }
1153
- addPlugin({ src: resolve(runtimeDir, "plugin") });
1154
- addPlugin({ src: resolve(runtimeDir, "vueuse-head.plugin") });
113
+ function mergeProperty (storeModule, moduleData, property) {
114
+ if (!moduleData) {
115
+ return
1155
116
  }
1156
- });
1157
-
1158
- const checkDocsMsg = "Please see https://v3.nuxtjs.org for more information.";
1159
- const msgPrefix = "[bridge] [meta]";
1160
- const setupMeta = async (opts) => {
1161
- const nuxt = useNuxt();
1162
- if (opts.needsExplicitEnable) {
1163
- const metaPath = addTemplate({
1164
- filename: "meta.mjs",
1165
- getContents: () => ["useHead", "useMeta"].map((fnName) => `export const ${fnName} = () => console.warn('${msgPrefix} To enable experimental \`useHead\` support, set \`bridge.meta\` to \`true\` in your \`nuxt.config\`. ${checkDocsMsg}')`).join("\n")
1166
- });
1167
- nuxt.options.alias["#head"] = metaPath.dst;
1168
- return;
117
+ if (property === 'state') {
118
+ storeModule.state = moduleData || storeModule.state
119
+ } else {
120
+ storeModule[property] = { ...storeModule[property], ...moduleData }
1169
121
  }
1170
- if (nuxt.options.head && typeof nuxt.options.head === "function") {
1171
- throw new TypeError(`${msgPrefix} The head() function in \`nuxt.config\` has been deprecated and in Nuxt 3 will need to be moved to \`app.vue\`. ${checkDocsMsg}`);
122
+ }`;
1172
123
  }
1173
- const runtimeDir = resolve(distDir, "runtime/head");
1174
- nuxt.options.alias["#head"] = runtimeDir;
1175
- await installModule(metaModule);
1176
124
  };
1177
-
1178
- const setupTranspile = () => {
1179
- const nuxt = useNuxt();
1180
- nuxt.hook("modules:done", () => {
1181
- const modules = [
1182
- "@nuxt/bridge-edge",
1183
- ...nuxt.options.buildModules,
1184
- ...nuxt.options.modules,
1185
- ...nuxt.options._modules
1186
- ].map((m) => typeof m === "string" ? m : Array.isArray(m) ? m[0] : m.src).filter((m) => typeof m === "string").map((m) => m.split(/node_modules[\\/]/g).pop());
1187
- nuxt.options.build.transpile = nuxt.options.build.transpile.map((m) => typeof m === "string" ? m.split(/node_modules[\\/]/g).pop() : m);
1188
- function isTranspilePresent(mod) {
1189
- return nuxt.options.build.transpile.some((t) => !(t instanceof Function) && (t instanceof RegExp ? t.test(mod) : new RegExp(t).test(mod)));
1190
- }
1191
- for (const module of modules) {
1192
- if (!isTranspilePresent(module)) {
1193
- nuxt.options.build.transpile.push(module);
1194
- }
1195
- }
1196
- });
125
+ const clientConfigTemplate = {
126
+ filename: "nitro.client.mjs",
127
+ getContents: () => `
128
+ export const useRuntimeConfig = () => window?.__NUXT__?.config || {}
129
+ `
130
+ };
131
+ const publicPathTemplate = {
132
+ filename: "paths.mjs",
133
+ getContents({ nuxt }) {
134
+ return [
135
+ "import { joinURL } from 'ufo'",
136
+ !nuxt.options.dev && "import { useRuntimeConfig } from '#internal/nitro'",
137
+ nuxt.options.dev ? `const appConfig = ${JSON.stringify(nuxt.options.app)}` : "const appConfig = useRuntimeConfig().app",
138
+ "export const baseURL = () => appConfig.baseURL",
139
+ "export const buildAssetsDir = () => appConfig.buildAssetsDir",
140
+ "export const buildAssetsURL = (...path) => joinURL(publicAssetsURL(), buildAssetsDir(), ...path)",
141
+ "export const publicAssetsURL = (...path) => {",
142
+ " const publicBase = appConfig.cdnURL || appConfig.baseURL",
143
+ " return path.length ? joinURL(publicBase, ...path) : publicBase",
144
+ "}"
145
+ ].filter(Boolean).join("\n");
146
+ }
1197
147
  };
1198
148
 
1199
149
  const module = defineNuxtModule({
1200
150
  meta: {
1201
- name: "nuxt-bridge",
1202
- configKey: "bridge"
151
+ name: "nuxt-bridge:vite",
152
+ configKey: "vite"
1203
153
  },
1204
- defaults: {
1205
- nitro: true,
1206
- nitroGenerator: true,
1207
- vite: false,
1208
- app: {},
1209
- capi: {},
1210
- transpile: true,
1211
- autoImports: true,
1212
- compatibility: true,
1213
- meta: null,
1214
- postcss8: true,
1215
- typescript: true,
1216
- resolve: true
1217
- },
1218
- async setup(opts, nuxt) {
1219
- if (nuxt.options.bridge === false) {
1220
- return;
1221
- }
1222
- if (!nuxt.options.bridge._version) {
1223
- throw new Error("[bridge] Bridge must be enabled by using `defineNuxtConfig` to wrap your Nuxt configuration.");
1224
- }
1225
- if (opts.nitro) {
1226
- nuxt.hook("modules:done", async () => {
1227
- await setupNitroBridge();
1228
- });
1229
- }
1230
- if (opts.app) {
1231
- await setupAppBridge(opts.app);
1232
- }
1233
- if (opts.capi) {
1234
- if (!opts.app) {
1235
- throw new Error("[bridge] Cannot enable composition-api with app disabled!");
154
+ defaults: {},
155
+ setup(viteOptions, nuxt) {
156
+ nuxt.options.cli.badgeMessages.push(`\u26A1 Vite Mode Enabled (v${version})`);
157
+ if (viteOptions.experimentWarning !== false && !nuxt.options.test) {
158
+ logger.log(
159
+ "\u{1F9EA} Vite mode is experimental and some nuxt modules might be incompatible\n",
160
+ " If you find a bug, please report via https://github.com/nuxt/bridge/issues with a minimal reproduction."
161
+ );
162
+ }
163
+ nuxt.options.build.loadingScreen = false;
164
+ nuxt.options.build.indicator = false;
165
+ nuxt.options._modules = nuxt.options._modules.filter((m) => !(Array.isArray(m) && m[0] === "@nuxt/loading-screen"));
166
+ const getModuleName = (m) => {
167
+ if (Array.isArray(m)) {
168
+ m = m[0];
169
+ }
170
+ return m.meta ? m.meta.name : m;
171
+ };
172
+ const filterModule = (modules) => modules.filter((m) => getModuleName(m) !== "nuxt-bridge:vite");
173
+ nuxt.options.modules = filterModule(nuxt.options.modules);
174
+ nuxt.options.buildModules = filterModule(nuxt.options.buildModules);
175
+ if (nuxt.options.store) {
176
+ addPluginTemplate(storeTemplate);
177
+ }
178
+ addPluginTemplate(middlewareTemplate);
179
+ addTemplate(clientConfigTemplate);
180
+ addTemplate({
181
+ ...publicPathTemplate,
182
+ options: { nuxt }
183
+ });
184
+ nuxt.hook("builder:prepared", async (builder) => {
185
+ if (nuxt.options._prepare) {
186
+ return;
1236
187
  }
1237
- await setupCAPIBridge(opts.capi === true ? {} : opts.capi);
1238
- }
1239
- if (opts.autoImports) {
1240
- nuxt.hook("modules:done", () => installModule(autoImports));
1241
- }
1242
- if (opts.vite) {
1243
- const viteModule = await import('./module2.mjs').then((r) => r.default || r);
1244
- nuxt.hook("modules:done", () => installModule(viteModule));
1245
- } else {
1246
- nuxt.options.build.transpile.push("vue");
1247
- }
1248
- if (opts.postcss8) {
1249
- const _require = createRequire(import.meta.url);
1250
- await installModule(_require.resolve("@nuxt/postcss8"));
1251
- }
1252
- if (opts.typescript) {
1253
- await setupTypescript();
1254
- }
1255
- if (opts.resolve) {
1256
- setupBetterResolve();
1257
- }
1258
- if (opts.transpile) {
1259
- setupTranspile();
1260
- }
1261
- if (opts.compatibility) {
1262
- nuxt.hook("modules:done", async (moduleContainer) => {
1263
- for (const [name, m] of Object.entries(moduleContainer.requiredModules || {})) {
1264
- const compat = m?.handler?.meta?.compatibility || {};
1265
- if (compat) {
1266
- const issues = await checkNuxtCompatibility(compat, nuxt);
1267
- if (issues.length) {
1268
- console.warn(`[bridge] Detected module incompatibility issues for \`${name}\`:
1269
- ` + issues.toString());
1270
- }
1271
- }
1272
- }
188
+ builder.bundleBuilder.close();
189
+ delete builder.bundleBuilder;
190
+ const { ViteBuilder } = await import('./vite.mjs');
191
+ builder.bundleBuilder = new ViteBuilder(builder);
192
+ });
193
+ nuxt.hook("build:templates", (templates) => {
194
+ const templatesFiles = templates.templatesFiles.filter((template) => {
195
+ return !["store.js", "middleware.js"].includes(template.dst);
1273
196
  });
1274
- }
1275
- if (opts.meta !== false && opts.capi) {
1276
- await setupMeta({ needsExplicitEnable: opts.meta === null });
1277
- }
197
+ templates.templatesFiles.length = 0;
198
+ templates.templatesFiles.push(...templatesFiles);
199
+ });
1278
200
  }
1279
201
  });
1280
202
 
1281
- export { distDir as d, module as m };
203
+ export { module as default };