@cloudflare/vite-plugin 0.0.0-4a742f249 → 0.0.0-4ad78ea2c

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
@@ -1200,6 +1200,7 @@ var cloudflareBuiltInModules = [
1200
1200
  "cloudflare:workflows"
1201
1201
  ];
1202
1202
  var defaultConditions = ["workerd", "module", "browser"];
1203
+ var target = "es2022";
1203
1204
  function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1204
1205
  return {
1205
1206
  resolve: {
@@ -1220,7 +1221,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1220
1221
  createEnvironment(name2, config) {
1221
1222
  return new vite2.BuildEnvironment(name2, config);
1222
1223
  },
1223
- target: "es2022",
1224
+ target,
1224
1225
  // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1225
1226
  emitAssets: true,
1226
1227
  outDir: getOutputDirectory(userConfig, environmentName),
@@ -1241,6 +1242,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1241
1242
  exclude: [...cloudflareBuiltInModules],
1242
1243
  esbuildOptions: {
1243
1244
  platform: "neutral",
1245
+ target,
1244
1246
  conditions: [...defaultConditions, "development"],
1245
1247
  resolveExtensions: [
1246
1248
  ".mjs",
@@ -1364,7 +1366,13 @@ import * as fs2 from "node:fs";
1364
1366
  import * as fsp from "node:fs/promises";
1365
1367
  import * as path3 from "node:path";
1366
1368
  import { fileURLToPath } from "node:url";
1367
- import { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
1369
+ import {
1370
+ kCurrentWorker,
1371
+ Log,
1372
+ LogLevel,
1373
+ Response as MiniflareResponse
1374
+ } from "miniflare";
1375
+ import { globSync } from "tinyglobby";
1368
1376
  import "vite";
1369
1377
  import {
1370
1378
  unstable_getMiniflareWorkerOptions,
@@ -1398,11 +1406,10 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
1398
1406
  );
1399
1407
  for (const worker of workers) {
1400
1408
  for (const value of Object.values(worker.serviceBindings ?? {})) {
1401
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1402
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1403
- value.name
1404
- );
1405
- assert4(entrypointNames, missingWorkerErrorMessage(value.name));
1409
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1410
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1411
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1412
+ assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1406
1413
  entrypointNames.add(value.entrypoint);
1407
1414
  }
1408
1415
  }
@@ -1547,7 +1554,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1547
1554
  }
1548
1555
  }
1549
1556
  ];
1550
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1557
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1551
1558
  ([environmentName, workerConfig]) => {
1552
1559
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1553
1560
  {
@@ -1556,51 +1563,58 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1556
1563
  },
1557
1564
  resolvedPluginConfig.cloudflareEnv
1558
1565
  );
1566
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1559
1567
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1560
1568
  return {
1561
- ...workerOptions,
1562
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1563
- name: workerConfig.name,
1564
- modulesRoot: miniflareModulesRoot,
1565
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1566
- bindings: {
1567
- ...workerOptions.bindings,
1568
- __VITE_ROOT__: resolvedViteConfig.root,
1569
- __VITE_ENTRY_PATH__: workerConfig.main
1570
- },
1571
- serviceBindings: {
1572
- ...workerOptions.serviceBindings,
1573
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1574
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1575
- } : {},
1576
- __VITE_INVOKE_MODULE__: async (request) => {
1577
- const payload = await request.json();
1578
- const invokePayloadData = payload.data;
1579
- assert4(
1580
- invokePayloadData.name === "fetchModule",
1581
- `Invalid invoke event: ${invokePayloadData.name}`
1582
- );
1583
- const [moduleId] = invokePayloadData.data;
1584
- const moduleRE = new RegExp(MODULE_PATTERN);
1585
- const shouldExternalize = (
1586
- // Worker modules (CompiledWasm, Text, Data)
1587
- moduleRE.test(moduleId)
1588
- );
1589
- if (shouldExternalize) {
1590
- const result2 = {
1591
- externalize: moduleId,
1592
- type: "module"
1593
- };
1594
- return MiniflareResponse.json({ result: result2 });
1569
+ externalWorkers: externalWorkers2,
1570
+ worker: {
1571
+ ...workerOptions,
1572
+ name: workerOptions.name ?? workerConfig.name,
1573
+ modulesRoot: miniflareModulesRoot,
1574
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1575
+ bindings: {
1576
+ ...workerOptions.bindings,
1577
+ __VITE_ROOT__: resolvedViteConfig.root,
1578
+ __VITE_ENTRY_PATH__: workerConfig.main
1579
+ },
1580
+ serviceBindings: {
1581
+ ...workerOptions.serviceBindings,
1582
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1583
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
1584
+ } : {},
1585
+ __VITE_INVOKE_MODULE__: async (request) => {
1586
+ const payload = await request.json();
1587
+ const invokePayloadData = payload.data;
1588
+ assert4(
1589
+ invokePayloadData.name === "fetchModule",
1590
+ `Invalid invoke event: ${invokePayloadData.name}`
1591
+ );
1592
+ const [moduleId] = invokePayloadData.data;
1593
+ const moduleRE = new RegExp(MODULE_PATTERN);
1594
+ const shouldExternalize = (
1595
+ // Worker modules (CompiledWasm, Text, Data)
1596
+ moduleRE.test(moduleId)
1597
+ );
1598
+ if (shouldExternalize) {
1599
+ const result2 = {
1600
+ externalize: moduleId,
1601
+ type: "module"
1602
+ };
1603
+ return MiniflareResponse.json({ result: result2 });
1604
+ }
1605
+ const devEnvironment = viteDevServer.environments[environmentName];
1606
+ const result = await devEnvironment.hot.handleInvoke(payload);
1607
+ return MiniflareResponse.json(result);
1595
1608
  }
1596
- const devEnvironment = viteDevServer.environments[environmentName];
1597
- const result = await devEnvironment.hot.handleInvoke(payload);
1598
- return MiniflareResponse.json(result);
1599
1609
  }
1600
1610
  }
1601
1611
  };
1602
1612
  }
1603
1613
  ) : [];
