@depup/cloudflare__vite-plugin 1.57.3-depup.1 → 1.58.0-depup.0

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/README.md CHANGED
@@ -13,7 +13,7 @@ npm install @depup/cloudflare__vite-plugin
13
13
 
14
14
  | Field | Value |
15
15
  |-------|-------|
16
- | Original | [@cloudflare/vite-plugin](https://www.npmjs.com/package/@cloudflare/vite-plugin) @ 1.57.3 |
16
+ | Original | [@cloudflare/vite-plugin](https://www.npmjs.com/package/@cloudflare/vite-plugin) @ 1.58.0 |
17
17
  | Processed | 2026-09-23 |
18
18
  | Smoke test | failed |
19
19
  | Deps updated | 2 |
package/changes.json CHANGED
@@ -9,6 +9,6 @@
9
9
  "to": "^8.21.3"
10
10
  }
11
11
  },
12
- "timestamp": "2026-09-23T08:11:57.633Z",
12
+ "timestamp": "2026-09-23T16:10:20.092Z",
13
13
  "totalUpdated": 2
14
14
  }
package/dist/index.d.mts CHANGED
@@ -103,14 +103,14 @@ interface ExperimentalNewConfig {
103
103
  /** Options for type generation. */
104
104
  types?: {
105
105
  /**
106
- * Whether to auto-generate `worker-configuration.d.ts` at the project
107
- * root. Defaults to `true`.
106
+ * Whether to auto-generate `.cloudflare/types/index.d.ts`. Defaults to
107
+ * `true`.
108
108
  */
109
109
  generate?: boolean;
110
110
  /**
111
111
  * Whether to include the Worker's runtime types (generated from the
112
112
  * project's compatibility date and flags) in the generated
113
- * `worker-configuration.d.ts`. Defaults to `true`.
113
+ * `.cloudflare/types/index.d.ts`. Defaults to `true`.
114
114
  */
115
115
  includeRuntime?: boolean;
116
116
  };
package/dist/index.mjs CHANGED
@@ -56718,7 +56718,7 @@ var import_dist = (/* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/ts-d
56718
56718
  exports$1.dedent = dedent$1$1;
56719
56719
  }) }))();
56720
56720
  /**
56721
- * Generate the content for worker-configuration.d.ts
56721
+ * Generate the content for a Worker types declaration file.
56722
56722
  *
56723
56723
  * @example
56724
56724
  * ```typescript
@@ -56726,10 +56726,10 @@ var import_dist = (/* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/ts-d
56726
56726
  * import { writeFileSync } from "node:fs";
56727
56727
  *
56728
56728
  * const content = generateTypes({
56729
- * configPath: "./cloudflare.config.ts",
56729
+ * configPath: "../../cloudflare.config.ts",
56730
56730
  * });
56731
56731
  *
56732
- * writeFileSync("worker-configuration.d.ts", content);
56732
+ * writeFileSync(".cloudflare/types/index.d.ts", content);
56733
56733
  * ```
56734
56734
  */
56735
56735
  function generateTypes({ configPath, packageName = "@cloudflare/config" }) {
@@ -65406,7 +65406,6 @@ async function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
65406
65406
  const result = await loadNewConfig({
65407
65407
  root,
65408
65408
  mode: viteEnv.mode,
65409
- command: viteEnv.command,
65410
65409
  types: resolvedNewConfig.types
65411
65410
  });
65412
65411
  configPath = result.configPath;
@@ -65537,7 +65536,7 @@ function resolveWorker(workerConfig, devOnly, parsedNewWorkerConfig) {
65537
65536
  };
65538
65537
  }
65539
65538
  const NEW_CONFIG_FILENAME = "cloudflare.config.ts";
65540
- const TYPES_OUTPUT_FILENAME = "worker-configuration.d.ts";
65539
+ const TYPES_OUTPUT_PATH = ".cloudflare/types/index.d.ts";
65541
65540
  const EXPERIMENTAL_CONFIG_PKG = "@cloudflare/vite-plugin/experimental-config";
65542
65541
  /**
65543
65542
  * Load and convert a `cloudflare.config.ts` file via `@cloudflare/config`. Returns
@@ -65546,9 +65545,8 @@ const EXPERIMENTAL_CONFIG_PKG = "@cloudflare/vite-plugin/experimental-config";
65546
65545
  * file, and the set of files imported while resolving the config (for
65547
65546
  * watch-mode).
65548
65547
  *
65549
- * When `types.generate` is true, also writes `worker-configuration.d.ts` next
65550
- * to the config when the generated content differs from what's already on disk.
65551
- * Type generation only runs in dev.
65548
+ * When `types.generate` is true, also writes `.cloudflare/types/index.d.ts`
65549
+ * when the generated content differs from what's already on disk.
65552
65550
  */
65553
65551
  async function loadNewConfig(options) {
65554
65552
  const configPath = path.resolve(options.root, NEW_CONFIG_FILENAME);
@@ -65561,7 +65559,7 @@ async function loadNewConfig(options) {
65561
65559
  const worker = result.data.worker;
65562
65560
  if (worker === void 0) throw new Error(`\`${NEW_CONFIG_FILENAME}\` must define a Worker using the \`worker\` property.`);
65563
65561
  const rawConfig = convertToWranglerConfig(result.data);
65564
- if (options.command === "serve" && options.types.generate) await writeWorkerConfigurationDts({
65562
+ if (options.types.generate) await writeCloudflareTypes({
65565
65563
  root: options.root,
65566
65564
  configPath,
65567
65565
  includeRuntime: options.types.includeRuntime,
@@ -65576,7 +65574,7 @@ async function loadNewConfig(options) {
65576
65574
  };
65577
65575
  }
65578
65576
  /**
65579
- * Write `worker-configuration.d.ts` to the project root using
65577
+ * Write `.cloudflare/types/index.d.ts` using
65580
65578
  * `@cloudflare/config`'s `generateTypes`, targeting the vite-plugin's
65581
65579
  * `experimental-config` subpath (so users don't need a direct dependency on
65582
65580
  * `@cloudflare/config`).
@@ -65590,15 +65588,17 @@ async function loadNewConfig(options) {
65590
65588
  * check and the diff-before-write (only writes if content differs, to avoid
65591
65589
  * touching mtimes unnecessarily).
65592
65590
  */
65593
- async function writeWorkerConfigurationDts(options) {
65594
- const outputPath = path.resolve(options.root, TYPES_OUTPUT_FILENAME);
65595
- const relativeConfigPath = "./" + path.relative(options.root, options.configPath);
65591
+ async function writeCloudflareTypes(options) {
65592
+ const outputPath = path.resolve(options.root, TYPES_OUTPUT_PATH);
65593
+ const outputDir = path.dirname(outputPath);
65594
+ const relativeConfigPath = vite.normalizePath(path.relative(outputDir, options.configPath));
65595
+ const configImportPath = relativeConfigPath.startsWith(".") ? relativeConfigPath : `./${relativeConfigPath}`;
65596
65596
  let existingContent;
65597
65597
  try {
65598
65598
  existingContent = await fsp.readFile(outputPath, "utf8");
65599
65599
  } catch {}
65600
65600
  let content = generateTypes({
65601
- configPath: relativeConfigPath,
65601
+ configPath: configImportPath,
65602
65602
  packageName: EXPERIMENTAL_CONFIG_PKG
65603
65603
  });
65604
65604
  if (options.includeRuntime) {
@@ -65609,7 +65609,10 @@ async function writeWorkerConfigurationDts(options) {
65609
65609
  });
65610
65610
  content += `\n${runtimeHeader}\n${RUNTIME_TYPES_MARKER}\n${runtimeTypes}`;
65611
65611
  }
65612
- if (existingContent !== content) await fsp.writeFile(outputPath, content);
65612
+ if (existingContent !== content) {
65613
+ await fsp.mkdir(outputDir, { recursive: true });
65614
+ await fsp.writeFile(outputPath, content);
65615
+ }
65613
65616
  }
65614
65617
 
65615
65618
  //#endregion
@@ -79985,6 +79988,79 @@ const generateStaticRoutingRuleMatcher = (rules) => ({ request: request$2 }) =>
79985
79988
  return false;
79986
79989
  };
79987
79990
 
79991
+ //#endregion
79992
+ //#region src/container-cleanup.ts
79993
+ /** Owns Container cleanup for one server session, including failed attempts. */
79994
+ function createContainerCleanup() {
79995
+ const pendingImages = /* @__PURE__ */ new Map();
79996
+ let restarting = false;
79997
+ function cleanupContainerImages() {
79998
+ for (const [dockerPath, imageTags] of pendingImages) if (cleanupContainers(dockerPath, imageTags)) pendingImages.delete(dockerPath);
79999
+ if (pendingImages.size === 0) process.off("exit", cleanupContainerImages);
80000
+ }
80001
+ return {
80002
+ cleanup: cleanupContainerImages,
80003
+ get isRestarting() {
80004
+ return restarting;
80005
+ },
80006
+ async restart(action) {
80007
+ if (restarting) return action();
80008
+ cleanupContainerImages();
80009
+ restarting = true;
80010
+ try {
80011
+ await action();
80012
+ } finally {
80013
+ restarting = false;
80014
+ }
80015
+ },
80016
+ track(dockerPath, imageTags) {
80017
+ const tags = new Set([...pendingImages.get(dockerPath) ?? [], ...imageTags]);
80018
+ if (tags.size === 0) return;
80019
+ pendingImages.set(dockerPath, tags);
80020
+ process.off("exit", cleanupContainerImages);
80021
+ process.on("exit", cleanupContainerImages);
80022
+ }
80023
+ };
80024
+ }
80025
+ /**
80026
+ * Retains Container cleanup across config reloads using Vite's inline plugins.
80027
+ * The state belongs to this server, not the re-evaluated cloudflare() factory.
80028
+ */
80029
+ function getDevContainerCleanup(server) {
80030
+ const pluginName = "vite-plugin-cloudflare:container-cleanup";
80031
+ const retainedPlugin = server.config.plugins.find((plugin$1) => plugin$1.name === pluginName);
80032
+ if (retainedPlugin?.api) return retainedPlugin.api;
80033
+ const cleanup = createContainerCleanup();
80034
+ const plugin = {
80035
+ name: pluginName,
80036
+ api: cleanup,
80037
+ configureServer(nextServer) {
80038
+ attachContainerCleanup(nextServer, cleanup);
80039
+ }
80040
+ };
80041
+ server.config = {
80042
+ ...server.config,
80043
+ inlineConfig: {
80044
+ ...server.config.inlineConfig,
80045
+ plugins: [...server.config.inlineConfig.plugins ?? [], plugin]
80046
+ }
80047
+ };
80048
+ attachContainerCleanup(server, cleanup);
80049
+ return cleanup;
80050
+ }
80051
+ function attachContainerCleanup(server, cleanup) {
80052
+ const restartServer = server.restart.bind(server);
80053
+ server.restart = (...args) => cleanup.restart(() => restartServer(...args));
80054
+ const closeServer = server.close.bind(server);
80055
+ server.close = async () => {
80056
+ try {
80057
+ await closeServer();
80058
+ } finally {
80059
+ if (!cleanup.isRestarting) cleanup.cleanup();
80060
+ }
80061
+ };
80062
+ }
80063
+
79988
80064
  //#endregion
79989
80065
  //#region src/containers.ts
79990
80066
  /**
@@ -80014,20 +80090,15 @@ function normalizeContainerImageUris(containerOptions, accountId, complianceConf
80014
80090
  } : option);
80015
80091
  }
80016
80092
  /**
80017
- * Prepares each Worker's Container images with that Worker's registry account
80018
- * and compliance settings.
80093
+ * Prepares the sidecar and each Worker's Container images with that Worker's
80094
+ * registry account and compliance settings, including Workers whose images
80095
+ * are selected at start time.
80019
80096
  *
80020
80097
  * @param args - Planned images, Docker executable, and Vite logger.
80021
80098
  * @returns No value.
80022
80099
  */
80023
80100
  async function prepareContainerImagesForVite(args) {
80024
- const optionsByWorkerConfig = /* @__PURE__ */ new Map();
80025
- for (const { containerOptions, workerConfig } of args.containerTagToOptionsMap.values()) {
80026
- const options = optionsByWorkerConfig.get(workerConfig) ?? [];
80027
- options.push(containerOptions);
80028
- optionsByWorkerConfig.set(workerConfig, options);
80029
- }
80030
- for (const [workerConfig, plannedOptions] of optionsByWorkerConfig) {
80101
+ for (const [workerConfig, plannedOptions] of args.containerOptionsByWorker) {
80031
80102
  let containerOptions = plannedOptions;
80032
80103
  if (containerOptions.some((options) => "image_uri" in options && isCloudflareRegistryImage(options.image_uri, workerConfig))) {
80033
80104
  const apiToken = process.env.CLOUDFLARE_API_TOKEN;
@@ -85517,7 +85588,7 @@ __name(createWorkerUploadForm, "createWorkerUploadForm");
85517
85588
  //#endregion
85518
85589
  //#region ../remote-bindings/dist/index.mjs
85519
85590
  var import_undici = require_undici();
85520
- var version$2 = "0.0.31";
85591
+ var version$2 = "0.0.32";
85521
85592
  var NoDefaultValueProvided = class extends UserError {
85522
85593
  constructor() {
85523
85594
  super("This command cannot be run in a non-interactive context", { telemetryMessage: "remote bindings prompt default missing" });
@@ -89279,7 +89350,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
89279
89350
  }
89280
89351
  }
89281
89352
  ];
89282
- const containerTagToOptionsMap = /* @__PURE__ */ new Map();
89353
+ const containerOptionsByWorker = /* @__PURE__ */ new Map();
89283
89354
  let containerEngine;
89284
89355
  const workersFromConfig = resolvedPluginConfig.type === "workers" ? await Promise.all([...resolvedPluginConfig.environmentNameToWorkerMap].map(async ([environmentName, worker]) => {
89285
89356
  const bindings = wrangler.unstable_convertConfigBindingsToStartWorkerBindings(worker.config);
@@ -89296,13 +89367,13 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
89296
89367
  if (worker.config.containers?.length && worker.config.dev.enable_containers) {
89297
89368
  containerEngine = resolveDockerHost(getDockerPath());
89298
89369
  containerBuildId = generateContainerBuildId();
89370
+ containerOptionsByWorker.set(worker.config, createContainerDevPlan({
89371
+ containers: worker.config.containers,
89372
+ exports: worker.config.exports,
89373
+ containerBuildId,
89374
+ configPath: worker.config.configPath
89375
+ })?.containerOptions ?? []);
89299
89376
  }
89300
- const containerPlan = worker.config.dev.enable_containers ? createContainerDevPlan({
89301
- containers: worker.config.containers,
89302
- exports: worker.config.exports,
89303
- containerBuildId,
89304
- configPath: worker.config.configPath
89305
- }) : void 0;
89306
89377
  const miniflareWorkerOptions = wrangler.unstable_getMiniflareWorkerOptions({
89307
89378
  ...worker.config,
89308
89379
  assets: void 0
@@ -89310,10 +89381,6 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
89310
89381
  remoteProxyConnectionString: remoteProxySessionData?.session?.remoteProxyConnectionString,
89311
89382
  containerBuildId
89312
89383
  });
89313
- for (const option of containerPlan?.containerOptions ?? []) containerTagToOptionsMap.set(option.image_tag, {
89314
- containerOptions: option,
89315
- workerConfig: worker.config
89316
- });
89317
89384
  const { externalWorkers: externalWorkers$1 } = miniflareWorkerOptions;
89318
89385
  const workerOptions = miniflareWorkerOptions.workerOptions;
89319
89386
  if (workerOptions.browserRendering && getBrowserRenderingHeadfulFromEnv()) workerOptions.browserRendering.headful = true;
@@ -89434,7 +89501,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
89434
89501
  }
89435
89502
  }
89436
89503
  }),
89437
- containerTagToOptionsMap
89504
+ containerOptionsByWorker
89438
89505
  };
89439
89506
  }
89440
89507
  function getPreviewModules(main, modulesRules) {
@@ -89500,7 +89567,7 @@ function getModulesFromManifest(bundle) {
89500
89567
  async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
89501
89568
  const inputInspectorPort = await getInputInspectorPort(ctx, vitePreviewServer);
89502
89569
  const { resolvedPluginConfig, resolvedViteConfig } = ctx;
89503
- const containerTagToOptionsMap = /* @__PURE__ */ new Map();
89570
+ const containerOptionsByWorker = /* @__PURE__ */ new Map();
89504
89571
  let containerEngine;
89505
89572
  const workers = (await Promise.all(resolvedPluginConfig.workers.map(async (previewWorker) => {
89506
89573
  const workerConfig = previewWorker.config;
@@ -89518,21 +89585,17 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
89518
89585
  if (workerConfig.containers?.length && workerConfig.dev.enable_containers) {
89519
89586
  containerEngine = resolveDockerHost(getDockerPath());
89520
89587
  containerBuildId = generateContainerBuildId();
89588
+ containerOptionsByWorker.set(workerConfig, createContainerDevPlan({
89589
+ containers: workerConfig.containers,
89590
+ exports: workerConfig.exports,
89591
+ containerBuildId,
89592
+ configPath: workerConfig.configPath
89593
+ })?.containerOptions ?? []);
89521
89594
  }
89522
- const containerPlan = workerConfig.dev.enable_containers ? createContainerDevPlan({
89523
- containers: workerConfig.containers,
89524
- exports: workerConfig.exports,
89525
- containerBuildId,
89526
- configPath: workerConfig.configPath
89527
- }) : void 0;
89528
89595
  const miniflareWorkerOptions = wrangler.unstable_getMiniflareWorkerOptions(workerConfig, void 0, {
89529
89596
  remoteProxyConnectionString: remoteProxySessionData?.session?.remoteProxyConnectionString,
89530
89597
  containerBuildId
89531
89598
  });
89532
- for (const option of containerPlan?.containerOptions ?? []) containerTagToOptionsMap.set(option.image_tag, {
89533
- containerOptions: option,
89534
- workerConfig
89535
- });
89536
89599
  const { externalWorkers } = miniflareWorkerOptions;
89537
89600
  const { modulesRules,...sourcelessWorkerOptions } = miniflareWorkerOptions.workerOptions;
89538
89601
  const workerOptions = sourcelessWorkerOptions;
@@ -89569,7 +89632,7 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
89569
89632
  containerEngine,
89570
89633
  workers
89571
89634
  }),
89572
- containerTagToOptionsMap
89635
+ containerOptionsByWorker
89573
89636
  };
89574
89637
  }
89575
89638
  /**
@@ -89711,136 +89774,121 @@ function hasSandboxOrigin(origin) {
89711
89774
  //#endregion
89712
89775
  //#region src/plugins/dev.ts
89713
89776
  var import_picocolors$2 = /* @__PURE__ */ __toESM$2(require_picocolors(), 1);
89714
- let exitCallback$2 = () => {};
89715
- process.on("exit", () => {
89716
- exitCallback$2();
89717
- });
89718
89777
  /**
89719
89778
  * Plugin to provide core development functionality
89720
89779
  */
89721
89780
  const devPlugin = createPlugin("dev", (ctx) => {
89722
- let containerImageTags = /* @__PURE__ */ new Set();
89723
- return {
89724
- buildEnd() {
89725
- if (ctx.resolvedViteConfig.command === "serve" && ctx.isRestartingDevServer && containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
89726
- },
89727
- async configureServer(viteDevServer) {
89728
- assertIsNotPreview(ctx);
89729
- const initialOptions = await getDevMiniflareOptions(ctx, viteDevServer);
89730
- let containerTagToOptionsMap = initialOptions.containerTagToOptionsMap;
89731
- await ctx.startOrUpdateMiniflare(initialOptions.miniflareOptions);
89732
- const closeServer = viteDevServer.close.bind(viteDevServer);
89733
- viteDevServer.close = async () => {
89734
- try {
89735
- await closeServer();
89736
- } finally {
89737
- if (!ctx.isRestartingDevServer) {
89738
- if (containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
89739
- try {
89740
- await ctx.disposeMiniflare();
89741
- } catch (error$2) {
89742
- debuglog("Failed to dispose Miniflare instance:", error$2);
89743
- }
89744
- }
89745
- }
89746
- };
89747
- if (viteDevServer.httpServer) viteDevServer.httpServer.on("listening", () => {
89748
- const addr = viteDevServer.httpServer?.address();
89749
- if (typeof addr === "object" && addr !== null) {
89750
- const serverConfig = viteDevServer.config.server;
89751
- ctx.miniflare.publicUrl = buildPublicUrl({
89752
- hostname: typeof serverConfig.host === "string" ? serverConfig.host : void 0,
89753
- port: addr.port,
89754
- secure: !!serverConfig.https
89755
- });
89781
+ return { async configureServer(viteDevServer) {
89782
+ assertIsNotPreview(ctx);
89783
+ const containerCleanup = getDevContainerCleanup(viteDevServer);
89784
+ const initialOptions = await getDevMiniflareOptions(ctx, viteDevServer);
89785
+ let containerOptionsByWorker = initialOptions.containerOptionsByWorker;
89786
+ await ctx.startOrUpdateMiniflare(initialOptions.miniflareOptions);
89787
+ const closeServer = viteDevServer.close.bind(viteDevServer);
89788
+ viteDevServer.close = async () => {
89789
+ try {
89790
+ await closeServer();
89791
+ } finally {
89792
+ if (!ctx.isRestartingDevServer) try {
89793
+ await ctx.disposeMiniflare();
89794
+ } catch (error$2) {
89795
+ debuglog("Failed to dispose Miniflare instance:", error$2);
89756
89796
  }
89757
- });
89758
- if (ctx.resolvedPluginConfig.type === "workers") {
89759
- debuglog("Initializing the Vite module runners");
89797
+ }
89798
+ };
89799
+ if (viteDevServer.httpServer) viteDevServer.httpServer.on("listening", () => {
89800
+ const addr = viteDevServer.httpServer?.address();
89801
+ if (typeof addr === "object" && addr !== null) {
89802
+ const serverConfig = viteDevServer.config.server;
89803
+ ctx.miniflare.publicUrl = buildPublicUrl({
89804
+ hostname: typeof serverConfig.host === "string" ? serverConfig.host : void 0,
89805
+ port: addr.port,
89806
+ secure: !!serverConfig.https
89807
+ });
89808
+ }
89809
+ });
89810
+ if (ctx.resolvedPluginConfig.type === "workers") {
89811
+ debuglog("Initializing the Vite module runners");
89812
+ await initRunners(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
89813
+ const currentWorkerNameToExportTypesMap = await getCurrentWorkerNameToExportTypesMap(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
89814
+ if (compareWorkerNameToExportTypesMaps(ctx.workerNameToExportTypesMap, currentWorkerNameToExportTypesMap)) {
89815
+ ctx.setWorkerNameToExportTypesMap(currentWorkerNameToExportTypesMap);
89816
+ const updatedOptions = await getDevMiniflareOptions(ctx, viteDevServer);
89817
+ containerOptionsByWorker = updatedOptions.containerOptionsByWorker;
89818
+ await ctx.startOrUpdateMiniflare(updatedOptions.miniflareOptions);
89760
89819
  await initRunners(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
89761
- const currentWorkerNameToExportTypesMap = await getCurrentWorkerNameToExportTypesMap(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
89762
- if (compareWorkerNameToExportTypesMaps(ctx.workerNameToExportTypesMap, currentWorkerNameToExportTypesMap)) {
89763
- ctx.setWorkerNameToExportTypesMap(currentWorkerNameToExportTypesMap);
89764
- const updatedOptions = await getDevMiniflareOptions(ctx, viteDevServer);
89765
- containerTagToOptionsMap = updatedOptions.containerTagToOptionsMap;
89766
- await ctx.startOrUpdateMiniflare(updatedOptions.miniflareOptions);
89767
- await initRunners(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
89768
- }
89769
- for (const environmentName of ctx.resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
89770
- const environment = viteDevServer.environments[environmentName];
89771
- assert2(environment, `Expected environment "${environmentName}" to be defined`);
89772
- environment.hot.on("vite-plugin-cloudflare:worker-export-types", async (newExportTypes) => {
89773
- const workerConfig = ctx.getWorkerConfig(environmentName);
89774
- assert2(workerConfig, `Expected workerConfig for environment "${environmentName}" to be defined`);
89775
- const oldExportTypes = ctx.workerNameToExportTypesMap.get(workerConfig.name);
89776
- assert2(oldExportTypes, `Expected export types for Worker "${workerConfig.name}" to be defined`);
89777
- if (compareExportTypes(oldExportTypes, newExportTypes)) {
89778
- viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("Worker exports have changed. Restarting dev server.")));
89779
- await viteDevServer.restart();
89780
- }
89781
- });
89782
- }
89783
- const entryWorkerConfig = ctx.entryWorkerConfig;
89784
- assert2(entryWorkerConfig, `No entry Worker config`);
89785
- const entryWorkerName = entryWorkerConfig.name;
89786
- if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, ctx.miniflare, entryWorkerName);
89787
- const staticRouting = entryWorkerConfig.assets?.run_worker_first === true ? { user_worker: ["/*"] } : ctx.resolvedPluginConfig.staticRouting;
89788
- if (staticRouting) {
89789
- const excludeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.asset_worker ?? []);
89790
- const includeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.user_worker);
89791
- const userWorkerHandler = createRequestHandler(async (request$2) => {
89792
- request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
89793
- return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
89794
- });
89795
- viteDevServer.middlewares.use(async function cloudflarePreMiddleware(req, res, next) {
89796
- assert2(req.url, `req.url not defined`);
89797
- const request$2 = new Request(new URL(req.url, UNKNOWN_HOST));
89798
- if (req[kRequestType] === "asset") next();
89799
- else if (excludeRulesMatcher({ request: request$2 })) {
89800
- req[kRequestType] = "asset";
89801
- next();
89802
- } else if (includeRulesMatcher({ request: request$2 })) userWorkerHandler(req, res, next);
89803
- else next();
89804
- });
89805
- }
89806
- if (containerTagToOptionsMap.size) {
89807
- viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("∷ Building container images for local development...\n")));
89808
- await prepareContainerImagesForVite({
89809
- dockerPath: getDockerPath(),
89810
- containerTagToOptionsMap,
89811
- logger: viteDevServer.config.logger
89812
- });
89813
- containerImageTags = new Set(containerTagToOptionsMap.keys());
89814
- viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("\n⚡️ Containers successfully built. To rebuild your containers during development, restart the Vite dev server (r + enter).")));
89815
- exitCallback$2 = () => {
89816
- if (containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
89817
- };
89818
- }
89819
89820
  }
89820
- return () => {
89821
- if (!satisfiesMinimumViteVersion("7.0.0")) {
89822
- const middlewareStack = viteDevServer.middlewares.stack;
89823
- const preMiddlewareIndex = middlewareStack.findIndex((middleware) => "name" in middleware.handle && middleware.handle.name === "cloudflarePreMiddleware");
89824
- if (preMiddlewareIndex !== -1) {
89825
- const [preMiddleware] = middlewareStack.splice(preMiddlewareIndex, 1);
89826
- assert2(preMiddleware, "Failed to remove cloudflarePreMiddleware from stack");
89827
- const cachedTransformMiddlewareIndex = middlewareStack.findIndex((middleware) => "name" in middleware.handle && middleware.handle.name === "viteCachedTransformMiddleware");
89828
- assert2(cachedTransformMiddlewareIndex !== -1, "Failed to find viteCachedTransformMiddleware");
89829
- middlewareStack.splice(cachedTransformMiddlewareIndex, 0, preMiddleware);
89830
- }
89831
- }
89832
- viteDevServer.middlewares.use(createRequestHandler(async (request$2, req) => {
89833
- if (req[kRequestType] === "asset") {
89834
- request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, ASSET_WORKER_NAME);
89835
- return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
89836
- } else {
89837
- request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, ROUTER_WORKER_NAME);
89838
- return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
89821
+ for (const environmentName of ctx.resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
89822
+ const environment = viteDevServer.environments[environmentName];
89823
+ assert2(environment, `Expected environment "${environmentName}" to be defined`);
89824
+ environment.hot.on("vite-plugin-cloudflare:worker-export-types", async (newExportTypes) => {
89825
+ const workerConfig = ctx.getWorkerConfig(environmentName);
89826
+ assert2(workerConfig, `Expected workerConfig for environment "${environmentName}" to be defined`);
89827
+ const oldExportTypes = ctx.workerNameToExportTypesMap.get(workerConfig.name);
89828
+ assert2(oldExportTypes, `Expected export types for Worker "${workerConfig.name}" to be defined`);
89829
+ if (compareExportTypes(oldExportTypes, newExportTypes)) {
89830
+ viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("Worker exports have changed. Restarting dev server.")));
89831
+ await viteDevServer.restart();
89839
89832
  }
89840
- }));
89841
- };
89833
+ });
89834
+ }
89835
+ const entryWorkerConfig = ctx.entryWorkerConfig;
89836
+ assert2(entryWorkerConfig, `No entry Worker config`);
89837
+ const entryWorkerName = entryWorkerConfig.name;
89838
+ if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, ctx.miniflare, entryWorkerName);
89839
+ const staticRouting = entryWorkerConfig.assets?.run_worker_first === true ? { user_worker: ["/*"] } : ctx.resolvedPluginConfig.staticRouting;
89840
+ if (staticRouting) {
89841
+ const excludeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.asset_worker ?? []);
89842
+ const includeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.user_worker);
89843
+ const userWorkerHandler = createRequestHandler(async (request$2) => {
89844
+ request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
89845
+ return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
89846
+ });
89847
+ viteDevServer.middlewares.use(async function cloudflarePreMiddleware(req, res, next) {
89848
+ assert2(req.url, `req.url not defined`);
89849
+ const request$2 = new Request(new URL(req.url, UNKNOWN_HOST));
89850
+ if (req[kRequestType] === "asset") next();
89851
+ else if (excludeRulesMatcher({ request: request$2 })) {
89852
+ req[kRequestType] = "asset";
89853
+ next();
89854
+ } else if (includeRulesMatcher({ request: request$2 })) userWorkerHandler(req, res, next);
89855
+ else next();
89856
+ });
89857
+ }
89858
+ if (containerOptionsByWorker.size) {
89859
+ viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("∷ Building container images for local development...\n")));
89860
+ await prepareContainerImagesForVite({
89861
+ dockerPath: getDockerPath(),
89862
+ containerOptionsByWorker,
89863
+ logger: viteDevServer.config.logger
89864
+ });
89865
+ containerCleanup.track(getDockerPath(), [...containerOptionsByWorker.values()].flatMap((options) => options.map(({ image_tag }) => image_tag)));
89866
+ viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("\n⚡️ Containers successfully built. To rebuild your containers during development, restart the Vite dev server (r + enter).")));
89867
+ }
89842
89868
  }
89843
- };
89869
+ return () => {
89870
+ if (!satisfiesMinimumViteVersion("7.0.0")) {
89871
+ const middlewareStack = viteDevServer.middlewares.stack;
89872
+ const preMiddlewareIndex = middlewareStack.findIndex((middleware) => "name" in middleware.handle && middleware.handle.name === "cloudflarePreMiddleware");
89873
+ if (preMiddlewareIndex !== -1) {
89874
+ const [preMiddleware] = middlewareStack.splice(preMiddlewareIndex, 1);
89875
+ assert2(preMiddleware, "Failed to remove cloudflarePreMiddleware from stack");
89876
+ const cachedTransformMiddlewareIndex = middlewareStack.findIndex((middleware) => "name" in middleware.handle && middleware.handle.name === "viteCachedTransformMiddleware");
89877
+ assert2(cachedTransformMiddlewareIndex !== -1, "Failed to find viteCachedTransformMiddleware");
89878
+ middlewareStack.splice(cachedTransformMiddlewareIndex, 0, preMiddleware);
89879
+ }
89880
+ }
89881
+ viteDevServer.middlewares.use(createRequestHandler(async (request$2, req) => {
89882
+ if (req[kRequestType] === "asset") {
89883
+ request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, ASSET_WORKER_NAME);
89884
+ return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
89885
+ } else {
89886
+ request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, ROUTER_WORKER_NAME);
89887
+ return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
89888
+ }
89889
+ }));
89890
+ };
89891
+ } };
89844
89892
  });
