@cloudflare/vite-plugin 0.0.0-94729a691 → 0.0.0-9609b9fd8

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",
@@ -1370,6 +1372,7 @@ import {
1370
1372
  LogLevel,
1371
1373
  Response as MiniflareResponse
1372
1374
  } from "miniflare";
1375
+ import { globSync } from "tinyglobby";
1373
1376
  import "vite";
1374
1377
  import {
1375
1378
  unstable_getMiniflareWorkerOptions,
@@ -1551,7 +1554,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1551
1554
  }
1552
1555
  }
1553
1556
  ];
1554
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1557
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1555
1558
  ([environmentName, workerConfig]) => {
1556
1559
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1557
1560
  {
@@ -1560,51 +1563,58 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1560
1563
  },
1561
1564
  resolvedPluginConfig.cloudflareEnv
1562
1565
  );
1566
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1563
1567
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1564
1568
  return {
1565
- ...workerOptions,
1566
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1567
- name: workerConfig.name,
1568
- modulesRoot: miniflareModulesRoot,
1569
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1570
- bindings: {
1571
- ...workerOptions.bindings,
1572
- __VITE_ROOT__: resolvedViteConfig.root,
1573
- __VITE_ENTRY_PATH__: workerConfig.main
1574
- },
1575
- serviceBindings: {
1576
- ...workerOptions.serviceBindings,
1577
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1578
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1579
- } : {},
1580
- __VITE_INVOKE_MODULE__: async (request) => {
1581
- const payload = await request.json();
1582
- const invokePayloadData = payload.data;
1583
- assert4(
1584
- invokePayloadData.name === "fetchModule",
1585
- `Invalid invoke event: ${invokePayloadData.name}`
1586
- );
1587
- const [moduleId] = invokePayloadData.data;
1588
- const moduleRE = new RegExp(MODULE_PATTERN);
1589
- const shouldExternalize = (
1590
- // Worker modules (CompiledWasm, Text, Data)
1591
- moduleRE.test(moduleId)
1592
- );
1593
- if (shouldExternalize) {
1594
- const result2 = {
1595
- externalize: moduleId,
1596
- type: "module"
1597
- };
1598
- 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);
1599
1608
  }
1600
- const devEnvironment = viteDevServer.environments[environmentName];
1601
- const result = await devEnvironment.hot.handleInvoke(payload);
1602
- return MiniflareResponse.json(result);
1603
1609
  }
1604
1610
  }
1605
1611
  };
1606
1612
  }
1607
1613
  ) : [];
1614
+ const userWorkers = workersFromConfig.map((options) => options.worker);
1615
+ const externalWorkers = workersFromConfig.flatMap(
1616
+ (options) => options.externalWorkers
1617
+ );
1608
1618
  const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1609
1619
  const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1610
1620
  const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
@@ -1624,6 +1634,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1624
1634
  ),
1625
1635
  workers: [
1626
1636
  ...assetWorkers,
1637
+ ...externalWorkers,
1627
1638
  ...userWorkers.map((workerOptions) => {
1628
1639
  const wrappers = [
1629
1640
  `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
@@ -1713,22 +1724,44 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1713
1724
  }
1714
1725
  };
1715
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
+ }
1716
1747
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1717
1748
  const resolvedViteConfig = vitePreviewServer.config;
1718
1749
  const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1719
1750
  const workerConfigs = configPaths.map(
1720
1751
  (configPath) => unstable_readConfig({ config: configPath })
1721
1752
  );
1722
- const workers = workerConfigs.map((config) => {
1753
+ const workers = workerConfigs.flatMap((config) => {
1723
1754
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1724
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1725
- return {
1726
- ...workerOptions,
1727
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1728
- name: config.name,
1729
- modules: true,
1730
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1731
- };
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
+ ];
1732
1765
  });
1733
1766
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
1734
1767
  return {
@@ -7370,7 +7403,7 @@ var isAbsolute = function(p) {
7370
7403
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7371
7404
  import assert5 from "node:assert";
7372
7405
  import process$1 from "node:process";
7373
- import path4, { dirname as dirname3 } from "node:path";
7406
+ import path4, { dirname as dirname4 } from "node:path";
7374
7407
  import v8 from "node:v8";
7375
7408
  import { format as format2, inspect } from "node:util";
7376
7409
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7502,14 +7535,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7502
7535
  * @param {boolean} [isImport=false]
7503
7536
  * @param {string} [base]
7504
7537
  */
7505
- (packagePath, key, target, isImport = false, base = void 0) => {
7506
- 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("./");
7507
7540
  if (key === ".") {
7508
7541
  assert5(isImport === false);
7509
- 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 "./"' : ""}`;
7510
7543
  }
7511
7544
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7512
- target
7545
+ target2
7513
7546
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7514
7547
  },
7515
7548
  Error
@@ -7905,14 +7938,14 @@ var patternRegEx = /\*/g;
7905
7938
  var encodedSeparatorRegEx = /%2f|%5c/i;
7906
7939
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7907
7940
  var doubleSlashRegEx = /[/\\]{2}/;
7908
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7941
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7909
7942
  if (process$1.noDeprecation) {
7910
7943
  return;
7911
7944
  }
7912
7945
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7913
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7946
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7914
7947
  process$1.emitWarning(
7915
- `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)}` : ""}.`,
7916
7949
  "DeprecationWarning",
7917
7950
  "DEP0166"
7918
7951
  );
@@ -8070,47 +8103,47 @@ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8070
8103
  base && fileURLToPath$1(base)
8071
8104
  );
8072
8105
  }
8073
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8074
- 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}`;
8075
8108
  return new ERR_INVALID_PACKAGE_TARGET(
8076
8109
  fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8077
8110
  subpath,
8078
- target,
8111
+ target2,
8079
8112
  internal,
8080
8113
  base && fileURLToPath$1(base)
8081
8114
  );
8082
8115
  }
8083
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8084
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8085
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8086
- if (!target.startsWith("./")) {
8087
- 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("/")) {
8088
8121
  let isURL = false;
8089
8122
  try {
8090
- new URL$1(target);
8123
+ new URL$1(target2);
8091
8124
  isURL = true;
8092
8125
  } catch {
8093
8126
  }
8094
8127
  if (!isURL) {
8095
8128
  const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8096
8129
  patternRegEx,
8097
- target,
8130
+ target2,
8098
8131
  () => subpath
8099
- ) : target + subpath;
8132
+ ) : target2 + subpath;
8100
8133
  return packageResolve(exportTarget, packageJsonUrl, conditions);
8101
8134
  }