1614
+ const userWorkers = workersFromConfig.map((options) => options.worker);
1615
+ const externalWorkers = workersFromConfig.flatMap(
1616
+ (options) => options.externalWorkers
1617
+ );
1604
1618
  const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1605
1619
  const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1606
1620
  const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
@@ -1620,6 +1634,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1620
1634
  ),
1621
1635
  workers: [
1622
1636
  ...assetWorkers,
1637
+ ...externalWorkers,
1623
1638
  ...userWorkers.map((workerOptions) => {
1624
1639
  const wrappers = [
1625
1640
  `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
@@ -1652,7 +1667,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1652
1667
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1653
1668
  assert4(
1654
1669
  workflowEntrypointClassNames,
1655
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1670
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1656
1671
  );
1657
1672
  for (const className of [...workflowEntrypointClassNames].sort()) {
1658
1673
  wrappers.push(
@@ -1688,17 +1703,19 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1688
1703
  );
1689
1704
  const moduleRE = new RegExp(MODULE_PATTERN);
1690
1705
  const match = moduleRE.exec(rawSpecifier);
1691
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1706
+ assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1692
1707
  const [full, moduleType, modulePath] = match;
1693
1708
  assert4(
1694
1709
  modulePath,
1695
- `Unexpected error: module path not found in reference ${full}.`
1710
+ `Unexpected error: module path not found in reference: ${full}.`
1696
1711
  );
1697
1712
  let source;
1698
1713
  try {
1699
1714
  source = fs2.readFileSync(modulePath);
1700
1715
  } catch (error) {
1701
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1716
+ throw new Error(
1717
+ `Import "${modulePath}" not found. Does the file exist?`
1718
+ );
1702
1719
  }
1703
1720
  return MiniflareResponse.json({
1704
1721
  // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
@@ -1707,22 +1724,44 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1707
1724
  }
1708
1725
  };
1709
1726
  }
1727
+ function getPreviewModules(main, modulesRules) {
1728
+ assert4(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
1729
+ const rootPath = path3.dirname(main);
1730
+ const entryPath = path3.basename(main);
1731
+ return {
1732
+ rootPath,
1733
+ modules: [
1734
+ {
1735
+ type: "ESModule",
1736
+ path: entryPath
1737
+ },
1738
+ ...modulesRules.flatMap(
1739
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
1740
+ type,
1741
+ path: path8
1742
+ }))
1743
+ )
1744
+ ]
1745
+ };
1746
+ }
1710
1747
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1711
1748
  const resolvedViteConfig = vitePreviewServer.config;
1712
1749
  const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1713
1750
  const workerConfigs = configPaths.map(
1714
1751
  (configPath) => unstable_readConfig({ config: configPath })
1715
1752
  );
1716
- const workers = workerConfigs.map((config) => {
1753
+ const workers = workerConfigs.flatMap((config) => {
1717
1754
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1718
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1719
- return {
1720
- ...workerOptions,
1721
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1722
- name: config.name,
1723
- modules: true,
1724
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1725
- };
1755
+ const { externalWorkers } = miniflareWorkerOptions;
1756
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1757
+ return [
1758
+ {
1759
+ ...workerOptions,
1760
+ name: workerOptions.name ?? config.name,
1761
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
1762
+ },
1763
+ ...externalWorkers
1764
+ ];
1726
1765
  });
1727
1766
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
1728
1767
  return {
@@ -7364,7 +7403,7 @@ var isAbsolute = function(p) {
7364
7403
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7365
7404
  import assert5 from "node:assert";
7366
7405
  import process$1 from "node:process";
7367
- import path4, { dirname as dirname3 } from "node:path";
7406
+ import path4, { dirname as dirname4 } from "node:path";
7368
7407
  import v8 from "node:v8";
7369
7408
  import { format as format2, inspect } from "node:util";
7370
7409
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7496,14 +7535,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7496
7535
  * @param {boolean} [isImport=false]
7497
7536
  * @param {string} [base]
7498
7537
  */
7499
- (packagePath, key, target, isImport = false, base = void 0) => {
7500
- const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
7538
+ (packagePath, key, target2, isImport = false, base = void 0) => {
7539
+ const relatedError = typeof target2 === "string" && !isImport && target2.length > 0 && !target2.startsWith("./");
7501
7540
  if (key === ".") {
7502
7541
  assert5(isImport === false);
7503
- return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7542
+ 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 "./"' : ""}`;
7504
7543
  }
7505
7544
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7506
- target
7545
+ target2
7507
7546
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7508
7547
  },
7509
7548
  Error
@@ -7899,14 +7938,14 @@ var patternRegEx = /\*/g;
7899
7938
  var encodedSeparatorRegEx = /%2f|%5c/i;
7900
7939
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7901
7940
  var doubleSlashRegEx = /[/\\]{2}/;
7902
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7941
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7903
7942
  if (process$1.noDeprecation) {
7904
7943
  return;
7905
7944
  }
7906
7945
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7907
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7946
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7908
7947
  process$1.emitWarning(
7909
- `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7948
+ `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target2}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7910
7949
  "DeprecationWarning",
7911
7950
  "DEP0166"
7912
7951
  );
@@ -8064,47 +8103,47 @@ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8064
8103
  base && fileURLToPath$1(base)
8065
8104
  );
