@cloudflare/vite-plugin 0.0.0-0322d085f → 0.0.0-0435d8ef5

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
@@ -1,6 +1,7 @@
1
1
  // src/index.ts
2
2
  import assert9 from "node:assert";
3
3
  import * as fs5 from "node:fs";
4
+ import { builtinModules as builtinModules2 } from "node:module";
4
5
  import * as path7 from "node:path";
5
6
  import { createMiddleware } from "@hattip/adapter-node";
6
7
 
@@ -1088,13 +1089,9 @@ var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1088
1089
  var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1089
1090
 
1090
1091
  // src/utils.ts
1091
- import { builtinModules } from "node:module";
1092
1092
  import * as path from "node:path";
1093
1093
  import { Request as MiniflareRequest } from "miniflare";
1094
1094
  import "vite";
1095
- var nodeBuiltInModules = new Set(
1096
- builtinModules.concat(builtinModules.map((m) => `node:${m}`))
1097
- );
1098
1095
  function getOutputDirectory(userConfig, environmentName) {
1099
1096
  const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
1100
1097
  return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
@@ -1203,6 +1200,7 @@ var cloudflareBuiltInModules = [
1203
1200
  "cloudflare:workflows"
1204
1201
  ];
1205
1202
  var defaultConditions = ["workerd", "module", "browser"];
1203
+ var target = "es2022";
1206
1204
  function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1207
1205
  return {
1208
1206
  resolve: {
@@ -1212,9 +1210,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1212
1210
  // We want to use `workerd` package exports if available (e.g. for postgres).
1213
1211
  conditions: [...defaultConditions, "development|production"],
1214
1212
  // The Cloudflare ones are proper builtins in the environment
1215
- builtins: [...cloudflareBuiltInModules],
1216
- // The Node.js ones are no proper builtins in the environment since we also polyfill them using unenv
1217
- external: [...nodeBuiltInModules]
1213
+ builtins: [...cloudflareBuiltInModules]
1218
1214
  },
1219
1215
  dev: {
1220
1216
  createEnvironment(name2, config) {
@@ -1225,7 +1221,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1225
1221
  createEnvironment(name2, config) {
1226
1222
  return new vite2.BuildEnvironment(name2, config);
1227
1223
  },
1228
- target: "es2022",
1224
+ target,
1229
1225
  // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1230
1226
  emitAssets: true,
1231
1227
  outDir: getOutputDirectory(userConfig, environmentName),
@@ -1243,12 +1239,10 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1243
1239
  // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1244
1240
  noDiscovery: false,
1245
1241
  entries: workerConfig.main,
1246
- exclude: [
1247
- // we have to exclude all node modules to work in dev-mode not just the unenv externals...
1248
- ...nodeBuiltInModules
1249
- ],
1242
+ exclude: [...cloudflareBuiltInModules],
1250
1243
  esbuildOptions: {
1251
1244
  platform: "neutral",
1245
+ target,
1252
1246
  conditions: [...defaultConditions, "development"],
1253
1247
  resolveExtensions: [
1254
1248
  ".mjs",
@@ -1372,7 +1366,13 @@ import * as fs2 from "node:fs";
1372
1366
  import * as fsp from "node:fs/promises";
1373
1367
  import * as path3 from "node:path";
1374
1368
  import { fileURLToPath } from "node:url";
1375
- 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";
1376
1376
  import "vite";
1377
1377
  import {
1378
1378
  unstable_getMiniflareWorkerOptions,
@@ -1406,11 +1406,10 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
1406
1406
  );
1407
1407
  for (const worker of workers) {
1408
1408
  for (const value of Object.values(worker.serviceBindings ?? {})) {
1409
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1410
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1411
- value.name
1412
- );
1413
- 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));
1414
1413
  entrypointNames.add(value.entrypoint);
1415
1414
  }
1416
1415
  }
@@ -1555,7 +1554,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1555
1554
  }
1556
1555
  }
1557
1556
  ];
