@cloudflare/vite-plugin 1.7.2 → 1.7.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.
package/dist/index.js CHANGED
@@ -248,17 +248,17 @@ var require_ignore = __commonJS({
248
248
  var throwError = (message, Ctor) => {
249
249
  throw new Ctor(message);
250
250
  };
251
- var checkPath = (path11, originalPath, doThrow) => {
252
- if (!isString(path11)) {
251
+ var checkPath = (path12, originalPath, doThrow) => {
252
+ if (!isString(path12)) {
253
253
  return doThrow(
254
254
  `path must be a string, but got \`${originalPath}\``,
255
255
  TypeError
256
256
  );
257
257
  }
258
- if (!path11) {
258
+ if (!path12) {
259
259
  return doThrow(`path must not be empty`, TypeError);
260
260
  }
261
- if (checkPath.isNotRelative(path11)) {
261
+ if (checkPath.isNotRelative(path12)) {
262
262
  const r2 = "`path.relative()`d";
263
263
  return doThrow(
264
264
  `path should be a ${r2} string, but got "${originalPath}"`,
@@ -267,7 +267,7 @@ var require_ignore = __commonJS({
267
267
  }
268
268
  return true;
269
269
  };
270
- var isNotRelative = (path11) => REGEX_TEST_INVALID_PATH.test(path11);
270
+ var isNotRelative = (path12) => REGEX_TEST_INVALID_PATH.test(path12);
271
271
  checkPath.isNotRelative = isNotRelative;
272
272
  checkPath.convert = (p) => p;
273
273
  var Ignore = class {
@@ -326,7 +326,7 @@ var require_ignore = __commonJS({
326
326
  // setting `checkUnignored` to `false` could reduce additional
327
327
  // path matching.
328
328
  // @returns {TestResult} true if a file is ignored
329
- _testOne(path11, checkUnignored) {
329
+ _testOne(path12, checkUnignored) {
330
330
  let ignored = false;
331
331
  let unignored = false;
332
332
  this._rules.forEach((rule) => {
@@ -334,7 +334,7 @@ var require_ignore = __commonJS({
334
334
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
335
335
  return;
336
336
  }
337
- const matched = rule.regex.test(path11);
337
+ const matched = rule.regex.test(path12);
338
338
  if (matched) {
339
339
  ignored = !negative;
340
340
  unignored = negative;
@@ -347,24 +347,24 @@ var require_ignore = __commonJS({
347
347
  }
348
348
  // @returns {TestResult}
349
349
  _test(originalPath, cache2, checkUnignored, slices) {
350
- const path11 = originalPath && checkPath.convert(originalPath);
350
+ const path12 = originalPath && checkPath.convert(originalPath);
351
351
  checkPath(
352
- path11,
352
+ path12,
353
353
  originalPath,
354
354
  this._allowRelativePaths ? RETURN_FALSE : throwError
355
355
  );
356
- return this._t(path11, cache2, checkUnignored, slices);
356
+ return this._t(path12, cache2, checkUnignored, slices);
357
357
  }
358
- _t(path11, cache2, checkUnignored, slices) {
359
- if (path11 in cache2) {
360
- return cache2[path11];
358
+ _t(path12, cache2, checkUnignored, slices) {
359
+ if (path12 in cache2) {
360
+ return cache2[path12];
361
361
  }
362
362
  if (!slices) {
363
- slices = path11.split(SLASH);
363
+ slices = path12.split(SLASH);
364
364
  }
365
365
  slices.pop();
366
366
  if (!slices.length) {
367
- return cache2[path11] = this._testOne(path11, checkUnignored);
367
+ return cache2[path12] = this._testOne(path12, checkUnignored);
368
368
  }
369
369
  const parent = this._t(
370
370
  slices.join(SLASH) + SLASH,
@@ -372,24 +372,24 @@ var require_ignore = __commonJS({
372
372
  checkUnignored,
373
373
  slices
374
374
  );
375
- return cache2[path11] = parent.ignored ? parent : this._testOne(path11, checkUnignored);
375
+ return cache2[path12] = parent.ignored ? parent : this._testOne(path12, checkUnignored);
376
376
  }
377
- ignores(path11) {
378
- return this._test(path11, this._ignoreCache, false).ignored;
377
+ ignores(path12) {
378
+ return this._test(path12, this._ignoreCache, false).ignored;
379
379
  }
380
380
  createFilter() {
381
- return (path11) => !this.ignores(path11);
381
+ return (path12) => !this.ignores(path12);
382
382
  }
383
383
  filter(paths) {
384
384
  return makeArray(paths).filter(this.createFilter());
385
385
  }
386
386
  // @returns {TestResult}
387
- test(path11) {
388
- return this._test(path11, this._testCache, true);
387
+ test(path12) {
388
+ return this._test(path12, this._testCache, true);
389
389
  }
390
390
  };
391
391
  var factory = (options) => new Ignore(options);
392
- var isPathValid = (path11) => checkPath(path11 && checkPath.convert(path11), path11, RETURN_FALSE);
392
+ var isPathValid = (path12) => checkPath(path12 && checkPath.convert(path12), path12, RETURN_FALSE);
393
393
  factory.isPathValid = isPathValid;
394
394
  factory.default = factory;
395
395
  module.exports = factory;
@@ -400,7 +400,7 @@ var require_ignore = __commonJS({
400
400
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
401
401
  checkPath.convert = makePosix;
402
402
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
403
- checkPath.isNotRelative = (path11) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path11) || isNotRelative(path11);
403
+ checkPath.isNotRelative = (path12) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path12) || isNotRelative(path12);
404
404
  }
405
405
  }
406
406
  });
@@ -443,11 +443,11 @@ var require_Mime = __commonJS({
443
443
  }
444
444
  }
445
445
  };
446
- Mime.prototype.getType = function(path11) {
447
- path11 = String(path11);
448
- let last = path11.replace(/^.*[/\\]/, "").toLowerCase();
446
+ Mime.prototype.getType = function(path12) {
447
+ path12 = String(path12);
448
+ let last = path12.replace(/^.*[/\\]/, "").toLowerCase();
449
449
  let ext = last.replace(/^.*\./, "").toLowerCase();
450
- let hasPath = last.length < path11.length;
450
+ let hasPath = last.length < path12.length;
451
451
  let hasDot = ext.length < last.length - 1;
452
452
  return (hasDot || !hasPath) && this._types[ext] || null;
453
453
  };
@@ -486,9 +486,8 @@ var require_mime = __commonJS({
486
486
 
487
487
  // src/index.ts
488
488
  import assert11 from "node:assert";
489
- import * as fs6 from "node:fs";
490
489
  import * as fsp2 from "node:fs/promises";
491
- import * as path10 from "node:path";
490
+ import * as path11 from "node:path";
492
491
 
493
492
  // ../workers-shared/asset-worker/src/utils/rules-engine.ts
494
493
  var ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
@@ -1583,7 +1582,6 @@ var MagicString = class _MagicString {
1583
1582
 
1584
1583
  // src/index.ts
1585
1584
  import { Miniflare } from "miniflare";
1586
- import colors4 from "picocolors";
1587
1585
  import * as vite6 from "vite";
1588
1586
 
1589
1587
  // src/constants.ts
@@ -1597,6 +1595,7 @@ var ADDITIONAL_MODULE_TYPES = [
1597
1595
  ];
1598
1596
  var PUBLIC_DIR_PREFIX = "/__vite_public_dir__";
1599
1597
  var DEFAULT_INSPECTOR_PORT = 9229;
1598
+ var DEBUG_PATH = "/__debug";
1600
1599
  var kRequestType = Symbol("kRequestType");
1601
1600
 
1602
1601
  // src/additional-modules.ts
@@ -1756,11 +1755,11 @@ ${invalidHeaderRulesList}`
1756
1755
  }
1757
1756
 
1758
1757
  // ../workers-shared/utils/configuration/validateURL.ts
1759
- var extractPathname = (path11 = "/", includeSearch, includeHash) => {
1760
- if (!path11.startsWith("/")) {
1761
- path11 = `/${path11}`;
1758
+ var extractPathname = (path12 = "/", includeSearch, includeHash) => {
1759
+ if (!path12.startsWith("/")) {
1760
+ path12 = `/${path12}`;
1762
1761
  }
1763
- const url = new URL(`//${path11}`, "relative://");
1762
+ const url = new URL(`//${path12}`, "relative://");
1764
1763
  return `${url.pathname}${includeSearch ? url.search : ""}${includeHash ? url.hash : ""}`;
1765
1764
  };
1766
1765
  var URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
@@ -1793,8 +1792,8 @@ var validateUrl = (token, onlyRelative = false, disallowPorts = false, includeSe
1793
1792
  if (!token.startsWith("/") && onlyRelative) {
1794
1793
  token = `/${token}`;
1795
1794
  }
1796
- const path11 = PATH_REGEX.exec(token);
1797
- if (path11) {
1795
+ const path12 = PATH_REGEX.exec(token);
1796
+ if (path12) {
1798
1797
  try {
1799
1798
  return [extractPathname(token, includeSearch, includeHash), void 0];
1800
1799
  } catch {
@@ -1855,7 +1854,7 @@ function parseHeaders(input, {
1855
1854
  });
1856
1855
  }
1857
1856
  }
1858
- const [path11, pathError] = validateUrl(line, false, true);
1857
+ const [path12, pathError] = validateUrl(line, false, true);
1859
1858
  if (pathError) {
1860
1859
  invalid.push({
1861
1860
  line,
@@ -1866,7 +1865,7 @@ function parseHeaders(input, {
1866
1865
  continue;
1867
1866
  }
1868
1867
  rule = {
1869
- path: path11,
1868
+ path: path12,
1870
1869
  line,
1871
1870
  headers: {},
1872
1871
  unsetHeaders: []
@@ -2441,8 +2440,8 @@ function getErrorMap() {
2441
2440
  return overrideErrorMap;
2442
2441
  }
2443
2442
  var makeIssue = (params) => {
2444
- const { data: data2, path: path11, errorMaps, issueData } = params;
2445
- const fullPath = [...path11, ...issueData.path || []];
2443
+ const { data: data2, path: path12, errorMaps, issueData } = params;
2444
+ const fullPath = [...path12, ...issueData.path || []];
2446
2445
  const fullIssue = {
2447
2446
  ...issueData,
2448
2447
  path: fullPath
@@ -2541,11 +2540,11 @@ var errorUtil;
2541
2540
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2542
2541
  })(errorUtil || (errorUtil = {}));
2543
2542
  var ParseInputLazyPath = class {
2544
- constructor(parent, value, path11, key) {
2543
+ constructor(parent, value, path12, key) {
2545
2544
  this._cachedPath = [];
2546
2545
  this.parent = parent;
2547
2546
  this.data = value;
2548
- this._path = path11;
2547
+ this._path = path12;
2549
2548
  this._key = key;
2550
2549
  }
2551
2550
  get path() {
@@ -5826,6 +5825,12 @@ var RouterConfigSchema = z.object({
5826
5825
  has_user_worker: z.boolean().optional(),
5827
5826
  ...InternalConfigSchema.shape
5828
5827
  });
5828
+ var EyeballRouterConfigSchema = z.union([
5829
+ z.object({
5830
+ limitedAssetsOnly: z.boolean().optional()
5831
+ }),
5832
+ z.null()
5833
+ ]);
5829
5834
  var MetadataStaticRedirectEntry = z.object({
5830
5835
  status: z.number(),
5831
5836
  to: z.string(),
@@ -11633,17 +11638,17 @@ function withTrailingSlash(input = "", respectQueryAndFragment) {
11633
11638
  if (hasTrailingSlash(input, true)) {
11634
11639
  return input || "/";
11635
11640
  }
11636
- let path11 = input;
11641
+ let path12 = input;
11637
11642
  let fragment = "";
11638
11643
  const fragmentIndex = input.indexOf("#");
11639
11644
  if (fragmentIndex >= 0) {
11640
- path11 = input.slice(0, fragmentIndex);
11645
+ path12 = input.slice(0, fragmentIndex);
11641
11646
  fragment = input.slice(fragmentIndex);
11642
- if (!path11) {
11647
+ if (!path12) {
11643
11648
  return fragment;
11644
11649
  }
11645
11650
  }
11646
- const [s0, ...s] = path11.split("?");
11651
+ const [s0, ...s] = path12.split("?");
11647
11652
  return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
11648
11653
  }
11649
11654
  function isNonEmptyURL(url) {
@@ -11677,8 +11682,8 @@ import path3, { dirname as dirname3 } from "node:path";
11677
11682
  import v8 from "node:v8";
11678
11683
  import { format as format2, inspect } from "node:util";
11679
11684
  var BUILTIN_MODULES = new Set(builtinModules);
11680
- function normalizeSlash(path11) {
11681
- return path11.replace(/\\/g, "/");
11685
+ function normalizeSlash(path12) {
11686
+ return path12.replace(/\\/g, "/");
11682
11687
  }
11683
11688
  var own$1 = {}.hasOwnProperty;
11684
11689
  var classRegExp = /^([A-Z][a-z\d]*)+$/;
@@ -11791,8 +11796,8 @@ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
11791
11796
  * @param {string} [base]
11792
11797
  * @param {string} [message]
11793
11798
  */
11794
- (path11, base, message) => {
11795
- return `Invalid package config ${path11}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11799
+ (path12, base, message) => {
11800
+ return `Invalid package config ${path12}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
11796
11801
  },
11797
11802
  Error
11798
11803
  );
@@ -11824,8 +11829,8 @@ codes.ERR_MODULE_NOT_FOUND = createError(
11824
11829
  * @param {string} base
11825
11830
  * @param {boolean} [exactUrl]
11826
11831
  */
11827
- (path11, base, exactUrl = false) => {
11828
- return `Cannot find ${exactUrl ? "module" : "package"} '${path11}' imported from ${base}`;
11832
+ (path12, base, exactUrl = false) => {
11833
+ return `Cannot find ${exactUrl ? "module" : "package"} '${path12}' imported from ${base}`;
11829
11834
  },
11830
11835
  Error
11831
11836
  );
@@ -11876,8 +11881,8 @@ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
11876
11881
  * @param {string} extension
11877
11882
  * @param {string} path
11878
11883
  */
11879
- (extension, path11) => {
11880
- return `Unknown file extension "${extension}" for ${path11}`;
11884
+ (extension, path12) => {
11885
+ return `Unknown file extension "${extension}" for ${path12}`;
11881
11886
  },
11882
11887
  TypeError
11883
11888
  );
@@ -12249,9 +12254,9 @@ Default "index" lookups for the main are deprecated for ES modules.`,
12249
12254
  );
12250
12255
  }
12251
12256
  }
12252
- function tryStatSync(path11) {
12257
+ function tryStatSync(path12) {
12253
12258
  try {
12254
- return statSync(path11);
12259
+ return statSync(path12);
12255
12260
  } catch {
12256
12261
  }
12257
12262
  }
@@ -13056,8 +13061,8 @@ function isNodeAls(workerConfig) {
13056
13061
  workerConfig.compatibility_flags ?? []
13057
13062
  ).mode === "als";
13058
13063
  }
13059
- function isNodeAlsModule(path11) {
13060
- return /^(node:)?async_hooks$/.test(path11);
13064
+ function isNodeAlsModule(path12) {
13065
+ return /^(node:)?async_hooks$/.test(path12);
13061
13066
  }
13062
13067
  var injectsByModule = /* @__PURE__ */ new Map();
13063
13068
  var virtualModulePathToSpecifier = /* @__PURE__ */ new Map();
@@ -13190,7 +13195,6 @@ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
13190
13195
  // src/utils.ts
13191
13196
  import * as path5 from "node:path";
13192
13197
  import { createRequest, sendResponse } from "@mjackson/node-fetch-server";
13193
- import getPort, { portNumbers } from "get-port";
13194
13198
  import {
13195
13199
  Request as MiniflareRequest,
13196
13200
  Response as MiniflareResponse
@@ -13203,11 +13207,8 @@ var postfixRE = /[?#].*$/;
13203
13207
  function cleanUrl(url) {
13204
13208
  return url.replace(postfixRE, "");
13205
13209
  }
13206
- function getFirstAvailablePort(start) {
13207
- return getPort({ port: portNumbers(start, 65535) });
13208
- }
13209
- function withTrailingSlash2(path11) {
13210
- return path11.endsWith("/") ? path11 : `${path11}/`;
13210
+ function withTrailingSlash2(path12) {
13211
+ return path12.endsWith("/") ? path12 : `${path12}/`;
13211
13212
  }
13212
13213
  function createRequestHandler(handler) {
13213
13214
  return async (req, res, next) => {
@@ -13296,14 +13297,13 @@ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
13296
13297
  });
13297
13298
  this.#webSocketContainer = webSocketContainer;
13298
13299
  }
13299
- async initRunner(worker, root, workerConfig) {
13300
+ async initRunner(worker, workerConfig) {
13300
13301
  this.#worker = worker;
13301
13302
  const response = await this.#worker.fetch(
13302
13303
  new URL(INIT_PATH, UNKNOWN_HOST),
13303
13304
  {
13304
13305
  headers: {
13305
13306
  [VITE_DEV_METADATA_HEADER]: JSON.stringify({
13306
- root,
13307
13307
  entryPath: workerConfig.main
13308
13308
  }),
13309
13309
  upgrade: "websocket"
@@ -13386,14 +13386,11 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
13386
13386
  };
13387
13387
  }
13388
13388
  function initRunners(resolvedPluginConfig, viteDevServer, miniflare2) {
13389
- if (resolvedPluginConfig.type === "assets-only") {
13390
- return;
13391
- }
13392
13389
  return Promise.all(
13393
13390
  Object.entries(resolvedPluginConfig.workers).map(
13394
13391
  async ([environmentName, workerConfig]) => {
13395
13392
  const worker = await miniflare2.getWorker(workerConfig.name);
13396
- return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
13393
+ return viteDevServer.environments[environmentName].initRunner(worker, workerConfig);
13397
13394
  }
13398
13395
  )
13399
13396
  );
@@ -13401,8 +13398,39 @@ function initRunners(resolvedPluginConfig, viteDevServer, miniflare2) {
13401
13398
 
13402
13399
  // src/debugging.ts
13403
13400
  import assert5 from "node:assert";
13401
+ import getPort, { portNumbers } from "get-port";
13404
13402
  import colors2 from "picocolors";
13405
- var debuggingPath = "/__debug";
13403
+ async function getInputInspectorPortOption(resolvedPluginConfig, viteServer, miniflare2) {
13404
+ if (resolvedPluginConfig.inspectorPort === void 0 || resolvedPluginConfig.inspectorPort === 0) {
13405
+ const resolvedInspectorPort = await getResolvedInspectorPort(
13406
+ resolvedPluginConfig,
13407
+ miniflare2
13408
+ );
13409
+ if (resolvedInspectorPort !== null) {
13410
+ return resolvedInspectorPort;
13411
+ }
13412
+ }
13413
+ const inputInspectorPort = resolvedPluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
13414
+ if (resolvedPluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
13415
+ viteServer.config.logger.warn(
13416
+ colors2.dim(
13417
+ `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
13418
+ `
13419
+ )
13420
+ );
13421
+ }
13422
+ return inputInspectorPort;
13423
+ }
13424
+ async function getResolvedInspectorPort(resolvedPluginConfig, miniflare2) {
13425
+ if (miniflare2 && resolvedPluginConfig.inspectorPort !== false) {
13426
+ const miniflareInspectorUrl = await miniflare2.getInspectorURL();
13427
+ return Number.parseInt(miniflareInspectorUrl.port);
13428
+ }
13429
+ return null;
13430
+ }
13431
+ function getFirstAvailablePort(start) {
13432
+ return getPort({ port: portNumbers(start, 65535) });
13433
+ }
13406
13434
  function addDebugToVitePrintUrls(server) {
13407
13435
  const originalPrintUrls = server.printUrls;
13408
13436
  server.printUrls = () => {
@@ -13416,7 +13444,7 @@ function addDebugToVitePrintUrls(server) {
13416
13444
  )
13417
13445
  );
13418
13446
  server.config.logger.info(
13419
- ` ${colors2.green("\u279C")} ${colors2.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${debuggingPath}`)}`
13447
+ ` ${colors2.green("\u279C")} ${colors2.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${DEBUG_PATH}`)}`
13420
13448
  );
13421
13449
  }
13422
13450
  };
@@ -13424,11 +13452,11 @@ function addDebugToVitePrintUrls(server) {
13424
13452
  function getDebugPathHtml(workerNames, inspectorPort) {
13425
13453
  assert5(workerNames.length >= 1, "no workers present to debug");
13426
13454
  const workerDevtoolsUrls = workerNames.map((workerName) => {
13427
- const localHost = `localhost:${inspectorPort}/${workerName}`;
13455
+ const localhost = `localhost:${inspectorPort}/${workerName}`;
13428
13456
  const searchParams = new URLSearchParams({
13429
13457
  theme: "systemPreferred",
13430
13458
  debugger: "true",
13431
- ws: localHost,
13459
+ ws: localhost,
13432
13460
  domain: workerName
13433
13461
  });
13434
13462
  const devtoolsFrontendUrl = `https://devtools.devprod.cloudflare.dev/js_app?${searchParams}`;
@@ -13457,7 +13485,7 @@ import { unstable_readConfig } from "wrangler";
13457
13485
  function getDeployConfigPath(root) {
13458
13486
  return path6.resolve(root, ".wrangler", "deploy", "config.json");
13459
13487
  }
13460
- function getWorkerConfigs(root, remoteBindingsEnabled) {
13488
+ function getWorkerConfigs(root) {
13461
13489
  const deployConfigPath = getDeployConfigPath(root);
13462
13490
  const deployConfig = JSON.parse(
13463
13491
  fs3.readFileSync(deployConfigPath, "utf-8")
@@ -13470,10 +13498,7 @@ function getWorkerConfigs(root, remoteBindingsEnabled) {
13470
13498
  path6.dirname(deployConfigPath),
13471
13499
  configPath
13472
13500
  );
13473
- return unstable_readConfig(
13474
- { config: resolvedConfigPath },
13475
- { experimental: { remoteBindingsEnabled } }
13476
- );
13501
+ return unstable_readConfig({ config: resolvedConfigPath });
13477
13502
  });
13478
13503
  }
13479
13504
  function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
@@ -13533,11 +13558,39 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
13533
13558
  }
13534
13559
  }
13535
13560
 
13561
+ // src/dev-vars.ts
13562
+ import * as fs4 from "node:fs";
13563
+ import * as path7 from "node:path";
13564
+ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
13565
+ const configDir = path7.dirname(configPath);
13566
+ const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
13567
+ const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
13568
+ const targetPath = fs4.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs4.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
13569
+ if (targetPath) {
13570
+ const dotDevDotVarsContent = fs4.readFileSync(targetPath);
13571
+ return dotDevDotVarsContent;
13572
+ }
13573
+ return null;
13574
+ }
13575
+ function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
13576
+ return [...resolvedPluginConfig.configPaths].some((configPath) => {
13577
+ const dotDevDotVars = path7.join(path7.dirname(configPath), ".dev.vars");
13578
+ if (dotDevDotVars === changedFilePath) {
13579
+ return true;
13580
+ }
13581
+ if (resolvedPluginConfig.cloudflareEnv) {
13582
+ const dotDevDotVarsForEnv = `${dotDevDotVars}.${resolvedPluginConfig.cloudflareEnv}`;
13583
+ return dotDevDotVarsForEnv === changedFilePath;
13584
+ }
13585
+ return false;
13586
+ });
13587
+ }
13588
+
13536
13589
  // src/miniflare-options.ts
13537
13590
  import assert7 from "node:assert";
13538
- import * as fs4 from "node:fs";
13591
+ import * as fs5 from "node:fs";
13539
13592
  import * as fsp from "node:fs/promises";
13540
- import * as path7 from "node:path";
13593
+ import * as path8 from "node:path";
13541
13594
  import { fileURLToPath as fileURLToPath2 } from "node:url";
13542
13595
  import {
13543
13596
  getDefaultDevRegistryPath,
@@ -13559,7 +13612,7 @@ function getPersistenceRoot(root, persistState) {
13559
13612
  return;
13560
13613
  }
13561
13614
  const defaultPersistPath = ".wrangler/state";
13562
- const persistPath = path7.resolve(
13615
+ const persistPath = path8.resolve(
13563
13616
  root,
13564
13617
  typeof persistState === "object" ? persistState.path : defaultPersistPath,
13565
13618
  "v3"
@@ -13688,8 +13741,8 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13688
13741
  modules: [
13689
13742
  {
13690
13743
  type: "ESModule",
13691
- path: path7.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13692
- contents: fs4.readFileSync(
13744
+ path: path8.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
13745
+ contents: fs5.readFileSync(
13693
13746
  fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
13694
13747
  )
13695
13748
  }
@@ -13711,8 +13764,8 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13711
13764
  modules: [
13712
13765
  {
13713
13766
  type: "ESModule",
13714
- path: path7.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13715
- contents: fs4.readFileSync(
13767
+ path: path8.join(miniflareModulesRoot, ASSET_WORKER_PATH),
13768
+ contents: fs5.readFileSync(
13716
13769
  fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
13717
13770
  )
13718
13771
  }
@@ -13732,8 +13785,8 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13732
13785
  if (publicDirInRoot && pathname.startsWith(publicPath)) {
13733
13786
  return MiniflareResponse2.json(null);
13734
13787
  }
13735
- const publicDirFilePath = path7.join(publicDir, pathname);
13736
- const rootDirFilePath = path7.join(root, pathname);
13788
+ const publicDirFilePath = path8.join(publicDir, pathname);
13789
+ const rootDirFilePath = path8.join(root, pathname);
13737
13790
  for (const resolvedPath of [publicDirFilePath, rootDirFilePath]) {
13738
13791
  try {
13739
13792
  const stats = await fsp.stat(resolvedPath);
@@ -13752,7 +13805,7 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13752
13805
  const { pathname } = new URL(request.url);
13753
13806
  const { root, publicDir } = resolvedViteConfig;
13754
13807
  const isInPublicDir = pathname.startsWith(PUBLIC_DIR_PREFIX);
13755
- const resolvedPath = isInPublicDir ? path7.join(publicDir, pathname.slice(PUBLIC_DIR_PREFIX.length)) : path7.join(root, pathname);
13808
+ const resolvedPath = isInPublicDir ? path8.join(publicDir, pathname.slice(PUBLIC_DIR_PREFIX.length)) : path8.join(root, pathname);
13756
13809
  try {
13757
13810
  let html = await fsp.readFile(resolvedPath, "utf-8");
13758
13811
  if (!isInPublicDir) {
@@ -13925,13 +13978,13 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13925
13978
  modules: [
13926
13979
  {
13927
13980
  type: "ESModule",
13928
- path: path7.join(miniflareModulesRoot, WRAPPER_PATH),
13981
+ path: path8.join(miniflareModulesRoot, WRAPPER_PATH),
13929
13982
  contents: wrappers.join("\n")
13930
13983
  },
13931
13984
  {
13932
13985
  type: "ESModule",
13933
- path: path7.join(miniflareModulesRoot, RUNNER_PATH),
13934
- contents: fs4.readFileSync(
13986
+ path: path8.join(miniflareModulesRoot, RUNNER_PATH),
13987
+ contents: fs5.readFileSync(
13935
13988
  fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
13936
13989
  )
13937
13990
  }
@@ -13985,8 +14038,8 @@ async function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer, inspe
13985
14038
  }
13986
14039
  function getPreviewModules(main, modulesRules) {
13987
14040
  assert7(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
13988
- const rootPath = path7.dirname(main);
13989
- const entryPath = path7.basename(main);
14041
+ const rootPath = path8.dirname(main);
14042
+ const entryPath = path8.basename(main);
13990
14043
  return {
13991
14044
  rootPath,
13992
14045
  modules: [
@@ -13995,21 +14048,21 @@ function getPreviewModules(main, modulesRules) {
13995
14048
  path: entryPath
13996
14049
  },
13997
14050
  ...modulesRules.flatMap(
13998
- ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path11) => ({
14051
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path12) => ({
13999
14052
  type,
14000
- path: path11
14053
+ path: path12
14001
14054
  }))
14002
14055
  )
14003
14056
  ]
14004
14057
  };
14005
14058
  }
14006
- async function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, persistState, remoteBindingsEnabled, inspectorPort) {
14059
+ async function getPreviewMiniflareOptions(resolvedPluginConfig, vitePreviewServer, inspectorPort) {
14007
14060
  const resolvedViteConfig = vitePreviewServer.config;
14008
14061
  const workers = (await Promise.all(
14009
- workerConfigs.map(async (workerConfig, i) => {
14062
+ resolvedPluginConfig.workers.map(async (workerConfig, i) => {
14010
14063
  const bindings = unstable_convertConfigBindingsToStartWorkerBindings(workerConfig);
14011
14064
  const preExistingRemoteProxySessionData = workerConfig.configPath ? remoteProxySessionsDataMap.get(workerConfig.configPath) : void 0;
14012
- const remoteProxySessionData = remoteBindingsEnabled ? await experimental_maybeStartOrUpdateRemoteProxySession(
14065
+ const remoteProxySessionData = resolvedPluginConfig.experimental.remoteBindings ? await experimental_maybeStartOrUpdateRemoteProxySession(
14013
14066
  {
14014
14067
  name: workerConfig.name,
14015
14068
  bindings: bindings ?? {}
@@ -14027,14 +14080,14 @@ async function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, pers
14027
14080
  void 0,
14028
14081
  {
14029
14082
  remoteProxyConnectionString: remoteProxySessionData?.session?.remoteProxyConnectionString,
14030
- remoteBindingsEnabled
14083
+ remoteBindingsEnabled: resolvedPluginConfig.experimental.remoteBindings
14031
14084
  }
14032
14085
  );
14033
14086
  const { externalWorkers } = miniflareWorkerOptions;
14034
14087
  const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
14035
14088
  logUnknownTails(
14036
14089
  workerOptions.tails,
14037
- workerConfigs,
14090
+ resolvedPluginConfig.workers,
14038
14091
  vitePreviewServer.config.logger.warn
14039
14092
  );
14040
14093
  return [
@@ -14068,7 +14121,7 @@ async function getPreviewMiniflareOptions(vitePreviewServer, workerConfigs, pers
14068
14121
  },
14069
14122
  defaultPersistRoot: getPersistenceRoot(
14070
14123
  resolvedViteConfig.root,
14071
- persistState
14124
+ resolvedPluginConfig.persistState
14072
14125
  ),
14073
14126
  workers
14074
14127
  };
@@ -14107,7 +14160,7 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
14107
14160
 
14108
14161
  // src/plugin-config.ts
14109
14162
  import assert9 from "node:assert";
14110
- import * as path9 from "node:path";
14163
+ import * as path10 from "node:path";
14111
14164
 
14112
14165
  // ../workers-shared/utils/configuration/parseStaticRouting.ts
14113
14166
  function parseStaticRouting(input) {
@@ -14190,8 +14243,8 @@ import * as vite5 from "vite";
14190
14243
 
14191
14244
  // src/workers-configs.ts
14192
14245
  import assert8 from "node:assert";
14193
- import * as fs5 from "node:fs";
14194
- import * as path8 from "node:path";
14246
+ import * as fs6 from "node:fs";
14247
+ import * as path9 from "node:path";
14195
14248
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
14196
14249
  var nonApplicableWorkerConfigs = {
14197
14250
  /**
@@ -14236,15 +14289,12 @@ var nullableNonApplicable = [
14236
14289
  "site",
14237
14290
  "tsconfig"
14238
14291
  ];
14239
- function readWorkerConfig(configPath, env2, remoteBindingsEnabled) {
14292
+ function readWorkerConfig(configPath, env2) {
14240
14293
  const nonApplicable = {
14241
14294
  replacedByVite: /* @__PURE__ */ new Set(),
14242
14295
  notRelevant: /* @__PURE__ */ new Set()
14243
14296
  };
14244
- const config = unstable_readConfig2(
14245
- { config: configPath, env: env2 },
14246
- { experimental: { remoteBindingsEnabled } }
14247
- );
14297
+ const config = unstable_readConfig2({ config: configPath, env: env2 });
14248
14298
  const raw = structuredClone(config);
14249
14299
  nullableNonApplicable.forEach((prop) => {
14250
14300
  if (config[prop] !== void 0) {
@@ -14286,7 +14336,7 @@ function getWarningForWorkersConfigs(configs) {
14286
14336
  const lines2 = [
14287
14337
  `
14288
14338
 
14289
- \x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path8.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
14339
+ \x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path9.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
14290
14340
  ];
14291
14341
  nonApplicableLines.forEach((line) => lines2.push(line));
14292
14342
  lines2.push("");
@@ -14300,7 +14350,7 @@ function getWarningForWorkersConfigs(configs) {
14300
14350
  );
14301
14351
  if (nonApplicableLines.length > 0) {
14302
14352
  lines.push(
14303
- ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path8.relative("", workerConfig.config.configPath)}\`)` : ""}`
14353
+ ` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path9.relative("", workerConfig.config.configPath)}\`)` : ""}`
14304
14354
  );
14305
14355
  nonApplicableLines.forEach((line) => lines.push(line));
14306
14356
  }
@@ -14339,15 +14389,11 @@ function isNotRelevant(configName) {
14339
14389
  function missingFieldErrorMessage(field, configPath, env2) {
14340
14390
  return `No ${field} field provided in '${configPath}'${env2 ? ` for '${env2}' environment` : ""}`;
14341
14391
  }
14342
- function getWorkerConfig(configPath, env2, remoteBindingsEnabled, opts) {
14392
+ function getWorkerConfig(configPath, env2, opts) {
14343
14393
  if (opts?.visitedConfigPaths?.has(configPath)) {
14344
14394
  throw new Error(`Duplicate Wrangler config path found: ${configPath}`);
14345
14395
  }
14346
- const { raw, config, nonApplicable } = readWorkerConfig(
14347
- configPath,
14348
- env2,
14349
- remoteBindingsEnabled
14350
- );
14396
+ const { raw, config, nonApplicable } = readWorkerConfig(configPath, env2);
14351
14397
  opts?.visitedConfigPaths?.add(configPath);
14352
14398
  if (!config.name) {
14353
14399
  throw new Error(missingFieldErrorMessage(`'name'`, configPath, env2));
@@ -14381,7 +14427,7 @@ function getWorkerConfig(configPath, env2, remoteBindingsEnabled, opts) {
14381
14427
  if (!config.main) {
14382
14428
  throw new Error(missingFieldErrorMessage(`'main'`, configPath, env2));
14383
14429
  }
14384
- const mainStat = fs5.statSync(config.main, { throwIfNoEntry: false });
14430
+ const mainStat = fs6.statSync(config.main, { throwIfNoEntry: false });
14385
14431
  if (!mainStat) {
14386
14432
  throw new Error(
14387
14433
  `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
@@ -14405,17 +14451,17 @@ function getWorkerConfig(configPath, env2, remoteBindingsEnabled, opts) {
14405
14451
  }
14406
14452
  function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
14407
14453
  if (requestedConfigPath) {
14408
- const configPath2 = path8.resolve(root, requestedConfigPath);
14454
+ const configPath2 = path9.resolve(root, requestedConfigPath);
14409
14455
  const forAuxiliaryWorkerErrorMessage = isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : "";
14410
14456
  const errorMessagePrefix = `The provided configPath (${configPath2})${forAuxiliaryWorkerErrorMessage}`;
14411
- const fileExtension = path8.extname(configPath2).slice(1);
14457
+ const fileExtension = path9.extname(configPath2).slice(1);
14412
14458
  if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
14413
14459
  const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
14414
14460
  throw new Error(
14415
14461
  `${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`
14416
14462
  );
14417
14463
  }
14418
- const mainStat = fs5.statSync(configPath2, { throwIfNoEntry: false });
14464
+ const mainStat = fs6.statSync(configPath2, { throwIfNoEntry: false });
14419
14465
  if (!mainStat) {
14420
14466
  throw new Error(
14421
14467
  `${errorMessagePrefix} doesn't point to an existing file`
@@ -14442,8 +14488,8 @@ function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliar
14442
14488
  }
14443
14489
  function findWranglerConfig(root) {
14444
14490
  for (const extension of allowedWranglerConfigExtensions) {
14445
- const configPath = path8.join(root, `wrangler.${extension}`);
14446
- if (fs5.existsSync(configPath)) {
14491
+ const configPath = path9.join(root, `wrangler.${extension}`);
14492
+ if (fs6.existsSync(configPath)) {
14447
14493
  return configPath;
14448
14494
  }
14449
14495
  }
@@ -14455,10 +14501,20 @@ function workerNameToEnvironmentName(workerName) {
14455
14501
  return workerName.replaceAll("-", "_");
14456
14502
  }
14457
14503
  function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14504
+ const shared = {
14505
+ persistState: pluginConfig.persistState ?? true,
14506
+ inspectorPort: pluginConfig.inspectorPort,
14507
+ experimental: pluginConfig.experimental ?? {}
14508
+ };
14509
+ const root = userConfig.root ? path10.resolve(userConfig.root) : process.cwd();
14510
+ if (viteEnv.isPreview) {
14511
+ return {
14512
+ ...shared,
14513
+ type: "preview",
14514
+ workers: getWorkerConfigs(root)
14515
+ };
14516
+ }
14458
14517
  const configPaths = /* @__PURE__ */ new Set();
14459
- const persistState = pluginConfig.persistState ?? true;
14460
- const experimental = pluginConfig.experimental ?? {};
14461
- const root = userConfig.root ? path9.resolve(userConfig.root) : process.cwd();
14462
14518
  const { CLOUDFLARE_ENV: cloudflareEnv } = vite5.loadEnv(
14463
14519
  viteEnv.mode,
14464
14520
  root,
@@ -14472,7 +14528,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14472
14528
  const entryWorkerResolvedConfig = getWorkerConfig(
14473
14529
  entryWorkerConfigPath,
14474
14530
  cloudflareEnv,
14475
- pluginConfig.experimental?.remoteBindings ?? false,
14476
14531
  {
14477
14532
  visitedConfigPaths: configPaths,
14478
14533
  isEntryWorker: true
@@ -14480,15 +14535,14 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14480
14535
  );
14481
14536
  if (entryWorkerResolvedConfig.type === "assets-only") {
14482
14537
  return {
14538
+ ...shared,
14483
14539
  type: "assets-only",
14540
+ cloudflareEnv,
14484
14541
  config: entryWorkerResolvedConfig.config,
14485
14542
  configPaths,
14486
- persistState,
14487
14543
  rawConfigs: {
14488
14544
  entryWorker: entryWorkerResolvedConfig
14489
- },
14490
- cloudflareEnv,
14491
- experimental
14545
+ }
14492
14546
  };
14493
14547
  }
14494
14548
  const entryWorkerConfig = entryWorkerResolvedConfig.config;
@@ -14512,7 +14566,6 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14512
14566
  const workerResolvedConfig = getWorkerConfig(
14513
14567
  workerConfigPath,
14514
14568
  cloudflareEnv,
14515
- pluginConfig.experimental?.remoteBindings ?? false,
14516
14569
  {
14517
14570
  visitedConfigPaths: configPaths
14518
14571
  }
@@ -14532,20 +14585,31 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
14532
14585
  workers[workerEnvironmentName] = workerConfig;
14533
14586
  }
14534
14587
  return {
14588
+ ...shared,
14535
14589
  type: "workers",
14590
+ cloudflareEnv,
14536
14591
  configPaths,
14537
- persistState,
14538
14592
  workers,
14539
14593
  entryWorkerEnvironmentName,
14540
14594
  staticRouting,
14541
14595
  rawConfigs: {
14542
14596
  entryWorker: entryWorkerResolvedConfig,
14543
14597
  auxiliaryWorkers: auxiliaryWorkersResolvedConfigs
14544
- },
14545
- cloudflareEnv,
14546
- experimental
14598
+ }
14547
14599
  };
14548
14600
  }
14601
+ function assertIsNotPreview(resolvedPluginConfig) {
14602
+ assert9(
14603
+ resolvedPluginConfig.type !== "preview",
14604
+ `Expected "assets-only" or "workers" plugin config`
14605
+ );
14606
+ }
14607
+ function assertIsPreview(resolvedPluginConfig) {
14608
+ assert9(
14609
+ resolvedPluginConfig.type === "preview",
14610
+ `Expected "preview" plugin config`
14611
+ );
14612
+ }
14549
14613
 
14550
14614
  // src/websockets.ts
14551
14615
  import { createHeaders } from "@mjackson/node-fetch-server";
@@ -14649,14 +14713,14 @@ function cloudflare2(pluginConfig = {}) {
14649
14713
  // This only applies to this plugin so is safe to use while other plugins migrate to the Environment API
14650
14714
  sharedDuringBuild: true,
14651
14715
  config(userConfig, env2) {
14652
- if (env2.isPreview) {
14653
- return { appType: "custom" };
14654
- }
14655
14716
  resolvedPluginConfig = resolvePluginConfig(
14656
14717
  pluginConfig,
14657
14718
  userConfig,
14658
14719
  env2
14659
14720
  );
14721
+ if (resolvedPluginConfig.type === "preview") {
14722
+ return { appType: "custom" };
14723
+ }
14660
14724
  if (!workersConfigsWarningShown) {
14661
14725
  workersConfigsWarningShown = true;
14662
14726
  const workersConfigsWarning = getWarningForWorkersConfigs(
@@ -14713,7 +14777,7 @@ function cloudflare2(pluginConfig = {}) {
14713
14777
  },
14714
14778
  configResolved(config) {
14715
14779
  resolvedViteConfig = config;
14716
- if (resolvedPluginConfig?.type === "workers") {
14780
+ if (resolvedPluginConfig.type === "workers") {
14717
14781
  validateWorkerEnvironmentsResolvedConfigs(
14718
14782
  resolvedPluginConfig,
14719
14783
  resolvedViteConfig
@@ -14721,6 +14785,7 @@ function cloudflare2(pluginConfig = {}) {
14721
14785
  }
14722
14786
  },
14723
14787
  generateBundle(_, bundle) {
14788
+ assertIsNotPreview(resolvedPluginConfig);
14724
14789
  let config;
14725
14790
  if (resolvedPluginConfig.type === "workers") {
14726
14791
  const workerConfig = resolvedPluginConfig.workers[this.environment.name];
@@ -14745,9 +14810,9 @@ function cloudflare2(pluginConfig = {}) {
14745
14810
  );
14746
14811
  workerConfig.assets = {
14747
14812
  ...workerConfig.assets,
14748
- directory: path10.relative(
14749
- path10.resolve(resolvedViteConfig.root, workerOutputDirectory),
14750
- path10.resolve(resolvedViteConfig.root, clientOutputDirectory)
14813
+ directory: path11.relative(
14814
+ path11.resolve(resolvedViteConfig.root, workerOutputDirectory),
14815
+ path11.resolve(resolvedViteConfig.root, clientOutputDirectory)
14751
14816
  )
14752
14817
  };
14753
14818
  } else {
@@ -14795,12 +14860,14 @@ function cloudflare2(pluginConfig = {}) {
14795
14860
  });
14796
14861
  },
14797
14862
  writeBundle() {
14798
- if (this.environment.name === (resolvedPluginConfig.type === "assets-only" ? "client" : resolvedPluginConfig.entryWorkerEnvironmentName)) {
14863
+ assertIsNotPreview(resolvedPluginConfig);
14864
+ if (this.environment.name === (resolvedPluginConfig.type === "workers" ? resolvedPluginConfig.entryWorkerEnvironmentName : "client")) {
14799
14865
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
14800
14866
  }
14801
14867
  },
14802
14868
  hotUpdate(options) {
14803
- const changedFilePath = path10.resolve(options.file);
14869
+ assertIsNotPreview(resolvedPluginConfig);
14870
+ const changedFilePath = path11.resolve(options.file);
14804
14871
  if (resolvedPluginConfig.configPaths.has(changedFilePath) || hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(
14805
14872
  resolvedPluginConfig,
14806
14873
  resolvedViteConfig,
@@ -14811,9 +14878,11 @@ function cloudflare2(pluginConfig = {}) {
14811
14878
  }
14812
14879
  },
14813
14880
  async configureServer(viteDevServer) {
14881
+ assertIsNotPreview(resolvedPluginConfig);
14814
14882
  const inputInspectorPort = await getInputInspectorPortOption(
14815
- pluginConfig,
14816
- viteDevServer
14883
+ resolvedPluginConfig,
14884
+ viteDevServer,
14885
+ miniflare
14817
14886
  );
14818
14887
  const miniflareDevOptions = await getDevMiniflareOptions(
14819
14888
  resolvedPluginConfig,
@@ -14825,9 +14894,9 @@ function cloudflare2(pluginConfig = {}) {
14825
14894
  } else {
14826
14895
  await miniflare.setOptions(miniflareDevOptions);
14827
14896
  }
14828
- await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14829
14897
  let preMiddleware;
14830
14898
  if (resolvedPluginConfig.type === "workers") {
14899
+ await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
14831
14900
  const entryWorkerConfig = getWorkerConfig2(
14832
14901
  resolvedPluginConfig.entryWorkerEnvironmentName
14833
14902
  );
@@ -14901,30 +14970,26 @@ function cloudflare2(pluginConfig = {}) {
14901
14970
  };
14902
14971
  },
14903
14972
  async configurePreviewServer(vitePreviewServer) {
14904
- const workerConfigs = getWorkerConfigs(
14905
- vitePreviewServer.config.root,
14906
- pluginConfig.experimental?.remoteBindings ?? false
14907
- );
14973
+ assertIsPreview(resolvedPluginConfig);
14908
14974
  const inputInspectorPort = await getInputInspectorPortOption(
14909
- pluginConfig,
14975
+ resolvedPluginConfig,
14910
14976
  vitePreviewServer
14911
14977
  );
14912
- const miniflare2 = new Miniflare(
14978
+ miniflare = new Miniflare(
14913
14979
  await getPreviewMiniflareOptions(
14980
+ resolvedPluginConfig,
14914
14981
  vitePreviewServer,
14915
- workerConfigs,
14916
- pluginConfig.persistState ?? true,
14917
- !!pluginConfig.experimental?.remoteBindings,
14918
14982
  inputInspectorPort
14919
14983
  )
14920
14984
  );
14921
- handleWebSocket(
14922
- vitePreviewServer.httpServer,
14923
- () => miniflare2.dispatchFetch
14924
- );
14985
+ handleWebSocket(vitePreviewServer.httpServer, () => {
14986
+ assert11(miniflare, `Miniflare not defined`);
14987
+ return miniflare.dispatchFetch;
14988
+ });
14925
14989
  vitePreviewServer.middlewares.use(
14926
14990
  createRequestHandler((request) => {
14927
- return miniflare2.dispatchFetch(request, { redirect: "manual" });
14991
+ assert11(miniflare, `Miniflare not defined`);
14992
+ return miniflare.dispatchFetch(request, { redirect: "manual" });
14928
14993
  })
14929
14994
  );
14930
14995
  }
@@ -15016,13 +15081,13 @@ function cloudflare2(pluginConfig = {}) {
15016
15081
  }
15017
15082
  const referenceId = this.emitFile({
15018
15083
  type: "asset",
15019
- name: path10.basename(modulePath),
15084
+ name: path11.basename(modulePath),
15020
15085
  originalFileName: modulePath,
15021
15086
  source
15022
15087
  });
15023
15088
  const emittedFileName = this.getFileName(referenceId);
15024
15089
  const relativePath = vite6.normalizePath(
15025
- path10.relative(path10.dirname(chunk.fileName), emittedFileName)
15090
+ path11.relative(path11.dirname(chunk.fileName), emittedFileName)
15026
15091
  );
15027
15092
  const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
15028
15093
  magicString.update(
@@ -15042,9 +15107,6 @@ function cloudflare2(pluginConfig = {}) {
15042
15107
  // Plugin that can provide Node.js compatibility support for Vite Environments that are hosted in Cloudflare Workers.
15043
15108
  {
15044
15109
  name: "vite-plugin-cloudflare:nodejs-compat",
15045
- apply(_config, env2) {
15046
- return !env2.isPreview;
15047
- },
15048
15110
  configEnvironment(name) {
15049
15111
  if (isNodeCompat(getWorkerConfig2(name))) {
15050
15112
  return {
@@ -15141,10 +15203,7 @@ function cloudflare2(pluginConfig = {}) {
15141
15203
  // Plugin that handles Node.js Async Local Storage (ALS) compatibility support for Vite Environments that are hosted in Cloudflare Workers.
15142
15204
  {
15143
15205
  name: "vite-plugin-cloudflare:nodejs-als",
15144
- apply(_config, env2) {
15145
- return !env2.isPreview;
15146
- },
15147
- configEnvironment(name, config) {
15206
+ configEnvironment(name) {
15148
15207
  if (isNodeAls(getWorkerConfig2(name))) {
15149
15208
  return {
15150
15209
  resolve: {
@@ -15164,51 +15223,54 @@ function cloudflare2(pluginConfig = {}) {
15164
15223
  // the preview middleware here can take precedence
15165
15224
  enforce: "pre",
15166
15225
  configureServer(viteDevServer) {
15226
+ assertIsNotPreview(resolvedPluginConfig);
15167
15227
  if (resolvedPluginConfig.type === "workers" && pluginConfig.inspectorPort !== false) {
15168
15228
  addDebugToVitePrintUrls(viteDevServer);
15169
15229
  }
15170
- const workerNames = resolvedPluginConfig.type === "assets-only" ? [] : Object.values(resolvedPluginConfig.workers).map(
15230
+ const workerNames = resolvedPluginConfig.type === "workers" ? Object.values(resolvedPluginConfig.workers).map(
15171
15231
  (worker) => worker.name
15172
- );
15173
- viteDevServer.middlewares.use(async (req, res, next) => {
15174
- const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
15175
- if (req.url === debuggingPath && resolvedInspectorPort) {
15232
+ ) : [];
15233
+ viteDevServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
15234
+ const resolvedInspectorPort = await getResolvedInspectorPort(
15235
+ resolvedPluginConfig,
15236
+ miniflare
15237
+ );
15238
+ if (resolvedInspectorPort) {
15176
15239
  const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
15177
15240
  res.setHeader("Content-Type", "text/html");
15178
- return res.end(html);
15241
+ res.end(html);
15242
+ } else {
15243
+ next();
15179
15244
  }
15180
- next();
15181
15245
  });
15182
15246
  },
15183
15247
  async configurePreviewServer(vitePreviewServer) {
15184
- const workerConfigs = getWorkerConfigs(
15185
- vitePreviewServer.config.root,
15186
- pluginConfig.experimental?.remoteBindings ?? false
15187
- );
15188
- if (workerConfigs.length >= 1 && pluginConfig.inspectorPort !== false) {
15248
+ assertIsPreview(resolvedPluginConfig);
15249
+ if (resolvedPluginConfig.workers.length >= 1 && resolvedPluginConfig.inspectorPort !== false) {
15189
15250
  addDebugToVitePrintUrls(vitePreviewServer);
15190
15251
  }
15191
- const workerNames = workerConfigs.map((worker) => {
15252
+ const workerNames = resolvedPluginConfig.workers.map((worker) => {
15192
15253
  assert11(worker.name, "Expected the Worker to have a name");
15193
15254
  return worker.name;
15194
15255
  });
15195
- vitePreviewServer.middlewares.use(async (req, res, next) => {
15196
- const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
15197
- if (req.url === debuggingPath && resolvedInspectorPort) {
15256
+ vitePreviewServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
15257
+ const resolvedInspectorPort = await getResolvedInspectorPort(
15258
+ resolvedPluginConfig,
15259
+ miniflare
15260
+ );
15261
+ if (resolvedInspectorPort) {
15198
15262
  const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
15199
15263
  res.setHeader("Content-Type", "text/html");
15200
- return res.end(html);
15264
+ res.end(html);
15265
+ } else {
15266
+ next();
15201
15267
  }
15202
- next();
15203
15268
  });
15204
15269
  }
15205
15270
  },
15206
15271
  // Plugin to warn if Node.js APIs are being used without nodejs_compat turned on
15207
15272
  {
15208
15273
  name: "vite-plugin-cloudflare:nodejs-compat-warnings",
15209
- apply(_config, env2) {
15210
- return !env2.isPreview;
15211
- },
15212
15274
  // We must ensure that the `resolveId` hook runs before the built-in ones.
15213
15275
  // Otherwise we never see the Node.js built-in imports since they get handled by default Vite behavior.
15214
15276
  enforce: "pre",
@@ -15224,13 +15286,13 @@ function cloudflare2(pluginConfig = {}) {
15224
15286
  setup(build) {
15225
15287
  build.onResolve(
15226
15288
  { filter: NODEJS_MODULES_RE },
15227
- ({ path: path11, importer }) => {
15228
- if (isNodeAls(workerConfig) && isNodeAlsModule(path11)) {
15289
+ ({ path: path12, importer }) => {
15290
+ if (isNodeAls(workerConfig) && isNodeAlsModule(path12)) {
15229
15291
  return;
15230
15292
  }
15231
15293
  const nodeJsCompatWarnings = nodeJsCompatWarningsMap.get(workerConfig);
15232
- nodeJsCompatWarnings?.registerImport(path11, importer);
15233
- return { path: path11, external: true };
15294
+ nodeJsCompatWarnings?.registerImport(path12, importer);
15295
+ return { path: path12, external: true };
15234
15296
  }
15235
15297
  );
15236
15298
  }
@@ -15273,59 +15335,9 @@ function cloudflare2(pluginConfig = {}) {
15273
15335
  }
15274
15336
  ];
15275
15337
  function getWorkerConfig2(environmentName) {
15276
- assert11(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
15277
- return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
15338
+ return resolvedPluginConfig.type === "workers" ? resolvedPluginConfig.workers[environmentName] : void 0;
15278
15339
  }
15279
15340
  }
15280
- async function getInputInspectorPortOption(pluginConfig, viteServer) {
15281
- if (pluginConfig.inspectorPort === void 0 || pluginConfig.inspectorPort === 0) {
15282
- const resolvedInspectorPort = await getResolvedInspectorPort(pluginConfig);
15283
- if (resolvedInspectorPort !== null) {
15284
- return resolvedInspectorPort;
15285
- }
15286
- }
15287
- const inputInspectorPort = pluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
15288
- if (pluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) {
15289
- viteServer.config.logger.warn(
15290
- colors4.dim(
15291
- `Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead
15292
- `
15293
- )
15294
- );
15295
- }
15296
- return inputInspectorPort;
15297
- }
15298
- async function getResolvedInspectorPort(pluginConfig) {
15299
- if (miniflare && pluginConfig.inspectorPort !== false) {
15300
- const miniflareInspectorUrl = await miniflare.getInspectorURL();
15301
- return Number.parseInt(miniflareInspectorUrl.port);
15302
- }
15303
- return null;
15304
- }
15305
- function getDotDevDotVarsContent(configPath, cloudflareEnv) {
15306
- const configDir = path10.dirname(configPath);
15307
- const defaultDotDevDotVarsPath = `${configDir}/.dev.vars`;
15308
- const inputDotDevDotVarsPath = `${defaultDotDevDotVarsPath}${cloudflareEnv ? `.${cloudflareEnv}` : ""}`;
15309
- const targetPath = fs6.existsSync(inputDotDevDotVarsPath) ? inputDotDevDotVarsPath : fs6.existsSync(defaultDotDevDotVarsPath) ? defaultDotDevDotVarsPath : null;
15310
- if (targetPath) {
15311
- const dotDevDotVarsContent = fs6.readFileSync(targetPath);
15312
- return dotDevDotVarsContent;
15313
- }
15314
- return null;
15315
- }
15316
- function hasDotDevDotVarsFileChanged(resolvedPluginConfig, changedFilePath) {
15317
- return [...resolvedPluginConfig.configPaths].some((configPath) => {
15318
- const dotDevDotVars = path10.join(path10.dirname(configPath), ".dev.vars");
15319
- if (dotDevDotVars === changedFilePath) {
15320
- return true;
15321
- }
15322
- if (resolvedPluginConfig.cloudflareEnv) {
15323
- const dotDevDotVarsForEnv = `${dotDevDotVars}.${resolvedPluginConfig.cloudflareEnv}`;
15324
- return dotDevDotVarsForEnv === changedFilePath;
15325
- }
15326
- return false;
15327
- });
15328
- }
15329
15341
  export {
15330
15342
  cloudflare2 as cloudflare
15331
15343
  };