@cloudflare/vite-plugin 0.0.0-8e3688f27 → 0.0.0-8e87754a2

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.
package/dist/index.js CHANGED
@@ -248,17 +248,17 @@ var require_ignore = __commonJS({
248
248
  var throwError = (message, Ctor) => {
249
249
  throw new Ctor(message);
250
250
  };
251
- var checkPath = (path9, originalPath, doThrow) => {
252
- if (!isString(path9)) {
251
+ var checkPath = (path10, originalPath, doThrow) => {
252
+ if (!isString(path10)) {
253
253
  return doThrow(
254
254
  `path must be a string, but got \`${originalPath}\``,
255
255
  TypeError
256
256
  );
257
257
  }
258
- if (!path9) {
258
+ if (!path10) {
259
259
  return doThrow(`path must not be empty`, TypeError);
260
260
  }
261
- if (checkPath.isNotRelative(path9)) {
261
+ if (checkPath.isNotRelative(path10)) {
262
262
  const r2 = "`path.relative()`d";
263
263
  return doThrow(
264
264
  `path should be a ${r2} string, but got "${originalPath}"`,
@@ -267,7 +267,7 @@ var require_ignore = __commonJS({
267
267
  }
268
268
  return true;
269
269
  };
270
- var isNotRelative = (path9) => REGEX_TEST_INVALID_PATH.test(path9);
270
+ var isNotRelative = (path10) => REGEX_TEST_INVALID_PATH.test(path10);
271
271
  checkPath.isNotRelative = isNotRelative;
272
272
  checkPath.convert = (p) => p;
273
273
  var Ignore = class {
@@ -326,7 +326,7 @@ var require_ignore = __commonJS({
326
326
  // setting `checkUnignored` to `false` could reduce additional
327
327
  // path matching.
328
328
  // @returns {TestResult} true if a file is ignored
329
- _testOne(path9, checkUnignored) {
329
+ _testOne(path10, checkUnignored) {
330
330
  let ignored = false;
331
331
  let unignored = false;
332
332
  this._rules.forEach((rule) => {
@@ -334,7 +334,7 @@ var require_ignore = __commonJS({
334
334
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
335
335
  return;
336
336
  }
337
- const matched = rule.regex.test(path9);
337
+ const matched = rule.regex.test(path10);
338
338
  if (matched) {
339
339
  ignored = !negative;
340
340
  unignored = negative;
@@ -347,24 +347,24 @@ var require_ignore = __commonJS({
347
347
  }
348
348
  // @returns {TestResult}
349
349
  _test(originalPath, cache2, checkUnignored, slices) {
350
- const path9 = originalPath && checkPath.convert(originalPath);
350
+ const path10 = originalPath && checkPath.convert(originalPath);
351
351
  checkPath(
352
- path9,
352
+ path10,
353
353
  originalPath,
354
354
  this._allowRelativePaths ? RETURN_FALSE : throwError
355
355
  );
356
- return this._t(path9, cache2, checkUnignored, slices);
356
+ return this._t(path10, cache2, checkUnignored, slices);
357
357
  }
358
- _t(path9, cache2, checkUnignored, slices) {
359
- if (path9 in cache2) {
360
- return cache2[path9];
358
+ _t(path10, cache2, checkUnignored, slices) {
359
+ if (path10 in cache2) {
360
+ return cache2[path10];
361
361
  }
362
362
  if (!slices) {
363
- slices = path9.split(SLASH);
363
+ slices = path10.split(SLASH);
364
364
  }
365
365
  slices.pop();
366
366
  if (!slices.length) {
367
- return cache2[path9] = this._testOne(path9, checkUnignored);
367
+ return cache2[path10] = this._testOne(path10, checkUnignored);
368
368
  }
369
369
  const parent = this._t(
370
370
  slices.join(SLASH) + SLASH,
@@ -372,24 +372,24 @@ var require_ignore = __commonJS({
372
372
  checkUnignored,
373
373
  slices
374
374
  );
375
- return cache2[path9] = parent.ignored ? parent : this._testOne(path9, checkUnignored);
375
+ return cache2[path10] = parent.ignored ? parent : this._testOne(path10, checkUnignored);
376
376
  }
377
- ignores(path9) {
378
- return this._test(path9, this._ignoreCache, false).ignored;
377
+ ignores(path10) {
378
+ return this._test(path10, this._ignoreCache, false).ignored;
379
379
  }
380
380
  createFilter() {
381
- return (path9) => !this.ignores(path9);
381
+ return (path10) => !this.ignores(path10);
382
382
  }
383
383
  filter(paths) {
384
384
  return makeArray(paths).filter(this.createFilter());
385
385
  }
386
386
  // @returns {TestResult}
387
- test(path9) {
388
- return this._test(path9, this._testCache, true);
387
+ test(path10) {
388
+ return this._test(path10, this._testCache, true);
389
389
  }
390
390
  };
391
391
  var factory = (options) => new Ignore(options);
392
- var isPathValid = (path9) => checkPath(path9 && checkPath.convert(path9), path9, RETURN_FALSE);
392
+ var isPathValid = (path10) => checkPath(path10 && checkPath.convert(path10), path10, RETURN_FALSE);
393
393
  factory.isPathValid = isPathValid;
394
394
  factory.default = factory;
395
395
  module.exports = factory;
@@ -400,7 +400,7 @@ var require_ignore = __commonJS({
400
400
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
401
401
  checkPath.convert = makePosix;
402
402
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
403
- checkPath.isNotRelative = (path9) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path9) || isNotRelative(path9);
403
+ checkPath.isNotRelative = (path10) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path10) || isNotRelative(path10);
404
404
  }
405
405
  }
406
406
  });
@@ -443,11 +443,11 @@ var require_Mime = __commonJS({
443
443
  }
444
444
  }
445
445
  };
446
- Mime.prototype.getType = function(path9) {
447
- path9 = String(path9);
448
- let last = path9.replace(/^.*[/\\]/, "").toLowerCase();
446
+ Mime.prototype.getType = function(path10) {
447
+ path10 = String(path10);
448
+ let last = path10.replace(/^.*[/\\]/, "").toLowerCase();
449
449
  let ext = last.replace(/^.*\./, "").toLowerCase();
450
- let hasPath = last.length < path9.length;
450
+ let hasPath = last.length < path10.length;
451
451
  let hasDot = ext.length < last.length - 1;
452
452
  return (hasDot || !hasPath) && this._types[ext] || null;
453
453
  };
@@ -485,12 +485,12 @@ var require_mime = __commonJS({
485
485
  });
486
486
 
487
487
  // src/index.ts
488
- import assert8 from "node:assert";
488
+ import assert10 from "node:assert";
489
489
  import * as fs5 from "node:fs";
490
490
  import * as fsp2 from "node:fs/promises";
491
- import { builtinModules as builtinModules2 } from "node:module";
492
- import * as path8 from "node:path";
491
+ import * as path9 from "node:path";
493
492
  import { createMiddleware } from "@hattip/adapter-node";
493
+ import replace from "@rollup/plugin-replace";
494
494
 
495
495
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
496
496
  var comma = ",".charCodeAt(0);
@@ -1558,7 +1558,8 @@ var MagicString = class _MagicString {
1558
1558
 
1559
1559
  // src/index.ts
1560
1560
  import { Miniflare } from "miniflare";
1561
- import * as vite6 from "vite";
1561
+ import colors2 from "picocolors";
1562
+ import * as vite7 from "vite";
1562
1563
 
1563
1564
  // src/constants.ts
1564
1565
  var ROUTER_WORKER_NAME = "__router-worker__";
@@ -1726,11 +1727,11 @@ ${invalidHeaderRulesList}`
1726
1727
  }
1727
1728
 
1728
1729
  // ../workers-shared/utils/configuration/validateURL.ts
1729
- var extractPathname = (path9 = "/", includeSearch, includeHash) => {
1730
- if (!path9.startsWith("/")) {
1731
- path9 = `/${path9}`;
1730
+ var extractPathname = (path10 = "/", includeSearch, includeHash) => {
1731
+ if (!path10.startsWith("/")) {
1732
+ path10 = `/${path10}`;
1732
1733
  }
1733
- const url = new URL(`//${path9}`, "relative://");
1734
+ const url = new URL(`//${path10}`, "relative://");
1734
1735
  return `${url.pathname}${includeSearch ? url.search : ""}${includeHash ? url.hash : ""}`;
1735
1736
  };
1736
1737
  var URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
@@ -1763,8 +1764,8 @@ var validateUrl = (token, onlyRelative = false, disallowPorts = false, includeSe
1763
1764
  if (!token.startsWith("/") && onlyRelative) {
1764
1765
  token = `/${token}`;
1765
1766
  }
1766
- const path9 = PATH_REGEX.exec(token);
1767
- if (path9) {
1767
+ const path10 = PATH_REGEX.exec(token);
1768
+ if (path10) {
1768
1769
  try {
1769
1770
  return [extractPathname(token, includeSearch, includeHash), void 0];
1770
1771
  } catch {
@@ -1825,7 +1826,7 @@ function parseHeaders(input, {
1825
1826
  });
1826
1827
  }
1827
1828
  }
1828
- const [path9, pathError] = validateUrl(line, false, true);
1829
+ const [path10, pathError] = validateUrl(line, false, true);
1829
1830
  if (pathError) {
1830
1831
  invalid.push({
1831
1832
  line,
@@ -1836,7 +1837,7 @@ function parseHeaders(input, {
1836
1837
  continue;
1837
1838
  }
1838
1839
  rule = {
1839
- path: path9,
1840
+ path: path10,
1840
1841
  line,
1841
1842
  headers: {},
1842
1843
  unsetHeaders: []
@@ -2411,8 +2412,8 @@ function getErrorMap() {
2411
2412
  return overrideErrorMap;
2412
2413
  }
2413
2414
  var makeIssue = (params) => {
2414
- const { data: data2, path: path9, errorMaps, issueData } = params;
2415
- const fullPath = [...path9, ...issueData.path || []];
2415
+ const { data: data2, path: path10, errorMaps, issueData } = params;
2416
+ const fullPath = [...path10, ...issueData.path || []];
2416
2417
  const fullIssue = {
2417
2418
  ...issueData,
2418
2419
  path: fullPath
@@ -2511,11 +2512,11 @@ var errorUtil;
2511
2512
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2512
2513
  })(errorUtil || (errorUtil = {}));
2513
2514
  var ParseInputLazyPath = class {
2514
- constructor(parent, value, path9, key) {
2515
+ constructor(parent, value, path10, key) {
2515
2516
  this._cachedPath = [];
2516
2517
  this.parent = parent;
2517
2518
  this.data = value;
2518
- this._path = path9;
2519
+ this._path = path10;
2519
2520
  this._key = key;
2520
2521
  }
2521
2522
  get path() {
@@ -5831,14 +5832,14 @@ var AssetConfigSchema = z.object({
5831
5832
  });
5832
5833
 
5833
5834
  // src/asset-config.ts
5834
- function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFile) {
5835
+ function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFilePath) {
5835
5836
  if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) {
5836
5837
  return false;
5837
5838
  }
5838
5839
  return [
5839
5840
  getRedirectsConfigPath(resolvedViteConfig),
5840
5841
  getHeadersConfigPath(resolvedViteConfig)
5841
- ].includes(path.resolve(changedFile));
5842
+ ].includes(changedFilePath);
5842
5843
  }
5843
5844
  function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig) {
5844
5845
  const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
@@ -5905,10 +5906,12 @@ function getHeadersConfigPath(config) {
5905
5906
 
5906
5907
  // src/cloudflare-environment.ts
5907
5908
  import assert3 from "node:assert";
5908
- import * as vite2 from "vite";
5909
+ import * as vite3 from "vite";
5909
5910
 
5910
5911
  // src/node-js-compat.ts
5911
5912
  import assert2 from "node:assert";
5913
+ import { builtinModules as builtinModules2 } from "node:module";
5914
+ import path3 from "node:path";
5912
5915
  import { cloudflare } from "@cloudflare/unenv-preset";
5913
5916
  import { getNodeCompat } from "miniflare";
5914
5917
 
@@ -11460,17 +11463,17 @@ function withTrailingSlash(input = "", respectQueryAndFragment) {
11460
11463
  if (hasTrailingSlash(input, true)) {
11461
11464
  return input || "/";
11462
11465
  }
11463
- let path9 = input;
11466
+ let path10 = input;
11464
11467
  let fragment = "";
11465
11468
  const fragmentIndex = input.indexOf("#");
11466
11469
  if (fragmentIndex >= 0) {
11467
- path9 = input.slice(0, fragmentIndex);
11470
+ path10 = input.slice(0, fragmentIndex);
11468
11471
  fragment = input.slice(fragmentIndex);
11469
- if (!path9) {
11472
+ if (!path10) {
11470
11473
  return fragment;
11471
11474
  }
11472
11475
  }
11473
- const [s0, ...s] = path9.split("?");
11476
+ const [s0, ...s] = path10.split("?");
11474
11477
  return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
11475
11478
  }
11476
11479
  function isNonEmptyURL(url) {
@@ -11504,8 +11507,8 @@ import path2, { dirname as dirname2 } from "node:path";
11504
11507
  import v8 from "node:v8";
11505
11508
  import { format as format2, inspect } from "node:util";
11506
11509
  var BUILTIN_MODULES = new Set(builtinModules);
11507
- function normalizeSlash(path9) {
11508
- return path9.replace(/\\/g, "/");
11510
+ function normalizeSlash(path10) {
11511
+ return path10.replace(/\\/g, "/");
11509
11512
  }
11510
11513
  var own$1 = {}.hasOwnProperty;
11511
11514
  var classRegExp = /^([A-Z][a-z\d]*)+$/;
@@ -11618,8 +11621,8 @@ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
11618
11621
  * @param {string} [base]
11619
11622
  * @param {string} [message]
11620
11623
  */
11621
- (path9, base, message) => {
11622
- return `Invalid package config ${path9}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11624
+ (path10, base, message) => {
11625
+ return `Invalid package config ${path10}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11623
11626
  },
11624
11627
  Error
11625
11628
  );
@@ -11651,8 +11654,8 @@ codes.ERR_MODULE_NOT_FOUND = createError(
11651
11654
  * @param {string} base
11652
11655
  * @param {boolean} [exactUrl]
11653
11656
  */
11654
- (path9, base, exactUrl = false) => {
11655
- return `Cannot find ${exactUrl ? "module" : "package"} '${path9}' imported from ${base}`;
11657
+ (path10, base, exactUrl = false) => {
11658
+ return `Cannot find ${exactUrl ? "module" : "package"} '${path10}' imported from ${base}`;
11656
11659
  },
11657
11660
  Error
11658
11661
  );
@@ -11703,8 +11706,8 @@ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
11703
11706
  * @param {string} extension
11704
11707
  * @param {string} path
11705
11708
  */
11706
- (extension, path9) => {
11707
- return `Unknown file extension "${extension}" for ${path9}`;
11709
+ (extension, path10) => {
11710
+ return `Unknown file extension "${extension}" for ${path10}`;
11708
11711
  },
11709
11712
  TypeError
11710
11713
  );
@@ -12076,9 +12079,9 @@ Default "index" lookups for the main are deprecated for ES modules.`,
12076
12079
  );
12077
12080
  }
12078
12081
  }
12079
- function tryStatSync(path9) {
12082
+ function tryStatSync(path10) {
12080
12083
  try {
12081
- return statSync(path9);
12084
+ return statSync(path10);
12082
12085
  } catch {
12083
12086
  }
12084
12087
  }
@@ -12845,12 +12848,20 @@ function resolvePathSync(id, options) {
12845
12848
 
12846
12849
  // src/node-js-compat.ts
12847
12850
  import { defineEnv } from "unenv";
12851
+ import "vite";
12848
12852
  var { env } = defineEnv({
12849
12853
  nodeCompat: true,
12850
12854
  presets: [cloudflare]
12851
12855
  });
12852
12856
  var nodeCompatExternals = new Set(env.external);
12853
12857
  var nodeCompatEntries = getNodeCompatEntries();
12858
+ var nodejsBuiltins = /* @__PURE__ */ new Set([
12859
+ ...builtinModules2,
12860
+ ...builtinModules2.map((m) => `node:${m}`)
12861
+ ]);
12862
+ var NODEJS_MODULES_RE = new RegExp(
12863
+ `^(node:)?(${builtinModules2.join("|")})$`
12864
+ );
12854
12865
  function isNodeCompat(workerConfig) {
12855
12866
  if (workerConfig === void 0) {
12856
12867
  return false;
@@ -12899,7 +12910,7 @@ globalThis.${globalName} = var_${globalName}.${exportName};
12899
12910
  }
12900
12911
  function resolveNodeJSImport(source) {
12901
12912
  const alias = env.alias[source];
12902
- if (alias) {
12913
+ if (alias && !nodeCompatExternals.has(alias)) {
12903
12914
  return {
12904
12915
  unresolved: alias,
12905
12916
  resolved: resolvePathSync(alias, { url: import.meta.url })
@@ -12929,6 +12940,45 @@ function getNodeCompatEntries() {
12929
12940
  nodeCompatExternals.forEach((external) => entries.delete(external));
12930
12941
  return entries;
12931
12942
  }
12943
+ var NodeJsCompatWarnings = class {
12944
+ constructor(environmentName, resolvedViteConfig) {
12945
+ this.environmentName = environmentName;
12946
+ this.resolvedViteConfig = resolvedViteConfig;
12947
+ }
12948
+ sources = /* @__PURE__ */ new Map();
12949
+ timer;
12950
+ registerImport(source, importer = "<unknown>") {
12951
+ const importers = this.sources.get(source) ?? /* @__PURE__ */ new Set();
12952
+ this.sources.set(source, importers);
12953
+ importers.add(importer);
12954
+ this.renderWarningsOnIdle();
12955
+ }
12956
+ renderWarningsOnIdle() {
12957
+ if (this.timer) {
12958
+ clearTimeout(this.timer);
12959
+ }
12960
+ this.timer = setTimeout(() => {
12961
+ this.renderWarnings();
12962
+ this.timer = void 0;
12963
+ }, 500);
12964
+ }
12965
+ renderWarnings() {
12966
+ if (this.sources.size > 0) {
12967
+ let message = `Unexpected Node.js imports for environment "${this.environmentName}". Do you need to enable the "nodejs_compat" compatibility flag? Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.
12968
+ `;
12969
+ this.sources.forEach((importers, source) => {
12970
+ importers.forEach((importer) => {
12971
+ message += ` - "${source}" imported from "${path3.relative(this.resolvedViteConfig.root, importer)}"
12972
+ `;
12973
+ });
12974
+ });
12975
+ this.resolvedViteConfig.logger.warn(message, {
12976
+ timestamp: true
12977
+ });
12978
+ this.sources.clear();
12979
+ }
12980
+ }
12981
+ };
12932
12982
 
12933
12983
  // src/shared.ts
12934
12984
  var UNKNOWN_HOST = "http://localhost";
@@ -12942,17 +12992,22 @@ var additionalModuleGlobalRE = new RegExp(
12942
12992
  var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
12943
12993
 
12944
12994
  // src/utils.ts
12945
- import * as path3 from "node:path";
12995
+ import * as path4 from "node:path";
12996
+ import getPort, { portNumbers } from "get-port";
12946
12997
  import { Request as MiniflareRequest } from "miniflare";
12947
12998
  import "vite";
12948
12999
  function getOutputDirectory(userConfig, environmentName) {
12949
13000
  const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
12950
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path3.join(rootOutputDirectory, environmentName);
13001
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path4.join(rootOutputDirectory, environmentName);
12951
13002
  }
12952
13003
  function getRouterWorker(miniflare2) {
12953
13004
  return miniflare2.getWorker(ROUTER_WORKER_NAME);
12954
13005
  }
12955
13006
  function toMiniflareRequest(request) {
13007
+ const host = request.headers.get("Host");
13008
+ if (host) {
13009
+ request.headers.set("X-Forwarded-Host", host);
13010
+ }
12956
13011
  const secFetchMode = request.headers.get("Sec-Fetch-Mode");
12957
13012
  if (secFetchMode) {
12958
13013
  request.headers.set("X-Mf-Sec-Fetch-Mode", secFetchMode);
@@ -12981,6 +13036,9 @@ var postfixRE = /[?#].*$/;
12981
13036
  function cleanUrl(url) {
12982
13037
  return url.replace(postfixRE, "");
12983
13038
  }
13039
+ function getFirstAvailablePort(start) {
13040
+ return getPort({ port: portNumbers(start, 65535) });
13041
+ }
12984
13042
 
12985
13043
  // src/cloudflare-environment.ts
12986
13044
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -13026,7 +13084,7 @@ function createHotChannel(webSocketContainer) {
13026
13084
  }
13027
13085
  };
13028
13086
  }
13029
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
13087
+ var CloudflareDevEnvironment = class extends vite3.DevEnvironment {
13030
13088
  #webSocketContainer;
13031
13089
  #worker;
13032
13090
  constructor(name, config) {
@@ -13087,7 +13145,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
13087
13145
  },
13088
13146
  build: {
13089
13147
  createEnvironment(name, config) {
13090
- return new vite2.BuildEnvironment(name, config);
13148
+ return new vite3.BuildEnvironment(name, config);
13091
13149
  },
13092
13150
  target,
13093
13151
  // We need to enable `emitAssets` in order to support additional modules defined by `rules`
@@ -13196,11 +13254,11 @@ function getDebugPathHtml(workerNames, inspectorPort) {
13196
13254
  // src/deploy-config.ts
13197
13255
  import assert5 from "node:assert";
13198
13256
  import * as fs2 from "node:fs";
13199
- import * as path4 from "node:path";
13257
+ import * as path5 from "node:path";
13200
13258
  import "vite";
13201
13259
  import { unstable_readConfig } from "wrangler";
13202
13260
  function getDeployConfigPath(root) {
13203
- return path4.resolve(root, ".wrangler", "deploy", "config.json");
13261
+ return path5.resolve(root, ".wrangler", "deploy", "config.json");
13204
13262
  }
13205
13263
  function getWorkerConfigs(root) {
13206
13264
  const deployConfigPath = getDeployConfigPath(root);
@@ -13211,22 +13269,22 @@ function getWorkerConfigs(root) {
13211
13269
  { configPath: deployConfig.configPath },
13212
13270
  ...deployConfig.auxiliaryWorkers
13213
13271
  ].map(({ configPath }) => {
13214
- const resolvedConfigPath = path4.resolve(
13215
- path4.dirname(deployConfigPath),
13272
+ const resolvedConfigPath = path5.resolve(
13273
+ path5.dirname(deployConfigPath),
13216
13274
  configPath
13217
13275
  );
13218
13276
  return unstable_readConfig({ config: resolvedConfigPath });
13219
13277
  });
13220
13278
  }
13221
13279
  function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
13222
- return path4.relative(
13280
+ return path5.relative(
13223
13281
  deployConfigDirectory,
13224
- path4.resolve(root, outputDirectory, "wrangler.json")
13282
+ path5.resolve(root, outputDirectory, "wrangler.json")
13225
13283
  );
13226
13284
  }
13227
13285
  function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13228
13286
  const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
13229
- const deployConfigDirectory = path4.dirname(deployConfigPath);
13287
+ const deployConfigDirectory = path5.dirname(deployConfigPath);
13230
13288
  fs2.mkdirSync(deployConfigDirectory, { recursive: true });
13231
13289
  if (resolvedPluginConfig.type === "assets-only") {
13232
13290
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
@@ -13279,7 +13337,7 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13279
13337
  import assert6 from "node:assert";
13280
13338
  import * as fs3 from "node:fs";
13281
13339
  import * as fsp from "node:fs/promises";
13282
- import * as path5 from "node:path";
13340
+ import * as path6 from "node:path";
13283
13341
  import { fileURLToPath as fileURLToPath2 } from "node:url";
13284
13342
  import {
13285
13343
  kCurrentWorker,
@@ -13295,18 +13353,18 @@ function getPersistence(root, persistState) {
13295
13353
  return {};
13296
13354
  }
13297
13355
  const defaultPersistPath = ".wrangler/state";
13298
- const persistPath = path5.resolve(
13356
+ const persistPath = path6.resolve(
13299
13357
  root,
13300
13358
  typeof persistState === "object" ? persistState.path : defaultPersistPath,
13301
13359
  "v3"
13302
13360
  );
13303
13361
  return {
13304
- cachePersist: path5.join(persistPath, "cache"),
13305
- d1Persist: path5.join(persistPath, "d1"),
13306
- durableObjectsPersist: path5.join(persistPath, "do"),
13307
- kvPersist: path5.join(persistPath, "kv"),
13308
- r2Persist: path5.join(persistPath, "r2"),
13309
- workflowsPersist: path5.join(persistPath, "workflows")
13362
+ cachePersist: path6.join(persistPath, "cache"),
13363
+ d1Persist: path6.join(persistPath, "d1"),
13364
+ durableObjectsPersist: path6.join(persistPath, "do"),
13365
+ kvPersist: path6.join(persistPath, "kv"),
13366
+ r2Persist: path6.join(persistPath, "r2"),
13367
+ workflowsPersist: path6.join(persistPath, "workflows")
13310
13368
  };
13311
13369
  }
13312
13370
  function missingWorkerErrorMessage(workerName) {
@@ -13391,7 +13449,7 @@ function getEntryWorkerConfig(resolvedPluginConfig) {
13391
13449
  }
13392
13450
  return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
13393
13451
  }
13394
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13452
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspectorPort) {
13395
13453
  const resolvedViteConfig = viteDevServer.config;
13396
13454
  const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
13397
13455
  const assetsConfig = getAssetsConfig(
@@ -13407,7 +13465,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13407
13465
  modules: [
13408
13466
  {
13409
13467
  type: "ESModule",
13410
- path: path5.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13468
+ path: path6.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13411
13469
  contents: fs3.readFileSync(
13412
13470
  fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
13413
13471
  )
@@ -13430,7 +13488,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13430
13488
  modules: [
13431
13489
  {
13432
13490
  type: "ESModule",
13433
- path: path5.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13491
+ path: path6.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13434
13492
  contents: fs3.readFileSync(
13435
13493
  fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
13436
13494
  )
@@ -13442,7 +13500,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13442
13500
  serviceBindings: {
13443
13501
  __VITE_ASSET_EXISTS__: async (request) => {
13444
13502
  const { pathname } = new URL(request.url);
13445
- const filePath = path5.join(resolvedViteConfig.root, pathname);
13503
+ const filePath = path6.join(resolvedViteConfig.root, pathname);
13446
13504
  let exists;
13447
13505
  try {
13448
13506
  exists = fs3.statSync(filePath).isFile();
@@ -13453,7 +13511,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13453
13511
  },
13454
13512
  __VITE_FETCH_ASSET__: async (request) => {
13455
13513
  const { pathname } = new URL(request.url);
13456
- const filePath = path5.join(resolvedViteConfig.root, pathname);
13514
+ const filePath = path6.join(resolvedViteConfig.root, pathname);
13457
13515
  try {
13458
13516
  let html = await fsp.readFile(filePath, "utf-8");
13459
13517
  html = await viteDevServer.transformIndexHtml(pathname, html);
@@ -13483,7 +13541,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13483
13541
  worker: {
13484
13542
  ...workerOptions,
13485
13543
  name: workerOptions.name ?? workerConfig.name,
13486
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13544
+ unsafeInspectorProxy: inspectorPort !== false,
13487
13545
  modulesRoot: miniflareModulesRoot,
13488
13546
  unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
13489
13547
  serviceBindings: {
@@ -13525,8 +13583,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13525
13583
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13526
13584
  return {
13527
13585
  log: logger,
13528
- inspectorPort: resolvedPluginConfig.inspectorPort || void 0,
13529
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13586
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13587
+ unsafeInspectorProxy: inspectorPort !== false,
13530
13588
  handleRuntimeStdio(stdout, stderr) {
13531
13589
  const decoder = new TextDecoder();
13532
13590
  stdout.forEach((data2) => logger.info(decoder.decode(data2)));
@@ -13585,12 +13643,12 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13585
13643
  modules: [
13586
13644
  {
13587
13645
  type: "ESModule",
13588
- path: path5.join(miniflareModulesRoot, WRAPPER_PATH),
13646
+ path: path6.join(miniflareModulesRoot, WRAPPER_PATH),
13589
13647
  contents: wrappers.join("\n")
13590
13648
  },
13591
13649
  {
13592
13650
  type: "ESModule",
13593
- path: path5.join(miniflareModulesRoot, RUNNER_PATH),
13651
+ path: path6.join(miniflareModulesRoot, RUNNER_PATH),
13594
13652
  contents: fs3.readFileSync(
13595
13653
  fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
13596
13654
  )
@@ -13645,8 +13703,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13645
13703
  }
13646
13704
  function getPreviewModules(main, modulesRules) {
13647
13705
  assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
13648
- const rootPath = path5.dirname(main);
13649
- const entryPath = path5.basename(main);
13706
+ const rootPath = path6.dirname(main);
13707
+ const entryPath = path6.basename(main);
13650
13708
  return {
13651
13709
  rootPath,
13652
13710
  modules: [
@@ -13655,15 +13713,15 @@ function getPreviewModules(main, modulesRules) {
13655
13713
  path: entryPath
13656
13714
  },
13657
13715
  ...modulesRules.flatMap(
13658
- ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path9) => ({
13716
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path10) => ({
13659
13717
  type,
13660
- path: path9
13718
+ path: path10
13661
13719
  }))
13662
13720
  )
13663
13721
  ]
13664
13722
  };
13665
13723
  }
13666
- function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort = DEFAULT_INSPECTOR_PORT) {
13724
+ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort) {
13667
13725
  const resolvedViteConfig = vitePreviewServer.config;
13668
13726
  const workers = workerConfigs.flatMap((config) => {
13669
13727
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
@@ -13682,7 +13740,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13682
13740
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13683
13741
  return {
13684
13742
  log: logger,
13685
- inspectorPort: inspectorPort || void 0,
13743
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13686
13744
  unsafeInspectorProxy: inspectorPort !== false,
13687
13745
  handleRuntimeStdio(stdout, stderr) {
13688
13746
  const decoder = new TextDecoder();
@@ -13732,13 +13790,14 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
13732
13790
  }
13733
13791
 
13734
13792
  // src/plugin-config.ts
13735
- import assert7 from "node:assert";
13736
- import * as path7 from "node:path";
13737
- import * as vite5 from "vite";
13793
+ import assert8 from "node:assert";
13794
+ import * as path8 from "node:path";
13795
+ import * as vite6 from "vite";
13738
13796
 
13739
13797
  // src/workers-configs.ts
13798
+ import assert7 from "node:assert";
13740
13799
  import * as fs4 from "node:fs";
13741
- import * as path6 from "node:path";
13800
+ import * as path7 from "node:path";
13742
13801
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
13743
13802
  var nonApplicableWorkerConfigs = {
13744
13803
  /**
@@ -13770,8 +13829,7 @@ var nonApplicableWorkerConfigs = {
13770
13829
  "preserve_file_names",
13771
13830
  "rules",
13772
13831
  "site",
13773
- "tsconfig",
13774
- "upload_source_maps"
13832
+ "tsconfig"
13775
13833
  ]
13776
13834
  };
13777
13835
  var nullableNonApplicable = [
@@ -13782,8 +13840,7 @@ var nullableNonApplicable = [
13782
13840
  "no_bundle",
13783
13841
  "preserve_file_names",
13784
13842
  "site",
13785
- "tsconfig",
13786
- "upload_source_maps"
13843
+ "tsconfig"
13787
13844
  ];
13788
13845
  function readWorkerConfig(configPath, env2) {
13789
13846
  const nonApplicable = {
@@ -13832,7 +13889,7 @@ function getWarningForWorkersConfigs(configs) {
13832
13889
  const lines2 = [
13833
13890
  `
13834
13891
 
13835
- \x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path6.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
13892
+ \x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path7.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
13836
13893
  ];
13837
13894
  nonApplicableLines.forEach((line) => lines2.push(line));
13838
13895
  lines2.push("");
@@ -13846,7 +13903,7 @@ function getWarningForWorkersConfigs(configs) {
13846
13903
  );
13847
13904
  if (nonApplicableLines.length > 0) {
13848
13905
  lines.push(
13849
- ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path6.relative("", workerConfig.config.configPath)}\`)` : ""}`
13906
+ ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path7.relative("", workerConfig.config.configPath)}\`)` : ""}`
13850
13907
  );
13851
13908
  nonApplicableLines.forEach((line) => lines.push(line));
13852
13909
  }
@@ -13945,14 +14002,52 @@ function getWorkerConfig(configPath, env2, opts) {
13945
14002
  nonApplicable
13946
14003
  };
13947
14004
  }
14005
+ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
14006
+ if (requestedConfigPath) {
14007
+ const configPath2 = path7.resolve(root, requestedConfigPath);
14008
+ const forAuxiliaryWorkerErrorMessage = isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : "";
14009
+ const errorMessagePrefix = `The provided configPath (${configPath2})${forAuxiliaryWorkerErrorMessage}`;
14010
+ const fileExtension = path7.extname(configPath2).slice(1);
14011
+ if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
14012
+ const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
14013
+ throw new Error(
14014
+ `${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`
14015
+ );
14016
+ }
14017
+ const mainStat = fs4.statSync(configPath2, { throwIfNoEntry: false });
14018
+ if (!mainStat) {
14019
+ throw new Error(
14020
+ `${errorMessagePrefix} doesn't point to an existing file`
14021
+ );
14022
+ }
14023
+ if (mainStat.isDirectory()) {
14024
+ throw new Error(
14025
+ `${errorMessagePrefix} points to a directory. It should point to a file.`
14026
+ );
14027
+ }
14028
+ return configPath2;
14029
+ }
14030
+ assert7(
14031
+ isForAuxiliaryWorker === false,
14032
+ "Unexpected Error: trying to find the wrangler config for an auxiliary worker"
14033
+ );
14034
+ const configPath = findWranglerConfig(root);
14035
+ if (!configPath) {
14036
+ throw new Error(
14037
+ `No config file found in the ${root} directory. Please add a wrangler.(jsonc|json|toml) file.`
14038
+ );
14039
+ }
14040
+ return configPath;
14041
+ }
13948
14042
  function findWranglerConfig(root) {
13949
- for (const extension of ["json", "jsonc", "toml"]) {
13950
- const configPath = path6.join(root, `wrangler.${extension}`);
14043
+ for (const extension of allowedWranglerConfigExtensions) {
14044
+ const configPath = path7.join(root, `wrangler.${extension}`);
13951
14045
  if (fs4.existsSync(configPath)) {
13952
14046
  return configPath;
13953
14047
  }
13954
14048
  }
13955
14049
  }
14050
+ var allowedWranglerConfigExtensions = ["jsonc", "json", "toml"];
13956
14051
 
13957
14052
  // src/plugin-config.ts
13958
14053
  function workerNameToEnvironmentName(workerName) {
@@ -13961,31 +14056,31 @@ function workerNameToEnvironmentName(workerName) {
13961
14056
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
13962
14057
  const configPaths = /* @__PURE__ */ new Set();
13963
14058
  const persistState = pluginConfig.persistState ?? true;
13964
- const inspectorPort = pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT;
13965
14059
  const experimental = pluginConfig.experimental ?? {};
13966
- const root = userConfig.root ? path7.resolve(userConfig.root) : process.cwd();
13967
- const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
14060
+ const root = userConfig.root ? path8.resolve(userConfig.root) : process.cwd();
14061
+ const { CLOUDFLARE_ENV: cloudflareEnv } = vite6.loadEnv(
13968
14062
  viteEnv.mode,
13969
14063
  root,
13970
14064
  /* prefixes */
13971
14065
  ""
13972
14066
  );
13973
- const configPath = pluginConfig.configPath ? path7.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
13974
- if (!configPath) {
13975
- throw new Error(
13976
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
13977
- );
13978
- }
13979
- const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
13980
- visitedConfigPaths: configPaths,
13981
- isEntryWorker: true
13982
- });
14067
+ const entryWorkerConfigPath = getValidatedWranglerConfigPath(
14068
+ root,
14069
+ pluginConfig.configPath
14070
+ );
14071
+ const entryWorkerResolvedConfig = getWorkerConfig(
14072
+ entryWorkerConfigPath,
14073
+ cloudflareEnv,
14074
+ {
14075
+ visitedConfigPaths: configPaths,
14076
+ isEntryWorker: true
14077
+ }
14078
+ );
13983
14079
  if (entryWorkerResolvedConfig.type === "assets-only") {
13984
14080
  return {
13985
14081
  type: "assets-only",
13986
14082
  config: entryWorkerResolvedConfig.config,
13987
14083
  configPaths,
13988
- inspectorPort,
13989
14084
  persistState,
13990
14085
  rawConfigs: {
13991
14086
  entryWorker: entryWorkerResolvedConfig
@@ -14001,15 +14096,20 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14001
14096
  };
14002
14097
  const auxiliaryWorkersResolvedConfigs = [];
14003
14098
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
14099
+ const workerConfigPath = getValidatedWranglerConfigPath(
14100
+ root,
14101
+ auxiliaryWorker.configPath,
14102
+ true
14103
+ );
14004
14104
  const workerResolvedConfig = getWorkerConfig(
14005
- path7.resolve(root, auxiliaryWorker.configPath),
14105
+ workerConfigPath,
14006
14106
  cloudflareEnv,
14007
14107
  {
14008
14108
  visitedConfigPaths: configPaths
14009
14109
  }
14010
14110
  );
14011
14111
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
14012
- assert7(
14112
+ assert8(
14013
14113
  workerResolvedConfig.type === "worker",
14014
14114
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
14015
14115
  );
@@ -14026,7 +14126,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14026
14126
  type: "workers",
14027
14127
  configPaths,
14028
14128
  persistState,
14029
- inspectorPort,
14030
14129
  workers,
14031
14130
  entryWorkerEnvironmentName,
14032
14131
  rawConfigs: {
@@ -14074,6 +14173,54 @@ function handleWebSocket(httpServer, getFetcher) {
14074
14173
  );
14075
14174
  }
14076
14175
 
14176
+ // src/worker-environments-validation.ts
14177
+ import assert9 from "node:assert";
14178
+ function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolvedViteConfig) {
14179
+ const workersEnvironmentNames = Object.keys(resolvedPluginConfig.workers);
14180
+ const disallowedEnvsConfigs = /* @__PURE__ */ new Map();
14181
+ for (const envName of workersEnvironmentNames) {
14182
+ const workerEnvConfig = resolvedViteConfig.environments[envName];
14183
+ assert9(workerEnvConfig, `Missing environment config for "${envName}"`);
14184
+ const { optimizeDeps, resolve: resolve7 } = workerEnvConfig;
14185
+ const disallowedConfig = {};
14186
+ const disallowedOptimizeDepsExcludeEntries = (optimizeDeps.exclude ?? []).filter((entry) => {
14187
+ if (cloudflareBuiltInModules.includes(entry)) {
14188
+ return false;
14189
+ }
14190
+ if (NODEJS_MODULES_RE.test(entry) && isNodeCompat(resolvedPluginConfig.workers[envName])) {
14191
+ return false;
14192
+ }
14193
+ return true;
14194
+ });
14195
+ if (disallowedOptimizeDepsExcludeEntries.length > 0) {
14196
+ disallowedConfig.optimizeDepsExclude = disallowedOptimizeDepsExcludeEntries;
14197
+ }
14198
+ if (resolve7.external === true || resolve7.external.length > 0) {
14199
+ disallowedConfig.resolveExternal = resolve7.external;
14200
+ }
14201
+ if (Object.keys(disallowedConfig).length > 0) {
14202
+ disallowedEnvsConfigs.set(envName, disallowedConfig);
14203
+ }
14204
+ }
14205
+ if (disallowedEnvsConfigs.size > 0) {
14206
+ const errorMessage = `The following environment configurations are incompatible with the Cloudflare Vite plugin:
14207
+ ${[
14208
+ ...disallowedEnvsConfigs
14209
+ ].map(
14210
+ ([envName, disallowedConfig]) => [
14211
+ disallowedConfig.optimizeDepsExclude ? ` - "${envName}" environment: \`optimizeDeps.exclude\`: ${JSON.stringify(disallowedConfig.optimizeDepsExclude)}
14212
+ ` : null,
14213
+ disallowedConfig.resolveExternal ? ` - "${envName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedConfig.resolveExternal)}
14214
+ ` : null
14215
+ ].join("")
14216
+ ).join(
14217
+ ""
14218
+ )}To resolve this issue, avoid setting \`optimizeDeps.exclude\` and \`resolve.external\` in your Cloudflare Worker environments.
14219
+ `;
14220
+ throw new Error(errorMessage);
14221
+ }
14222
+ }
14223
+
14077
14224
  // src/index.ts
14078
14225
  var workersConfigsWarningShown = false;
14079
14226
  var miniflare;
@@ -14081,6 +14228,7 @@ function cloudflare2(pluginConfig = {}) {
14081
14228
  let resolvedPluginConfig;
14082
14229
  let resolvedViteConfig;
14083
14230
  const additionalModulePaths = /* @__PURE__ */ new Set();
14231
+ const nodeJsCompatWarningsMap = /* @__PURE__ */ new Map();
14084
14232
  let hasClientBuild = false;
14085
14233
  return [
14086
14234
  {
@@ -14131,7 +14279,7 @@ function cloudflare2(pluginConfig = {}) {
14131
14279
  builder: {
14132
14280
  buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
14133
14281
  const clientEnvironment = builder.environments.client;
14134
- const defaultHtmlPath = path8.resolve(
14282
+ const defaultHtmlPath = path9.resolve(
14135
14283
  builder.config.root,
14136
14284
  "index.html"
14137
14285
  );
@@ -14143,7 +14291,7 @@ function cloudflare2(pluginConfig = {}) {
14143
14291
  resolvedPluginConfig.workers
14144
14292
  ).map((environmentName) => {
14145
14293
  const environment = builder.environments[environmentName];
14146
- assert8(
14294
+ assert10(
14147
14295
  environment,
14148
14296
  `${environmentName} environment not found`
14149
14297
  );
@@ -14164,6 +14312,12 @@ function cloudflare2(pluginConfig = {}) {
14164
14312
  },
14165
14313
  configResolved(config) {
14166
14314
  resolvedViteConfig = config;
14315
+ if (resolvedPluginConfig?.type === "workers") {
14316
+ validateWorkerEnvironmentsResolvedConfigs(
14317
+ resolvedPluginConfig,
14318
+ resolvedViteConfig
14319
+ );
14320
+ }
14167
14321
  },
14168
14322
  generateBundle(_, bundle) {
14169
14323
  let config;
@@ -14184,15 +14338,15 @@ function cloudflare2(pluginConfig = {}) {
14184
14338
  if (isEntryWorker && hasClientBuild) {
14185
14339
  const workerOutputDirectory = this.environment.config.build.outDir;
14186
14340
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
14187
- assert8(
14341
+ assert10(
14188
14342
  clientOutputDirectory,
14189
14343
  "Unexpected error: client output directory is undefined"
14190
14344
  );
14191
14345
  workerConfig.assets = {
14192
14346
  ...workerConfig.assets,
14193
- directory: path8.relative(
14194
- path8.resolve(resolvedViteConfig.root, workerOutputDirectory),
14195
- path8.resolve(resolvedViteConfig.root, clientOutputDirectory)
14347
+ directory: path9.relative(
14348
+ path9.resolve(resolvedViteConfig.root, workerOutputDirectory),
14349
+ path9.resolve(resolvedViteConfig.root, clientOutputDirectory)
14196
14350
  )
14197
14351
  };
14198
14352
  } else {
@@ -14248,36 +14402,47 @@ function cloudflare2(pluginConfig = {}) {
14248
14402
  }
14249
14403
  },
14250
14404
  hotUpdate(options) {
14251
- if (
14252
- // Vite normalizes `options.file` so we use `path.resolve` for Windows compatibility
14253
- resolvedPluginConfig.configPaths.has(path8.resolve(options.file)) || hasAssetsConfigChanged(
14254
- resolvedPluginConfig,
14255
- resolvedViteConfig,
14256
- options.file
14257
- )
14258
- ) {
14405
+ const changedFilePath = path9.resolve(options.file);
14406
+ if (resolvedPluginConfig.configPaths.has(changedFilePath) || hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(
14407
+ resolvedPluginConfig,
14408
+ resolvedViteConfig,
14409
+ changedFilePath
14410
+ )) {
14259
14411
  options.server.restart();
14260
14412
  return [];
14261
14413
  }
14262
14414
  },
14263
14415
  async configureServer(viteDevServer) {
14264
- assert8(
14416
+ assert10(
14265
14417
  viteDevServer.httpServer,
14266
14418
  "Unexpected error: No Vite HTTP server"
14267
14419
  );
14268
- if (miniflare) {
14269
- await miniflare.setOptions(
14270
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14420
+ if (!miniflare) {
14421
+ const inputInspectorPort = await getInputInspectorPortOption(
14422
+ pluginConfig,
14423
+ viteDevServer
14271
14424
  );
14272
- } else {
14273
14425
  miniflare = new Miniflare(
14274
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14426
+ getDevMiniflareOptions(
14427
+ resolvedPluginConfig,
14428
+ viteDevServer,
14429
+ inputInspectorPort
14430
+ )
14431
+ );
14432
+ } else {
14433
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14434
+ await miniflare.setOptions(
14435
+ getDevMiniflareOptions(
14436
+ resolvedPluginConfig,
14437
+ viteDevServer,
14438
+ resolvedInspectorPort ?? false
14439
+ )
14275
14440
  );
14276
14441
  }
14277
14442
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14278
14443
  const middleware = createMiddleware(
14279
14444
  async ({ request }) => {
14280
- assert8(miniflare, `Miniflare not defined`);
14445
+ assert10(miniflare, `Miniflare not defined`);
14281
14446
  const routerWorker = await getRouterWorker(miniflare);
14282
14447
  return routerWorker.fetch(toMiniflareRequest(request), {
14283
14448
  redirect: "manual"
@@ -14286,7 +14451,7 @@ function cloudflare2(pluginConfig = {}) {
14286
14451
  { alwaysCallNext: false }
14287
14452
  );
14288
14453
  handleWebSocket(viteDevServer.httpServer, async () => {
14289
- assert8(miniflare, `Miniflare not defined`);
14454
+ assert10(miniflare, `Miniflare not defined`);
14290
14455
  const routerWorker = await getRouterWorker(miniflare);
14291
14456
  return routerWorker.fetch;
14292
14457
  });
@@ -14296,14 +14461,18 @@ function cloudflare2(pluginConfig = {}) {
14296
14461
  });
14297
14462
  };
14298
14463
  },
14299
- configurePreviewServer(vitePreviewServer) {
14464
+ async configurePreviewServer(vitePreviewServer) {
14300
14465
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14466
+ const inputInspectorPort = await getInputInspectorPortOption(
14467
+ pluginConfig,
14468
+ vitePreviewServer
14469
+ );
14301
14470
  const miniflare2 = new Miniflare(
14302
14471
  getPreviewMiniflareOptions(
14303
14472
  vitePreviewServer,
14304
14473
  workerConfigs,
14305
14474
  pluginConfig.persistState ?? true,
14306
- pluginConfig.inspectorPort
14475
+ inputInspectorPort
14307
14476
  )
14308
14477
  );
14309
14478
  const middleware = createMiddleware(
@@ -14382,7 +14551,7 @@ function cloudflare2(pluginConfig = {}) {
14382
14551
  for (const match of matches) {
14383
14552
  magicString ??= new MagicString(code);
14384
14553
  const [full, _, modulePath] = match;
14385
- assert8(
14554
+ assert10(
14386
14555
  modulePath,
14387
14556
  `Unexpected error: module path not found in reference ${full}.`
14388
14557
  );
@@ -14396,13 +14565,13 @@ function cloudflare2(pluginConfig = {}) {
14396
14565
  }
14397
14566
  const referenceId = this.emitFile({
14398
14567
  type: "asset",
14399
- name: path8.basename(modulePath),
14568
+ name: path9.basename(modulePath),
14400
14569
  originalFileName: modulePath,
14401
14570
  source
14402
14571
  });
14403
14572
  const emittedFileName = this.getFileName(referenceId);
14404
- const relativePath = vite6.normalizePath(
14405
- path8.relative(path8.dirname(chunk.fileName), emittedFileName)
14573
+ const relativePath = vite7.normalizePath(
14574
+ path9.relative(path9.dirname(chunk.fileName), emittedFileName)
14406
14575
  );
14407
14576
  const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
14408
14577
  magicString.update(
@@ -14428,26 +14597,28 @@ function cloudflare2(pluginConfig = {}) {
14428
14597
  configEnvironment(name) {
14429
14598
  if (isNodeCompat(getWorkerConfig2(name))) {
14430
14599
  return {
14600
+ build: {
14601
+ rollupOptions: {
14602
+ plugins: [
14603
+ replace({
14604
+ "process.env.NODE_ENV": JSON.stringify(
14605
+ process.env.NODE_ENV ?? "production"
14606
+ ),
14607
+ preventAssignment: true
14608
+ })
14609
+ ]
14610
+ }
14611
+ },
14431
14612
  resolve: {
14432
14613
  builtins: [...nodeCompatExternals]
14433
14614
  },
14434
14615
  optimizeDeps: {
14435
- // This is a list of dependency entry-points that should be pre-bundled.
14436
- // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
14437
- // ready ahead the first request to the dev server.
14438
- // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
14439
- // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
14440
- // TODO: work out how to re-enable pre-bundling of these
14441
- // include: [...getNodeCompatEntries()],
14442
14616
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
14443
14617
  // In this case we provide a list of all the Node.js modules, both those built-in to workerd and those that will be polyfilled.
14444
14618
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
14445
14619
  // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
14446
14620
  // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
14447
- exclude: [
14448
- ...builtinModules2,
14449
- ...builtinModules2.map((m) => `node:${m}`)
14450
- ]
14621
+ exclude: [...nodejsBuiltins]
14451
14622
  }
14452
14623
  };
14453
14624
  }
@@ -14465,7 +14636,7 @@ function cloudflare2(pluginConfig = {}) {
14465
14636
  return this.resolve(source, importer, options);
14466
14637
  }
14467
14638
  if (this.environment.mode === "dev") {
14468
- assert8(
14639
+ assert10(
14469
14640
  this.environment.depsOptimizer,
14470
14641
  "depsOptimizer is required in dev mode"
14471
14642
  );
@@ -14479,11 +14650,35 @@ function cloudflare2(pluginConfig = {}) {
14479
14650
  },
14480
14651
  async transform(code, id) {
14481
14652
  const workerConfig = getWorkerConfig2(this.environment.name);
14482
- assert8(workerConfig, "Expected a worker config");
14653
+ if (!workerConfig) {
14654
+ return;
14655
+ }
14483
14656
  const resolvedId = await this.resolve(workerConfig.main);
14484
14657
  if (id === resolvedId?.id) {
14485
14658
  return injectGlobalCode(id, code);
14486
14659
  }
14660
+ },
14661
+ async configureServer(viteDevServer) {
14662
+ await Promise.all(
14663
+ Object.values(viteDevServer.environments).flatMap(
14664
+ async (environment) => {
14665
+ const workerConfig = getWorkerConfig2(environment.name);
14666
+ if (isNodeCompat(workerConfig)) {
14667
+ await environment.depsOptimizer?.init();
14668
+ return Array.from(nodeCompatEntries).map((entry) => {
14669
+ const result = resolveNodeJSImport(entry);
14670
+ if (result) {
14671
+ const registration = environment.depsOptimizer?.registerMissingImport(
14672
+ result.unresolved,
14673
+ result.resolved
14674
+ );
14675
+ return registration?.processing;
14676
+ }
14677
+ });
14678
+ }
14679
+ }
14680
+ )
14681
+ );
14487
14682
  }
14488
14683
  },
14489
14684
  // Plugin that provides an __debug path for debugging the Cloudflare Workers.
@@ -14493,54 +14688,131 @@ function cloudflare2(pluginConfig = {}) {
14493
14688
  // the preview middleware here can take precedence
14494
14689
  enforce: "pre",
14495
14690
  configureServer(viteDevServer) {
14496
- if (resolvedPluginConfig.type === "workers" && resolvedPluginConfig.inspectorPort !== false) {
14691
+ if (resolvedPluginConfig.type === "workers" && pluginConfig.inspectorPort !== false) {
14497
14692
  addDebugToVitePrintUrls(viteDevServer);
14498
14693
  }
14499
14694
  const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
14500
14695
  (worker) => worker.name
14501
14696
  );
14502
- viteDevServer.middlewares.use((req, res, next) => {
14503
- if (req.url === debuggingPath && resolvedPluginConfig.inspectorPort !== false) {
14504
- const html = getDebugPathHtml(
14505
- workerNames,
14506
- resolvedPluginConfig.inspectorPort
14507
- );
14697
+ viteDevServer.middlewares.use(async (req, res, next) => {
14698
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14699
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14700
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14508
14701
  res.setHeader("Content-Type", "text/html");
14509
14702
  return res.end(html);
14510
14703
  }
14511
14704
  next();
14512
14705
  });
14513
14706
  },
14514
- configurePreviewServer(vitePreviewServer) {
14707
+ async configurePreviewServer(vitePreviewServer) {
14515
14708
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14516
14709
  if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
14517
14710
  addDebugToVitePrintUrls(vitePreviewServer);
14518
14711
  }
14519
14712
  const workerNames = workerConfigs.map((worker) => {
14520
- assert8(worker.name);
14713
+ assert10(worker.name, "Expected the Worker to have a name");
14521
14714
  return worker.name;
14522
14715
  });
14523
- vitePreviewServer.middlewares.use((req, res, next) => {
14524
- if (req.url === debuggingPath && pluginConfig.inspectorPort !== false) {
14525
- const html = getDebugPathHtml(
14526
- workerNames,
14527
- pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT
14528
- );
14716
+ vitePreviewServer.middlewares.use(async (req, res, next) => {
14717
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14718
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14719
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14529
14720
  res.setHeader("Content-Type", "text/html");
14530
14721
  return res.end(html);
14531
14722
  }
14532
14723
  next();
14533
14724
  });
14534
14725
  }
14726
+ },
14727
+ // Plugin to warn if Node.js APIs are being used without nodejs_compat turned on
14728
+ {
14729
+ name: "vite-plugin-cloudflare:nodejs-compat-warnings",
14730
+ apply(_config, env2) {
14731
+ return !env2.isPreview;
14732
+ },
14733
+ // We must ensure that the `resolveId` hook runs before the built-in ones.
14734
+ // Otherwise we never see the Node.js built-in imports since they get handled by default Vite behavior.
14735
+ enforce: "pre",
14736
+ configEnvironment(environmentName) {
14737
+ const workerConfig = getWorkerConfig2(environmentName);
14738
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14739
+ return {
14740
+ optimizeDeps: {
14741
+ esbuildOptions: {
14742
+ plugins: [
14743
+ {
14744
+ name: "vite-plugin-cloudflare:nodejs-compat-warnings-resolver",
14745
+ setup(build) {
14746
+ build.onResolve(
14747
+ { filter: NODEJS_MODULES_RE },
14748
+ ({ path: path10, importer }) => {
14749
+ const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14750
+ nodeJsCompatWarnings?.registerImport(path10, importer);
14751
+ return { path: path10, external: true };
14752
+ }
14753
+ );
14754
+ }
14755
+ }
14756
+ ]
14757
+ }
14758
+ }
14759
+ };
14760
+ }
14761
+ },
14762
+ configResolved(resolvedViteConfig2) {
14763
+ for (const environmentName of Object.keys(
14764
+ resolvedViteConfig2.environments
14765
+ )) {
14766
+ const workerConfig = getWorkerConfig2(environmentName);
14767
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14768
+ nodeJsCompatWarningsMap.set(
14769
+ workerConfig,
14770
+ new NodeJsCompatWarnings(environmentName, resolvedViteConfig2)
14771
+ );
14772
+ }
14773
+ }
14774
+ },
14775
+ async resolveId(source, importer) {
14776
+ const workerConfig = getWorkerConfig2(this.environment.name);
14777
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14778
+ const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14779
+ if (nodejsBuiltins.has(source)) {
14780
+ nodeJsCompatWarnings?.registerImport(source, importer);
14781
+ return {
14782
+ id: source,
14783
+ external: true
14784
+ };
14785
+ }
14786
+ }
14787
+ }
14535
14788
  }
14536
14789
  ];
14537
14790
  function getWorkerConfig2(environmentName) {
14538
- assert8(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14791
+ assert10(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14539
14792
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
14540
14793
  }
14541
14794
  }
14795
+ async function getInputInspectorPortOption(pluginConfig, viteServer) {
14796
+ const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
14797
+ if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
14798
+ viteServer.config.logger.warn(
14799
+ colors2.dim(
14800
+ `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
14801
+ `
14802
+ )
14803
+ );
14804
+ }
14805
+ return inputInspectorPort;
14806
+ }
14807
+ async function getResolvedInspectorPort(pluginConfig) {
14808
+ if (miniflare && pluginConfig.inspectorPort !== false) {
14809
+ const miniflareInspectorUrl = await miniflare.getInspectorURL();
14810
+ return Number.parseInt(miniflareInspectorUrl.port);
14811
+ }
14812
+ return null;
14813
+ }
14542
14814
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14543
- const configDir = path8.dirname(configPath);
14815
+ const configDir = path9.dirname(configPath);
14544
14816
  const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
14545
14817
  const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
14546
14818
  const targetPath = fs5.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs5.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
@@ -14550,6 +14822,19 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14550
14822
  }
14551
14823
  return null;
14552
14824
  }
14825
+ function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
14826
+ return [...resolvedPluginConfig.configPaths].some((configPath) => {
14827
+ const dotDevDotVars = path9.join(path9.dirname(configPath), ".dev.vars");
14828
+ if (dotDevDotVars === changedFilePath) {
14829
+ return true;
14830
+ }
14831
+ if (resolvedPluginConfig.cloudflareEnv) {
14832
+ const dotDevDotVarsForEnv = `${dotDevDotVars}.${resolvedPluginConfig.cloudflareEnv}`;
14833
+ return dotDevDotVarsForEnv === changedFilePath;
14834
+ }
14835
+ return false;
14836
+ });
14837
+ }
14553
14838
  export {
14554
14839
  cloudflare2 as cloudflare
14555
14840
  };