@cloudflare/vite-plugin 0.0.0-6c2e94318 → 0.0.0-7006630cf

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
@@ -3,16 +3,6 @@ import assert7 from "node:assert";
3
3
  import * as fs4 from "node:fs";
4
4
  import * as path6 from "node:path";
5
5
  import { createMiddleware } from "@hattip/adapter-node";
6
- import { Miniflare } from "miniflare";
7
- import "vite";
8
-
9
- // src/cloudflare-environment.ts
10
- import assert from "node:assert";
11
- import { builtinModules } from "node:module";
12
- import * as vite2 from "vite";
13
-
14
- // src/node-js-compat.ts
15
- import { createRequire } from "node:module";
16
6
 
17
7
  // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
18
8
  var comma = ",".charCodeAt(0);
@@ -1078,7 +1068,17 @@ var MagicString = class _MagicString {
1078
1068
  }
1079
1069
  };
1080
1070
 
1071
+ // src/index.ts
1072
+ import { Miniflare } from "miniflare";
1073
+ import * as vite6 from "vite";
1074
+
1075
+ // src/cloudflare-environment.ts
1076
+ import assert from "node:assert";
1077
+ import { builtinModules } from "node:module";
1078
+ import * as vite2 from "vite";
1079
+
1081
1080
  // src/node-js-compat.ts
1081
+ import { createRequire } from "node:module";
1082
1082
  import { getNodeCompat } from "miniflare";
1083
1083
  import * as unenv from "unenv";
1084
1084
  var require2 = createRequire(import.meta.url);
@@ -1169,9 +1169,16 @@ function resolveNodeAliases(source, workerConfig) {
1169
1169
  return alias;
1170
1170
  }
1171
1171
 
1172
+ // src/constants.ts
1173
+ var ROUTER_WORKER_NAME = "__router-worker__";
1174
+ var ASSET_WORKER_NAME = "__asset-worker__";
1175
+ var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1176
+ var MODULE_TYPES = ["CompiledWasm"];
1177
+
1172
1178
  // src/shared.ts
1173
1179
  var UNKNOWN_HOST = "http://localhost";
1174
1180
  var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1181
+ var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1175
1182
 
1176
1183
  // src/utils.ts
1177
1184
  import * as path from "node:path";
@@ -1268,7 +1275,10 @@ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
1268
1275
  }
1269
1276
  }
1270
1277
  );
1271
- assert(response.ok, "Failed to initialize module runner");
1278
+ assert(
1279
+ response.ok,
1280
+ `Failed to initialize module runner, error: ${await response.text()}`
1281
+ );
1272
1282
  const webSocket = response.webSocket;
1273
1283
  assert(webSocket, "Failed to establish WebSocket");
1274
1284
  webSocket.accept();
@@ -1281,6 +1291,7 @@ var cloudflareBuiltInModules = [
1281
1291
  "cloudflare:workers",
1282
1292
  "cloudflare:workflows"
1283
1293
  ];
1294
+ var defaultConditions = ["workerd", "module", "browser"];
1284
1295
  function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1285
