@cloudflare/vite-plugin 0.1.2 → 0.1.4

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.
Files changed (2) hide show
  1. package/dist/index.js +76 -76
  2. package/package.json +3 -3
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"],
@@ -1592,8 +1584,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1592
1584
  const moduleRE = new RegExp(MODULE_PATTERN);
1593
1585
  const shouldExternalize = (
1594
1586
  // 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)
1587
+ moduleRE.test(moduleId)
1597
1588
  );
1598
1589
  if (shouldExternalize) {
1599
1590
  const result2 = {
@@ -7313,7 +7304,7 @@ Parser.acorn = {
7313
7304
  };
7314
7305
 
7315
7306
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7316
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7307
+ import { builtinModules, createRequire } from "node:module";
7317
7308
  import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
7318
7309
 
7319
7310
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
@@ -7376,7 +7367,7 @@ import process$1 from "node:process";
7376
7367
  import path4, { dirname as dirname3 } from "node:path";
7377
7368
  import v8 from "node:v8";
7378
7369
  import { format as format2, inspect } from "node:util";
7379
- var BUILTIN_MODULES = new Set(builtinModules2);
7370
+ var BUILTIN_MODULES = new Set(builtinModules);
7380
7371
  function normalizeSlash(path8) {
7381
7372
  return path8.replace(/\\/g, "/");
7382
7373
  }
@@ -8490,7 +8481,7 @@ function parsePackageName(specifier, base) {
8490
8481
  return { packageName, packageSubpath, isScoped };
8491
8482
  }
8492
8483
  function packageResolve(specifier, base, conditions) {
8493
- if (builtinModules2.includes(specifier)) {
8484
+ if (builtinModules.includes(specifier)) {
8494
8485
  return new URL$1("node:" + specifier);
8495
8486
  }
8496
8487
  const { packageName, packageSubpath, isScoped } = parsePackageName(
@@ -8577,7 +8568,7 @@ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8577
8568
  try {
8578
8569
  resolved = new URL$1(specifier);
8579
8570
  } catch (error_) {
8580
- if (isRemote && !builtinModules2.includes(specifier)) {
8571
+ if (isRemote && !builtinModules.includes(specifier)) {
8581
8572
  const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8582
8573
  error.cause = error_;
8583
8574
  throw error;
@@ -8722,7 +8713,6 @@ var { env } = defineEnv({
8722
8713
  nodeCompat: true,
8723
8714
  presets: [cloudflare]
8724
8715
  });
8725
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8726
8716
  function isNodeCompat(workerConfig) {
8727
8717
  if (workerConfig === void 0) {
8728
8718
  return false;
@@ -8746,16 +8736,39 @@ function isNodeCompat(workerConfig) {
8746
8736
  }
8747
8737
  return false;
8748
8738
  }
8739
+ function getNodeCompatEntries() {
8740
+ const entries = new Set(Object.values(env.alias));
8741
+ for (const globalInject of Object.values(env.inject)) {
8742
+ if (typeof globalInject === "string") {
8743
+ entries.add(globalInject);
8744
+ } else {
8745
+ assert6(
8746
+ globalInject[0] !== void 0,
8747
+ "Expected first element of globalInject to be defined"
8748
+ );
8749
+ entries.add(globalInject[0]);
8750
+ }
8751
+ }
8752
+ for (const external of env.external) {
8753
+ entries.delete(external);
8754
+ }
8755
+ return entries;
8756
+ }
8749
8757
  function injectGlobalCode(id, code) {
8750
8758
  const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8751
8759
  if (typeof globalInject === "string") {
8752
8760
  const moduleSpecifier2 = globalInject;
8753
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8761
+ return `import var_${globalName} from "${moduleSpecifier2}";
8754
8762
  globalThis.${globalName} = var_${globalName};
8755
8763
  `;
8756
8764
  }
8757
8765
  const [moduleSpecifier, exportName] = globalInject;
8758
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8766
+ assert6(
8767
+ moduleSpecifier !== void 0,
8768
+ "Expected moduleSpecifier to be defined"
8769
+ );
8770
+ assert6(exportName !== void 0, "Expected exportName to be defined");
8771
+ return `import var_${globalName} from "${moduleSpecifier}";
8759
8772
  globalThis.${globalName} = var_${globalName}.${exportName};
8760
8773
  `;
8761
8774
  }).join("\n");
@@ -8766,37 +8779,17 @@ globalThis.${globalName} = var_${globalName}.${exportName};
8766
8779
  map: modified.generateMap({ hires: "boundary", source: id })
8767
8780
  };
8768
8781
  }
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
8782
  function getNodeCompatExternals() {
8779
8783
  return env.external;
8780
8784
  }
8781
- function maybeStripNodeJsVirtualPrefix(source) {
8782
- return source.startsWith(CLOUDFLARE_VIRTUAL_PREFIX) ? source.slice(CLOUDFLARE_VIRTUAL_PREFIX.length) : void 0;
8783
- }
8784
8785
  function resolveNodeJSImport(source) {
8785
8786
  const alias = env.alias[source];
8786
8787
  if (alias) {
8787
- assert6(
8788
- !env.external.includes(alias),
8789
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8790
- );
8791
- source = alias;
8788
+ return {
8789
+ unresolved: alias,
8790
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8791
+ };
8792
8792
  }
8793
- const resolved = resolvePathSync(source, {
8794
- url: import.meta.url
8795
- });
8796
- return {
8797
- unresolved: source,
8798
- resolved
8799
- };
8800
8793
  }
8801
8794
 
8802
8795
  // src/plugin-config.ts
@@ -9465,49 +9458,56 @@ function cloudflare2(pluginConfig = {}) {
9465
9458
  apply(_config, env2) {
9466
9459
  return !env2.isPreview;
9467
9460
  },
9468
- config() {
9469
- return {
9470
- resolve: {
9471
- alias: getNodeCompatAliases()
9472
- }
9473
- };
9474
- },
9475
- configEnvironment(environmentName) {
9476
- const workerConfig = getWorkerConfig2(environmentName);
9477
- if (isNodeCompat(workerConfig)) {
9461
+ configEnvironment(name2) {
9462
+ if (isNodeCompat(getWorkerConfig2(name2))) {
9478
9463
  return {
9479
- build: {
9480
- rollupOptions: {
9481
- external: getNodeCompatExternals()
9482
- }
9464
+ resolve: {
9465
+ builtins: getNodeCompatExternals()
9466
+ },
9467
+ optimizeDeps: {
9468
+ // This is a list of dependency entry-points that should be pre-bundled.
9469
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9470
+ // ready ahead the first request to the dev server.
9471
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9472
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9473
+ include: [...getNodeCompatEntries()],
9474
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9475
+ // 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.
9476
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9477
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9478
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9479
+ exclude: [
9480
+ ...builtinModules2,
9481
+ ...builtinModules2.map((m) => `node:${m}`)
9482
+ ]
9483
9483
  }
9484
9484
  };
9485
9485
  }
9486
9486
  },
9487
+ applyToEnvironment(environment) {
9488
+ return isNodeCompat(getWorkerConfig2(environment.name));
9489
+ },
9490
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9491
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9492
+ // rather than allowing the resolve hook here to alias then to polyfills.
9493
+ enforce: "pre",
9487
9494
  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);
9495
+ const result = resolveNodeJSImport(source);
9496
+ if (!result) {
9497
+ return this.resolve(source, importer, options);
9495
9498
  }
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);
9499
+ if (this.environment.mode === "dev") {
9500
+ assert9(
9501
+ this.environment.depsOptimizer,
9502
+ "depsOptimizer is required in dev mode"
9503
+ );
9504
+ return this.resolve(result.unresolved, importer, options);
9503
9505
  }
9504
- return this.resolve(resolved, importer, options);
9506
+ return this.resolve(result.resolved, importer, options);
9505
9507
  },
9506
9508
  async transform(code, id) {
9507
9509
  const workerConfig = getWorkerConfig2(this.environment.name);
9508
- if (!isNodeCompat(workerConfig)) {
9509
- return;
9510
- }
9510
+ assert9(workerConfig, "Expected a worker config");
9511
9511
  const resolvedId = await this.resolve(workerConfig.main);
9512
9512
  if (id === resolvedId?.id) {
9513
9513
  return injectGlobalCode(id, code);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vite-plugin",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Cloudflare plugin for Vite",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -51,9 +51,9 @@
51
51
  "vite": "^6.1.0",
52
52
  "vitest": "~3.0.5",
53
53
  "@cloudflare/mock-npm-registry": "0.0.0",
54
- "@cloudflare/workers-shared": "0.14.3",
55
54
  "@cloudflare/workers-tsconfig": "0.0.0",
56
- "wrangler": "3.109.2"
55
+ "wrangler": "3.109.3",
56
+ "@cloudflare/workers-shared": "0.14.3"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vite": "^6.1.0",