@cloudflare/vite-plugin 1.5.1 → 1.7.0

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 = (path10, originalPath, doThrow) => {
252
- if (!isString(path10)) {
251
+ var checkPath = (path11, originalPath, doThrow) => {
252
+ if (!isString(path11)) {
253
253
  return doThrow(
254
254
  `path must be a string, but got \`${originalPath}\``,
255
255
  TypeError
256
256
  );
257
257
  }
258
- if (!path10) {
258
+ if (!path11) {
259
259
  return doThrow(`path must not be empty`, TypeError);
260
260
  }
261
- if (checkPath.isNotRelative(path10)) {
261
+ if (checkPath.isNotRelative(path11)) {
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 = (path10) => REGEX_TEST_INVALID_PATH.test(path10);
270
+ var isNotRelative = (path11) => REGEX_TEST_INVALID_PATH.test(path11);
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(path10, checkUnignored) {
329
+ _testOne(path11, 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(path10);
337
+ const matched = rule.regex.test(path11);
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 path10 = originalPath && checkPath.convert(originalPath);
350
+ const path11 = originalPath && checkPath.convert(originalPath);
351
351
  checkPath(
352
- path10,
352
+ path11,
353
353
  originalPath,
354
354
  this._allowRelativePaths ? RETURN_FALSE : throwError
355
355
  );
356
- return this._t(path10, cache2, checkUnignored, slices);
356
+ return this._t(path11, cache2, checkUnignored, slices);
357
357
  }
358
- _t(path10, cache2, checkUnignored, slices) {
359
- if (path10 in cache2) {
360
- return cache2[path10];
358
+ _t(path11, cache2, checkUnignored, slices) {
359
+ if (path11 in cache2) {
360
+ return cache2[path11];
361
361
  }
362
362
  if (!slices) {
363
- slices = path10.split(SLASH);
363
+ slices = path11.split(SLASH);
364
364
  }
365
365
  slices.pop();
366
366
  if (!slices.length) {
367
- return cache2[path10] = this._testOne(path10, checkUnignored);
367
+ return cache2[path11] = this._testOne(path11, 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[path10] = parent.ignored ? parent : this._testOne(path10, checkUnignored);
375
+ return cache2[path11] = parent.ignored ? parent : this._testOne(path11, checkUnignored);
376
376
  }
377
- ignores(path10) {
378
- return this._test(path10, this._ignoreCache, false).ignored;
377
+ ignores(path11) {
378
+ return this._test(path11, this._ignoreCache, false).ignored;
379
379
  }
380
380
  createFilter() {
381
- return (path10) => !this.ignores(path10);
381
+ return (path11) => !this.ignores(path11);
382
382
  }
383
383
  filter(paths) {
384
384
  return makeArray(paths).filter(this.createFilter());
385
385
  }
386
386
  // @returns {TestResult}
387
- test(path10) {
388
- return this._test(path10, this._testCache, true);
387
+ test(path11) {
388
+ return this._test(path11, this._testCache, true);
389
389
  }
390
390
  };
391
391
  var factory = (options) => new Ignore(options);
392
- var isPathValid = (path10) => checkPath(path10 && checkPath.convert(path10), path10, RETURN_FALSE);
392
+ var isPathValid = (path11) => checkPath(path11 && checkPath.convert(path11), path11, 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 = (path10) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path10) || isNotRelative(path10);
403
+ checkPath.isNotRelative = (path11) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path11) || isNotRelative(path11);
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(path10) {
447
- path10 = String(path10);
448
- let last = path10.replace(/^.*[/\\]/, "").toLowerCase();
446
+ Mime.prototype.getType = function(path11) {
447
+ path11 = String(path11);
448
+ let last = path11.replace(/^.*[/\\]/, "").toLowerCase();
449
449
  let ext = last.replace(/^.*\./, "").toLowerCase();
450
- let hasPath = last.length < path10.length;
450
+ let hasPath = last.length < path11.length;
451
451
  let hasDot = ext.length < last.length - 1;
452
452
  return (hasDot || !hasPath) && this._types[ext] || null;
453
453
  };
@@ -485,11 +485,36 @@ var require_mime = __commonJS({
485
485
  });
486
486
 
487
487
  // src/index.ts
488
- import assert10 from "node:assert";
489
- import * as fs5 from "node:fs";
488
+ import assert11 from "node:assert";
489
+ import * as fs6 from "node:fs";
490
490
  import * as fsp2 from "node:fs/promises";
491
- import * as path9 from "node:path";
492
- import { createRequest, sendResponse } from "@mjackson/node-fetch-server";
491
+ import * as path10 from "node:path";
492
+
493
+ // ../workers-shared/asset-worker/src/utils/rules-engine.ts
494
+ var ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
495
+ var escapeRegex = (str) => {
496
+ return str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&");
497
+ };
498
+ var generateGlobOnlyRuleRegExp = (rule) => {
499
+ rule = rule.split("*").map(escapeRegex).join(".*");
500
+ rule = "^" + rule + "$";
501
+ return RegExp(rule);
502
+ };
503
+ var generateStaticRoutingRuleMatcher = (rules) => ({ request }) => {
504
+ const { pathname } = new URL(request.url);
505
+ for (const rule of rules) {
506
+ try {
507
+ const regExp = generateGlobOnlyRuleRegExp(rule);
508
+ if (regExp.test(pathname)) {
509
+ return true;
510
+ }
511
+ } catch {
512
+ }
513
+ }
514
+ return false;
515
+ };
516
+
517
+ // src/index.ts
493
518
  import replace from "@rollup/plugin-replace";
494
519
 
495
520
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
@@ -503,8 +528,8 @@ for (let i = 0; i < chars.length; i++) {
503
528
  intToChar[i] = c;
504
529
  charToInt[c] = i;
505
530
  }
506
- function encodeInteger(builder, num, relative6) {
507
- let delta = num - relative6;
531
+ function encodeInteger(builder, num, relative7) {
532
+ let delta = num - relative7;
508
533
  delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
509
534
  do {
510
535
  let clamped = delta & 31;
@@ -1066,19 +1091,19 @@ var MagicString = class _MagicString {
1066
1091
  });
1067
1092
  }
1068
1093
  let shouldIndentNextCharacter = options.indentStart !== false;
1069
- const replacer = (match) => {
1094
+ const replacer2 = (match) => {
1070
1095
  if (shouldIndentNextCharacter) return `${indentStr}${match}`;
1071
1096
  shouldIndentNextCharacter = true;
1072
1097
  return match;
1073
1098
  };
1074
- this.intro = this.intro.replace(pattern, replacer);
1099
+ this.intro = this.intro.replace(pattern, replacer2);
1075
1100
  let charIndex = 0;
1076
1101
  let chunk = this.firstChunk;
1077
1102
  while (chunk) {
1078
1103
  const end = chunk.end;
1079
1104
  if (chunk.edited) {
1080
1105
  if (!isExcluded[charIndex]) {
1081
- chunk.content = chunk.content.replace(pattern, replacer);
1106
+ chunk.content = chunk.content.replace(pattern, replacer2);
1082
1107
  if (chunk.content.length) {
1083
1108
  shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1084
1109
  }
@@ -1107,7 +1132,7 @@ var MagicString = class _MagicString {
1107
1132
  charIndex = chunk.end;
1108
1133
  chunk = chunk.next;
1109
1134
  }
1110
- this.outro = this.outro.replace(pattern, replacer);
1135
+ this.outro = this.outro.replace(pattern, replacer2);
1111
1136
  return this;
1112
1137
  }
1113
1138
  insert() {
@@ -1558,8 +1583,8 @@ var MagicString = class _MagicString {
1558
1583
 
1559
1584
  // src/index.ts
1560
1585
  import { Miniflare } from "miniflare";
1561
- import colors3 from "picocolors";
1562
- import * as vite7 from "vite";
1586
+ import colors4 from "picocolors";
1587
+ import * as vite6 from "vite";
1563
1588
 
1564
1589
  // src/constants.ts
1565
1590
  var ROUTER_WORKER_NAME = "__router-worker__";
@@ -1570,6 +1595,7 @@ var ADDITIONAL_MODULE_TYPES = [
1570
1595
  "Data",
1571
1596
  "Text"
1572
1597
  ];
1598
+ var PUBLIC_DIR_PREFIX = "/__vite_public_dir__";
1573
1599
  var DEFAULT_INSPECTOR_PORT = 9229;
1574
1600
  var kRequestType = Symbol("kRequestType");
1575
1601
 
@@ -1600,8 +1626,8 @@ import * as path from "node:path";
1600
1626
  import { relative } from "node:path";
1601
1627
 
1602
1628
  // ../workers-shared/utils/configuration/constants.ts
1603
- var REDIRECTS_VERSION = 1;
1604
- var HEADERS_VERSION = 2;
1629
+ var REDIRECTS_VERSION2 = 1;
1630
+ var HEADERS_VERSION2 = 2;
1605
1631
  var PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([200, 301, 302, 303, 307, 308]);
1606
1632
  var HEADER_SEPARATOR = ":";
1607
1633
  var MAX_LINE_LENGTH = 2e3;
@@ -1611,6 +1637,8 @@ var MAX_STATIC_REDIRECT_RULES = 2e3;
1611
1637
  var UNSET_OPERATOR = "! ";
1612
1638
  var SPLAT_REGEX = /\*/g;
1613
1639
  var PLACEHOLDER_REGEX = /:[A-Za-z]\w*/g;
1640
+ var MAX_ROUTES_RULES = 100;
1641
+ var MAX_ROUTES_RULE_LENGTH = 100;
1614
1642
 
1615
1643
  // ../workers-shared/utils/configuration/constructConfiguration.ts
1616
1644
  function constructRedirects({
@@ -1669,7 +1697,7 @@ ${invalidRedirectRulesList}`
1669
1697
  }
1670
1698
  return {
1671
1699
  redirects: {
1672
- version: REDIRECTS_VERSION,
1700
+ version: REDIRECTS_VERSION2,
1673
1701
  staticRules: staticRedirects,
1674
1702
  rules: dynamicRedirects
1675
1703
  }
@@ -1721,18 +1749,18 @@ ${invalidHeaderRulesList}`
1721
1749
  }
1722
1750
  return {
1723
1751
  headers: {
1724
- version: HEADERS_VERSION,
1752
+ version: HEADERS_VERSION2,
1725
1753
  rules
1726
1754
  }
1727
1755
  };
1728
1756
  }
1729
1757
 
1730
1758
  // ../workers-shared/utils/configuration/validateURL.ts
1731
- var extractPathname = (path10 = "/", includeSearch, includeHash) => {
1732
- if (!path10.startsWith("/")) {
1733
- path10 = `/${path10}`;
1759
+ var extractPathname = (path11 = "/", includeSearch, includeHash) => {
1760
+ if (!path11.startsWith("/")) {
1761
+ path11 = `/${path11}`;
1734
1762
  }
1735
- const url = new URL(`//${path10}`, "relative://");
1763
+ const url = new URL(`//${path11}`, "relative://");
1736
1764
  return `${url.pathname}${includeSearch ? url.search : ""}${includeHash ? url.hash : ""}`;
1737
1765
  };
1738
1766
  var URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
@@ -1765,8 +1793,8 @@ var validateUrl = (token, onlyRelative = false, disallowPorts = false, includeSe
1765
1793
  if (!token.startsWith("/") && onlyRelative) {
1766
1794
  token = `/${token}`;
1767
1795
  }
1768
- const path10 = PATH_REGEX.exec(token);
1769
- if (path10) {
1796
+ const path11 = PATH_REGEX.exec(token);
1797
+ if (path11) {
1770
1798
  try {
1771
1799
  return [extractPathname(token, includeSearch, includeHash), void 0];
1772
1800
  } catch {
@@ -1827,7 +1855,7 @@ function parseHeaders(input, {
1827
1855
  });
1828
1856
  }
1829
1857
  }
1830
- const [path10, pathError] = validateUrl(line, false, true);
1858
+ const [path11, pathError] = validateUrl(line, false, true);
1831
1859
  if (pathError) {
1832
1860
  invalid.push({
1833
1861
  line,
@@ -1838,7 +1866,7 @@ function parseHeaders(input, {
1838
1866
  continue;
1839
1867
  }
1840
1868
  rule = {
1841
- path: path10,
1869
+ path: path11,
1842
1870
  line,
1843
1871
  headers: {},
1844
1872
  unsetHeaders: []
@@ -2413,8 +2441,8 @@ function getErrorMap() {
2413
2441
  return overrideErrorMap;
2414
2442
  }
2415
2443
  var makeIssue = (params) => {
2416
- const { data: data2, path: path10, errorMaps, issueData } = params;
2417
- const fullPath = [...path10, ...issueData.path || []];
2444
+ const { data: data2, path: path11, errorMaps, issueData } = params;
2445
+ const fullPath = [...path11, ...issueData.path || []];
2418
2446
  const fullIssue = {
2419
2447
  ...issueData,
2420
2448
  path: fullPath
@@ -2513,11 +2541,11 @@ var errorUtil;
2513
2541
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2514
2542
  })(errorUtil || (errorUtil = {}));
2515
2543
  var ParseInputLazyPath = class {
2516
- constructor(parent, value, path10, key) {
2544
+ constructor(parent, value, path11, key) {
2517
2545
  this._cachedPath = [];
2518
2546
  this.parent = parent;
2519
2547
  this.data = value;
2520
- this._path = path10;
2548
+ this._path = path11;
2521
2549
  this._key = key;
2522
2550
  }
2523
2551
  get path() {
@@ -5860,7 +5888,8 @@ function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig
5860
5888
  };
5861
5889
  const config = {
5862
5890
  ...compatibilityOptions,
5863
- ...assetsConfig
5891
+ ...assetsConfig,
5892
+ has_static_routing: resolvedPluginConfig.type === "workers" && resolvedPluginConfig.staticRouting ? true : false
5864
5893
  };
5865
5894
  if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) {
5866
5895
  return config;
@@ -5912,14 +5941,147 @@ function getHeadersConfigPath(config) {
5912
5941
  return path.join(config.publicDir, HEADERS_FILENAME);
5913
5942
  }
5914
5943
 
5944
+ // src/build.ts
5945
+ import assert from "node:assert";
5946
+ import * as fs from "node:fs";
5947
+ import * as path2 from "node:path";
5948
+ import colors from "picocolors";
5949
+ function createBuildApp(resolvedPluginConfig) {
5950
+ return async (builder) => {
5951
+ const clientEnvironment = builder.environments.client;
5952
+ assert(clientEnvironment, `No "client" environment`);
5953
+ const defaultHtmlPath = path2.resolve(builder.config.root, "index.html");
5954
+ const hasClientEntry = clientEnvironment.config.build.rollupOptions.input || fs.existsSync(defaultHtmlPath);
5955
+ if (resolvedPluginConfig.type === "assets-only") {
5956
+ if (hasClientEntry) {
5957
+ await builder.build(clientEnvironment);
5958
+ } else if (getHasPublicAssets(builder.config)) {
5959
+ await fallbackBuild(builder, clientEnvironment);
5960
+ }
5961
+ return;
5962
+ }
5963
+ const workerEnvironments = Object.keys(resolvedPluginConfig.workers).map(
5964
+ (environmentName) => {
5965
+ const environment = builder.environments[environmentName];
5966
+ assert(environment, `"${environmentName}" environment not found`);
5967
+ return environment;
5968
+ }
5969
+ );
5970
+ await Promise.all(
5971
+ workerEnvironments.map((environment) => builder.build(environment))
5972
+ );
5973
+ const { entryWorkerEnvironmentName } = resolvedPluginConfig;
5974
+ const entryWorkerEnvironment = builder.environments[entryWorkerEnvironmentName];
5975
+ assert(
5976
+ entryWorkerEnvironment,
5977
+ `No "${entryWorkerEnvironmentName}" environment`
5978
+ );
5979
+ const entryWorkerBuildDirectory = path2.resolve(
5980
+ builder.config.root,
5981
+ entryWorkerEnvironment.config.build.outDir
5982
+ );
5983
+ const entryWorkerManifest = loadViteManifest(entryWorkerBuildDirectory);
5984
+ const importedAssetPaths = getImportedAssetPaths(entryWorkerManifest);
5985
+ if (hasClientEntry) {
5986
+ await builder.build(clientEnvironment);
5987
+ } else if (importedAssetPaths.size || getHasPublicAssets(builder.config)) {
5988
+ await fallbackBuild(builder, clientEnvironment);
5989
+ } else {
5990
+ const entryWorkerConfigPath = path2.join(
5991
+ entryWorkerBuildDirectory,
5992
+ "wrangler.json"
5993
+ );
5994
+ const workerConfig = JSON.parse(
5995
+ fs.readFileSync(entryWorkerConfigPath, "utf-8")
5996
+ );
5997
+ workerConfig.assets = void 0;
5998
+ fs.writeFileSync(entryWorkerConfigPath, JSON.stringify(workerConfig));
5999
+ return;
6000
+ }
6001
+ const clientBuildDirectory = path2.resolve(
6002
+ builder.config.root,
6003
+ clientEnvironment.config.build.outDir
6004
+ );
6005
+ const movedAssetPaths = [];
6006
+ for (const assetPath of importedAssetPaths) {
6007
+ const src = path2.join(entryWorkerBuildDirectory, assetPath);
6008
+ const dest = path2.join(clientBuildDirectory, assetPath);
6009
+ if (!fs.existsSync(src)) {
6010
+ continue;
6011
+ }
6012
+ if (fs.existsSync(dest)) {
6013
+ fs.unlinkSync(src);
6014
+ } else {
6015
+ const destDir = path2.dirname(dest);
6016
+ fs.mkdirSync(destDir, { recursive: true });
6017
+ fs.renameSync(src, dest);
6018
+ movedAssetPaths.push(dest);
6019
+ }
6020
+ }
6021
+ if (movedAssetPaths.length) {
6022
+ builder.config.logger.info(
6023
+ [
6024
+ `${colors.green("\u2713")} ${movedAssetPaths.length} asset${movedAssetPaths.length > 1 ? "s" : ""} moved from "${entryWorkerEnvironmentName}" to "client" build output.`,
6025
+ ...movedAssetPaths.map(
6026
+ (assetPath) => colors.dim(path2.relative(builder.config.root, assetPath))
6027
+ )
6028
+ ].join("\n")
6029
+ );
6030
+ }
6031
+ };
6032
+ }
6033
+ function getHasPublicAssets({ publicDir }) {
6034
+ let hasPublicAssets = false;
6035
+ if (publicDir) {
6036
+ try {
6037
+ const files = fs.readdirSync(publicDir);
6038
+ if (files.length) {
6039
+ hasPublicAssets = true;
6040
+ }
6041
+ } catch (error) {
6042
+ }
6043
+ }
6044
+ return hasPublicAssets;
6045
+ }
6046
+ async function fallbackBuild(builder, environment) {
6047
+ const fallbackEntryName = "__cloudflare_fallback_entry__";
6048
+ environment.config.build.rollupOptions = {
6049
+ input: "virtual:__cloudflare_fallback_entry__",
6050
+ logLevel: "silent",
6051
+ output: {
6052
+ entryFileNames: fallbackEntryName
6053
+ }
6054
+ };
6055
+ await builder.build(environment);
6056
+ const fallbackEntryPath = path2.resolve(
6057
+ builder.config.root,
6058
+ environment.config.build.outDir,
6059
+ fallbackEntryName
6060
+ );
6061
+ fs.unlinkSync(fallbackEntryPath);
6062
+ }
6063
+ function loadViteManifest(directory) {
6064
+ const contents = fs.readFileSync(
6065
+ path2.resolve(directory, ".vite", "manifest.json"),
6066
+ "utf-8"
6067
+ );
6068
+ return JSON.parse(contents);
6069
+ }
6070
+ function getImportedAssetPaths(viteManifest) {
6071
+ const assetPaths = Object.values(viteManifest).flatMap(
6072
+ (chunk) => chunk.assets ?? []
6073
+ );
6074
+ return new Set(assetPaths);
6075
+ }
6076
+
5915
6077
  // src/cloudflare-environment.ts
5916
- import assert3 from "node:assert";
5917
- import * as vite3 from "vite";
6078
+ import assert4 from "node:assert";
6079
+ import * as vite2 from "vite";
5918
6080
 
5919
6081
  // src/node-js-compat.ts
5920
- import assert2 from "node:assert";
6082
+ import assert3 from "node:assert";
5921
6083
  import { builtinModules as builtinModules2 } from "node:module";
5922
- import path3 from "node:path";
6084
+ import path4 from "node:path";
5923
6085
  import { cloudflare } from "@cloudflare/unenv-preset";
5924
6086
  import { getNodeCompat } from "miniflare";
5925
6087
 
@@ -11452,7 +11614,7 @@ Parser.acorn = {
11452
11614
 
11453
11615
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
11454
11616
  import { builtinModules, createRequire } from "node:module";
11455
- import fs, { realpathSync, statSync, promises } from "node:fs";
11617
+ import fs2, { realpathSync, statSync, promises } from "node:fs";
11456
11618
 
11457
11619
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
11458
11620
  var r = String.fromCharCode;
@@ -11471,17 +11633,17 @@ function withTrailingSlash(input = "", respectQueryAndFragment) {
11471
11633
  if (hasTrailingSlash(input, true)) {
11472
11634
  return input || "/";
11473
11635
  }
11474
- let path10 = input;
11636
+ let path11 = input;
11475
11637
  let fragment = "";
11476
11638
  const fragmentIndex = input.indexOf("#");
11477
11639
  if (fragmentIndex >= 0) {
11478
- path10 = input.slice(0, fragmentIndex);
11640
+ path11 = input.slice(0, fragmentIndex);
11479
11641
  fragment = input.slice(fragmentIndex);
11480
- if (!path10) {
11642
+ if (!path11) {
11481
11643
  return fragment;
11482
11644
  }
11483
11645
  }
11484
- const [s0, ...s] = path10.split("?");
11646
+ const [s0, ...s] = path11.split("?");
11485
11647
  return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
11486
11648
  }
11487
11649
  function isNonEmptyURL(url) {
@@ -11509,14 +11671,14 @@ var isAbsolute = function(p) {
11509
11671
 
11510
11672
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
11511
11673
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
11512
- import assert from "node:assert";
11674
+ import assert2 from "node:assert";
11513
11675
  import process$1 from "node:process";
11514
- import path2, { dirname as dirname2 } from "node:path";
11676
+ import path3, { dirname as dirname3 } from "node:path";
11515
11677
  import v8 from "node:v8";
11516
11678
  import { format as format2, inspect } from "node:util";
11517
11679
  var BUILTIN_MODULES = new Set(builtinModules);
11518
- function normalizeSlash(path10) {
11519
- return path10.replace(/\\/g, "/");
11680
+ function normalizeSlash(path11) {
11681
+ return path11.replace(/\\/g, "/");
11520
11682
  }
11521
11683
  var own$1 = {}.hasOwnProperty;
11522
11684
  var classRegExp = /^([A-Z][a-z\d]*)+$/;
@@ -11547,7 +11709,7 @@ codes.ERR_INVALID_ARG_TYPE = createError(
11547
11709
  * @param {unknown} actual
11548
11710
  */
11549
11711
  (name, expected, actual) => {
11550
- assert(typeof name === "string", "'name' must be a string");
11712
+ assert2(typeof name === "string", "'name' must be a string");
11551
11713
  if (!Array.isArray(expected)) {
11552
11714
  expected = [expected];
11553
11715
  }
@@ -11563,14 +11725,14 @@ codes.ERR_INVALID_ARG_TYPE = createError(
11563
11725
  const instances = [];
11564
11726
  const other = [];
11565
11727
  for (const value of expected) {
11566
- assert(
11728
+ assert2(
11567
11729
  typeof value === "string",
11568
11730
  "All expected entries have to be of type string"
11569
11731
  );
11570
11732
  if (kTypes.has(value)) {
11571
11733
  types2.push(value.toLowerCase());
11572
11734
  } else if (classRegExp.exec(value) === null) {
11573
- assert(
11735
+ assert2(
11574
11736
  value !== "object",
11575
11737
  'The value "object" should be written as "Object"'
11576
11738
  );
@@ -11629,8 +11791,8 @@ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
11629
11791
  * @param {string} [base]
11630
11792
  * @param {string} [message]
11631
11793
  */
11632
- (path10, base, message) => {
11633
- return `Invalid package config ${path10}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11794
+ (path11, base, message) => {
11795
+ return `Invalid package config ${path11}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11634
11796
  },
11635
11797
  Error
11636
11798
  );
@@ -11646,7 +11808,7 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
11646
11808
  (packagePath, key, target2, isImport = false, base = void 0) => {
11647
11809
  const relatedError = typeof target2 === "string" && !isImport && target2.length > 0 && !target2.startsWith("./");
11648
11810
  if (key === ".") {
11649
- assert(isImport === false);
11811
+ assert2(isImport === false);
11650
11812
  return `Invalid "exports" main target ${JSON.stringify(target2)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
11651
11813
  }
11652
11814
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
@@ -11662,8 +11824,8 @@ codes.ERR_MODULE_NOT_FOUND = createError(
11662
11824
  * @param {string} base
11663
11825
  * @param {boolean} [exactUrl]
11664
11826
  */
11665
- (path10, base, exactUrl = false) => {
11666
- return `Cannot find ${exactUrl ? "module" : "package"} '${path10}' imported from ${base}`;
11827
+ (path11, base, exactUrl = false) => {
11828
+ return `Cannot find ${exactUrl ? "module" : "package"} '${path11}' imported from ${base}`;
11667
11829
  },
11668
11830
  Error
11669
11831
  );
@@ -11714,8 +11876,8 @@ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
11714
11876
  * @param {string} extension
11715
11877
  * @param {string} path
11716
11878
  */
11717
- (extension, path10) => {
11718
- return `Unknown file extension "${extension}" for ${path10}`;
11879
+ (extension, path11) => {
11880
+ return `Unknown file extension "${extension}" for ${path11}`;
11719
11881
  },
11720
11882
  TypeError
11721
11883
  );
@@ -11811,9 +11973,9 @@ var captureLargerStackTrace = hideStackFrames(
11811
11973
  );
11812
11974
  function getMessage(key, parameters, self) {
11813
11975
  const message = messages.get(key);
11814
- assert(message !== void 0, "expected `message` to be found");
11976
+ assert2(message !== void 0, "expected `message` to be found");
11815
11977
  if (typeof message === "function") {
11816
- assert(
11978
+ assert2(
11817
11979
  message.length <= parameters.length,
11818
11980
  // Default options do not count.
11819
11981
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -11823,7 +11985,7 @@ function getMessage(key, parameters, self) {
11823
11985
  const regex = /%[dfijoOs]/g;
11824
11986
  let expectedLength = 0;
11825
11987
  while (regex.exec(message) !== null) expectedLength++;
11826
- assert(
11988
+ assert2(
11827
11989
  expectedLength === parameters.length,
11828
11990
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
11829
11991
  );
@@ -11860,7 +12022,7 @@ function read(jsonPath, { base, specifier }) {
11860
12022
  }
11861
12023
  let string;
11862
12024
  try {
11863
- string = fs.readFileSync(path2.toNamespacedPath(jsonPath), "utf8");
12025
+ string = fs2.readFileSync(path3.toNamespacedPath(jsonPath), "utf8");
11864
12026
  } catch (error) {
11865
12027
  const exception = (
11866
12028
  /** @type {ErrnoException} */
@@ -12076,7 +12238,7 @@ Default "index" lookups for the main are deprecated for ES modules.`,
12076
12238
  "DeprecationWarning",
12077
12239
  "DEP0151"
12078
12240
  );
12079
- } else if (path2.resolve(packagePath, main) !== urlPath) {
12241
+ } else if (path3.resolve(packagePath, main) !== urlPath) {
12080
12242
  process$1.emitWarning(
12081
12243
  `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
12082
12244
  packagePath.length
@@ -12087,9 +12249,9 @@ Default "index" lookups for the main are deprecated for ES modules.`,
12087
12249
  );
12088
12250
  }
12089
12251
  }
12090
- function tryStatSync(path10) {
12252
+ function tryStatSync(path11) {
12091
12253
  try {
12092
- return statSync(path10);
12254
+ return statSync(path11);
12093
12255
  } catch {
12094
12256
  }
12095
12257
  }
@@ -12183,7 +12345,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
12183
12345
  {
12184
12346
  const real = realpathSync(filePath);
12185
12347
  const { search, hash } = resolved;
12186
- resolved = pathToFileURL$1(real + (filePath.endsWith(path2.sep) ? "/" : ""));
12348
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path3.sep) ? "/" : ""));
12187
12349
  resolved.search = search;
12188
12350
  resolved.hash = hash;
12189
12351
  }
@@ -12723,7 +12885,7 @@ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
12723
12885
  resolved = packageResolve(specifier, base, conditions);
12724
12886
  }
12725
12887
  }
12726
- assert(resolved !== void 0, "expected to be defined");
12888
+ assert2(resolved !== void 0, "expected to be defined");
12727
12889
  if (resolved.protocol !== "file:") {
12728
12890
  return resolved;
12729
12891
  }
@@ -12894,27 +13056,44 @@ function isNodeAls(workerConfig) {
12894
13056
  workerConfig.compatibility_flags ?? []
12895
13057
  ).mode === "als";
12896
13058
  }
12897
- function isNodeAlsModule(path10) {
12898
- return /^(node:)?async_hooks$/.test(path10);
13059
+ function isNodeAlsModule(path11) {
13060
+ return /^(node:)?async_hooks$/.test(path11);
13061
+ }
13062
+ var injectsByModule = /* @__PURE__ */ new Map();
13063
+ var virtualModulePathToSpecifier = /* @__PURE__ */ new Map();
13064
+ var virtualModulePrefix = `\0_nodejs_global_inject-`;
13065
+ for (const [injectedName, moduleSpecifier] of Object.entries(env.inject)) {
13066
+ const [module, exportName, importName] = Array.isArray(moduleSpecifier) ? [moduleSpecifier[0], moduleSpecifier[1], moduleSpecifier[1]] : [moduleSpecifier, "default", "defaultExport"];
13067
+ if (!injectsByModule.has(module)) {
13068
+ injectsByModule.set(module, []);
13069
+ virtualModulePathToSpecifier.set(
13070
+ virtualModulePrefix + module.replaceAll("/", "-"),
13071
+ module
13072
+ );
13073
+ }
13074
+ const injects = injectsByModule.get(module);
13075
+ assert3(injects, `expected injects for ${module} to be defined`);
13076
+ injects.push({ injectedName, exportName, importName });
13077
+ }
13078
+ function isGlobalVirtualModule(modulePath) {
13079
+ return virtualModulePathToSpecifier.has(modulePath);
13080
+ }
13081
+ function getGlobalVirtualModule(modulePath) {
13082
+ const module = virtualModulePathToSpecifier.get(modulePath);
13083
+ if (!module) {
13084
+ return void 0;
13085
+ }
13086
+ const injects = injectsByModule.get(module);
13087
+ assert3(injects, `expected injects for ${module} to be defined`);
13088
+ const imports = injects.map(
13089
+ ({ exportName, importName }) => importName === exportName ? exportName : `${exportName} as ${importName}`
13090
+ );
13091
+ return `import { ${imports.join(", ")} } from "${module}";
13092
+ ${injects.map(({ injectedName, importName }) => `globalThis.${injectedName} = ${importName};`).join("\n")}`;
12899
13093
  }
12900
13094
  function injectGlobalCode(id, code) {
12901
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
12902
- if (typeof globalInject === "string") {
12903
- const moduleSpecifier2 = globalInject;
12904
- return `import var_${globalName} from "${moduleSpecifier2}";
12905
- globalThis.${globalName} = var_${globalName};
12906
- `;
12907
- }
12908
- const [moduleSpecifier, exportName] = globalInject;
12909
- assert2(
12910
- moduleSpecifier !== void 0,
12911
- "Expected moduleSpecifier to be defined"
12912
- );
12913
- assert2(exportName !== void 0, "Expected exportName to be defined");
12914
- return `import var_${globalName} from "${moduleSpecifier}";
12915
- globalThis.${globalName} = var_${globalName}.${exportName};
12916
- `;
12917
- }).join("\n");
13095
+ const injectedCode = Array.from(virtualModulePathToSpecifier.keys()).map((moduleId) => `import "${moduleId}";
13096
+ `).join("");
12918
13097
  const polyfillCode = env.polyfill.map((polyfillPath) => `import "${polyfillPath}";
12919
13098
  `).join("");
12920
13099
  const modified = new MagicString(code);
@@ -12946,7 +13125,7 @@ function getNodeCompatEntries() {
12946
13125
  if (typeof globalInject === "string") {
12947
13126
  entries.add(globalInject);
12948
13127
  } else {
12949
- assert2(
13128
+ assert3(
12950
13129
  globalInject[0] !== void 0,
12951
13130
  "Expected first element of globalInject to be defined"
12952
13131
  );
@@ -12985,7 +13164,7 @@ var NodeJsCompatWarnings = class {
12985
13164
  `;
12986
13165
  this.sources.forEach((importers, source) => {
12987
13166
  importers.forEach((importer) => {
12988
- message += ` - "${source}" imported from "${path3.relative(this.resolvedViteConfig.root, importer)}"
13167
+ message += ` - "${source}" imported from "${path4.relative(this.resolvedViteConfig.root, importer)}"
12989
13168
  `;
12990
13169
  });
12991
13170
  });
@@ -13009,13 +13188,41 @@ var additionalModuleGlobalRE = new RegExp(
13009
13188
  var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
13010
13189
 
13011
13190
  // src/utils.ts
13012
- import * as path4 from "node:path";
13191
+ import * as path5 from "node:path";
13192
+ import { createRequest, sendResponse } from "@mjackson/node-fetch-server";
13013
13193
  import getPort, { portNumbers } from "get-port";
13014
- import { Request as MiniflareRequest } from "miniflare";
13015
- import "vite";
13194
+ import {
13195
+ Request as MiniflareRequest,
13196
+ Response as MiniflareResponse
13197
+ } from "miniflare";
13016
13198
  function getOutputDirectory(userConfig, environmentName) {
13017
13199
  const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
13018
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path4.join(rootOutputDirectory, environmentName);
13200
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path5.join(rootOutputDirectory, environmentName);
13201
+ }
13202
+ var postfixRE = /[?#].*$/;
13203
+ function cleanUrl(url) {
13204
+ return url.replace(postfixRE, "");
13205
+ }
13206
+ function getFirstAvailablePort(start) {
13207
+ return getPort({ port: portNumbers(start, 65535) });
13208
+ }
13209
+ function withTrailingSlash2(path11) {
13210
+ return path11.endsWith("/") ? path11 : `${path11}/`;
13211
+ }
13212
+ function createRequestHandler(handler) {
13213
+ return async (req, res, next) => {
13214
+ try {
13215
+ const request = createRequest(req, res);
13216
+ let response = await handler(toMiniflareRequest(request), req);
13217
+ if (req.httpVersionMajor === 2) {
13218
+ response = new MiniflareResponse(response.body, response);
13219
+ response.headers.delete("transfer-encoding");
13220
+ }
13221
+ await sendResponse(res, response);
13222
+ } catch (error) {
13223
+ next(error);
13224
+ }
13225
+ };
13019
13226
  }
13020
13227
  function toMiniflareRequest(request) {
13021
13228
  const host = request.headers.get("Host");
@@ -13033,13 +13240,6 @@ function toMiniflareRequest(request) {
13033
13240
  duplex: "half"
13034
13241
  });
13035
13242
  }
13036
- var postfixRE = /[?#].*$/;
13037
- function cleanUrl(url) {
13038
- return url.replace(postfixRE, "");
13039
- }
13040
- function getFirstAvailablePort(start) {
13041
- return getPort({ port: portNumbers(start, 65535) });
13042
- }
13043
13243
 
13044
13244
  // src/cloudflare-environment.ts
13045
13245
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -13048,7 +13248,7 @@ function createHotChannel(webSocketContainer) {
13048
13248
  const client = {
13049
13249
  send(payload) {
13050
13250
  const webSocket = webSocketContainer.webSocket;
13051
- assert3(webSocket, webSocketUndefinedError);
13251
+ assert4(webSocket, webSocketUndefinedError);
13052
13252
  webSocket.send(JSON.stringify(payload));
13053
13253
  }
13054
13254
  };
@@ -13062,7 +13262,7 @@ function createHotChannel(webSocketContainer) {
13062
13262
  return {
13063
13263
  send(payload) {
13064
13264
  const webSocket = webSocketContainer.webSocket;
13065
- assert3(webSocket, webSocketUndefinedError);
13265
+ assert4(webSocket, webSocketUndefinedError);
13066
13266
  webSocket.send(JSON.stringify(payload));
13067
13267
  },
13068
13268
  on(event, listener) {
@@ -13075,17 +13275,17 @@ function createHotChannel(webSocketContainer) {
13075
13275
  },
13076
13276
  listen() {
13077
13277
  const webSocket = webSocketContainer.webSocket;
13078
- assert3(webSocket, webSocketUndefinedError);
13278
+ assert4(webSocket, webSocketUndefinedError);
13079
13279
  webSocket.addEventListener("message", onMessage);
13080
13280
  },
13081
13281
  close() {
13082
13282
  const webSocket = webSocketContainer.webSocket;
13083
- assert3(webSocket, webSocketUndefinedError);
13283
+ assert4(webSocket, webSocketUndefinedError);
13084
13284
  webSocket.removeEventListener("message", onMessage);
13085
13285
  }
13086
13286
  };
13087
13287
  }
13088
- var CloudflareDevEnvironment = class extends vite3.DevEnvironment {
13288
+ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
13089
13289
  #webSocketContainer;
13090
13290
  #worker;
13091
13291
  constructor(name, config) {
@@ -13110,12 +13310,12 @@ var CloudflareDevEnvironment = class extends vite3.DevEnvironment {
13110
13310
  }
13111
13311
  }
13112
13312
  );
13113
- assert3(
13313
+ assert4(
13114
13314
  response.ok,
13115
13315
  `Failed to initialize module runner, error: ${await response.text()}`
13116
13316
  );
13117
13317
  const webSocket = response.webSocket;
13118
- assert3(webSocket, "Failed to establish WebSocket");
13318
+ assert4(webSocket, "Failed to establish WebSocket");
13119
13319
  webSocket.accept();
13120
13320
  this.#webSocketContainer.webSocket = webSocket;
13121
13321
  }
@@ -13128,7 +13328,7 @@ var cloudflareBuiltInModules = [
13128
13328
  ];
13129
13329
  var defaultConditions = ["workerd", "module", "browser"];
13130
13330
  var target = "es2022";
13131
- function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
13331
+ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environment) {
13132
13332
  return {
13133
13333
  resolve: {
13134
13334
  // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
@@ -13146,19 +13346,15 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
13146
13346
  },
13147
13347
  build: {
13148
13348
  createEnvironment(name, config) {
13149
- return new vite3.BuildEnvironment(name, config);
13349
+ return new vite2.BuildEnvironment(name, config);
13150
13350
  },
13151
13351
  target,
13152
- // We need to enable `emitAssets` in order to support additional modules defined by `rules`
13153
13352
  emitAssets: true,
13154
- outDir: getOutputDirectory(userConfig, environmentName),
13353
+ manifest: environment.isEntry,
13354
+ outDir: getOutputDirectory(userConfig, environment.name),
13155
13355
  copyPublicDir: false,
13156
13356
  ssr: true,
13157
13357
  rollupOptions: {
13158
- // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
13159
- // so the input value here serves both as the build input as well as the starting point for
13160
- // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
13161
- // optimizeDeps.entries in the dev config)
13162
13358
  input: workerConfig.main
13163
13359
  }
13164
13360
  },
@@ -13204,8 +13400,8 @@ function initRunners(resolvedPluginConfig, viteDevServer, miniflare2) {
13204
13400
  }
13205
13401
 
13206
13402
  // src/debugging.ts
13207
- import assert4 from "node:assert";
13208
- import colors from "picocolors";
13403
+ import assert5 from "node:assert";
13404
+ import colors2 from "picocolors";
13209
13405
  var debuggingPath = "/__debug";
13210
13406
  function addDebugToVitePrintUrls(server) {
13211
13407
  const originalPrintUrls = server.printUrls;
@@ -13214,19 +13410,19 @@ function addDebugToVitePrintUrls(server) {
13214
13410
  const localUrl = server.resolvedUrls?.local[0];
13215
13411
  if (localUrl) {
13216
13412
  const { protocol, hostname, port } = new URL(localUrl);
13217
- const colorDebugUrl = (url) => colors.dim(
13218
- colors.yellow(
13219
- url.replace(/:(\d+)\//, (_, port2) => `:${colors.bold(port2)}/`)
13413
+ const colorDebugUrl = (url) => colors2.dim(
13414
+ colors2.yellow(
13415
+ url.replace(/:(\d+)\//, (_, port2) => `:${colors2.bold(port2)}/`)
13220
13416
  )
13221
13417
  );
13222
13418
  server.config.logger.info(
13223
- ` ${colors.green("\u279C")} ${colors.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${debuggingPath}`)}`
13419
+ ` ${colors2.green("\u279C")} ${colors2.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${debuggingPath}`)}`
13224
13420
  );
13225
13421
  }
13226
13422
  };
13227
13423
  }
13228
13424
  function getDebugPathHtml(workerNames, inspectorPort) {
13229
- assert4(workerNames.length >= 1, "no workers present to debug");
13425
+ assert5(workerNames.length >= 1, "no workers present to debug");
13230
13426
  const workerDevtoolsUrls = workerNames.map((workerName) => {
13231
13427
  const localHost = `localhost:${inspectorPort}/${workerName}`;
13232
13428
  const searchParams = new URLSearchParams({
@@ -13253,25 +13449,25 @@ function getDebugPathHtml(workerNames, inspectorPort) {
13253
13449
  }
13254
13450
 
13255
13451
  // src/deploy-config.ts
13256
- import assert5 from "node:assert";
13257
- import * as fs2 from "node:fs";
13258
- import * as path5 from "node:path";
13452
+ import assert6 from "node:assert";
13453
+ import * as fs3 from "node:fs";
13454
+ import * as path6 from "node:path";
13259
13455
  import "vite";
13260
13456
  import { unstable_readConfig } from "wrangler";
13261
13457
  function getDeployConfigPath(root) {
13262
- return path5.resolve(root, ".wrangler", "deploy", "config.json");
13458
+ return path6.resolve(root, ".wrangler", "deploy", "config.json");
13263
13459
  }
13264
13460
  function getWorkerConfigs(root, mixedModeEnabled) {
13265
13461
  const deployConfigPath = getDeployConfigPath(root);
13266
13462
  const deployConfig = JSON.parse(
13267
- fs2.readFileSync(deployConfigPath, "utf-8")
13463
+ fs3.readFileSync(deployConfigPath, "utf-8")
13268
13464
  );
13269
13465
  return [
13270
13466
  { configPath: deployConfig.configPath },
13271
13467
  ...deployConfig.auxiliaryWorkers
13272
13468
  ].map(({ configPath }) => {
13273
- const resolvedConfigPath = path5.resolve(
13274
- path5.dirname(deployConfigPath),
13469
+ const resolvedConfigPath = path6.resolve(
13470
+ path6.dirname(deployConfigPath),
13275
13471
  configPath
13276
13472
  );
13277
13473
  return unstable_readConfig(
@@ -13281,18 +13477,18 @@ function getWorkerConfigs(root, mixedModeEnabled) {
13281
13477
  });
13282
13478
  }
13283
13479
  function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
13284
- return path5.relative(
13480
+ return path6.relative(
13285
13481
  deployConfigDirectory,
13286
- path5.resolve(root, outputDirectory, "wrangler.json")
13482
+ path6.resolve(root, outputDirectory, "wrangler.json")
13287
13483
  );
13288
13484
  }
13289
13485
  function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13290
13486
  const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
13291
- const deployConfigDirectory = path5.dirname(deployConfigPath);
13292
- fs2.mkdirSync(deployConfigDirectory, { recursive: true });
13487
+ const deployConfigDirectory = path6.dirname(deployConfigPath);
13488
+ fs3.mkdirSync(deployConfigDirectory, { recursive: true });
13293
13489
  if (resolvedPluginConfig.type === "assets-only") {
13294
13490
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
13295
- assert5(
13491
+ assert6(
13296
13492
  clientOutputDirectory,
13297
13493
  "Unexpected error: client environment output directory is undefined"
13298
13494
  );
@@ -13304,13 +13500,13 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13304
13500
  ),
13305
13501
  auxiliaryWorkers: []
13306
13502
  };
13307
- fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
13503
+ fs3.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
13308
13504
  } else {
13309
13505
  let entryWorkerConfigPath;
13310
13506
  const auxiliaryWorkers = [];
13311
13507
  for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
13312
13508
  const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
13313
- assert5(
13509
+ assert6(
13314
13510
  outputDirectory,
13315
13511
  `Unexpected error: ${environmentName} environment output directory is undefined`
13316
13512
  );
@@ -13325,7 +13521,7 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13325
13521
  auxiliaryWorkers.push({ configPath });
13326
13522
  }
13327
13523
  }
13328
- assert5(
13524
+ assert6(
13329
13525
  entryWorkerConfigPath,
13330
13526
  `Unexpected error: entryWorkerConfigPath is undefined`
13331
13527
  );
@@ -13333,29 +13529,28 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13333
13529
  configPath: entryWorkerConfigPath,
13334
13530
  auxiliaryWorkers
13335
13531
  };
13336
- fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
13532
+ fs3.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
13337
13533
  }
13338
13534
  }
13339
13535
 
13340
13536
  // src/miniflare-options.ts
13341
- import assert6 from "node:assert";
13342
- import * as fs3 from "node:fs";
13537
+ import assert7 from "node:assert";
13538
+ import * as fs4 from "node:fs";
13343
13539
  import * as fsp from "node:fs/promises";
13344
- import * as path6 from "node:path";
13540
+ import * as path7 from "node:path";
13345
13541
  import { fileURLToPath as fileURLToPath2 } from "node:url";
13346
13542
  import {
13347
13543
  getDefaultDevRegistryPath,
13348
13544
  kCurrentWorker,
13349
13545
  Log,
13350
13546
  LogLevel,
13351
- Response as MiniflareResponse
13547
+ Response as MiniflareResponse2
13352
13548
  } from "miniflare";
13353
- import colors2 from "picocolors";
13549
+ import colors3 from "picocolors";
13354
13550
  import { globSync } from "tinyglobby";
13355
13551
  import "vite";
13356
13552
  import {
13357
- experimental_pickRemoteBindings,
13358
- experimental_startMixedModeSession,
13553
+ experimental_maybeStartOrUpdateMixedModeSession,
13359
13554
  unstable_convertConfigBindingsToStartWorkerBindings,
13360
13555
  unstable_getMiniflareWorkerOptions
13361
13556
  } from "wrangler";
@@ -13364,7 +13559,7 @@ function getPersistenceRoot(root, persistState) {
13364
13559
  return;
13365
13560
  }
13366
13561
  const defaultPersistPath = ".wrangler/state";
13367
- const persistPath = path6.resolve(
13562
+ const persistPath = path7.resolve(
13368
13563
  root,
13369
13564
  typeof persistState === "object" ? persistState.path : defaultPersistPath,
13370
13565
  "v3"
@@ -13383,8 +13578,9 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
13383
13578
  if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
13384
13579
  const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
13385
13580
  const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
13386
- assert6(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
13387
- entrypointNames.add(value.entrypoint);
13581
+ if (entrypointNames) {
13582
+ entrypointNames.add(value.entrypoint);
13583
+ }
13388
13584
  }
13389
13585
  }
13390
13586
  }
@@ -13398,20 +13594,20 @@ function getWorkerToDurableObjectClassNamesMap(workers) {
13398
13594
  for (const value of Object.values(worker.durableObjects ?? {})) {
13399
13595
  if (typeof value === "string") {
13400
13596
  const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
13401
- assert6(classNames, missingWorkerErrorMessage(worker.name));
13597
+ assert7(classNames, missingWorkerErrorMessage(worker.name));
13402
13598
  classNames.add(value);
13403
13599
  } else if (typeof value === "object") {
13404
13600
  if (value.scriptName) {
13405
13601
  const classNames = workerToDurableObjectClassNamesMap.get(
13406
13602
  value.scriptName
13407
13603
  );
13408
- assert6(classNames, missingWorkerErrorMessage(value.scriptName));
13604
+ assert7(classNames, missingWorkerErrorMessage(value.scriptName));
13409
13605
  classNames.add(value.className);
13410
13606
  } else {
13411
13607
  const classNames = workerToDurableObjectClassNamesMap.get(
13412
13608
  worker.name
13413
13609
  );
13414
- assert6(classNames, missingWorkerErrorMessage(worker.name));
13610
+ assert7(classNames, missingWorkerErrorMessage(worker.name));
13415
13611
  classNames.add(value.className);
13416
13612
  }
13417
13613
  }
@@ -13429,13 +13625,13 @@ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
13429
13625
  const classNames = workerToWorkflowEntrypointClassNamesMap.get(
13430
13626
  value.scriptName
13431
13627
  );
13432
- assert6(classNames, missingWorkerErrorMessage(value.scriptName));
13628
+ assert7(classNames, missingWorkerErrorMessage(value.scriptName));
13433
13629
  classNames.add(value.className);
13434
13630
  } else {
13435
13631
  const classNames = workerToWorkflowEntrypointClassNamesMap.get(
13436
13632
  worker.name
13437
13633
  );
13438
- assert6(classNames, missingWorkerErrorMessage(worker.name));
13634
+ assert7(classNames, missingWorkerErrorMessage(worker.name));
13439
13635
  classNames.add(value.className);
13440
13636
  }
13441
13637
  }
@@ -13466,8 +13662,8 @@ function logUnknownTails(tails, userWorkers, log) {
13466
13662
  const found = userWorkers.some((w) => w.name === name);
13467
13663
  if (!found) {
13468
13664
  log(
13469
- colors2.dim(
13470
- colors2.yellow(
13665
+ colors3.dim(
13666
+ colors3.yellow(
13471
13667
  `Tail consumer "${name}" was not found in your config. Make sure you add it to the config or run it in another dev session if you'd like to simulate receiving tail events locally.`
13472
13668
  )
13473
13669
  )
@@ -13475,6 +13671,7 @@ function logUnknownTails(tails, userWorkers, log) {
13475
13671
  }
13476
13672
  }
13477
13673
  }
13674
+ var mixedModeSessionsDataMap = /* @__PURE__ */ new Map();
13478
13675
  async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspectorPort) {
13479
13676
  const resolvedViteConfig = viteDevServer.config;
13480
13677
  const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
@@ -13491,8 +13688,8 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13491
13688
  modules: [
13492
13689
  {
13493
13690
  type: "ESModule",
13494
- path: path6.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13495
- contents: fs3.readFileSync(
13691
+ path: path7.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13692
+ contents: fs4.readFileSync(
13496
13693
  fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
13497
13694
  )
13498
13695
  }
@@ -13514,8 +13711,8 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13514
13711
  modules: [
13515
13712
  {
13516
13713
  type: "ESModule",
13517
- path: path6.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13518
- contents: fs3.readFileSync(
13714
+ path: path7.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13715
+ contents: fs4.readFileSync(
13519
13716
  fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
13520
13717
  )
13521
13718
  }
@@ -13524,26 +13721,44 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13524
13721
  CONFIG: assetsConfig
13525
13722
  },
13526
13723
  serviceBindings: {
13527
- __VITE_ASSET_EXISTS__: async (request) => {
13724
+ __VITE_HTML_EXISTS__: async (request) => {
13528
13725
  const { pathname } = new URL(request.url);
13529
- let exists = false;
13530
13726
  if (pathname.endsWith(".html")) {
13531
- try {
13532
- const filePath = path6.join(resolvedViteConfig.root, pathname);
13533
- const stats = await fsp.stat(filePath);
13534
- exists = stats.isFile();
13535
- } catch (error) {
13727
+ const { root, publicDir } = resolvedViteConfig;
13728
+ const publicDirInRoot = publicDir.startsWith(
13729
+ withTrailingSlash2(root)
13730
+ );
13731
+ const publicPath = withTrailingSlash2(publicDir.slice(root.length));
13732
+ if (publicDirInRoot && pathname.startsWith(publicPath)) {
13733
+ return MiniflareResponse2.json(null);
13734
+ }
13735
+ const publicDirFilePath = path7.join(publicDir, pathname);
13736
+ const rootDirFilePath = path7.join(root, pathname);
13737
+ for (const resolvedPath of [publicDirFilePath, rootDirFilePath]) {
13738
+ try {
13739
+ const stats = await fsp.stat(resolvedPath);
13740
+ if (stats.isFile()) {
13741
+ return MiniflareResponse2.json(
13742
+ resolvedPath === publicDirFilePath ? `${PUBLIC_DIR_PREFIX}${pathname}` : pathname
13743
+ );
13744
+ }
13745
+ } catch (error) {
13746
+ }
13536
13747
  }
13537
13748
  }
13538
- return MiniflareResponse.json(exists);
13749
+ return MiniflareResponse2.json(null);
13539
13750
  },
13540
- __VITE_FETCH_ASSET__: async (request) => {
13751
+ __VITE_FETCH_HTML__: async (request) => {
13541
13752
  const { pathname } = new URL(request.url);
13542
- const filePath = path6.join(resolvedViteConfig.root, pathname);
13753
+ const { root, publicDir } = resolvedViteConfig;
13754
+ const isInPublicDir = pathname.startsWith(PUBLIC_DIR_PREFIX);
13755
+ const resolvedPath = isInPublicDir ? path7.join(publicDir, pathname.slice(PUBLIC_DIR_PREFIX.length)) : path7.join(root, pathname);
13543
13756
  try {
13544
- let html = await fsp.readFile(filePath, "utf-8");
13545
- html = await viteDevServer.transformIndexHtml(pathname, html);
13546
- return new MiniflareResponse(html, {
13757
+ let html = await fsp.readFile(resolvedPath, "utf-8");
13758
+ if (!isInPublicDir) {
13759
+ html = await viteDevServer.transformIndexHtml(resolvedPath, html);
13760
+ }
13761
+ return new MiniflareResponse2(html, {
13547
13762
  headers: { "Content-Type": "text/html" }
13548
13763
  });
13549
13764
  } catch (error) {
@@ -13556,7 +13771,23 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13556
13771
  const workersFromConfig = resolvedPluginConfig.type === "workers" ? await Promise.all(
13557
13772
  Object.entries(resolvedPluginConfig.workers).map(
13558
13773
  async ([environmentName, workerConfig]) => {
13559
- const mixedModeSession = resolvedPluginConfig.experimental.mixedMode ? await maybeStartOrUpdateMixedModeSession(workerConfig) : void 0;
13774
+ const bindings = unstable_convertConfigBindingsToStartWorkerBindings(
13775
+ workerConfig
13776
+ );
13777
+ const preExistingMixedModeSession = workerConfig.configPath ? mixedModeSessionsDataMap.get(workerConfig.configPath) : void 0;
13778
+ const mixedModeSessionData = resolvedPluginConfig.experimental.mixedMode ? await experimental_maybeStartOrUpdateMixedModeSession(
13779
+ {
13780
+ name: workerConfig.name,
13781
+ bindings: bindings ?? {}
13782
+ },
13783
+ preExistingMixedModeSession ?? null
13784
+ ) : void 0;
13785
+ if (workerConfig.configPath && mixedModeSessionData) {
13786
+ mixedModeSessionsDataMap.set(
13787
+ workerConfig.configPath,
13788
+ mixedModeSessionData
13789
+ );
13790
+ }
13560
13791
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
13561
13792
  {
13562
13793
  ...workerConfig,
@@ -13564,7 +13795,7 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13564
13795
  },
13565
13796
  resolvedPluginConfig.cloudflareEnv,
13566
13797
  {
13567
- mixedModeConnectionString: mixedModeSession?.mixedModeConnectionString,
13798
+ mixedModeConnectionString: mixedModeSessionData?.session?.mixedModeConnectionString,
13568
13799
  mixedModeEnabled: resolvedPluginConfig.experimental.mixedMode
13569
13800
  }
13570
13801
  );
@@ -13595,7 +13826,7 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13595
13826
  __VITE_INVOKE_MODULE__: async (request) => {
13596
13827
  const payload = await request.json();
13597
13828
  const invokePayloadData = payload.data;
13598
- assert6(
13829
+ assert7(
13599
13830
  invokePayloadData.name === "fetchModule",
13600
13831
  `Invalid invoke event: ${invokePayloadData.name}`
13601
13832
  );
@@ -13605,11 +13836,11 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13605
13836
  externalize: moduleId,
13606
13837
  type: "module"
13607
13838
  };
13608
- return MiniflareResponse.json({ result: result2 });
13839
+ return MiniflareResponse2.json({ result: result2 });
13609
13840
  }
13610
13841
  const devEnvironment = viteDevServer.environments[environmentName];
13611
13842
  const result = await devEnvironment.hot.handleInvoke(payload);
13612
- return MiniflareResponse.json(result);
13843
+ return MiniflareResponse2.json(result);
13613
13844
  }
13614
13845
  }
13615
13846
  }
@@ -13653,7 +13884,7 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13653
13884
  const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
13654
13885
  workerOptions.name
13655
13886
  );
13656
- assert6(
13887
+ assert7(
13657
13888
  workerEntrypointNames,
13658
13889
  `WorkerEntrypoint names not found for worker ${workerOptions.name}`
13659
13890
  );
@@ -13665,7 +13896,7 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13665
13896
  const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
13666
13897
  workerOptions.name
13667
13898
  );
13668
- assert6(
13899
+ assert7(
13669
13900
  durableObjectClassNames,
13670
13901
  `DurableObject class names not found for worker ${workerOptions.name}`
13671
13902
  );
@@ -13675,7 +13906,7 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13675
13906
  );
13676
13907
  }
13677
13908
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
13678
- assert6(
13909
+ assert7(
13679
13910
  workflowEntrypointClassNames,
13680
13911
  `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
13681
13912
  );
@@ -13694,13 +13925,13 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13694
13925
  modules: [
13695
13926
  {
13696
13927
  type: "ESModule",
13697
- path: path6.join(miniflareModulesRoot, WRAPPER_PATH),
13928
+ path: path7.join(miniflareModulesRoot, WRAPPER_PATH),
13698
13929
  contents: wrappers.join("\n")
13699
13930
  },
13700
13931
  {
13701
13932
  type: "ESModule",
13702
- path: path6.join(miniflareModulesRoot, RUNNER_PATH),
13703
- contents: fs3.readFileSync(
13933
+ path: path7.join(miniflareModulesRoot, RUNNER_PATH),
13934
+ contents: fs4.readFileSync(
13704
13935
  fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
13705
13936
  )
13706
13937
  }
@@ -13712,18 +13943,18 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13712
13943
  async unsafeModuleFallbackService(request) {
13713
13944
  const url = new URL(request.url);
13714
13945
  const rawSpecifier = url.searchParams.get("rawSpecifier");
13715
- assert6(
13946
+ assert7(
13716
13947
  rawSpecifier,
13717
13948
  `Unexpected error: no specifier in request to module fallback service.`
13718
13949
  );
13719
13950
  const match = additionalModuleRE.exec(rawSpecifier);
13720
- assert6(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
13951
+ assert7(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
13721
13952
  const [full, moduleType, modulePath] = match;
13722
- assert6(
13953
+ assert7(
13723
13954
  moduleType,
13724
13955
  `Unexpected error: module type not found in reference: ${full}.`
13725
13956
  );
13726
- assert6(
13957
+ assert7(
13727
13958
  modulePath,
13728
13959
  `Unexpected error: module path not found in reference: ${full}.`
13729
13960
  );
@@ -13737,25 +13968,25 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13737
13968
  }
13738
13969
  switch (moduleType) {
13739
13970
  case "CompiledWasm": {
13740
- return MiniflareResponse.json({ wasm: Array.from(contents) });
13971
+ return MiniflareResponse2.json({ wasm: Array.from(contents) });
13741
13972
  }
13742
13973
  case "Data": {
13743
- return MiniflareResponse.json({ data: Array.from(contents) });
13974
+ return MiniflareResponse2.json({ data: Array.from(contents) });
13744
13975
  }
13745
13976
  case "Text": {
13746
- return MiniflareResponse.json({ text: contents.toString() });
13977
+ return MiniflareResponse2.json({ text: contents.toString() });
13747
13978
  }
13748
13979
  default: {
13749
- return MiniflareResponse.error();
13980
+ return MiniflareResponse2.error();
13750
13981
  }
13751
13982
  }
13752
13983
  }
13753
13984
  };
13754
13985
  }
13755
13986
  function getPreviewModules(main, modulesRules) {
13756
- assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
13757
- const rootPath = path6.dirname(main);
13758
- const entryPath = path6.basename(main);
13987
+ assert7(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
13988
+ const rootPath = path7.dirname(main);
13989
+ const entryPath = path7.basename(main);
13759
13990
  return {
13760
13991
  rootPath,
13761
13992
  modules: [
@@ -13764,9 +13995,9 @@ function getPreviewModules(main, modulesRules) {
13764
13995
  path: entryPath
13765
13996
  },
13766
13997
  ...modulesRules.flatMap(
13767
- ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path10) => ({
13998
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path11) => ({
13768
13999
  type,
13769
- path: path10
14000
+ path: path11
13770
14001
  }))
13771
14002
  )
13772
14003
  ]
@@ -13776,12 +14007,26 @@ async function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, pers
13776
14007
  const resolvedViteConfig = vitePreviewServer.config;
13777
14008
  const workers = (await Promise.all(
13778
14009
  workerConfigs.map(async (workerConfig, i) => {
13779
- const mixedModeSession = mixedModeEnabled ? await maybeStartOrUpdateMixedModeSession(workerConfig) : void 0;
14010
+ const bindings = unstable_convertConfigBindingsToStartWorkerBindings(workerConfig);
14011
+ const preExistingMixedModeSessionData = workerConfig.configPath ? mixedModeSessionsDataMap.get(workerConfig.configPath) : void 0;
14012
+ const mixedModeSessionData = mixedModeEnabled ? await experimental_maybeStartOrUpdateMixedModeSession(
14013
+ {
14014
+ name: workerConfig.name,
14015
+ bindings: bindings ?? {}
14016
+ },
14017
+ preExistingMixedModeSessionData ?? null
14018
+ ) : void 0;
14019
+ if (workerConfig.configPath && mixedModeSessionData) {
14020
+ mixedModeSessionsDataMap.set(
14021
+ workerConfig.configPath,
14022
+ mixedModeSessionData
14023
+ );
14024
+ }
13780
14025
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
13781
14026
  workerConfig,
13782
14027
  void 0,
13783
14028
  {
13784
- mixedModeConnectionString: mixedModeSession?.mixedModeConnectionString,
14029
+ mixedModeConnectionString: mixedModeSessionData?.session?.mixedModeConnectionString,
13785
14030
  mixedModeEnabled
13786
14031
  }
13787
14032
  );
@@ -13859,34 +14104,94 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
13859
14104
  return LogLevel.NONE;
13860
14105
  }
13861
14106
  }
13862
- var mixedModeSessionsMap = /* @__PURE__ */ new Map();
13863
- async function maybeStartOrUpdateMixedModeSession(workerConfig) {
13864
- const workerRemoteBindings = experimental_pickRemoteBindings(
13865
- unstable_convertConfigBindingsToStartWorkerBindings(workerConfig) ?? {}
13866
- );
13867
- assert6(workerConfig.name, "Found workerConfig without a name");
13868
- let mixedModeSession = mixedModeSessionsMap.get(workerConfig.name);
13869
- if (mixedModeSession === void 0) {
13870
- if (Object.keys(workerRemoteBindings).length > 0) {
13871
- mixedModeSession = await experimental_startMixedModeSession(workerRemoteBindings);
13872
- mixedModeSessionsMap.set(workerConfig.name, mixedModeSession);
14107
+
14108
+ // src/plugin-config.ts
14109
+ import assert9 from "node:assert";
14110
+ import * as path9 from "node:path";
14111
+
14112
+ // ../workers-shared/utils/configuration/parseStaticRouting.ts
14113
+ function parseStaticRouting(input) {
14114
+ if (input.length === 0) {
14115
+ throw new Error(
14116
+ "No `run_worker_first` rules were provided; must provide at least 1 rule."
14117
+ );
14118
+ }
14119
+ if (input.length > MAX_ROUTES_RULES) {
14120
+ throw new Error(
14121
+ `Too many \`run_worker_first\` rules were provided; ${input.length} rules provided exceeds max of ${MAX_ROUTES_RULES}.`
14122
+ );
14123
+ }
14124
+ const rawAssetWorkerRules = [];
14125
+ const assetWorkerRules = [];
14126
+ const userWorkerRules = [];
14127
+ const invalidRules = [];
14128
+ for (const rule of input) {
14129
+ if (rule.startsWith("!/")) {
14130
+ assetWorkerRules.push(rule.slice(1));
14131
+ rawAssetWorkerRules.push(rule);
14132
+ } else if (rule.startsWith("/")) {
14133
+ userWorkerRules.push(rule);
14134
+ } else if (rule.startsWith("!")) {
14135
+ invalidRules.push(`'${rule}': negative rules must start with '!/'`);
14136
+ } else {
14137
+ invalidRules.push(`'${rule}': rules must start with '/' or '!/'`);
13873
14138
  }
13874
- } else {
13875
- await mixedModeSession.updateBindings(workerRemoteBindings);
13876
14139
  }
13877
- await mixedModeSession?.ready;
13878
- return mixedModeSession;
14140
+ if (assetWorkerRules.length > 0 && userWorkerRules.length === 0) {
14141
+ throw new Error(
14142
+ "Only negative `run_worker_first` rules were provided; must provide at least 1 non-negative rule"
14143
+ );
14144
+ }
14145
+ const invalidAssetWorkerRules = validateStaticRoutingRules(rawAssetWorkerRules);
14146
+ const invalidUserWorkerRules = validateStaticRoutingRules(userWorkerRules);
14147
+ const errorMessage = formatInvalidRoutes([
14148
+ ...invalidRules,
14149
+ ...invalidUserWorkerRules,
14150
+ ...invalidAssetWorkerRules
14151
+ ]);
14152
+ if (errorMessage) {
14153
+ throw new Error(errorMessage);
14154
+ }
14155
+ return { asset_worker: assetWorkerRules, user_worker: userWorkerRules };
14156
+ }
14157
+ function validateStaticRoutingRules(rules) {
14158
+ const invalid = [];
14159
+ const seen = /* @__PURE__ */ new Set();
14160
+ for (const rule of rules) {
14161
+ if (rule.length > MAX_ROUTES_RULE_LENGTH) {
14162
+ invalid.push(
14163
+ `'${rule}': all rules must be less than ${MAX_ROUTES_RULE_LENGTH} characters in length`
14164
+ );
14165
+ }
14166
+ if (seen.has(rule)) {
14167
+ invalid.push(`'${rule}': rule is a duplicate; rules must be unique`);
14168
+ }
14169
+ if (rule.endsWith("*")) {
14170
+ for (const otherRule of rules) {
14171
+ if (otherRule !== rule && otherRule.startsWith(rule.slice(0, -1))) {
14172
+ invalid.push(`'${otherRule}': rule '${rule}' makes it redundant`);
14173
+ }
14174
+ }
14175
+ }
14176
+ seen.add(rule);
14177
+ }
14178
+ return invalid;
13879
14179
  }
14180
+ var formatInvalidRoutes = (invalidRules) => {
14181
+ if (invalidRules.length === 0) {
14182
+ return void 0;
14183
+ }
14184
+ return `Invalid routes in \`run_worker_first\`:
14185
+ ` + invalidRules.join("\n");
14186
+ };
13880
14187
 
13881
14188
  // src/plugin-config.ts
13882
- import assert8 from "node:assert";
13883
- import * as path8 from "node:path";
13884
- import * as vite6 from "vite";
14189
+ import * as vite5 from "vite";
13885
14190
 
13886
14191
  // src/workers-configs.ts
13887
- import assert7 from "node:assert";
13888
- import * as fs4 from "node:fs";
13889
- import * as path7 from "node:path";
14192
+ import assert8 from "node:assert";
14193
+ import * as fs5 from "node:fs";
14194
+ import * as path8 from "node:path";
13890
14195
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
13891
14196
  var nonApplicableWorkerConfigs = {
13892
14197
  /**
@@ -13981,7 +14286,7 @@ function getWarningForWorkersConfigs(configs) {
13981
14286
  const lines2 = [
13982
14287
  `
13983
14288
 
13984
- \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:`
14289
+ \x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path8.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
13985
14290
  ];
13986
14291
  nonApplicableLines.forEach((line) => lines2.push(line));
13987
14292
  lines2.push("");
@@ -13995,7 +14300,7 @@ function getWarningForWorkersConfigs(configs) {
13995
14300
  );
13996
14301
  if (nonApplicableLines.length > 0) {
13997
14302
  lines.push(
13998
- ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path7.relative("", workerConfig.config.configPath)}\`)` : ""}`
14303
+ ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path8.relative("", workerConfig.config.configPath)}\`)` : ""}`
13999
14304
  );
14000
14305
  nonApplicableLines.forEach((line) => lines.push(line));
14001
14306
  }
@@ -14076,7 +14381,7 @@ function getWorkerConfig(configPath, env2, mixedModeEnabled, opts) {
14076
14381
  if (!config.main) {
14077
14382
  throw new Error(missingFieldErrorMessage(`'main'`, configPath, env2));
14078
14383
  }
14079
- const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
14384
+ const mainStat = fs5.statSync(config.main, { throwIfNoEntry: false });
14080
14385
  if (!mainStat) {
14081
14386
  throw new Error(
14082
14387
  `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
@@ -14100,17 +14405,17 @@ function getWorkerConfig(configPath, env2, mixedModeEnabled, opts) {
14100
14405
  }
14101
14406
  function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
14102
14407
  if (requestedConfigPath) {
14103
- const configPath2 = path7.resolve(root, requestedConfigPath);
14408
+ const configPath2 = path8.resolve(root, requestedConfigPath);
14104
14409
  const forAuxiliaryWorkerErrorMessage = isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : "";
14105
14410
  const errorMessagePrefix = `The provided configPath (${configPath2})${forAuxiliaryWorkerErrorMessage}`;
14106
- const fileExtension = path7.extname(configPath2).slice(1);
14411
+ const fileExtension = path8.extname(configPath2).slice(1);
14107
14412
  if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
14108
14413
  const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
14109
14414
  throw new Error(
14110
14415
  `${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`
14111
14416
  );
14112
14417
  }
14113
- const mainStat = fs4.statSync(configPath2, { throwIfNoEntry: false });
14418
+ const mainStat = fs5.statSync(configPath2, { throwIfNoEntry: false });
14114
14419
  if (!mainStat) {
14115
14420
  throw new Error(
14116
14421
  `${errorMessagePrefix} doesn't point to an existing file`
@@ -14123,7 +14428,7 @@ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliar
14123
14428
  }
14124
14429
  return configPath2;
14125
14430
  }
14126
- assert7(
14431
+ assert8(
14127
14432
  isForAuxiliaryWorker === false,
14128
14433
  "Unexpected Error: trying to find the wrangler config for an auxiliary worker"
14129
14434
  );
@@ -14137,8 +14442,8 @@ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliar
14137
14442
  }
14138
14443
  function findWranglerConfig(root) {
14139
14444
  for (const extension of allowedWranglerConfigExtensions) {
14140
- const configPath = path7.join(root, `wrangler.${extension}`);
14141
- if (fs4.existsSync(configPath)) {
14445
+ const configPath = path8.join(root, `wrangler.${extension}`);
14446
+ if (fs5.existsSync(configPath)) {
14142
14447
  return configPath;
14143
14448
  }
14144
14449
  }
@@ -14153,8 +14458,8 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14153
14458
  const configPaths = /* @__PURE__ */ new Set();
14154
14459
  const persistState = pluginConfig.persistState ?? true;
14155
14460
  const experimental = pluginConfig.experimental ?? {};
14156
- const root = userConfig.root ? path8.resolve(userConfig.root) : process.cwd();
14157
- const { CLOUDFLARE_ENV: cloudflareEnv } = vite6.loadEnv(
14461
+ const root = userConfig.root ? path9.resolve(userConfig.root) : process.cwd();
14462
+ const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
14158
14463
  viteEnv.mode,
14159
14464
  root,
14160
14465
  /* prefixes */
@@ -14188,6 +14493,12 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14188
14493
  }
14189
14494
  const entryWorkerConfig = entryWorkerResolvedConfig.config;
14190
14495
  const entryWorkerEnvironmentName = pluginConfig.viteEnvironment?.name ?? workerNameToEnvironmentName(entryWorkerConfig.topLevelName);
14496
+ let staticRouting;
14497
+ if (Array.isArray(entryWorkerConfig.assets?.run_worker_first)) {
14498
+ staticRouting = parseStaticRouting(
14499
+ entryWorkerConfig.assets.run_worker_first
14500
+ );
14501
+ }
14191
14502
  const workers = {
14192
14503
  [entryWorkerEnvironmentName]: entryWorkerConfig
14193
14504
  };
@@ -14207,7 +14518,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14207
14518
  }
14208
14519
  );
14209
14520
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
14210
- assert8(
14521
+ assert9(
14211
14522
  workerResolvedConfig.type === "worker",
14212
14523
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
14213
14524
  );
@@ -14226,6 +14537,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14226
14537
  persistState,
14227
14538
  workers,
14228
14539
  entryWorkerEnvironmentName,
14540
+ staticRouting,
14229
14541
  rawConfigs: {
14230
14542
  entryWorker: entryWorkerResolvedConfig,
14231
14543
  auxiliaryWorkers: auxiliaryWorkersResolvedConfigs
@@ -14273,14 +14585,14 @@ function handleWebSocket(httpServer, getFetcher) {
14273
14585
  }
14274
14586
 
14275
14587
  // src/worker-environments-validation.ts
14276
- import assert9 from "node:assert";
14588
+ import assert10 from "node:assert";
14277
14589
  function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolvedViteConfig) {
14278
14590
  const workersEnvironmentNames = Object.keys(resolvedPluginConfig.workers);
14279
14591
  const disallowedEnvsConfigs = /* @__PURE__ */ new Map();
14280
14592
  for (const envName of workersEnvironmentNames) {
14281
14593
  const workerEnvConfig = resolvedViteConfig.environments[envName];
14282
- assert9(workerEnvConfig, `Missing environment config for "${envName}"`);
14283
- const { optimizeDeps, resolve: resolve7 } = workerEnvConfig;
14594
+ assert10(workerEnvConfig, `Missing environment config for "${envName}"`);
14595
+ const { optimizeDeps, resolve: resolve8 } = workerEnvConfig;
14284
14596
  const disallowedConfig = {};
14285
14597
  const disallowedOptimizeDepsExcludeEntries = (optimizeDeps.exclude ?? []).filter((entry) => {
14286
14598
  if (cloudflareBuiltInModules.includes(entry)) {
@@ -14297,8 +14609,8 @@ function validateWorkerEnvironmentsResolvedConfigs(resolvedPluginConfig, resolve
14297
14609
  if (disallowedOptimizeDepsExcludeEntries.length > 0) {
14298
14610
  disallowedConfig.optimizeDepsExclude = disallowedOptimizeDepsExcludeEntries;
14299
14611
  }
14300
- if (resolve7.external === true || resolve7.external.length > 0) {
14301
- disallowedConfig.resolveExternal = resolve7.external;
14612
+ if (resolve8.external === true || resolve8.external.length > 0) {
14613
+ disallowedConfig.resolveExternal = resolve8.external;
14302
14614
  }
14303
14615
  if (Object.keys(disallowedConfig).length > 0) {
14304
14616
  disallowedEnvsConfigs.set(envName, disallowedConfig);
@@ -14331,7 +14643,6 @@ function cloudflare2(pluginConfig = {}) {
14331
14643
  let resolvedViteConfig;
14332
14644
  const additionalModulePaths = /* @__PURE__ */ new Set();
14333
14645
  const nodeJsCompatWarningsMap = /* @__PURE__ */ new Map();
14334
- let hasClientBuild = false;
14335
14646
  return [
14336
14647
  {
14337
14648
  name: "vite-plugin-cloudflare",
@@ -14355,8 +14666,19 @@ function cloudflare2(pluginConfig = {}) {
14355
14666
  console.warn(workersConfigsWarning);
14356
14667
  }
14357
14668
  }
14669
+ const defaultDeniedFiles = [
14670
+ ".env",
14671
+ ".env.*",
14672
+ "*.{crt,pem}",
14673
+ "**/.git/**"
14674
+ ];
14358
14675
  return {
14359
14676
  appType: "custom",
14677
+ server: {
14678
+ fs: {
14679
+ deny: [...defaultDeniedFiles, ".dev.vars", ".dev.vars.*"]
14680
+ }
14681
+ },
14360
14682
  environments: resolvedPluginConfig.type === "workers" ? {
14361
14683
  ...Object.fromEntries(
14362
14684
  Object.entries(resolvedPluginConfig.workers).map(
@@ -14366,7 +14688,10 @@ function cloudflare2(pluginConfig = {}) {
14366
14688
  createCloudflareEnvironmentOptions(
14367
14689
  workerConfig,
14368
14690
  userConfig,
14369
- environmentName
14691
+ {
14692
+ name: environmentName,
14693
+ isEntry: resolvedPluginConfig.type === "workers" && environmentName === resolvedPluginConfig.entryWorkerEnvironmentName
14694
+ }
14370
14695
  )
14371
14696
  ];
14372
14697
  }
@@ -14379,33 +14704,7 @@ function cloudflare2(pluginConfig = {}) {
14379
14704
  }
14380
14705
  } : void 0,
14381
14706
  builder: {
14382
- buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
14383
- const clientEnvironment = builder.environments.client;
14384
- const defaultHtmlPath = path9.resolve(
14385
- builder.config.root,
14386
- "index.html"
14387
- );
14388
- if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs5.existsSync(defaultHtmlPath))) {
14389
- await builder.build(clientEnvironment);
14390
- }
14391
- if (resolvedPluginConfig.type === "workers") {
14392
- const workerEnvironments = Object.keys(
14393
- resolvedPluginConfig.workers
14394
- ).map((environmentName) => {
14395
- const environment = builder.environments[environmentName];
14396
- assert10(
14397
- environment,
14398
- `${environmentName} environment not found`
14399
- );
14400
- return environment;
14401
- });
14402
- await Promise.all(
14403
- workerEnvironments.map(
14404
- (environment) => builder.build(environment)
14405
- )
14406
- );
14407
- }
14408
- })
14707
+ buildApp: userConfig.builder?.buildApp ?? createBuildApp(resolvedPluginConfig)
14409
14708
  }
14410
14709
  };
14411
14710
  },
@@ -14437,18 +14736,18 @@ function cloudflare2(pluginConfig = {}) {
14437
14736
  { type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }
14438
14737
  ];
14439
14738
  const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
14440
- if (isEntryWorker && hasClientBuild) {
14739
+ if (isEntryWorker) {
14441
14740
  const workerOutputDirectory = this.environment.config.build.outDir;
14442
14741
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
14443
- assert10(
14742
+ assert11(
14444
14743
  clientOutputDirectory,
14445
14744
  "Unexpected error: client output directory is undefined"
14446
14745
  );
14447
14746
  workerConfig.assets = {
14448
14747
  ...workerConfig.assets,
14449
- directory: path9.relative(
14450
- path9.resolve(resolvedViteConfig.root, workerOutputDirectory),
14451
- path9.resolve(resolvedViteConfig.root, clientOutputDirectory)
14748
+ directory: path10.relative(
14749
+ path10.resolve(resolvedViteConfig.root, workerOutputDirectory),
14750
+ path10.resolve(resolvedViteConfig.root, clientOutputDirectory)
14452
14751
  )
14453
14752
  };
14454
14753
  } else {
@@ -14496,15 +14795,12 @@ function cloudflare2(pluginConfig = {}) {
14496
14795
  });
14497
14796
  },
14498
14797
  writeBundle() {
14499
- if (this.environment.name === "client") {
14500
- hasClientBuild = true;
14501
- }
14502
14798
  if (this.environment.name === (resolvedPluginConfig.type === "assets-only" ? "client" : resolvedPluginConfig.entryWorkerEnvironmentName)) {
14503
14799
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
14504
14800
  }
14505
14801
  },
14506
14802
  hotUpdate(options) {
14507
- const changedFilePath = path9.resolve(options.file);
14803
+ const changedFilePath = path10.resolve(options.file);
14508
14804
  if (resolvedPluginConfig.configPaths.has(changedFilePath) || hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(
14509
14805
  resolvedPluginConfig,
14510
14806
  resolvedViteConfig,
@@ -14530,40 +14826,78 @@ function cloudflare2(pluginConfig = {}) {
14530
14826
  await miniflare.setOptions(miniflareDevOptions);
14531
14827
  }
14532
14828
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14533
- if (viteDevServer.httpServer) {
14534
- handleWebSocket(viteDevServer.httpServer, async () => {
14535
- assert10(miniflare, `Miniflare not defined`);
14536
- const routerWorker = await miniflare.getWorker(ROUTER_WORKER_NAME);
14537
- return routerWorker.fetch;
14538
- });
14829
+ let preMiddleware;
14830
+ if (resolvedPluginConfig.type === "workers") {
14831
+ const entryWorkerConfig = getWorkerConfig2(
14832
+ resolvedPluginConfig.entryWorkerEnvironmentName
14833
+ );
14834
+ assert11(entryWorkerConfig, `No entry Worker config`);
14835
+ const entryWorkerName = entryWorkerConfig.name;
14836
+ if (viteDevServer.httpServer) {
14837
+ handleWebSocket(viteDevServer.httpServer, async () => {
14838
+ assert11(miniflare, `Miniflare not defined`);
14839
+ const entryWorker = await miniflare.getWorker(entryWorkerName);
14840
+ return entryWorker.fetch;
14841
+ });
14842
+ }
14843
+ const staticRouting = entryWorkerConfig.assets?.run_worker_first === true ? { user_worker: ["/*"] } : resolvedPluginConfig.staticRouting;
14844
+ if (staticRouting) {
14845
+ const excludeRulesMatcher = generateStaticRoutingRuleMatcher(
14846
+ staticRouting.asset_worker ?? []
14847
+ );
14848
+ const includeRulesMatcher = generateStaticRoutingRuleMatcher(
14849
+ staticRouting.user_worker
14850
+ );
14851
+ const userWorkerHandler = createRequestHandler(async (request) => {
14852
+ assert11(miniflare, `Miniflare not defined`);
14853
+ const userWorker = await miniflare.getWorker(entryWorkerName);
14854
+ return userWorker.fetch(request, { redirect: "manual" });
14855
+ });
14856
+ preMiddleware = async (req, res, next) => {
14857
+ assert11(req.url, `req.url not defined`);
14858
+ const request = new Request(new URL(req.url, UNKNOWN_HOST));
14859
+ if (req[kRequestType] === "asset") {
14860
+ next();
14861
+ } else if (excludeRulesMatcher({ request })) {
14862
+ req[kRequestType] === "asset";
14863
+ next();
14864
+ } else if (includeRulesMatcher({ request })) {
14865
+ userWorkerHandler(req, res, next);
14866
+ } else {
14867
+ next();
14868
+ }
14869
+ };
14870
+ }
14539
14871
  }
14540
14872
  return () => {
14541
- viteDevServer.middlewares.use(async (req, res, next) => {
14542
- try {
14543
- assert10(miniflare, `Miniflare not defined`);
14544
- const request = createRequest(req, res);
14545
- let response;
14873
+ if (preMiddleware) {
14874
+ const middlewareStack = viteDevServer.middlewares.stack;
14875
+ const cachedTransformMiddlewareIndex = middlewareStack.findIndex(
14876
+ (middleware) => "name" in middleware.handle && middleware.handle.name === "viteCachedTransformMiddleware"
14877
+ );
14878
+ assert11(
14879
+ cachedTransformMiddlewareIndex !== -1,
14880
+ "Failed to find viteCachedTransformMiddleware"
14881
+ );
14882
+ middlewareStack.splice(cachedTransformMiddlewareIndex, 0, {
14883
+ route: "",
14884
+ handle: preMiddleware
14885
+ });
14886
+ }
14887
+ viteDevServer.middlewares.use(
14888
+ createRequestHandler(async (request, req) => {
14889
+ assert11(miniflare, `Miniflare not defined`);
14546
14890
  if (req[kRequestType] === "asset") {
14547
14891
  const assetWorker = await miniflare.getWorker(ASSET_WORKER_NAME);
14548
- response = await assetWorker.fetch(
14549
- toMiniflareRequest(request),
14550
- { redirect: "manual" }
14551
- );
14892
+ return assetWorker.fetch(request, { redirect: "manual" });
14552
14893
  } else {
14553
14894
  const routerWorker = await miniflare.getWorker(ROUTER_WORKER_NAME);
14554
- response = await routerWorker.fetch(
14555
- toMiniflareRequest(request),
14556
- { redirect: "manual" }
14557
- );
14558
- }
14559
- if (req.httpVersionMajor === 2) {
14560
- response.headers.delete("transfer-encoding");
14895
+ return routerWorker.fetch(request, {
14896
+ redirect: "manual"
14897
+ });
14561
14898
  }
14562
- await sendResponse(res, response);
14563
- } catch (error) {
14564
- next(error);
14565
- }
14566
- });
14899
+ })
14900
+ );
14567
14901
  };
14568
14902
  },
14569
14903
  async configurePreviewServer(vitePreviewServer) {
@@ -14588,21 +14922,25 @@ function cloudflare2(pluginConfig = {}) {
14588
14922
  vitePreviewServer.httpServer,
14589
14923
  () => miniflare2.dispatchFetch
14590
14924
  );
14591
- vitePreviewServer.middlewares.use(async (req, res, next) => {
14592
- try {
14593
- const request = createRequest(req, res);
14594
- const response = await miniflare2.dispatchFetch(
14595
- toMiniflareRequest(request),
14596
- { redirect: "manual" }
14597
- );
14598
- if (req.httpVersionMajor === 2) {
14599
- response.headers.delete("transfer-encoding");
14600
- }
14601
- await sendResponse(res, response);
14602
- } catch (error) {
14603
- next(error);
14604
- }
14605
- });
14925
+ vitePreviewServer.middlewares.use(
14926
+ createRequestHandler((request) => {
14927
+ return miniflare2.dispatchFetch(request, { redirect: "manual" });
14928
+ })
14929
+ );
14930
+ }
14931
+ },
14932
+ // Plugin to provide a fallback entry file
14933
+ {
14934
+ name: "vite-plugin-cloudflare:fallback-entry",
14935
+ resolveId(source) {
14936
+ if (source === "virtual:__cloudflare_fallback_entry__") {
14937
+ return `\0virtual:__cloudflare_fallback_entry__`;
14938
+ }
14939
+ },
14940
+ load(id) {
14941
+ if (id === "\0virtual:__cloudflare_fallback_entry__") {
14942
+ return ``;
14943
+ }
14606
14944
  }
14607
14945
  },
14608
14946
  // Plugin to support `.wasm?init` extension
@@ -14664,7 +15002,7 @@ function cloudflare2(pluginConfig = {}) {
14664
15002
  for (const match of matches) {
14665
15003
  magicString ??= new MagicString(code);
14666
15004
  const [full, _, modulePath] = match;
14667
- assert10(
15005
+ assert11(
14668
15006
  modulePath,
14669
15007
  `Unexpected error: module path not found in reference ${full}.`
14670
15008
  );
@@ -14678,13 +15016,13 @@ function cloudflare2(pluginConfig = {}) {
14678
15016
  }
14679
15017
  const referenceId = this.emitFile({
14680
15018
  type: "asset",
14681
- name: path9.basename(modulePath),
15019
+ name: path10.basename(modulePath),
14682
15020
  originalFileName: modulePath,
14683
15021
  source
14684
15022
  });
14685
15023
  const emittedFileName = this.getFileName(referenceId);
14686
- const relativePath = vite7.normalizePath(
14687
- path9.relative(path9.dirname(chunk.fileName), emittedFileName)
15024
+ const relativePath = vite6.normalizePath(
15025
+ path10.relative(path10.dirname(chunk.fileName), emittedFileName)
14688
15026
  );
14689
15027
  const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
14690
15028
  magicString.update(
@@ -14744,12 +15082,15 @@ function cloudflare2(pluginConfig = {}) {
14744
15082
  // rather than allowing the resolve hook here to alias then to polyfills.
14745
15083
  enforce: "pre",
14746
15084
  async resolveId(source, importer, options) {
15085
+ if (isGlobalVirtualModule(source)) {
15086
+ return source;
15087
+ }
14747
15088
  const result = resolveNodeJSImport(source);
14748
15089
  if (!result) {
14749
15090
  return this.resolve(source, importer, options);
14750
15091
  }
14751
15092
  if (this.environment.mode === "dev") {
14752
- assert10(
15093
+ assert11(
14753
15094
  this.environment.depsOptimizer,
14754
15095
  "depsOptimizer is required in dev mode"
14755
15096
  );
@@ -14761,6 +15102,9 @@ function cloudflare2(pluginConfig = {}) {
14761
15102
  }
14762
15103
  return this.resolve(result.resolved, importer, options);
14763
15104
  },
15105
+ load(id) {
15106
+ return getGlobalVirtualModule(id);
15107
+ },
14764
15108
  async transform(code, id) {
14765
15109
  const workerConfig = getWorkerConfig2(this.environment.name);
14766
15110
  if (!workerConfig) {
@@ -14845,7 +15189,7 @@ function cloudflare2(pluginConfig = {}) {
14845
15189
  addDebugToVitePrintUrls(vitePreviewServer);
14846
15190
  }
14847
15191
  const workerNames = workerConfigs.map((worker) => {
14848
- assert10(worker.name, "Expected the Worker to have a name");
15192
+ assert11(worker.name, "Expected the Worker to have a name");
14849
15193
  return worker.name;
14850
15194
  });
14851
15195
  vitePreviewServer.middlewares.use(async (req, res, next) => {
@@ -14880,13 +15224,13 @@ function cloudflare2(pluginConfig = {}) {
14880
15224
  setup(build) {
14881
15225
  build.onResolve(
14882
15226
  { filter: NODEJS_MODULES_RE },
14883
- ({ path: path10, importer }) => {
14884
- if (isNodeAls(workerConfig) && isNodeAlsModule(path10)) {
15227
+ ({ path: path11, importer }) => {
15228
+ if (isNodeAls(workerConfig) && isNodeAlsModule(path11)) {
14885
15229
  return;
14886
15230
  }
14887
15231
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
14888
- nodeJsCompatWarnings?.registerImport(path10, importer);
14889
- return { path: path10, external: true };
15232
+ nodeJsCompatWarnings?.registerImport(path11, importer);
15233
+ return { path: path11, external: true };
14890
15234
  }
14891
15235
  );
14892
15236
  }
@@ -14929,7 +15273,7 @@ function cloudflare2(pluginConfig = {}) {
14929
15273
  }
14930
15274
  ];
14931
15275
  function getWorkerConfig2(environmentName) {
14932
- assert10(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
15276
+ assert11(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
14933
15277
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
14934
15278
  }
14935
15279
  }
@@ -14943,7 +15287,7 @@ async function getInputInspectorPortOption(pluginConfig, viteServer) {
14943
15287
  const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
14944
15288
  if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
14945
15289
  viteServer.config.logger.warn(
14946
- colors3.dim(
15290
+ colors4.dim(
14947
15291
  `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
14948
15292
  `
14949
15293
  )
@@ -14959,19 +15303,19 @@ async function getResolvedInspectorPort(pluginConfig) {
14959
15303
  return null;
14960
15304
  }
14961
15305
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
14962
- const configDir = path9.dirname(configPath);
15306
+ const configDir = path10.dirname(configPath);
14963
15307
  const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
14964
15308
  const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
14965
- const targetPath = fs5.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs5.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
15309
+ const targetPath = fs6.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs6.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
14966
15310
  if (targetPath) {
14967
- const dotDevDotVarsContent = fs5.readFileSync(targetPath);
15311
+ const dotDevDotVarsContent = fs6.readFileSync(targetPath);
14968
15312
  return dotDevDotVarsContent;
14969
15313
  }
14970
15314
  return null;
14971
15315
  }
14972
15316
  function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
14973
15317
  return [...resolvedPluginConfig.configPaths].some((configPath) => {
14974
- const dotDevDotVars = path9.join(path9.dirname(configPath), ".dev.vars");
15318
+ const dotDevDotVars = path10.join(path10.dirname(configPath), ".dev.vars");
14975
15319
  if (dotDevDotVars === changedFilePath) {
14976
15320
  return true;
14977
15321
  }