8102
8135
  }
8103
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8136
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8104
8137
  }
8105
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8106
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8138
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
8139
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
8107
8140
  if (!isPathMap) {
8108
8141
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8109
8142
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8110
8143
  patternRegEx,
8111
- target,
8144
+ target2,
8112
8145
  () => subpath
8113
- ) : target;
8146
+ ) : target2;
8114
8147
  emitInvalidSegmentDeprecation(
8115
8148
  resolvedTarget,
8116
8149
  request,
@@ -8122,14 +8155,14 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8122
8155
  );
8123
8156
  }
8124
8157
  } else {
8125
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8158
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8126
8159
  }
8127
8160
  }
8128
- const resolved = new URL$1(target, packageJsonUrl);
8161
+ const resolved = new URL$1(target2, packageJsonUrl);
8129
8162
  const resolvedPath = resolved.pathname;
8130
8163
  const packagePath = new URL$1(".", packageJsonUrl).pathname;
8131
8164
  if (!resolvedPath.startsWith(packagePath))
8132
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8165
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8133
8166
  if (subpath === "") return resolved;
8134
8167
  if (invalidSegmentRegEx.exec(subpath) !== null) {
8135
8168
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
@@ -8137,9 +8170,9 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8137
8170
  if (!isPathMap) {
8138
8171
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8139
8172
  patternRegEx,
8140
- target,
8173
+ target2,
8141
8174
  () => subpath
8142
- ) : target;
8175
+ ) : target2;
8143
8176
  emitInvalidSegmentDeprecation(
8144
8177
  resolvedTarget,
8145
8178
  request,
@@ -8170,10 +8203,10 @@ function isArrayIndex(key) {
8170
8203
  if (`${keyNumber}` !== key) return false;
8171
8204
  return keyNumber >= 0 && keyNumber < 4294967295;
8172
8205
  }
8173
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8174
- if (typeof target === "string") {
8206
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8207
+ if (typeof target2 === "string") {
8175
8208
  return resolvePackageTargetString(
8176
- target,
8209
+ target2,
8177
8210
  subpath,
8178
8211
  packageSubpath,
8179
8212
  packageJsonUrl,
@@ -8184,8 +8217,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8184
8217
  conditions
8185
8218
  );
8186
8219
  }
8187
- if (Array.isArray(target)) {
8188
- const targetList = target;
8220
+ if (Array.isArray(target2)) {
8221
+ const targetList = target2;
8189
8222
  if (targetList.length === 0) return null;
8190
8223
  let lastException;
8191
8224
  let i = -1;
@@ -8225,8 +8258,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8225
8258
  }
8226
8259
  throw lastException;
8227
8260
  }
8228
- if (typeof target === "object" && target !== null) {
8229
- const keys = Object.getOwnPropertyNames(target);
8261
+ if (typeof target2 === "object" && target2 !== null) {
8262
+ const keys = Object.getOwnPropertyNames(target2);
8230
8263
  let i = -1;
8231
8264
  while (++i < keys.length) {
8232
8265
  const key = keys[i];
@@ -8244,7 +8277,7 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8244
8277
  if (key === "default" || conditions && conditions.has(key)) {
8245
8278
  const conditionalTarget = (
8246
8279
  /** @type {unknown} */
8247
- target[key]
8280
+ target2[key]
8248
8281
  );
8249
8282
  const resolveResult = resolvePackageTarget(
8250
8283
  packageJsonUrl,
@@ -8263,12 +8296,12 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8263
8296
  }
8264
8297
  return null;
8265
8298
  }
8266
- if (target === null) {
8299
+ if (target2 === null) {
8267
8300
  return null;
8268
8301
  }
8269
8302
  throw invalidPackageTarget(
8270
8303
  packageSubpath,
8271
- target,
8304
+ target2,
8272
8305
  packageJsonUrl,
8273
8306
  internal,
8274
8307
  base
@@ -8315,10 +8348,10 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8315
8348
  exports = { ".": exports };
8316
8349
  }
8317
8350
  if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8318
- const target = exports[packageSubpath];
8351
+ const target2 = exports[packageSubpath];
8319
8352
  const resolveResult = resolvePackageTarget(
8320
8353
  packageJsonUrl,
8321
- target,
8354
+ target2,
8322
8355
  "",
8323
8356
  packageSubpath,
8324
8357
  base,
@@ -8358,13 +8391,13 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8358
8391
  }
8359
8392
  }
8360
8393
  if (bestMatch) {
8361
- const target = (
8394
+ const target2 = (
8362
8395
  /** @type {unknown} */
8363
8396
  exports[bestMatch]
8364
8397
  );
8365
8398
  const resolveResult = resolvePackageTarget(
8366
8399
  packageJsonUrl,
8367
- target,
8400
+ target2,
8368
8401
  bestMatchSubpath,
8369
8402
  bestMatch,
8370
8403
  base,
@@ -8439,10 +8472,10 @@ function packageImportsResolve(name2, base, conditions) {
8439
8472
  }
8440
8473
  }
8441
8474
  if (bestMatch) {
8442
- const target = imports[bestMatch];
8475
+ const target2 = imports[bestMatch];
8443
8476
  const resolveResult = resolvePackageTarget(
8444
8477
  packageJsonUrl,
8445
- target,
8478
+ target2,
8446
8479
  bestMatchSubpath,
8447
8480
  bestMatch,
8448
8481
  base,
@@ -8732,11 +8765,6 @@ function isNodeCompat(workerConfig) {
8732
8765
  if (nodeCompatMode === "v2") {
8733
8766
  return true;
8734
8767
  }
8735
- if (nodeCompatMode === "legacy") {
8736
- throw new Error(
8737
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8738
- );
8739
- }
8740
8768
  if (nodeCompatMode === "v1") {
8741
8769
  throw new Error(
8742
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`
@@ -8843,7 +8871,6 @@ var nonApplicableWorkerConfigs = {
8843
8871
  "build",
8844
8872
  "find_additional_modules",
8845
8873
  "no_bundle",
8846
- "node_compat",
8847
8874
  "preserve_file_names",
8848
8875
  "site",
8849
8876
  "tsconfig",
@@ -8860,7 +8887,6 @@ var nullableNonApplicable = [
8860
8887
  "find_additional_modules",
8861
8888
  "minify",
8862
8889
  "no_bundle",
8863
- "node_compat",
8864
8890
  "preserve_file_names",
8865
8891
  "site",
8866
8892
  "tsconfig",
@@ -9011,6 +9037,17 @@ function getWorkerConfig(configPath, env2, opts) {
9011
9037
  };
9012
9038
  }
9013
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
+ }
9014
9051
  return {
9015
9052
  type: "worker",
9016
9053
  raw,
@@ -9111,8 +9148,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9111
9148
  }
9112
9149
 
9113
9150
  // src/websockets.ts
9151
+ import { coupleWebSocket } from "miniflare";
9114
9152
  import { WebSocketServer } from "ws";
9115
- function handleWebSocket(httpServer, fetcher, logger) {
9153
+ function handleWebSocket(httpServer, fetcher) {
9116
9154
  const nodeWebSocket = new WebSocketServer({ noServer: true });
9117
9155
  httpServer.on(
9118
9156
  "upgrade",
@@ -9136,34 +9174,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9136
9174
  socket,
9137
9175
  head,
9138
9176
  async (clientWebSocket) => {
9139
- workerWebSocket.accept();
9140
- workerWebSocket.addEventListener("message", (event) => {
9141
- clientWebSocket.send(event.data);
9142
- });
9143
- workerWebSocket.addEventListener("error", (event) => {
9144
- logger.error(
9145
- `WebSocket error:
9146
- ${event.error?.stack || event.error?.message}`,
9147
- { error: event.error }
9148
- );
9149
- });
9150
- workerWebSocket.addEventListener("close", () => {
9151
- clientWebSocket.close();
9152
- });
9153
- clientWebSocket.on("message", (data2, isBinary) => {
9154
- workerWebSocket.send(
9155
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9156
- );
9157
- });
9158
- clientWebSocket.on("error", (error) => {
9159
- logger.error(`WebSocket error:
9160
- ${error.stack || error.message}`, {
9161
- error
9162
- });
9163
- });
9164
- clientWebSocket.on("close", () => {
9165
- workerWebSocket.close();
9166
- });
9177
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9167
9178
  nodeWebSocket.emit("connection", clientWebSocket, request);
9168
9179
  }
9169
9180
  );
@@ -9309,7 +9320,7 @@ function cloudflare2(pluginConfig = {}) {
9309
9320
  return;
9310
9321
  }
9311
9322
  config.no_bundle = true;
9312
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9323
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9313
9324
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9314
9325
  config.unsafe = void 0;
9315
9326
  }
@@ -9356,11 +9367,7 @@ function cloudflare2(pluginConfig = {}) {
9356
9367
  },
9357
9368
  { alwaysCallNext: false }
9358
9369
  );
9359
- handleWebSocket(
9360
- viteDevServer.httpServer,
9361
- entryWorker.fetch,
9362
- viteDevServer.config.logger
9363
- );
9370
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9364
9371
  return () => {
9365
9372
  viteDevServer.middlewares.use((req, res, next) => {
9366
9373
  middleware(req, res, next);
@@ -9382,16 +9389,10 @@ function cloudflare2(pluginConfig = {}) {
9382
9389
  },
9383
9390
  { alwaysCallNext: false }
9384
9391
  );
9385
- handleWebSocket(
9386
- vitePreviewServer.httpServer,
9387
- miniflare2.dispatchFetch,
9388
- vitePreviewServer.config.logger
9389
- );
9390
- return () => {
9391
- vitePreviewServer.middlewares.use((req, res, next) => {
9392
- middleware(req, res, next);
9393
- });
9394
- };
9392
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9393
+ vitePreviewServer.middlewares.use((req, res, next) => {
9394
+ middleware(req, res, next);
9395
+ });
9395
9396
  }
9396
9397
  },
9397
9398
  // Plugin to support `CompiledWasm` modules
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vite-plugin",
3
- "version": "0.0.0-94729a691",
3
+ "version": "0.0.0-9609b9fd8",
4
4
  "description": "Cloudflare plugin for Vite",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -35,12 +35,14 @@
35
35
  "dependencies": {
36
36
  "@cloudflare/unenv-preset": "1.1.1",
37
37
  "@hattip/adapter-node": "^0.0.49",
38
+ "tinyglobby": "^0.2.12",
38
39
  "unenv": "2.0.0-rc.1",
39
40
  "ws": "8.18.0",
40
- "miniflare": "0.0.0-94729a691"
41
+ "miniflare": "0.0.0-9609b9fd8",
42
+ "wrangler": "0.0.0-9609b9fd8"
41
43
  },
42
44
  "devDependencies": {
43
- "@cloudflare/workers-types": "^4.20250214.0",
45
+ "@cloudflare/workers-types": "^4.20250317.0",
44
46
  "@types/node": "^22.10.1",
45
47
  "@types/ws": "^8.5.13",
46
48
  "magic-string": "^0.30.12",
@@ -50,14 +52,13 @@
50
52
  "undici": "^5.28.5",
51
53
  "vite": "^6.1.0",
52
54
  "vitest": "~3.0.5",
53
- "@cloudflare/mock-npm-registry": "0.0.0",
54
- "@cloudflare/workers-shared": "0.0.0-94729a691",
55
+ "@cloudflare/workers-shared": "0.0.0-9609b9fd8",
55
56
  "@cloudflare/workers-tsconfig": "0.0.0",
56
- "wrangler": "0.0.0-94729a691"
57
+ "@cloudflare/mock-npm-registry": "0.0.0"
57
58
  },
58
59
  "peerDependencies": {
59
60
  "vite": "^6.1.0",
60
- "wrangler": "^3.101.0"
61
+ "wrangler": "^3.101.0 || ^4.0.0"
61
62
  },
62
63
  "publishConfig": {
63
64
  "access": "public"
@@ -70,7 +71,7 @@
70
71
  "check:type": "tsc --build",
71
72
  "dev": "tsup --watch",
72
73
  "test": "vitest run",
73
- "test:ci": "pnpm test && pnpm test:e2e",
74
+ "test:ci": "pnpm test",
74
75
  "test:e2e": "vitest run -c e2e/vitest.config.ts",
75
76
  "test:watch": "vitest"
76
77
  }