@cloudflare/vite-plugin 0.0.0-d422c8ecb → 0.0.0-d5ce0c459

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);
@@ -1212,9 +1209,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1212
1209
  // We want to use `workerd` package exports if available (e.g. for postgres).
1213
1210
  conditions: [...defaultConditions, "development|production"],
1214
1211
  // 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]
1212
+ builtins: [...cloudflareBuiltInModules]
1218
1213
  },
1219
1214
  dev: {
1220
1215
  createEnvironment(name2, config) {
@@ -1243,10 +1238,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1243
1238
  // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1244
1239
  noDiscovery: false,
1245
1240
  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
- ],
1241
+ exclude: [...cloudflareBuiltInModules],
1250
1242
  esbuildOptions: {
1251
1243
  platform: "neutral",
1252
1244
  conditions: [...defaultConditions, "development"],
@@ -1372,7 +1364,13 @@ import * as fs2 from "node:fs";
1372
1364
  import * as fsp from "node:fs/promises";
1373
1365
  import * as path3 from "node:path";
1374
1366
  import { fileURLToPath } from "node:url";
1375
- import { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
1367
+ import {
1368
+ kCurrentWorker,
1369
+ Log,
1370
+ LogLevel,
1371
+ Response as MiniflareResponse
1372
+ } from "miniflare";
1373
+ import { globSync } from "tinyglobby";
1376
1374
  import "vite";
1377
1375
  import {
1378
1376
  unstable_getMiniflareWorkerOptions,
@@ -1406,11 +1404,10 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
1406
1404
  );
1407
1405
  for (const worker of workers) {
1408
1406
  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));
1407
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1408
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1409
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1410
+ assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1414
1411
  entrypointNames.add(value.entrypoint);
1415
1412
  }
1416
1413
  }
@@ -1555,7 +1552,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1555
1552
  }
1556
1553
  }
1557
1554
  ];
1558
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1555
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1559
1556
  ([environmentName, workerConfig]) => {
1560
1557
  const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1561
1558
  {
@@ -1564,52 +1561,58 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1564
1561
  },
1565
1562
  resolvedPluginConfig.cloudflareEnv
1566
1563
  );
1564
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1567
1565
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1568
1566
  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 });
1567
+ externalWorkers: externalWorkers2,
1568
+ worker: {
1569
+ ...workerOptions,
1570
+ name: workerOptions.name ?? workerConfig.name,
1571
+ modulesRoot: miniflareModulesRoot,
1572
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1573
+ bindings: {
1574
+ ...workerOptions.bindings,
1575
+ __VITE_ROOT__: resolvedViteConfig.root,
1576
+ __VITE_ENTRY_PATH__: workerConfig.main
1577
+ },
1578
+ serviceBindings: {
1579
+ ...workerOptions.serviceBindings,
1580
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1581
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
1582
+ } : {},
1583
+ __VITE_INVOKE_MODULE__: async (request) => {
1584
+ const payload = await request.json();
1585
+ const invokePayloadData = payload.data;
1586
+ assert4(
1587
+ invokePayloadData.name === "fetchModule",
1588
+ `Invalid invoke event: ${invokePayloadData.name}`
1589
+ );
1590
+ const [moduleId] = invokePayloadData.data;
1591
+ const moduleRE = new RegExp(MODULE_PATTERN);
1592
+ const shouldExternalize = (
1593
+ // Worker modules (CompiledWasm, Text, Data)
1594
+ moduleRE.test(moduleId)
1595
+ );
1596
+ if (shouldExternalize) {
1597
+ const result2 = {
1598
+ externalize: moduleId,
1599
+ type: "module"
1600
+ };
1601
+ return MiniflareResponse.json({ result: result2 });
1602
+ }
1603
+ const devEnvironment = viteDevServer.environments[environmentName];
1604
+ const result = await devEnvironment.hot.handleInvoke(payload);
1605
+ return MiniflareResponse.json(result);
1604
1606
  }
1605
- const devEnvironment = viteDevServer.environments[environmentName];
1606
- const result = await devEnvironment.hot.handleInvoke(payload);
1607
- return MiniflareResponse.json(result);
1608
1607
  }
