@cloudflare/vite-plugin 0.0.0-070ceaef9 → 0.0.0-078c568c2

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 colors3 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() {
@@ -5783,7 +5784,8 @@ var z = /* @__PURE__ */ Object.freeze({
5783
5784
  // ../workers-shared/utils/types.ts
5784
5785
  var InternalConfigSchema = z.object({
5785
5786
  account_id: z.number().optional(),
5786
- script_id: z.number().optional()
5787
+ script_id: z.number().optional(),
5788
+ debug: z.boolean().optional()
5787
5789
  });
5788
5790
  var RouterConfigSchema = z.object({
5789
5791
  invoke_user_worker_ahead_of_assets: z.boolean().optional(),
@@ -5831,14 +5833,14 @@ var AssetConfigSchema = z.object({
5831
5833
  });
5832
5834
 
5833
5835
  // src/asset-config.ts
5834
- function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFile) {
5836
+ function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFilePath) {
5835
5837
  if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) {
5836
5838
  return false;
5837
5839
  }
5838
5840
  return [
5839
5841
  getRedirectsConfigPath(resolvedViteConfig),
5840
5842
  getHeadersConfigPath(resolvedViteConfig)
5841
- ].includes(path.resolve(changedFile));
5843
+ ].includes(changedFilePath);
5842
5844
  }
5843
5845
  function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig) {
5844
5846
  const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
@@ -5905,10 +5907,12 @@ function getHeadersConfigPath(config) {
5905
5907
 
5906
5908
  // src/cloudflare-environment.ts
5907
5909
  import assert3 from "node:assert";
5908
- import * as vite2 from "vite";
5910
+ import * as vite3 from "vite";
5909
5911
 
5910
5912
  // src/node-js-compat.ts
5911
5913
  import assert2 from "node:assert";
5914
+ import { builtinModules as builtinModules2 } from "node:module";
5915
+ import path3 from "node:path";
5912
5916
  import { cloudflare } from "@cloudflare/unenv-preset";
5913
5917
  import { getNodeCompat } from "miniflare";
5914
5918
 
@@ -11460,17 +11464,17 @@ function withTrailingSlash(input = "", respectQueryAndFragment) {
11460
11464
  if (hasTrailingSlash(input, true)) {
11461
11465
  return input || "/";
11462
11466
  }
11463
- let path9 = input;
11467
+ let path10 = input;
11464
11468
  let fragment = "";
11465
11469
  const fragmentIndex = input.indexOf("#");
11466
11470
  if (fragmentIndex >= 0) {
11467
- path9 = input.slice(0, fragmentIndex);
11471
+ path10 = input.slice(0, fragmentIndex);
11468
11472
  fragment = input.slice(fragmentIndex);
11469
- if (!path9) {
11473
+ if (!path10) {
11470
11474
  return fragment;
11471
11475
  }
11472
11476
  }
11473
- const [s0, ...s] = path9.split("?");
11477
+ const [s0, ...s] = path10.split("?");
11474
11478
  return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
11475
11479
  }
11476
11480
  function isNonEmptyURL(url) {
@@ -11504,8 +11508,8 @@ import path2, { dirname as dirname2 } from "node:path";
11504
11508
  import v8 from "node:v8";
11505
11509
  import { format as format2, inspect } from "node:util";
11506
11510
  var BUILTIN_MODULES = new Set(builtinModules);
11507
- function normalizeSlash(path9) {
11508
- return path9.replace(/\\/g, "/");
11511
+ function normalizeSlash(path10) {
11512
+ return path10.replace(/\\/g, "/");
11509
11513
  }
11510
11514
  var own$1 = {}.hasOwnProperty;
11511
11515
  var classRegExp = /^([A-Z][a-z\d]*)+$/;
@@ -11618,8 +11622,8 @@ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
11618
11622
  * @param {string} [base]
11619
11623
  * @param {string} [message]
11620
11624
  */
11621
- (path9, base, message) => {
11622
- return `Invalid package config ${path9}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11625
+ (path10, base, message) => {
11626
+ return `Invalid package config ${path10}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11623
11627
  },
11624
11628
  Error
11625
11629
  );
@@ -11651,8 +11655,8 @@ codes.ERR_MODULE_NOT_FOUND = createError(
11651
11655
  * @param {string} base
11652
11656
  * @param {boolean} [exactUrl]
11653
11657
  */
11654
- (path9, base, exactUrl = false) => {
11655
- return `Cannot find ${exactUrl ? "module" : "package"} '${path9}' imported from ${base}`;
11658
+ (path10, base, exactUrl = false) => {
11659
+ return `Cannot find ${exactUrl ? "module" : "package"} '${path10}' imported from ${base}`;
11656
11660
  },
11657
11661
  Error
11658
11662
  );
@@ -11703,8 +11707,8 @@ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
11703
11707
  * @param {string} extension
11704
11708
  * @param {string} path
11705
11709
  */
11706
- (extension, path9) => {
11707
- return `Unknown file extension "${extension}" for ${path9}`;
11710
+ (extension, path10) => {
11711
+ return `Unknown file extension "${extension}" for ${path10}`;
11708
11712
  },
11709
11713
  TypeError
11710
11714
  );
@@ -12076,9 +12080,9 @@ Default "index" lookups for the main are deprecated for ES modules.`,
12076
12080
  );
12077
12081
  }
12078
12082
  }
12079
- function tryStatSync(path9) {
12083
+ function tryStatSync(path10) {
12080
12084
  try {
12081
- return statSync(path9);
12085
+ return statSync(path10);
12082
12086
  } catch {
12083
12087
  }
12084
12088
  }
@@ -12845,12 +12849,20 @@ function resolvePathSync(id, options) {
12845
12849
 
12846
12850
  // src/node-js-compat.ts
12847
12851
  import { defineEnv } from "unenv";
12852
+ import "vite";
12848
12853
  var { env } = defineEnv({
12849
12854
  nodeCompat: true,
12850
12855
  presets: [cloudflare]
12851
12856
  });
12852
12857
  var nodeCompatExternals = new Set(env.external);
12853
12858
  var nodeCompatEntries = getNodeCompatEntries();
12859
+ var nodejsBuiltins = /* @__PURE__ */ new Set([
12860
+ ...builtinModules2,
12861
+ ...builtinModules2.map((m) => `node:${m}`)
12862
+ ]);
12863
+ var NODEJS_MODULES_RE = new RegExp(
12864
+ `^(node:)?(${builtinModules2.join("|")})$`
12865
+ );
12854
12866
  function isNodeCompat(workerConfig) {
12855
12867
  if (workerConfig === void 0) {
12856
12868
  return false;
@@ -12869,6 +12881,15 @@ function isNodeCompat(workerConfig) {
12869
12881
  }
12870
12882
  return false;
12871
12883
  }
12884
+ function isNodeAls(workerConfig) {
12885
+ return workerConfig !== void 0 && getNodeCompat(
12886
+ workerConfig.compatibility_date,
12887
+ workerConfig.compatibility_flags ?? []
12888
+ ).mode === "als";
12889
+ }
12890
+ function isNodeAlsModule(path10) {
12891
+ return /^(node:)?async_hooks$/.test(path10);
12892
+ }
12872
12893
  function injectGlobalCode(id, code) {
12873
12894
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
12874
12895
  if (typeof globalInject === "string") {
@@ -12899,7 +12920,7 @@ globalThis.${globalName} = var_${globalName}.${exportName};
12899
12920
  }
12900
12921
  function resolveNodeJSImport(source) {
12901
12922
  const alias = env.alias[source];
12902
- if (alias) {
12923
+ if (alias && !nodeCompatExternals.has(alias)) {
12903
12924
  return {
12904
12925
  unresolved: alias,
12905
12926
  resolved: resolvePathSync(alias, { url: import.meta.url })
@@ -12929,6 +12950,45 @@ function getNodeCompatEntries() {
12929
12950
  nodeCompatExternals.forEach((external) => entries.delete(external));
12930
12951
  return entries;
12931
12952
  }
12953
+ var NodeJsCompatWarnings = class {
12954
+ constructor(environmentName, resolvedViteConfig) {
12955
+ this.environmentName = environmentName;
12956
+ this.resolvedViteConfig = resolvedViteConfig;
12957
+ }
12958
+ sources = /* @__PURE__ */ new Map();
12959
+ timer;
12960
+ registerImport(source, importer = "<unknown>") {
12961
+ const importers = this.sources.get(source) ?? /* @__PURE__ */ new Set();
12962
+ this.sources.set(source, importers);
12963
+ importers.add(importer);
12964
+ this.renderWarningsOnIdle();
12965
+ }
12966
+ renderWarningsOnIdle() {
12967
+ if (this.timer) {
12968
+ clearTimeout(this.timer);
12969
+ }
12970
+ this.timer = setTimeout(() => {
12971
+ this.renderWarnings();
12972
+ this.timer = void 0;
12973
+ }, 500);
12974
+ }
12975
+ renderWarnings() {
12976
+ if (this.sources.size > 0) {
12977
+ 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.
12978
+ `;
12979
+ this.sources.forEach((importers, source) => {
12980
+ importers.forEach((importer) => {
12981
+ message += ` - "${source}" imported from "${path3.relative(this.resolvedViteConfig.root, importer)}"
12982
+ `;
12983
+ });
12984
+ });
12985
+ this.resolvedViteConfig.logger.warn(message, {
12986
+ timestamp: true
12987
+ });
12988
+ this.sources.clear();
12989
+ }
12990
+ }
12991
+ };
12932
12992
 
12933
12993
  // src/shared.ts
12934
12994
  var UNKNOWN_HOST = "http://localhost";
@@ -12942,17 +13002,22 @@ var additionalModuleGlobalRE = new RegExp(
12942
13002
  var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
12943
13003
 
12944
13004
  // src/utils.ts
12945
- import * as path3 from "node:path";
13005
+ import * as path4 from "node:path";
13006
+ import getPort, { portNumbers } from "get-port";
12946
13007
  import { Request as MiniflareRequest } from "miniflare";
12947
13008
  import "vite";
12948
13009
  function getOutputDirectory(userConfig, environmentName) {
12949
13010
  const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
12950
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path3.join(rootOutputDirectory, environmentName);
13011
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path4.join(rootOutputDirectory, environmentName);
12951
13012
  }
12952
- function getRouterWorker(miniflare) {
12953
- return miniflare.getWorker(ROUTER_WORKER_NAME);
13013
+ function getRouterWorker(miniflare2) {
13014
+ return miniflare2.getWorker(ROUTER_WORKER_NAME);
12954
13015
  }
12955
13016
  function toMiniflareRequest(request) {
13017
+ const host = request.headers.get("Host");
13018
+ if (host) {
13019
+ request.headers.set("X-Forwarded-Host", host);
13020
+ }
12956
13021
  const secFetchMode = request.headers.get("Sec-Fetch-Mode");
12957
13022
  if (secFetchMode) {
12958
13023
  request.headers.set("X-Mf-Sec-Fetch-Mode", secFetchMode);
@@ -12981,6 +13046,9 @@ var postfixRE = /[?#].*$/;
12981
13046
  function cleanUrl(url) {
12982
13047
  return url.replace(postfixRE, "");
12983
13048
  }
13049
+ function getFirstAvailablePort(start) {
13050
+ return getPort({ port: portNumbers(start, 65535) });
13051
+ }
12984
13052
 
12985
13053
  // src/cloudflare-environment.ts
12986
13054
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -13026,7 +13094,7 @@ function createHotChannel(webSocketContainer) {
13026
13094
  }
13027
13095
  };
13028
13096
  }
13029
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
13097
+ var CloudflareDevEnvironment = class extends vite3.DevEnvironment {
13030
13098
  #webSocketContainer;
13031
13099
  #worker;
13032
13100
  constructor(name, config) {
@@ -13087,7 +13155,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
13087
13155
  },
13088
13156
  build: {
13089
13157
  createEnvironment(name, config) {
13090
- return new vite2.BuildEnvironment(name, config);
13158
+ return new vite3.BuildEnvironment(name, config);
13091
13159
  },
13092
13160
  target,
13093
13161
  // We need to enable `emitAssets` in order to support additional modules defined by `rules`
@@ -13130,14 +13198,14 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
13130
13198
  keepProcessEnv: isNodeCompat(workerConfig)
13131
13199
  };
13132
13200
  }
13133
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
13201
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare2) {
13134
13202
  if (resolvedPluginConfig.type === "assets-only") {
13135
13203
  return;
13136
13204
  }
13137
13205
  return Promise.all(
13138
13206
  Object.entries(resolvedPluginConfig.workers).map(
13139
13207
  async ([environmentName, workerConfig]) => {
13140
- const worker = await miniflare.getWorker(workerConfig.name);
13208
+ const worker = await miniflare2.getWorker(workerConfig.name);
13141
13209
  return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
13142
13210
  }
13143
13211
  )
@@ -13196,11 +13264,11 @@ function getDebugPathHtml(workerNames, inspectorPort) {
13196
13264
  // src/deploy-config.ts
13197
13265
  import assert5 from "node:assert";
13198
13266
  import * as fs2 from "node:fs";
13199
- import * as path4 from "node:path";
13267
+ import * as path5 from "node:path";
13200
13268
  import "vite";
13201
13269
  import { unstable_readConfig } from "wrangler";
13202
13270
  function getDeployConfigPath(root) {
13203
- return path4.resolve(root, ".wrangler", "deploy", "config.json");
13271
+ return path5.resolve(root, ".wrangler", "deploy", "config.json");
13204
13272
  }
13205
13273
  function getWorkerConfigs(root) {
13206
13274
  const deployConfigPath = getDeployConfigPath(root);
@@ -13211,22 +13279,22 @@ function getWorkerConfigs(root) {
13211
13279
  { configPath: deployConfig.configPath },
13212
13280
  ...deployConfig.auxiliaryWorkers
13213
13281
  ].map(({ configPath }) => {
13214
- const resolvedConfigPath = path4.resolve(
13215
- path4.dirname(deployConfigPath),
13282
+ const resolvedConfigPath = path5.resolve(
13283
+ path5.dirname(deployConfigPath),
13216
13284
  configPath
13217
13285
  );
13218
13286
  return unstable_readConfig({ config: resolvedConfigPath });
13219
13287
  });
13220
13288
  }
13221
13289
  function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
13222
- return path4.relative(
13290
+ return path5.relative(
13223
13291
  deployConfigDirectory,
13224
- path4.resolve(root, outputDirectory, "wrangler.json")
13292
+ path5.resolve(root, outputDirectory, "wrangler.json")
13225
13293
  );
13226
13294
  }
13227
13295
  function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13228
13296
  const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
13229
- const deployConfigDirectory = path4.dirname(deployConfigPath);
13297
+ const deployConfigDirectory = path5.dirname(deployConfigPath);
13230
13298
  fs2.mkdirSync(deployConfigDirectory, { recursive: true });
13231
13299
  if (resolvedPluginConfig.type === "assets-only") {
13232
13300
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
@@ -13279,7 +13347,7 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13279
13347
  import assert6 from "node:assert";
13280
13348
  import * as fs3 from "node:fs";
13281
13349
  import * as fsp from "node:fs/promises";
13282
- import * as path5 from "node:path";
13350
+ import * as path6 from "node:path";
13283
13351
  import { fileURLToPath as fileURLToPath2 } from "node:url";
13284
13352
  import {
13285
13353
  kCurrentWorker,
@@ -13287,6 +13355,7 @@ import {
13287
13355
  LogLevel,
13288
13356
  Response as MiniflareResponse
13289
13357
  } from "miniflare";
13358
+ import colors2 from "picocolors";
13290
13359
  import { globSync } from "tinyglobby";
13291
13360
  import "vite";
13292
13361
  import { unstable_getMiniflareWorkerOptions } from "wrangler";
@@ -13295,18 +13364,18 @@ function getPersistence(root, persistState) {
13295
13364
  return {};
13296
13365
  }
13297
13366
  const defaultPersistPath = ".wrangler/state";
13298
- const persistPath = path5.resolve(
13367
+ const persistPath = path6.resolve(
13299
13368
  root,
13300
13369
  typeof persistState === "object" ? persistState.path : defaultPersistPath,
13301
13370
  "v3"
13302
13371
  );
13303
13372
  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")
13373
+ cachePersist: path6.join(persistPath, "cache"),
13374
+ d1Persist: path6.join(persistPath, "d1"),
13375
+ durableObjectsPersist: path6.join(persistPath, "do"),
13376
+ kvPersist: path6.join(persistPath, "kv"),
13377
+ r2Persist: path6.join(persistPath, "r2"),
13378
+ workflowsPersist: path6.join(persistPath, "workflows")
13310
13379
  };
13311
13380
  }
13312
13381
  function missingWorkerErrorMessage(workerName) {
@@ -13391,7 +13460,30 @@ function getEntryWorkerConfig(resolvedPluginConfig) {
13391
13460
  }
13392
13461
  return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
13393
13462
  }
13394
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13463
+ function filterTails(tails, userWorkers, log) {
13464
+ return tails?.filter((tailService) => {
13465
+ let name;
13466
+ if (typeof tailService === "string") {
13467
+ name = tailService;
13468
+ } else if (typeof tailService === "object" && "name" in tailService && typeof tailService.name === "string") {
13469
+ name = tailService.name;
13470
+ } else {
13471
+ return true;
13472
+ }
13473
+ const found = userWorkers.some((w) => w.name === name);
13474
+ if (!found) {
13475
+ log(
13476
+ colors2.dim(
13477
+ colors2.yellow(
13478
+ `Tail consumer "${name}" was not found in your config. Make sure you add it if you'd like to simulate receiving tail events locally.`
13479
+ )
13480
+ )
13481
+ );
13482
+ }
13483
+ return found;
13484
+ });
13485
+ }
13486
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspectorPort) {
13395
13487
  const resolvedViteConfig = viteDevServer.config;
13396
13488
  const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
13397
13489
  const assetsConfig = getAssetsConfig(
@@ -13407,7 +13499,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13407
13499
  modules: [
13408
13500
  {
13409
13501
  type: "ESModule",
13410
- path: path5.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13502
+ path: path6.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13411
13503
  contents: fs3.readFileSync(
13412
13504
  fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
13413
13505
  )
@@ -13430,7 +13522,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13430
13522
  modules: [
13431
13523
  {
13432
13524
  type: "ESModule",
13433
- path: path5.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13525
+ path: path6.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13434
13526
  contents: fs3.readFileSync(
13435
13527
  fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
13436
13528
  )
@@ -13442,7 +13534,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13442
13534
  serviceBindings: {
13443
13535
  __VITE_ASSET_EXISTS__: async (request) => {
13444
13536
  const { pathname } = new URL(request.url);
13445
- const filePath = path5.join(resolvedViteConfig.root, pathname);
13537
+ const filePath = path6.join(resolvedViteConfig.root, pathname);
13446
13538
  let exists;
13447
13539
  try {
13448
13540
  exists = fs3.statSync(filePath).isFile();
@@ -13453,7 +13545,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13453
13545
  },
13454
13546
  __VITE_FETCH_ASSET__: async (request) => {
13455
13547
  const { pathname } = new URL(request.url);
13456
- const filePath = path5.join(resolvedViteConfig.root, pathname);
13548
+ const filePath = path6.join(resolvedViteConfig.root, pathname);
13457
13549
  try {
13458
13550
  let html = await fsp.readFile(filePath, "utf-8");
13459
13551
  html = await viteDevServer.transformIndexHtml(pathname, html);
@@ -13483,7 +13575,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13483
13575
  worker: {
13484
13576
  ...workerOptions,
13485
13577
  name: workerOptions.name ?? workerConfig.name,
13486
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13578
+ unsafeInspectorProxy: inspectorPort !== false,
13487
13579
  modulesRoot: miniflareModulesRoot,
13488
13580
  unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
13489
13581
  serviceBindings: {
@@ -13525,8 +13617,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13525
13617
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13526
13618
  return {
13527
13619
  log: logger,
13528
- inspectorPort: resolvedPluginConfig.inspectorPort || void 0,
13529
- unsafeInspectorProxy: resolvedPluginConfig.inspectorPort !== false,
13620
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13621
+ unsafeInspectorProxy: inspectorPort !== false,
13530
13622
  handleRuntimeStdio(stdout, stderr) {
13531
13623
  const decoder = new TextDecoder();
13532
13624
  stdout.forEach((data2) => logger.info(decoder.decode(data2)));
@@ -13582,15 +13674,20 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13582
13674
  }
13583
13675
  return {
13584
13676
  ...workerOptions,
13677
+ tails: filterTails(
13678
+ workerOptions.tails,
13679
+ userWorkers,
13680
+ viteDevServer.config.logger.warn
13681
+ ),
13585
13682
  modules: [
13586
13683
  {
13587
13684
  type: "ESModule",
13588
- path: path5.join(miniflareModulesRoot, WRAPPER_PATH),
13685
+ path: path6.join(miniflareModulesRoot, WRAPPER_PATH),
13589
13686
  contents: wrappers.join("\n")
13590
13687
  },
13591
13688
  {
13592
13689
  type: "ESModule",
13593
- path: path5.join(miniflareModulesRoot, RUNNER_PATH),
13690
+ path: path6.join(miniflareModulesRoot, RUNNER_PATH),
13594
13691
  contents: fs3.readFileSync(
13595
13692
  fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
13596
13693
  )
@@ -13645,8 +13742,8 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
13645
13742
  }
13646
13743
  function getPreviewModules(main, modulesRules) {
13647
13744
  assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
13648
- const rootPath = path5.dirname(main);
13649
- const entryPath = path5.basename(main);
13745
+ const rootPath = path6.dirname(main);
13746
+ const entryPath = path6.basename(main);
13650
13747
  return {
13651
13748
  rootPath,
13652
13749
  modules: [
@@ -13655,15 +13752,15 @@ function getPreviewModules(main, modulesRules) {
13655
13752
  path: entryPath
13656
13753
  },
13657
13754
  ...modulesRules.flatMap(
13658
- ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path9) => ({
13755
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path10) => ({
13659
13756
  type,
13660
- path: path9
13757
+ path: path10
13661
13758
  }))
13662
13759
  )
13663
13760
  ]
13664
13761
  };
13665
13762
  }
13666
- function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort = DEFAULT_INSPECTOR_PORT) {
13763
+ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, inspectorPort) {
13667
13764
  const resolvedViteConfig = vitePreviewServer.config;
13668
13765
  const workers = workerConfigs.flatMap((config) => {
13669
13766
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
@@ -13672,6 +13769,11 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13672
13769
  return [
13673
13770
  {
13674
13771
  ...workerOptions,
13772
+ tails: filterTails(
13773
+ workerOptions.tails,
13774
+ workerConfigs,
13775
+ vitePreviewServer.config.logger.warn
13776
+ ),
13675
13777
  name: workerOptions.name ?? config.name,
13676
13778
  unsafeInspectorProxy: inspectorPort !== false,
13677
13779
  ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
@@ -13682,7 +13784,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13682
13784
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
13683
13785
  return {
13684
13786
  log: logger,
13685
- inspectorPort: inspectorPort || void 0,
13787
+ inspectorPort: inspectorPort === false ? void 0 : inspectorPort,
13686
13788
  unsafeInspectorProxy: inspectorPort !== false,
13687
13789
  handleRuntimeStdio(stdout, stderr) {
13688
13790
  const decoder = new TextDecoder();
@@ -13695,6 +13797,7 @@ function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistSta
13695
13797
  workers
13696
13798
  };
13697
13799
  }
13800
+ var removedMessages = [/^Ready on http/, /^Updated and ready on http/];
13698
13801
  var ViteMiniflareLogger = class extends Log {
13699
13802
  logger;
13700
13803
  constructor(config) {
@@ -13702,8 +13805,10 @@ var ViteMiniflareLogger = class extends Log {
13702
13805
  this.logger = config.logger;
13703
13806
  }
13704
13807
  logWithLevel(level, message) {
13705
- if (/^Ready on http/.test(message)) {
13706
- level = LogLevel.DEBUG;
13808
+ for (const removedMessage of removedMessages) {
13809
+ if (removedMessage.test(message)) {
13810
+ return;
13811
+ }
13707
13812
  }
13708
13813
  switch (level) {
13709
13814
  case LogLevel.ERROR:
@@ -13729,13 +13834,14 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
13729
13834
  }
13730
13835
 
13731
13836
  // src/plugin-config.ts
13732
- import assert7 from "node:assert";
13733
- import * as path7 from "node:path";
13734
- import * as vite5 from "vite";
13837
+ import assert8 from "node:assert";
13838
+ import * as path8 from "node:path";
13839
+ import * as vite6 from "vite";
13735
13840
 
13736
13841
  // src/workers-configs.ts
13842
+ import assert7 from "node:assert";
13737
13843
  import * as fs4 from "node:fs";
13738
- import * as path6 from "node:path";
13844
+ import * as path7 from "node:path";
13739
13845
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
13740
13846
  var nonApplicableWorkerConfigs = {
13741
13847
  /**
@@ -13767,8 +13873,7 @@ var nonApplicableWorkerConfigs = {
13767
13873
  "preserve_file_names",
13768
13874
  "rules",
13769
13875
  "site",
13770
- "tsconfig",
13771
- "upload_source_maps"
13876
+ "tsconfig"
13772
13877
  ]
13773
13878
  };
13774
13879
  var nullableNonApplicable = [
@@ -13779,8 +13884,7 @@ var nullableNonApplicable = [
13779
13884
  "no_bundle",
13780
13885
  "preserve_file_names",
13781
13886
  "site",
13782
- "tsconfig",
13783
- "upload_source_maps"
13887
+ "tsconfig"
13784
13888
  ];
13785
13889
  function readWorkerConfig(configPath, env2) {
13786
13890
  const nonApplicable = {
@@ -13829,7 +13933,7 @@ function getWarningForWorkersConfigs(configs) {
13829
13933
  const lines2 = [
13830
13934
  `
13831
13935
 
13832
- \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:`
13936
+ \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:`
13833
13937
  ];
13834
13938
  nonApplicableLines.forEach((line) => lines2.push(line));
13835
13939
  lines2.push("");
@@ -13843,7 +13947,7 @@ function getWarningForWorkersConfigs(configs) {
13843
13947
  );
13844
13948
  if (nonApplicableLines.length > 0) {
13845
13949
  lines.push(
13846
- ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path6.relative("", workerConfig.config.configPath)}\`)` : ""}`
13950
+ ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path7.relative("", workerConfig.config.configPath)}\`)` : ""}`
13847
13951
  );
13848
13952
  nonApplicableLines.forEach((line) => lines.push(line));
13849
13953
  }
@@ -13942,14 +14046,52 @@ function getWorkerConfig(configPath, env2, opts) {
13942
14046
  nonApplicable
13943
14047
  };
13944
14048
  }
14049
+ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
14050
+ if (requestedConfigPath) {
14051
+ const configPath2 = path7.resolve(root, requestedConfigPath);
14052
+ const forAuxiliaryWorkerErrorMessage = isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : "";
14053
+ const errorMessagePrefix = `The provided configPath (${configPath2})${forAuxiliaryWorkerErrorMessage}`;
14054
+ const fileExtension = path7.extname(configPath2).slice(1);
14055
+ if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
14056
+ const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
14057
+ throw new Error(
14058
+ `${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`
14059
+ );
14060
+ }
14061
+ const mainStat = fs4.statSync(configPath2, { throwIfNoEntry: false });
14062
+ if (!mainStat) {
14063
+ throw new Error(
14064
+ `${errorMessagePrefix} doesn't point to an existing file`
14065
+ );
14066
+ }
14067
+ if (mainStat.isDirectory()) {
14068
+ throw new Error(
14069
+ `${errorMessagePrefix} points to a directory. It should point to a file.`
14070
+ );
14071
+ }
14072
+ return configPath2;
14073
+ }
14074
+ assert7(
14075
+ isForAuxiliaryWorker === false,
14076
+ "Unexpected Error: trying to find the wrangler config for an auxiliary worker"
14077
+ );
14078
+ const configPath = findWranglerConfig(root);
14079
+ if (!configPath) {
14080
+ throw new Error(
14081
+ `No config file found in the ${root} directory. Please add a wrangler.(jsonc|json|toml) file.`
14082
+ );
14083
+ }
14084
+ return configPath;
14085
+ }
13945
14086
  function findWranglerConfig(root) {
13946
- for (const extension of ["json", "jsonc", "toml"]) {
13947
- const configPath = path6.join(root, `wrangler.${extension}`);
14087
+ for (const extension of allowedWranglerConfigExtensions) {
14088
+ const configPath = path7.join(root, `wrangler.${extension}`);
13948
14089
  if (fs4.existsSync(configPath)) {
13949
14090
  return configPath;
13950
14091
  }
13951
14092
  }
13952
14093
  }
14094
+ var allowedWranglerConfigExtensions = ["jsonc", "json", "toml"];
13953
14095
 
13954
14096
  // src/plugin-config.ts
13955
14097
  function workerNameToEnvironmentName(workerName) {
@@ -13958,31 +14100,31 @@ function workerNameToEnvironmentName(workerName) {
13958
14100
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
13959
14101
  const configPaths = /* @__PURE__ */ new Set();
13960
14102
  const persistState = pluginConfig.persistState ?? true;
13961
- const inspectorPort = pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT;
13962
14103
  const experimental = pluginConfig.experimental ?? {};
13963
- const root = userConfig.root ? path7.resolve(userConfig.root) : process.cwd();
13964
- const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
14104
+ const root = userConfig.root ? path8.resolve(userConfig.root) : process.cwd();
14105
+ const { CLOUDFLARE_ENV: cloudflareEnv } = vite6.loadEnv(
13965
14106
  viteEnv.mode,
13966
14107
  root,
13967
14108
  /* prefixes */
13968
14109
  ""
13969
14110
  );
13970
- const configPath = pluginConfig.configPath ? path7.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
13971
- if (!configPath) {
13972
- throw new Error(
13973
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
13974
- );
13975
- }
13976
- const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
13977
- visitedConfigPaths: configPaths,
13978
- isEntryWorker: true
13979
- });
14111
+ const entryWorkerConfigPath = getValidatedWranglerConfigPath(
14112
+ root,
14113
+ pluginConfig.configPath
14114
+ );
14115
+ const entryWorkerResolvedConfig = getWorkerConfig(
14116
+ entryWorkerConfigPath,
14117
+ cloudflareEnv,
14118
+ {
14119
+ visitedConfigPaths: configPaths,
14120
+ isEntryWorker: true
14121
+ }
14122
+ );
13980
14123
  if (entryWorkerResolvedConfig.type === "assets-only") {
13981
14124
  return {
13982
14125
  type: "assets-only",
13983
14126
  config: entryWorkerResolvedConfig.config,
13984
14127
  configPaths,
13985
- inspectorPort,
13986
14128
  persistState,
13987
14129
  rawConfigs: {
13988
14130
  entryWorker: entryWorkerResolvedConfig
@@ -13998,15 +14140,20 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
13998
14140
  };
13999
14141
  const auxiliaryWorkersResolvedConfigs = [];
14000
14142
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
14143
+ const workerConfigPath = getValidatedWranglerConfigPath(
14144
+ root,
14145
+ auxiliaryWorker.configPath,
14146
+ true
14147
+ );
14001
14148
  const workerResolvedConfig = getWorkerConfig(
14002
- path7.resolve(root, auxiliaryWorker.configPath),
14149
+ workerConfigPath,
14003
14150
  cloudflareEnv,
14004
14151
  {
14005
14152
  visitedConfigPaths: configPaths
14006
14153
  }
14007
14154
  );
14008
14155
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
14009
- assert7(
14156
+ assert8(
14010
14157
  workerResolvedConfig.type === "worker",
14011
14158
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
14012
14159
  );
@@ -14023,7 +14170,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14023
14170
  type: "workers",
14024
14171
  configPaths,
14025
14172
  persistState,
14026
- inspectorPort,
14027
14173
  workers,
14028
14174
  entryWorkerEnvironmentName,
14029
14175
  rawConfigs: {
@@ -14038,7 +14184,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14038
14184
  // src/websockets.ts
14039
14185
  import { coupleWebSocket } from "miniflare";
14040
14186
  import { WebSocketServer } from "ws";
14041
- function handleWebSocket(httpServer, fetcher) {
14187
+ function handleWebSocket(httpServer, getFetcher) {
14042
14188
  const nodeWebSocket = new WebSocketServer({ noServer: true });
14043
14189
  httpServer.on(
14044
14190
  "upgrade",
@@ -14048,6 +14194,7 @@ function handleWebSocket(httpServer, fetcher) {
14048
14194
  return;
14049
14195
  }
14050
14196
  const headers = nodeHeadersToWebHeaders(request.headers);
14197
+ const fetcher = await getFetcher();
14051
14198
  const response = await fetcher(url, {
14052
14199
  headers,
14053
14200
  method: request.method
@@ -14070,13 +14217,65 @@ function handleWebSocket(httpServer, fetcher) {
14070
14217
  );
14071
14218
  }
14072
14219
 
14220
+ // src/worker-environments-validation.ts
14221
+ import assert9 from "node:assert";
14222
+ function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolvedViteConfig) {
14223
+ const workersEnvironmentNames = Object.keys(resolvedPluginConfig.workers);
14224
+ const disallowedEnvsConfigs = /* @__PURE__ */ new Map();
14225
+ for (const envName of workersEnvironmentNames) {
14226
+ const workerEnvConfig = resolvedViteConfig.environments[envName];
14227
+ assert9(workerEnvConfig, `Missing environment config for "${envName}"`);
14228
+ const { optimizeDeps, resolve: resolve7 } = workerEnvConfig;
14229
+ const disallowedConfig = {};
14230
+ const disallowedOptimizeDepsExcludeEntries = (optimizeDeps.exclude ?? []).filter((entry) => {
14231
+ if (cloudflareBuiltInModules.includes(entry)) {
14232
+ return false;
14233
+ }
14234
+ if (isNodeAlsModule(entry) && isNodeAls(resolvedPluginConfig.workers[envName])) {
14235
+ return false;
14236
+ }
14237
+ if (NODEJS_MODULES_RE.test(entry) && isNodeCompat(resolvedPluginConfig.workers[envName])) {
14238
+ return false;
14239
+ }
14240
+ return true;
14241
+ });
14242
+ if (disallowedOptimizeDepsExcludeEntries.length > 0) {
14243
+ disallowedConfig.optimizeDepsExclude = disallowedOptimizeDepsExcludeEntries;
14244
+ }
14245
+ if (resolve7.external === true || resolve7.external.length > 0) {
14246
+ disallowedConfig.resolveExternal = resolve7.external;
14247
+ }
14248
+ if (Object.keys(disallowedConfig).length > 0) {
14249
+ disallowedEnvsConfigs.set(envName, disallowedConfig);
14250
+ }
14251
+ }
14252
+ if (disallowedEnvsConfigs.size > 0) {
14253
+ const errorMessage = `The following environment configurations are incompatible with the Cloudflare Vite plugin:
14254
+ ${[
14255
+ ...disallowedEnvsConfigs
14256
+ ].map(
14257
+ ([envName, disallowedConfig]) => [
14258
+ disallowedConfig.optimizeDepsExclude ? ` - "${envName}" environment: \`optimizeDeps.exclude\`: ${JSON.stringify(disallowedConfig.optimizeDepsExclude)}
14259
+ ` : null,
14260
+ disallowedConfig.resolveExternal ? ` - "${envName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedConfig.resolveExternal)}
14261
+ ` : null
14262
+ ].join("")
14263
+ ).join(
14264
+ ""
14265
+ )}To resolve this issue, avoid setting \`optimizeDeps.exclude\` and \`resolve.external\` in your Cloudflare Worker environments.
14266
+ `;
14267
+ throw new Error(errorMessage);
14268
+ }
14269
+ }
14270
+
14073
14271
  // src/index.ts
14074
14272
  var workersConfigsWarningShown = false;
14273
+ var miniflare;
14075
14274
  function cloudflare2(pluginConfig = {}) {
14076
14275
  let resolvedPluginConfig;
14077
14276
  let resolvedViteConfig;
14078
- let miniflare;
14079
14277
  const additionalModulePaths = /* @__PURE__ */ new Set();
14278
+ const nodeJsCompatWarningsMap = /* @__PURE__ */ new Map();
14080
14279
  let hasClientBuild = false;
14081
14280
  return [
14082
14281
  {
@@ -14127,7 +14326,7 @@ function cloudflare2(pluginConfig = {}) {
14127
14326
  builder: {
14128
14327
  buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
14129
14328
  const clientEnvironment = builder.environments.client;
14130
- const defaultHtmlPath = path8.resolve(
14329
+ const defaultHtmlPath = path9.resolve(
14131
14330
  builder.config.root,
14132
14331
  "index.html"
14133
14332
  );
@@ -14139,7 +14338,7 @@ function cloudflare2(pluginConfig = {}) {
14139
14338
  resolvedPluginConfig.workers
14140
14339
  ).map((environmentName) => {
14141
14340
  const environment = builder.environments[environmentName];
14142
- assert8(
14341
+ assert10(
14143
14342
  environment,
14144
14343
  `${environmentName} environment not found`
14145
14344
  );
@@ -14160,6 +14359,12 @@ function cloudflare2(pluginConfig = {}) {
14160
14359
  },
14161
14360
  configResolved(config) {
14162
14361
  resolvedViteConfig = config;
14362
+ if (resolvedPluginConfig?.type === "workers") {
14363
+ validateWorkerEnvironmentsResolvedConfigs(
14364
+ resolvedPluginConfig,
14365
+ resolvedViteConfig
14366
+ );
14367
+ }
14163
14368
  },
14164
14369
  generateBundle(_, bundle) {
14165
14370
  let config;
@@ -14180,15 +14385,15 @@ function cloudflare2(pluginConfig = {}) {
14180
14385
  if (isEntryWorker && hasClientBuild) {
14181
14386
  const workerOutputDirectory = this.environment.config.build.outDir;
14182
14387
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
14183
- assert8(
14388
+ assert10(
14184
14389
  clientOutputDirectory,
14185
14390
  "Unexpected error: client output directory is undefined"
14186
14391
  );
14187
14392
  workerConfig.assets = {
14188
14393
  ...workerConfig.assets,
14189
- directory: path8.relative(
14190
- path8.resolve(resolvedViteConfig.root, workerOutputDirectory),
14191
- path8.resolve(resolvedViteConfig.root, clientOutputDirectory)
14394
+ directory: path9.relative(
14395
+ path9.resolve(resolvedViteConfig.root, workerOutputDirectory),
14396
+ path9.resolve(resolvedViteConfig.root, clientOutputDirectory)
14192
14397
  )
14193
14398
  };
14194
14399
  } else {
@@ -14243,54 +14448,75 @@ function cloudflare2(pluginConfig = {}) {
14243
14448
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
14244
14449
  }
14245
14450
  },
14246
- handleHotUpdate(options) {
14247
- if (resolvedPluginConfig.configPaths.has(options.file) || hasAssetsConfigChanged(
14451
+ hotUpdate(options) {
14452
+ const changedFilePath = path9.resolve(options.file);
14453
+ if (resolvedPluginConfig.configPaths.has(changedFilePath) || hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(
14248
14454
  resolvedPluginConfig,
14249
14455
  resolvedViteConfig,
14250
- options.file
14456
+ changedFilePath
14251
14457
  )) {
14252
14458
  options.server.restart();
14253
- }
14254
- },
14255
- async buildEnd() {
14256
- if (miniflare) {
14257
- await miniflare.dispose();
14258
- miniflare = void 0;
14459
+ return [];
14259
14460
  }
14260
14461
  },
14261
14462
  async configureServer(viteDevServer) {
14262
- assert8(
14263
- viteDevServer.httpServer,
14264
- "Unexpected error: No Vite HTTP server"
14265
- );
14266
- miniflare = new Miniflare(
14267
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
14463
+ const inputInspectorPort = await getInputInspectorPortOption(
14464
+ pluginConfig,
14465
+ viteDevServer
14268
14466
  );
14467
+ if (!miniflare) {
14468
+ miniflare = new Miniflare(
14469
+ getDevMiniflareOptions(
14470
+ resolvedPluginConfig,
14471
+ viteDevServer,
14472
+ inputInspectorPort
14473
+ )
14474
+ );
14475
+ } else {
14476
+ await miniflare.setOptions(
14477
+ getDevMiniflareOptions(
14478
+ resolvedPluginConfig,
14479
+ viteDevServer,
14480
+ inputInspectorPort
14481
+ )
14482
+ );
14483
+ }
14269
14484
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14270
- const routerWorker = await getRouterWorker(miniflare);
14271
14485
  const middleware = createMiddleware(
14272
- ({ request }) => {
14486
+ async ({ request }) => {
14487
+ assert10(miniflare, `Miniflare not defined`);
14488
+ const routerWorker = await getRouterWorker(miniflare);
14273
14489
  return routerWorker.fetch(toMiniflareRequest(request), {
14274
14490
  redirect: "manual"
14275
14491
  });
14276
14492
  },
14277
14493
  { alwaysCallNext: false }
14278
14494
  );
14279
- handleWebSocket(viteDevServer.httpServer, routerWorker.fetch);
14495
+ if (viteDevServer.httpServer) {
14496
+ handleWebSocket(viteDevServer.httpServer, async () => {
14497
+ assert10(miniflare, `Miniflare not defined`);
14498
+ const routerWorker = await getRouterWorker(miniflare);
14499
+ return routerWorker.fetch;
14500
+ });
14501
+ }
14280
14502
  return () => {
14281
14503
  viteDevServer.middlewares.use((req, res, next) => {
14282
14504
  middleware(req, res, next);
14283
14505
  });
14284
14506
  };
14285
14507
  },
14286
- configurePreviewServer(vitePreviewServer) {
14508
+ async configurePreviewServer(vitePreviewServer) {
14287
14509
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14510
+ const inputInspectorPort = await getInputInspectorPortOption(
14511
+ pluginConfig,
14512
+ vitePreviewServer
14513
+ );
14288
14514
  const miniflare2 = new Miniflare(
14289
14515
  getPreviewMiniflareOptions(
14290
14516
  vitePreviewServer,
14291
14517
  workerConfigs,
14292
14518
  pluginConfig.persistState ?? true,
14293
- pluginConfig.inspectorPort
14519
+ inputInspectorPort
14294
14520
  )
14295
14521
  );
14296
14522
  const middleware = createMiddleware(
@@ -14301,7 +14527,10 @@ function cloudflare2(pluginConfig = {}) {
14301
14527
  },
14302
14528
  { alwaysCallNext: false }
14303
14529
  );
14304
- handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
14530
+ handleWebSocket(
14531
+ vitePreviewServer.httpServer,
14532
+ () => miniflare2.dispatchFetch
14533
+ );
14305
14534
  vitePreviewServer.middlewares.use((req, res, next) => {
14306
14535
  middleware(req, res, next);
14307
14536
  });
@@ -14357,6 +14586,7 @@ function cloudflare2(pluginConfig = {}) {
14357
14586
  hotUpdate(options) {
14358
14587
  if (additionalModulePaths.has(options.file)) {
14359
14588
  options.server.restart();
14589
+ return [];
14360
14590
  }
14361
14591
  },
14362
14592
  async renderChunk(code, chunk) {
@@ -14365,7 +14595,7 @@ function cloudflare2(pluginConfig = {}) {
14365
14595
  for (const match of matches) {
14366
14596
  magicString ??= new MagicString(code);
14367
14597
  const [full, _, modulePath] = match;
14368
- assert8(
14598
+ assert10(
14369
14599
  modulePath,
14370
14600
  `Unexpected error: module path not found in reference ${full}.`
14371
14601
  );
@@ -14379,13 +14609,13 @@ function cloudflare2(pluginConfig = {}) {
14379
14609
  }
14380
14610
  const referenceId = this.emitFile({
14381
14611
  type: "asset",
14382
- name: path8.basename(modulePath),
14612
+ name: path9.basename(modulePath),
14383
14613
  originalFileName: modulePath,
14384
14614
  source
14385
14615
  });
14386
14616
  const emittedFileName = this.getFileName(referenceId);
14387
- const relativePath = vite6.normalizePath(
14388
- path8.relative(path8.dirname(chunk.fileName), emittedFileName)
14617
+ const relativePath = vite7.normalizePath(
14618
+ path9.relative(path9.dirname(chunk.fileName), emittedFileName)
14389
14619
  );
14390
14620
  const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
14391
14621
  magicString.update(
@@ -14411,26 +14641,28 @@ function cloudflare2(pluginConfig = {}) {
14411
14641
  configEnvironment(name) {
14412
14642
  if (isNodeCompat(getWorkerConfig2(name))) {
14413
14643
  return {
14644
+ build: {
14645
+ rollupOptions: {
14646
+ plugins: [
14647
+ replace({
14648
+ "process.env.NODE_ENV": JSON.stringify(
14649
+ process.env.NODE_ENV ?? "production"
14650
+ ),
14651
+ preventAssignment: true
14652
+ })
14653
+ ]
14654
+ }
14655
+ },
14414
14656
  resolve: {
14415
14657
  builtins: [...nodeCompatExternals]
14416
14658
  },
14417
14659
  optimizeDeps: {
14418
- // This is a list of dependency entry-points that should be pre-bundled.
14419
- // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
14420
- // ready ahead the first request to the dev server.
14421
- // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
14422
- // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
14423
- // TODO: work out how to re-enable pre-bundling of these
14424
- // include: [...getNodeCompatEntries()],
14425
14660
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
14426
14661
  // 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.
14427
14662
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
14428
14663
  // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
14429
14664
  // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
14430
- exclude: [
14431
- ...builtinModules2,
14432
- ...builtinModules2.map((m) => `node:${m}`)
14433
- ]
14665
+ exclude: [...nodejsBuiltins]
14434
14666
  }
14435
14667
  };
14436
14668
  }
@@ -14448,7 +14680,7 @@ function cloudflare2(pluginConfig = {}) {
14448
14680
  return this.resolve(source, importer, options);
14449
14681
  }
14450
14682
  if (this.environment.mode === "dev") {
14451
- assert8(
14683
+ assert10(
14452
14684
  this.environment.depsOptimizer,
14453
14685
  "depsOptimizer is required in dev mode"
14454
14686
  );
@@ -14462,11 +14694,54 @@ function cloudflare2(pluginConfig = {}) {
14462
14694
  },
14463
14695
  async transform(code, id) {
14464
14696
  const workerConfig = getWorkerConfig2(this.environment.name);
14465
- assert8(workerConfig, "Expected a worker config");
14697
+ if (!workerConfig) {
14698
+ return;
14699
+ }
14466
14700
  const resolvedId = await this.resolve(workerConfig.main);
14467
14701
  if (id === resolvedId?.id) {
14468
14702
  return injectGlobalCode(id, code);
14469
14703
  }
14704
+ },
14705
+ async configureServer(viteDevServer) {
14706
+ await Promise.all(
14707
+ Object.values(viteDevServer.environments).flatMap(
14708
+ async (environment) => {
14709
+ const workerConfig = getWorkerConfig2(environment.name);
14710
+ if (isNodeCompat(workerConfig)) {
14711
+ await environment.depsOptimizer?.init();
14712
+ return Array.from(nodeCompatEntries).map((entry) => {
14713
+ const result = resolveNodeJSImport(entry);
14714
+ if (result) {
14715
+ const registration = environment.depsOptimizer?.registerMissingImport(
14716
+ result.unresolved,
14717
+ result.resolved
14718
+ );
14719
+ return registration?.processing;
14720
+ }
14721
+ });
14722
+ }
14723
+ }
14724
+ )
14725
+ );
14726
+ }
14727
+ },
14728
+ // Plugin that handles Node.js Async Local Storage (ALS) compatibility support for Vite Environments that are hosted in Cloudflare Workers.
14729
+ {
14730
+ name: "vite-plugin-cloudflare:nodejs-als",
14731
+ apply(_config, env2) {
14732
+ return !env2.isPreview;
14733
+ },
14734
+ configEnvironment(name, config) {
14735
+ if (isNodeAls(getWorkerConfig2(name))) {
14736
+ return {
14737
+ resolve: {
14738
+ builtins: ["async_hooks", "node:async_hooks"]
14739
+ },
14740
+ optimizeDeps: {
14741
+ exclude: ["async_hooks", "node:async_hooks"]
14742
+ }
14743
+ };
14744
+ }
14470
14745
  }
14471
14746
  },
14472
14747
  // Plugin that provides an __debug path for debugging the Cloudflare Workers.
@@ -14476,54 +14751,143 @@ function cloudflare2(pluginConfig = {}) {
14476
14751
  // the preview middleware here can take precedence
14477
14752
  enforce: "pre",
14478
14753
  configureServer(viteDevServer) {
14479
- if (resolvedPluginConfig.type === "workers" && resolvedPluginConfig.inspectorPort !== false) {
14754
+ if (resolvedPluginConfig.type === "workers" && pluginConfig.inspectorPort !== false) {
14480
14755
  addDebugToVitePrintUrls(viteDevServer);
14481
14756
  }
14482
14757
  const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
14483
14758
  (worker) => worker.name
14484
14759
  );
14485
- viteDevServer.middlewares.use((req, res, next) => {
14486
- if (req.url === debuggingPath && resolvedPluginConfig.inspectorPort !== false) {
14487
- const html = getDebugPathHtml(
14488
- workerNames,
14489
- resolvedPluginConfig.inspectorPort
14490
- );
14760
+ viteDevServer.middlewares.use(async (req, res, next) => {
14761
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14762
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14763
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14491
14764
  res.setHeader("Content-Type", "text/html");
14492
14765
  return res.end(html);
14493
14766
  }
14494
14767
  next();
14495
14768
  });
14496
14769
  },
14497
- configurePreviewServer(vitePreviewServer) {
14770
+ async configurePreviewServer(vitePreviewServer) {
14498
14771
  const workerConfigs = getWorkerConfigs(vitePreviewServer.config.root);
14499
14772
  if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
14500
14773
  addDebugToVitePrintUrls(vitePreviewServer);
14501
14774
  }
14502
14775
  const workerNames = workerConfigs.map((worker) => {
14503
- assert8(worker.name);
14776
+ assert10(worker.name, "Expected the Worker to have a name");
14504
14777
  return worker.name;
14505
14778
  });
14506
- vitePreviewServer.middlewares.use((req, res, next) => {
14507
- if (req.url === debuggingPath && pluginConfig.inspectorPort !== false) {
14508
- const html = getDebugPathHtml(
14509
- workerNames,
14510
- pluginConfig.inspectorPort ?? DEFAULT_INSPECTOR_PORT
14511
- );
14779
+ vitePreviewServer.middlewares.use(async (req, res, next) => {
14780
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14781
+ if (req.url === debuggingPath && resolvedInspectorPort) {
14782
+ const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
14512
14783
  res.setHeader("Content-Type", "text/html");
14513
14784
  return res.end(html);
14514
14785
  }
14515
14786
  next();
14516
14787
  });
14517
14788
  }
14789
+ },
14790
+ // Plugin to warn if Node.js APIs are being used without nodejs_compat turned on
14791
+ {
14792
+ name: "vite-plugin-cloudflare:nodejs-compat-warnings",
14793
+ apply(_config, env2) {
14794
+ return !env2.isPreview;
14795
+ },
14796
+ // We must ensure that the `resolveId` hook runs before the built-in ones.
14797
+ // Otherwise we never see the Node.js built-in imports since they get handled by default Vite behavior.
14798
+ enforce: "pre",
14799
+ configEnvironment(environmentName) {
14800
+ const workerConfig = getWorkerConfig2(environmentName);
14801
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14802
+ return {
14803
+ optimizeDeps: {
14804
+ esbuildOptions: {
14805
+ plugins: [
14806
+ {
14807
+ name: "vite-plugin-cloudflare:nodejs-compat-warnings-resolver",
14808
+ setup(build) {
14809
+ build.onResolve(
14810
+ { filter: NODEJS_MODULES_RE },
14811
+ ({ path: path10, importer }) => {
14812
+ if (isNodeAls(workerConfig) && isNodeAlsModule(path10)) {
14813
+ return;
14814
+ }
14815
+ const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14816
+ nodeJsCompatWarnings?.registerImport(path10, importer);
14817
+ return { path: path10, external: true };
14818
+ }
14819
+ );
14820
+ }
14821
+ }
14822
+ ]
14823
+ }
14824
+ }
14825
+ };
14826
+ }
14827
+ },
14828
+ configResolved(resolvedViteConfig2) {
14829
+ for (const environmentName of Object.keys(
14830
+ resolvedViteConfig2.environments
14831
+ )) {
14832
+ const workerConfig = getWorkerConfig2(environmentName);
14833
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14834
+ nodeJsCompatWarningsMap.set(
14835
+ workerConfig,
14836
+ new NodeJsCompatWarnings(environmentName, resolvedViteConfig2)
14837
+ );
14838
+ }
14839
+ }
14840
+ },
14841
+ async resolveId(source, importer) {
14842
+ const workerConfig = getWorkerConfig2(this.environment.name);
14843
+ if (workerConfig && !isNodeCompat(workerConfig)) {
14844
+ if (isNodeAls(workerConfig) && isNodeAlsModule(source)) {
14845
+ return;
14846
+ }
14847
+ const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14848
+ if (nodejsBuiltins.has(source)) {
14849
+ nodeJsCompatWarnings?.registerImport(source, importer);
14850
+ return {
14851
+ id: source,
14852
+ external: true
14853
+ };
14854
+ }
14855
+ }
14856
+ }
14518
14857
  }
14519
14858
  ];
14520
14859
  function getWorkerConfig2(environmentName) {
14521
- assert8(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14860
+ assert10(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14522
14861
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
14523
14862
  }
14524
14863
  }
14864
+ async function getInputInspectorPortOption(pluginConfig, viteServer) {
14865
+ if (pluginConfig.inspectorPort === void 0 || pluginConfig.inspectorPort === 0) {
14866
+ const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
14867
+ if (resolvedInspectorPort !== null) {
14868
+ return resolvedInspectorPort;
14869
+ }
14870
+ }
14871
+ const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
14872
+ if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
14873
+ viteServer.config.logger.warn(
14874
+ colors3.dim(
14875
+ `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
14876
+ `
14877
+ )
14878
+ );
14879
+ }
14880
+ return inputInspectorPort;
14881
+ }
14882
+ async function getResolvedInspectorPort(pluginConfig) {
14883
+ if (miniflare && pluginConfig.inspectorPort !== false) {
14884
+ const miniflareInspectorUrl = await miniflare.getInspectorURL();
14885
+ return Number.parseInt(miniflareInspectorUrl.port);
14886
+ }
14887
+ return null;
14888
+ }
14525
14889
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14526
- const configDir = path8.dirname(configPath);
14890
+ const configDir = path9.dirname(configPath);
14527
14891
  const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
14528
14892
  const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
14529
14893
  const targetPath = fs5.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs5.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
@@ -14533,6 +14897,19 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14533
14897
  }
14534
14898
  return null;
14535
14899
  }
14900
+ function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
14901
+ return [...resolvedPluginConfig.configPaths].some((configPath) => {
14902
+ const dotDevDotVars = path9.join(path9.dirname(configPath), ".dev.vars");
14903
+ if (dotDevDotVars === changedFilePath) {
14904
+ return true;
14905
+ }
14906
+ if (resolvedPluginConfig.cloudflareEnv) {
14907
+ const dotDevDotVarsForEnv = `${dotDevDotVars}.${resolvedPluginConfig.cloudflareEnv}`;
14908
+ return dotDevDotVarsForEnv === changedFilePath;
14909
+ }
14910
+ return false;
14911
+ });
14912
+ }
14536
14913
  export {
14537
14914
  cloudflare2 as cloudflare
14538
14915
  };