1558
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1557
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1559
1558
  ([environmentName, workerConfig]) => {
1560
1559
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1561
1560
  {
@@ -1564,52 +1563,58 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1564
1563
  },
1565
1564
  resolvedPluginConfig.cloudflareEnv
1566
1565
  );
1566
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1567
1567
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1568
1568
  return {
1569
- ...workerOptions,
1570
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1571
- name: workerConfig.name,
1572
- modulesRoot: miniflareModulesRoot,
1573
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1574
- bindings: {
1575
- ...workerOptions.bindings,
1576
- __VITE_ROOT__: resolvedViteConfig.root,
1577
- __VITE_ENTRY_PATH__: workerConfig.main
1578
- },
1579
- serviceBindings: {
1580
- ...workerOptions.serviceBindings,
1581
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1582
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1583
- } : {},
1584
- __VITE_INVOKE_MODULE__: async (request) => {
1585
- const payload = await request.json();
1586
- const invokePayloadData = payload.data;
1587
- assert4(
1588
- invokePayloadData.name === "fetchModule",
1589
- `Invalid invoke event: ${invokePayloadData.name}`
1590
- );
1591
- const [moduleId] = invokePayloadData.data;
1592
- const moduleRE = new RegExp(MODULE_PATTERN);
1593
- const shouldExternalize = (
1594
- // Worker modules (CompiledWasm, Text, Data)
1595
- moduleRE.test(moduleId) || // Node.js builtin node modules (they will be resolved to unenv aliases)
1596
- nodeBuiltInModules.has(moduleId)
1597
- );
1598
- if (shouldExternalize) {
1599
- const result2 = {
1600
- externalize: moduleId,
1601
- type: "module"
1602
- };
1603
- 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);
1604
1608
  }
1605
- const devEnvironment = viteDevServer.environments[environmentName];
1606
- const result = await devEnvironment.hot.handleInvoke(payload);
1607
- return MiniflareResponse.json(result);
1608
1609
  }
1609
1610
  }
1610
1611
  };
1611
1612
  }
1612
1613
  ) : [];
1614
+ const userWorkers = workersFromConfig.map((options) => options.worker);
1615
+ const externalWorkers = workersFromConfig.flatMap(
1616
+ (options) => options.externalWorkers
1617
+ );
1613
1618
  const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1614
1619
  const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1615
1620
  const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
@@ -1629,6 +1634,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1629
1634
  ),