8066
8105
  }
8067
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8068
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8106
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
8107
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
8069
8108
  return new ERR_INVALID_PACKAGE_TARGET(
8070
8109
  fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8071
8110
  subpath,
8072
- target,
8111
+ target2,
8073
8112
  internal,
8074
8113
  base && fileURLToPath$1(base)
8075
8114
  );
8076
8115
  }
8077
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8078
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8079
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8080
- if (!target.startsWith("./")) {
8081
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8116
+ function resolvePackageTargetString(target2, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8117
+ if (subpath !== "" && !pattern && target2[target2.length - 1] !== "/")
8118
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8119
+ if (!target2.startsWith("./")) {
8120
+ if (internal && !target2.startsWith("../") && !target2.startsWith("/")) {
8082
8121
  let isURL = false;
8083
8122
  try {
8084
- new URL$1(target);
8123
+ new URL$1(target2);
8085
8124
  isURL = true;
8086
8125
  } catch {
8087
8126
  }
8088
8127
  if (!isURL) {
8089
8128
  const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8090
8129
  patternRegEx,
8091
- target,
8130
+ target2,
8092
8131
  () => subpath
8093
- ) : target + subpath;
8132
+ ) : target2 + subpath;
8094
8133
  return packageResolve(exportTarget, packageJsonUrl, conditions);
8095
8134
  }
8096
8135
  }
8097
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8136
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8098
8137
  }
