@cloudflare/vite-plugin 0.0.0-a52a68a21 → 0.0.0-a60539794

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,12 @@ 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";
1376
1373
  import "vite";
1377
1374
  import {
1378
1375
  unstable_getMiniflareWorkerOptions,
@@ -1406,11 +1403,10 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
1406
1403
  );
1407
1404
  for (const worker of workers) {
1408
1405
  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));
1406
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1407
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1408
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1409
+ assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1414
1410
  entrypointNames.add(value.entrypoint);
1415
1411
  }
1416
1412
  }
@@ -1592,8 +1588,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1592
1588
  const moduleRE = new RegExp(MODULE_PATTERN);
1593
1589
  const shouldExternalize = (
1594
1590
  // 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)
1591
+ moduleRE.test(moduleId)
1597
1592
  );
1598
1593
  if (shouldExternalize) {
1599
1594
  const result2 = {
@@ -1661,7 +1656,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1661
1656
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1662
1657
  assert4(
1663
1658
  workflowEntrypointClassNames,
1664
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1659
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1665
1660
  );
1666
1661
  for (const className of [...workflowEntrypointClassNames].sort()) {
1667
1662
  wrappers.push(
@@ -1697,17 +1692,19 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1697
1692
  );
1698
1693
  const moduleRE = new RegExp(MODULE_PATTERN);
1699
1694
  const match = moduleRE.exec(rawSpecifier);
1700
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1695
+ assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1701
1696
  const [full, moduleType, modulePath] = match;
1702
1697
  assert4(
1703
1698
  modulePath,
1704
- `Unexpected error: module path not found in reference ${full}.`
1699
+ `Unexpected error: module path not found in reference: ${full}.`
1705
1700
  );
1706
1701
  let source;
1707
1702
  try {
1708
1703
  source = fs2.readFileSync(modulePath);
1709
1704
  } catch (error) {
1710
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1705
+ throw new Error(
1706
+ `Import "${modulePath}" not found. Does the file exist?`
1707
+ );
1711
1708
  }
1712
1709
  return MiniflareResponse.json({
1713
1710
  // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
@@ -7313,7 +7310,7 @@ Parser.acorn = {
7313
7310
  };
7314
7311
 
7315
7312
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7316
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7313
+ import { builtinModules, createRequire } from "node:module";
7317
7314
  import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
7318
7315
 
7319
7316
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
@@ -7376,7 +7373,7 @@ import process$1 from "node:process";
7376
7373
  import path4, { dirname as dirname3 } from "node:path";
7377
7374
  import v8 from "node:v8";
7378
7375
  import { format as format2, inspect } from "node:util";
7379
- var BUILTIN_MODULES = new Set(builtinModules2);
7376
+ var BUILTIN_MODULES = new Set(builtinModules);
7380
7377
  function normalizeSlash(path8) {
7381
7378
  return path8.replace(/\\/g, "/");
7382
7379
  }
@@ -8490,7 +8487,7 @@ function parsePackageName(specifier, base) {
8490
8487
  return { packageName, packageSubpath, isScoped };
8491
8488
  }
8492
8489
  function packageResolve(specifier, base, conditions) {
8493
- if (builtinModules2.includes(specifier)) {
8490
+ if (builtinModules.includes(specifier)) {
8494
8491
  return new URL$1("node:" + specifier);
8495
8492
  }
8496
8493
  const { packageName, packageSubpath, isScoped } = parsePackageName(
@@ -8577,7 +8574,7 @@ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8577
8574
  try {
8578
8575
  resolved = new URL$1(specifier);
8579
8576
  } catch (error_) {
8580
- if (isRemote && !builtinModules2.includes(specifier)) {
8577
+ if (isRemote && !builtinModules.includes(specifier)) {
8581
8578
  const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8582
8579
  error.cause = error_;
8583
8580
  throw error;
@@ -8722,7 +8719,8 @@ var { env } = defineEnv({
8722
8719
  nodeCompat: true,
8723
8720
  presets: [cloudflare]
8724
8721
  });
8725
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8722
+ var nodeCompatExternals = new Set(env.external);
8723
+ var nodeCompatEntries = getNodeCompatEntries();
8726
8724
  function isNodeCompat(workerConfig) {
8727
8725
  if (workerConfig === void 0) {
8728
8726
  return false;
@@ -8750,12 +8748,17 @@ function injectGlobalCode(id, code) {
8750
8748
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8751
8749
  if (typeof globalInject === "string") {
8752
8750
  const moduleSpecifier2 = globalInject;
8753
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8751
+ return `import var_${globalName} from "${moduleSpecifier2}";
8754
8752
  globalThis.${globalName} = var_${globalName};
8755
8753
  `;
8756
8754
  }
8757
8755
  const [moduleSpecifier, exportName] = globalInject;
8758
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8756
+ assert6(
8757
+ moduleSpecifier !== void 0,
8758
+ "Expected moduleSpecifier to be defined"
8759
+ );
8760
+ assert6(exportName !== void 0, "Expected exportName to be defined");
8761
+ return `import var_${globalName} from "${moduleSpecifier}";
8759
8762
  globalThis.${globalName} = var_${globalName}.${exportName};
8760
8763
  `;
8761
8764
  }).join("\n");
@@ -8766,37 +8769,36 @@ globalThis.${globalName} = var_${globalName}.${exportName};
8766
8769
  map: modified.generateMap({ hires: "boundary", source: id })
8767
8770
  };
8768
8771
  }
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
8772
  function resolveNodeJSImport(source) {
8785
8773
  const alias = env.alias[source];
8786
8774
  if (alias) {
8787
- assert6(
8788
- !env.external.includes(alias),
8789
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8790
- );
8791
- source = alias;
8775
+ return {
8776
+ unresolved: alias,
8777
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8778
+ };
8792
8779
  }
8793
- const resolved = resolvePathSync(source, {
8794
- url: import.meta.url
8795
- });
8796
- return {
8797
- unresolved: source,
8798
- resolved
8799
- };
8780
+ if (nodeCompatEntries.has(source)) {
8781
+ return {
8782
+ unresolved: source,
8783
+ resolved: resolvePathSync(source, { url: import.meta.url })
8784
+ };
8785
+ }
8786
+ }
8787
+ function getNodeCompatEntries() {
8788
+ const entries = new Set(Object.values(env.alias));
8789
+ for (const globalInject of Object.values(env.inject)) {
8790
+ if (typeof globalInject === "string") {
8791
+ entries.add(globalInject);
8792
+ } else {
8793
+ assert6(
8794
+ globalInject[0] !== void 0,
8795
+ "Expected first element of globalInject to be defined"
8796
+ );
8797
+ entries.add(globalInject[0]);
8798
+ }
8799
+ }
8800
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8801
+ return entries;
8800
8802
  }
8801
8803
 
8802
8804
  // src/plugin-config.ts
@@ -9109,9 +9111,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9111
  }
9110
9112
 
9111
9113
  // src/websockets.ts
9112
- import ws from "ws";
9114
+ import { WebSocketServer } from "ws";
9113
9115
  function handleWebSocket(httpServer, fetcher, logger) {
9114
- const nodeWebSocket = new ws.Server({ noServer: true });
9116
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9117
  httpServer.on(
9116
9118
  "upgrade",
9117
9119
  async (request, socket, head) => {
@@ -9220,7 +9222,7 @@ function cloudflare2(pluginConfig = {}) {
9220
9222
  }
9221
9223
  } : void 0,
9222
9224
  builder: {
9223
- async buildApp(builder) {
9225
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9224
9226
  const clientEnvironment = builder.environments.client;
9225
9227
  const defaultHtmlPath = path7.resolve(
9226
9228
  builder.config.root,
@@ -9246,7 +9248,7 @@ function cloudflare2(pluginConfig = {}) {
9246
9248
  )
9247
9249
  );
9248
9250
  }
9249
- }
9251
+ })
9250
9252
  }
9251
9253
  };
9252
9254
  },
@@ -9465,49 +9467,61 @@ function cloudflare2(pluginConfig = {}) {
9465
9467
  apply(_config, env2) {
9466
9468
  return !env2.isPreview;
9467
9469
  },
9468
- config() {
9469
- return {
9470
- resolve: {
9471
- alias: getNodeCompatAliases()
9472
- }
9473
- };
9474
- },
9475
- configEnvironment(environmentName) {
9476
- const workerConfig = getWorkerConfig2(environmentName);
9477
- if (isNodeCompat(workerConfig)) {
9470
+ configEnvironment(name2) {
9471
+ if (isNodeCompat(getWorkerConfig2(name2))) {
9478
9472
  return {
9479
- build: {
9480
- rollupOptions: {
9481
- external: getNodeCompatExternals()
9482
- }
9473
+ resolve: {
9474
+ builtins: [...nodeCompatExternals]
9475
+ },
9476
+ optimizeDeps: {
9477
+ // This is a list of dependency entry-points that should be pre-bundled.
9478
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9479
+ // ready ahead the first request to the dev server.
9480
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9481
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9482
+ // TODO: work out how to re-enable pre-bundling of these
9483
+ // include: [...getNodeCompatEntries()],
9484
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9485
+ // 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.
9486
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9487
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9488
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9489
+ exclude: [
9490
+ ...builtinModules2,
9491
+ ...builtinModules2.map((m) => `node:${m}`)
9492
+ ]
9483
9493
  }
9484
9494
  };
9485
9495
  }
9486
9496
  },
9497
+ applyToEnvironment(environment) {
9498
+ return isNodeCompat(getWorkerConfig2(environment.name));
9499
+ },
9500
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9501
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9502
+ // rather than allowing the resolve hook here to alias then to polyfills.
9503
+ enforce: "pre",
9487
9504
  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);
9505
+ const result = resolveNodeJSImport(source);
9506
+ if (!result) {
9507
+ return this.resolve(source, importer, options);
9495
9508
  }
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);
9509
+ if (this.environment.mode === "dev") {
9510
+ assert9(
9511
+ this.environment.depsOptimizer,
9512
+ "depsOptimizer is required in dev mode"
9513
+ );
9514
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9515
+ result.unresolved,
9516
+ result.resolved
9517
+ );
9518
+ return this.resolve(id, importer, options);
9503
9519
  }
9504
- return this.resolve(resolved, importer, options);
9520
+ return this.resolve(result.resolved, importer, options);
9505
9521
  },
9506
9522
  async transform(code, id) {
9507
9523
  const workerConfig = getWorkerConfig2(this.environment.name);
9508
- if (!isNodeCompat(workerConfig)) {
9509
- return;
9510
- }
9524
+ assert9(workerConfig, "Expected a worker config");
9511
9525
  const resolvedId = await this.resolve(workerConfig.main);
9512
9526
  if (id === resolvedId?.id) {
9513
9527
  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-a52a68a21",
3
+ "version": "0.0.0-a60539794",
4
4
  "description": "Cloudflare plugin for Vite",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -36,8 +36,8 @@
36
36
  "@cloudflare/unenv-preset": "1.1.1",
37
37
  "@hattip/adapter-node": "^0.0.49",
38
38
  "unenv": "2.0.0-rc.1",
39
- "ws": "^8.18.0",
40
- "miniflare": "0.0.0-a52a68a21"
39
+ "ws": "8.18.0",
40
+ "miniflare": "0.0.0-a60539794"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@cloudflare/workers-types": "^4.20250214.0",
@@ -50,10 +50,10 @@
50
50
  "undici": "^5.28.5",
51
51
  "vite": "^6.1.0",
52
52
  "vitest": "~3.0.5",
53
- "wrangler": "0.0.0-a52a68a21",
54
- "@cloudflare/workers-shared": "0.0.0-a52a68a21",
55
53
  "@cloudflare/mock-npm-registry": "0.0.0",
56
- "@cloudflare/workers-tsconfig": "0.0.0"
54
+ "@cloudflare/workers-shared": "0.0.0-a60539794",
55
+ "@cloudflare/workers-tsconfig": "0.0.0",
56
+ "wrangler": "0.0.0-a60539794"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vite": "^6.1.0",