@cloudflare/vite-plugin 0.0.0-9adbd50cf → 0.0.0-9b86dba81

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
@@ -1,6 +1,7 @@
1
1
  // src/index.ts
2
- import assert9 from "node:assert";
2
+ import assert7 from "node:assert";
3
3
  import * as fs5 from "node:fs";
4
+ import * as fsp2 from "node:fs/promises";
4
5
  import { builtinModules as builtinModules2 } from "node:module";
5
6
  import * as path7 from "node:path";
6
7
  import { createMiddleware } from "@hattip/adapter-node";
@@ -1073,6 +1074,36 @@ var MagicString = class _MagicString {
1073
1074
  import { Miniflare } from "miniflare";
1074
1075
  import * as vite6 from "vite";
1075
1076
 
1077
+ // src/constants.ts
1078
+ var ROUTER_WORKER_NAME = "__router-worker__";
1079
+ var ASSET_WORKER_NAME = "__asset-worker__";
1080
+ var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1081
+ var ADDITIONAL_MODULE_TYPES = [
1082
+ "CompiledWasm",
1083
+ "Data",
1084
+ "Text"
1085
+ ];
1086
+
1087
+ // src/additional-modules.ts
1088
+ var moduleRules = [
1089
+ { type: "CompiledWasm", extensions: [".wasm", ".wasm?module"] },
1090
+ { type: "Data", extensions: [".bin"] },
1091
+ { type: "Text", extensions: [".txt", ".html"] }
1092
+ ];
1093
+ function matchAdditionalModule(source) {
1094
+ for (const rule of moduleRules) {
1095
+ for (const extension of rule.extensions) {
1096
+ if (source.endsWith(extension)) {
1097
+ return rule.type;
1098
+ }
1099
+ }
1100
+ }
1101
+ return null;
1102
+ }
1103
+ function createModuleReference(type, id) {
1104
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
1105
+ }
1106
+
1076
1107
  // src/cloudflare-environment.ts
1077
1108
  import assert3 from "node:assert";
1078
1109
  import * as vite2 from "vite";
@@ -1178,16 +1209,16 @@ var TokenType = function TokenType2(label, conf) {
1178
1209
  this.binop = conf.binop || null;
1179
1210
  this.updateContext = null;
1180
1211
  };
1181
- function binop(name2, prec) {
1182
- return new TokenType(name2, { beforeExpr: true, binop: prec });
1212
+ function binop(name, prec) {
1213
+ return new TokenType(name, { beforeExpr: true, binop: prec });
1183
1214
  }
1184
1215
  var beforeExpr = { beforeExpr: true };
1185
1216
  var startsExpr = { startsExpr: true };
1186
1217
  var keywords = {};
1187
- function kw(name2, options) {
1218
+ function kw(name, options) {
1188
1219
  if (options === void 0) options = {};
1189
- options.keyword = name2;
1190
- return keywords[name2] = new TokenType(name2, options);
1220
+ options.keyword = name;
1221
+ return keywords[name] = new TokenType(name, options);
1191
1222
  }
1192
1223
  var types$1 = {
1193
1224
  num: new TokenType("num", startsExpr),
@@ -1664,18 +1695,18 @@ pp$9.eat = function(type) {
1664
1695
  return false;
1665
1696
  }
1666
1697
  };
1667
- pp$9.isContextual = function(name2) {
1668
- return this.type === types$1.name && this.value === name2 && !this.containsEsc;
1698
+ pp$9.isContextual = function(name) {
1699
+ return this.type === types$1.name && this.value === name && !this.containsEsc;
1669
1700
  };
1670
- pp$9.eatContextual = function(name2) {
1671
- if (!this.isContextual(name2)) {
1701
+ pp$9.eatContextual = function(name) {
1702
+ if (!this.isContextual(name)) {
1672
1703
  return false;
1673
1704
  }
1674
1705
  this.next();
1675
1706
  return true;
1676
1707
  };
1677
- pp$9.expectContextual = function(name2) {
1678
- if (!this.eatContextual(name2)) {
1708
+ pp$9.expectContextual = function(name) {
1709
+ if (!this.eatContextual(name)) {
1679
1710
  this.unexpected();
1680
1711
  }
1681
1712
  };
@@ -1769,8 +1800,8 @@ pp$8.parseTopLevel = function(node) {
1769
1800
  }
1770
1801
  if (this.inModule) {
1771
1802
  for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) {
1772
- var name2 = list[i];
1773
- this.raiseRecoverable(this.undefinedExports[name2].start, "Export '" + name2 + "' is not defined");
1803
+ var name = list[i];
1804
+ this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
1774
1805
  }
1775
1806
  }
1776
1807
  this.adaptDirectivePrologue(node.body);
@@ -2513,26 +2544,26 @@ pp$8.exitClassBody = function() {
2513
2544
  }
2514
2545
  };
2515
2546
  function isPrivateNameConflicted(privateNameMap, element) {
2516
- var name2 = element.key.name;
2517
- var curr = privateNameMap[name2];
2547
+ var name = element.key.name;
2548
+ var curr = privateNameMap[name];
2518
2549
  var next = "true";
2519
2550
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
2520
2551
  next = (element.static ? "s" : "i") + element.kind;
2521
2552
  }
2522
2553
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
2523
- privateNameMap[name2] = "true";
2554
+ privateNameMap[name] = "true";
2524
2555
  return false;
2525
2556
  } else if (!curr) {
2526
- privateNameMap[name2] = next;
2557
+ privateNameMap[name] = next;
2527
2558
  return false;
2528
2559
  } else {
2529
2560
  return true;
2530
2561
  }
2531
2562
  }
2532
- function checkKeyName(node, name2) {
2563
+ function checkKeyName(node, name) {
2533
2564
  var computed = node.computed;
2534
2565
  var key = node.key;
2535
- return !computed && (key.type === "Identifier" && key.name === name2 || key.type === "Literal" && key.value === name2);
2566
+ return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);
2536
2567
  }
2537
2568
  pp$8.parseExportAllDeclaration = function(node, exports) {
2538
2569
  if (this.options.ecmaVersion >= 11) {
@@ -2620,17 +2651,17 @@ pp$8.parseExportDefaultDeclaration = function() {
2620
2651
  return declaration;
2621
2652
  }
2622
2653
  };
2623
- pp$8.checkExport = function(exports, name2, pos) {
2654
+ pp$8.checkExport = function(exports, name, pos) {
2624
2655
  if (!exports) {
2625
2656
  return;
2626
2657
  }
2627
- if (typeof name2 !== "string") {
2628
- name2 = name2.type === "Identifier" ? name2.name : name2.value;
2658
+ if (typeof name !== "string") {
2659
+ name = name.type === "Identifier" ? name.name : name.value;
2629
2660
  }
2630
- if (hasOwn(exports, name2)) {
2631
- this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
2661
+ if (hasOwn(exports, name)) {
2662
+ this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
2632
2663
  }
2633
- exports[name2] = true;
2664
+ exports[name] = true;
2634
2665
  };
2635
2666
  pp$8.checkPatternExport = function(exports, pat) {
2636
2667
  var type = pat.type;
@@ -3210,20 +3241,20 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3210
3241
  return;
3211
3242
  }
3212
3243
  var key = prop.key;
3213
- var name2;
3244
+ var name;
3214
3245
  switch (key.type) {
3215
3246
  case "Identifier":
3216
- name2 = key.name;
3247
+ name = key.name;
3217
3248
  break;
3218
3249
  case "Literal":
3219
- name2 = String(key.value);
3250
+ name = String(key.value);
3220
3251
  break;
3221
3252
  default:
3222
3253
  return;
3223
3254
  }
3224
3255
  var kind = prop.kind;
3225
3256
  if (this.options.ecmaVersion >= 6) {
3226
- if (name2 === "__proto__" && kind === "init") {
3257
+ if (name === "__proto__" && kind === "init") {
3227
3258
  if (propHash.proto) {
3228
3259
  if (refDestructuringErrors) {
3229
3260
  if (refDestructuringErrors.doubleProto < 0) {
@@ -3237,8 +3268,8 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3237
3268
  }
3238
3269
  return;
3239
3270
  }
3240
- name2 = "$" + name2;
3241
- var other = propHash[name2];
3271
+ name = "$" + name;
3272
+ var other = propHash[name];
3242
3273
  if (other) {
3243
3274
  var redefinition;
3244
3275
  if (kind === "init") {
@@ -3250,7 +3281,7 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3250
3281
  this.raiseRecoverable(key.start, "Redefinition of property");
3251
3282
  }
3252
3283
  } else {
3253
- other = propHash[name2] = {
3284
+ other = propHash[name] = {
3254
3285
  init: false,
3255
3286
  get: false,
3256
3287
  set: false
@@ -4150,31 +4181,31 @@ pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestruct
4150
4181
  pp$5.checkUnreserved = function(ref2) {
4151
4182
  var start = ref2.start;
4152
4183
  var end = ref2.end;
4153
- var name2 = ref2.name;
4154
- if (this.inGenerator && name2 === "yield") {
4184
+ var name = ref2.name;
4185
+ if (this.inGenerator && name === "yield") {
4155
4186
  this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
4156
4187
  }
4157
- if (this.inAsync && name2 === "await") {
4188
+ if (this.inAsync && name === "await") {
4158
4189
  this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
4159
4190
  }
4160
- if (this.currentThisScope().inClassFieldInit && name2 === "arguments") {
4191
+ if (this.currentThisScope().inClassFieldInit && name === "arguments") {
4161
4192
  this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
4162
4193
  }
4163
- if (this.inClassStaticBlock && (name2 === "arguments" || name2 === "await")) {
4164
- this.raise(start, "Cannot use " + name2 + " in class static initialization block");
4194
+ if (this.inClassStaticBlock && (name === "arguments" || name === "await")) {
4195
+ this.raise(start, "Cannot use " + name + " in class static initialization block");
4165
4196
  }
4166
- if (this.keywords.test(name2)) {
4167
- this.raise(start, "Unexpected keyword '" + name2 + "'");
4197
+ if (this.keywords.test(name)) {
4198
+ this.raise(start, "Unexpected keyword '" + name + "'");
4168
4199
  }
4169
4200
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
4170
4201
  return;
4171
4202
  }
4172
4203
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
4173
- if (re.test(name2)) {
4174
- if (!this.inAsync && name2 === "await") {
4204
+ if (re.test(name)) {
4205
+ if (!this.inAsync && name === "await") {
4175
4206
  this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
4176
4207
  }
4177
- this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
4208
+ this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
4178
4209
  }
4179
4210
  };
4180
4211
  pp$5.parseIdent = function(liberal) {
@@ -4279,36 +4310,36 @@ pp$3.exitScope = function() {
4279
4310
  pp$3.treatFunctionsAsVarInScope = function(scope) {
4280
4311
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
4281
4312
  };
4282
- pp$3.declareName = function(name2, bindingType, pos) {
4313
+ pp$3.declareName = function(name, bindingType, pos) {
4283
4314
  var redeclared = false;
4284
4315
  if (bindingType === BIND_LEXICAL) {
4285
4316
  var scope = this.currentScope();
4286
- redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
4287
- scope.lexical.push(name2);
4317
+ redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
4318
+ scope.lexical.push(name);
4288
4319
  if (this.inModule && scope.flags & SCOPE_TOP) {
4289
- delete this.undefinedExports[name2];
4320
+ delete this.undefinedExports[name];
4290
4321
  }
4291
4322
  } else if (bindingType === BIND_SIMPLE_CATCH) {
4292
4323
  var scope$1 = this.currentScope();
4293
- scope$1.lexical.push(name2);
4324
+ scope$1.lexical.push(name);
4294
4325
  } else if (bindingType === BIND_FUNCTION) {
4295
4326
  var scope$2 = this.currentScope();
4296
4327
  if (this.treatFunctionsAsVar) {
4297
- redeclared = scope$2.lexical.indexOf(name2) > -1;
4328
+ redeclared = scope$2.lexical.indexOf(name) > -1;
4298
4329
  } else {
4299
- redeclared = scope$2.lexical.indexOf(name2) > -1 || scope$2.var.indexOf(name2) > -1;
4330
+ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
4300
4331
  }
4301
- scope$2.functions.push(name2);
4332
+ scope$2.functions.push(name);
4302
4333
  } else {
4303
4334
  for (var i = this.scopeStack.length - 1; i >= 0; --i) {
4304
4335
  var scope$3 = this.scopeStack[i];
4305
- if (scope$3.lexical.indexOf(name2) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name2) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name2) > -1) {
4336
+ if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
4306
4337
  redeclared = true;
4307
4338
  break;
4308
4339
  }
4309
- scope$3.var.push(name2);
4340
+ scope$3.var.push(name);
4310
4341
  if (this.inModule && scope$3.flags & SCOPE_TOP) {
4311
- delete this.undefinedExports[name2];
4342
+ delete this.undefinedExports[name];
4312
4343
  }
4313
4344
  if (scope$3.flags & SCOPE_VAR) {
4314
4345
  break;
@@ -4316,7 +4347,7 @@ pp$3.declareName = function(name2, bindingType, pos) {
4316
4347
  }
4317
4348
  }
4318
4349
  if (redeclared) {
4319
- this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
4350
+ this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
4320
4351
  }
4321
4352
  };
4322
4353
  pp$3.checkLocalExport = function(id) {
@@ -4636,8 +4667,8 @@ pp$1.regexp_pattern = function(state) {
4636
4667
  state.raise("Invalid escape");
4637
4668
  }
4638
4669
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
4639
- var name2 = list[i];
4640
- if (!state.groupNames[name2]) {
4670
+ var name = list[i];
4671
+ if (!state.groupNames[name]) {
4641
4672
  state.raise("Invalid named capture referenced");
4642
4673
  }
4643
4674
  }
@@ -5276,10 +5307,10 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5276
5307
  61
5277
5308
  /* = */
5278
5309
  )) {
5279
- var name2 = state.lastStringValue;
5310
+ var name = state.lastStringValue;
5280
5311
  if (this.regexp_eatUnicodePropertyValue(state)) {
5281
5312
  var value = state.lastStringValue;
5282
- this.regexp_validateUnicodePropertyNameAndValue(state, name2, value);
5313
+ this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
5283
5314
  return CharSetOk;
5284
5315
  }
5285
5316
  }
@@ -5290,11 +5321,11 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5290
5321
  }
5291
5322
  return CharSetNone;
5292
5323
  };
5293
- pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name2, value) {
5294
- if (!hasOwn(state.unicodeProperties.nonBinary, name2)) {
5324
+ pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
5325
+ if (!hasOwn(state.unicodeProperties.nonBinary, name)) {
5295
5326
  state.raise("Invalid property name");
5296
5327
  }
5297
- if (!state.unicodeProperties.nonBinary[name2].test(value)) {
5328
+ if (!state.unicodeProperties.nonBinary[name].test(value)) {
5298
5329
  state.raise("Invalid property value");
5299
5330
  }
5300
5331
  };
@@ -6705,17 +6736,17 @@ codes.ERR_INVALID_ARG_TYPE = createError(
6705
6736
  * @param {Array<string> | string} expected
6706
6737
  * @param {unknown} actual
6707
6738
  */
6708
- (name2, expected, actual) => {
6709
- assert(typeof name2 === "string", "'name' must be a string");
6739
+ (name, expected, actual) => {
6740
+ assert(typeof name === "string", "'name' must be a string");
6710
6741
  if (!Array.isArray(expected)) {
6711
6742
  expected = [expected];
6712
6743
  }
6713
6744
  let message = "The ";
6714
- if (name2.endsWith(" argument")) {
6715
- message += `${name2} `;
6745
+ if (name.endsWith(" argument")) {
6746
+ message += `${name} `;
6716
6747
  } else {
6717
- const type = name2.includes(".") ? "property" : "argument";
6718
- message += `"${name2}" ${type} `;
6748
+ const type = name.includes(".") ? "property" : "argument";
6749
+ message += `"${name}" ${type} `;
6719
6750
  }
6720
6751
  message += "must be ";
6721
6752
  const types2 = [];
@@ -6885,13 +6916,13 @@ codes.ERR_INVALID_ARG_VALUE = createError(
6885
6916
  * @param {unknown} value
6886
6917
  * @param {string} [reason='is invalid']
6887
6918
  */
6888
- (name2, value, reason = "is invalid") => {
6919
+ (name, value, reason = "is invalid") => {
6889
6920
  let inspected = inspect(value);
6890
6921
  if (inspected.length > 128) {
6891
6922
  inspected = `${inspected.slice(0, 128)}...`;
6892
6923
  }
6893
- const type = name2.includes(".") ? "property" : "argument";
6894
- return `The ${type} '${name2}' ${reason}. Received ${inspected}`;
6924
+ const type = name.includes(".") ? "property" : "argument";
6925
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`;
6895
6926
  },
6896
6927
  TypeError
6897
6928
  // Note: extra classes have been shaken out.
@@ -7693,10 +7724,10 @@ function patternKeyCompare(a, b) {
7693
7724
  if (b.length > a.length) return 1;
7694
7725
  return 0;
7695
7726
  }
7696
- function packageImportsResolve(name2, base, conditions) {
7697
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
7727
+ function packageImportsResolve(name, base, conditions) {
7728
+ if (name === "#" || name.startsWith("#/") || name.endsWith("/")) {
7698
7729
  const reason = "is not a valid internal imports specifier name";
7699
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
7730
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base));
7700
7731
  }
7701
7732
  let packageJsonUrl;
7702
7733
  const packageConfig = getPackageScopeConfig(base);
@@ -7704,12 +7735,12 @@ function packageImportsResolve(name2, base, conditions) {
7704
7735
  packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
7705
7736
  const imports = packageConfig.imports;
7706
7737
  if (imports) {
7707
- if (own.call(imports, name2) && !name2.includes("*")) {
7738
+ if (own.call(imports, name) && !name.includes("*")) {
7708
7739
  const resolveResult = resolvePackageTarget(
7709
7740
  packageJsonUrl,
7710
- imports[name2],
7741
+ imports[name],
7711
7742
  "",
7712
- name2,
7743
+ name,
7713
7744
  base,
7714
7745
  false,
7715
7746
  true,
@@ -7727,13 +7758,13 @@ function packageImportsResolve(name2, base, conditions) {
7727
7758
  while (++i < keys.length) {
7728
7759
  const key = keys[i];
7729
7760
  const patternIndex = key.indexOf("*");
7730
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
7761
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
7731
7762
  const patternTrailer = key.slice(patternIndex + 1);
7732
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7763
+ if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7733
7764
  bestMatch = key;
7734
- bestMatchSubpath = name2.slice(
7765
+ bestMatchSubpath = name.slice(
7735
7766
  patternIndex,
7736
- name2.length - patternTrailer.length
7767
+ name.length - patternTrailer.length
7737
7768
  );
7738
7769
  }
7739
7770
  }
@@ -7758,7 +7789,7 @@ function packageImportsResolve(name2, base, conditions) {
7758
7789
  }
7759
7790
  }
7760
7791
  }
7761
- throw importNotDefined(name2, packageJsonUrl, base);
7792
+ throw importNotDefined(name, packageJsonUrl, base);
7762
7793
  }
7763
7794
  function parsePackageName(specifier, base) {
7764
7795
  let separatorIndex = specifier.indexOf("/");
@@ -8057,8 +8088,11 @@ globalThis.${globalName} = var_${globalName};
8057
8088
  globalThis.${globalName} = var_${globalName}.${exportName};
8058
8089
  `;
8059
8090
  }).join("\n");
8091
+ const polyfillCode = env.polyfill.map((polyfillPath) => `import "${polyfillPath}";
8092
+ `).join("");
8060
8093
  const modified = new MagicString(code);
8061
8094
  modified.prepend(injectedCode);
8095
+ modified.prepend(polyfillCode);
8062
8096
  return {
8063
8097
  code: modified.toString(),
8064
8098
  map: modified.generateMap({ hires: "boundary", source: id })
@@ -8092,20 +8126,20 @@ function getNodeCompatEntries() {
8092
8126
  entries.add(globalInject[0]);
8093
8127
  }
8094
8128
  }
8129
+ env.polyfill.forEach((polyfill) => entries.add(polyfill));
8095
8130
  nodeCompatExternals.forEach((external) => entries.delete(external));
8096
8131
  return entries;
8097
8132
  }
8098
8133
 
8099
- // src/constants.ts
8100
- var ROUTER_WORKER_NAME = "__router-worker__";
8101
- var ASSET_WORKER_NAME = "__asset-worker__";
8102
- var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
8103
- var MODULE_TYPES = ["CompiledWasm"];
8104
-
8105
8134
  // src/shared.ts
8106
8135
  var UNKNOWN_HOST = "http://localhost";
8107
8136
  var INIT_PATH = "/__vite_plugin_cloudflare_init__";
8108
- var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
8137
+ var ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${ADDITIONAL_MODULE_TYPES.join("|")})__(.*?)__`;
8138
+ var additionalModuleRE = new RegExp(ADDITIONAL_MODULE_PATTERN);
8139
+ var additionalModuleGlobalRE = new RegExp(
8140
+ ADDITIONAL_MODULE_PATTERN,
8141
+ "g"
8142
+ );
8109
8143
  var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
8110
8144
 
8111
8145
  // src/utils.ts
@@ -8116,6 +8150,9 @@ function getOutputDirectory(userConfig, environmentName) {
8116
8150
  const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
8117
8151
  return userConfig.environments?.[environmentName]?.build?.outDir ?? path2.join(rootOutputDirectory, environmentName);
8118
8152
  }
8153
+ function getRouterWorker(miniflare) {
8154
+ return miniflare.getWorker(ROUTER_WORKER_NAME);
8155
+ }
8119
8156
  function toMiniflareRequest(request) {
8120
8157
  return new MiniflareRequest(request.url, {
8121
8158
  method: request.method,
@@ -8137,6 +8174,10 @@ function nodeHeadersToWebHeaders(nodeHeaders) {
8137
8174
  }
8138
8175
  return headers;
8139
8176
  }
8177
+ var postfixRE = /[?#].*$/;
8178
+ function cleanUrl(url) {
8179
+ return url.replace(postfixRE, "");
8180
+ }
8140
8181
 
8141
8182
  // src/cloudflare-environment.ts
8142
8183
  var webSocketUndefinedError = "The WebSocket is undefined";
@@ -8185,9 +8226,9 @@ function createHotChannel(webSocketContainer) {
8185
8226
  var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
8186
8227
  #webSocketContainer;
8187
8228
  #worker;
8188
- constructor(name2, config) {
8229
+ constructor(name, config) {
8189
8230
  const webSocketContainer = {};
8190
- super(name2, config, {
8231
+ super(name, config, {
8191
8232
  hot: true,
8192
8233
  transport: createHotChannel(webSocketContainer)
8193
8234
  });
@@ -8237,13 +8278,13 @@ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmen
8237
8278
  builtins: [...cloudflareBuiltInModules]
8238
8279
  },
8239
8280
  dev: {
8240
- createEnvironment(name2, config) {
8241
- return new CloudflareDevEnvironment(name2, config);
8281
+ createEnvironment(name, config) {
8282
+ return new CloudflareDevEnvironment(name, config);
8242
8283
  }
8243
8284
  },
8244
8285
  build: {
8245
- createEnvironment(name2, config) {
8246
- return new vite2.BuildEnvironment(name2, config);
8286
+ createEnvironment(name, config) {
8287
+ return new vite2.BuildEnvironment(name, config);
8247
8288
  },
8248
8289
  target,
8249
8290
  // We need to enable `emitAssets` in order to support additional modules defined by `rules`
@@ -8377,16 +8418,8 @@ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
8377
8418
  }
8378
8419
  }
8379
8420
 
8380
- // src/dev.ts
8381
- import assert5 from "node:assert";
8382
- function getDevEntryWorker(resolvedPluginConfig, miniflare) {
8383
- const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8384
- assert5(entryWorkerConfig, "Unexpected error: No entry worker configuration");
8385
- return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
8386
- }
8387
-
8388
8421
  // src/miniflare-options.ts
8389
- import assert6 from "node:assert";
8422
+ import assert5 from "node:assert";
8390
8423
  import * as fs3 from "node:fs";
8391
8424
  import * as fsp from "node:fs/promises";
8392
8425
  import * as path4 from "node:path";
@@ -8434,7 +8467,7 @@ function getWorkerToWorkerEntrypointNamesMap(workers) {
8434
8467
  if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
8435
8468
  const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
8436
8469
  const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
8437
- assert6(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8470
+ assert5(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8438
8471
  entrypointNames.add(value.entrypoint);
8439
8472
  }
8440
8473
  }
@@ -8449,20 +8482,20 @@ function getWorkerToDurableObjectClassNamesMap(workers) {
8449
8482
  for (const value of Object.values(worker.durableObjects ?? {})) {
8450
8483
  if (typeof value === "string") {
8451
8484
  const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
8452
- assert6(classNames, missingWorkerErrorMessage(worker.name));
8485
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8453
8486
  classNames.add(value);
8454
8487
  } else if (typeof value === "object") {
8455
8488
  if (value.scriptName) {
8456
8489
  const classNames = workerToDurableObjectClassNamesMap.get(
8457
8490
  value.scriptName
8458
8491
  );
8459
- assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8492
+ assert5(classNames, missingWorkerErrorMessage(value.scriptName));
8460
8493
  classNames.add(value.className);
8461
8494
  } else {
8462
8495
  const classNames = workerToDurableObjectClassNamesMap.get(
8463
8496
  worker.name
8464
8497
  );
8465
- assert6(classNames, missingWorkerErrorMessage(worker.name));
8498
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8466
8499
  classNames.add(value.className);
8467
8500
  }
8468
8501
  }
@@ -8480,13 +8513,13 @@ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
8480
8513
  const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8481
8514
  value.scriptName
8482
8515
  );
8483
- assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8516
+ assert5(classNames, missingWorkerErrorMessage(value.scriptName));
8484
8517
  classNames.add(value.className);
8485
8518
  } else {
8486
8519
  const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8487
8520
  worker.name
8488
8521
  );
8489
- assert6(classNames, missingWorkerErrorMessage(worker.name));
8522
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8490
8523
  classNames.add(value.className);
8491
8524
  }
8492
8525
  }
@@ -8605,17 +8638,12 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8605
8638
  __VITE_INVOKE_MODULE__: async (request) => {
8606
8639
  const payload = await request.json();
8607
8640
  const invokePayloadData = payload.data;
8608
- assert6(
8641
+ assert5(
8609
8642
  invokePayloadData.name === "fetchModule",
8610
8643
  `Invalid invoke event: ${invokePayloadData.name}`
8611
8644
  );
8612
8645
  const [moduleId] = invokePayloadData.data;
8613
- const moduleRE = new RegExp(MODULE_PATTERN);
8614
- const shouldExternalize = (
8615
- // Worker modules (CompiledWasm, Text, Data)
8616
- moduleRE.test(moduleId)
8617
- );
8618
- if (shouldExternalize) {
8646
+ if (additionalModuleRE.test(moduleId)) {
8619
8647
  const result2 = {
8620
8648
  externalize: moduleId,
8621
8649
  type: "module"
@@ -8663,7 +8691,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8663
8691
  const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
8664
8692
  workerOptions.name
8665
8693
  );
8666
- assert6(
8694
+ assert5(
8667
8695
  workerEntrypointNames,
8668
8696
  `WorkerEntrypoint names not found for worker ${workerOptions.name}`
8669
8697
  );
@@ -8675,7 +8703,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8675
8703
  const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8676
8704
  workerOptions.name
8677
8705
  );
8678
- assert6(
8706
+ assert5(
8679
8707
  durableObjectClassNames,
8680
8708
  `DurableObject class names not found for worker ${workerOptions.name}`
8681
8709
  );
@@ -8685,7 +8713,7 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8685
8713
  );
8686
8714
  }
8687
8715
  const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
8688
- assert6(
8716
+ assert5(
8689
8717
  workflowEntrypointClassNames,
8690
8718
  `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
8691
8719
  );
@@ -8714,38 +8742,51 @@ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8714
8742
  };
8715
8743
  })
8716
8744
  ],
8717
- unsafeModuleFallbackService(request) {
8745
+ async unsafeModuleFallbackService(request) {
8718
8746
  const url = new URL(request.url);
8719
8747
  const rawSpecifier = url.searchParams.get("rawSpecifier");
8720
- assert6(
8748
+ assert5(
8721
8749
  rawSpecifier,
8722
8750
  `Unexpected error: no specifier in request to module fallback service.`
8723
8751
  );
8724
- const moduleRE = new RegExp(MODULE_PATTERN);
8725
- const match = moduleRE.exec(rawSpecifier);
8726
- assert6(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8752
+ const match = additionalModuleRE.exec(rawSpecifier);
8753
+ assert5(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8727
8754
  const [full, moduleType, modulePath] = match;
8728
- assert6(
8755
+ assert5(
8756
+ moduleType,
8757
+ `Unexpected error: module type not found in reference: ${full}.`
8758
+ );
8759
+ assert5(
8729
8760
  modulePath,
8730
8761
  `Unexpected error: module path not found in reference: ${full}.`
8731
8762
  );
8732
- let source;
8763
+ let contents;
8733
8764
  try {
8734
- source = fs3.readFileSync(modulePath);
8765
+ contents = await fsp.readFile(modulePath);
8735
8766
  } catch (error) {
8736
8767
  throw new Error(
8737
8768
  `Import "${modulePath}" not found. Does the file exist?`
8738
8769
  );
8739
8770
  }
8740
- return MiniflareResponse.json({
8741
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
8742
- wasm: Array.from(source)
8743
- });
8771
+ switch (moduleType) {
8772
+ case "CompiledWasm": {
8773
+ return MiniflareResponse.json({ wasm: Array.from(contents) });
8774
+ }
8775
+ case "Data": {
8776
+ return MiniflareResponse.json({ data: Array.from(contents) });
8777
+ }
8778
+ case "Text": {
8779
+ return MiniflareResponse.json({ text: contents.toString() });
8780
+ }
8781
+ default: {
8782
+ return MiniflareResponse.error();
8783
+ }
8784
+ }
8744
8785
  }
8745
8786
  };
8746
8787
  }
8747
8788
  function getPreviewModules(main, modulesRules) {
8748
- assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8789
+ assert5(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8749
8790
  const rootPath = path4.dirname(main);
8750
8791
  const entryPath = path4.basename(main);
8751
8792
  return {
@@ -8831,20 +8872,14 @@ function miniflareLogLevelFromViteLogLevel(level = "info") {
8831
8872
  }
8832
8873
 
8833
8874
  // src/plugin-config.ts
8834
- import assert8 from "node:assert";
8875
+ import assert6 from "node:assert";
8835
8876
  import * as path6 from "node:path";
8836
8877
  import * as vite5 from "vite";
8837
8878
 
8838
8879
  // src/workers-configs.ts
8839
- import assert7 from "node:assert";
8840
8880
  import * as fs4 from "node:fs";
8841
8881
  import * as path5 from "node:path";
8842
8882
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
8843
-
8844
- // package.json
8845
- var name = "@cloudflare/vite-plugin";
8846
-
8847
- // src/workers-configs.ts
8848
8883
  var nonApplicableWorkerConfigs = {
8849
8884
  /**
8850
8885
  * Object containing configs that have a vite replacement, the object's field contain details about the config's replacement
@@ -8873,14 +8908,11 @@ var nonApplicableWorkerConfigs = {
8873
8908
  "find_additional_modules",
8874
8909
  "no_bundle",
8875
8910
  "preserve_file_names",
8911
+ "rules",
8876
8912
  "site",
8877
8913
  "tsconfig",
8878
8914
  "upload_source_maps"
8879
- ],
8880
- /**
8881
- * All the configs that get overridden by our plugin
8882
- */
8883
- overridden: ["rules"]
8915
+ ]
8884
8916
  };
8885
8917
  var nullableNonApplicable = [
8886
8918
  "alias",
@@ -8896,8 +8928,7 @@ var nullableNonApplicable = [
8896
8928
  function readWorkerConfig(configPath, env2) {
8897
8929
  const nonApplicable = {
8898
8930
  replacedByVite: /* @__PURE__ */ new Set(),
8899
- notRelevant: /* @__PURE__ */ new Set(),
8900
- overridden: /* @__PURE__ */ new Set()
8931
+ notRelevant: /* @__PURE__ */ new Set()
8901
8932
  };
8902
8933
  const config = unstable_readConfig2({ config: configPath, env: env2 }, {});
8903
8934
  const raw = structuredClone(config);
@@ -8909,9 +8940,6 @@ function readWorkerConfig(configPath, env2) {
8909
8940
  if (isNotRelevant(prop)) {
8910
8941
  nonApplicable.notRelevant.add(prop);
8911
8942
  }
8912
- if (isOverridden(prop)) {
8913
- nonApplicable.overridden.add(prop);
8914
- }
8915
8943
  }
8916
8944
  delete config[prop];
8917
8945
  });
@@ -8924,7 +8952,7 @@ function readWorkerConfig(configPath, env2) {
8924
8952
  }
8925
8953
  delete config["define"];
8926
8954
  if (config.rules.length > 0) {
8927
- nonApplicable.overridden.add("rules");
8955
+ nonApplicable.notRelevant.add("rules");
8928
8956
  }
8929
8957
  return {
8930
8958
  raw,
@@ -8976,7 +9004,7 @@ function getWarningForWorkersConfigs(configs) {
8976
9004
  }
8977
9005
  function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8978
9006
  const lines = [];
8979
- const { replacedByVite, notRelevant, overridden } = workerConfig.nonApplicable;
9007
+ const { replacedByVite, notRelevant } = workerConfig.nonApplicable;
8980
9008
  for (const config of replacedByVite) {
8981
9009
  lines.push(
8982
9010
  `${linePrefix}\`${config}\` which is replaced by Vite's \`${nonApplicableWorkerConfigs.replacedByVite[config].viteReplacement}\` (docs: ${nonApplicableWorkerConfigs.replacedByVite[config].viteDocs})`
@@ -8986,10 +9014,6 @@ function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8986
9014
  lines.push(
8987
9015
  `${linePrefix}${[...notRelevant].map((config) => `\`${config}\``).join(", ")} which ${notRelevant.size > 1 ? "are" : "is"} not relevant in the context of a Vite project`
8988
9016
  );
8989
- if (overridden.size > 0)
8990
- lines.push(
8991
- `${linePrefix}${[...overridden].map((config) => `\`${config}\``).join(", ")} which ${overridden.size > 1 ? "are" : "is"} overridden by \`${name}\``
8992
- );
8993
9017
  return lines;
8994
9018
  }
8995
9019
  function isReplacedByVite(configName) {
@@ -8998,9 +9022,6 @@ function isReplacedByVite(configName) {
8998
9022
  function isNotRelevant(configName) {
8999
9023
  return nonApplicableWorkerConfigs.notRelevant.includes(configName);
9000
9024
  }
9001
- function isOverridden(configName) {
9002
- return nonApplicableWorkerConfigs.overridden.includes(configName);
9003
- }
9004
9025
  function missingFieldErrorMessage(field, configPath, env2) {
9005
9026
  return `No ${field} field provided in '${configPath}'${env2 ? ` for '${env2}' environment` : ""}`;
9006
9027
  }
@@ -9010,34 +9031,38 @@ function getWorkerConfig(configPath, env2, opts) {
9010
9031
  }
9011
9032
  const { raw, config, nonApplicable } = readWorkerConfig(configPath, env2);
9012
9033
  opts?.visitedConfigPaths?.add(configPath);
9013
- assert7(
9014
- config.topLevelName,
9015
- missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
9016
- );
9017
- assert7(config.name, missingFieldErrorMessage(`'name'`, configPath, env2));
9018
- assert7(
9019
- config.compatibility_date,
9020
- missingFieldErrorMessage(`'compatibility_date'`, configPath, env2)
9021
- );
9022
- if (opts?.isEntryWorker && !config.main) {
9023
- assert7(
9024
- config.assets,
9025
- missingFieldErrorMessage(`'main' or 'assets'`, configPath, env2)
9034
+ if (!config.name) {
9035
+ throw new Error(missingFieldErrorMessage(`'name'`, configPath, env2));
9036
+ }
9037
+ if (!config.topLevelName) {
9038
+ throw new Error(
9039
+ missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
9040
+ );
9041
+ }
9042
+ if (!config.compatibility_date) {
9043
+ throw new Error(
9044
+ missingFieldErrorMessage(`'compatibility_date`, configPath, env2)
9026
9045
  );
9046
+ }
9047
+ const requiredFields = {
9048
+ topLevelName: config.topLevelName,
9049
+ name: config.name,
9050
+ compatibility_date: config.compatibility_date
9051
+ };
9052
+ if (opts?.isEntryWorker && !config.main) {
9027
9053
  return {
9028
9054
  type: "assets-only",
9029
9055
  raw,
9030
9056
  config: {
9031
9057
  ...config,
9032
- topLevelName: config.topLevelName,
9033
- name: config.name,
9034
- compatibility_date: config.compatibility_date,
9035
- assets: config.assets
9058
+ ...requiredFields
9036
9059
  },
9037
9060
  nonApplicable
9038
9061
  };
9039
9062
  }
9040
- assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9063
+ if (!config.main) {
9064
+ throw new Error(missingFieldErrorMessage(`'main'`, configPath, env2));
9065
+ }
9041
9066
  const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9042
9067
  if (!mainStat) {
9043
9068
  throw new Error(
@@ -9054,9 +9079,7 @@ function getWorkerConfig(configPath, env2, opts) {
9054
9079
  raw,
9055
9080
  config: {
9056
9081
  ...config,
9057
- topLevelName: config.topLevelName,
9058
- name: config.name,
9059
- compatibility_date: config.compatibility_date,
9082
+ ...requiredFields,
9060
9083
  main: config.main
9061
9084
  },
9062
9085
  nonApplicable
@@ -9086,10 +9109,11 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9086
9109
  ""
9087
9110
  );
9088
9111
  const configPath = pluginConfig.configPath ? path6.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
9089
- assert8(
9090
- configPath,
9091
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9092
- );
9112
+ if (!configPath) {
9113
+ throw new Error(
9114
+ `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9115
+ );
9116
+ }
9093
9117
  const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
9094
9118
  visitedConfigPaths: configPaths,
9095
9119
  isEntryWorker: true
@@ -9121,7 +9145,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9121
9145
  }
9122
9146
  );
9123
9147
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
9124
- assert8(
9148
+ assert6(
9125
9149
  workerResolvedConfig.type === "worker",
9126
9150
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
9127
9151
  );
@@ -9184,14 +9208,18 @@ function handleWebSocket(httpServer, fetcher) {
9184
9208
  }
9185
9209
 
9186
9210
  // src/index.ts
9211
+ var workersConfigsWarningShown = false;
9187
9212
  function cloudflare2(pluginConfig = {}) {
9188
9213
  let resolvedPluginConfig;
9189
9214
  let resolvedViteConfig;
9190
9215
  let miniflare;
9191
- let workersConfigsWarningShown = false;
9216
+ const additionalModulePaths = /* @__PURE__ */ new Set();
9217
+ let hasClientBuild = false;
9192
9218
  return [
9193
9219
  {
9194
9220
  name: "vite-plugin-cloudflare",
9221
+ // This only applies to this plugin so is safe to use while other plugins migrate to the Environment API
9222
+ sharedDuringBuild: true,
9195
9223
  config(userConfig, env2) {
9196
9224
  if (env2.isPreview) {
9197
9225
  return { appType: "custom" };
@@ -9248,7 +9276,7 @@ function cloudflare2(pluginConfig = {}) {
9248
9276
  resolvedPluginConfig.workers
9249
9277
  ).map((environmentName) => {
9250
9278
  const environment = builder.environments[environmentName];
9251
- assert9(
9279
+ assert7(
9252
9280
  environment,
9253
9281
  `${environmentName} environment not found`
9254
9282
  );
@@ -9264,6 +9292,9 @@ function cloudflare2(pluginConfig = {}) {
9264
9292
  }
9265
9293
  };
9266
9294
  },
9295
+ buildStart() {
9296
+ workersConfigsWarningShown = false;
9297
+ },
9267
9298
  configResolved(config) {
9268
9299
  resolvedViteConfig = config;
9269
9300
  },
@@ -9278,18 +9309,27 @@ function cloudflare2(pluginConfig = {}) {
9278
9309
  return;
9279
9310
  }
9280
9311
  workerConfig.main = entryChunk[0];
9312
+ workerConfig.no_bundle = true;
9313
+ workerConfig.rules = [
9314
+ { type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }
9315
+ ];
9281
9316
  const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
9282
- if (isEntryWorker && workerConfig.assets) {
9317
+ if (isEntryWorker && hasClientBuild) {
9283
9318
  const workerOutputDirectory = this.environment.config.build.outDir;
9284
9319
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
9285
- assert9(
9320
+ assert7(
9286
9321
  clientOutputDirectory,
9287
9322
  "Unexpected error: client output directory is undefined"
9288
9323
  );
9289
- workerConfig.assets.directory = path7.relative(
9290
- path7.resolve(resolvedViteConfig.root, workerOutputDirectory),
9291
- path7.resolve(resolvedViteConfig.root, clientOutputDirectory)
9292
- );
9324
+ workerConfig.assets = {
9325
+ ...workerConfig.assets,
9326
+ directory: path7.relative(
9327
+ path7.resolve(resolvedViteConfig.root, workerOutputDirectory),
9328
+ path7.resolve(resolvedViteConfig.root, clientOutputDirectory)
9329
+ )
9330
+ };
9331
+ } else {
9332
+ workerConfig.assets = void 0;
9293
9333
  }
9294
9334
  config = workerConfig;
9295
9335
  if (workerConfig.configPath) {
@@ -9307,7 +9347,10 @@ function cloudflare2(pluginConfig = {}) {
9307
9347
  }
9308
9348
  } else if (this.environment.name === "client") {
9309
9349
  const assetsOnlyConfig = resolvedPluginConfig.config;
9310
- assetsOnlyConfig.assets.directory = ".";
9350
+ assetsOnlyConfig.assets = {
9351
+ ...assetsOnlyConfig.assets,
9352
+ directory: "."
9353
+ };
9311
9354
  const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
9312
9355
  this.emitFile({
9313
9356
  type: "asset",
@@ -9320,8 +9363,6 @@ function cloudflare2(pluginConfig = {}) {
9320
9363
  if (!config) {
9321
9364
  return;
9322
9365
  }
9323
- config.no_bundle = true;
9324
- config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9325
9366
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9326
9367
  config.unsafe = void 0;
9327
9368
  }
@@ -9332,6 +9373,9 @@ function cloudflare2(pluginConfig = {}) {
9332
9373
  });
9333
9374
  },
9334
9375
  writeBundle() {
9376
+ if (this.environment.name === "client") {
9377
+ hasClientBuild = true;
9378
+ }
9335
9379
  if (this.environment.name === (resolvedPluginConfig.type === "assets-only" ? "client" : resolvedPluginConfig.entryWorkerEnvironmentName)) {
9336
9380
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
9337
9381
  }
@@ -9348,7 +9392,7 @@ function cloudflare2(pluginConfig = {}) {
9348
9392
  }
9349
9393
  },
9350
9394
  async configureServer(viteDevServer) {
9351
- assert9(
9395
+ assert7(
9352
9396
  viteDevServer.httpServer,
9353
9397
  "Unexpected error: No Vite HTTP server"
9354
9398
  );
@@ -9356,19 +9400,16 @@ function cloudflare2(pluginConfig = {}) {
9356
9400
  getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
9357
9401
  );
9358
9402
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
9359
- const entryWorker = await getDevEntryWorker(
9360
- resolvedPluginConfig,
9361
- miniflare
9362
- );
9403
+ const routerWorker = await getRouterWorker(miniflare);
9363
9404
  const middleware = createMiddleware(
9364
9405
  ({ request }) => {
9365
- return entryWorker.fetch(toMiniflareRequest(request), {
9406
+ return routerWorker.fetch(toMiniflareRequest(request), {
9366
9407
  redirect: "manual"
9367
9408
  });
9368
9409
  },
9369
9410
  { alwaysCallNext: false }
9370
9411
  );
9371
- handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9412
+ handleWebSocket(viteDevServer.httpServer, routerWorker.fetch);
9372
9413
  return () => {
9373
9414
  viteDevServer.middlewares.use((req, res, next) => {
9374
9415
  middleware(req, res, next);
@@ -9396,46 +9437,55 @@ function cloudflare2(pluginConfig = {}) {
9396
9437
  });
9397
9438
  }
9398
9439
  },
9399
- // Plugin to support `CompiledWasm` modules
9440
+ // Plugin to support additional modules
9400
9441
  {
9401
- name: "vite-plugin-cloudflare:modules",
9442
+ name: "vite-plugin-cloudflare:additional-modules",
9402
9443
  // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
9403
9444
  // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
9404
9445
  enforce: "pre",
9405
9446
  applyToEnvironment(environment) {
9406
9447
  return getWorkerConfig2(environment.name) !== void 0;
9407
9448
  },
9408
- async resolveId(source, importer) {
9409
- if (!source.endsWith(".wasm")) {
9449
+ async resolveId(source, importer, options) {
9450
+ const additionalModuleType = matchAdditionalModule(source);
9451
+ if (!additionalModuleType) {
9410
9452
  return;
9411
9453
  }
9412
- const resolved = await this.resolve(source, importer);
9413
- assert9(
9414
- resolved,
9415
- `Unexpected error: could not resolve Wasm module ${source}`
9454
+ const resolved = await this.resolve(
9455
+ cleanUrl(source),
9456
+ importer,
9457
+ options
9416
9458
  );
9459
+ if (!resolved) {
9460
+ throw new Error(`Import "${source}" not found. Does the file exist?`);
9461
+ }
9462
+ additionalModulePaths.add(resolved.id);
9417
9463
  return {
9418
9464
  external: true,
9419
- id: createModuleReference("CompiledWasm", resolved.id)
9465
+ id: createModuleReference(additionalModuleType, resolved.id)
9420
9466
  };
9421
9467
  },
9422
- renderChunk(code, chunk) {
9423
- const moduleRE = new RegExp(MODULE_PATTERN, "g");
9424
- let match;
9468
+ hotUpdate(options) {
9469
+ if (additionalModulePaths.has(options.file)) {
9470
+ options.server.restart();
9471
+ }
9472
+ },
9473
+ async renderChunk(code, chunk) {
9474
+ const matches = code.matchAll(additionalModuleGlobalRE);
9425
9475
  let magicString;
9426
- while (match = moduleRE.exec(code)) {
9476
+ for (const match of matches) {
9427
9477
  magicString ??= new MagicString(code);
9428
- const [full, moduleType, modulePath] = match;
9429
- assert9(
9478
+ const [full, _, modulePath] = match;
9479
+ assert7(
9430
9480
  modulePath,
9431
9481
  `Unexpected error: module path not found in reference ${full}.`
9432
9482
  );
9433
9483
  let source;
9434
9484
  try {
9435
- source = fs5.readFileSync(modulePath);
9485
+ source = await fsp2.readFile(modulePath);
9436
9486
  } catch (error) {
9437
9487
  throw new Error(
9438
- `Import ${modulePath} not found. Does the file exist?`
9488
+ `Import "${modulePath}" not found. Does the file exist?`
9439
9489
  );
9440
9490
  }
9441
9491
  const referenceId = this.emitFile({
@@ -9469,8 +9519,8 @@ function cloudflare2(pluginConfig = {}) {
9469
9519
  apply(_config, env2) {
9470
9520
  return !env2.isPreview;
9471
9521
  },
9472
- configEnvironment(name2) {
9473
- if (isNodeCompat(getWorkerConfig2(name2))) {
9522
+ configEnvironment(name) {
9523
+ if (isNodeCompat(getWorkerConfig2(name))) {
9474
9524
  return {
9475
9525
  resolve: {
9476
9526
  builtins: [...nodeCompatExternals]
@@ -9509,7 +9559,7 @@ function cloudflare2(pluginConfig = {}) {
9509
9559
  return this.resolve(source, importer, options);
9510
9560
  }
9511
9561
  if (this.environment.mode === "dev") {
9512
- assert9(
9562
+ assert7(
9513
9563
  this.environment.depsOptimizer,
9514
9564
  "depsOptimizer is required in dev mode"
9515
9565
  );
@@ -9523,7 +9573,7 @@ function cloudflare2(pluginConfig = {}) {
9523
9573
  },
9524
9574
  async transform(code, id) {
9525
9575
  const workerConfig = getWorkerConfig2(this.environment.name);
9526
- assert9(workerConfig, "Expected a worker config");
9576
+ assert7(workerConfig, "Expected a worker config");
9527
9577
  const resolvedId = await this.resolve(workerConfig.main);
9528
9578
  if (id === resolvedId?.id) {
9529
9579
  return injectGlobalCode(id, code);
@@ -9532,7 +9582,7 @@ function cloudflare2(pluginConfig = {}) {
9532
9582
  }
9533
9583
  ];
9534
9584
  function getWorkerConfig2(environmentName) {
9535
- assert9(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9585
+ assert7(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9536
9586
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
9537
9587
  }
9538
9588
  }
@@ -9547,9 +9597,6 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
9547
9597
  }
9548
9598
  return null;
9549
9599
  }
9550
- function createModuleReference(type, id) {
9551
- return `__CLOUDFLARE_MODULE__${type}__${id}__`;
9552
- }
9553
9600
  export {
9554
9601
  cloudflare2 as cloudflare
9555
9602
  };