vite 5.0.0-beta.2 → 5.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { D as getDefaultExportFromCjs } from './dep-82f73734.js';
1
+ import { D as getDefaultExportFromCjs } from './dep-69dc786c.js';
2
2
  import require$$0 from 'path';
3
3
  import require$$0__default from 'fs';
4
4
  import { l as lib } from './dep-c423598f.js';
@@ -1,4 +1,4 @@
1
- import { E as commonjsGlobal, D as getDefaultExportFromCjs } from './dep-82f73734.js';
1
+ import { E as commonjsGlobal, D as getDefaultExportFromCjs } from './dep-69dc786c.js';
2
2
  import require$$0__default from 'fs';
3
3
  import require$$0 from 'postcss';
4
4
  import require$$0$1 from 'path';
package/dist/node/cli.js CHANGED
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import fs from 'node:fs';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { EventEmitter } from 'events';
5
- import { C as colors, x as createLogger, h as resolveConfig } from './chunks/dep-82f73734.js';
5
+ import { C as colors, x as createLogger, h as resolveConfig } from './chunks/dep-69dc786c.js';
6
6
  import { VERSION } from './constants.js';
7
7
  import 'node:fs/promises';
8
8
  import 'node:url';
@@ -27,10 +27,10 @@ import 'node:dns';
27
27
  import 'crypto';
28
28
  import 'node:buffer';
29
29
  import 'module';
30
+ import 'rollup';
30
31
  import 'node:assert';
31
32
  import 'node:process';
32
33
  import 'node:v8';
33
- import 'rollup';
34
34
  import 'node:http';
35
35
  import 'node:https';
36
36
  import 'zlib';
@@ -40,6 +40,7 @@ import 'tls';
40
40
  import 'worker_threads';
41
41
  import 'querystring';
42
42
  import 'node:readline';
43
+ import 'node:events';
43
44
  import 'node:zlib';
44
45
 
