vike 0.4.227 → 0.4.228

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 (86) hide show
  1. package/dist/cjs/node/api/dev.js +2 -0
  2. package/dist/cjs/node/plugin/plugins/build/pluginBuildConfig.js +3 -5
  3. package/dist/cjs/node/plugin/plugins/build/pluginBuildEntry.js +5 -7
  4. package/dist/cjs/node/plugin/plugins/build/pluginModuleBanner.js +13 -21
  5. package/dist/cjs/node/plugin/plugins/devConfig/determineFsAllowList.js +8 -9
  6. package/dist/cjs/node/plugin/plugins/envVars.js +22 -13
  7. package/dist/cjs/node/plugin/plugins/extractAssetsPlugin.js +1 -2
  8. package/dist/cjs/node/plugin/plugins/extractExportNamesPlugin.js +1 -2
  9. package/dist/cjs/node/plugin/plugins/fileEnv.js +1 -2
  10. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolvePointerImport.js +1 -3
  11. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.js +25 -19
  12. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +1 -1
  13. package/dist/cjs/node/plugin/plugins/setGlobalContext.js +3 -4
  14. package/dist/cjs/node/plugin/shared/getViteConfigRuntime.js +21 -0
  15. package/dist/cjs/node/plugin/shared/resolveClientEntriesDev.js +11 -12
  16. package/dist/cjs/node/plugin/utils.js +1 -0
  17. package/dist/cjs/node/prerender/resolvePrerenderConfig.js +1 -1
  18. package/dist/cjs/node/prerender/runPrerender.js +157 -196
  19. package/dist/cjs/node/prerender/utils.js +1 -1
  20. package/dist/cjs/node/runtime/globalContext.js +52 -27
  21. package/dist/cjs/node/runtime/html/stream.js +2 -4
  22. package/dist/cjs/node/runtime/index-common.js +2 -1
  23. package/dist/cjs/node/runtime/renderPage/renderPageAlreadyRouted.js +0 -23
  24. package/dist/cjs/node/runtime-dev/createDevMiddleware.js +1 -1
  25. package/dist/cjs/shared/route/executeOnBeforeRouteHook.js +1 -1
  26. package/dist/cjs/shared/route/index.js +13 -11
  27. package/dist/cjs/utils/PROJECT_VERSION.js +1 -1
  28. package/dist/cjs/utils/assert.js +2 -5
  29. package/dist/cjs/utils/findPackageJson.js +2 -2
  30. package/dist/cjs/utils/isFilePathAbsoluteFilesystem.js +1 -1
  31. package/dist/cjs/utils/isNpmPackage.js +1 -1
  32. package/dist/cjs/utils/isScriptFile.js +4 -4
  33. package/dist/cjs/utils/parseUrl.js +4 -4
  34. package/dist/cjs/utils/preservePropertyGetters.js +30 -0
  35. package/dist/cjs/utils/requireResolve.js +60 -16
  36. package/dist/cjs/{node/plugin/shared → utils}/rollupSourceMap.js +4 -4
  37. package/dist/esm/node/api/dev.js +2 -0
  38. package/dist/esm/node/plugin/plugins/build/pluginBuildConfig.js +2 -4
  39. package/dist/esm/node/plugin/plugins/build/pluginBuildEntry.js +4 -6
  40. package/dist/esm/node/plugin/plugins/build/pluginModuleBanner.js +11 -22
  41. package/dist/esm/node/plugin/plugins/devConfig/determineFsAllowList.js +7 -8
  42. package/dist/esm/node/plugin/plugins/envVars.js +19 -13
  43. package/dist/esm/node/plugin/plugins/extractAssetsPlugin.js +2 -3
  44. package/dist/esm/node/plugin/plugins/extractExportNamesPlugin.js +2 -3
  45. package/dist/esm/node/plugin/plugins/fileEnv.js +2 -3
  46. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolvePointerImport.js +2 -4
  47. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.js +26 -20
  48. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +1 -1
  49. package/dist/esm/node/plugin/plugins/setGlobalContext.js +4 -5
  50. package/dist/esm/node/plugin/shared/getViteConfigRuntime.d.ts +14 -0
  51. package/dist/esm/node/plugin/shared/getViteConfigRuntime.js +19 -0
  52. package/dist/esm/node/plugin/shared/resolveClientEntriesDev.js +10 -11
  53. package/dist/esm/node/plugin/utils.d.ts +1 -0
  54. package/dist/esm/node/plugin/utils.js +1 -0
  55. package/dist/esm/node/prerender/resolvePrerenderConfig.d.ts +1 -1
  56. package/dist/esm/node/prerender/resolvePrerenderConfig.js +1 -1
  57. package/dist/esm/node/prerender/runPrerender.d.ts +1 -0
  58. package/dist/esm/node/prerender/runPrerender.js +160 -199
  59. package/dist/esm/node/prerender/utils.d.ts +1 -1
  60. package/dist/esm/node/prerender/utils.js +1 -1
  61. package/dist/esm/node/runtime/globalContext.d.ts +26 -17
  62. package/dist/esm/node/runtime/globalContext.js +52 -27
  63. package/dist/esm/node/runtime/html/stream.js +2 -4
  64. package/dist/esm/node/runtime/index-common.d.ts +1 -1
  65. package/dist/esm/node/runtime/index-common.js +1 -1
  66. package/dist/esm/node/runtime/renderPage/renderPageAlreadyRouted.d.ts +9 -197
  67. package/dist/esm/node/runtime/renderPage/renderPageAlreadyRouted.js +0 -23
  68. package/dist/esm/node/runtime-dev/createDevMiddleware.js +1 -1
  69. package/dist/esm/shared/route/executeOnBeforeRouteHook.js +1 -1
  70. package/dist/esm/shared/route/index.d.ts +1 -1
  71. package/dist/esm/shared/route/index.js +13 -11
  72. package/dist/esm/shared/types.d.ts +1 -3
  73. package/dist/esm/utils/PROJECT_VERSION.d.ts +1 -1
  74. package/dist/esm/utils/PROJECT_VERSION.js +1 -1
  75. package/dist/esm/utils/assert.js +2 -5
  76. package/dist/esm/utils/isFilePathAbsoluteFilesystem.js +1 -1
  77. package/dist/esm/utils/isNpmPackage.js +1 -1
  78. package/dist/esm/utils/isScriptFile.js +4 -4
  79. package/dist/esm/utils/parseUrl.js +4 -4
  80. package/dist/esm/utils/preservePropertyGetters.d.ts +2 -0
  81. package/dist/esm/utils/preservePropertyGetters.js +28 -0
  82. package/dist/esm/utils/requireResolve.d.ts +7 -1
  83. package/dist/esm/utils/requireResolve.js +54 -13
  84. package/dist/esm/{node/plugin/shared → utils}/rollupSourceMap.d.ts +4 -4
  85. package/dist/esm/{node/plugin/shared → utils}/rollupSourceMap.js +4 -4
  86. package/package.json +3 -2