89845
89893
 
89846
89894
  //#endregion
@@ -89908,16 +89956,16 @@ const nodeJsCompatPlugin = createPlugin("nodejs-compat", (ctx) => {
89908
89956
  }
89909
89957
  };
89910
89958
  });
89911
- let exitCallback$1 = () => {};
89959
+ let exitCallback = () => {};
89912
89960
  process.on("exit", () => {
89913
- exitCallback$1();
89961
+ exitCallback();
89914
89962
  });
89915
89963
  /**
89916
89964
  * Plugin to warn if Node.js APIs are used without enabling the `nodejs_compat` compatibility flag
89917
89965
  */
89918
89966
  const nodeJsCompatWarningsPlugin = createPlugin("nodejs-compat-warnings", (ctx) => {
89919
89967
  const nodeJsCompatWarningsMap = /* @__PURE__ */ new Map();
89920
- exitCallback$1 = () => {
89968
+ exitCallback = () => {
89921
89969
  for (const nodeJsCompatWarnings of nodeJsCompatWarningsMap.values()) nodeJsCompatWarnings.renderWarnings();
89922
89970
  };
89923
89971
  return {
@@ -90116,21 +90164,23 @@ const triggerHandlersPlugin = createPlugin("trigger-handlers", (ctx) => {
90116
90164
  //#endregion
90117
90165
  //#region src/plugins/preview.ts
90118
90166
  var import_picocolors$1 = /* @__PURE__ */ __toESM$2(require_picocolors(), 1);
90119
- let exitCallback = () => {};
90120
- process.on("exit", () => {
90121
- exitCallback();
90122
- });
90123
90167
  /**
90124
90168
  * Plugin to provide core preview functionality
90125
90169
  */
90126
90170
  const previewPlugin = createPlugin("preview", (ctx) => {
90127
90171
  return { async configurePreviewServer(vitePreviewServer) {
90128
90172
  assertIsPreview(ctx);
90173
+ const dockerPath = getDockerPath();
90174
+ const containerCleanup = createContainerCleanup();
90129
90175
  const closePreviewServer = vitePreviewServer.close.bind(vitePreviewServer);
90130
90176
  vitePreviewServer.close = async () => {
90131
- await Promise.all([ctx.disposeMiniflare(), closePreviewServer()]);
90177
+ try {
90178
+ await Promise.all([ctx.disposeMiniflare(), closePreviewServer()]);
90179
+ } finally {
90180
+ containerCleanup.cleanup();
90181
+ }
90132
90182
  };
90133
- const { miniflareOptions, containerTagToOptionsMap } = await getPreviewMiniflareOptions(ctx, vitePreviewServer);
90183
+ const { miniflareOptions, containerOptionsByWorker } = await getPreviewMiniflareOptions(ctx, vitePreviewServer);
90134
90184
  await ctx.startOrUpdateMiniflare(miniflareOptions);
90135
90185
  if (vitePreviewServer.httpServer) vitePreviewServer.httpServer.on("listening", () => {
90136
90186
  const addr = vitePreviewServer.httpServer?.address();
@@ -90143,19 +90193,15 @@ const previewPlugin = createPlugin("preview", (ctx) => {
90143
90193
  });
90144
90194
  }
90145
90195
  });
90146
- if (containerTagToOptionsMap.size) {
90147
- const dockerPath = getDockerPath();
90196
+ if (containerOptionsByWorker.size) {
90148
90197
  vitePreviewServer.config.logger.info(import_picocolors$1.default.dim(import_picocolors$1.default.yellow("∷ Building container images for local preview...\n")));
90149
90198
  await prepareContainerImagesForVite({
90150
90199
  dockerPath,
90151
- containerTagToOptionsMap,
90200
+ containerOptionsByWorker,
90152
90201
  logger: vitePreviewServer.config.logger
90153
90202
  });
90154
- const containerImageTags = new Set(containerTagToOptionsMap.keys());
90203
+ containerCleanup.track(dockerPath, [...containerOptionsByWorker.values()].flatMap((options) => options.map(({ image_tag }) => image_tag)));
90155
90204
  vitePreviewServer.config.logger.info(import_picocolors$1.default.dim(import_picocolors$1.default.yellow("\n⚡️ Containers successfully built.\n")));
90156
- exitCallback = () => {
90157
- if (containerImageTags.size) cleanupContainers(dockerPath, containerImageTags);
90158
- };
90159
90205
  }
90160
90206
  handleWebSocket(vitePreviewServer.httpServer, ctx.miniflare);
90161
90207
  vitePreviewServer.middlewares.use(createRequestHandler((request$2) => {