45
46
  function toArr(any) {
@@ -758,7 +759,7 @@ cli
758
759
  filterDuplicateOptions(options);
759
760
  // output structure is preserved even after bundling so require()
760
761
  // is ok here
761
- const { createServer } = await import('./chunks/dep-82f73734.js').then(function (n) { return n.H; });
762
+ const { createServer } = await import('./chunks/dep-69dc786c.js').then(function (n) { return n.H; });
762
763
  try {
763
764
  const server = await createServer({
764
765
  root,
@@ -779,7 +780,10 @@ cli
779
780
  const startupDurationString = viteStartTime
780
781
  ? colors.dim(`ready in ${colors.reset(colors.bold(Math.ceil(performance.now() - viteStartTime)))} ms`)
781
782
  : '';
782
- info(`\n ${colors.green(`${colors.bold('VITE')} v${VERSION}`)} ${startupDurationString}\n`, { clear: !server.config.logger.hasWarned });
783
+ info(`\n ${colors.green(`${colors.bold('VITE')} v${VERSION}`)} ${startupDurationString}\n`, {
784
+ clear: !server.config.logger.hasWarned &&
785
+ !globalThis.__vite_cjs_skip_clear_screen,
786
+ });
783
787
  server.printUrls();
784
788
  server.bindCLIShortcuts({
785
789
  print: true,
@@ -836,7 +840,7 @@ cli
836
840
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
837
841
  .action(async (root, options) => {
838
842
  filterDuplicateOptions(options);
839
- const { build } = await import('./chunks/dep-82f73734.js').then(function (n) { return n.G; });
843
+ const { build } = await import('./chunks/dep-69dc786c.js').then(function (n) { return n.G; });
840
844
  const buildOptions = cleanOptions(options);
841
845
  try {
842
846
  await build({
@@ -864,7 +868,7 @@ cli
864
868
  .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
865
869
  .action(async (root, options) => {
866
870
  filterDuplicateOptions(options);
867
- const { optimizeDeps } = await import('./chunks/dep-82f73734.js').then(function (n) { return n.F; });
871
+ const { optimizeDeps } = await import('./chunks/dep-69dc786c.js').then(function (n) { return n.F; });
868
872
  try {
869
873
  const config = await resolveConfig({
870
874
  root,
@@ -891,7 +895,7 @@ cli
891
895
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
892
896
  .action(async (root, options) => {
893
897
  filterDuplicateOptions(options);
894
- const { preview } = await import('./chunks/dep-82f73734.js').then(function (n) { return n.I; });
898
+ const { preview } = await import('./chunks/dep-69dc786c.js').then(function (n) { return n.I; });
895
899
  try {
896
900
  const server = await preview({
897
901
  root,
@@ -225,8 +225,11 @@ export declare interface BuildOptions {
225
225
  /**
226
226
  * Options for terser
227
227
  * https://terser.org/docs/api-reference#minify-options
228
+ *
229
+ * In addition, you can also pass a `maxWorkers: number` option to specify the
230
+ * max number of workers to spawn. Defaults to the number of CPUs minus 1.
228
231
  */
229
- terserOptions?: Terser.MinifyOptions;
232
+ terserOptions?: TerserOptions;
230
233
  /**
231
234
  * Will be merged with internal rollup options.
232
235
  * https://rollupjs.org/configuration-options/
@@ -256,7 +259,7 @@ export declare interface BuildOptions {
256
259
  */
257
260
  copyPublicDir?: boolean;
258
261
  /**
259
- * Whether to emit a manifest.json under assets dir to map hash-less filenames
262
+ * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
260
263
  * to their hashed versions. Useful when you want to generate your own HTML
261
264
  * instead of using the one generated by Vite.
262
265
  *
@@ -728,8 +731,6 @@ export declare interface DepsOptimizer {
728
731
  }
729
732
 
730
733
  declare interface Drafts {
731
- /** Whether to enable CSS nesting. */
732
- nesting?: boolean,
733
734
  /** Whether to enable @custom-media rules. */
734
735
  customMedia?: boolean
735
736
  }
@@ -791,32 +792,6 @@ export declare type ExportsData = {
791
792
  jsxLoader?: boolean;
792
793
  };
793
794
 
794
- declare const enum Features {
795
- Nesting = 1,
796
- NotSelectorList = 2,
797
- DirSelector = 4,
798
- LangSelectorList = 8,
799
- IsSelector = 16,
800
- TextDecorationThicknessPercent = 32,
801
- MediaIntervalSyntax = 64,
802
- MediaRangeSyntax = 128,
803
- CustomMediaQueries = 256,
804
- ClampFunction = 512,
805
- ColorFunction = 1024,
806
- OklabColors = 2048,
807
- LabColors = 4096,
808
- P3Colors = 8192,
809
- HexAlphaColors = 16384,
810
- SpaceSeparatedColorNotation = 32768,
811
- FontFamilySystemUi = 65536,
812
- DoublePositionGradients = 131072,
813
- VendorPrefixes = 262144,
814
- LogicalProperties = 524288,
815
- Selectors = 31,
816
- MediaQueries = 448,
817
- Colors = 64512,
818
- }
819
-
820
795
  export declare interface FileSystemServeOptions {
821
796
  /**
822
797
  * Strictly restrict file accessing outside of allowing paths.
@@ -1297,14 +1272,6 @@ export declare interface JsonOptions {
1297
1272
  export { KnownAsTypeMap }
1298
1273
 
1299
1274
  export declare interface LegacyOptions {
1300
- /**
1301
- * Revert vite build --ssr to the v2.9 strategy. Use CJS SSR build and v2.9 externalization heuristics
1302
- *
1303
- * @experimental
1304
- * @deprecated
1305
- * @default false
1306
- */
1307
- buildSsrCjsExternalHeuristics?: boolean;
1308
1275
  }
1309
1276
 
1310
1277
  export declare type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife';
@@ -1338,8 +1305,8 @@ export declare interface LibraryOptions {
1338
1305
  */
1339
1306
  export declare type LightningCSSOptions = {
1340
1307
  targets?: Targets
1341
- include?: Features
1342
- exclude?: Features
1308
+ include?: number
1309
+ exclude?: number
1343
1310
  drafts?: Drafts
1344
1311
  nonStandard?: NonStandard
1345
1312
  pseudoClasses?: PseudoClasses
@@ -1559,7 +1526,7 @@ export declare interface PackageData {
1559
1526
  * If a plugin should be applied only for server or build, a function format
1560
1527
  * config file can be used to conditional determine the plugins to use.
1561
1528
  */
1562
- declare interface Plugin_2 extends Plugin_3 {
1529
+ declare interface Plugin_2<A = any> extends Plugin_3<A> {
1563
1530
  /**
1564
1531
  * Enforce plugin invocation tier similar to webpack loaders.
1565
1532
  *
@@ -1860,7 +1827,6 @@ export declare interface ResolvedServerUrls {
1860
1827
 
1861
1828
  export declare interface ResolvedSSROptions extends SSROptions {
1862
1829
  target: SSRTarget;
1863
- format: SSRFormat;
1864
1830
  optimizeDeps: SsrDepOptimizationOptions;
1865
1831
  }
1866
1832
 
@@ -2195,10 +2161,10 @@ export declare interface ServerOptions extends CommonServerOptions {
2195
2161
  */
2196
2162
  hmr?: HmrOptions | boolean;
2197
2163
  /**
2198
- * chokidar watch options
2164
+ * chokidar watch options or null to disable FS watching
2199
2165
  * https://github.com/paulmillr/chokidar#api
2200
2166
  */
2201
- watch?: WatchOptions;
2167
+ watch?: WatchOptions | null;
2202
2168
  /**
2203
2169
  * Create Vite dev server to be used as a middleware in an existing server
2204
2170
  * @default false
@@ -2253,8 +2219,6 @@ export declare function splitVendorChunkPlugin(): Plugin_2;
2253
2219
 
2254
2220
  export declare type SsrDepOptimizationOptions = DepOptimizationConfig;
2255
2221
 
2256
- export declare type SSRFormat = 'esm' | 'cjs';
2257
-
2258
2222
  export declare interface SSROptions {
2259
2223
  noExternal?: string | RegExp | (string | RegExp)[] | true;
2260
2224
  external?: string[];
@@ -2264,16 +2228,6 @@ export declare interface SSROptions {
2264
2228
  * @default 'node'
2265
2229
  */
2266
2230
  target?: SSRTarget;
2267
- /**
2268
- * Define the format for the ssr build. Since Vite v3 the SSR build generates ESM by default.
2269
- * `'cjs'` can be selected to generate a CJS build, but it isn't recommended. This option is
2270
- * left marked as experimental to give users more time to update to ESM. CJS builds requires
2271
- * complex externalization heuristics that aren't present in the ESM format.
2272
- * @experimental
2273
- * @deprecated
2274
- * @default 'esm'
2275
- */
2276
- format?: SSRFormat;
2277
2231
  /**
2278
2232
  * Control over which dependencies are optimized during SSR and esbuild options
2279
2233
  * During build:
@@ -2514,6 +2468,16 @@ export declare namespace Terser {
2514
2468
  }
2515
2469
  }
2516
2470
 
2471
+ export declare interface TerserOptions extends Terser.MinifyOptions {
2472
+ /**
2473
+ * Vite-specific option to specify the max number of workers to spawn
2474
+ * when minifying files with terser.
2475
+ *
2476
+ * @default number of CPUs minus 1
2477
+ */
2478
+ maxWorkers?: number;
2479
+ }
2480
+
2517
2481
  export declare interface TransformOptions {
2518
2482
  ssr?: boolean;
2519
2483
  html?: boolean;
@@ -2802,7 +2766,6 @@ export declare interface ViteDevServer {
2802
2766
  */
2803
2767
  openBrowser(): void;
2804
2768
  /* Excluded from this release type: _importGlobMap */
2805
- /* Excluded from this release type: _ssrExternals */
2806
2769
  /* Excluded from this release type: _restartPromise */
2807
2770
  /* Excluded from this release type: _forceOptimizeOnRestart */
2808
2771
  /* Excluded from this release type: _pendingRequests */
@@ -1,5 +1,5 @@
1
- import { i as isInNodeModules } from './chunks/dep-82f73734.js';
2
- export { b as build, e as buildErrorMessage, v as createFilter, x as createLogger, c as createServer, g as defineConfig, f as formatPostcssSourceMap, k as getDepOptimizationConfig, m as isDepsOptimizerEnabled, z as isFileServingAllowed, l as loadConfigFromFile, A as loadEnv, u as mergeAlias, q as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, j as resolveBaseUrl, h as resolveConfig, B as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, y as searchForWorkspaceRoot, w as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-82f73734.js';
1
+ import { i as isInNodeModules } from './chunks/dep-69dc786c.js';
2
+ export { b as build, e as buildErrorMessage, v as createFilter, x as createLogger, c as createServer, g as defineConfig, f as formatPostcssSourceMap, k as getDepOptimizationConfig, m as isDepsOptimizerEnabled, z as isFileServingAllowed, l as loadConfigFromFile, A as loadEnv, u as mergeAlias, q as mergeConfig, n as normalizePath, o as optimizeDeps, a as preprocessCSS, p as preview, j as resolveBaseUrl, h as resolveConfig, B as resolveEnvPrefix, d as resolvePackageData, r as resolvePackageEntry, y as searchForWorkspaceRoot, w as send, s as sortUserPlugins, t as transformWithEsbuild } from './chunks/dep-69dc786c.js';
3
3
  export { VERSION as version } from './constants.js';
4
4
  export { version as esbuildVersion } from 'esbuild';
5
5
  export { VERSION as rollupVersion } from 'rollup';
@@ -41,6 +41,7 @@ import 'tls';
41
41
  import 'worker_threads';
42
42
  import 'querystring';
43
43
  import 'node:readline';
44
+ import 'node:events';
44
45
  import 'node:zlib';
45
46
 
46
47
  // This file will be built for both ESM and CJS. Avoid relying on other modules as possible.
@@ -15,7 +15,8 @@ var fs$2 = require('fs');
15
15
  var readline = require('node:readline');
16
16
  var require$$2 = require('os');
17
17
 
18
- const { version: version$2 } = JSON.parse(fs$1.readFileSync(new URL('../../package.json', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString());
18
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
19
+ const { version: version$2 } = JSON.parse(fs$1.readFileSync(new URL('../../package.json', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString());
19
20
  const VERSION = version$2;
20
21
  /**
21
22
  * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
@@ -23,32 +24,11 @@ const VERSION = version$2;
23
24
  const FS_PREFIX = `/@fs/`;
24
25
  const VITE_PACKAGE_DIR = path$3.resolve(
25
26
  // import.meta.url is `dist/node/constants.js` after bundle
26
- node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))), '../../..');
27
+ node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))), '../../..');
27
28
  const CLIENT_ENTRY = path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs');
28
29
  path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/env.mjs');
29
30
  path$3.dirname(CLIENT_ENTRY);
30
31
 
31
- const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
32
- const intToChar$1 = new Uint8Array(64); // 64 possible chars.
33
- const charToInt$1 = new Uint8Array(128); // z is 122 in ASCII
34
- for (let i = 0; i < chars$1.length; i++) {
35
- const c = chars$1.charCodeAt(i);
36
- intToChar$1[i] = c;
37
- charToInt$1[c] = i;
38
- }
39
-
40
- // Matches the scheme of a URL, eg "http://"
41
- var UrlType;
42
- (function (UrlType) {
43
- UrlType[UrlType["Empty"] = 1] = "Empty";
44
- UrlType[UrlType["Hash"] = 2] = "Hash";
45
- UrlType[UrlType["Query"] = 3] = "Query";
46
- UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
47
- UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
48
- UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
49
- UrlType[UrlType["Absolute"] = 7] = "Absolute";
50
- })(UrlType || (UrlType = {}));
51
-
52
32
  const comma = ','.charCodeAt(0);
53
33
  const semicolon = ';'.charCodeAt(0);
54
34
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
@@ -137,6 +117,18 @@ function encodeInteger(buf, pos, state, segment, j) {
137
117
  return pos;
138
118
  }
139
119
 
120
+ // Matches the scheme of a URL, eg "http://"
121
+ var UrlType;
122
+ (function (UrlType) {
123
+ UrlType[UrlType["Empty"] = 1] = "Empty";
124
+ UrlType[UrlType["Hash"] = 2] = "Hash";
125
+ UrlType[UrlType["Query"] = 3] = "Query";
126
+ UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
127
+ UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
128
+ UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
129
+ UrlType[UrlType["Absolute"] = 7] = "Absolute";
130
+ })(UrlType || (UrlType = {}));
131
+
140
132
  function getDefaultExportFromCjs (x) {
141
133
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
142
134
  }
@@ -3311,7 +3303,7 @@ const normalizePath$1 = function normalizePath(filename) {
3311
3303
  };
3312
3304
 
3313
3305
  function getMatcherString(id, resolutionBase) {
3314
- if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('*')) {
3306
+ if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('**')) {
3315
3307
  return normalizePath$1(id);
3316
3308
  }
3317
3309
  // resolve('') is valid and will default to process.cwd()
@@ -3366,7 +3358,7 @@ forbiddenIdentifiers.add('');
3366
3358
 
3367
3359
  if (process.versions.pnp) {
3368
3360
  try {
3369
- node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))('pnpapi');
3361
+ node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))('pnpapi');
3370
3362
  }
3371
3363
  catch { }
3372
3364
  }
@@ -3376,11 +3368,13 @@ const windowsSlashRE = /\\/g;
3376
3368
  function slash(p) {
3377
3369
  return p.replace(windowsSlashRE, '/');
3378
3370
  }
3371
+ // Some runtimes like Bun injects namespaced modules here, which is not a node builtin
3372
+ node_module.builtinModules.filter((id) => !id.includes(':'));
3379
3373
  function isInNodeModules(id) {
3380
3374
  return id.includes('node_modules');
3381
3375
  }
3382
3376
  // TODO: use import()
3383
- const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)));
3377
+ const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)));
3384
3378
  // set in bin/vite.js
3385
3379
  const filter = process.env.VITE_DEBUG_FILTER;
3386
3380
  const DEBUG = process.env.DEBUG;
@@ -3470,6 +3464,7 @@ function isObject$1(value) {
3470
3464
  }
3471
3465
  function tryStatSync(file) {
3472
3466
  try {
3467
+ // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
3473
3468
  return fs$1.statSync(file, { throwIfNoEntry: false });
3474
3469
  }
3475
3470
  catch {
@@ -3477,11 +3472,10 @@ function tryStatSync(file) {
3477
3472
  }
3478
3473
  }
3479
3474
  function isFileReadable(filename) {
3475
+ if (!tryStatSync(filename)) {
3476
+ return false;
3477
+ }
3480
3478
  try {
3481
- // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
3482
- if (!fs$1.statSync(filename, { throwIfNoEntry: false })) {
3483
- return false;
3484
- }
3485
3479
  // Check if current process has read permission to the file
3486
3480
  fs$1.accessSync(filename, fs$1.constants.R_OK);
3487
3481
  return true;
@@ -3507,7 +3501,7 @@ const usingDynamicImport = typeof jest === 'undefined';
3507
3501
  usingDynamicImport
3508
3502
  ? new Function('file', 'return import(file)')
3509
3503
  : _require;
3510
- path$3.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))));
3504
+ path$3.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))));
3511
3505
  function mergeConfigRecursively(defaults, overrides, rootPath) {
3512
3506
  const merged = { ...defaults };
3513
3507
  for (const key in overrides) {
@@ -4184,6 +4178,13 @@ class Chunk {
4184
4178
  this.end = index;
4185
4179
 
4186
4180
  if (this.edited) {
4181
+ // after split we should save the edit content record into the correct chunk
4182
+ // to make sure sourcemap correct
4183
+ // For example:
4184
+ // ' test'.trim()
4185
+ // split -> ' ' + 'test'
4186
+ // ✔️ edit -> '' + 'test'
4187
+ // ✖️ edit -> 'test' + ''
4187
4188
  // TODO is this block necessary?...
4188
4189
  newChunk.edit('', false);
4189
4190
  this.content = '';
@@ -4212,6 +4213,10 @@ class Chunk {
4212
4213
  if (trimmed.length) {
4213
4214
  if (trimmed !== this.content) {
4214
4215
  this.split(this.start + trimmed.length).edit('', undefined, true);
4216
+ if (this.edited) {
4217
+ // save the change, if it has been edited
4218
+ this.edit(trimmed, this.storeName, true);
4219
+ }
4215
4220
  }
4216
4221
  return true;
4217
4222
  } else {
@@ -4230,7 +4235,11 @@ class Chunk {
4230
4235
 
4231
4236
  if (trimmed.length) {
4232
4237
  if (trimmed !== this.content) {
4233
- this.split(this.end - trimmed.length);
4238
+ const newChunk = this.split(this.end - trimmed.length);
4239
+ if (this.edited) {
4240
+ // save the change, if it has been edited
4241
+ newChunk.edit(trimmed, this.storeName, true);
4242
+ }
4234
4243
  this.edit('', undefined, true);
4235
4244
  }
4236
4245
  return true;
@@ -5444,8 +5453,13 @@ function hasWorkspacePackageJSON(root) {
5444
5453
  if (!isFileReadable(path)) {
5445
5454
  return false;
5446
5455
  }
5447
- const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {};
5448
- return !!content.workspaces;
5456
+ try {
5457
+ const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {};
5458
+ return !!content.workspaces;
5459
+ }
5460
+ catch {
5461
+ return false;
5462
+ }
5449
5463
  }
5450
5464
  function hasRootFile(root) {
5451
5465
  return ROOT_FILES.some((file) => fs$1.existsSync(path$3.join(root, file)));
@@ -5894,48 +5908,59 @@ main$1.exports.populate = DotenvModule.populate;
5894
5908
 
5895
5909
  main$1.exports = DotenvModule;
5896
5910
 
5911
+ // like String.prototype.search but returns the last index
5912
+ function _searchLast (str, rgx) {
5913
+ const matches = Array.from(str.matchAll(rgx));
5914
+ return matches.length > 0 ? matches.slice(-1)[0].index : -1
5915
+ }
5916
+
5897
5917
  function _interpolate (envValue, environment, config) {
5898
- const matches = envValue.match(/(.?\${*[\w]*(?::-[\w/]*)?}*)/g) || [];
5918
+ // find the last unescaped dollar sign in the
5919
+ // value so that we can evaluate it
5920
+ const lastUnescapedDollarSignIndex = _searchLast(envValue, /(?!(?<=\\))\$/g);
5899
5921
 
5900
- return matches.reduce(function (newEnv, match, index) {
5901
- const parts = /(.?)\${*([\w]*(?::-[\w/]*)?)?}*/g.exec(match);
5902
- if (!parts || parts.length === 0) {
5903
- return newEnv
5904
- }
5922
+ // If we couldn't match any unescaped dollar sign
5923
+ // let's return the string as is
5924
+ if (lastUnescapedDollarSignIndex === -1) return envValue
5905
5925
 
5906
- const prefix = parts[1];
5926
+ // This is the right-most group of variables in the string
5927
+ const rightMostGroup = envValue.slice(lastUnescapedDollarSignIndex);
5907
5928
 
5908
- let value, replacePart;
5929
+ /**
5930
+ * This finds the inner most variable/group divided
5931
+ * by variable name and default value (if present)
5932
+ * (
5933
+ * (?!(?<=\\))\$ // only match dollar signs that are not escaped
5934
+ * {? // optional opening curly brace
5935
+ * ([\w]+) // match the variable name
5936
+ * (?::-([^}\\]*))? // match an optional default value
5937
+ * }? // optional closing curly brace
5938
+ * )
5939
+ */
5940
+ const matchGroup = /((?!(?<=\\))\${?([\w]+)(?::-([^}\\]*))?}?)/;
5941
+ const match = rightMostGroup.match(matchGroup);
5942
+
5943
+ if (match != null) {
5944
+ const [, group, variableName, defaultValue] = match;
5945
+
5946
+ return _interpolate(
5947
+ envValue.replace(
5948
+ group,
5949
+ environment[variableName] ||
5950
+ defaultValue ||
5951
+ config.parsed[variableName] ||
5952
+ ''
5953
+ ),
5954
+ environment,
5955
+ config
5956
+ )
5957
+ }
5909
5958
 
5910
- if (prefix === '\\') {
5911
- replacePart = parts[0];
5912
- value = replacePart.replace('\\$', '$');
5913
- } else {
5914
- // PATCH: compatible with env variables ended with unescaped $
5915
- if(!parts[2]) {
5916
- return newEnv
5917
- }
5918
- const keyParts = parts[2].split(':-');
5919
- const key = keyParts[0];
5920
- replacePart = parts[0].substring(prefix.length);
5921
- // process.env value 'wins' over .env file's value
5922
- value = Object.prototype.hasOwnProperty.call(environment, key)
5923
- ? environment[key]
5924
- : (config.parsed[key] || keyParts[1] || '');
5925
-
5926
- // If the value is found, remove nested expansions.
5927
- if (keyParts.length > 1 && value) {
5928
- const replaceNested = matches[index + 1];
5929
- matches[index + 1] = '';
5930
-
5931
- newEnv = newEnv.replace(replaceNested, '');
5932
- }
5933
- // Resolve recursive interpolations
5934
- value = _interpolate(value, environment, config);
5935
- }
5959
+ return envValue
5960
+ }
5936
5961
 
5937
- return newEnv.replace(replacePart, value)
5938
- }, envValue)
5962
+ function _resolveEscapeSequences (value) {
5963
+ return value.replace(/\\\$/g, '$')
5939
5964
  }
5940
5965
 
5941
5966
  function expand (config) {
@@ -5943,9 +5968,13 @@ function expand (config) {
5943
5968
  const environment = config.ignoreProcessEnv ? {} : process.env;
5944
5969
 
5945
5970
  for (const configKey in config.parsed) {
5946
- const value = Object.prototype.hasOwnProperty.call(environment, configKey) ? environment[configKey] : config.parsed[configKey];
5971
+ const value = Object.prototype.hasOwnProperty.call(environment, configKey)
5972
+ ? environment[configKey]
5973
+ : config.parsed[configKey];
5947
5974
 
5948
- config.parsed[configKey] = _interpolate(value, environment, config);
5975
+ config.parsed[configKey] = _resolveEscapeSequences(
5976
+ _interpolate(value, environment, config)
5977
+ );
5949
5978
  }
5950
5979
 
5951
5980
  // PATCH: don't write to process.env
@@ -5958,6 +5987,14 @@ function expand (config) {
5958
5987
 
5959
5988
  var expand_1 = expand;
5960
5989
 
5990
+ function getEnvFilesForMode(mode) {
5991
+ return [
5992
+ /** default file */ `.env`,
5993
+ /** local file */ `.env.local`,
5994
+ /** mode file */ `.env.${mode}`,
5995
+ /** mode local file */ `.env.${mode}.local`,
5996
+ ];
5997
+ }
5961
5998
  function loadEnv(mode, envDir, prefixes = 'VITE_') {
5962
5999
  if (mode === 'local') {
5963
6000
  throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
@@ -5965,12 +6002,7 @@ function loadEnv(mode, envDir, prefixes = 'VITE_') {
5965
6002
  }
5966
6003
  prefixes = arraify(prefixes);
5967
6004
  const env = {};
5968
- const envFiles = [
5969
- /** default file */ `.env`,
5970
- /** local file */ `.env.local`,
5971
- /** mode file */ `.env.${mode}`,
5972
- /** mode local file */ `.env.${mode}.local`,
5973
- ];
6005
+ const envFiles = getEnvFilesForMode(mode);
5974
6006
  const parsed = Object.fromEntries(envFiles.flatMap((file) => {
5975
6007
  const filePath = path$3.join(envDir, file);
5976
6008
  if (!tryStatSync(filePath)?.isFile())
package/index.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  /* eslint-disable no-restricted-globals */
2
2
 
3
+ warnCjsUsage()
4
+
3
5
  // type utils
4
6
  module.exports.defineConfig = (config) => config
5
7
 
@@ -32,3 +34,15 @@ unsupportedCJS.forEach((name) => {
32
34
  )
33
35
  }
34
36
  })
37
+
38
+ function warnCjsUsage() {
39
+ if (process.env.VITE_CJS_IGNORE_WARNING) return
40
+ globalThis.__vite_cjs_skip_clear_screen = true
41
+ const yellow = (str) => `\u001b[33m${str}\u001b[39m`
42
+ const log = process.env.VITE_CJS_TRACE ? console.trace : console.warn
43
+ log(
44
+ yellow(
45
+ `The CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.`,
46
+ ),
47
+ )
48
+ }
package/index.d.cts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @deprecated The CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.
3
+ */
4
+ declare const module: any
5
+
6
+ export = module