vike 0.4.226 → 0.4.227

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.
@@ -62,14 +62,19 @@ async function cmdDev() {
62
62
  const startTime = performance.now();
63
63
  try {
64
64
  const { viteServer } = await (0, index_js_1.dev)();
65
- await viteServer.listen();
66
- const info = viteServer.config.logger.info;
67
- const startupDurationString = picocolors_1.default.dim(`ready in ${picocolors_1.default.reset(picocolors_1.default.bold(String(Math.ceil(performance.now() - startTime))))} ms`);
68
- const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
69
- info(` ${picocolors_1.default.yellow(`${picocolors_1.default.bold('Vike')} v${utils_js_1.PROJECT_VERSION}`)} ${startupDurationString}\n`, {
70
- clear: !hasExistingLogs
71
- });
72
- viteServer.printUrls();
65
+ if (viteServer.httpServer) {
66
+ await viteServer.listen();
67
+ const info = viteServer.config.logger.info;
68
+ const startupDurationString = picocolors_1.default.dim(`ready in ${picocolors_1.default.reset(picocolors_1.default.bold(String(Math.ceil(performance.now() - startTime))))} ms`);
69
+ const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
70
+ info(` ${picocolors_1.default.yellow(`${picocolors_1.default.bold('Vike')} v${utils_js_1.PROJECT_VERSION}`)} ${startupDurationString}\n`, {
71
+ clear: !hasExistingLogs
72
+ });
73
+ viteServer.printUrls();
74
+ }
75
+ else {
76
+ // vike-server => middleware mode => `viteServer.httpServer === null`
77
+ }
73
78
  viteServer.bindCLIShortcuts({ print: true });
74
79
  }
75
80
  catch (err) {
@@ -95,7 +95,7 @@ async function triggerFullBuild(config, vikeConfig, viteEnv, bundle) {
95
95
  // The server bulid is already called by builder.buildApp()
96
96
  }
97
97
  if ((0, context_js_1.isPrerenderAutoRunEnabled)(vikeConfig)) {
98
- const res = await (0, runPrerender_js_1.runPrerenderFromAutoRun)(configInline, config);
98
+ const res = await (0, runPrerender_js_1.runPrerenderFromAutoRun)(configInline);
99
99
  forceExit = res.forceExit;
100
100
  }
101
101
  }
@@ -19,6 +19,8 @@ const context_js_2 = require("../../prerender/context.js");
19
19
  const resolvePrerenderConfig_js_1 = require("../../prerender/resolvePrerenderConfig.js");
20
20
  const pluginName = 'vike:commonConfig';
21
21
  function commonConfig(vikeVitePluginOptions) {
22
+ // We cache it => makes sure we only generate one object => we can mutate it at runPrerender()
23
+ let prerenderContext;
22
24
  return [
23
25
  {
24
26
  name: `${pluginName}:pre`,
@@ -31,6 +33,15 @@ function commonConfig(vikeVitePluginOptions) {
31
33
  const root = configFromUser.root ? (0, prepareViteApiCall_js_1.normalizeViteRoot)(configFromUser.root) : await (0, prepareViteApiCall_js_1.getViteRoot)(operation);
32
34
  (0, utils_js_1.assert)(root);
33
35
  const vikeConfig = await (0, getVikeConfig_js_1.getVikeConfig2)(root, isDev, vikeVitePluginOptions);
36
+ const { isPrerenderingEnabled, isPrerenderingEnabledForAllPages } = (0, resolvePrerenderConfig_js_1.resolvePrerenderConfigGlobal)(vikeConfig);
37
+ prerenderContext ?? (prerenderContext = {
38
+ isPrerenderingEnabled,
39
+ isPrerenderingEnabledForAllPages,
40
+ output: null,
41
+ pageContexts: null
42
+ });
43
+ (0, utils_js_1.assert)(prerenderContext.isPrerenderingEnabled === isPrerenderingEnabled);
44
+ (0, utils_js_1.assert)(prerenderContext.isPrerenderingEnabledForAllPages === isPrerenderingEnabledForAllPages);
34
45
  return {
35
46
  _isDev: isDev,
36
47
  _root: root,
@@ -38,11 +49,12 @@ function commonConfig(vikeVitePluginOptions) {
38
49
  _vikeConfigObject: vikeConfig,
39
50
  _vike: {
40
51
  pages: vikeConfig.pages,
41
- config: vikeConfig.global.config
52
+ config: vikeConfig.global.config,
53
+ prerenderContext
42
54
  },
43
55
  // TODO/v1-release: remove https://github.com/vikejs/vike/issues/2122
44
56
  configVikePromise: Promise.resolve({
45
- prerender: (0, resolvePrerenderConfig_js_1.resolvePrerenderConfigGlobal)(vikeConfig).isPrerenderingEnabled
57
+ prerender: isPrerenderingEnabled
46
58
  })
47
59
  };
48
60
  }
@@ -12,6 +12,7 @@ const getFilePath_js_1 = require("../shared/getFilePath.js");
12
12
  const rollupSourceMap_js_1 = require("../shared/rollupSourceMap.js");
13
13
  const parseEsModule_js_1 = require("../shared/parseEsModule.js");
14
14
  const normalizeId_js_1 = require("../shared/normalizeId.js");
15
+ const getVikeConfig_js_1 = require("./importUserCode/v1-design/getVikeConfig.js");
15
16
  function fileEnv() {
16
17
  let config;
17
18
  let viteDevServer;
@@ -21,6 +22,8 @@ function fileEnv() {
21
22
  // In build, we use generateBundle() instead of the load() hook. Using load() works for dynamic imports in dev thanks to Vite's lazy transpiling, but it doesn't work in build because Rollup transpiles any dynamically imported module even if it's never actually imported.
22
23
  if (!viteDevServer)
23
24
  return;
25
+ if (!(0, getVikeConfig_js_1.isV1Design)(config))
26
+ return;
24
27
  if (skip(id))
25
28
  return;
26
29
  // For `.vue` files: https://github.com/vikejs/vike/issues/1912#issuecomment-2394981475
@@ -38,20 +38,24 @@ function previewConfig() {
38
38
  config.appType = 'mpa'
39
39
  */
40
40
  return () => {
41
- assertDist();
41
+ const prerenderConfigGlobal = (0, resolvePrerenderConfig_js_1.resolvePrerenderConfigGlobal)(config._vikeConfigObject);
42
+ const { isPrerenderingEnabledForAllPages, isPrerenderingEnabled } = prerenderConfigGlobal;
43
+ assertDist(isPrerenderingEnabledForAllPages);
42
44
  // We cannot re-use Vite's static middleware: https://github.com/vitejs/vite/pull/14836#issuecomment-1788540300
43
45
  addStaticAssetsMiddleware(server.middlewares);
44
- const prerenderConfigGlobal = (0, resolvePrerenderConfig_js_1.resolvePrerenderConfigGlobal)(config._vikeConfigObject);
45
- if (!prerenderConfigGlobal.isPrerenderingEnabledForAllPages) {
46
- (0, addSsrMiddleware_js_1.addSsrMiddleware)(server.middlewares, config, true, prerenderConfigGlobal.isPrerenderingEnabled);
46
+ if (!isPrerenderingEnabledForAllPages) {
47
+ (0, addSsrMiddleware_js_1.addSsrMiddleware)(server.middlewares, config, true, isPrerenderingEnabled);
47
48
  }
48
49
  addStatic404Middleware(server.middlewares);
49
50
  };
50
51
  }
51
52
  };
52
- function assertDist() {
53
+ function assertDist(isPrerenderingEnabledForAllPages) {
53
54
  const { outDirRoot, outDirClient, outDirServer } = (0, getOutDirs_js_1.getOutDirs)(config);
54
- [outDirRoot, outDirClient, outDirServer].forEach((outDirAny) => {
55
+ const dirS = [outDirRoot, outDirClient];
56
+ if (!isPrerenderingEnabledForAllPages)
57
+ dirS.push(outDirServer);
58
+ dirS.forEach((outDirAny) => {
55
59
  (0, utils_js_1.assertUsage)(fs_1.default.existsSync(outDirAny), `Cannot run ${picocolors_1.default.cyan('$ vike preview')}: your app isn't built (the build directory ${picocolors_1.default.cyan(outDirAny)} is missing). Make sure to run ${picocolors_1.default.cyan('$ vike build')} before running ${picocolors_1.default.cyan('$ vike preview')}.`);
56
60
  });
57
61
  }
@@ -12,6 +12,7 @@ function resolvePrerenderConfigGlobal(vikeConfig) {
12
12
  const prerenderConfigGlobal = {
13
13
  partial: pickFirst(prerenderSettings.map((c) => c.partial)) ?? false,
14
14
  noExtraDir: pickFirst(prerenderSettings.map((c) => c.noExtraDir)) ?? false,
15
+ keepDistServer: pickFirst(prerenderSettings.map((c) => c.keepDistServer)) ?? false,
15
16
  parallel: pickFirst(prerenderSettings.map((c) => c.parallel)) ?? true,
16
17
  disableAutoRun: pickFirst(prerenderSettings.map((c) => c.disableAutoRun)) ?? false
17
18
  };
@@ -69,6 +69,7 @@ const getOutDirs_js_1 = require("../plugin/shared/getOutDirs.js");
69
69
  const context_js_2 = require("../cli/context.js");
70
70
  const isViteCliCall_js_1 = require("../plugin/shared/isViteCliCall.js");
71
71
  const commonConfig_js_1 = require("../plugin/plugins/commonConfig.js");
72
+ const node_fs_1 = __importDefault(require("node:fs"));
72
73
  async function runPrerenderFromAPI(options = {}) {
73
74
  return await runPrerender(options, 'prerender()');
74
75
  // - We purposely propagate the error to the user land, so that the error interrupts the user land. It's also, I guess, a nice-to-have that the user has control over the error.
@@ -88,11 +89,9 @@ async function runPrerenderFromCLIPrerenderCommand() {
88
89
  runPrerender_forceExit();
89
90
  (0, utils_js_1.assert)(false);
90
91
  }
91
- async function runPrerenderFromAutoRun(viteConfig, config) {
92
- let prerenderContextPublic;
92
+ async function runPrerenderFromAutoRun(viteConfig) {
93
93
  try {
94
- const ret = await runPrerender({ viteConfig });
95
- prerenderContextPublic = ret.prerenderContextPublic;
94
+ await runPrerender({ viteConfig });
96
95
  }
97
96
  catch (err) {
98
97
  // Avoid Rollup prefixing the error with [vike:build:pluginAutoFullBuild], see for example https://github.com/vikejs/vike/issues/472#issuecomment-1276274203
@@ -100,8 +99,6 @@ async function runPrerenderFromAutoRun(viteConfig, config) {
100
99
  (0, logErrorHint_js_1.logErrorHint)(err);
101
100
  process.exit(1);
102
101
  }
103
- const vike = (0, commonConfig_js_1.getVikeConfigPublic)(config);
104
- vike.prerenderContext = prerenderContextPublic;
105
102
  const forceExit = (0, context_js_2.isVikeCli)() || (0, isViteCliCall_js_1.isViteCliCall)();
106
103
  return { forceExit };
107
104
  }
@@ -118,7 +115,9 @@ async function runPrerender(options = {}, standaloneTrigger) {
118
115
  await disableReactStreaming();
119
116
  const viteConfig = await (0, vite_1.resolveConfig)(options.viteConfig || {}, 'build', 'production');
120
117
  const vikeConfig = await (0, getVikeConfig_js_1.getVikeConfig)(viteConfig);
121
- const { outDirClient } = (0, getOutDirs_js_1.getOutDirs)(viteConfig);
118
+ const vike = (0, commonConfig_js_1.getVikeConfigPublic)(viteConfig);
119
+ (0, utils_js_1.assert)(vike.prerenderContext.isPrerenderingEnabled);
120
+ const { outDirClient, outDirServer } = (0, getOutDirs_js_1.getOutDirs)(viteConfig);
122
121
  const { root } = viteConfig;
123
122
  const prerenderConfigGlobal = (0, resolvePrerenderConfig_js_1.resolvePrerenderConfigGlobal)(vikeConfig);
124
123
  validatePrerenderConfig(prerenderConfigGlobal);
@@ -161,7 +160,11 @@ async function runPrerender(options = {}, standaloneTrigger) {
161
160
  }
162
161
  await warnMissingPages(prerenderContext.prerenderedPageContexts, globalContext, doNotPrerenderList, partial);
163
162
  const prerenderContextPublic = makePublic(prerenderContext);
164
- return { viteConfig, prerenderContextPublic };
163
+ (0, utils_js_1.objectAssign)(vike.prerenderContext, prerenderContextPublic);
164
+ if (prerenderConfigGlobal.isPrerenderingEnabledForAllPages && !prerenderConfigGlobal.keepDistServer) {
165
+ node_fs_1.default.rmSync(outDirServer, { recursive: true });
166
+ }
167
+ return { viteConfig };
165
168
  }
166
169
  async function collectDoNoPrerenderList(pageConfigs, doNotPrerenderList, defaultLocalValue, concurrencyLimit, globalContext) {
167
170
  // V1 design
@@ -630,6 +633,12 @@ async function write(urlOriginal, pageContext, fileType, fileContent, root, outD
630
633
  (0, utils_js_1.assertPosixPath)(outDirClient);
631
634
  (0, utils_js_1.assertPosixPath)(filePathRelative);
632
635
  const filePath = path_1.default.posix.join(outDirClient, filePathRelative);
636
+ (0, utils_js_1.objectAssign)(pageContext, {
637
+ _prerenderResult: {
638
+ filePath,
639
+ fileContent
640
+ }
641
+ });
633
642
  output.push({
634
643
  filePath,
635
644
  fileType,
@@ -637,15 +646,7 @@ async function write(urlOriginal, pageContext, fileType, fileContent, root, outD
637
646
  pageContext
638
647
  });
639
648
  if (onPagePrerender) {
640
- const prerenderPageContext = {};
641
- (0, utils_js_1.objectAssign)(prerenderPageContext, pageContext);
642
- (0, utils_js_1.objectAssign)(prerenderPageContext, {
643
- _prerenderResult: {
644
- filePath,
645
- fileContent
646
- }
647
- });
648
- await onPagePrerender(prerenderPageContext);
649
+ await onPagePrerender(pageContext);
649
650
  }
650
651
  else {
651
652
  const { promises } = await Promise.resolve().then(() => __importStar(require('fs')));
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PROJECT_VERSION = void 0;
4
4
  // Automatically updated by @brillout/release-me
5
- exports.PROJECT_VERSION = '0.4.226';
5
+ exports.PROJECT_VERSION = '0.4.227';
@@ -16,13 +16,24 @@ const PROJECT_VERSION_js_1 = require("./PROJECT_VERSION.js");
16
16
  /* Use original assertWarning() after all CJS is removed from node_modules/vike/dist/
17
17
  import { assertWarning } from './assert.js'
18
18
  */
19
- const globalObject = (0, getGlobalObject_js_1.getGlobalObject)('utils/assertSingleInstance.ts', {
20
- instances: [],
21
- alreadyLogged: new Set()
22
- });
19
+ let globalObject;
20
+ // getGlobalObjectSafe() can be called before this line
21
+ globalObject ?? (globalObject = genGlobalConfig());
22
+ function genGlobalConfig() {
23
+ return (0, getGlobalObject_js_1.getGlobalObject)('utils/assertSingleInstance.ts', {
24
+ instances: [],
25
+ alreadyLogged: new Set()
26
+ });
27
+ }
28
+ // We need getGlobalObjectSafe() because globalObject is `undefined` when exported functions are called before globalObject is initialized
29
+ function getGlobalObjectSafe() {
30
+ globalObject ?? (globalObject = genGlobalConfig());
31
+ return globalObject;
32
+ }
23
33
  const clientRuntimesClonflict = 'Client runtime of both Server Routing and Client Routing loaded https://vike.dev/client-runtimes-conflict';
24
34
  const clientNotSingleInstance = 'Client runtime loaded twice https://vike.dev/client-runtime-duplicated';
25
35
  function assertSingleInstance() {
36
+ const globalObject = getGlobalObjectSafe();
26
37
  {
27
38
  const versions = (0, unique_js_1.unique)(globalObject.instances);
28
39
  assertWarning(versions.length <= 1,
@@ -39,6 +50,7 @@ function assertSingleInstance() {
39
50
  }
40
51
  }
41
52
  function assertSingleInstance_onClientEntryServerRouting(isProduction) {
53
+ const globalObject = getGlobalObjectSafe();
42
54
  assertWarning(globalObject.isClientRouting !== true, clientRuntimesClonflict, {
43
55
  onlyOnce: true,
44
56
  showStackTrace: true
@@ -53,6 +65,7 @@ function assertSingleInstance_onClientEntryServerRouting(isProduction) {
53
65
  assertSingleInstance();
54
66
  }
55
67
  function assertSingleInstance_onClientEntryClientRouting(isProduction) {
68
+ const globalObject = getGlobalObjectSafe();
56
69
  assertWarning(globalObject.isClientRouting !== false, clientRuntimesClonflict, {
57
70
  onlyOnce: true,
58
71
  showStackTrace: true
@@ -68,10 +81,12 @@ function assertSingleInstance_onClientEntryClientRouting(isProduction) {
68
81
  }
69
82
  // Called by utils/assert.ts which is (most certainly) loaded by all entries. That way we don't have to call a callback for every entry. (There are a lot of entries: `client/router/`, `client/`, `node/runtime/`, `node/plugin/`, `node/cli`.)
70
83
  function assertSingleInstance_onAssertModuleLoad() {
84
+ const globalObject = getGlobalObjectSafe();
71
85
  globalObject.instances.push(PROJECT_VERSION_js_1.PROJECT_VERSION);
72
86
  assertSingleInstance();
73
87
  }
74
88
  function assertWarning(condition, errorMessage, { onlyOnce, showStackTrace }) {
89
+ const globalObject = getGlobalObjectSafe();
75
90
  if (condition) {
76
91
  return;
77
92
  }
@@ -24,14 +24,19 @@ async function cmdDev() {
24
24
  const startTime = performance.now();
25
25
  try {
26
26
  const { viteServer } = await dev();
27
- await viteServer.listen();
28
- const info = viteServer.config.logger.info;
29
- const startupDurationString = pc.dim(`ready in ${pc.reset(pc.bold(String(Math.ceil(performance.now() - startTime))))} ms`);
30
- const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
31
- info(` ${pc.yellow(`${pc.bold('Vike')} v${PROJECT_VERSION}`)} ${startupDurationString}\n`, {
32
- clear: !hasExistingLogs
33
- });
34
- viteServer.printUrls();
27
+ if (viteServer.httpServer) {
28
+ await viteServer.listen();
29
+ const info = viteServer.config.logger.info;
30
+ const startupDurationString = pc.dim(`ready in ${pc.reset(pc.bold(String(Math.ceil(performance.now() - startTime))))} ms`);
31
+ const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
32
+ info(` ${pc.yellow(`${pc.bold('Vike')} v${PROJECT_VERSION}`)} ${startupDurationString}\n`, {
33
+ clear: !hasExistingLogs
34
+ });
35
+ viteServer.printUrls();
36
+ }
37
+ else {
38
+ // vike-server => middleware mode => `viteServer.httpServer === null`
39
+ }
35
40
  viteServer.bindCLIShortcuts({ print: true });
36
41
  }
37
42
  catch (err) {
@@ -90,7 +90,7 @@ async function triggerFullBuild(config, vikeConfig, viteEnv, bundle) {
90
90
  // The server bulid is already called by builder.buildApp()
91
91
  }
92
92
  if (isPrerenderAutoRunEnabled(vikeConfig)) {
93
- const res = await runPrerenderFromAutoRun(configInline, config);
93
+ const res = await runPrerenderFromAutoRun(configInline);
94
94
  forceExit = res.forceExit;
95
95
  }
96
96
  }
@@ -20,8 +20,14 @@ declare module 'vite' {
20
20
  type VikeConfigPublic = {
21
21
  config: VikeConfigObject['global']['config'];
22
22
  pages: VikeConfigObject['pages'];
23
- prerenderContext?: PrerenderContextPublic;
23
+ prerenderContext: PrerenderContext;
24
24
  };
25
+ type PrerenderContext = {
26
+ isPrerenderingEnabled: boolean;
27
+ isPrerenderingEnabledForAllPages: boolean;
28
+ } & ({
29
+ [K in keyof PrerenderContextPublic]: null;
30
+ } | PrerenderContextPublic);
25
31
  declare function commonConfig(vikeVitePluginOptions: unknown): Plugin[];
26
32
  /**
27
33
  * Get all the information Vike knows about the app in your Vite plugin.
@@ -14,6 +14,8 @@ import { temp_disablePrerenderAutoRun } from '../../prerender/context.js';
14
14
  import { resolvePrerenderConfigGlobal } from '../../prerender/resolvePrerenderConfig.js';
15
15
  const pluginName = 'vike:commonConfig';
16
16
  function commonConfig(vikeVitePluginOptions) {
17
+ // We cache it => makes sure we only generate one object => we can mutate it at runPrerender()
18
+ let prerenderContext;
17
19
  return [
18
20
  {
19
21
  name: `${pluginName}:pre`,
@@ -26,6 +28,15 @@ function commonConfig(vikeVitePluginOptions) {
26
28
  const root = configFromUser.root ? normalizeViteRoot(configFromUser.root) : await getViteRoot(operation);
27
29
  assert(root);
28
30
  const vikeConfig = await getVikeConfig2(root, isDev, vikeVitePluginOptions);
31
+ const { isPrerenderingEnabled, isPrerenderingEnabledForAllPages } = resolvePrerenderConfigGlobal(vikeConfig);
32
+ prerenderContext ?? (prerenderContext = {
33
+ isPrerenderingEnabled,
34
+ isPrerenderingEnabledForAllPages,
35
+ output: null,
36
+ pageContexts: null
37
+ });
38
+ assert(prerenderContext.isPrerenderingEnabled === isPrerenderingEnabled);
39
+ assert(prerenderContext.isPrerenderingEnabledForAllPages === isPrerenderingEnabledForAllPages);
29
40
  return {
30
41
  _isDev: isDev,
31
42
  _root: root,
@@ -33,11 +44,12 @@ function commonConfig(vikeVitePluginOptions) {
33
44
  _vikeConfigObject: vikeConfig,
34
45
  _vike: {
35
46
  pages: vikeConfig.pages,
36
- config: vikeConfig.global.config
47
+ config: vikeConfig.global.config,
48
+ prerenderContext
37
49
  },
38
50
  // TODO/v1-release: remove https://github.com/vikejs/vike/issues/2122
39
51
  configVikePromise: Promise.resolve({
40
- prerender: resolvePrerenderConfigGlobal(vikeConfig).isPrerenderingEnabled
52
+ prerender: isPrerenderingEnabled
41
53
  })
42
54
  };
43
55
  }
@@ -7,6 +7,7 @@ import { getModuleFilePathAbsolute } from '../shared/getFilePath.js';
7
7
  import { sourceMapRemove } from '../shared/rollupSourceMap.js';
8
8
  import { getExportNames } from '../shared/parseEsModule.js';
9
9
  import { normalizeId } from '../shared/normalizeId.js';
10
+ import { isV1Design } from './importUserCode/v1-design/getVikeConfig.js';
10
11
  function fileEnv() {
11
12
  let config;
12
13
  let viteDevServer;
@@ -16,6 +17,8 @@ function fileEnv() {
16
17
  // In build, we use generateBundle() instead of the load() hook. Using load() works for dynamic imports in dev thanks to Vite's lazy transpiling, but it doesn't work in build because Rollup transpiles any dynamically imported module even if it's never actually imported.
17
18
  if (!viteDevServer)
18
19
  return;
20
+ if (!isV1Design(config))
21
+ return;
19
22
  if (skip(id))
20
23
  return;
21
24
  // For `.vue` files: https://github.com/vikejs/vike/issues/1912#issuecomment-2394981475
@@ -33,20 +33,24 @@ function previewConfig() {
33
33
  config.appType = 'mpa'
34
34
  */
35
35
  return () => {
36
- assertDist();
36
+ const prerenderConfigGlobal = resolvePrerenderConfigGlobal(config._vikeConfigObject);
37
+ const { isPrerenderingEnabledForAllPages, isPrerenderingEnabled } = prerenderConfigGlobal;
38
+ assertDist(isPrerenderingEnabledForAllPages);
37
39
  // We cannot re-use Vite's static middleware: https://github.com/vitejs/vite/pull/14836#issuecomment-1788540300
38
40
  addStaticAssetsMiddleware(server.middlewares);
39
- const prerenderConfigGlobal = resolvePrerenderConfigGlobal(config._vikeConfigObject);
40
- if (!prerenderConfigGlobal.isPrerenderingEnabledForAllPages) {
41
- addSsrMiddleware(server.middlewares, config, true, prerenderConfigGlobal.isPrerenderingEnabled);
41
+ if (!isPrerenderingEnabledForAllPages) {
42
+ addSsrMiddleware(server.middlewares, config, true, isPrerenderingEnabled);
42
43
  }
43
44
  addStatic404Middleware(server.middlewares);
44
45
  };
45
46
  }
46
47
  };
47
- function assertDist() {
48
+ function assertDist(isPrerenderingEnabledForAllPages) {
48
49
  const { outDirRoot, outDirClient, outDirServer } = getOutDirs(config);
49
- [outDirRoot, outDirClient, outDirServer].forEach((outDirAny) => {
50
+ const dirS = [outDirRoot, outDirClient];
51
+ if (!isPrerenderingEnabledForAllPages)
52
+ dirS.push(outDirServer);
53
+ dirS.forEach((outDirAny) => {
50
54
  assertUsage(fs.existsSync(outDirAny), `Cannot run ${pc.cyan('$ vike preview')}: your app isn't built (the build directory ${pc.cyan(outDirAny)} is missing). Make sure to run ${pc.cyan('$ vike build')} before running ${pc.cyan('$ vike preview')}.`);
51
55
  });
52
56
  }
@@ -5,6 +5,7 @@ import type { PageConfigBuildTime } from '../../shared/page-configs/PageConfig.j
5
5
  declare function resolvePrerenderConfigGlobal(vikeConfig: VikeConfigObject): {
6
6
  partial: boolean;
7
7
  noExtraDir: boolean;
8
+ keepDistServer: boolean;
8
9
  parallel: number | boolean;
9
10
  disableAutoRun: boolean;
10
11
  } & {
@@ -10,6 +10,7 @@ function resolvePrerenderConfigGlobal(vikeConfig) {
10
10
  const prerenderConfigGlobal = {
11
11
  partial: pickFirst(prerenderSettings.map((c) => c.partial)) ?? false,
12
12
  noExtraDir: pickFirst(prerenderSettings.map((c) => c.noExtraDir)) ?? false,
13
+ keepDistServer: pickFirst(prerenderSettings.map((c) => c.keepDistServer)) ?? false,
13
14
  parallel: pickFirst(prerenderSettings.map((c) => c.parallel)) ?? true,
14
15
  disableAutoRun: pickFirst(prerenderSettings.map((c) => c.disableAutoRun)) ?? false
15
16
  };
@@ -46,7 +46,7 @@ declare function runPrerenderFromAPI(options?: PrerenderOptions): Promise<{
46
46
  viteConfig: ResolvedConfig;
47
47
  }>;
48
48
  declare function runPrerenderFromCLIPrerenderCommand(): Promise<void>;
49
- declare function runPrerenderFromAutoRun(viteConfig: InlineConfig | undefined, config: ResolvedConfig): Promise<{
49
+ declare function runPrerenderFromAutoRun(viteConfig: InlineConfig | undefined): Promise<{
50
50
  forceExit: boolean;
51
51
  }>;
52
52
  declare function runPrerender_forceExit(): void;
@@ -31,6 +31,7 @@ import { getOutDirs } from '../plugin/shared/getOutDirs.js';
31
31
  import { isVikeCli } from '../cli/context.js';
32
32
  import { isViteCliCall } from '../plugin/shared/isViteCliCall.js';
33
33
  import { getVikeConfigPublic } from '../plugin/plugins/commonConfig.js';
34
+ import fs from 'node:fs';
34
35
  async function runPrerenderFromAPI(options = {}) {
35
36
  return await runPrerender(options, 'prerender()');
36
37
  // - We purposely propagate the error to the user land, so that the error interrupts the user land. It's also, I guess, a nice-to-have that the user has control over the error.
@@ -50,11 +51,9 @@ async function runPrerenderFromCLIPrerenderCommand() {
50
51
  runPrerender_forceExit();
51
52
  assert(false);
52
53
  }
53
- async function runPrerenderFromAutoRun(viteConfig, config) {
54
- let prerenderContextPublic;
54
+ async function runPrerenderFromAutoRun(viteConfig) {
55
55
  try {
56
- const ret = await runPrerender({ viteConfig });
57
- prerenderContextPublic = ret.prerenderContextPublic;
56
+ await runPrerender({ viteConfig });
58
57
  }
59
58
  catch (err) {
60
59
  // Avoid Rollup prefixing the error with [vike:build:pluginAutoFullBuild], see for example https://github.com/vikejs/vike/issues/472#issuecomment-1276274203
@@ -62,8 +61,6 @@ async function runPrerenderFromAutoRun(viteConfig, config) {
62
61
  logErrorHint(err);
63
62
  process.exit(1);
64
63
  }
65
- const vike = getVikeConfigPublic(config);
66
- vike.prerenderContext = prerenderContextPublic;
67
64
  const forceExit = isVikeCli() || isViteCliCall();
68
65
  return { forceExit };
69
66
  }
@@ -80,7 +77,9 @@ async function runPrerender(options = {}, standaloneTrigger) {
80
77
  await disableReactStreaming();
81
78
  const viteConfig = await resolveConfig(options.viteConfig || {}, 'build', 'production');
82
79
  const vikeConfig = await getVikeConfig(viteConfig);
83
- const { outDirClient } = getOutDirs(viteConfig);
80
+ const vike = getVikeConfigPublic(viteConfig);
81
+ assert(vike.prerenderContext.isPrerenderingEnabled);
82
+ const { outDirClient, outDirServer } = getOutDirs(viteConfig);
84
83
  const { root } = viteConfig;
85
84
  const prerenderConfigGlobal = resolvePrerenderConfigGlobal(vikeConfig);
86
85
  validatePrerenderConfig(prerenderConfigGlobal);
@@ -123,7 +122,11 @@ async function runPrerender(options = {}, standaloneTrigger) {
123
122
  }
124
123
  await warnMissingPages(prerenderContext.prerenderedPageContexts, globalContext, doNotPrerenderList, partial);
125
124
  const prerenderContextPublic = makePublic(prerenderContext);
126
- return { viteConfig, prerenderContextPublic };
125
+ objectAssign(vike.prerenderContext, prerenderContextPublic);
126
+ if (prerenderConfigGlobal.isPrerenderingEnabledForAllPages && !prerenderConfigGlobal.keepDistServer) {
127
+ fs.rmSync(outDirServer, { recursive: true });
128
+ }
129
+ return { viteConfig };
127
130
  }
128
131
  async function collectDoNoPrerenderList(pageConfigs, doNotPrerenderList, defaultLocalValue, concurrencyLimit, globalContext) {
129
132
  // V1 design
@@ -592,6 +595,12 @@ async function write(urlOriginal, pageContext, fileType, fileContent, root, outD
592
595
  assertPosixPath(outDirClient);
593
596
  assertPosixPath(filePathRelative);
594
597
  const filePath = path.posix.join(outDirClient, filePathRelative);
598
+ objectAssign(pageContext, {
599
+ _prerenderResult: {
600
+ filePath,
601
+ fileContent
602
+ }
603
+ });
595
604
  output.push({
596
605
  filePath,
597
606
  fileType,
@@ -599,15 +608,7 @@ async function write(urlOriginal, pageContext, fileType, fileContent, root, outD
599
608
  pageContext
600
609
  });
601
610
  if (onPagePrerender) {
602
- const prerenderPageContext = {};
603
- objectAssign(prerenderPageContext, pageContext);
604
- objectAssign(prerenderPageContext, {
605
- _prerenderResult: {
606
- filePath,
607
- fileContent
608
- }
609
- });
610
- await onPagePrerender(prerenderPageContext);
611
+ await onPagePrerender(pageContext);
611
612
  }
612
613
  else {
613
614
  const { promises } = await import('fs');
@@ -308,6 +308,16 @@ type ConfigBuiltIn = {
308
308
  * @default true
309
309
  */
310
310
  enable?: boolean | null;
311
+ /**
312
+ * If you pre-render all your pages then Vike removes the `dist/server/` directory after pre-rendering has finished.
313
+ *
314
+ * If you set this setting to `true` then Vike won't remove the `dist/server/` directory.
315
+ *
316
+ * https://vike.dev/prerender#keepDistServer
317
+ *
318
+ * @default false
319
+ */
320
+ keepDistServer?: boolean;
311
321
  };
312
322
  /**
313
323
  * Install Vike extensions.
@@ -1 +1 @@
1
- export declare const PROJECT_VERSION: "0.4.226";
1
+ export declare const PROJECT_VERSION: "0.4.227";
@@ -1,2 +1,2 @@
1
1
  // Automatically updated by @brillout/release-me
2
- export const PROJECT_VERSION = '0.4.226';
2
+ export const PROJECT_VERSION = '0.4.227';
@@ -11,13 +11,24 @@ import { PROJECT_VERSION } from './PROJECT_VERSION.js';
11
11
  /* Use original assertWarning() after all CJS is removed from node_modules/vike/dist/
12
12
  import { assertWarning } from './assert.js'
13
13
  */
14
- const globalObject = getGlobalObject('utils/assertSingleInstance.ts', {
15
- instances: [],
16
- alreadyLogged: new Set()
17
- });
14
+ let globalObject;
15
+ // getGlobalObjectSafe() can be called before this line
16
+ globalObject ?? (globalObject = genGlobalConfig());
17
+ function genGlobalConfig() {
18
+ return getGlobalObject('utils/assertSingleInstance.ts', {
19
+ instances: [],
20
+ alreadyLogged: new Set()
21
+ });
22
+ }
23
+ // We need getGlobalObjectSafe() because globalObject is `undefined` when exported functions are called before globalObject is initialized
24
+ function getGlobalObjectSafe() {
25
+ globalObject ?? (globalObject = genGlobalConfig());
26
+ return globalObject;
27
+ }
18
28
  const clientRuntimesClonflict = 'Client runtime of both Server Routing and Client Routing loaded https://vike.dev/client-runtimes-conflict';
19
29
  const clientNotSingleInstance = 'Client runtime loaded twice https://vike.dev/client-runtime-duplicated';
20
30
  function assertSingleInstance() {
31
+ const globalObject = getGlobalObjectSafe();
21
32
  {
22
33
  const versions = unique(globalObject.instances);
23
34
  assertWarning(versions.length <= 1,
@@ -34,6 +45,7 @@ function assertSingleInstance() {
34
45
  }
35
46
  }
36
47
  function assertSingleInstance_onClientEntryServerRouting(isProduction) {
48
+ const globalObject = getGlobalObjectSafe();
37
49
  assertWarning(globalObject.isClientRouting !== true, clientRuntimesClonflict, {
38
50
  onlyOnce: true,
39
51
  showStackTrace: true
@@ -48,6 +60,7 @@ function assertSingleInstance_onClientEntryServerRouting(isProduction) {
48
60
  assertSingleInstance();
49
61
  }
50
62
  function assertSingleInstance_onClientEntryClientRouting(isProduction) {
63
+ const globalObject = getGlobalObjectSafe();
51
64
  assertWarning(globalObject.isClientRouting !== false, clientRuntimesClonflict, {
52
65
  onlyOnce: true,
53
66
  showStackTrace: true
@@ -63,10 +76,12 @@ function assertSingleInstance_onClientEntryClientRouting(isProduction) {
63
76
  }
64
77
  // Called by utils/assert.ts which is (most certainly) loaded by all entries. That way we don't have to call a callback for every entry. (There are a lot of entries: `client/router/`, `client/`, `node/runtime/`, `node/plugin/`, `node/cli`.)
65
78
  function assertSingleInstance_onAssertModuleLoad() {
79
+ const globalObject = getGlobalObjectSafe();
66
80
  globalObject.instances.push(PROJECT_VERSION);
67
81
  assertSingleInstance();
68
82
  }
69
83
  function assertWarning(condition, errorMessage, { onlyOnce, showStackTrace }) {
84
+ const globalObject = getGlobalObjectSafe();
70
85
  if (condition) {
71
86
  return;
72
87
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vike",
3
- "version": "0.4.226",
3
+ "version": "0.4.227",
4
4
  "repository": "https://github.com/vikejs/vike",
5
5
  "exports": {
6
6
  "./server": {