@@ -2,16 +2,15 @@ export { pluginBuildEntry };
2
2
  export { set_macro_ASSETS_MANIFEST };
3
3
  import { serverProductionEntryPlugin } from '@brillout/vite-plugin-server-entry/plugin';
4
4
  import { virtualFileIdImportUserCodeServer } from '../../../shared/virtual-files/virtualFileImportUserCode.js';
5
- import { assert, PROJECT_VERSION, toPosixPath } from '../../utils.js';
5
+ import { assert, PROJECT_VERSION, requireResolveNonUserFile } from '../../utils.js';
6
6
  import fs from 'fs/promises';
7
7
  import path from 'path';
8
- import { createRequire } from 'module';
9
8
  // @ts-ignore import.meta.url is shimmed at dist/cjs by dist-cjs-fixup.js.
10
9
  const importMetaUrl = import.meta.url;
11
- const require_ = createRequire(importMetaUrl);
12
10
  import { isUsingClientRouter } from '../extractExportNamesPlugin.js';
13
- import { assertBuildInfo, getViteConfigRuntime } from '../../../runtime/globalContext.js';
11
+ import { assertBuildInfo } from '../../../runtime/globalContext.js';
14
12
  import { getOutDirs } from '../../shared/getOutDirs.js';
13
+ import { getViteConfigRuntime } from '../../shared/getViteConfigRuntime.js';
15
14
  const ASSETS_MANIFEST = '__VITE_ASSETS_MANIFEST__';