1609
1608
  }
1610
1609
  };
1611
1610
  }
1612
1611
  ) : [];
1612
+ const userWorkers = workersFromConfig.map((options) => options.worker);
1613
+ const externalWorkers = workersFromConfig.flatMap(
1614
+ (options) => options.externalWorkers
1615
+ );
1613
1616
  const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1614
1617
  const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1615
1618
  const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
@@ -1629,6 +1632,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1629
1632
  ),
1630
1633
  workers: [
1631
1634
  ...assetWorkers,
1635
+ ...externalWorkers,
1632
1636
  ...userWorkers.map((workerOptions) => {
1633
1637
  const wrappers = [
1634
1638
  `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
@@ -1661,7 +1665,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1661
1665
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1662
1666
  assert4(
1663
1667
  workflowEntrypointClassNames,
1664
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1668
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1665
1669
  );
1666
1670
  for (const className of [...workflowEntrypointClassNames].sort()) {
1667
1671
  wrappers.push(
@@ -1697,17 +1701,19 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1697
1701
  );
1698
1702
  const moduleRE = new RegExp(MODULE_PATTERN);
1699
1703
  const match = moduleRE.exec(rawSpecifier);
1700
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1704
+ assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1701
1705
  const [full, moduleType, modulePath] = match;
1702
1706
  assert4(
1703
1707
  modulePath,
1704
- `Unexpected error: module path not found in reference ${full}.`
1708
+ `Unexpected error: module path not found in reference: ${full}.`
1705
1709
  );
1706
1710
  let source;
1707
1711
  try {
1708
1712
  source = fs2.readFileSync(modulePath);
1709
1713
  } catch (error) {
1710
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1714
+ throw new Error(
1715
+ `Import "${modulePath}" not found. Does the file exist?`
1716
+ );
1711
1717
  }
1712
1718
  return MiniflareResponse.json({
1713
1719
  // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
@@ -1716,22 +1722,44 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1716
1722
  }
1717
1723
  };
1718
1724
  }
1725
+ function getPreviewModules(main, modulesRules) {
1726
+ assert4(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
1727
+ const rootPath = path3.dirname(main);
1728
+ const entryPath = path3.basename(main);
1729
+ return {
1730
+ rootPath,
1731
+ modules: [
1732
+ {
1733
+ type: "ESModule",
1734
+ path: entryPath
1735
+ },
1736
+ ...modulesRules.flatMap(
1737
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
1738
+ type,
1739
+ path: path8
1740
+ }))
1741
+ )
1742
+ ]
1743
+ };
1744
+ }
1719
1745
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1720
1746
  const resolvedViteConfig = vitePreviewServer.config;
1721
1747
  const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1722
1748
  const workerConfigs = configPaths.map(
1723
1749
  (configPath) => unstable_readConfig({ config: configPath })
1724
1750
  );
1725
- const workers = workerConfigs.map((config) => {
1751
+ const workers = workerConfigs.flatMap((config) => {
1726
1752
  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
- };
1753
+ const { externalWorkers } = miniflareWorkerOptions;
1754
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1755
+ return [
1756
+ {
1757
+ ...workerOptions,
1758
+ name: workerOptions.name ?? config.name,
1759
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
1760
+ },
1761
+ ...externalWorkers
1762
+ ];
1735
1763
  });
1736
1764
  const logger = new ViteMiniflareLogger(resolvedViteConfig);
1737
1765
  return {
@@ -7313,7 +7341,7 @@ Parser.acorn = {
7313
7341
  };
7314
7342
 
7315
7343
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7316
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7344
+ import { builtinModules, createRequire } from "node:module";
7317
7345
  import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
7318
7346
 
7319
7347
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
@@ -7373,10 +7401,10 @@ var isAbsolute = function(p) {
7373
7401
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7374
7402
  import assert5 from "node:assert";
7375
7403
  import process$1 from "node:process";
7376
- import path4, { dirname as dirname3 } from "node:path";
7404
+ import path4, { dirname as dirname4 } from "node:path";
7377
7405
  import v8 from "node:v8";
7378
7406
  import { format as format2, inspect } from "node:util";
7379
- var BUILTIN_MODULES = new Set(builtinModules2);
7407
+ var BUILTIN_MODULES = new Set(builtinModules);
7380
7408
  function normalizeSlash(path8) {
7381
7409
  return path8.replace(/\\/g, "/");
7382
7410
  }
@@ -8490,7 +8518,7 @@ function parsePackageName(specifier, base) {
8490
8518
  return { packageName, packageSubpath, isScoped };
8491
8519
  }
8492
8520
  function packageResolve(specifier, base, conditions) {
8493
- if (builtinModules2.includes(specifier)) {
8521
+ if (builtinModules.includes(specifier)) {
8494
8522
  return new URL$1("node:" + specifier);
8495
8523
  }
8496
8524
  const { packageName, packageSubpath, isScoped } = parsePackageName(
@@ -8577,7 +8605,7 @@ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8577
8605
  try {
8578
8606
  resolved = new URL$1(specifier);
8579
8607
  } catch (error_) {
8580
- if (isRemote && !builtinModules2.includes(specifier)) {
8608
+ if (isRemote && !builtinModules.includes(specifier)) {
8581
8609
  const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8582
8610
  error.cause = error_;
8583
8611
  throw error;
@@ -8722,7 +8750,8 @@ var { env } = defineEnv({
8722
8750
  nodeCompat: true,
8723
8751
  presets: [cloudflare]
8724
8752
  });
8725
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8753
+ var nodeCompatExternals = new Set(env.external);
8754
+ var nodeCompatEntries = getNodeCompatEntries();
8726
8755
  function isNodeCompat(workerConfig) {
8727
8756
  if (workerConfig === void 0) {
8728
8757
  return false;
@@ -8734,11 +8763,6 @@ function isNodeCompat(workerConfig) {
8734
8763
  if (nodeCompatMode === "v2") {
8735
8764
  return true;
8736
8765
  }
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
8766
  if (nodeCompatMode === "v1") {
8743
8767
  throw new Error(
8744
8768
  `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 +8774,17 @@ function injectGlobalCode(id, code) {
8750
8774
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8751
8775
  if (typeof globalInject === "string") {
8752
8776
  const moduleSpecifier2 = globalInject;
8753
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8777
+ return `import var_${globalName} from "${moduleSpecifier2}";
8754
8778
  globalThis.${globalName} = var_${globalName};
8755
8779
  `;
8756
8780
  }
8757
8781
  const [moduleSpecifier, exportName] = globalInject;
8758
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8782
+ assert6(
8783
+ moduleSpecifier !== void 0,
8784
+ "Expected moduleSpecifier to be defined"
8785
+ );
8786
+ assert6(exportName !== void 0, "Expected exportName to be defined");
8787
+ return `import var_${globalName} from "${moduleSpecifier}";
8759
8788
  globalThis.${globalName} = var_${globalName}.${exportName};
8760
8789
  `;
8761
8790
  }).join("\n");
@@ -8766,37 +8795,36 @@ globalThis.${globalName} = var_${globalName}.${exportName};
8766
8795
  map: modified.generateMap({ hires: "boundary", source: id })
8767
8796
  };
8768
8797
  }
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
8798
  function resolveNodeJSImport(source) {
8785
8799
  const alias = env.alias[source];
8786
8800
  if (alias) {
8787
- assert6(
8788
- !env.external.includes(alias),
8789
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8790
- );
8791
- source = alias;
8801
+ return {
8802
+ unresolved: alias,
8803
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8804
+ };
8792
8805
  }
8793
- const resolved = resolvePathSync(source, {
8794
- url: import.meta.url
8795
- });
8796
- return {
8797
- unresolved: source,
8798
- resolved
8799
- };
8806
+ if (nodeCompatEntries.has(source)) {
8807
+ return {
8808
+ unresolved: source,
8809
+ resolved: resolvePathSync(source, { url: import.meta.url })
8810
+ };
8811
+ }
8812
+ }
8813
+ function getNodeCompatEntries() {
8814
+ const entries = new Set(Object.values(env.alias));
8815
+ for (const globalInject of Object.values(env.inject)) {
8816
+ if (typeof globalInject === "string") {
8817
+ entries.add(globalInject);
8818
+ } else {
8819
+ assert6(
8820
+ globalInject[0] !== void 0,
8821
+ "Expected first element of globalInject to be defined"
8822
+ );
8823
+ entries.add(globalInject[0]);
8824
+ }
8825
+ }
8826
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8827
+ return entries;
8800
8828
  }
8801
8829
 
8802
8830
  // src/plugin-config.ts
@@ -8841,7 +8869,6 @@ var nonApplicableWorkerConfigs = {
8841
8869
  "build",
8842
8870
  "find_additional_modules",
8843
8871
  "no_bundle",
8844
- "node_compat",
8845
8872
  "preserve_file_names",
8846
8873
  "site",
8847
8874
  "tsconfig",
@@ -8858,7 +8885,6 @@ var nullableNonApplicable = [
8858
8885
  "find_additional_modules",
8859
8886
  "minify",
8860
8887
  "no_bundle",
8861
- "node_compat",
8862
8888
  "preserve_file_names",
8863
8889
  "site",
8864
8890
  "tsconfig",
@@ -9109,9 +9135,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9135
  }
9110
9136
 
9111
9137
  // src/websockets.ts
9112
- import ws from "ws";
9138
+ import { WebSocketServer } from "ws";
9113
9139
  function handleWebSocket(httpServer, fetcher, logger) {
9114
- const nodeWebSocket = new ws.Server({ noServer: true });
9140
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9141
  httpServer.on(
9116
9142
  "upgrade",
9117
9143
  async (request, socket, head) => {
@@ -9220,7 +9246,7 @@ function cloudflare2(pluginConfig = {}) {
9220
9246
  }
9221
9247
  } : void 0,
9222
9248
  builder: {
9223
- async buildApp(builder) {
9249
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9224
9250
  const clientEnvironment = builder.environments.client;
9225
9251
  const defaultHtmlPath = path7.resolve(
9226
9252
  builder.config.root,
@@ -9246,7 +9272,7 @@ function cloudflare2(pluginConfig = {}) {
9246
9272
  )
9247
9273
  );
9248
9274
  }
9249
- }
9275
+ })
9250
9276
  }
9251
9277
  };