1630
1635
  workers: [
1631
1636
  ...assetWorkers,
1637
+ ...externalWorkers,
1632
1638
  ...userWorkers.map((workerOptions) => {
1633
1639
  const wrappers = [
1634
1640
  `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
@@ -1661,7 +1667,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1661
1667
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1662
1668
  assert4(
1663
1669
  workflowEntrypointClassNames,
1664
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1670
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1665
1671
  );
1666
1672
  for (const className of [...workflowEntrypointClassNames].sort()) {
1667
1673
  wrappers.push(
@@ -1697,17 +1703,19 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1697
1703
  );
1698
1704
  const moduleRE = new RegExp(MODULE_PATTERN);
1699
1705
  const match = moduleRE.exec(rawSpecifier);
1700
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1706
+ assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1701
1707
  const [full, moduleType, modulePath] = match;
1702
1708
  assert4(
1703
1709
  modulePath,
1704
- `Unexpected error: module path not found in reference ${full}.`
1710
+ `Unexpected error: module path not found in reference: ${full}.`
1705
1711
  );
1706
1712
  let source;
1707
1713
  try {
1708
1714
  source = fs2.readFileSync(modulePath);
1709
1715
  } catch (error) {
1710
- 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
+ );
1711
1719
  }
1712
1720
  return MiniflareResponse.json({
1713
1721
  // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
@@ -1716,22 +1724,44 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1716
1724
  }
1717
1725
  };
1718
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
+ }
1719
1747
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1720
1748
  const resolvedViteConfig = vitePreviewServer.config;
1721
1749
  const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1722
1750
  const workerConfigs = configPaths.map(
1723
1751
  (configPath) => unstable_readConfig({ config: configPath })
1724
1752
  );
1725
- const workers = workerConfigs.map((config) => {
1753
+ const workers = workerConfigs.flatMap((config) => {
1726
1754
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1727
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1728
- return {
1729
- ...workerOptions,
1730
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1731
- name: config.name,
1732
- modules: true,
1733
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1734
- };
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
+ ];
1735
1765
  });
1736
1766
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
1737
1767
  return {
@@ -7313,7 +7343,7 @@ Parser.acorn = {
7313
7343
  };
7314
7344
 
7315
7345
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7316
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7346
+ import { builtinModules, createRequire } from "node:module";
7317
7347
  import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
7318
7348
 
7319
7349
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
@@ -7373,10 +7403,10 @@ var isAbsolute = function(p) {
7373
7403
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7374
7404
  import assert5 from "node:assert";
7375
7405
  import process$1 from "node:process";
7376
- import path4, { dirname as dirname3 } from "node:path";
7406
+ import path4, { dirname as dirname4 } from "node:path";
7377
7407
  import v8 from "node:v8";
7378
7408
  import { format as format2, inspect } from "node:util";
7379
- var BUILTIN_MODULES = new Set(builtinModules2);
7409
+ var BUILTIN_MODULES = new Set(builtinModules);
7380
7410
  function normalizeSlash(path8) {
7381
7411
  return path8.replace(/\\/g, "/");
7382
7412
  }
@@ -7505,14 +7535,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7505
7535
  * @param {boolean} [isImport=false]
7506
7536
  * @param {string} [base]
7507
7537
  */
7508
- (packagePath, key, target, isImport = false, base = void 0) => {
7509
- 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("./");
7510
7540
  if (key === ".") {
7511
7541
  assert5(isImport === false);
7512
- 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 "./"' : ""}`;
7513
7543
  }
7514
7544
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7515
- target
7545
+ target2
7516
7546
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7517
7547
  },
7518
7548
  Error
@@ -7908,14 +7938,14 @@ var patternRegEx = /\*/g;
7908
7938
  var encodedSeparatorRegEx = /%2f|%5c/i;
7909
7939
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7910
7940
  var doubleSlashRegEx = /[/\\]{2}/;
7911
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7941
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7912
7942
  if (process$1.noDeprecation) {
7913
7943
  return;
7914
7944
  }
7915
7945
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7916
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7946
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7917
7947
  process$1.emitWarning(
7918
- `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)}` : ""}.`,
7919
7949
  "DeprecationWarning",
7920
7950
  "DEP0166"
7921
7951
  );
@@ -8073,47 +8103,47 @@ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8073
8103
  base && fileURLToPath$1(base)
8074
8104
  );
8075
8105
  }
8076
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8077
- 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}`;
8078
8108
  return new ERR_INVALID_PACKAGE_TARGET(
8079
8109
  fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8080
8110
  subpath,
8081
- target,
8111
+ target2,
8082
8112
  internal,
8083
8113
  base && fileURLToPath$1(base)
8084
8114
  );
8085
8115
  }
8086
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8087
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8088
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8089
- if (!target.startsWith("./")) {
8090
- 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("/")) {
8091
8121
  let isURL = false;
8092
8122
  try {
8093
- new URL$1(target);
8123
+ new URL$1(target2);
8094
8124
  isURL = true;
8095
8125
  } catch {
8096
8126
  }
8097
8127
  if (!isURL) {
8098
8128
  const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8099
8129
  patternRegEx,
8100
- target,
8130
+ target2,
8101
8131
  () => subpath
8102
- ) : target + subpath;
8132
+ ) : target2 + subpath;
8103
8133
  return packageResolve(exportTarget, packageJsonUrl, conditions);
8104
8134
  }
