vike 0.4.217 → 0.4.218

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 (35) hide show
  1. package/dist/cjs/node/api/build.js +1 -1
  2. package/dist/cjs/node/api/prepareViteApiCall.js +93 -20
  3. package/dist/cjs/node/api/utils.js +2 -0
  4. package/dist/cjs/node/plugin/index.js +2 -1
  5. package/dist/cjs/node/plugin/plugins/baseUrls.js +20 -18
  6. package/dist/cjs/node/plugin/plugins/commonConfig.js +6 -6
  7. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +22 -111
  8. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +6 -6
  9. package/dist/cjs/node/prerender/runPrerender.js +1 -1
  10. package/dist/cjs/node/shared/resolveBase.js +2 -2
  11. package/dist/cjs/utils/PROJECT_VERSION.js +1 -1
  12. package/dist/esm/node/api/build.js +1 -1
  13. package/dist/esm/node/api/prepareViteApiCall.d.ts +8 -2
  14. package/dist/esm/node/api/prepareViteApiCall.js +91 -21
  15. package/dist/esm/node/api/utils.d.ts +2 -0
  16. package/dist/esm/node/api/utils.js +2 -0
  17. package/dist/esm/node/plugin/index.js +2 -1
  18. package/dist/esm/node/plugin/plugins/baseUrls.d.ts +1 -2
  19. package/dist/esm/node/plugin/plugins/baseUrls.js +21 -19
  20. package/dist/esm/node/plugin/plugins/commonConfig.d.ts +7 -1
  21. package/dist/esm/node/plugin/plugins/commonConfig.js +2 -2
  22. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.d.ts +1 -1
  23. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +23 -112
  24. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +6 -6
  25. package/dist/esm/node/plugin/shared/getEnvVarObject.d.ts +1 -1
  26. package/dist/esm/node/prerender/runPrerender.d.ts +1 -1
  27. package/dist/esm/node/prerender/runPrerender.js +1 -1
  28. package/dist/esm/node/shared/resolveBase.js +2 -2
  29. package/dist/esm/utils/PROJECT_VERSION.d.ts +1 -1
  30. package/dist/esm/utils/PROJECT_VERSION.js +1 -1
  31. package/dist/esm/utils/projectInfo.d.ts +1 -1
  32. package/package.json +1 -1
  33. package/dist/cjs/node/plugin/plugins/commonConfig/pluginName.js +0 -4
  34. package/dist/esm/node/plugin/plugins/commonConfig/pluginName.d.ts +0 -1
  35. package/dist/esm/node/plugin/plugins/commonConfig/pluginName.js +0 -1