16
15
  function pluginBuildEntry() {
17
16
  let config;
@@ -87,9 +86,8 @@ function find_ASSETS_MANIFEST(bundle) {
87
86
  }
88
87
  function getImportPath(config) {
89
88
  // We resolve filePathAbsolute even if we don't use it: we use require.resolve() as an assertion that the relative path is correct
90
- const filePathAbsolute = toPosixPath(
91
89
  // [RELATIVE_PATH_FROM_DIST] Current file: node_modules/vike/dist/esm/node/plugin/plugins/pluginBuildEntry/index.js
92
- require_.resolve(`../../../../../../dist/esm/__internal/index.js`));
90
+ const filePathAbsolute = requireResolveNonUserFile(`../../../../../../dist/esm/__internal/index.js`, importMetaUrl);
93
91
  if (
94
92
  // Let's implement a new config if a user needs the import to be a relative path instead of 'vike/__internal' (AFAIK a relative path is needed only if a framework has npm package 'vike' as direct dependency instead of a peer dependency and if the user of that framework uses pnpm)
95
93
  true) {
@@ -1,10 +1,9 @@
1
1
  export { pluginModuleBanner };
2
- import { assert } from '../../utils.js';
2
+ import MagicString from 'magic-string';
3
3
  import { removeVirtualIdTag } from '../../../shared/virtual-files.js';
4
- import { isViteServerBuild, isViteServerBuild_safe } from '../../shared/isViteServerBuild.js';
4
+ import { isViteServerBuild_safe } from '../../shared/isViteServerBuild.js';
5
5
  // Rollup's banner feature doesn't work with Vite: https://github.com/vitejs/vite/issues/8412
6
6
  // But, anyways, we want to prepend the banner at the beginning of each module, not at the beginning of each file (I believe that's what Rollup's banner feature does).
7
- const vikeModuleBannerPlaceholder = 'vikeModuleBannerPlaceholder';
8
7
  function pluginModuleBanner() {
9
8
  let config;
10
9
  return {
@@ -14,24 +13,6 @@ function pluginModuleBanner() {
14
13
  configResolved(config_) {
15
14
  config = config_;
16
15
  },
17
- generateBundle: {
18
- order: 'post',
19
- handler(_options, bundle) {
20
- for (const module of Object.values(bundle)) {
21
- if (module.type === 'chunk') {
22
- if (isViteServerBuild(config)) {
23
- const codeOld = module.code;
24
- const codeNew = codeOld.replace(/vikeModuleBannerPlaceholder\("([^"]*)"\);/g, '/* $1 [vike:pluginModuleBanner] */');
25
- assert(!codeNew.includes(vikeModuleBannerPlaceholder));
26
- module.code = codeNew;
27
- }
28
- else {
29
- assert(!module.code.includes(vikeModuleBannerPlaceholder));
30
- }
31
- }
32
- }
33
- }
34
- },
35
16
  transform: {
36
17
  order: 'post',
37
18
  handler(code, id, options) {
@@ -42,7 +23,15 @@ function pluginModuleBanner() {
42
23
  id = removeVirtualIdTag(id);
43
24
  if (id.startsWith(config.root))
44
25
  id = id.slice(config.root.length + 1);
45
- return `${vikeModuleBannerPlaceholder}(${JSON.stringify(id)}); ${code}`;
26
+ const s = new MagicString(code);
27
+ // Use legal comment so that esbuild doesn't remove it.
28
+ // - Terser still removes the comment, but I guess users use terser to minify JavaScript so I guess it's a good thing that comment is removed.
29
+ // - https://esbuild.github.io/api/#legal-comments
30
+ s.prepend(`/*! ${id} [vike:pluginModuleBanner] */\n`);
31
+ return {
32
+ code: s.toString(),
33
+ map: s.generateMap({ hires: true, source: id })
34
+ };
46
35
  }
47
36
  }
48
37
  };
@@ -1,14 +1,13 @@
1
1
  export { determineFsAllowList };
2
2
  import { searchForWorkspaceRoot } from 'vite';
3
- import path from 'path';
4
- import { assert } from '../../utils.js';
5
- import { createRequire } from 'module';
6
- import { dirname } from 'path';
3
+ import path from 'node:path';
4
+ import { assert, assertPosixPath, requireResolveNonUserFile } from '../../utils.js';
7
5
  import { fileURLToPath } from 'url';
8
6
  // @ts-ignore import.meta.url is shimmed at dist/cjs by dist-cjs-fixup.js.
9
7
  const importMetaUrl = import.meta.url;
10
- const require_ = createRequire(importMetaUrl);
11
- const __dirname_ = dirname(fileURLToPath(importMetaUrl));
8
+ assertPosixPath(importMetaUrl);
9
+ const __dirname_ = path.posix.dirname(fileURLToPath(importMetaUrl));
10
+ assertPosixPath(__dirname_);
12
11
  async function determineFsAllowList(config) {
13
12
  const fsAllow = config.server.fs.allow;
14
13
  // fsAllow should already contain searchForWorkspaceRoot()
@@ -21,9 +20,9 @@ async function determineFsAllowList(config) {
21
20
  // Add node_modules/vike/
22
21
  {
23
22
  // [RELATIVE_PATH_FROM_DIST] Current directory: node_modules/vike/dist/esm/node/plugin/plugins/config/
24
- const vikeRoot = path.join(__dirname_, '../../../../../../');
23
+ const vikeRoot = path.posix.join(__dirname_, '../../../../../../');
25
24
  // Assert that `vikeRoot` is indeed pointing to `node_modules/vike/`
26
- require_.resolve(`${vikeRoot}/dist/esm/node/plugin/plugins/devConfig/index.js`);
25
+ requireResolveNonUserFile(`${vikeRoot}/dist/esm/node/plugin/plugins/devConfig/index.js`, importMetaUrl);
27
26
  fsAllow.push(vikeRoot);
28
27
  }
29
28
  }
@@ -1,7 +1,7 @@
1
1
  export { envVarsPlugin };
2
+ import MagicString from 'magic-string';
2
3
  import { loadEnv } from 'vite';
3
4
  import { assert, assertPosixPath, assertUsage, assertWarning, escapeRegex, isArray, lowerFirst } from '../utils.js';
4
- import { sourceMapPassthrough } from '../shared/rollupSourceMap.js';
5
5
  import { getModuleFilePathAbsolute } from '../shared/getFilePath.js';
6
6
  import { normalizeId } from '../shared/normalizeId.js';
7
7
  import { isViteServerBuild_safe } from '../shared/isViteServerBuild.js';
@@ -10,7 +10,7 @@ import { isViteServerBuild_safe } from '../shared/isViteServerBuild.js';
10
10
  // - For it to work, we'll probably need the user to define the settings (e.g. `envDir`) for loadEnv() inside vike.config.js instead of vite.config.js
11
11
  // - Or stop using Vite's `mode` implemention and have Vike implement its own `mode` feature? (So that the only dependencies are `$ vike build --mode staging` and `$ MODE=staging vike build`.)
12
12
  const PUBLIC_ENV_PREFIX = 'PUBLIC_ENV__';
13
- const PUBLIC_ENV_WHITELIST = [
13
+ const PUBLIC_ENV_ALLOWLIST = [
14
14
  // https://github.com/vikejs/vike/issues/1724
15
15
  'STORYBOOK'
16
16
  ];
@@ -38,6 +38,7 @@ function envVarsPlugin() {
38
38
  return;
39
39
  const isBuild = config.command === 'build';
40
40
  const isClientSide = !isViteServerBuild_safe(config, options);
41
+ const s = new MagicString(code);
41
42
  Object.entries(envsAll)
42
43
  .filter(([key]) => {
43
44
  // Already handled by Vite
@@ -46,12 +47,12 @@ function envVarsPlugin() {
46
47
  })
47
48
  .forEach(([envName, envVal]) => {
48
49
  const envStatement = `import.meta.env.${envName}`;
49
- const envStatementRegEx = new RegExp(escapeRegex(envStatement) + '\\b', 'g');
50
+ const envStatementRegExStr = escapeRegex(envStatement) + '\\b';
50
51
  // Security check
51
52
  {
52
- const isPrivate = !envName.startsWith(PUBLIC_ENV_PREFIX) && !PUBLIC_ENV_WHITELIST.includes(envName);
53
+ const isPrivate = !envName.startsWith(PUBLIC_ENV_PREFIX) && !PUBLIC_ENV_ALLOWLIST.includes(envName);
53
54
  if (isPrivate && isClientSide) {
54
- if (!envStatementRegEx.test(code))
55
+ if (!new RegExp(envStatementRegExStr).test(code))
55
56
  return;
56
57
  const modulePath = getModuleFilePathAbsolute(id, config);
57
58
  const errMsgAddendum = isBuild ? '' : ' (Vike will prevent your app from building for production)';
@@ -70,16 +71,21 @@ function envVarsPlugin() {
70
71
  assert(!(isPrivate && isClientSide) || !isBuild);
71
72
  }
72
73
  // Apply
73
- code = applyEnvVar(envStatementRegEx, envVal, code);
74
+ applyEnvVar(s, envStatementRegExStr, envVal);
74
75
  });
75
- // Line numbers didn't change.
76
- // - We only break the column number of a couple of lines, wich is acceptable.
77
- // - Anyways, I'm not even sure Vite supports high-resolution column number source mapping.
78
- const ret = sourceMapPassthrough(code);
79
- return ret;
76
+ if (!s.hasChanged())
77
+ return null;
78
+ return {
79
+ code: s.toString(),
80
+ map: s.generateMap({ hires: true, source: id })
81
+ };
80
82
  }
81
83
  };
82
84
  }
83
- function applyEnvVar(envStatementRegEx, envVal, code) {
84
- return code.replace(envStatementRegEx, JSON.stringify(envVal));
85
+ function applyEnvVar(s, envStatementRegExStr, envVal) {
86
+ const envStatementRegEx = new RegExp(envStatementRegExStr, 'g');
87
+ let match;
88
+ while ((match = envStatementRegEx.exec(s.original))) {
89
+ s.overwrite(match.index, match.index + match[0].length, JSON.stringify(envVal));
90
+ }
85
91
  }
@@ -6,12 +6,11 @@
6
6
  // - This appraoch supports import path aliases `vite.config.js#resolve.alias` https://vitejs.dev/config/#resolve-alias
7
7
  export { extractAssetsPlugin };
8
8
  export { extractAssetsRE };
9
- import { assert, assertPosixPath, styleFileRE, createDebugger, isScriptFile, assertUsage } from '../utils.js';
9
+ import { assert, assertPosixPath, styleFileRE, createDebugger, isScriptFile, assertUsage, rollupSourceMapRemove } from '../utils.js';
10
10
  import { resolveVirtualFileId, isVirtualFileId, getVirtualFileId } from '../../shared/virtual-files.js';
11
11
  import { extractAssetsAddQuery } from '../../shared/extractAssetsQuery.js';
12
12
  import { isAsset } from '../shared/isAsset.js';
13
13
  import { getImportStatements } from '../shared/parseEsModule.js';
14
- import { sourceMapRemove } from '../shared/rollupSourceMap.js';
15
14
  import pc from '@brillout/picocolors';
16
15
  import { handleAssetsManifest_isFixEnabled } from './build/handleAssetsManifest.js';
17
16
  import { getVikeConfig } from './importUserCode/v1-design/getVikeConfig.js';
@@ -51,7 +50,7 @@ function extractAssetsPlugin() {
51
50
  const moduleNames = getImportedModules(importStatements);
52
51
  const code = moduleNames.map((moduleName) => `import '${moduleName}';`).join('\n');
53
52
  debugTransformResult(id, code, importStatements);
54
- return sourceMapRemove(code);
53
+ return rollupSourceMapRemove(code);
55
54
  }
56
55
  },
57
56
  // This plugin appends `?extractAssets` to module IDs
@@ -1,9 +1,8 @@
1
1
  export { extractExportNamesPlugin };
2
2
  export { isUsingClientRouter };
3
3
  export { extractExportNamesRE };
4
- import { assert, getFileExtension, createDebugger, getGlobalObject, assertUsage } from '../utils.js';
4
+ import { assert, getFileExtension, createDebugger, getGlobalObject, assertUsage, rollupSourceMapRemove } from '../utils.js';
5
5
  import { getExportNames } from '../shared/parseEsModule.js';
6
- import { sourceMapRemove } from '../shared/rollupSourceMap.js';
7
6
  import { normalizeId } from '../shared/normalizeId.js';
8
7
  import { isViteServerBuild_options } from '../shared/isViteServerBuild.js';
9
8
  const extractExportNamesRE = /(\?|&)extractExportNames(?:&|$)/;
@@ -39,7 +38,7 @@ async function getExtractExportNamesCode(src, isClientSide, isProduction, id) {
39
38
  globalObject.usesClientRouter = true;
40
39
  }
41
40
  const code = getCode(exportNames, wildcardReExports, isClientSide, isProduction, id);
42
- return sourceMapRemove(code);
41
+ return rollupSourceMapRemove(code);
43
42
  }
44
43
  function getCode(exportNames, wildcardReExports, isClientSide, isProduction, id) {
45
44
  let code = '';
@@ -1,10 +1,9 @@
1
1
  export { fileEnv };
2
- import { assert, assertUsage, assertWarning, capitalizeFirstLetter, joinEnglish } from '../utils.js';
2
+ import { assert, assertUsage, assertWarning, capitalizeFirstLetter, joinEnglish, rollupSourceMapRemove } from '../utils.js';
3
3
  import { extractAssetsRE } from './extractAssetsPlugin.js';
4
4
  import { extractExportNamesRE } from './extractExportNamesPlugin.js';
5
5
  import pc from '@brillout/picocolors';
6
6
  import { getModuleFilePathAbsolute } from '../shared/getFilePath.js';
7
- import { sourceMapRemove } from '../shared/rollupSourceMap.js';
8
7
  import { getExportNames } from '../shared/parseEsModule.js';
9
8
  import { normalizeId } from '../shared/normalizeId.js';
10
9
  import { isV1Design } from './importUserCode/v1-design/getVikeConfig.js';
@@ -49,7 +48,7 @@ function fileEnv() {
49
48
  const errMsg = getErrorMessage(id, isServerSide, importers, false, true);
50
49
  // We have to inject empty exports to avoid Rollup complaining about missing exports, see https://gist.github.com/brillout/5ea45776e65bd65100a52ecd7bfda3ff
51
50
  const { exportNames } = await getExportNames(code);
52
- return sourceMapRemove([
51
+ return rollupSourceMapRemove([
53
52
  `throw new Error(${JSON.stringify(errMsg)});`,
54
53
  ...exportNames.map((name) => name === 'default' ? 'export default undefined;' : `export const ${name} = undefined;`)
55
54
  ].join('\n'));
@@ -1,7 +1,7 @@
1
1
  export { resolvePointerImport };
2
2
  export { resolvePointerImportData };
3
3
  import pc from '@brillout/picocolors';
4
- import { assert, assertPosixPath, assertUsage, isFilePathAbsolute, pathIsRelative, requireResolve } from '../../../../utils.js';
4
+ import { assert, assertPosixPath, assertUsage, isFilePathAbsolute, pathIsRelative, requireResolveOptional } from '../../../../utils.js';
5
5
  import { parsePointerImportData } from './transformPointerImports.js';
6
6
  import path from 'path';
7
7
  import { getFilePathAbsoluteUserRootDir, getFilePathResolved, getFilePathUnresolved } from '../../../../shared/getFilePath.js';
@@ -72,10 +72,8 @@ function resolveImportPathWithNode(pointerImportData, importerFilePath) {
72
72
  const importerFilePathAbsolute = importerFilePath.filePathAbsoluteFilesystem;
73
73
  assertPosixPath(importerFilePathAbsolute);
74
74
  const cwd = path.posix.dirname(importerFilePathAbsolute);
75
- // We still can't use import.meta.resolve() as of 23.1.0 (November 2024) because `parent` argument requires an experimental flag.
76
- // - https://stackoverflow.com/questions/54977743/do-require-resolve-for-es-modules#comment139581675_62272600
77
75
  // filePathAbsoluteFilesystem is expected to be null when pointerImportData.importPath is a Vite path alias
78
- const filePathAbsoluteFilesystem = requireResolve(pointerImportData.importPath, cwd);
76
+ const filePathAbsoluteFilesystem = requireResolveOptional(pointerImportData.importPath, cwd);
79
77
  return filePathAbsoluteFilesystem;
80
78
  }
81
79
  function assertUsageResolutionSuccess(filePathAbsoluteFilesystem, pointerImportData, importerFilePath) {
@@ -7,14 +7,10 @@ import fs from 'fs';
7
7
  import path from 'path';
8
8
  import pc from '@brillout/picocolors';
9
9
  import { import_ } from '@brillout/import';
10
- import { assertPosixPath, getRandomId, assertIsNotProductionRuntime, assert, assertWarning, isObject, toPosixPath, assertUsage, isPlainJavaScriptFile, createDebugger, assertFilePathAbsoluteFilesystem, assertIsNpmPackageImport, genPromise, isVitest } from '../../../../utils.js';
10
+ import { assertPosixPath, getRandomId, assertIsNotProductionRuntime, assert, assertWarning, isObject, toPosixPath, assertUsage, isPlainJavaScriptFile, createDebugger, assertFilePathAbsoluteFilesystem, assertIsNpmPackageImport, genPromise, isVitest, requireResolveOptional, isNpmPackageImport_unreliable } from '../../../../utils.js';
11
11
  import { transformPointerImports } from './transformPointerImports.js';
12
12
  import sourceMapSupport from 'source-map-support';
13
13
  import { getFilePathAbsoluteUserRootDir } from '../../../../shared/getFilePath.js';
14
- import { createRequire } from 'module';
15
- // @ts-ignore import.meta.url is shimmed at dist/cjs by dist-cjs-fixup.js.
16
- const importMetaUrl = import.meta.url;
17
- const require_ = createRequire(importMetaUrl);
18
14
  assertIsNotProductionRuntime();
19
15
  installSourceMapSupport();
20
16
  const debug = createDebugger('vike:pointer-imports');
@@ -110,8 +106,6 @@ async function transpileWithEsbuild(filePath, userRootDir, transformImports, esb
110
106
  build.onResolve({ filter: /.*/ }, async (args) => {
111
107
  if (args.kind !== 'import-statement')
112
108
  return;
113
- if (debugEsbuildResolve.isActivated)
114
- debugEsbuildResolve('args', args);
115
109
  // Avoid infinite loop: https://github.com/evanw/esbuild/issues/3095#issuecomment-1546916366
116
110
  const useEsbuildResolver = 'useEsbuildResolver';
117
111
  if (args.pluginData?.[useEsbuildResolver])
@@ -119,17 +113,15 @@ async function transpileWithEsbuild(filePath, userRootDir, transformImports, esb
119
113
  const { path, ...opts } = args;
120
114
  opts.pluginData = { [useEsbuildResolver]: true };
121
115
  let resolved = await build.resolve(path, opts);
116
+ if (debugEsbuildResolve.isActivated)
117
+ debugEsbuildResolve('args', args);
122
118
  if (debugEsbuildResolve.isActivated)
123
119
  debugEsbuildResolve('resolved', resolved);
124
120
  // Temporary workaround for https://github.com/evanw/esbuild/issues/3973
125
121
  // - Sitll required for esbuild@0.24.0 (November 2024).
126
122
  // - Let's try to remove this workaround again later.
127
123
  if (resolved.errors.length > 0) {
128
- let resolvedWithNode;
129
- try {
130
- resolvedWithNode = require_.resolve(path, { paths: [args.resolveDir] });
131
- }
132
- catch { }
124
+ const resolvedWithNode = requireResolveOptional(path, args.resolveDir);
133
125
  if (debugEsbuildResolve.isActivated)
134
126
  debugEsbuildResolve('resolvedWithNode', resolvedWithNode);
135
127
  if (resolvedWithNode)
@@ -163,11 +155,25 @@ async function transpileWithEsbuild(filePath, userRootDir, transformImports, esb
163
155
  // - vike@0.4.162 started soft-requiring Vike extensions to set the name config.
164
156
  // - In practice, it seems like it requires some (non-trivial?) refactoring.
165
157
  isVikeExtensionImport;
166
- // Externalize npm package imports
167
158
  assertPosixPath(importPathResolved);
168
- const isNpmPkgImport = importPathResolved.includes('/node_modules/') ||
159
+ // `isNpmPkgImport` => `importPathOriginal` is most likely an npm package import, but it can also be a path alias that a) looks like an npm package import and b) resolves outside of `userRootDir`.
160
+ const isNpmPkgImport = (() => {
161
+ if (importPathResolved.includes('/node_modules/')) {
162
+ // So far I can't think of a use case where this assertion would fail, but let's eventually remove it to avoid artificially restricting the user.
163
+ assert(isNpmPackageImport_unreliable(importPathOriginal));
164
+ return true;
165
+ }
169
166
  // Linked npm packages
170
- !importPathResolved.startsWith(userRootDir);
167
+ if (
168
+ // Assuming path aliases usually resolve inside `userRootDir`.
169
+ // - This isn't always the case: https://github.com/vikejs/vike/issues/2326
170
+ !importPathResolved.startsWith(userRootDir) &&
171
+ // False positive if `importPathOriginal` is a path alias that a) looks like an npm package import and b) resolves outside of `userRootDir` => we then we wrongfully assume that `importPathOriginal` is an npm package import.
172
+ isNpmPackageImport_unreliable(importPathOriginal)) {
173
+ return true;
174
+ }
175
+ return false;
176
+ })();
171
177
  const isExternal = isPointerImport ||
172
178
  // Performance: npm package imports can be externalized. (We could as well let esbuild transpile /node_modules/ code but it's useless as /node_modules/ code is already built. It would unnecessarily slow down transpilation.)
173
179
  isNpmPkgImport;
@@ -191,19 +197,19 @@ async function transpileWithEsbuild(filePath, userRootDir, transformImports, esb
191
197
  filePathAbsoluteFilesystem: importPathResolved,
192
198
  userRootDir
193
199
  });
194
- // We assuming that path aliases always resolve inside `userRootDir`.
195
200
  if (filePathAbsoluteUserRootDir && !isNpmPkgImport) {
196
- // `importPathOriginal` is a path alias.
201
+ // `importPathOriginal` is most likely a path alias.
197
202
  // - We have to use esbuild's path alias resolution, because:
198
203
  // - Vike doesn't resolve path aliases at all.
199
204
  // - Node.js doesn't support `tsconfig.js#compilerOptions.paths`.
200
- // - Esbuild path alias resolution seems to be reliable, e.g. it supports `tsconfig.js#compilerOptions.paths`.
205
+ // - Esbuild path alias resolution seems reliable, e.g. it supports `tsconfig.js#compilerOptions.paths`.
206
+ assert(!isNpmPackageImport_unreliable(importPathOriginal));
201
207
  importPathTranspiled = importPathResolved;
202
208
  }
203
209
  else {
204
- // `importPathOriginal` is an npm package import.
210
+ // `importPathOriginal` is most likely an npm package import.
205
211
  assertIsNpmPackageImport(importPathOriginal);
206
- // For less confusing error messages, let the resolution be handled by Vike or Node.js.
212
+ // For improved error messages, let the resolution be handled by Vike or Node.js.
207
213
  importPathTranspiled = importPathOriginal;
208
214
  }
209
215
  }
@@ -896,7 +896,7 @@ function assertKnownConfig(configName, configNamesKnownRelevant, configDefinitio
896
896
  if (configNamesKnownAll.includes(configName)) {
897
897
  assertUsage(false, `${sourceName} sets the value of the config ${configNameColored} which is a custom config that is defined with ${pc.underline('https://vike.dev/meta')} at a path that doesn't apply to ${locationId} — see ${pc.underline('https://vike.dev/config#inheritance')}`, { exitOnError });
898
898
  }
899
- const errMsg = `${sourceName} sets an unknown config ${configNameColored}`;
899
+ const errMsg = `${sourceName} sets an unknown Vike config, see ${pc.underline('https://vike.dev/cli')} for the list of CLI options.`;
900
900
  // Missing vike-{react,vue,solid} installation
901
901
  {
902
902
  const ui = ['vike-react', 'vike-vue', 'vike-solid'];
@@ -1,8 +1,8 @@
1
1
  export { setGlobalContext };
2
2
  import { setGlobalContext_viteDevServer, setGlobalContext_viteConfig, setGlobalContext_isProduction } from '../../runtime/globalContext.js';
3
- import { assert, assertFilePathAbsoluteFilesystem, isDevCheck, markSetup_isViteDev, markSetup_viteDevServer, markSetup_vitePreviewServer } from '../utils.js';
4
- import { getOutDirs } from '../shared/getOutDirs.js';
3
+ import { assert, isDevCheck, markSetup_isViteDev, markSetup_viteDevServer, markSetup_vitePreviewServer } from '../utils.js';
5
4
  import { reloadVikeConfig } from './importUserCode/v1-design/getVikeConfig.js';
5
+ import { getViteConfigRuntime } from '../shared/getViteConfigRuntime.js';
6
6
  function setGlobalContext() {
7
7
  let isServerReload = false;
8
8
  let config;
@@ -41,9 +41,8 @@ function setGlobalContext() {
41
41
  order: 'post',
42
42
  async handler(config_) {
43
43
  config = config_;
44
- const { outDirRoot } = getOutDirs(config);
45
- assertFilePathAbsoluteFilesystem(outDirRoot); // Needed for `importServerProductionEntry({ outDir })` of @brillout/vite-plugin-server-entry
46
- setGlobalContext_viteConfig(config, outDirRoot);
44
+ const viteConfigRuntime = getViteConfigRuntime(config);
45
+ setGlobalContext_viteConfig(config, viteConfigRuntime);
47
46
  }
48
47
  }
49
48
  }
@@ -0,0 +1,14 @@
1
+ export { getViteConfigRuntime };
2
+ export type { ViteConfigRuntime };
3
+ import type { ResolvedConfig } from 'vite';
4
+ type ViteConfigRuntime = ReturnType<typeof getViteConfigRuntime>;
5
+ declare function getViteConfigRuntime(config: ResolvedConfig): {
6
+ root: string;
7
+ build: {
8
+ outDir: string;
9
+ };
10
+ _baseViteOriginal: string;
11
+ vitePluginServerEntry: {
12
+ inject: boolean | undefined;
13
+ };
14
+ };
@@ -0,0 +1,19 @@
1
+ export { getViteConfigRuntime };
2
+ import { assert, assertFilePathAbsoluteFilesystem, hasProp } from '../utils.js';
3
+ import { getOutDirs } from './getOutDirs.js';
4
+ function getViteConfigRuntime(config) {
5
+ assert(hasProp(config, '_baseViteOriginal', 'string'));
6
+ const { outDirRoot } = getOutDirs(config);
7
+ assertFilePathAbsoluteFilesystem(outDirRoot);
8
+ const viteConfigRuntime = {
9
+ root: config.root,
10
+ build: {
11
+ outDir: outDirRoot
12
+ },
13
+ _baseViteOriginal: config._baseViteOriginal,
14
+ vitePluginServerEntry: {
15
+ inject: config.vitePluginServerEntry?.inject
16
+ }
17
+ };
18
+ return viteConfigRuntime;
19
+ }
@@ -1,9 +1,7 @@
1
1
  export { resolveClientEntriesDev };
2
- import { assert, assertPosixPath, toPosixPath, pathJoin, assertIsNpmPackageImport, assertIsNotProductionRuntime } from '../utils.js';
3
- import { createRequire } from 'module';
2
+ import { assert, assertPosixPath, toPosixPath, pathJoin, assertIsNpmPackageImport, assertIsNotProductionRuntime, requireResolveOptionalNonUserFile, requireResolve } from '../utils.js';
4
3
  // @ts-ignore import.meta.url is shimmed at dist/cjs by dist-cjs-fixup.js.
5
4
  const importMetaUrl = import.meta.url;
6
- const require_ = createRequire(importMetaUrl);
7
5
  assertIsNotProductionRuntime();
8
6
  async function resolveClientEntriesDev(clientEntry, viteDevServer) {
9
7
  let root = viteDevServer.config.root;
@@ -27,20 +25,21 @@ async function resolveClientEntriesDev(clientEntry, viteDevServer) {
27
25
  else {
28
26
  if (clientEntry.startsWith('@@vike/')) {
29
27
  assert(clientEntry.endsWith('.js'));
30
- try {
31
- // For Vitest (which doesn't resolve vike to its dist but to its source files)
32
- // [RELATIVE_PATH_FROM_DIST] Current file: node_modules/vike/node/plugin/shared/resolveClientEntriesDev.js
33
- filePath = toPosixPath(require_.resolve(clientEntry.replace('@@vike/dist/esm/client/', '../../../client/').replace('.js', '.ts')));
34
- }
35
- catch {
28
+ let filePath_;
29
+ // For Vitest (which doesn't resolve vike to its dist but to its source files)
30
+ // [RELATIVE_PATH_FROM_DIST] Current file: node_modules/vike/node/plugin/shared/resolveClientEntriesDev.js
31
+ filePath_ = requireResolveOptionalNonUserFile(clientEntry.replace('@@vike/dist/esm/client/', '../../../client/').replace('.js', '.ts'), importMetaUrl);
32
+ if (!filePath_) {
36
33
  // For users
37
34
  // [RELATIVE_PATH_FROM_DIST] Current file: node_modules/vike/dist/esm/node/plugin/shared/resolveClientEntriesDev.js
38
- filePath = toPosixPath(require_.resolve(clientEntry.replace('@@vike/dist/esm/client/', '../../../../../dist/esm/client/')));
35
+ filePath_ = requireResolveOptionalNonUserFile(clientEntry.replace('@@vike/dist/esm/client/', '../../../../../dist/esm/client/'), importMetaUrl);
39
36
  }
37
+ assert(filePath_);
38
+ filePath = filePath_;
40
39
  }
41
40
  else {
42
41
  assertIsNpmPackageImport(clientEntry);
43
- filePath = require_.resolve(clientEntry);
42
+ filePath = requireResolve(clientEntry, root);
44
43
  }
45
44
  }
46
45
  if (!filePath.startsWith('/')) {
@@ -23,3 +23,4 @@ export * from '../../utils/PROJECT_VERSION.js';
23
23
  export * from '../../utils/isEqualStringList.js';
24
24
  export * from '../../utils/isDocker.js';
25
25
  export * from '../../utils/isVitest.js';
26
+ export * from '../../utils/rollupSourceMap.js';
@@ -29,3 +29,4 @@ export * from '../../utils/PROJECT_VERSION.js';
29
29
  export * from '../../utils/isEqualStringList.js';
30
30
  export * from '../../utils/isDocker.js';
31
31
  export * from '../../utils/isVitest.js';
32
+ export * from '../../utils/rollupSourceMap.js';
@@ -4,7 +4,7 @@ import { VikeConfigObject } from '../plugin/plugins/importUserCode/v1-design/get
4
4
  import type { PageConfigBuildTime } from '../../shared/page-configs/PageConfig.js';
5
5
  declare function resolvePrerenderConfigGlobal(vikeConfig: VikeConfigObject): {
6
6
  partial: boolean;
7
- noExtraDir: boolean;
7
+ noExtraDir: boolean | null;
8
8
  keepDistServer: boolean;
9
9
  parallel: number | boolean;
10
10
  disableAutoRun: boolean;
@@ -9,7 +9,7 @@ function resolvePrerenderConfigGlobal(vikeConfig) {
9
9
  const prerenderSettings = prerenderConfigs.filter(isObject2);
10
10
  const prerenderConfigGlobal = {
11
11
  partial: pickFirst(prerenderSettings.map((c) => c.partial)) ?? false,
12
- noExtraDir: pickFirst(prerenderSettings.map((c) => c.noExtraDir)) ?? false,
12
+ noExtraDir: pickFirst(prerenderSettings.map((c) => c.noExtraDir)) ?? null,
13
13
  keepDistServer: pickFirst(prerenderSettings.map((c) => c.keepDistServer)) ?? false,
14
14
  parallel: pickFirst(prerenderSettings.map((c) => c.parallel)) ?? true,
15
15
  disableAutoRun: pickFirst(prerenderSettings.map((c) => c.disableAutoRun)) ?? false
@@ -14,6 +14,7 @@ type ProvidedByHook = null | {
14
14
  type PageContextPrerendered = {
15
15
  urlOriginal: string;
16
16
  _providedByHook?: ProvidedByHook;
17
+ pageId: string;
17
18
  };
18
19
  type Output<PageContext = PageContextPrerendered> = {
19
20
  filePath: string;