1296
  return {
1286
1297
  resolve: {
@@ -1288,7 +1299,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1288
1299
  // dependencies as not external
1289
1300
  noExternal: true,
1290
1301
  // We want to use `workerd` package exports if available (e.g. for postgres).
1291
- conditions: ["workerd", "module", "browser", "development|production"]
1302
+ conditions: [...defaultConditions, "development|production"]
1292
1303
  },
1293
1304
  dev: {
1294
1305
  createEnvironment(name2, config) {
@@ -1299,6 +1310,9 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1299
1310
  createEnvironment(name2, config) {
1300
1311
  return new vite2.BuildEnvironment(name2, config);
1301
1312
  },
1313
+ target: "es2022",
1314
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1315
+ emitAssets: true,
1302
1316
  outDir: getOutputDirectory(userConfig, environmentName),
1303
1317
  ssr: true,
1304
1318
  rollupOptions: {
@@ -1320,6 +1334,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1320
1334
  ],
1321
1335
  esbuildOptions: {
1322
1336
  platform: "neutral",
1337
+ conditions: [...defaultConditions, "development"],
1323
1338
  resolveExtensions: [
1324
1339
  ".mjs",
1325
1340
  ".js",
@@ -1430,13 +1445,6 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1430
1445
 
1431
1446
  // src/dev.ts
1432
1447
  import assert3 from "node:assert";
1433
-
1434
- // src/constants.ts
1435
- var ROUTER_WORKER_NAME = "__router-worker__";
1436
- var ASSET_WORKER_NAME = "__asset-worker__";
1437
- var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1438
-
1439
- // src/dev.ts
1440
1448
  function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1441
1449
  const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1442
1450
  assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
@@ -1634,10 +1642,13 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1634
1642
  ];
1635
1643
  const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1636
1644
  ([environmentName, workerConfig]) => {
1637
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions({
1638
- ...workerConfig,
1639
- assets: void 0
1640
- });
1645
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1646
+ {
1647
+ ...workerConfig,
1648
+ assets: void 0
1649
+ },
1650
+ resolvedPluginConfig.cloudflareEnv
1651
+ );
1641
1652
  const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1642
1653
  return {
1643
1654
  ...workerOptions,
@@ -1663,16 +1674,24 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1663
1674
  `Invalid invoke event: ${invokePayloadData.name}`
1664
1675
  );
1665
1676
  const [moduleId] = invokePayloadData.data;
1677
+ const moduleRE = new RegExp(MODULE_PATTERN);
1678
+ if (moduleRE.test(moduleId)) {
1679
+ const result2 = {
1680
+ externalize: moduleId,
1681
+ type: "module"
1682
+ };
1683
+ return MiniflareResponse.json({ result: result2 });
1684
+ }
1666
1685
  if (moduleId.startsWith("cloudflare:")) {
1667
1686
  const result2 = {
1668
1687
  externalize: moduleId,
1669
1688
  type: "builtin"
1670
1689
  };
1671
- return new MiniflareResponse(JSON.stringify({ result: result2 }));
1690
+ return MiniflareResponse.json({ result: result2 });
1672
1691
  }
1673
1692
  const devEnvironment = viteDevServer.environments[environmentName];
1674
1693
  const result = await devEnvironment.hot.handleInvoke(payload);
1675
- return new MiniflareResponse(JSON.stringify(result));
1694
+ return MiniflareResponse.json(result);
1676
1695
  }
1677
1696
  }
1678
1697
  };
@@ -1751,10 +1770,37 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1751
1770
  fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1752
1771
  )
1753
1772
  }
1754
- ]
1773
+ ],
1774
+ unsafeUseModuleFallbackService: true
1755
1775
  };
1756
1776
  })
1757
- ]
1777
+ ],
1778
+ unsafeModuleFallbackService(request) {
1779
+ const url = new URL(request.url);
1780
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
1781
+ assert4(
1782
+ rawSpecifier,
1783
+ `Unexpected error: no specifier in request to module fallback service.`
1784
+ );
1785
+ const moduleRE = new RegExp(MODULE_PATTERN);
1786
+ const match = moduleRE.exec(rawSpecifier);
1787
+ assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1788
+ const [full, moduleType, modulePath] = match;
1789
+ assert4(
1790
+ modulePath,
1791
+ `Unexpected error: module path not found in reference ${full}.`
1792
+ );
1793
+ let source;
1794
+ try {
1795
+ source = fs2.readFileSync(modulePath);
1796
+ } catch (error) {
1797
+ throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1798
+ }
1799
+ return MiniflareResponse.json({
1800
+ // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1801
+ wasm: Array.from(source)
1802
+ });
1803
+ }
1758
1804
  };
1759
1805
  }
1760
1806
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
@@ -2061,20 +2107,21 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2061
2107
  const configPaths = /* @__PURE__ */ new Set();
2062
2108
  const persistState = pluginConfig.persistState ?? true;
2063
2109
  const root = userConfig.root ? path5.resolve(userConfig.root) : process.cwd();