@@ -56,7 +56,7 @@ function setSSR(viteConfig) {
56
56
  return {
57
57
  ...viteConfig,
58
58
  build: {
59
- ...viteConfig.build,
59
+ ...viteConfig?.build,
60
60
  ssr: true
61
61
  }
62
62
  };
@@ -22,42 +22,100 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
25
28
  Object.defineProperty(exports, "__esModule", { value: true });
26
29
  exports.prepareViteApiCall = prepareViteApiCall;
30
+ exports.getViteRoot = getViteRoot;
31
+ exports.assertViteRoot = assertViteRoot;
32
+ exports.normalizeViteRoot = normalizeViteRoot;
33
+ // TODO: enable Vike extensions to add Vite plugins
27
34
  const vite_1 = require("vite");
28
- const pluginName_js_1 = require("../plugin/plugins/commonConfig/pluginName.js");
29
35
  const context_js_1 = require("./context.js");
30
36
  const getVikeConfig_js_1 = require("../plugin/plugins/importUserCode/v1-design/getVikeConfig.js");
31
- async function prepareViteApiCall(viteConfig = {}, operation) {
37
+ const path_1 = __importDefault(require("path"));
38
+ const utils_js_1 = require("./utils.js");
39
+ const picocolors_1 = __importDefault(require("@brillout/picocolors"));
40
+ const globalObject = (0, utils_js_1.getGlobalObject)('prepareViteApiCall.ts', {});
41
+ async function prepareViteApiCall(viteConfig, operation) {
32
42
  (0, context_js_1.setOperation)(operation);
33
43
  return enhanceViteConfig(viteConfig, operation);
34
44
  }
35
- async function enhanceViteConfig(viteConfig = {}, operation) {
36
- let viteConfigResolved = await resolveViteConfig(viteConfig, operation);
45
+ async function enhanceViteConfig(viteConfig, operation) {
46
+ const { root, vikeVitePluginOptions, viteConfigEnhanced } = await getInfoFromVite(viteConfig, operation);
47
+ await assertViteRoot2(root, viteConfigEnhanced, operation);
48
+ const { vikeConfigGlobal } = await (0, getVikeConfig_js_1.getVikeConfig2)(root, operation === 'dev', vikeVitePluginOptions);
49
+ return {
50
+ viteConfigEnhanced,
51
+ vikeConfigGlobal
52
+ };
53
+ }
54
+ async function getViteRoot(operation) {
55
+ if (!globalObject.root)
56
+ await getInfoFromVite(undefined, operation);
57
+ (0, utils_js_1.assert)(globalObject.root);
58
+ return globalObject.root;
59
+ }
60
+ async function getInfoFromVite(viteConfig, operation) {
61
+ const viteConfigFromFile = await loadViteConfigFile(viteConfig, operation);
62
+ const root = normalizeViteRoot(viteConfigFromFile?.root ?? viteConfig?.root ?? process.cwd());
63
+ globalObject.root = root;
64
+ let vikeVitePluginOptions;
37
65
  let viteConfigEnhanced = viteConfig;
38
- // Add vike to plugins if not present
39
- if (!viteConfigResolved.plugins.some((p) => p.name === pluginName_js_1.pluginName)) {
40
- // Using a dynamic import because the script calling the Vike API may not live in the same place as vite.config.js, thus have vike/plugin may resolved to two different node_modules/vike directories
66
+ const found = findVikeVitePlugin([...(viteConfig?.plugins ?? []), ...(viteConfigFromFile?.plugins ?? [])]);
67
+ if (found) {
68
+ vikeVitePluginOptions = found.vikeVitePluginOptions;
69
+ }
70
+ else {
71
+ // Add Vike to plugins if not present.
72
+ // Using a dynamic import because the script calling the Vike API may not live in the same place as vite.config.js, thus vike/plugin may resolved to two different node_modules/vike directories.
41
73
  const { plugin: vikePlugin } = await Promise.resolve().then(() => __importStar(require('../plugin/index.js')));
42
74
  viteConfigEnhanced = {
43
75
  ...viteConfig,
44
- plugins: [...(viteConfig.plugins ?? []), vikePlugin()]
76
+ plugins: [...(viteConfig?.plugins ?? []), vikePlugin()]
45
77
  };
46
- viteConfigResolved = await resolveViteConfig(viteConfigEnhanced, operation);
78
+ const res = findVikeVitePlugin(viteConfigEnhanced.plugins);
79
+ (0, utils_js_1.assert)(res);
80
+ vikeVitePluginOptions = res.vikeVitePluginOptions;
47
81
  }
48
- // TODO: use loadConfigFromFile() instead of viteConfigResolved
49
- const { vikeConfigGlobal } = await (0, getVikeConfig_js_1.getVikeConfig2)(viteConfigResolved.root, operation === 'dev', viteConfigResolved._vikeVitePluginOptions);
50
- // TODO: enable Vike extensions to add Vite plugins
51
- return {
52
- viteConfigEnhanced,
53
- vikeConfigGlobal
54
- };
82
+ (0, utils_js_1.assert)(vikeVitePluginOptions);
83
+ return { root, vikeVitePluginOptions, viteConfigEnhanced };
55
84
  }
56
- async function resolveViteConfig(viteConfig, operation) {
57
- const args = getResolveConfigArgs(viteConfig, operation);
58
- return await (0, vite_1.resolveConfig)(...args);
85
+ function findVikeVitePlugin(plugins) {
86
+ let vikeVitePluginOptions;
87
+ let vikeVitePuginFound = false;
88
+ plugins.forEach((p) => {
89
+ if (p && '__vikeVitePluginOptions' in p) {
90
+ vikeVitePuginFound = true;
91
+ const options = p.__vikeVitePluginOptions;
92
+ vikeVitePluginOptions ?? (vikeVitePluginOptions = {});
93
+ Object.assign(vikeVitePluginOptions, options);
94
+ }
95
+ });
96
+ if (!vikeVitePuginFound)
97
+ return null;
98
+ return { vikeVitePluginOptions };
59
99
  }
60
- function getResolveConfigArgs(viteConfig, operation) {
100
+ // Copied from https://github.com/vitejs/vite/blob/4f5845a3182fc950eb9cd76d7161698383113b18/packages/vite/src/node/config.ts#L961-L1005
101
+ async function loadViteConfigFile(viteConfig, operation) {
102
+ const [inlineConfig, command, defaultMode, _defaultNodeEnv, isPreview] = getResolveConfigArgs(viteConfig, operation);
103
+ let config = inlineConfig;
104
+ let mode = inlineConfig.mode || defaultMode;
105
+ const configEnv = {
106
+ mode,
107
+ command,
108
+ isSsrBuild: command === 'build' && !!config.build?.ssr,
109
+ isPreview
110
+ };
111
+ let { configFile } = config;
112
+ if (configFile !== false) {
113
+ const loadResult = await (0, vite_1.loadConfigFromFile)(configEnv, configFile, config.root, config.logLevel, config.customLogger);
114
+ return loadResult?.config;
115
+ }
116
+ return null;
117
+ }
118
+ function getResolveConfigArgs(viteConfig = {}, operation) {
61
119
  const inlineConfig = viteConfig;
62
120
  const command = operation === 'build' || operation === 'prerender' ? 'build' : 'serve';
63
121
  const defaultMode = operation === 'dev' ? 'development' : 'production';
@@ -65,3 +123,18 @@ function getResolveConfigArgs(viteConfig, operation) {
65
123
  const isPreview = operation === 'preview';
66
124
  return [inlineConfig, command, defaultMode, defaultNodeEnv, isPreview];
67
125
  }
126
+ function normalizeViteRoot(root) {
127
+ return (0, utils_js_1.toPosixPath)(path_1.default.resolve(root));
128
+ }
129
+ const errMsg = `A Vite plugin is modifying Vite's setting ${picocolors_1.default.cyan('root')} which is forbidden`;
130
+ async function assertViteRoot2(root, viteConfigEnhanced, operation) {
131
+ const args = getResolveConfigArgs(viteConfigEnhanced, operation);
132
+ // We can eventually this resolveConfig() call (along with removing the whole assertViteRoot2() function which is redundant with the assertViteRoot() function) so that Vike doesn't make any resolveConfig() (except for pre-rendering which is required). But let's keep it for now, just to see whether calling resolveConfig() can be problematic.
133
+ const viteConfigResolved = await (0, vite_1.resolveConfig)(...args);
134
+ (0, utils_js_1.assertUsage)(normalizeViteRoot(viteConfigResolved.root) === normalizeViteRoot(root), errMsg);
135
+ }
136
+ function assertViteRoot(root, config) {
137
+ if (globalObject.root)
138
+ (0, utils_js_1.assert)(normalizeViteRoot(globalObject.root) === normalizeViteRoot(root));
139
+ (0, utils_js_1.assertUsage)(normalizeViteRoot(root) === normalizeViteRoot(config.root), errMsg);
140
+ }
@@ -20,3 +20,5 @@ const onLoad_js_1 = require("./onLoad.js");
20
20
  (0, onLoad_js_1.onLoad)();
21
21
  __exportStar(require("../../utils/assert.js"), exports);
22
22
  __exportStar(require("../../utils/getGlobalObject.js"), exports);
23
+ __exportStar(require("../../utils/filesystemPathHandling.js"), exports);
24
+ __exportStar(require("../../utils/isObject.js"), exports);
@@ -37,7 +37,7 @@ const vite6HmrRegressionWorkaround_js_1 = require("./plugins/vite6HmrRegressionW
37
37
  assertViteVersion();
38
38
  (0, getPageAssets_js_1.setResolveClientEntriesDev)(resolveClientEntriesDev_js_1.resolveClientEntriesDev);
39
39
  // Return as `any` to avoid Plugin type mismatches when there are multiple Vite versions installed
40
- function plugin(vikeVitePluginOptions) {
40
+ function plugin(vikeVitePluginOptions = {}) {
41
41
  const plugins = [
42
42
  ...(0, commonConfig_js_1.commonConfig)(vikeVitePluginOptions),
43
43
  (0, index_js_2.importUserCode)(),
@@ -59,6 +59,7 @@ function plugin(vikeVitePluginOptions) {
59
59
  (0, workaroundCssModuleHmr_js_1.workaroundCssModuleHmr)(),
60
60
  (0, vite6HmrRegressionWorkaround_js_1.vite6HmrRegressionWorkaround)()
61
61
  ];
62
+ Object.assign(plugins, { __vikeVitePluginOptions: vikeVitePluginOptions });
62
63
  return plugins;
63
64
  }
64
65
  // Error upon wrong usage
@@ -4,35 +4,41 @@ exports.baseUrls = baseUrls;
4
4
  const resolveBase_js_1 = require("../../shared/resolveBase.js");
5
5
  const utils_js_1 = require("../utils.js");
6
6
  const getVikeConfig_js_1 = require("./importUserCode/v1-design/getVikeConfig.js");
7
+ const prepareViteApiCall_js_1 = require("../../api/prepareViteApiCall.js");
7
8
  function baseUrls(vikeVitePluginOptions) {
8
- let bases;
9
+ let basesResolved;
10
+ let root;
9
11
  return {
10
12
  name: 'vike:baseUrls',
11
13
  enforce: 'post',
12
- async config(config) {
13
- // TODO: fix bug: use getVikeConfig2() and udpate check below
14
- bases = resolveBaseFromUserConfig(config, vikeVitePluginOptions);
15
- const { baseServer, baseAssets } = bases;
14
+ async config(config, env) {
15
+ const isDev = config._isDev;
16
+ (0, utils_js_1.assert)(typeof isDev === 'boolean');
17
+ const operation = env.command === 'build' ? 'build' : env.isPreview ? 'preview' : 'dev';
18
+ root = config.root ? (0, prepareViteApiCall_js_1.normalizeViteRoot)(config.root) : await (0, prepareViteApiCall_js_1.getViteRoot)(operation);
19
+ (0, utils_js_1.assert)(root);
20
+ const baseViteOriginal = config.base ?? '/__UNSET__'; // '/__UNSET__' because Vite resolves `_baseViteOriginal: null` to `undefined`
21
+ const vikeConfig = await (0, getVikeConfig_js_1.getVikeConfig2)(root, isDev, vikeVitePluginOptions);
22
+ basesResolved = (0, resolveBase_js_1.resolveBase)(baseViteOriginal, vikeConfig.vikeConfigGlobal.baseServer, vikeConfig.vikeConfigGlobal.baseAssets);
16
23
  // We cannot define these in configResolved() because Vite picks up the env variables before any configResolved() hook is called
17
- process.env.BASE_SERVER = baseServer;
18
- process.env.BASE_ASSETS = baseAssets;
24
+ process.env.BASE_SERVER = basesResolved.baseServer;
25
+ process.env.BASE_ASSETS = basesResolved.baseAssets;
19
26
  return {
20
27
  envPrefix: [
21
28
  'VITE_', // Vite doesn't seem to merge in its default, see https://github.com/vikejs/vike/issues/554
22
29
  'BASE_SERVER',
23
30
  'BASE_ASSETS'
24
31
  ],
25
- base: baseAssets, // Make Vite inject baseAssets to imports e.g. `import logoUrl from './logo.svg.js'`
26
- _baseViteOriginal: config.base ?? '/__UNSET__' // Vite resolves `_baseViteOriginal: null` to `undefined`
32
+ base: basesResolved.baseAssets, // Make Vite inject baseAssets to imports e.g. `import logoUrl from './logo.svg.js'`
33
+ _baseViteOriginal: baseViteOriginal
27
34
  };
28
35
  },
29
36
  async configResolved(config) {
37
+ (0, prepareViteApiCall_js_1.assertViteRoot)(root, config);
30
38
  const vikeConfig = await (0, getVikeConfig_js_1.getVikeConfig)(config);
31
- const { baseServer, baseAssets } = vikeConfig.vikeConfigGlobal;
32
- const basesResolved = (0, resolveBase_js_1.resolveBaseFromResolvedConfig)(baseServer, baseAssets, config);
33
- // Ensure that the premature base URL resolving we did in config() isn't erroneous
34
- (0, utils_js_1.assert)(basesResolved.baseServer === bases.baseServer);
35
- (0, utils_js_1.assert)(basesResolved.baseAssets === bases.baseAssets);
39
+ const basesResolved2 = (0, resolveBase_js_1.resolveBaseFromResolvedConfig)(vikeConfig.vikeConfigGlobal.baseServer, vikeConfig.vikeConfigGlobal.baseAssets, config);
40
+ (0, utils_js_1.assert)(basesResolved2.baseServer === basesResolved.baseServer);
41
+ (0, utils_js_1.assert)(basesResolved2.baseAssets === basesResolved.baseAssets);
36
42
  /* In dev, Vite seems buggy around setting vite.config.js#base to an absolute URL (e.g. http://localhost:8080/cdn/)
37
43
  * - In dev, Vite removes the URL origin. (I.e. it resolves the user config `vite.config.js#base: 'http://localhost:8080/cdn/'` to resolved config `config.base === '/cdn/'`.)
38
44
  * - Instead of having an internal Vike assertion fail, we let the user discover Vite's buggy behavior.
@@ -41,7 +47,3 @@ function baseUrls(vikeVitePluginOptions) {
41
47
  }
42
48
  };
43
49
  }
44
- function resolveBaseFromUserConfig(config, vikeVitePluginOptions) {
45
- const baseViteOriginal = config.base ?? null;
46
- return (0, resolveBase_js_1.resolveBase)(baseViteOriginal, vikeVitePluginOptions?.baseServer ?? null, vikeVitePluginOptions?.baseAssets ?? null);
47
- }
@@ -11,14 +11,14 @@ const require_shim_1 = require("@brillout/require-shim");
11
11
  const picocolors_1 = __importDefault(require("@brillout/picocolors"));
12
12
  const path_1 = __importDefault(require("path"));
13
13
  const assertResolveAlias_js_1 = require("./commonConfig/assertResolveAlias.js");
14
- const pluginName_js_1 = require("./commonConfig/pluginName.js");
15
14
  const getEnvVarObject_js_1 = require("../shared/getEnvVarObject.js");
16
15
  const isViteCliCall_js_1 = require("../shared/isViteCliCall.js");
17
16
  const context_js_1 = require("../../api/context.js");
18
- function commonConfig(vikeVitePluginOptions = {}) {
17
+ const pluginName = 'vike:commonConfig';
18
+ function commonConfig(vikeVitePluginOptions) {
19
19
  return [
20
20
  {
21
- name: `${pluginName_js_1.pluginName}:pre`,
21
+ name: `${pluginName}:pre`,
22
22
  enforce: 'pre',
23
23
  config: {
24
24
  order: 'pre',
@@ -31,14 +31,14 @@ function commonConfig(vikeVitePluginOptions = {}) {
31
31
  }
32
32
  },
33
33
  {
34
- name: pluginName_js_1.pluginName,
34
+ name: pluginName,
35
35
  configResolved(config) {
36
36
  assertSingleInstance(config);
37
37
  (0, require_shim_1.installRequireShim_setUserRootDir)(config.root);
38
38
  }
39
39
  },
40
40
  {
41
- name: `${pluginName_js_1.pluginName}:post`,
41
+ name: `${pluginName}:post`,
42
42
  enforce: 'post',
43
43
  configResolved: {
44
44
  order: 'post',
@@ -111,7 +111,7 @@ function assertEsm(userViteRoot) {
111
111
  (0, utils_js_1.assertWarning)(packageJson.type === 'module', `We recommend setting ${dir}package.json#type to "module", see https://vike.dev/CJS`, { onlyOnce: true });
112
112
  }
113
113
  function assertSingleInstance(config) {
114
- const numberOfInstances = config.plugins.filter((o) => o.name === pluginName_js_1.pluginName).length;
114
+ const numberOfInstances = config.plugins.filter((o) => o.name === pluginName).length;
115
115
  (0, utils_js_1.assertUsage)(numberOfInstances === 1, `Vike's Vite plugin (${picocolors_1.default.cyan("import vike from 'vike/plugin'")}) is being added ${numberOfInstances} times to the list of Vite plugins. Make sure to add it only once instead.`);
116
116
  }
117
117
  function assertVikeCliOrApi(config) {
@@ -6,17 +6,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.crawlPlusFiles = crawlPlusFiles;
7
7
  const utils_js_1 = require("../../../../utils.js");
8
8
  const path_1 = __importDefault(require("path"));
9
- const promises_1 = __importDefault(require("fs/promises"));
10
9
  const fast_glob_1 = __importDefault(require("fast-glob"));
11
10
  const child_process_1 = require("child_process");
12
11
  const util_1 = require("util");
13
12
  const transpileAndExecuteFile_js_1 = require("./transpileAndExecuteFile.js");
13
+ const getEnvVarObject_js_1 = require("../../../../shared/getEnvVarObject.js");
14
14
  const execA = (0, util_1.promisify)(child_process_1.exec);
15
- const TOO_MANY_UNTRACKED_FILES = 5;
16
15
  (0, utils_js_1.assertIsNotProductionRuntime)();
17
16
  (0, utils_js_1.assertIsSingleModuleInstance)('crawlPlusFiles.ts');
18
17
  let gitIsNotUsable = false;
19
- async function crawlPlusFiles(userRootDir, outDirAbsoluteFilesystem, crawlWithGit) {
18
+ async function crawlPlusFiles(userRootDir, outDirAbsoluteFilesystem) {
20
19
  (0, utils_js_1.assertPosixPath)(userRootDir);
21
20
  //*/
22
21
  const outDirRelativeFromUserRootDir = null;
@@ -36,14 +35,13 @@ async function crawlPlusFiles(userRootDir, outDirAbsoluteFilesystem, crawlWithGi
36
35
  //
37
36
  !outDirRelativeFromUserRootDir.startsWith('../')));
38
37
  // Crawl
39
- let files = [];
40
- const res = crawlWithGit !== false && (await gitLsFiles(userRootDir, outDirRelativeFromUserRootDir));
38
+ let files;
39
+ const res = !isGitCrawlDisabled() && (await gitLsFiles(userRootDir, outDirRelativeFromUserRootDir));
41
40
  if (res &&
42
41
  // Fallback to fast-glob for users that dynamically generate plus files. (Assuming that no plus file is found because of the user's .gitignore list.)
43
- res.files.length > 0) {
44
- files = res.files;
42
+ res.length > 0) {
43
+ files = res;
45
44
  // We cannot find files inside symlink directories with `$ git ls-files` => we use fast-glob
46
- files.push(...(await crawlSymlinkDirs(res.symlinkDirs, userRootDir, outDirRelativeFromUserRootDir)));
47
45
  }
48
46
  else {
49
47
  files = await fastGlob(userRootDir, outDirRelativeFromUserRootDir);
@@ -75,24 +73,21 @@ async function gitLsFiles(userRootDir, outDirRelativeFromUserRootDir) {
75
73
  'git',
76
74
  preserveUTF8,
77
75
  'ls-files',
78
- // We don't filter because:
79
- // - It would skip symlink directories
80
- // - Performance gain seems negligible: https://github.com/vikejs/vike/pull/1688#issuecomment-2166206648
81
- // ...scriptFileExtensionList.map((ext) => `"**/+*.${ext}"`),
76
+ // Performance gain seems negligible: https://github.com/vikejs/vike/pull/1688#issuecomment-2166206648
77
+ ...utils_js_1.scriptFileExtensionList.map((ext) => `"**/+*.${ext}"`),
82
78
  // Performance gain is non-negligible.
83
79
  // - https://github.com/vikejs/vike/pull/1688#issuecomment-2166206648
84
80
  // - When node_modules/ is untracked the performance gain could be significant?
85
81
  ...ignoreAsPatterns.map((pattern) => `--exclude="${pattern}"`),
86
82
  // --others --exclude-standard => list untracked files (--others) while using .gitignore (--exclude-standard)
87
83
  // --cached => list tracked files
88
- // --stage => get file modes which we use to find symlink directories
89
- '--others --exclude-standard --cached --stage'
84
+ '--others --exclude-standard --cached'
90
85
  ].join(' ');
91
- let resultLines;
86
+ let filesAll;
92
87
  let filesDeleted;
93
88
  try {
94
89
  ;
95
- [resultLines, filesDeleted] = await Promise.all([
90
+ [filesAll, filesDeleted] = await Promise.all([
96
91
  // Main command
97
92
  runCmd1(cmd, userRootDir),
98
93
  // Get tracked but deleted files
@@ -106,40 +101,23 @@ async function gitLsFiles(userRootDir, outDirRelativeFromUserRootDir) {
106
101
  }
107
102
  throw err;
108
103
  }
109
- const filePaths = resultLines.map(parseGitLsResultLine);
110
- // If there are too many files without mode we fallback to fast-glob
111
- if (filePaths.filter((f) => !f.mode).length > TOO_MANY_UNTRACKED_FILES)
112
- return null;
113
- const symlinkDirs = [];
114
104
  const files = [];
115
- for (const { filePath, mode } of filePaths) {
116
- // Deleted?
117
- if (filesDeleted.includes(filePath))
105
+ for (const filePath of filesAll) {
106
+ // + file?
107
+ if (!path_1.default.posix.basename(filePath).startsWith('+'))
118
108
  continue;
119
109
  // We have to repeat the same exclusion logic here because the option --exclude of `$ git ls-files` only applies to untracked files. (We use --exclude only to speed up the `$ git ls-files` command.)
120
110
  if (!ignoreAsFilterFn(filePath))
121
111
  continue;
122
- // Symlink directory?
123
- {
124
- const isSymlinkDir = await isSymlinkDirectory(mode, filePath, userRootDir);
125
- if (isSymlinkDir) {
126
- symlinkDirs.push(filePath);
127
- continue;
128
- }
129
- // Skip deleted files and non-symlink directories
130
- if (isSymlinkDir === null) {
131
- continue;
132
- }
133
- }
134
- // + file?
135
- if (!path_1.default.posix.basename(filePath).startsWith('+'))
136
- continue;
137
112
  // JavaScript file?
138
113
  if (!(0, utils_js_1.isScriptFile)(filePath))
139
114
  continue;
115
+ // Deleted?
116
+ if (filesDeleted.includes(filePath))
117
+ continue;
140
118
  files.push(filePath);
141
119
  }
142
- return { files, symlinkDirs };
120
+ return files;
143
121
  }
144
122
  // Same as gitLsFiles() but using fast-glob
145
123
  async function fastGlob(userRootDir, outDirRelativeFromUserRootDir) {
@@ -209,77 +187,6 @@ async function isGitNotUsable(userRootDir) {
209
187
  return false;
210
188
  }
211
189
  }
212
- async function crawlSymlinkDirs(symlinkDirs, userRootDir, outDirRelativeFromUserRootDir) {
213
- const filesInSymlinkDirs = (await Promise.all(symlinkDirs.map(async (symlinkDir) => (await fastGlob(path_1.default.posix.join(userRootDir, symlinkDir), outDirRelativeFromUserRootDir)).map((filePath) => path_1.default.posix.join(symlinkDir, filePath))))).flat();
214
- return filesInSymlinkDirs;
215
- }
216
- // Parse:
217
- // ```
218
- // some/not/tracked/path
219
- // 100644 f6928073402b241b468b199893ff6f4aed0b7195 0\tpages/index/+Page.tsx
220
- // ```
221
- function parseGitLsResultLine(resultLine) {
222
- const [part1, part2, ...rest] = resultLine.split('\t');
223
- (0, utils_js_1.assert)(part1);
224
- (0, utils_js_1.assert)(rest.length === 0);
225
- // Git doesn't provide the mode for untracked paths.
226
- // `resultLine` is:
227
- // ```
228
- // some/not/tracked/path
229
- // ```
230
- if (part2 === undefined) {
231
- return { filePath: part1, mode: null };
232
- }
233
- (0, utils_js_1.assert)(part2);
234
- // `resultLine` is:
235
- // ```
236
- // 100644 f6928073402b241b468b199893ff6f4aed0b7195 0\tpages/index/+Page.tsx
237
- // ```
238
- const [mode, _, __, ...rest2] = part1.split(' ');
239
- (0, utils_js_1.assert)(mode && _ && __ && rest2.length === 0);
240
- return { filePath: part2, mode };
241
- }
242
- async function isSymlinkDirectory(mode, filePath, userRootDir) {
243
- const filePathAbsolute = path_1.default.posix.join(userRootDir, filePath);
244
- let stats = null;
245
- let isSymlink = false;
246
- if (mode === '120000') {
247
- isSymlink = true;
248
- }
249
- else if (mode === null) {
250
- // `$ git ls-files` doesn't provide the mode when Git doesn't track the path
251
- stats = await getFileStats(filePathAbsolute);
252
- if (stats === null)
253
- return null;
254
- isSymlink = stats.isSymbolicLink();
255
- if (!isSymlink && stats.isDirectory())
256
- return null;
257
- }
258
- else {
259
- (0, utils_js_1.assert)(mode);
260
- }
261
- if (!isSymlink)
262
- return false;
263
- if (!stats)
264
- stats = await getFileStats(filePathAbsolute);
265
- if (stats === null)
266
- return null;
267
- const isDirectory = stats.isDirectory();
268
- return isDirectory;
269
- }
270
- async function getFileStats(filePathAbsolute) {
271
- let stats;
272
- try {
273
- stats = await promises_1.default.lstat(filePathAbsolute);
274
- }
275
- catch (err) {
276
- // File was deleted, usually a temporary file such as +config.js.build-j95xb988fpln.mjs
277
- // ENOENT: no such file or directory
278
- (0, utils_js_1.assert)(err.code === 'ENOENT');
279
- return null;
280
- }
281
- return stats;
282
- }
283
190
  async function runCmd1(cmd, cwd) {
284
191
  const { stdout } = await execA(cmd, {
285
192
  cwd,
@@ -304,3 +211,7 @@ async function runCmd2(cmd, cwd) {
304
211
  stderr = stderr.toString().trim();
305
212
  return { stdout, stderr };
306
213
  }
214
+ function isGitCrawlDisabled() {
215
+ const crawSettings = (0, getEnvVarObject_js_1.getEnvVarObject)('VIKE_CRAWL');
216
+ return crawSettings?.git === false;
217
+ }
@@ -84,6 +84,7 @@ async function getVikeConfig(config, { doNotRestartViteOnError } = {}) {
84
84
  return await getVikeConfigEntry(userRootDir, isDev, vikeVitePluginOptions, doNotRestartViteOnError ?? false);
85
85
  }
86
86
  async function getVikeConfig2(userRootDir, isDev, vikeVitePluginOptions) {
87
+ (0, utils_js_1.assert)(vikeVitePluginOptions);
87
88
  return await getVikeConfigEntry(userRootDir, isDev, vikeVitePluginOptions, false);
88
89
  }
89
90
  async function getVikeConfigEntry(userRootDir, isDev, vikeVitePluginOptions, doNotRestartViteOnError) {
@@ -98,8 +99,8 @@ async function isV1Design(config) {
98
99
  const isV1Design = pageConfigs.length > 0;
99
100
  return isV1Design;
100
101
  }
101
- async function loadInterfaceFiles(userRootDir, crawlWithGit) {
102
- const plusFiles = await findPlusFiles(userRootDir, null, crawlWithGit);
102
+ async function loadInterfaceFiles(userRootDir) {
103
+ const plusFiles = await findPlusFiles(userRootDir, null);
103
104
  const configFiles = [];
104
105
  const valueFiles = [];
105
106
  plusFiles.forEach((f) => {
@@ -251,8 +252,7 @@ async function loadVikeConfig_withErrorHandling(userRootDir, isDev, vikeVitePlug
251
252
  }
252
253
  }
253
254
  async function loadVikeConfig(userRootDir, vikeVitePluginOptions) {
254
- const crawlWithGit = (0, resolveVikeConfigGlobal_js_1.resolveVikeConfigGlobal)(vikeVitePluginOptions, {}).crawl.git ?? null;
255
- const interfaceFilesByLocationId = await loadInterfaceFiles(userRootDir, crawlWithGit);
255
+ const interfaceFilesByLocationId = await loadInterfaceFiles(userRootDir);
256
256
  const importedFilesLoaded = {};
257
257
  const { pageConfigGlobal, pageConfigGlobalValues } = await getGlobalConfigs(interfaceFilesByLocationId, userRootDir, importedFilesLoaded);
258
258
  const vikeConfigGlobal = (0, resolveVikeConfigGlobal_js_1.resolveVikeConfigGlobal)(vikeVitePluginOptions, pageConfigGlobalValues);
@@ -799,8 +799,8 @@ function getComputed(configValueSources, configDefinitions) {
799
799
  });
800
800
  return configValuesComputed;
801
801
  }
802
- async function findPlusFiles(userRootDir, outDirRoot, crawlWithGit) {
803
- const files = await (0, crawlPlusFiles_js_1.crawlPlusFiles)(userRootDir, outDirRoot, crawlWithGit);
802
+ async function findPlusFiles(userRootDir, outDirRoot) {
803
+ const files = await (0, crawlPlusFiles_js_1.crawlPlusFiles)(userRootDir, outDirRoot);
804
804
  const plusFiles = files.map(({ filePathAbsoluteUserRootDir }) => (0, getFilePath_js_1.getFilePathResolved)({ filePathAbsoluteUserRootDir, userRootDir }));
805
805
  return plusFiles;
806
806
  }
@@ -96,7 +96,7 @@ async function runPrerender(options = {}, standaloneTrigger) {
96
96
  console.log(`${picocolors_1.default.cyan(`vike v${utils_js_1.projectInfo.projectVersion}`)} ${picocolors_1.default.green('pre-rendering HTML...')}`);
97
97
  }
98
98
  await disableReactStreaming();
99
- const viteConfig = await (0, vite_1.resolveConfig)(options.viteConfig || {}, 'vike pre-rendering', 'production');
99
+ const viteConfig = await (0, vite_1.resolveConfig)(options.viteConfig || {}, 'build', 'production');
100
100
  assertLoadedConfig(viteConfig, options);
101
101
  const vikeConfig = await (0, getVikeConfig_js_1.getVikeConfig)(viteConfig);
102
102
  const { outDirClient } = (0, utils_js_1.getOutDirs)(viteConfig);
@@ -9,12 +9,12 @@ const utils_js_1 = require("./utils.js");
9
9
  const picocolors_1 = __importDefault(require("@brillout/picocolors"));
10
10
  function resolveBaseFromResolvedConfig(baseServer, baseAssets, config) {
11
11
  let baseViteOriginal = config._baseViteOriginal;
12
- if (baseViteOriginal === '/__UNSET__')
13
- baseViteOriginal = null;
14
12
  (0, utils_js_1.assert)(baseViteOriginal === null || typeof baseViteOriginal == 'string');
15
13
  return resolveBase(baseViteOriginal, baseServer, baseAssets);
16
14
  }
17
15
  function resolveBase(baseViteOriginal, baseServerUnresolved, baseAssetsUnresolved) {
16
+ if (baseViteOriginal === '/__UNSET__')
17
+ baseViteOriginal = null;
18
18
  {
19
19
  const wrongBase = (val) => `should start with ${picocolors_1.default.cyan('/')}, ${picocolors_1.default.cyan('http://')}, or ${picocolors_1.default.cyan('https://')} (it's ${picocolors_1.default.cyan(val)} instead)`;
20
20
  (0, utils_js_1.assertUsage)(baseViteOriginal === null || (0, utils_js_1.isBaseAssets)(baseViteOriginal), `vite.config.js#base ${wrongBase(baseViteOriginal)}`);
@@ -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.217';
5
+ exports.PROJECT_VERSION = '0.4.218';
@@ -31,7 +31,7 @@ function setSSR(viteConfig) {
31
31
  return {
32
32
  ...viteConfig,
33
33
  build: {
34
- ...viteConfig.build,
34
+ ...viteConfig?.build,
35
35
  ssr: true
36
36
  }
37
37
  };
@@ -1,7 +1,13 @@
1
1
  export { prepareViteApiCall };
2
- import type { InlineConfig } from 'vite';
2
+ export { getViteRoot };
3
+ export { assertViteRoot };
4
+ export { normalizeViteRoot };
5
+ import type { InlineConfig, ResolvedConfig } from 'vite';
3
6
  import type { Operation } from './types.js';
4
7
  declare function prepareViteApiCall(viteConfig: InlineConfig | undefined, operation: Operation): Promise<{
5
- viteConfigEnhanced: InlineConfig;
8
+ viteConfigEnhanced: InlineConfig | undefined;
6
9
  vikeConfigGlobal: import("../plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveVikeConfigGlobal.js").VikeConfigGlobal;
7
10
  }>;
11
+ declare function getViteRoot(operation: 'build' | 'dev' | 'preview' | 'prerender'): Promise<string>;
12
+ declare function normalizeViteRoot(root: string): string;
13
+ declare function assertViteRoot(root: string, config: ResolvedConfig): void;
@@ -1,38 +1,93 @@
1
1
  export { prepareViteApiCall };
2
- import { resolveConfig } from 'vite';
3
- import { pluginName } from '../plugin/plugins/commonConfig/pluginName.js';
2
+ export { getViteRoot };
3
+ export { assertViteRoot };
4
+ export { normalizeViteRoot };
5
+ // TODO: enable Vike extensions to add Vite plugins
6
+ import { loadConfigFromFile, resolveConfig } from 'vite';
4
7
  import { setOperation } from './context.js';
5
8
  import { getVikeConfig2 } from '../plugin/plugins/importUserCode/v1-design/getVikeConfig.js';
6
- async function prepareViteApiCall(viteConfig = {}, operation) {
9
+ import path from 'path';
10
+ import { assert, assertUsage, getGlobalObject, toPosixPath } from './utils.js';
11
+ import pc from '@brillout/picocolors';
12
+ const globalObject = getGlobalObject('prepareViteApiCall.ts', {});
13
+ async function prepareViteApiCall(viteConfig, operation) {
7
14
  setOperation(operation);
8
15
  return enhanceViteConfig(viteConfig, operation);
9
16
  }
10
- async function enhanceViteConfig(viteConfig = {}, operation) {
11
- let viteConfigResolved = await resolveViteConfig(viteConfig, operation);
17
+ async function enhanceViteConfig(viteConfig, operation) {
18
+ const { root, vikeVitePluginOptions, viteConfigEnhanced } = await getInfoFromVite(viteConfig, operation);
19
+ await assertViteRoot2(root, viteConfigEnhanced, operation);
20
+ const { vikeConfigGlobal } = await getVikeConfig2(root, operation === 'dev', vikeVitePluginOptions);
21
+ return {
22
+ viteConfigEnhanced,
23
+ vikeConfigGlobal
24
+ };
25
+ }
26
+ async function getViteRoot(operation) {
27
+ if (!globalObject.root)
28
+ await getInfoFromVite(undefined, operation);
29
+ assert(globalObject.root);
30
+ return globalObject.root;
31
+ }
32
+ async function getInfoFromVite(viteConfig, operation) {
33
+ const viteConfigFromFile = await loadViteConfigFile(viteConfig, operation);
34
+ const root = normalizeViteRoot(viteConfigFromFile?.root ?? viteConfig?.root ?? process.cwd());
35
+ globalObject.root = root;
36
+ let vikeVitePluginOptions;
12
37
  let viteConfigEnhanced = viteConfig;
13
- // Add vike to plugins if not present
14
- if (!viteConfigResolved.plugins.some((p) => p.name === pluginName)) {
15
- // Using a dynamic import because the script calling the Vike API may not live in the same place as vite.config.js, thus have vike/plugin may resolved to two different node_modules/vike directories
38
+ const found = findVikeVitePlugin([...(viteConfig?.plugins ?? []), ...(viteConfigFromFile?.plugins ?? [])]);
39
+ if (found) {
40
+ vikeVitePluginOptions = found.vikeVitePluginOptions;
41
+ }
42
+ else {
43
+ // Add Vike to plugins if not present.
44
+ // Using a dynamic import because the script calling the Vike API may not live in the same place as vite.config.js, thus vike/plugin may resolved to two different node_modules/vike directories.
16
45
  const { plugin: vikePlugin } = await import('../plugin/index.js');
17
46
  viteConfigEnhanced = {
18
47
  ...viteConfig,
19
- plugins: [...(viteConfig.plugins ?? []), vikePlugin()]
48
+ plugins: [...(viteConfig?.plugins ?? []), vikePlugin()]
20
49
  };
21
- viteConfigResolved = await resolveViteConfig(viteConfigEnhanced, operation);
50
+ const res = findVikeVitePlugin(viteConfigEnhanced.plugins);
51
+ assert(res);
52
+ vikeVitePluginOptions = res.vikeVitePluginOptions;
22
53
  }
23
- // TODO: use loadConfigFromFile() instead of viteConfigResolved
24
- const { vikeConfigGlobal } = await getVikeConfig2(viteConfigResolved.root, operation === 'dev', viteConfigResolved._vikeVitePluginOptions);
25
- // TODO: enable Vike extensions to add Vite plugins
26
- return {
27
- viteConfigEnhanced,
28
- vikeConfigGlobal
29
- };
54
+ assert(vikeVitePluginOptions);
55
+ return { root, vikeVitePluginOptions, viteConfigEnhanced };
30
56
  }
31
- async function resolveViteConfig(viteConfig, operation) {
32
- const args = getResolveConfigArgs(viteConfig, operation);
33
- return await resolveConfig(...args);
57
+ function findVikeVitePlugin(plugins) {
58
+ let vikeVitePluginOptions;
59
+ let vikeVitePuginFound = false;
60
+ plugins.forEach((p) => {
61
+ if (p && '__vikeVitePluginOptions' in p) {
62
+ vikeVitePuginFound = true;
63
+ const options = p.__vikeVitePluginOptions;
64
+ vikeVitePluginOptions ?? (vikeVitePluginOptions = {});
65
+ Object.assign(vikeVitePluginOptions, options);
66
+ }
67
+ });
68
+ if (!vikeVitePuginFound)
69
+ return null;
70
+ return { vikeVitePluginOptions };
71
+ }
72
+ // Copied from https://github.com/vitejs/vite/blob/4f5845a3182fc950eb9cd76d7161698383113b18/packages/vite/src/node/config.ts#L961-L1005
73
+ async function loadViteConfigFile(viteConfig, operation) {
74
+ const [inlineConfig, command, defaultMode, _defaultNodeEnv, isPreview] = getResolveConfigArgs(viteConfig, operation);
75
+ let config = inlineConfig;
76
+ let mode = inlineConfig.mode || defaultMode;
77
+ const configEnv = {
78
+ mode,
79
+ command,
80
+ isSsrBuild: command === 'build' && !!config.build?.ssr,
81
+ isPreview
82
+ };
83
+ let { configFile } = config;
84
+ if (configFile !== false) {
85
+ const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel, config.customLogger);
86
+ return loadResult?.config;
87
+ }
88
+ return null;
34
89
  }
35
- function getResolveConfigArgs(viteConfig, operation) {
90
+ function getResolveConfigArgs(viteConfig = {}, operation) {
36
91
  const inlineConfig = viteConfig;
37
92
  const command = operation === 'build' || operation === 'prerender' ? 'build' : 'serve';
38
93
  const defaultMode = operation === 'dev' ? 'development' : 'production';
@@ -40,3 +95,18 @@ function getResolveConfigArgs(viteConfig, operation) {
40
95
  const isPreview = operation === 'preview';
41
96
  return [inlineConfig, command, defaultMode, defaultNodeEnv, isPreview];
42
97
  }
98
+ function normalizeViteRoot(root) {
99
+ return toPosixPath(path.resolve(root));
100
+ }
101
+ const errMsg = `A Vite plugin is modifying Vite's setting ${pc.cyan('root')} which is forbidden`;
102
+ async function assertViteRoot2(root, viteConfigEnhanced, operation) {
103
+ const args = getResolveConfigArgs(viteConfigEnhanced, operation);
104
+ // We can eventually this resolveConfig() call (along with removing the whole assertViteRoot2() function which is redundant with the assertViteRoot() function) so that Vike doesn't make any resolveConfig() (except for pre-rendering which is required). But let's keep it for now, just to see whether calling resolveConfig() can be problematic.
105
+ const viteConfigResolved = await resolveConfig(...args);
106
+ assertUsage(normalizeViteRoot(viteConfigResolved.root) === normalizeViteRoot(root), errMsg);
107
+ }
108
+ function assertViteRoot(root, config) {
109
+ if (globalObject.root)
110
+ assert(normalizeViteRoot(globalObject.root) === normalizeViteRoot(root));
111
+ assertUsage(normalizeViteRoot(root) === normalizeViteRoot(config.root), errMsg);
112
+ }
@@ -1,2 +1,4 @@
1
1
  export * from '../../utils/assert.js';
2
2
  export * from '../../utils/getGlobalObject.js';
3
+ export * from '../../utils/filesystemPathHandling.js';
4
+ export * from '../../utils/isObject.js';
@@ -4,3 +4,5 @@ import { onLoad } from './onLoad.js';
4
4
  onLoad();
5
5
  export * from '../../utils/assert.js';
6
6
  export * from '../../utils/getGlobalObject.js';
7
+ export * from '../../utils/filesystemPathHandling.js';
8
+ export * from '../../utils/isObject.js';
@@ -31,7 +31,7 @@ markSetup_vikeVitePlugin();
31
31
  assertViteVersion();
32
32
  setResolveClientEntriesDev(resolveClientEntriesDev);
33
33
  // Return as `any` to avoid Plugin type mismatches when there are multiple Vite versions installed
34
- function plugin(vikeVitePluginOptions) {
34
+ function plugin(vikeVitePluginOptions = {}) {
35
35
  const plugins = [
36
36
  ...commonConfig(vikeVitePluginOptions),
37
37
  importUserCode(),
@@ -53,6 +53,7 @@ function plugin(vikeVitePluginOptions) {
53
53
  workaroundCssModuleHmr(),
54
54
  vite6HmrRegressionWorkaround()
55
55
  ];
56
+ Object.assign(plugins, { __vikeVitePluginOptions: vikeVitePluginOptions });
56
57
  return plugins;
57
58
  }
58
59
  // Error upon wrong usage
@@ -1,4 +1,3 @@
1
1
  export { baseUrls };
2
2
  import type { Plugin } from 'vite';
3
- import type { VikeVitePluginOptions } from './importUserCode/v1-design/getVikeConfig/resolveVikeConfigGlobal.js';
4
- declare function baseUrls(vikeVitePluginOptions?: VikeVitePluginOptions): Plugin;
3
+ declare function baseUrls(vikeVitePluginOptions: unknown): Plugin;
@@ -1,36 +1,42 @@
1
1
  export { baseUrls };
2
2
  import { resolveBase, resolveBaseFromResolvedConfig } from '../../shared/resolveBase.js';
3
3
  import { assert } from '../utils.js';
4
- import { getVikeConfig } from './importUserCode/v1-design/getVikeConfig.js';
4
+ import { getVikeConfig, getVikeConfig2 } from './importUserCode/v1-design/getVikeConfig.js';
5
+ import { assertViteRoot, getViteRoot, normalizeViteRoot } from '../../api/prepareViteApiCall.js';
5
6
  function baseUrls(vikeVitePluginOptions) {
6
- let bases;
7
+ let basesResolved;
8
+ let root;
7
9
  return {
8
10
  name: 'vike:baseUrls',
9
11
  enforce: 'post',
10
- async config(config) {
11
- // TODO: fix bug: use getVikeConfig2() and udpate check below
12
- bases = resolveBaseFromUserConfig(config, vikeVitePluginOptions);
13
- const { baseServer, baseAssets } = bases;
12
+ async config(config, env) {
13
+ const isDev = config._isDev;
14
+ assert(typeof isDev === 'boolean');
15
+ const operation = env.command === 'build' ? 'build' : env.isPreview ? 'preview' : 'dev';
16
+ root = config.root ? normalizeViteRoot(config.root) : await getViteRoot(operation);
17
+ assert(root);
18
+ const baseViteOriginal = config.base ?? '/__UNSET__'; // '/__UNSET__' because Vite resolves `_baseViteOriginal: null` to `undefined`
19
+ const vikeConfig = await getVikeConfig2(root, isDev, vikeVitePluginOptions);
20
+ basesResolved = resolveBase(baseViteOriginal, vikeConfig.vikeConfigGlobal.baseServer, vikeConfig.vikeConfigGlobal.baseAssets);
14
21
  // We cannot define these in configResolved() because Vite picks up the env variables before any configResolved() hook is called
15
- process.env.BASE_SERVER = baseServer;
16
- process.env.BASE_ASSETS = baseAssets;
22
+ process.env.BASE_SERVER = basesResolved.baseServer;
23
+ process.env.BASE_ASSETS = basesResolved.baseAssets;
17
24
  return {
18
25
  envPrefix: [
19
26
  'VITE_', // Vite doesn't seem to merge in its default, see https://github.com/vikejs/vike/issues/554
20
27
  'BASE_SERVER',
21
28
  'BASE_ASSETS'
22
29
  ],
23
- base: baseAssets, // Make Vite inject baseAssets to imports e.g. `import logoUrl from './logo.svg.js'`
24
- _baseViteOriginal: config.base ?? '/__UNSET__' // Vite resolves `_baseViteOriginal: null` to `undefined`
30
+ base: basesResolved.baseAssets, // Make Vite inject baseAssets to imports e.g. `import logoUrl from './logo.svg.js'`
31
+ _baseViteOriginal: baseViteOriginal
25
32
  };
26
33
  },
27
34
  async configResolved(config) {
35
+ assertViteRoot(root, config);
28
36
  const vikeConfig = await getVikeConfig(config);
29
- const { baseServer, baseAssets } = vikeConfig.vikeConfigGlobal;
30
- const basesResolved = resolveBaseFromResolvedConfig(baseServer, baseAssets, config);
31
- // Ensure that the premature base URL resolving we did in config() isn't erroneous
32
- assert(basesResolved.baseServer === bases.baseServer);
33
- assert(basesResolved.baseAssets === bases.baseAssets);
37
+ const basesResolved2 = resolveBaseFromResolvedConfig(vikeConfig.vikeConfigGlobal.baseServer, vikeConfig.vikeConfigGlobal.baseAssets, config);
38
+ assert(basesResolved2.baseServer === basesResolved.baseServer);
39
+ assert(basesResolved2.baseAssets === basesResolved.baseAssets);
34
40
  /* In dev, Vite seems buggy around setting vite.config.js#base to an absolute URL (e.g. http://localhost:8080/cdn/)
35
41
  * - In dev, Vite removes the URL origin. (I.e. it resolves the user config `vite.config.js#base: 'http://localhost:8080/cdn/'` to resolved config `config.base === '/cdn/'`.)
36
42
  * - Instead of having an internal Vike assertion fail, we let the user discover Vite's buggy behavior.
@@ -39,7 +45,3 @@ function baseUrls(vikeVitePluginOptions) {
39
45
  }
40
46
  };
41
47
  }
42
- function resolveBaseFromUserConfig(config, vikeVitePluginOptions) {
43
- const baseViteOriginal = config.base ?? null;
44
- return resolveBase(baseViteOriginal, vikeVitePluginOptions?.baseServer ?? null, vikeVitePluginOptions?.baseAssets ?? null);
45
- }
@@ -1,3 +1,9 @@
1
1
  export { commonConfig };
2
2
  import { type Plugin } from 'vite';
3
- declare function commonConfig(vikeVitePluginOptions?: unknown): Plugin[];
3
+ declare module 'vite' {
4
+ interface UserConfig {
5
+ _isDev?: boolean;
6
+ _vikeVitePluginOptions?: unknown;
7
+ }
8
+ }
9
+ declare function commonConfig(vikeVitePluginOptions: unknown): Plugin[];
@@ -6,11 +6,11 @@ import { installRequireShim_setUserRootDir } from '@brillout/require-shim';
6
6
  import pc from '@brillout/picocolors';
7
7
  import path from 'path';
8
8
  import { assertResolveAlias } from './commonConfig/assertResolveAlias.js';
9
- import { pluginName } from './commonConfig/pluginName.js';
10
9
  import { getEnvVarObject } from '../shared/getEnvVarObject.js';
11
10
  import { isViteCliCall } from '../shared/isViteCliCall.js';
12
11
  import { isVikeCliOrApi } from '../../api/context.js';
13
- function commonConfig(vikeVitePluginOptions = {}) {
12
+ const pluginName = 'vike:commonConfig';
13
+ function commonConfig(vikeVitePluginOptions) {
14
14
  return [
15
15
  {
16
16
  name: `${pluginName}:pre`,
@@ -1,4 +1,4 @@
1
1
  export { crawlPlusFiles };
2
- declare function crawlPlusFiles(userRootDir: string, outDirAbsoluteFilesystem: null | string, crawlWithGit: null | boolean): Promise<{
2
+ declare function crawlPlusFiles(userRootDir: string, outDirAbsoluteFilesystem: null | string): Promise<{
3
3
  filePathAbsoluteUserRootDir: string;
4
4
  }[]>;
@@ -1,17 +1,16 @@
1
1
  export { crawlPlusFiles };
2
- import { assertPosixPath, assert, scriptFileExtensions, assertIsSingleModuleInstance, assertIsNotProductionRuntime, isVersionOrAbove, isScriptFile } from '../../../../utils.js';
2
+ import { assertPosixPath, assert, scriptFileExtensions, assertIsSingleModuleInstance, assertIsNotProductionRuntime, isVersionOrAbove, isScriptFile, scriptFileExtensionList } from '../../../../utils.js';
3
3
  import path from 'path';
4
- import fs from 'fs/promises';
5
4
  import glob from 'fast-glob';
6
5
  import { exec } from 'child_process';
7
6
  import { promisify } from 'util';
8
7
  import { isTemporaryBuildFile } from './transpileAndExecuteFile.js';
8
+ import { getEnvVarObject } from '../../../../shared/getEnvVarObject.js';
9
9
  const execA = promisify(exec);
10
- const TOO_MANY_UNTRACKED_FILES = 5;
11
10
  assertIsNotProductionRuntime();
12
11
  assertIsSingleModuleInstance('crawlPlusFiles.ts');
13
12
  let gitIsNotUsable = false;
14
- async function crawlPlusFiles(userRootDir, outDirAbsoluteFilesystem, crawlWithGit) {
13
+ async function crawlPlusFiles(userRootDir, outDirAbsoluteFilesystem) {
15
14
  assertPosixPath(userRootDir);
16
15
  //*/
17
16
  const outDirRelativeFromUserRootDir = null;
@@ -31,14 +30,13 @@ async function crawlPlusFiles(userRootDir, outDirAbsoluteFilesystem, crawlWithGi
31
30
  //
32
31
  !outDirRelativeFromUserRootDir.startsWith('../')));
33
32
  // Crawl
34
- let files = [];
35
- const res = crawlWithGit !== false && (await gitLsFiles(userRootDir, outDirRelativeFromUserRootDir));
33
+ let files;
34
+ const res = !isGitCrawlDisabled() && (await gitLsFiles(userRootDir, outDirRelativeFromUserRootDir));
36
35
  if (res &&
37
36
  // Fallback to fast-glob for users that dynamically generate plus files. (Assuming that no plus file is found because of the user's .gitignore list.)
38
- res.files.length > 0) {
39
- files = res.files;
37
+ res.length > 0) {
38
+ files = res;
40
39
  // We cannot find files inside symlink directories with `$ git ls-files` => we use fast-glob
41
- files.push(...(await crawlSymlinkDirs(res.symlinkDirs, userRootDir, outDirRelativeFromUserRootDir)));
42
40
  }
43
41
  else {
44
42
  files = await fastGlob(userRootDir, outDirRelativeFromUserRootDir);
@@ -70,24 +68,21 @@ async function gitLsFiles(userRootDir, outDirRelativeFromUserRootDir) {
70
68
  'git',
71
69
  preserveUTF8,
72
70
  'ls-files',
73
- // We don't filter because:
74
- // - It would skip symlink directories
75
- // - Performance gain seems negligible: https://github.com/vikejs/vike/pull/1688#issuecomment-2166206648
76
- // ...scriptFileExtensionList.map((ext) => `"**/+*.${ext}"`),
71
+ // Performance gain seems negligible: https://github.com/vikejs/vike/pull/1688#issuecomment-2166206648
72
+ ...scriptFileExtensionList.map((ext) => `"**/+*.${ext}"`),
77
73
  // Performance gain is non-negligible.
78
74
  // - https://github.com/vikejs/vike/pull/1688#issuecomment-2166206648
79
75
  // - When node_modules/ is untracked the performance gain could be significant?
80
76
  ...ignoreAsPatterns.map((pattern) => `--exclude="${pattern}"`),
81
77
  // --others --exclude-standard => list untracked files (--others) while using .gitignore (--exclude-standard)
82
78
  // --cached => list tracked files
83
- // --stage => get file modes which we use to find symlink directories
84
- '--others --exclude-standard --cached --stage'
79
+ '--others --exclude-standard --cached'
85
80
  ].join(' ');
86
- let resultLines;
81
+ let filesAll;
87
82
  let filesDeleted;
88
83
  try {
89
84
  ;
90
- [resultLines, filesDeleted] = await Promise.all([
85
+ [filesAll, filesDeleted] = await Promise.all([
91
86
  // Main command
92
87
  runCmd1(cmd, userRootDir),
93
88
  // Get tracked but deleted files
@@ -101,40 +96,23 @@ async function gitLsFiles(userRootDir, outDirRelativeFromUserRootDir) {
101
96
  }
102
97
  throw err;
103
98
  }
104
- const filePaths = resultLines.map(parseGitLsResultLine);
105
- // If there are too many files without mode we fallback to fast-glob
106
- if (filePaths.filter((f) => !f.mode).length > TOO_MANY_UNTRACKED_FILES)
107
- return null;
108
- const symlinkDirs = [];
109
99
  const files = [];
110
- for (const { filePath, mode } of filePaths) {
111
- // Deleted?
112
- if (filesDeleted.includes(filePath))
100
+ for (const filePath of filesAll) {
101
+ // + file?
102
+ if (!path.posix.basename(filePath).startsWith('+'))
113
103
  continue;
114
104
  // We have to repeat the same exclusion logic here because the option --exclude of `$ git ls-files` only applies to untracked files. (We use --exclude only to speed up the `$ git ls-files` command.)
115
105
  if (!ignoreAsFilterFn(filePath))
116
106
  continue;
117
- // Symlink directory?
118
- {
119
- const isSymlinkDir = await isSymlinkDirectory(mode, filePath, userRootDir);
120
- if (isSymlinkDir) {
121
- symlinkDirs.push(filePath);
122
- continue;
123
- }
124
- // Skip deleted files and non-symlink directories
125
- if (isSymlinkDir === null) {
126
- continue;
127
- }
128
- }
129
- // + file?
130
- if (!path.posix.basename(filePath).startsWith('+'))
131
- continue;
132
107
  // JavaScript file?
133
108
  if (!isScriptFile(filePath))
134
109
  continue;
110
+ // Deleted?
111
+ if (filesDeleted.includes(filePath))
112
+ continue;
135
113
  files.push(filePath);
136
114
  }
137
- return { files, symlinkDirs };
115
+ return files;
138
116
  }
139
117
  // Same as gitLsFiles() but using fast-glob
140
118
  async function fastGlob(userRootDir, outDirRelativeFromUserRootDir) {
@@ -204,77 +182,6 @@ async function isGitNotUsable(userRootDir) {
204
182
  return false;
205
183
  }
206
184
  }
207
- async function crawlSymlinkDirs(symlinkDirs, userRootDir, outDirRelativeFromUserRootDir) {
208
- const filesInSymlinkDirs = (await Promise.all(symlinkDirs.map(async (symlinkDir) => (await fastGlob(path.posix.join(userRootDir, symlinkDir), outDirRelativeFromUserRootDir)).map((filePath) => path.posix.join(symlinkDir, filePath))))).flat();
209
- return filesInSymlinkDirs;
210
- }
211
- // Parse:
212
- // ```
213
- // some/not/tracked/path
214
- // 100644 f6928073402b241b468b199893ff6f4aed0b7195 0\tpages/index/+Page.tsx
215
- // ```
216
- function parseGitLsResultLine(resultLine) {
217
- const [part1, part2, ...rest] = resultLine.split('\t');
218
- assert(part1);
219
- assert(rest.length === 0);
220
- // Git doesn't provide the mode for untracked paths.
221
- // `resultLine` is:
222
- // ```
223
- // some/not/tracked/path
224
- // ```
225
- if (part2 === undefined) {
226
- return { filePath: part1, mode: null };
227
- }
228
- assert(part2);
229
- // `resultLine` is:
230
- // ```
231
- // 100644 f6928073402b241b468b199893ff6f4aed0b7195 0\tpages/index/+Page.tsx
232
- // ```
233
- const [mode, _, __, ...rest2] = part1.split(' ');
234
- assert(mode && _ && __ && rest2.length === 0);
235
- return { filePath: part2, mode };
236
- }
237
- async function isSymlinkDirectory(mode, filePath, userRootDir) {
238
- const filePathAbsolute = path.posix.join(userRootDir, filePath);
239
- let stats = null;
240
- let isSymlink = false;
241
- if (mode === '120000') {
242
- isSymlink = true;
243
- }
244
- else if (mode === null) {
245
- // `$ git ls-files` doesn't provide the mode when Git doesn't track the path
246
- stats = await getFileStats(filePathAbsolute);
247
- if (stats === null)
248
- return null;
249
- isSymlink = stats.isSymbolicLink();
250
- if (!isSymlink && stats.isDirectory())
251
- return null;
252
- }
253
- else {
254
- assert(mode);
255
- }
256
- if (!isSymlink)
257
- return false;
258
- if (!stats)
259
- stats = await getFileStats(filePathAbsolute);
260
- if (stats === null)
261
- return null;
262
- const isDirectory = stats.isDirectory();
263
- return isDirectory;
264
- }
265
- async function getFileStats(filePathAbsolute) {
266
- let stats;
267
- try {
268
- stats = await fs.lstat(filePathAbsolute);
269
- }
270
- catch (err) {
271
- // File was deleted, usually a temporary file such as +config.js.build-j95xb988fpln.mjs
272
- // ENOENT: no such file or directory
273
- assert(err.code === 'ENOENT');
274
- return null;
275
- }
276
- return stats;
277
- }
278
185
  async function runCmd1(cmd, cwd) {
279
186
  const { stdout } = await execA(cmd, {
280
187
  cwd,
@@ -299,3 +206,7 @@ async function runCmd2(cmd, cwd) {
299
206
  stderr = stderr.toString().trim();
300
207
  return { stdout, stderr };
301
208
  }
209
+ function isGitCrawlDisabled() {
210
+ const crawSettings = getEnvVarObject('VIKE_CRAWL');
211
+ return crawSettings?.git === false;
212
+ }
@@ -78,6 +78,7 @@ async function getVikeConfig(config, { doNotRestartViteOnError } = {}) {
78
78
  return await getVikeConfigEntry(userRootDir, isDev, vikeVitePluginOptions, doNotRestartViteOnError ?? false);
79
79
  }
80
80
  async function getVikeConfig2(userRootDir, isDev, vikeVitePluginOptions) {
81
+ assert(vikeVitePluginOptions);
81
82
  return await getVikeConfigEntry(userRootDir, isDev, vikeVitePluginOptions, false);
82
83
  }
83
84
  async function getVikeConfigEntry(userRootDir, isDev, vikeVitePluginOptions, doNotRestartViteOnError) {
@@ -92,8 +93,8 @@ async function isV1Design(config) {
92
93
  const isV1Design = pageConfigs.length > 0;
93
94
  return isV1Design;
94
95
  }
95
- async function loadInterfaceFiles(userRootDir, crawlWithGit) {
96
- const plusFiles = await findPlusFiles(userRootDir, null, crawlWithGit);
96
+ async function loadInterfaceFiles(userRootDir) {
97
+ const plusFiles = await findPlusFiles(userRootDir, null);
97
98
  const configFiles = [];
98
99
  const valueFiles = [];
99
100
  plusFiles.forEach((f) => {
@@ -245,8 +246,7 @@ async function loadVikeConfig_withErrorHandling(userRootDir, isDev, vikeVitePlug
245
246
  }
246
247
  }
247
248
  async function loadVikeConfig(userRootDir, vikeVitePluginOptions) {
248
- const crawlWithGit = resolveVikeConfigGlobal(vikeVitePluginOptions, {}).crawl.git ?? null;
249
- const interfaceFilesByLocationId = await loadInterfaceFiles(userRootDir, crawlWithGit);
249
+ const interfaceFilesByLocationId = await loadInterfaceFiles(userRootDir);
250
250
  const importedFilesLoaded = {};
251
251
  const { pageConfigGlobal, pageConfigGlobalValues } = await getGlobalConfigs(interfaceFilesByLocationId, userRootDir, importedFilesLoaded);
252
252
  const vikeConfigGlobal = resolveVikeConfigGlobal(vikeVitePluginOptions, pageConfigGlobalValues);
@@ -793,8 +793,8 @@ function getComputed(configValueSources, configDefinitions) {
793
793
  });
794
794
  return configValuesComputed;
795
795
  }
796
- async function findPlusFiles(userRootDir, outDirRoot, crawlWithGit) {
797
- const files = await crawlPlusFiles(userRootDir, outDirRoot, crawlWithGit);
796
+ async function findPlusFiles(userRootDir, outDirRoot) {
797
+ const files = await crawlPlusFiles(userRootDir, outDirRoot);
798
798
  const plusFiles = files.map(({ filePathAbsoluteUserRootDir }) => getFilePathResolved({ filePathAbsoluteUserRootDir, userRootDir }));
799
799
  return plusFiles;
800
800
  }
@@ -1,2 +1,2 @@
1
1
  export { getEnvVarObject };
2
- declare function getEnvVarObject(envVarName: 'VITE_CONFIG'): null | Record<string, unknown>;
2
+ declare function getEnvVarObject(envVarName: 'VITE_CONFIG' | 'VIKE_CRAWL'): null | Record<string, unknown>;
@@ -30,5 +30,5 @@ declare function runPrerenderFromAPI(options?: PrerenderOptions): Promise<{
30
30
  viteConfig: ResolvedConfig;
31
31
  }>;
32
32
  declare function runPrerenderFromCLIPrerenderCommand(): Promise<void>;
33
- declare function runPrerenderFromAutoRun(viteConfig: InlineConfig, forceExit: boolean): Promise<void>;
33
+ declare function runPrerenderFromAutoRun(viteConfig: InlineConfig | undefined, forceExit: boolean): Promise<void>;
34
34
  declare function runPrerender_forceExit(): void;
@@ -68,7 +68,7 @@ async function runPrerender(options = {}, standaloneTrigger) {
68
68
  console.log(`${pc.cyan(`vike v${projectInfo.projectVersion}`)} ${pc.green('pre-rendering HTML...')}`);
69
69
  }
70
70
  await disableReactStreaming();
71
- const viteConfig = await resolveConfig(options.viteConfig || {}, 'vike pre-rendering', 'production');
71
+ const viteConfig = await resolveConfig(options.viteConfig || {}, 'build', 'production');
72
72
  assertLoadedConfig(viteConfig, options);
73
73
  const vikeConfig = await getVikeConfig(viteConfig);
74
74
  const { outDirClient } = getOutDirs(viteConfig);
@@ -4,12 +4,12 @@ import { assert, assertUsage, isBaseServer, isBaseAssets } from './utils.js';
4
4
  import pc from '@brillout/picocolors';
5
5
  function resolveBaseFromResolvedConfig(baseServer, baseAssets, config) {
6
6
  let baseViteOriginal = config._baseViteOriginal;
7
- if (baseViteOriginal === '/__UNSET__')
8
- baseViteOriginal = null;
9
7
  assert(baseViteOriginal === null || typeof baseViteOriginal == 'string');
10
8
  return resolveBase(baseViteOriginal, baseServer, baseAssets);
11
9
  }
12
10
  function resolveBase(baseViteOriginal, baseServerUnresolved, baseAssetsUnresolved) {
11
+ if (baseViteOriginal === '/__UNSET__')
12
+ baseViteOriginal = null;
13
13
  {
14
14
  const wrongBase = (val) => `should start with ${pc.cyan('/')}, ${pc.cyan('http://')}, or ${pc.cyan('https://')} (it's ${pc.cyan(val)} instead)`;
15
15
  assertUsage(baseViteOriginal === null || isBaseAssets(baseViteOriginal), `vite.config.js#base ${wrongBase(baseViteOriginal)}`);
@@ -1 +1 @@
1
- export declare const PROJECT_VERSION: "0.4.217";
1
+ export declare const PROJECT_VERSION: "0.4.218";
@@ -1,2 +1,2 @@
1
1
  // Automatically updated by @brillout/release-me
2
- export const PROJECT_VERSION = '0.4.217';
2
+ export const PROJECT_VERSION = '0.4.218';
@@ -1,4 +1,4 @@
1
1
  export declare const projectInfo: {
2
2
  projectName: "Vike";
3
- projectVersion: "0.4.217";
3
+ projectVersion: "0.4.218";
4
4
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vike",
3
- "version": "0.4.217",
3
+ "version": "0.4.218",
4
4
  "repository": "https://github.com/vikejs/vike",
5
5
  "exports": {
6
6
  "./server": {
@@ -1,4 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.pluginName = void 0;
4
- exports.pluginName = 'vike:commonConfig';
@@ -1 +0,0 @@
1
- export declare const pluginName = "vike:commonConfig";
@@ -1 +0,0 @@
1
- export const pluginName = 'vike:commonConfig';