8105
8135
  }
8106
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8136
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8107
8137
  }
8108
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8109
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8138
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
8139
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
8110
8140
  if (!isPathMap) {
8111
8141
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8112
8142
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8113
8143
  patternRegEx,
8114
- target,
8144
+ target2,
8115
8145
  () => subpath
8116
- ) : target;
8146
+ ) : target2;
8117
8147
  emitInvalidSegmentDeprecation(
8118
8148
  resolvedTarget,
8119
8149
  request,
@@ -8125,14 +8155,14 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8125
8155
  );
8126
8156
  }
8127
8157
  } else {
8128
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8158
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8129
8159
  }
8130
8160
  }
8131
- const resolved = new URL$1(target, packageJsonUrl);
8161
+ const resolved = new URL$1(target2, packageJsonUrl);
8132
8162
  const resolvedPath = resolved.pathname;
8133
8163
  const packagePath = new URL$1(".", packageJsonUrl).pathname;
8134
8164
  if (!resolvedPath.startsWith(packagePath))
8135
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8165
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8136
8166
  if (subpath === "") return resolved;
8137
8167
  if (invalidSegmentRegEx.exec(subpath) !== null) {
8138
8168
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
@@ -8140,9 +8170,9 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8140
8170
  if (!isPathMap) {
8141
8171
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8142
8172
  patternRegEx,
8143
- target,
8173
+ target2,
8144
8174
  () => subpath
8145
- ) : target;
8175
+ ) : target2;
8146
8176
  emitInvalidSegmentDeprecation(
8147
8177
  resolvedTarget,
8148
8178
  request,
@@ -8173,10 +8203,10 @@ function isArrayIndex(key) {
8173
8203
  if (`${keyNumber}` !== key) return false;
8174
8204
  return keyNumber >= 0 && keyNumber < 4294967295;
8175
8205
  }
8176
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8177
- if (typeof target === "string") {
8206
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8207
+ if (typeof target2 === "string") {
8178
8208
  return resolvePackageTargetString(
8179
- target,
8209
+ target2,
8180
8210
  subpath,
8181
8211
  packageSubpath,
8182
8212
  packageJsonUrl,
@@ -8187,8 +8217,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8187
8217
  conditions
8188
8218
  );
8189
8219
  }
8190
- if (Array.isArray(target)) {
8191
- const targetList = target;
8220
+ if (Array.isArray(target2)) {
8221
+ const targetList = target2;
8192
8222
  if (targetList.length === 0) return null;
8193
8223
  let lastException;
8194
8224
  let i = -1;
@@ -8228,8 +8258,8 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8228
8258
  }
8229
8259
  throw lastException;
8230
8260
  }
8231
- if (typeof target === "object" && target !== null) {
8232
- const keys = Object.getOwnPropertyNames(target);
8261
+ if (typeof target2 === "object" && target2 !== null) {
8262
+ const keys = Object.getOwnPropertyNames(target2);
8233
8263
  let i = -1;
8234
8264
  while (++i < keys.length) {
8235
8265
  const key = keys[i];
@@ -8247,7 +8277,7 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8247
8277
  if (key === "default" || conditions && conditions.has(key)) {
8248
8278
  const conditionalTarget = (
8249
8279
  /** @type {unknown} */
8250
- target[key]
8280
+ target2[key]
8251
8281
  );
8252
8282
  const resolveResult = resolvePackageTarget(
8253
8283
  packageJsonUrl,
@@ -8266,12 +8296,12 @@ function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, b
8266
8296
  }
8267
8297
  return null;
8268
8298
  }
8269
- if (target === null) {
8299
+ if (target2 === null) {
8270
8300
  return null;
8271
8301
  }
8272
8302
  throw invalidPackageTarget(
8273
8303
  packageSubpath,
8274
- target,
8304
+ target2,
8275
8305
  packageJsonUrl,
8276
8306
  internal,
8277
8307
  base
@@ -8318,10 +8348,10 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8318
8348
  exports = { ".": exports };
8319
8349
  }
8320
8350
  if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8321
- const target = exports[packageSubpath];
8351
+ const target2 = exports[packageSubpath];
8322
8352
  const resolveResult = resolvePackageTarget(
8323
8353
  packageJsonUrl,
8324
- target,
8354
+ target2,
8325
8355
  "",
8326
8356
  packageSubpath,
8327
8357
  base,
@@ -8361,13 +8391,13 @@ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, ba
8361
8391
  }
8362
8392
  }
8363
8393
  if (bestMatch) {
8364
- const target = (
8394
+ const target2 = (
8365
8395
  /** @type {unknown} */
8366
8396
  exports[bestMatch]
8367
8397
  );
8368
8398
  const resolveResult = resolvePackageTarget(
8369
8399
  packageJsonUrl,
8370
- target,
8400
+ target2,
8371
8401
  bestMatchSubpath,
8372
8402
  bestMatch,
8373
8403
  base,
@@ -8442,10 +8472,10 @@ function packageImportsResolve(name2, base, conditions) {
8442
8472
  }
8443
8473
  }
8444
8474
  if (bestMatch) {
8445
- const target = imports[bestMatch];
8475
+ const target2 = imports[bestMatch];
8446
8476
  const resolveResult = resolvePackageTarget(
8447
8477
  packageJsonUrl,
8448
- target,
8478
+ target2,
8449
8479
  bestMatchSubpath,
8450
8480
  bestMatch,
8451
8481
  base,
@@ -8490,7 +8520,7 @@ function parsePackageName(specifier, base) {
8490
8520
  return { packageName, packageSubpath, isScoped };
8491
8521
  }
8492
8522
  function packageResolve(specifier, base, conditions) {
8493
- if (builtinModules2.includes(specifier)) {
8523
+ if (builtinModules.includes(specifier)) {
8494
8524
  return new URL$1("node:" + specifier);
8495
8525
  }
8496
8526
  const { packageName, packageSubpath, isScoped } = parsePackageName(
@@ -8577,7 +8607,7 @@ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8577
8607
  try {
8578
8608
  resolved = new URL$1(specifier);
8579
8609
  } catch (error_) {
8580
- if (isRemote && !builtinModules2.includes(specifier)) {
8610
+ if (isRemote && !builtinModules.includes(specifier)) {
8581
8611
  const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8582
8612
  error.cause = error_;
8583
8613
  throw error;
@@ -8722,7 +8752,8 @@ var { env } = defineEnv({
8722
8752
  nodeCompat: true,
8723
8753
  presets: [cloudflare]
8724
8754
  });
8725
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8755
+ var nodeCompatExternals = new Set(env.external);
8756
+ var nodeCompatEntries = getNodeCompatEntries();
8726
8757
  function isNodeCompat(workerConfig) {
8727
8758
  if (workerConfig === void 0) {
8728
8759
  return false;
@@ -8734,11 +8765,6 @@ function isNodeCompat(workerConfig) {
8734
8765
  if (nodeCompatMode === "v2") {
8735
8766
  return true;
8736
8767
  }
8737
- if (nodeCompatMode === "legacy") {
8738
- throw new Error(
8739
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8740
- );
8741
- }
8742
8768
  if (nodeCompatMode === "v1") {
8743
8769
  throw new Error(
8744
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`
@@ -8750,12 +8776,17 @@ function injectGlobalCode(id, code) {
8750
8776
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8751
8777
  if (typeof globalInject === "string") {
8752
8778
  const moduleSpecifier2 = globalInject;
8753
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8779
+ return `import var_${globalName} from "${moduleSpecifier2}";
8754
8780
  globalThis.${globalName} = var_${globalName};
8755
8781
  `;
8756
8782
  }
8757
8783
  const [moduleSpecifier, exportName] = globalInject;
8758
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8784
+ assert6(
8785
+ moduleSpecifier !== void 0,
8786
+ "Expected moduleSpecifier to be defined"
8787
+ );
8788
+ assert6(exportName !== void 0, "Expected exportName to be defined");
8789
+ return `import var_${globalName} from "${moduleSpecifier}";
8759
8790
  globalThis.${globalName} = var_${globalName}.${exportName};
8760
8791
  `;
8761
8792
  }).join("\n");
@@ -8766,37 +8797,36 @@ globalThis.${globalName} = var_${globalName}.${exportName};
8766
8797
  map: modified.generateMap({ hires: "boundary", source: id })
8767
8798
  };
8768
8799
  }
8769
- function getNodeCompatAliases() {
8770
- const aliases = {};
8771
- Object.keys(env.alias).forEach((key) => {
8772
- if (!env.external.includes(key)) {
8773
- aliases[key] = CLOUDFLARE_VIRTUAL_PREFIX + key;
8774
- }
8775
- });
8776
- return aliases;
8777
- }
8778
- function getNodeCompatExternals() {
8779
- return env.external;
8780
- }
8781
- function maybeStripNodeJsVirtualPrefix(source) {
8782
- return source.startsWith(CLOUDFLARE_VIRTUAL_PREFIX) ? source.slice(CLOUDFLARE_VIRTUAL_PREFIX.length) : void 0;
8783
- }
8784
8800
  function resolveNodeJSImport(source) {
8785
8801
  const alias = env.alias[source];
8786
8802
  if (alias) {
8787
- assert6(
8788
- !env.external.includes(alias),
8789
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8790
- );
8791
- source = alias;
8803
+ return {
8804
+ unresolved: alias,
8805
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8806
+ };
8807
+ }
8808
+ if (nodeCompatEntries.has(source)) {
8809
+ return {
8810
+ unresolved: source,
8811
+ resolved: resolvePathSync(source, { url: import.meta.url })
8812
+ };
8792
8813
  }
8793
- const resolved = resolvePathSync(source, {
8794
- url: import.meta.url
8795
- });
8796
- return {
8797
- unresolved: source,
8798
- resolved
8799
- };
8814
+ }
8815
+ function getNodeCompatEntries() {
8816
+ const entries = new Set(Object.values(env.alias));
8817
+ for (const globalInject of Object.values(env.inject)) {
8818
+ if (typeof globalInject === "string") {
8819
+ entries.add(globalInject);
8820
+ } else {
8821
+ assert6(
8822
+ globalInject[0] !== void 0,
8823
+ "Expected first element of globalInject to be defined"
8824
+ );
8825
+ entries.add(globalInject[0]);
8826
+ }
8827
+ }
8828
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8829
+ return entries;
8800
8830
  }
8801
8831
 
8802
8832
  // src/plugin-config.ts
@@ -8841,7 +8871,6 @@ var nonApplicableWorkerConfigs = {
8841
8871
  "build",
8842
8872
  "find_additional_modules",
8843
8873
  "no_bundle",
8844
- "node_compat",
8845
8874
  "preserve_file_names",
8846
8875
  "site",
8847
8876
  "tsconfig",
@@ -8858,7 +8887,6 @@ var nullableNonApplicable = [
8858
8887
  "find_additional_modules",
8859
8888
  "minify",
8860
8889
  "no_bundle",
8861
- "node_compat",
8862
8890
  "preserve_file_names",
8863
8891
  "site",
8864
8892
  "tsconfig",
@@ -9009,6 +9037,17 @@ function getWorkerConfig(configPath, env2, opts) {
9009
9037
  };
9010
9038
  }
9011
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
+ }
9012
9051
  return {
9013
9052
  type: "worker",
9014
9053
  raw,
@@ -9109,9 +9148,10 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9148
  }
9110
9149
 
9111
9150
  // src/websockets.ts
9112
- import ws from "ws";
9113
- function handleWebSocket(httpServer, fetcher, logger) {
9114
- const nodeWebSocket = new ws.Server({ noServer: true });
9151
+ import { coupleWebSocket } from "miniflare";
9152
+ import { WebSocketServer } from "ws";
9153
+ function handleWebSocket(httpServer, fetcher) {
9154
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9155
  httpServer.on(
9116
9156
  "upgrade",
9117
9157
  async (request, socket, head) => {
@@ -9134,34 +9174,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9134
9174
  socket,
9135
9175
  head,
9136
9176
  async (clientWebSocket) => {
9137
- workerWebSocket.accept();
9138
- workerWebSocket.addEventListener("message", (event) => {
9139
- clientWebSocket.send(event.data);
9140
- });
9141
- workerWebSocket.addEventListener("error", (event) => {
9142
- logger.error(
9143
- `WebSocket error:
9144
- ${event.error?.stack || event.error?.message}`,
9145
- { error: event.error }
9146
- );
9147
- });
9148
- workerWebSocket.addEventListener("close", () => {
9149
- clientWebSocket.close();
9150
- });
9151
- clientWebSocket.on("message", (data2, isBinary) => {
9152
- workerWebSocket.send(
9153
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9154
- );
9155
- });
9156
- clientWebSocket.on("error", (error) => {
9157
- logger.error(`WebSocket error:
9158
- ${error.stack || error.message}`, {
9159
- error
9160
- });
9161
- });
9162
- clientWebSocket.on("close", () => {
9163
- workerWebSocket.close();
9164
- });
9177
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9165
9178
  nodeWebSocket.emit("connection", clientWebSocket, request);
9166
9179
  }
9167
9180
  );
@@ -9220,7 +9233,7 @@ function cloudflare2(pluginConfig = {}) {
9220
9233
  }
9221
9234
  } : void 0,
9222
9235
  builder: {
9223
- async buildApp(builder) {
9236
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9224
9237
  const clientEnvironment = builder.environments.client;
9225
9238
  const defaultHtmlPath = path7.resolve(
9226
9239
  builder.config.root,
@@ -9246,7 +9259,7 @@ function cloudflare2(pluginConfig = {}) {
9246
9259
  )
9247
9260
  );
9248
9261
  }
9249
- }
9262
+ })
9250
9263
  }
9251
9264
  };
9252
9265
  },
@@ -9307,7 +9320,7 @@ function cloudflare2(pluginConfig = {}) {
9307
9320
  return;
9308
9321
  }
9309
9322
  config.no_bundle = true;
9310
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9323
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9311
9324
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9312
9325
  config.unsafe = void 0;
9313
9326
  }
@@ -9354,11 +9367,7 @@ function cloudflare2(pluginConfig = {}) {
9354
9367
  },
9355
9368
  { alwaysCallNext: false }
9356
9369
  );
9357
- handleWebSocket(
9358
- viteDevServer.httpServer,
9359
- entryWorker.fetch,
9360
- viteDevServer.config.logger
9361
- );
9370
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9362
9371
  return () => {
9363
9372
  viteDevServer.middlewares.use((req, res, next) => {
9364
9373
  middleware(req, res, next);
@@ -9380,16 +9389,10 @@ function cloudflare2(pluginConfig = {}) {
9380
9389
  },
9381
9390
  { alwaysCallNext: false }
9382
9391
  );
9383
- handleWebSocket(
9384
- vitePreviewServer.httpServer,
9385
- miniflare2.dispatchFetch,
9386
- vitePreviewServer.config.logger
9387
- );
9388
- return () => {
9389
- vitePreviewServer.middlewares.use((req, res, next) => {
9390
- middleware(req, res, next);
9391
- });
9392
- };
9392
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9393
+ vitePreviewServer.middlewares.use((req, res, next) => {
9394
+ middleware(req, res, next);
9395
+ });
9393
9396
  }
9394
9397
  },
9395
9398
  // Plugin to support `CompiledWasm` modules
@@ -9465,49 +9468,61 @@ function cloudflare2(pluginConfig = {}) {
9465
9468
  apply(_config, env2) {
9466
9469
  return !env2.isPreview;
9467
9470
  },
9468
- config() {
9469
- return {
9470
- resolve: {
9471
- alias: getNodeCompatAliases()
9472
- }
9473
- };
9474
- },
9475
- configEnvironment(environmentName) {
9476
- const workerConfig = getWorkerConfig2(environmentName);
9477
- if (isNodeCompat(workerConfig)) {
9471
+ configEnvironment(name2) {
9472
+ if (isNodeCompat(getWorkerConfig2(name2))) {
9478
9473
  return {
9479
- build: {
9480
- rollupOptions: {
9481
- external: getNodeCompatExternals()
9482
- }
9474
+ resolve: {
9475
+ builtins: [...nodeCompatExternals]
9476
+ },
9477
+ optimizeDeps: {
9478
+ // This is a list of dependency entry-points that should be pre-bundled.
9479
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9480
+ // ready ahead the first request to the dev server.
9481
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9482
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9483
+ // TODO: work out how to re-enable pre-bundling of these
9484
+ // include: [...getNodeCompatEntries()],
9485
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9486
+ // In this case we provide a list of all the Node.js modules, both those built-in to workerd and those that will be polyfilled.
9487
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9488
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9489
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9490
+ exclude: [
9491
+ ...builtinModules2,
9492
+ ...builtinModules2.map((m) => `node:${m}`)
9493
+ ]
9483
9494
  }
9484
9495
  };
9485
9496
  }
9486
9497
  },
9498
+ applyToEnvironment(environment) {
9499
+ return isNodeCompat(getWorkerConfig2(environment.name));
9500
+ },
9501
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9502
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9503
+ // rather than allowing the resolve hook here to alias then to polyfills.
9504
+ enforce: "pre",
9487
9505
  async resolveId(source, importer, options) {
9488
- const strippedSource = maybeStripNodeJsVirtualPrefix(source);
9489
- if (!strippedSource) {
9490
- return;
9491
- }
9492
- const workerConfig = getWorkerConfig2(this.environment.name);
9493
- if (!isNodeCompat(workerConfig)) {
9494
- return this.resolve(strippedSource, importer, options);
9506
+ const result = resolveNodeJSImport(source);
9507
+ if (!result) {
9508
+ return this.resolve(source, importer, options);
9495
9509
  }
9496
- const { unresolved, resolved } = resolveNodeJSImport(strippedSource);
9497
- if (this.environment.mode === "dev" && this.environment.depsOptimizer) {
9498
- const optimized = this.environment.depsOptimizer.registerMissingImport(
9499
- unresolved,
9500
- resolved
9501
- ).id;
9502
- return this.resolve(optimized, importer, options);
9510
+ if (this.environment.mode === "dev") {
9511
+ assert9(
9512
+ this.environment.depsOptimizer,
9513
+ "depsOptimizer is required in dev mode"
9514
+ );
9515
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9516
+ result.unresolved,
9517
+ result.resolved
9518
+ );
9519
+ return this.resolve(id, importer, options);
9503
9520
  }
9504
- return this.resolve(resolved, importer, options);
9521
+ return this.resolve(result.resolved, importer, options);
9505
9522
  },
9506
9523
  async transform(code, id) {
9507
9524
  const workerConfig = getWorkerConfig2(this.environment.name);
9508
- if (!isNodeCompat(workerConfig)) {
9509
- return;
9510
- }
9525
+ assert9(workerConfig, "Expected a worker config");
9511
9526
  const resolvedId = await this.resolve(workerConfig.main);
9512
9527
  if (id === resolvedId?.id) {
9513
9528
  return injectGlobalCode(id, code);