2064
- const { CLOUDFLARE_ENV } = vite5.loadEnv(viteEnv.mode, root, "");
2110
+ const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
2111
+ viteEnv.mode,
2112
+ root,
2113
+ /* prefixes */
2114
+ ""
2115
+ );
2065
2116
  const configPath = pluginConfig.configPath ? path5.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
2066
2117
  assert6(
2067
2118
  configPath,
2068
2119
  `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
2069
2120
  );
2070
- const entryWorkerResolvedConfig = getWorkerConfig(
2071
- configPath,
2072
- CLOUDFLARE_ENV,
2073
- {
2074
- visitedConfigPaths: configPaths,
2075
- isEntryWorker: true
2076
- }
2077
- );
2121
+ const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
2122
+ visitedConfigPaths: configPaths,
2123
+ isEntryWorker: true
2124
+ });
2078
2125
  if (entryWorkerResolvedConfig.type === "assets-only") {
2079
2126
  return {
2080
2127
  type: "assets-only",
@@ -2083,7 +2130,8 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2083
2130
  persistState,
2084
2131
  rawConfigs: {
2085
2132
  entryWorker: entryWorkerResolvedConfig
2086
- }
2133
+ },
2134
+ cloudflareEnv
2087
2135
  };
2088
2136
  }
2089
2137
  const entryWorkerConfig = entryWorkerResolvedConfig.config;
@@ -2095,7 +2143,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2095
2143
  for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
2096
2144
  const workerResolvedConfig = getWorkerConfig(
2097
2145
  path5.resolve(root, auxiliaryWorker.configPath),
2098
- CLOUDFLARE_ENV,
2146
+ cloudflareEnv,
2099
2147
  {
2100
2148
  visitedConfigPaths: configPaths
2101
2149
  }
@@ -2123,7 +2171,8 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
2123
2171
  rawConfigs: {
2124
2172
  entryWorker: entryWorkerResolvedConfig,
2125
2173
  auxiliaryWorkers: auxiliaryWorkersResolvedConfigs
2126
- }
2174
+ },
2175
+ cloudflareEnv
2127
2176
  };
2128
2177
  }
2129
2178
 
@@ -2192,211 +2241,326 @@ function cloudflare2(pluginConfig = {}) {
2192
2241
  let resolvedViteConfig;
2193
2242
  let miniflare;
2194
2243
  let workersConfigsWarningShown = false;
2195
- return {
2196
- name: "vite-plugin-cloudflare",
2197
- config(userConfig, env2) {
2198
- if (env2.isPreview) {
2199
- return { appType: "custom" };
2200
- }
2201
- resolvedPluginConfig = resolvePluginConfig(pluginConfig, userConfig, env2);
2202
- if (!workersConfigsWarningShown) {
2203
- workersConfigsWarningShown = true;
2204
- const workersConfigsWarning = getWarningForWorkersConfigs(
2205
- resolvedPluginConfig.rawConfigs
2244
+ return [
2245
+ {
2246
+ name: "vite-plugin-cloudflare",
2247
+ config(userConfig, env2) {
2248
+ if (env2.isPreview) {
2249
+ return { appType: "custom" };
2250
+ }
2251
+ resolvedPluginConfig = resolvePluginConfig(
2252
+ pluginConfig,
2253
+ userConfig,
2254
+ env2
2206
2255
  );
2207
- if (workersConfigsWarning) {
2208
- console.warn(workersConfigsWarning);
2256
+ if (!workersConfigsWarningShown) {
2257
+ workersConfigsWarningShown = true;
2258
+ const workersConfigsWarning = getWarningForWorkersConfigs(
2259
+ resolvedPluginConfig.rawConfigs
2260
+ );
2261
+ if (workersConfigsWarning) {
2262
+ console.warn(workersConfigsWarning);
2263
+ }
2209
2264
  }
2210
- }
2211
- return {
2212
- appType: "custom",
2213
- resolve: {
2214
- alias: getNodeCompatAliases()
2215
- },
2216
- environments: resolvedPluginConfig.type === "workers" ? {
2217
- ...Object.fromEntries(
2218
- Object.entries(resolvedPluginConfig.workers).map(
2219
- ([environmentName, workerConfig]) => {
2220
- return [
2221
- environmentName,
2222
- createCloudflareEnvironmentOptions(
2223
- workerConfig,
2224
- userConfig,
2225
- environmentName
2265
+ return {
2266
+ appType: "custom",
2267
+ resolve: {
2268
+ alias: getNodeCompatAliases()
2269
+ },
2270
+ environments: resolvedPluginConfig.type === "workers" ? {
2271
+ ...Object.fromEntries(
2272
+ Object.entries(resolvedPluginConfig.workers).map(
2273
+ ([environmentName, workerConfig]) => {
2274
+ return [
2275
+ environmentName,
2276
+ createCloudflareEnvironmentOptions(
2277
+ workerConfig,
2278
+ userConfig,
2279
+ environmentName
2280
+ )
2281
+ ];
2282
+ }
2283
+ )
2284
+ ),
2285
+ client: {
2286
+ build: {
2287
+ outDir: getOutputDirectory(userConfig, "client")
2288
+ }
2289
+ }
2290
+ } : void 0,
2291
+ builder: {
2292
+ async buildApp(builder) {
2293
+ const clientEnvironment = builder.environments.client;
2294
+ const defaultHtmlPath = path6.resolve(
2295
+ builder.config.root,
2296
+ "index.html"
2297
+ );
2298
+ if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2299
+ await builder.build(clientEnvironment);
2300
+ }
2301
+ if (resolvedPluginConfig.type === "workers") {
2302
+ const workerEnvironments = Object.keys(
2303
+ resolvedPluginConfig.workers
2304
+ ).map((environmentName) => {
2305
+ const environment = builder.environments[environmentName];
2306
+ assert7(
2307
+ environment,
2308
+ `${environmentName} environment not found`
2309
+ );
2310
+ return environment;
2311
+ });
2312
+ await Promise.all(
2313
+ workerEnvironments.map(
2314
+ (environment) => builder.build(environment)
2226
2315
  )
2227
- ];
2316
+ );
2228
2317
  }
2229
- )
2230
- ),
2231
- client: {
2232
- build: {
2233
- outDir: getOutputDirectory(userConfig, "client")
2318
+ writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2234
2319
  }
2235
2320
  }
2236
- } : void 0,
2237
- builder: {
2238
- async buildApp(builder) {
2239
- const clientEnvironment = builder.environments.client;
2240
- const defaultHtmlPath = path6.resolve(
2241
- builder.config.root,
2242
- "index.html"
2321
+ };
2322
+ },
2323
+ configResolved(config) {
2324
+ resolvedViteConfig = config;
2325
+ },
2326
+ async resolveId(source) {
2327
+ if (resolvedPluginConfig.type === "assets-only") {
2328
+ return;
2329
+ }
2330
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2331
+ if (!workerConfig) {
2332
+ return;
2333
+ }
2334
+ return resolveNodeCompatId(this.environment, workerConfig, source);
2335
+ },
2336
+ async transform(code, id) {
2337
+ if (resolvedPluginConfig.type === "assets-only") {
2338
+ return;
2339
+ }
2340
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2341
+ if (!workerConfig) {
2342
+ return;
2343
+ }
2344
+ const resolvedId = await this.resolve(workerConfig.main);
2345
+ if (id === resolvedId?.id) {
2346
+ return injectGlobalCode(id, code, workerConfig);
2347
+ }
2348
+ },
2349
+ generateBundle(_, bundle) {
2350
+ let config;
2351
+ if (resolvedPluginConfig.type === "workers") {
2352
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2353
+ const entryChunk = Object.entries(bundle).find(
2354
+ ([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
2355
+ );
2356
+ if (!workerConfig || !entryChunk) {
2357
+ return;
2358
+ }
2359
+ workerConfig.main = entryChunk[0];
2360
+ const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2361
+ if (isEntryWorker && workerConfig.assets) {
2362
+ const workerOutputDirectory = this.environment.config.build.outDir;
2363
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
2364
+ assert7(
2365
+ clientOutputDirectory,
2366
+ "Unexpected error: client output directory is undefined"
2243
2367
  );
2244
- if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2245
- await builder.build(clientEnvironment);
2246
- }
2247
- if (resolvedPluginConfig.type === "workers") {
2248
- const workerEnvironments = Object.keys(
2249
- resolvedPluginConfig.workers
2250
- ).map((environmentName) => {
2251
- const environment = builder.environments[environmentName];
2252
- assert7(environment, `${environmentName} environment not found`);
2253
- return environment;
2368
+ workerConfig.assets.directory = path6.relative(
2369
+ path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2370
+ path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2371
+ );
2372
+ }
2373
+ config = workerConfig;
2374
+ if (workerConfig.configPath) {
2375
+ const dotDevDotVarsContent = getDotDevDotVarsContent(
2376
+ workerConfig.configPath,
2377
+ resolvedPluginConfig.cloudflareEnv
2378
+ );
2379
+ if (dotDevDotVarsContent) {
2380
+ this.emitFile({
2381
+ type: "asset",
2382
+ fileName: ".dev.vars",
2383
+ source: dotDevDotVarsContent
2254
2384
  });
2255
- await Promise.all(
2256
- workerEnvironments.map(
2257
- (environment) => builder.build(environment)
2258
- )
2259
- );
2260
2385
  }
2261
- writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2262
2386
  }
2387
+ } else if (this.environment.name === "client") {
2388
+ const assetsOnlyConfig = resolvedPluginConfig.config;
2389
+ assetsOnlyConfig.assets.directory = ".";
2390
+ const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
2391
+ this.emitFile({
2392
+ type: "asset",
2393
+ fileName: ".assetsignore",
2394
+ source: `${filesToAssetsIgnore.join("\n")}
2395
+ `
2396
+ });
2397
+ config = assetsOnlyConfig;
2263
2398
  }
2264
- };
2265
- },
2266
- configResolved(config) {
2267
- resolvedViteConfig = config;
2268
- },
2269
- async resolveId(source) {
2270
- if (resolvedPluginConfig.type === "assets-only") {
2271
- return;
2272
- }
2273
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2274
- if (!workerConfig) {
2275
- return;
2276
- }
2277
- return resolveNodeCompatId(this.environment, workerConfig, source);
2278
- },
2279
- async transform(code, id) {
2280
- if (resolvedPluginConfig.type === "assets-only") {
2281
- return;
2282
- }
2283
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2284
- if (!workerConfig) {
2285
- return;
2286
- }
2287
- const resolvedId = await this.resolve(workerConfig.main);
2288
- if (id === resolvedId?.id) {
2289
- return injectGlobalCode(id, code, workerConfig);
2399
+ if (!config) {
2400
+ return;
2401
+ }
2402
+ config.no_bundle = true;
2403
+ config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2404
+ if (config.unsafe && Object.keys(config.unsafe).length === 0) {
2405
+ config.unsafe = void 0;
2406
+ }
2407
+ this.emitFile({
2408
+ type: "asset",
2409
+ fileName: "wrangler.json",
2410
+ source: JSON.stringify(config)
2411
+ });
2412
+ },
2413
+ handleHotUpdate(options) {
2414
+ if (resolvedPluginConfig.configPaths.has(options.file)) {
2415
+ options.server.restart();
2416
+ }
2417
+ },
2418
+ async buildEnd() {
2419
+ if (miniflare) {
2420
+ await miniflare.dispose();
2421
+ miniflare = void 0;
2422
+ }
2423
+ },
2424
+ async configureServer(viteDevServer) {
2425
+ assert7(
2426
+ viteDevServer.httpServer,
2427
+ "Unexpected error: No Vite HTTP server"
2428
+ );
2429
+ miniflare = new Miniflare(
2430
+ getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2431
+ );
2432
+ await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2433
+ const entryWorker = await getDevEntryWorker(
2434
+ resolvedPluginConfig,
2435
+ miniflare
2436
+ );
2437
+ const middleware = createMiddleware(({ request }) => {
2438
+ return entryWorker.fetch(toMiniflareRequest(request), {
2439
+ redirect: "manual"
2440
+ });
2441
+ });
2442
+ handleWebSocket(
2443
+ viteDevServer.httpServer,
2444
+ entryWorker.fetch,
2445
+ viteDevServer.config.logger
2446
+ );
2447
+ return () => {
2448
+ viteDevServer.middlewares.use((req, res, next) => {
2449
+ middleware(req, res, next);
2450
+ });
2451
+ };
2452
+ },
2453
+ configurePreviewServer(vitePreviewServer) {
2454
+ const miniflare2 = new Miniflare(
2455
+ getPreviewMiniflareOptions(
2456
+ vitePreviewServer,
2457
+ pluginConfig.persistState ?? true
2458
+ )
2459
+ );
2460
+ const middleware = createMiddleware(({ request }) => {
2461
+ return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2462
+ redirect: "manual"
2463
+ });
2464
+ });
2465
+ handleWebSocket(
2466
+ vitePreviewServer.httpServer,
2467
+ miniflare2.dispatchFetch,
2468
+ vitePreviewServer.config.logger
2469
+ );
2470
+ return () => {
2471
+ vitePreviewServer.middlewares.use((req, res, next) => {
2472
+ middleware(req, res, next);
2473
+ });
2474
+ };
2290
2475
  }
2291
2476
  },
2292
- generateBundle(_, bundle) {
2293
- let config;
2294
- if (resolvedPluginConfig.type === "workers") {
2295
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2296
- const entryChunk = Object.entries(bundle).find(
2297
- ([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
2477
+ // Plugin to support `CompiledWasm` modules
2478
+ {
2479
+ name: "vite-plugin-cloudflare:modules",
2480
+ // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
2481
+ // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
2482
+ enforce: "pre",
2483
+ applyToEnvironment(environment) {
2484
+ if (resolvedPluginConfig.type === "assets-only") {
2485
+ return false;
2486
+ }
2487
+ return Object.keys(resolvedPluginConfig.workers).includes(
2488
+ environment.name
2298
2489
  );
2299
- if (!workerConfig || !entryChunk) {
2490
+ },
2491
+ async resolveId(source, importer) {
2492
+ if (!source.endsWith(".wasm")) {
2300
2493
  return;
2301
2494
  }
2302
- workerConfig.main = entryChunk[0];
2303
- const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2304
- if (isEntryWorker && workerConfig.assets) {
2305
- const workerOutputDirectory = this.environment.config.build.outDir;
2306
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
2495
+ const resolved = await this.resolve(source, importer);
2496
+ assert7(
2497
+ resolved,
2498
+ `Unexpected error: could not resolve Wasm module ${source}`
2499
+ );
2500
+ return {
2501
+ external: true,
2502
+ id: createModuleReference("CompiledWasm", resolved.id)
2503
+ };
2504
+ },
2505
+ renderChunk(code, chunk) {
2506
+ const moduleRE = new RegExp(MODULE_PATTERN, "g");
2507
+ let match;
2508
+ let magicString;
2509
+ while (match = moduleRE.exec(code)) {
2510
+ magicString ??= new MagicString(code);
2511
+ const [full, moduleType, modulePath] = match;
2307
2512
  assert7(
2308
- clientOutputDirectory,
2309
- "Unexpected error: client output directory is undefined"
2513
+ modulePath,
2514
+ `Unexpected error: module path not found in reference ${full}.`
2310
2515
  );
2311
- workerConfig.assets.directory = path6.relative(
2312
- path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2313
- path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2516
+ let source;
2517
+ try {
2518
+ source = fs4.readFileSync(modulePath);
2519
+ } catch (error) {
2520
+ throw new Error(
2521
+ `Import ${modulePath} not found. Does the file exist?`
2522
+ );
2523
+ }
2524
+ const referenceId = this.emitFile({
2525
+ type: "asset",
2526
+ name: path6.basename(modulePath),
2527
+ originalFileName: modulePath,
2528
+ source
2529
+ });
2530
+ const emittedFileName = this.getFileName(referenceId);
2531
+ const relativePath = vite6.normalizePath(
2532
+ path6.relative(path6.dirname(chunk.fileName), emittedFileName)
2533
+ );
2534
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2535
+ magicString.update(
2536
+ match.index,
2537
+ match.index + full.length,
2538
+ importPath
2314
2539
  );
2315
2540
  }
2316
- config = workerConfig;
2317
- } else if (this.environment.name === "client") {
2318
- const assetsOnlyConfig = resolvedPluginConfig.config;
2319
- assetsOnlyConfig.assets.directory = ".";
2320
- this.emitFile({
2321
- type: "asset",
2322
- fileName: ".assetsignore",
2323
- source: "wrangler.json"
2324
- });
2325
- config = assetsOnlyConfig;
2326
- }
2327
- if (!config) {
2328
- return;
2329
- }
2330
- config.no_bundle = true;
2331
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2332
- config.unsafe = void 0;
2333
- this.emitFile({
2334
- type: "asset",
2335
- fileName: "wrangler.json",
2336
- source: JSON.stringify(config)
2337
- });
2338
- },
2339
- handleHotUpdate(options) {
2340
- if (resolvedPluginConfig.configPaths.has(options.file)) {
2341
- options.server.restart();
2342
- }
2343
- },
2344
- async buildEnd() {
2345
- if (miniflare) {
2346
- await miniflare.dispose();
2347
- miniflare = void 0;
2541
+ if (magicString) {
2542
+ return {
2543
+ code: magicString.toString(),
2544
+ map: this.environment.config.build.sourcemap ? magicString.generateMap({ hires: "boundary" }) : null
2545
+ };
2546
+ }
2348
2547
  }
2349
- },
2350
- async configureServer(viteDevServer) {
2351
- assert7(viteDevServer.httpServer, "Unexpected error: No Vite HTTP server");
2352
- miniflare = new Miniflare(
2353
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2354
- );
2355
- await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2356
- const entryWorker = await getDevEntryWorker(
2357
- resolvedPluginConfig,
2358
- miniflare
2359
- );
2360
- const middleware = createMiddleware(({ request }) => {
2361
- return entryWorker.fetch(toMiniflareRequest(request), {
2362
- redirect: "manual"
2363
- });
2364
- });
2365
- handleWebSocket(
2366
- viteDevServer.httpServer,
2367
- entryWorker.fetch,
2368
- viteDevServer.config.logger
2369
- );
2370
- return () => {
2371
- viteDevServer.middlewares.use((req, res, next) => {
2372
- middleware(req, res, next);
2373
- });
2374
- };
2375
- },
2376
- configurePreviewServer(vitePreviewServer) {
2377
- const miniflare2 = new Miniflare(
2378
- getPreviewMiniflareOptions(
2379
- vitePreviewServer,
2380
- pluginConfig.persistState ?? true
2381
- )
2382
- );
2383
- const middleware = createMiddleware(({ request }) => {
2384
- return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2385
- redirect: "manual"
2386
- });
2387
- });
2388
- handleWebSocket(
2389
- vitePreviewServer.httpServer,
2390
- miniflare2.dispatchFetch,
2391
- vitePreviewServer.config.logger
2392
- );
2393
- return () => {
2394
- vitePreviewServer.middlewares.use((req, res, next) => {
2395
- middleware(req, res, next);
2396
- });
2397
- };
2398
2548
  }
2399
- };
2549
+ ];
2550
+ }
2551
+ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2552
+ const configDir = path6.dirname(configPath);
2553
+ const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
2554
+ const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
2555
+ const targetPath = fs4.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs4.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
2556
+ if (targetPath) {
2557
+ const dotDevDotVarsContent = fs4.readFileSync(targetPath);
2558
+ return dotDevDotVarsContent;
2559
+ }
2560
+ return null;
2561
+ }
2562
+ function createModuleReference(type, id) {
2563
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
2400
2564
  }
2401
2565
  export {
2402
2566
  cloudflare2 as cloudflare