8099
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8100
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8138
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
8139
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
8101
8140
  if (!isPathMap) {
8102
8141
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8103
8142
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8104
8143
  patternRegEx,
8105
- target,
8144
+ target2,
8106
8145
  () => subpath
8107
- ) : target;
8146
+ ) : target2;
8108
8147
  emitInvalidSegmentDeprecation(
8109
8148
  resolvedTarget,
8110
8149
  request,
@@ -8116,14 +8155,14 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8116
8155
  );
8117
8156
  }
8118
8157
  } else {
8119
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8158
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8120
8159
  }
8121
8160
  }
8122
- const resolved = new URL$1(target, packageJsonUrl);
8161
+ const resolved = new URL$1(target2, packageJsonUrl);
8123
8162
  const resolvedPath = resolved.pathname;
8124
8163
  const packagePath = new URL$1(".", packageJsonUrl).pathname;
8125
8164
  if (!resolvedPath.startsWith(packagePath))
8126
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8165
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8127
8166
  if (subpath === "") return resolved;
8128
8167
  if (invalidSegmentRegEx.exec(subpath) !== null) {
8129
8168
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
@@ -8131,9 +8170,9 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8131
8170
  if (!isPathMap) {
8132
8171
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8133
8172
  patternRegEx,
8134
- target,
8173
+ target2,
8135
8174
  () => subpath
8136
- ) : target;
8175
+ ) : target2;
8137
8176
  emitInvalidSegmentDeprecation(
8138
8177
  resolvedTarget,
8139
8178
  request,
@@ -8164,10 +8203,10 @@ function isArrayIndex(key) {
8164
8203
  if (`${keyNumber}` !== key) return false;
8165
8204
  return keyNumber >= 0 && keyNumber < 4294967295;
8166
8205
  }
8167
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8168
- if (typeof target === "string") {
8206
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8207
+ if (typeof target2 === "string") {
8169
8208
  return resolvePackageTargetString(
8170
- target,
8209
+ target2,
8171
8210
  subpath,
8172
8211
  packageSubpath,
8173
8212
  packageJsonUrl,
@@ -8178,8 +8217,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8178
8217
  conditions
8179
8218
  );
8180
8219
  }
8181
- if (Array.isArray(target)) {
8182
- const targetList = target;
8220
+ if (Array.isArray(target2)) {
8221
+ const targetList = target2;
8183
8222
  if (targetList.length === 0) return null;
8184
8223
  let lastException;
8185
8224
  let i = -1;
@@ -8219,8 +8258,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8219
8258
  }
8220
8259
  throw lastException;
8221
8260
  }
8222
- if (typeof target === "object" && target !== null) {
8223
- const keys = Object.getOwnPropertyNames(target);
8261
+ if (typeof target2 === "object" && target2 !== null) {
8262
+ const keys = Object.getOwnPropertyNames(target2);
8224
8263
  let i = -1;
8225
8264
  while (++i < keys.length) {
8226
8265
  const key = keys[i];
@@ -8238,7 +8277,7 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8238
8277
  if (key === "default" || conditions && conditions.has(key)) {
8239
8278
  const conditionalTarget = (
8240
8279
  /** @type {unknown} */
8241
- target[key]
8280
+ target2[key]
8242
8281
  );
8243
8282
  const resolveResult = resolvePackageTarget(
8244
8283
  packageJsonUrl,
@@ -8257,12 +8296,12 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8257
8296
  }
8258
8297
  return null;
8259
8298
  }
8260
- if (target === null) {
8299
+ if (target2 === null) {
8261
8300
  return null;
8262
8301
  }
8263
8302
  throw invalidPackageTarget(
8264
8303
  packageSubpath,
8265
- target,
8304
+ target2,
8266
8305
  packageJsonUrl,
8267
8306
  internal,
8268
8307
  base
@@ -8309,10 +8348,10 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8309
8348
  exports = { ".": exports };
8310
8349
  }
8311
8350
  if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8312
- const target = exports[packageSubpath];
8351
+ const target2 = exports[packageSubpath];
8313
8352
  const resolveResult = resolvePackageTarget(
8314
8353
  packageJsonUrl,
8315
- target,
8354
+ target2,
8316
8355
  "",
8317
8356
  packageSubpath,
8318
8357
  base,
@@ -8352,13 +8391,13 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8352
8391
  }
8353
8392
  }
8354
8393
  if (bestMatch) {
8355
- const target = (
8394
+ const target2 = (
8356
8395
  /** @type {unknown} */
8357
8396
  exports[bestMatch]
8358
8397
  );
8359
8398
  const resolveResult = resolvePackageTarget(
8360
8399
  packageJsonUrl,
8361
- target,
8400
+ target2,
8362
8401
  bestMatchSubpath,
8363
8402
  bestMatch,
8364
8403
  base,
@@ -8433,10 +8472,10 @@ function packageImportsResolve(name2, base, conditions) {
8433
8472
  }
8434
8473
  }
8435
8474
  if (bestMatch) {
8436
- const target = imports[bestMatch];
8475
+ const target2 = imports[bestMatch];
8437
8476
  const resolveResult = resolvePackageTarget(
8438
8477
  packageJsonUrl,
8439
- target,
8478
+ target2,
8440
8479
  bestMatchSubpath,
8441
8480
  bestMatch,
8442
8481
  base,
@@ -8726,11 +8765,6 @@ function isNodeCompat(workerConfig) {
8726
8765
  if (nodeCompatMode === "v2") {
8727
8766
  return true;
8728
8767
  }
8729
- if (nodeCompatMode === "legacy") {
8730
- throw new Error(
8731
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8732
- );
8733
- }
8734
8768
  if (nodeCompatMode === "v1") {
8735
8769
  throw new Error(
8736
8770
  `Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
@@ -8837,7 +8871,6 @@ var nonApplicableWorkerConfigs = {
8837
8871
  "build",
8838
8872
  "find_additional_modules",
8839
8873
  "no_bundle",
8840
- "node_compat",
8841
8874
  "preserve_file_names",
8842
8875
  "site",
8843
8876
  "tsconfig",
@@ -8854,7 +8887,6 @@ var nullableNonApplicable = [
8854
8887
  "find_additional_modules",
8855
8888
  "minify",
8856
8889
  "no_bundle",
8857
- "node_compat",
8858
8890
  "preserve_file_names",
8859
8891
  "site",
8860
8892
  "tsconfig",
@@ -9005,6 +9037,17 @@ function getWorkerConfig(configPath, env2, opts) {
9005
9037
  };
9006
9038
  }
9007
9039
  assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9040
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9041
+ if (!mainStat) {
9042
+ throw new Error(
9043
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9044
+ );
9045
+ }
9046
+ if (mainStat.isDirectory()) {
9047
+ throw new Error(
9048
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9049
+ );
9050
+ }
9008
9051
  return {
9009
9052
  type: "worker",
9010
9053
  raw,
@@ -9105,8 +9148,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9105
9148
  }
9106
9149
 
9107
9150
  // src/websockets.ts
9151
+ import { coupleWebSocket } from "miniflare";
9108
9152
  import { WebSocketServer } from "ws";
9109
- function handleWebSocket(httpServer, fetcher, logger) {
9153
+ function handleWebSocket(httpServer, fetcher) {
9110
9154
  const nodeWebSocket = new WebSocketServer({ noServer: true });
9111
9155
  httpServer.on(
9112
9156
  "upgrade",
@@ -9130,34 +9174,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9130
9174
  socket,
9131
9175
  head,
9132
9176
  async (clientWebSocket) => {
9133
- workerWebSocket.accept();
9134
- workerWebSocket.addEventListener("message", (event) => {
9135
- clientWebSocket.send(event.data);
9136
- });
9137
- workerWebSocket.addEventListener("error", (event) => {
9138
- logger.error(
9139
- `WebSocket error:
9140
- ${event.error?.stack || event.error?.message}`,
9141
- { error: event.error }
9142
- );
9143
- });
9144
- workerWebSocket.addEventListener("close", () => {
9145
- clientWebSocket.close();
9146
- });
9147
- clientWebSocket.on("message", (data2, isBinary) => {
9148
- workerWebSocket.send(
9149
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9150
- );
9151
- });
9152
- clientWebSocket.on("error", (error) => {
9153
- logger.error(`WebSocket error:
9154
- ${error.stack || error.message}`, {
9155
- error
9156
- });
9157
- });
9158
- clientWebSocket.on("close", () => {
9159
- workerWebSocket.close();
9160
- });
9177
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9161
9178
  nodeWebSocket.emit("connection", clientWebSocket, request);
9162
9179
  }
9163
9180
  );
@@ -9216,7 +9233,7 @@ function cloudflare2(pluginConfig = {}) {
9216
9233
  }
9217
9234
  } : void 0,
9218
9235
  builder: {
9219
- async buildApp(builder) {
9236
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9220
9237
  const clientEnvironment = builder.environments.client;
9221
9238
  const defaultHtmlPath = path7.resolve(
9222
9239
  builder.config.root,
@@ -9242,7 +9259,7 @@ function cloudflare2(pluginConfig = {}) {
9242
9259
  )
9243
9260
  );
9244
9261
  }
9245
- }
9262
+ })
9246
9263
  }
9247
9264
  };
9248
9265
  },
@@ -9303,7 +9320,7 @@ function cloudflare2(pluginConfig = {}) {
9303
9320
  return;
9304
9321
  }
9305
9322
  config.no_bundle = true;
9306
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9323
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9307
9324
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9308
9325
  config.unsafe = void 0;
9309
9326
  }
@@ -9350,11 +9367,7 @@ function cloudflare2(pluginConfig = {}) {
9350
9367
  },
9351
9368
  { alwaysCallNext: false }
9352
9369
  );
9353
- handleWebSocket(
9354
- viteDevServer.httpServer,
9355
- entryWorker.fetch,
9356
- viteDevServer.config.logger
9357
- );
9370
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9358
9371
  return () => {
9359
9372
  viteDevServer.middlewares.use((req, res, next) => {
9360
9373
  middleware(req, res, next);
@@ -9376,16 +9389,10 @@ function cloudflare2(pluginConfig = {}) {
9376
9389
  },
9377
9390
  { alwaysCallNext: false }
9378
9391
  );
9379
- handleWebSocket(
9380
- vitePreviewServer.httpServer,
9381
- miniflare2.dispatchFetch,
9382
- vitePreviewServer.config.logger
9383
- );
9384
- return () => {
9385
- vitePreviewServer.middlewares.use((req, res, next) => {
9386
- middleware(req, res, next);
9387
- });
9388
- };
9392
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9393
+ vitePreviewServer.middlewares.use((req, res, next) => {
9394
+ middleware(req, res, next);
9395
+ });
9389
9396
  }
9390
9397
  },
9391
9398
  // Plugin to support `CompiledWasm` modules