@cloudflare/vite-plugin 0.0.0-01edd2807 → 0.0.0-027698c05

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";
@@ -1284,6 +1291,7 @@ var cloudflareBuiltInModules = [
1284
1291
  "cloudflare:workers",
1285
1292
  "cloudflare:workflows"
1286
1293
  ];
1294
+ var defaultConditions = ["workerd", "module", "browser"];
1287
1295
  function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1288
1296
  return {
1289
1297
  resolve: {
@@ -1291,7 +1299,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1291
1299
  // dependencies as not external
1292
1300
  noExternal: true,
1293
1301
  // We want to use `workerd` package exports if available (e.g. for postgres).
1294
- conditions: ["workerd", "module", "browser", "development|production"]
1302
+ conditions: [...defaultConditions, "development|production"]
1295
1303
  },
1296
1304
  dev: {
1297
1305
  createEnvironment(name2, config) {
@@ -1302,6 +1310,9 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1302
1310
  createEnvironment(name2, config) {
1303
1311
  return new vite2.BuildEnvironment(name2, config);
1304
1312
  },
1313
+ target: "es2022",
1314
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1315
+ emitAssets: true,
1305
1316
  outDir: getOutputDirectory(userConfig, environmentName),
1306
1317
  ssr: true,
1307
1318
  rollupOptions: {
@@ -1323,6 +1334,7 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
1323
1334
  ],
1324
1335
  esbuildOptions: {
1325
1336
  platform: "neutral",
1337
+ conditions: [...defaultConditions, "development"],
1326
1338
  resolveExtensions: [
1327
1339
  ".mjs",
1328
1340
  ".js",
@@ -1433,13 +1445,6 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1433
1445
 
1434
1446
  // src/dev.ts
1435
1447
  import assert3 from "node:assert";
1436
-
1437
- // src/constants.ts
1438
- var ROUTER_WORKER_NAME = "__router-worker__";
1439
- var ASSET_WORKER_NAME = "__asset-worker__";
1440
- var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1441
-
1442
- // src/dev.ts
1443
1448
  function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1444
1449
  const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1445
1450
  assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
@@ -1669,16 +1674,24 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1669
1674
  `Invalid invoke event: ${invokePayloadData.name}`
1670
1675
  );
1671
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
+ }
1672
1685
  if (moduleId.startsWith("cloudflare:")) {
1673
1686
  const result2 = {
1674
1687
  externalize: moduleId,
1675
1688
  type: "builtin"
1676
1689
  };
1677
- return new MiniflareResponse(JSON.stringify({ result: result2 }));
1690
+ return MiniflareResponse.json({ result: result2 });
1678
1691
  }
1679
1692
  const devEnvironment = viteDevServer.environments[environmentName];
1680
1693
  const result = await devEnvironment.hot.handleInvoke(payload);
1681
- return new MiniflareResponse(JSON.stringify(result));
1694
+ return MiniflareResponse.json(result);
1682
1695
  }
1683
1696
  }
1684
1697
  };
@@ -1757,10 +1770,37 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1757
1770
  fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1758
1771
  )
1759
1772
  }
1760
- ]
1773
+ ],
1774
+ unsafeUseModuleFallbackService: true
1761
1775
  };
1762
1776
  })
1763
- ]
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
+ }
1764
1804
  };
1765
1805
  }
1766
1806
  function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
@@ -2176,8 +2216,10 @@ ${event.error?.stack || event.error?.message}`,
2176
2216
  workerWebSocket.addEventListener("close", () => {
2177
2217
  clientWebSocket.close();
2178
2218
  });
2179
- clientWebSocket.on("message", (event) => {
2180
- workerWebSocket.send(event);
2219
+ clientWebSocket.on("message", (data, isBinary) => {
2220
+ workerWebSocket.send(
2221
+ isBinary ? Array.isArray(data) ? Buffer.concat(data) : data : data.toString()
2222
+ );
2181
2223
  });
2182
2224
  clientWebSocket.on("error", (error) => {
2183
2225
  logger.error(`WebSocket error:
@@ -2201,228 +2243,312 @@ function cloudflare2(pluginConfig = {}) {
2201
2243
  let resolvedViteConfig;
2202
2244
  let miniflare;
2203
2245
  let workersConfigsWarningShown = false;
2204
- return {
2205
- name: "vite-plugin-cloudflare",
2206
- config(userConfig, env2) {
2207
- if (env2.isPreview) {
2208
- return { appType: "custom" };
2209
- }
2210
- resolvedPluginConfig = resolvePluginConfig(pluginConfig, userConfig, env2);
2211
- if (!workersConfigsWarningShown) {
2212
- workersConfigsWarningShown = true;
2213
- const workersConfigsWarning = getWarningForWorkersConfigs(
2214
- resolvedPluginConfig.rawConfigs
2246
+ return [
2247
+ {
2248
+ name: "vite-plugin-cloudflare",
2249
+ config(userConfig, env2) {
2250
+ if (env2.isPreview) {
2251
+ return { appType: "custom" };
2252
+ }
2253
+ resolvedPluginConfig = resolvePluginConfig(
2254
+ pluginConfig,
2255
+ userConfig,
2256
+ env2
2215
2257
  );
2216
- if (workersConfigsWarning) {
2217
- console.warn(workersConfigsWarning);
2258
+ if (!workersConfigsWarningShown) {
2259
+ workersConfigsWarningShown = true;
2260
+ const workersConfigsWarning = getWarningForWorkersConfigs(
2261
+ resolvedPluginConfig.rawConfigs
2262
+ );
2263
+ if (workersConfigsWarning) {
2264
+ console.warn(workersConfigsWarning);
2265
+ }
2218
2266
  }
2219
- }
2220
- return {
2221
- appType: "custom",
2222
- resolve: {
2223
- alias: getNodeCompatAliases()
2224
- },
2225
- environments: resolvedPluginConfig.type === "workers" ? {
2226
- ...Object.fromEntries(
2227
- Object.entries(resolvedPluginConfig.workers).map(
2228
- ([environmentName, workerConfig]) => {
2229
- return [
2230
- environmentName,
2231
- createCloudflareEnvironmentOptions(
2232
- workerConfig,
2233
- userConfig,
2234
- environmentName
2267
+ return {
2268
+ appType: "custom",
2269
+ resolve: {
2270
+ alias: getNodeCompatAliases()
2271
+ },
2272
+ environments: resolvedPluginConfig.type === "workers" ? {
2273
+ ...Object.fromEntries(
2274
+ Object.entries(resolvedPluginConfig.workers).map(
2275
+ ([environmentName, workerConfig]) => {
2276
+ return [
2277
+ environmentName,
2278
+ createCloudflareEnvironmentOptions(
2279
+ workerConfig,
2280
+ userConfig,
2281
+ environmentName
2282
+ )
2283
+ ];
2284
+ }
2285
+ )
2286
+ ),
2287
+ client: {
2288
+ build: {
2289
+ outDir: getOutputDirectory(userConfig, "client")
2290
+ }
2291
+ }
2292
+ } : void 0,
2293
+ builder: {
2294
+ async buildApp(builder) {
2295
+ const clientEnvironment = builder.environments.client;
2296
+ const defaultHtmlPath = path6.resolve(
2297
+ builder.config.root,
2298
+ "index.html"
2299
+ );
2300
+ if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2301
+ await builder.build(clientEnvironment);
2302
+ }
2303
+ if (resolvedPluginConfig.type === "workers") {
2304
+ const workerEnvironments = Object.keys(
2305
+ resolvedPluginConfig.workers
2306
+ ).map((environmentName) => {
2307
+ const environment = builder.environments[environmentName];
2308
+ assert7(
2309
+ environment,
2310
+ `${environmentName} environment not found`
2311
+ );
2312
+ return environment;
2313
+ });
2314
+ await Promise.all(
2315
+ workerEnvironments.map(
2316
+ (environment) => builder.build(environment)
2235
2317
  )
2236
- ];
2318
+ );
2237
2319
  }
2238
- )
2239
- ),
2240
- client: {
2241
- build: {
2242
- outDir: getOutputDirectory(userConfig, "client")
2320
+ writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2243
2321
  }
2244
2322
  }
2245
- } : void 0,
2246
- builder: {
2247
- async buildApp(builder) {
2248
- const clientEnvironment = builder.environments.client;
2249
- const defaultHtmlPath = path6.resolve(
2250
- builder.config.root,
2251
- "index.html"
2323
+ };
2324
+ },
2325
+ configResolved(config) {
2326
+ resolvedViteConfig = config;
2327
+ },
2328
+ async resolveId(source) {
2329
+ if (resolvedPluginConfig.type === "assets-only") {
2330
+ return;
2331
+ }
2332
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2333
+ if (!workerConfig) {
2334
+ return;
2335
+ }
2336
+ return resolveNodeCompatId(this.environment, workerConfig, source);
2337
+ },
2338
+ async transform(code, id) {
2339
+ if (resolvedPluginConfig.type === "assets-only") {
2340
+ return;
2341
+ }
2342
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2343
+ if (!workerConfig) {
2344
+ return;
2345
+ }
2346
+ const resolvedId = await this.resolve(workerConfig.main);
2347
+ if (id === resolvedId?.id) {
2348
+ return injectGlobalCode(id, code, workerConfig);
2349
+ }
2350
+ },
2351
+ generateBundle(_, bundle) {
2352
+ let config;
2353
+ if (resolvedPluginConfig.type === "workers") {
2354
+ const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2355
+ const entryChunk = Object.entries(bundle).find(
2356
+ ([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
2357
+ );
2358
+ if (!workerConfig || !entryChunk) {
2359
+ return;
2360
+ }
2361
+ workerConfig.main = entryChunk[0];
2362
+ const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2363
+ if (isEntryWorker && workerConfig.assets) {
2364
+ const workerOutputDirectory = this.environment.config.build.outDir;
2365
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
2366
+ assert7(
2367
+ clientOutputDirectory,
2368
+ "Unexpected error: client output directory is undefined"
2252
2369
  );
2253
- if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
2254
- await builder.build(clientEnvironment);
2255
- }
2256
- if (resolvedPluginConfig.type === "workers") {
2257
- const workerEnvironments = Object.keys(
2258
- resolvedPluginConfig.workers
2259
- ).map((environmentName) => {
2260
- const environment = builder.environments[environmentName];
2261
- assert7(environment, `${environmentName} environment not found`);
2262
- return environment;
2370
+ workerConfig.assets.directory = path6.relative(
2371
+ path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2372
+ path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2373
+ );
2374
+ }
2375
+ config = workerConfig;
2376
+ if (workerConfig.configPath) {
2377
+ const dotDevDotVarsContent = getDotDevDotVarsContent(
2378
+ workerConfig.configPath,
2379
+ resolvedPluginConfig.cloudflareEnv
2380
+ );
2381
+ if (dotDevDotVarsContent) {
2382
+ this.emitFile({
2383
+ type: "asset",
2384
+ fileName: ".dev.vars",
2385
+ source: dotDevDotVarsContent
2263
2386
  });
2264
- await Promise.all(
2265
- workerEnvironments.map(
2266
- (environment) => builder.build(environment)
2267
- )
2268
- );
2269
2387
  }
2270
- writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
2271
2388
  }
2389
+ } else if (this.environment.name === "client") {
2390
+ const assetsOnlyConfig = resolvedPluginConfig.config;
2391
+ assetsOnlyConfig.assets.directory = ".";
2392
+ const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
2393
+ this.emitFile({
2394
+ type: "asset",
2395
+ fileName: ".assetsignore",
2396
+ source: `${filesToAssetsIgnore.join("\n")}
2397
+ `
2398
+ });
2399
+ config = assetsOnlyConfig;
2272
2400
  }
2273
- };
2274
- },
2275
- configResolved(config) {
2276
- resolvedViteConfig = config;
2277
- },
2278
- async resolveId(source) {
2279
- if (resolvedPluginConfig.type === "assets-only") {
2280
- return;
2281
- }
2282
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2283
- if (!workerConfig) {
2284
- return;
2285
- }
2286
- return resolveNodeCompatId(this.environment, workerConfig, source);
2287
- },
2288
- async transform(code, id) {
2289
- if (resolvedPluginConfig.type === "assets-only") {
2290
- return;
2291
- }
2292
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2293
- if (!workerConfig) {
2294
- return;
2295
- }
2296
- const resolvedId = await this.resolve(workerConfig.main);
2297
- if (id === resolvedId?.id) {
2298
- return injectGlobalCode(id, code, workerConfig);
2401
+ if (!config) {
2402
+ return;
2403
+ }
2404
+ config.no_bundle = true;
2405
+ config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2406
+ if (config.unsafe && Object.keys(config.unsafe).length === 0) {
2407
+ config.unsafe = void 0;
2408
+ }
2409
+ this.emitFile({
2410
+ type: "asset",
2411
+ fileName: "wrangler.json",
2412
+ source: JSON.stringify(config)
2413
+ });
2414
+ },
2415
+ handleHotUpdate(options) {
2416
+ if (resolvedPluginConfig.configPaths.has(options.file)) {
2417
+ options.server.restart();
2418
+ }
2419
+ },
2420
+ async buildEnd() {
2421
+ if (miniflare) {
2422
+ await miniflare.dispose();
2423
+ miniflare = void 0;
2424
+ }
2425
+ },
2426
+ async configureServer(viteDevServer) {
2427
+ assert7(
2428
+ viteDevServer.httpServer,
2429
+ "Unexpected error: No Vite HTTP server"
2430
+ );
2431
+ miniflare = new Miniflare(
2432
+ getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2433
+ );
2434
+ await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2435
+ const entryWorker = await getDevEntryWorker(
2436
+ resolvedPluginConfig,
2437
+ miniflare
2438
+ );
2439
+ const middleware = createMiddleware(({ request }) => {
2440
+ return entryWorker.fetch(toMiniflareRequest(request), {
2441
+ redirect: "manual"
2442
+ });
2443
+ });
2444
+ handleWebSocket(
2445
+ viteDevServer.httpServer,
2446
+ entryWorker.fetch,
2447
+ viteDevServer.config.logger
2448
+ );
2449
+ return () => {
2450
+ viteDevServer.middlewares.use((req, res, next) => {
2451
+ middleware(req, res, next);
2452
+ });
2453
+ };
2454
+ },
2455
+ configurePreviewServer(vitePreviewServer) {
2456
+ const miniflare2 = new Miniflare(
2457
+ getPreviewMiniflareOptions(
2458
+ vitePreviewServer,
2459
+ pluginConfig.persistState ?? true
2460
+ )
2461
+ );
2462
+ const middleware = createMiddleware(({ request }) => {
2463
+ return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2464
+ redirect: "manual"
2465
+ });
2466
+ });
2467
+ handleWebSocket(
2468
+ vitePreviewServer.httpServer,
2469
+ miniflare2.dispatchFetch,
2470
+ vitePreviewServer.config.logger
2471
+ );
2472
+ return () => {
2473
+ vitePreviewServer.middlewares.use((req, res, next) => {
2474
+ middleware(req, res, next);
2475
+ });
2476
+ };
2299
2477
  }
2300
2478
  },
2301
- generateBundle(_, bundle) {
2302
- let config;
2303
- if (resolvedPluginConfig.type === "workers") {
2304
- const workerConfig = resolvedPluginConfig.workers[this.environment.name];
2305
- const entryChunk = Object.entries(bundle).find(
2306
- ([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
2479
+ // Plugin to support `CompiledWasm` modules
2480
+ {
2481
+ name: "vite-plugin-cloudflare:modules",
2482
+ // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
2483
+ // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
2484
+ enforce: "pre",
2485
+ applyToEnvironment(environment) {
2486
+ if (resolvedPluginConfig.type === "assets-only") {
2487
+ return false;
2488
+ }
2489
+ return Object.keys(resolvedPluginConfig.workers).includes(
2490
+ environment.name
2307
2491
  );
2308
- if (!workerConfig || !entryChunk) {
2492
+ },
2493
+ async resolveId(source, importer) {
2494
+ if (!source.endsWith(".wasm")) {
2309
2495
  return;
2310
2496
  }
2311
- workerConfig.main = entryChunk[0];
2312
- const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
2313
- if (isEntryWorker && workerConfig.assets) {
2314
- const workerOutputDirectory = this.environment.config.build.outDir;
2315
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
2497
+ const resolved = await this.resolve(source, importer);
2498
+ assert7(
2499
+ resolved,
2500
+ `Unexpected error: could not resolve Wasm module ${source}`
2501
+ );
2502
+ return {
2503
+ external: true,
2504
+ id: createModuleReference("CompiledWasm", resolved.id)
2505
+ };
2506
+ },
2507
+ renderChunk(code, chunk) {
2508
+ const moduleRE = new RegExp(MODULE_PATTERN, "g");
2509
+ let match;
2510
+ let magicString;
2511
+ while (match = moduleRE.exec(code)) {
2512
+ magicString ??= new MagicString(code);
2513
+ const [full, moduleType, modulePath] = match;
2316
2514
  assert7(
2317
- clientOutputDirectory,
2318
- "Unexpected error: client output directory is undefined"
2515
+ modulePath,
2516
+ `Unexpected error: module path not found in reference ${full}.`
2319
2517
  );
2320
- workerConfig.assets.directory = path6.relative(
2321
- path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
2322
- path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
2518
+ let source;
2519
+ try {
2520
+ source = fs4.readFileSync(modulePath);
2521
+ } catch (error) {
2522
+ throw new Error(
2523
+ `Import ${modulePath} not found. Does the file exist?`
2524
+ );
2525
+ }
2526
+ const referenceId = this.emitFile({
2527
+ type: "asset",
2528
+ name: path6.basename(modulePath),
2529
+ originalFileName: modulePath,
2530
+ source
2531
+ });
2532
+ const emittedFileName = this.getFileName(referenceId);
2533
+ const relativePath = vite6.normalizePath(
2534
+ path6.relative(path6.dirname(chunk.fileName), emittedFileName)
2323
2535
  );
2324
- }
2325
- config = workerConfig;
2326
- if (workerConfig.configPath) {
2327
- const dotDevDotVarsContent = getDotDevDotVarsContent(
2328
- workerConfig.configPath,
2329
- resolvedPluginConfig.cloudflareEnv
2536
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2537
+ magicString.update(
2538
+ match.index,
2539
+ match.index + full.length,
2540
+ importPath
2330
2541
  );
2331
- if (dotDevDotVarsContent) {
2332
- this.emitFile({
2333
- type: "asset",
2334
- fileName: ".dev.vars",
2335
- source: dotDevDotVarsContent
2336
- });
2337
- }
2338
2542
  }
2339
- } else if (this.environment.name === "client") {
2340
- const assetsOnlyConfig = resolvedPluginConfig.config;
2341
- assetsOnlyConfig.assets.directory = ".";
2342
- const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
2343
- this.emitFile({
2344
- type: "asset",
2345
- fileName: ".assetsignore",
2346
- source: `${filesToAssetsIgnore.join("\n")}
2347
- `
2348
- });
2349
- config = assetsOnlyConfig;
2350
- }
2351
- if (!config) {
2352
- return;
2353
- }
2354
- config.no_bundle = true;
2355
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
2356
- if (config.unsafe && Object.keys(config.unsafe).length === 0) {
2357
- config.unsafe = void 0;
2358
- }
2359
- this.emitFile({
2360
- type: "asset",
2361
- fileName: "wrangler.json",
2362
- source: JSON.stringify(config)
2363
- });
2364
- },
2365
- handleHotUpdate(options) {
2366
- if (resolvedPluginConfig.configPaths.has(options.file)) {
2367
- options.server.restart();
2368
- }
2369
- },
2370
- async buildEnd() {
2371
- if (miniflare) {
2372
- await miniflare.dispose();
2373
- miniflare = void 0;
2543
+ if (magicString) {
2544
+ return {
2545
+ code: magicString.toString(),
2546
+ map: this.environment.config.build.sourcemap ? magicString.generateMap({ hires: "boundary" }) : null
2547
+ };
2548
+ }
2374
2549
  }
2375
- },
2376
- async configureServer(viteDevServer) {
2377
- assert7(viteDevServer.httpServer, "Unexpected error: No Vite HTTP server");
2378
- miniflare = new Miniflare(
2379
- getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
2380
- );
2381
- await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
2382
- const entryWorker = await getDevEntryWorker(
2383
- resolvedPluginConfig,
2384
- miniflare
2385
- );
2386
- const middleware = createMiddleware(({ request }) => {
2387
- return entryWorker.fetch(toMiniflareRequest(request), {
2388
- redirect: "manual"
2389
- });
2390
- });
2391
- handleWebSocket(
2392
- viteDevServer.httpServer,
2393
- entryWorker.fetch,
2394
- viteDevServer.config.logger
2395
- );
2396
- return () => {
2397
- viteDevServer.middlewares.use((req, res, next) => {
2398
- middleware(req, res, next);
2399
- });
2400
- };
2401
- },
2402
- configurePreviewServer(vitePreviewServer) {
2403
- const miniflare2 = new Miniflare(
2404
- getPreviewMiniflareOptions(
2405
- vitePreviewServer,
2406
- pluginConfig.persistState ?? true
2407
- )
2408
- );
2409
- const middleware = createMiddleware(({ request }) => {
2410
- return miniflare2.dispatchFetch(toMiniflareRequest(request), {
2411
- redirect: "manual"
2412
- });
2413
- });
2414
- handleWebSocket(
2415
- vitePreviewServer.httpServer,
2416
- miniflare2.dispatchFetch,
2417
- vitePreviewServer.config.logger
2418
- );
2419
- return () => {
2420
- vitePreviewServer.middlewares.use((req, res, next) => {
2421
- middleware(req, res, next);
2422
- });
2423
- };
2424
2550
  }
2425
- };
2551
+ ];
2426
2552
  }
2427
2553
  function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2428
2554
  const configDir = path6.dirname(configPath);
@@ -2435,6 +2561,9 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
2435
2561
  }
2436
2562
  return null;
2437
2563
  }
2564
+ function createModuleReference(type, id) {
2565
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
2566
+ }
2438
2567
  export {
2439
2568
  cloudflare2 as cloudflare
2440
2569
  };