9252
9278
  },
@@ -9307,7 +9333,7 @@ function cloudflare2(pluginConfig = {}) {
9307
9333
  return;
9308
9334
  }
9309
9335
  config.no_bundle = true;
9310
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9336
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9311
9337
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9312
9338
  config.unsafe = void 0;
9313
9339
  }
@@ -9465,49 +9491,61 @@ function cloudflare2(pluginConfig = {}) {
9465
9491
  apply(_config, env2) {
9466
9492
  return !env2.isPreview;
9467
9493
  },
9468
- config() {
9469
- return {
9470
- resolve: {
9471
- alias: getNodeCompatAliases()
9472
- }
9473
- };
9474
- },
9475
- configEnvironment(environmentName) {
9476
- const workerConfig = getWorkerConfig2(environmentName);
9477
- if (isNodeCompat(workerConfig)) {
9494
+ configEnvironment(name2) {
9495
+ if (isNodeCompat(getWorkerConfig2(name2))) {
9478
9496
  return {
9479
- build: {
9480
- rollupOptions: {
9481
- external: getNodeCompatExternals()
9482
- }
9497
+ resolve: {
9498
+ builtins: [...nodeCompatExternals]
9499
+ },
9500
+ optimizeDeps: {
9501
+ // This is a list of dependency entry-points that should be pre-bundled.
9502
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9503
+ // ready ahead the first request to the dev server.
9504
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9505
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9506
+ // TODO: work out how to re-enable pre-bundling of these
9507
+ // include: [...getNodeCompatEntries()],
9508
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9509
+ // 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.
9510
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9511
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9512
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9513
+ exclude: [
9514
+ ...builtinModules2,
9515
+ ...builtinModules2.map((m) => `node:${m}`)
9516
+ ]
9483
9517
  }
9484
9518
  };
9485
9519
  }
9486
9520
  },
9521
+ applyToEnvironment(environment) {
9522
+ return isNodeCompat(getWorkerConfig2(environment.name));
9523
+ },
9524
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9525
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9526
+ // rather than allowing the resolve hook here to alias then to polyfills.
9527
+ enforce: "pre",
9487
9528
  async resolveId(source, importer, options) {
9488
- const strippedSource = maybeStripNodeJsVirtualPrefix(source);
9489
- if (!strippedSource) {
9490
- return;
9529
+ const result = resolveNodeJSImport(source);
9530
+ if (!result) {
9531
+ return this.resolve(source, importer, options);
9491
9532
  }
9492
- const workerConfig = getWorkerConfig2(this.environment.name);
9493
- if (!isNodeCompat(workerConfig)) {
9494
- return this.resolve(strippedSource, importer, options);
9495
- }
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);
9533
+ if (this.environment.mode === "dev") {
9534
+ assert9(
9535
+ this.environment.depsOptimizer,
9536
+ "depsOptimizer is required in dev mode"
9537
+ );
9538
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9539
+ result.unresolved,
9540
+ result.resolved
9541
+ );
9542
+ return this.resolve(id, importer, options);
9503
9543
  }
9504
- return this.resolve(resolved, importer, options);
9544
+ return this.resolve(result.resolved, importer, options);
9505
9545
  },
9506
9546
  async transform(code, id) {
9507
9547
  const workerConfig = getWorkerConfig2(this.environment.name);
9508
- if (!isNodeCompat(workerConfig)) {
9509
- return;
9510
- }
9548
+ assert9(workerConfig, "Expected a worker config");
9511
9549
  const resolvedId = await this.resolve(workerConfig.main);
9512
9550
  if (id === resolvedId?.id) {
9513
9551
  return injectGlobalCode(id, code);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vite-plugin",
3
- "version": "0.0.0-d422c8ecb",
3
+ "version": "0.0.0-d5ce0c459",
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
- "ws": "^8.18.0",
40
- "miniflare": "0.0.0-d422c8ecb"
40
+ "ws": "8.18.0",
41
+ "miniflare": "0.0.0-d5ce0c459",
42
+ "wrangler": "0.0.0-d5ce0c459"
41
43
  },
42
44
  "devDependencies": {
43
- "@cloudflare/workers-types": "^4.20250214.0",
45
+ "@cloudflare/workers-types": "^4.20250310.0",
44
46
  "@types/node": "^22.10.1",
45
47
  "@types/ws": "^8.5.13",
46
48
  "magic-string": "^0.30.12",
@@ -51,9 +53,8 @@
51
53
  "vite": "^6.1.0",
52
54
  "vitest": "~3.0.5",
53
55
  "@cloudflare/mock-npm-registry": "0.0.0",
54
- "@cloudflare/workers-tsconfig": "0.0.0",
55
- "@cloudflare/workers-shared": "0.0.0-d422c8ecb",
56
- "wrangler": "0.0.0-d422c8ecb"
56
+ "@cloudflare/workers-shared": "0.0.0-d5ce0c459",
57
+ "@cloudflare/workers-tsconfig": "0.0.0"
57
58
  },
58
59
  "peerDependencies": {
59
60
  "vite": "^6.1.0",
@@ -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
  }