@cloudflare/vite-plugin 0.0.0-d422c8ecb → 0.0.0-d42966125

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,8 @@
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";
5
+ import { builtinModules as builtinModules2 } from "node:module";
4
6
  import * as path7 from "node:path";
5
7
  import { createMiddleware } from "@hattip/adapter-node";
6
8
 
@@ -1072,801 +1074,127 @@ var MagicString = class _MagicString {
1072
1074
  import { Miniflare } from "miniflare";
1073
1075
  import * as vite6 from "vite";
1074
1076
 
1075
- // src/cloudflare-environment.ts
1076
- import assert from "node:assert";
1077
- import * as vite2 from "vite";
1078
-
1079
1077
  // src/constants.ts
1080
1078
  var ROUTER_WORKER_NAME = "__router-worker__";
1081
1079
  var ASSET_WORKER_NAME = "__asset-worker__";
1082
1080
  var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1083
- var MODULE_TYPES = ["CompiledWasm"];
1084
-
1085
- // src/shared.ts
1086
- var UNKNOWN_HOST = "http://localhost";
1087
- var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1088
- var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1081
+ var ADDITIONAL_MODULE_TYPES = [
1082
+ "CompiledWasm",
1083
+ "Data",
1084
+ "Text"
1085
+ ];
1089
1086
 
1090
- // src/utils.ts
1091
- import { builtinModules } from "node:module";
1092
- import * as path from "node:path";
1093
- import { Request as MiniflareRequest } from "miniflare";
1094
- import "vite";
1095
- var nodeBuiltInModules = new Set(
1096
- builtinModules.concat(builtinModules.map((m) => `node:${m}`))
1097
- );
1098
- function getOutputDirectory(userConfig, environmentName) {
1099
- const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
1100
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
1101
- }
1102
- function toMiniflareRequest(request) {
1103
- return new MiniflareRequest(request.url, {
1104
- method: request.method,
1105
- headers: [["accept-encoding", "identity"], ...request.headers],
1106
- body: request.body,
1107
- duplex: "half"
1108
- });
1109
- }
1110
- function nodeHeadersToWebHeaders(nodeHeaders) {
1111
- const headers = new Headers();
1112
- for (const [key, value] of Object.entries(nodeHeaders)) {
1113
- if (typeof value === "string") {
1114
- headers.append(key, value);
1115
- } else if (Array.isArray(value)) {
1116
- for (const item of value) {
1117
- headers.append(key, item);
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;
1118
1098
  }
1119
1099
  }
1120
1100
  }
1121
- return headers;
1101
+ return null;
1102
+ }
1103
+ function createModuleReference(type, id) {
1104
+ return `__CLOUDFLARE_MODULE__${type}__${id}__`;
1122
1105
  }
1123
1106
 
1124
1107
  // src/cloudflare-environment.ts
1125
- var webSocketUndefinedError = "The WebSocket is undefined";
1126
- function createHotChannel(webSocketContainer) {
1127
- const listenersMap = /* @__PURE__ */ new Map();
1128
- const client = {
1129
- send(payload) {
1130
- const webSocket = webSocketContainer.webSocket;
1131
- assert(webSocket, webSocketUndefinedError);
1132
- webSocket.send(JSON.stringify(payload));
1108
+ import assert3 from "node:assert";
1109
+ import * as vite2 from "vite";
1110
+
1111
+ // src/node-js-compat.ts
1112
+ import assert2 from "node:assert";
1113
+ import { cloudflare } from "@cloudflare/unenv-preset";
1114
+ import { getNodeCompat } from "miniflare";
1115
+
1116
+ // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1117
+ var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
1118
+ var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
1119
+ var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
1120
+ var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
1121
+ var reservedWords = {
1122
+ 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
1123
+ 5: "class enum extends super const export import",
1124
+ 6: "enum",
1125
+ strict: "implements interface let package private protected public static yield",
1126
+ strictBind: "eval arguments"
1127
+ };
1128
+ var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
1129
+ var keywords$1 = {
1130
+ 5: ecma5AndLessKeywords,
1131
+ "5module": ecma5AndLessKeywords + " export import",
1132
+ 6: ecma5AndLessKeywords + " const class extends export import super"
1133
+ };
1134
+ var keywordRelationalOperator = /^in(stanceof)?$/;
1135
+ var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1136
+ var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1137
+ function isInAstralSet(code, set) {
1138
+ var pos = 65536;
1139
+ for (var i = 0; i < set.length; i += 2) {
1140
+ pos += set[i];
1141
+ if (pos > code) {
1142
+ return false;
1133
1143
  }
1134
- };
1135
- function onMessage(event) {
1136
- const payload = JSON.parse(event.data.toString());
1137
- const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
1138
- for (const listener of listeners) {
1139
- listener(payload.data, client);
1144
+ pos += set[i + 1];
1145
+ if (pos >= code) {
1146
+ return true;
1140
1147
  }
1141
1148
  }
1142
- return {
1143
- send(payload) {
1144
- const webSocket = webSocketContainer.webSocket;
1145
- assert(webSocket, webSocketUndefinedError);
1146
- webSocket.send(JSON.stringify(payload));
1147
- },
1148
- on(event, listener) {
1149
- const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
1150
- listeners.add(listener);
1151
- listenersMap.set(event, listeners);
1152
- },
1153
- off(event, listener) {
1154
- listenersMap.get(event)?.delete(listener);
1155
- },
1156
- listen() {
1157
- const webSocket = webSocketContainer.webSocket;
1158
- assert(webSocket, webSocketUndefinedError);
1159
- webSocket.addEventListener("message", onMessage);
1160
- },
1161
- close() {
1162
- const webSocket = webSocketContainer.webSocket;
1163
- assert(webSocket, webSocketUndefinedError);
1164
- webSocket.removeEventListener("message", onMessage);
1165
- }
1166
- };
1149
+ return false;
1167
1150
  }
1168
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
1169
- #webSocketContainer;
1170
- #worker;
1171
- constructor(name2, config) {
1172
- const webSocketContainer = {};
1173
- super(name2, config, {
1174
- hot: true,
1175
- transport: createHotChannel(webSocketContainer)
1176
- });
1177
- this.#webSocketContainer = webSocketContainer;
1151
+ function isIdentifierStart(code, astral) {
1152
+ if (code < 65) {
1153
+ return code === 36;
1178
1154
  }
1179
- async initRunner(worker) {
1180
- this.#worker = worker;
1181
- const response = await this.#worker.fetch(
1182
- new URL(INIT_PATH, UNKNOWN_HOST),
1183
- {
1184
- headers: {
1185
- upgrade: "websocket"
1186
- }
1187
- }
1188
- );
1189
- assert(
1190
- response.ok,
1191
- `Failed to initialize module runner, error: ${await response.text()}`
1192
- );
1193
- const webSocket = response.webSocket;
1194
- assert(webSocket, "Failed to establish WebSocket");
1195
- webSocket.accept();
1196
- this.#webSocketContainer.webSocket = webSocket;
1155
+ if (code < 91) {
1156
+ return true;
1197
1157
  }
1198
- };
1199
- var cloudflareBuiltInModules = [
1200
- "cloudflare:email",
1201
- "cloudflare:sockets",
1202
- "cloudflare:workers",
1203
- "cloudflare:workflows"
1204
- ];
1205
- var defaultConditions = ["workerd", "module", "browser"];
1206
- function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1207
- return {
1208
- resolve: {
1209
- // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
1210
- // dependencies as not external
1211
- noExternal: true,
1212
- // We want to use `workerd` package exports if available (e.g. for postgres).
1213
- conditions: [...defaultConditions, "development|production"],
1214
- // The Cloudflare ones are proper builtins in the environment
1215
- builtins: [...cloudflareBuiltInModules],
1216
- // The Node.js ones are no proper builtins in the environment since we also polyfill them using unenv
1217
- external: [...nodeBuiltInModules]
1218
- },
1219
- dev: {
1220
- createEnvironment(name2, config) {
1221
- return new CloudflareDevEnvironment(name2, config);
1222
- }
1223
- },
1224
- build: {
1225
- createEnvironment(name2, config) {
1226
- return new vite2.BuildEnvironment(name2, config);
1227
- },
1228
- target: "es2022",
1229
- // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1230
- emitAssets: true,
1231
- outDir: getOutputDirectory(userConfig, environmentName),
1232
- copyPublicDir: false,
1233
- ssr: true,
1234
- rollupOptions: {
1235
- // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
1236
- // so the input value here serves both as the build input as well as the starting point for
1237
- // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
1238
- // optimizeDeps.entries in the dev config)
1239
- input: workerConfig.main
1240
- }
1241
- },
1242
- optimizeDeps: {
1243
- // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1244
- noDiscovery: false,
1245
- entries: workerConfig.main,
1246
- exclude: [
1247
- // we have to exclude all node modules to work in dev-mode not just the unenv externals...
1248
- ...nodeBuiltInModules
1249
- ],
1250
- esbuildOptions: {
1251
- platform: "neutral",
1252
- conditions: [...defaultConditions, "development"],
1253
- resolveExtensions: [
1254
- ".mjs",
1255
- ".js",
1256
- ".mts",
1257
- ".ts",
1258
- ".jsx",
1259
- ".tsx",
1260
- ".json",
1261
- ".cjs",
1262
- ".cts",
1263
- ".ctx"
1264
- ]
1265
- }
1266
- },
1267
- keepProcessEnv: false
1268
- };
1269
- }
1270
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
1271
- if (resolvedPluginConfig.type === "assets-only") {
1272
- return;
1158
+ if (code < 97) {
1159
+ return code === 95;
1273
1160
  }
1274
- return Promise.all(
1275
- Object.entries(resolvedPluginConfig.workers).map(
1276
- async ([environmentName, workerConfig]) => {
1277
- const worker = await miniflare.getWorker(workerConfig.name);
1278
- return viteDevServer.environments[environmentName].initRunner(worker);
1279
- }
1280
- )
1281
- );
1161
+ if (code < 123) {
1162
+ return true;
1163
+ }
1164
+ if (code <= 65535) {
1165
+ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1166
+ }
1167
+ if (astral === false) {
1168
+ return false;
1169
+ }
1170
+ return isInAstralSet(code, astralIdentifierStartCodes);
1282
1171
  }
1283
-
1284
- // src/deploy-config.ts
1285
- import assert2 from "node:assert";
1286
- import * as fs from "node:fs";
1287
- import * as path2 from "node:path";
1288
- import "vite";
1289
- function getDeployConfigPath(root) {
1290
- return path2.resolve(root, ".wrangler", "deploy", "config.json");
1291
- }
1292
- function getWorkerConfigPaths(root) {
1293
- const deployConfigPath = getDeployConfigPath(root);
1294
- const deployConfig = JSON.parse(
1295
- fs.readFileSync(deployConfigPath, "utf-8")
1296
- );
1297
- return [
1298
- { configPath: deployConfig.configPath },
1299
- ...deployConfig.auxiliaryWorkers
1300
- ].map(
1301
- ({ configPath }) => path2.resolve(path2.dirname(deployConfigPath), configPath)
1302
- );
1303
- }
1304
- function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
1305
- return path2.relative(
1306
- deployConfigDirectory,
1307
- path2.resolve(root, outputDirectory, "wrangler.json")
1308
- );
1309
- }
1310
- function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1311
- const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
1312
- const deployConfigDirectory = path2.dirname(deployConfigPath);
1313
- fs.mkdirSync(deployConfigDirectory, { recursive: true });
1314
- if (resolvedPluginConfig.type === "assets-only") {
1315
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
1316
- assert2(
1317
- clientOutputDirectory,
1318
- "Unexpected error: client environment output directory is undefined"
1319
- );
1320
- const deployConfig = {
1321
- configPath: getRelativePathToWorkerConfig(
1322
- deployConfigDirectory,
1323
- resolvedViteConfig.root,
1324
- clientOutputDirectory
1325
- ),
1326
- auxiliaryWorkers: []
1327
- };
1328
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1329
- } else {
1330
- let entryWorkerConfigPath;
1331
- const auxiliaryWorkers = [];
1332
- for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
1333
- const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
1334
- assert2(
1335
- outputDirectory,
1336
- `Unexpected error: ${environmentName} environment output directory is undefined`
1337
- );
1338
- const configPath = getRelativePathToWorkerConfig(
1339
- deployConfigDirectory,
1340
- resolvedViteConfig.root,
1341
- outputDirectory
1342
- );
1343
- if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
1344
- entryWorkerConfigPath = configPath;
1345
- } else {
1346
- auxiliaryWorkers.push({ configPath });
1347
- }
1348
- }
1349
- assert2(
1350
- entryWorkerConfigPath,
1351
- `Unexpected error: entryWorkerConfigPath is undefined`
1352
- );
1353
- const deployConfig = {
1354
- configPath: entryWorkerConfigPath,
1355
- auxiliaryWorkers
1356
- };
1357
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1358
- }
1359
- }
1360
-
1361
- // src/dev.ts
1362
- import assert3 from "node:assert";
1363
- function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1364
- const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1365
- assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
1366
- return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
1367
- }
1368
-
1369
- // src/miniflare-options.ts
1370
- import assert4 from "node:assert";
1371
- import * as fs2 from "node:fs";
1372
- import * as fsp from "node:fs/promises";
1373
- import * as path3 from "node:path";
1374
- import { fileURLToPath } from "node:url";
1375
- import { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
1376
- import "vite";
1377
- import {
1378
- unstable_getMiniflareWorkerOptions,
1379
- unstable_readConfig
1380
- } from "wrangler";
1381
- function getPersistence(root, persistState) {
1382
- if (persistState === false) {
1383
- return {};
1384
- }
1385
- const defaultPersistPath = ".wrangler/state";
1386
- const persistPath = path3.resolve(
1387
- root,
1388
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1389
- "v3"
1390
- );
1391
- return {
1392
- cachePersist: path3.join(persistPath, "cache"),
1393
- d1Persist: path3.join(persistPath, "d1"),
1394
- durableObjectsPersist: path3.join(persistPath, "do"),
1395
- kvPersist: path3.join(persistPath, "kv"),
1396
- r2Persist: path3.join(persistPath, "r2"),
1397
- workflowsPersist: path3.join(persistPath, "workflows")
1398
- };
1399
- }
1400
- function missingWorkerErrorMessage(workerName) {
1401
- return `${workerName} does not match a worker name.`;
1402
- }
1403
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1404
- const workerToWorkerEntrypointNamesMap = new Map(
1405
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1406
- );
1407
- for (const worker of workers) {
1408
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1409
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1410
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1411
- value.name
1412
- );
1413
- assert4(entrypointNames, missingWorkerErrorMessage(value.name));
1414
- entrypointNames.add(value.entrypoint);
1415
- }
1416
- }
1417
- }
1418
- return workerToWorkerEntrypointNamesMap;
1419
- }
1420
- function getWorkerToDurableObjectClassNamesMap(workers) {
1421
- const workerToDurableObjectClassNamesMap = new Map(
1422
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1423
- );
1424
- for (const worker of workers) {
1425
- for (const value of Object.values(worker.durableObjects ?? {})) {
1426
- if (typeof value === "string") {
1427
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1428
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1429
- classNames.add(value);
1430
- } else if (typeof value === "object") {
1431
- if (value.scriptName) {
1432
- const classNames = workerToDurableObjectClassNamesMap.get(
1433
- value.scriptName
1434
- );
1435
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1436
- classNames.add(value.className);
1437
- } else {
1438
- const classNames = workerToDurableObjectClassNamesMap.get(
1439
- worker.name
1440
- );
1441
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1442
- classNames.add(value.className);
1443
- }
1444
- }
1445
- }
1446
- }
1447
- return workerToDurableObjectClassNamesMap;
1448
- }
1449
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1450
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1451
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1452
- );
1453
- for (const worker of workers) {
1454
- for (const value of Object.values(worker.workflows ?? {})) {
1455
- if (value.scriptName) {
1456
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1457
- value.scriptName
1458
- );
1459
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1460
- classNames.add(value.className);
1461
- } else {
1462
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1463
- worker.name
1464
- );
1465
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1466
- classNames.add(value.className);
1467
- }
1468
- }
1469
- }
1470
- return workerToWorkflowEntrypointClassNamesMap;
1471
- }
1472
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1473
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1474
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1475
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1476
- var RUNNER_PATH = "./runner-worker/index.js";
1477
- function getEntryWorkerConfig(resolvedPluginConfig) {
1478
- if (resolvedPluginConfig.type === "assets-only") {
1479
- return;
1480
- }
1481
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1482
- }
1483
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1484
- const resolvedViteConfig = viteDevServer.config;
1485
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1486
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1487
- const assetWorkers = [
1488
- {
1489
- name: ROUTER_WORKER_NAME,
1490
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1491
- modulesRoot: miniflareModulesRoot,
1492
- modules: [
1493
- {
1494
- type: "ESModule",
1495
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1496
- contents: fs2.readFileSync(
1497
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1498
- )
1499
- }
1500
- ],
1501
- bindings: {
1502
- CONFIG: {
1503
- has_user_worker: resolvedPluginConfig.type === "workers"
1504
- }
1505
- },
1506
- serviceBindings: {
1507
- ASSET_WORKER: ASSET_WORKER_NAME,
1508
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1509
- }
1510
- },
1511
- {
1512
- name: ASSET_WORKER_NAME,
1513
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1514
- modulesRoot: miniflareModulesRoot,
1515
- modules: [
1516
- {
1517
- type: "ESModule",
1518
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1519
- contents: fs2.readFileSync(
1520
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1521
- )
1522
- }
1523
- ],
1524
- bindings: {
1525
- CONFIG: {
1526
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1527
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1528
- }
1529
- },
1530
- serviceBindings: {
1531
- __VITE_ASSET_EXISTS__: async (request) => {
1532
- const { pathname } = new URL(request.url);
1533
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1534
- let exists;
1535
- try {
1536
- exists = fs2.statSync(filePath).isFile();
1537
- } catch (error) {
1538
- exists = false;
1539
- }
1540
- return MiniflareResponse.json(exists);
1541
- },
1542
- __VITE_FETCH_ASSET__: async (request) => {
1543
- const { pathname } = new URL(request.url);
1544
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1545
- try {
1546
- let html = await fsp.readFile(filePath, "utf-8");
1547
- html = await viteDevServer.transformIndexHtml(pathname, html);
1548
- return new MiniflareResponse(html, {
1549
- headers: { "Content-Type": "text/html" }
1550
- });
1551
- } catch (error) {
1552
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1553
- }
1554
- }
1555
- }
1556
- }
1557
- ];
1558
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1559
- ([environmentName, workerConfig]) => {
1560
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1561
- {
1562
- ...workerConfig,
1563
- assets: void 0
1564
- },
1565
- resolvedPluginConfig.cloudflareEnv
1566
- );
1567
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1568
- return {
1569
- ...workerOptions,
1570
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1571
- name: workerConfig.name,
1572
- modulesRoot: miniflareModulesRoot,
1573
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1574
- bindings: {
1575
- ...workerOptions.bindings,
1576
- __VITE_ROOT__: resolvedViteConfig.root,
1577
- __VITE_ENTRY_PATH__: workerConfig.main
1578
- },
1579
- serviceBindings: {
1580
- ...workerOptions.serviceBindings,
1581
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1582
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1583
- } : {},
1584
- __VITE_INVOKE_MODULE__: async (request) => {
1585
- const payload = await request.json();
1586
- const invokePayloadData = payload.data;
1587
- assert4(
1588
- invokePayloadData.name === "fetchModule",
1589
- `Invalid invoke event: ${invokePayloadData.name}`
1590
- );
1591
- const [moduleId] = invokePayloadData.data;
1592
- const moduleRE = new RegExp(MODULE_PATTERN);
1593
- const shouldExternalize = (
1594
- // Worker modules (CompiledWasm, Text, Data)
1595
- moduleRE.test(moduleId) || // Node.js builtin node modules (they will be resolved to unenv aliases)
1596
- nodeBuiltInModules.has(moduleId)
1597
- );
1598
- if (shouldExternalize) {
1599
- const result2 = {
1600
- externalize: moduleId,
1601
- type: "module"
1602
- };
1603
- return MiniflareResponse.json({ result: result2 });
1604
- }
1605
- const devEnvironment = viteDevServer.environments[environmentName];
1606
- const result = await devEnvironment.hot.handleInvoke(payload);
1607
- return MiniflareResponse.json(result);
1608
- }
1609
- }
1610
- };
1611
- }
1612
- ) : [];
1613
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1614
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1615
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1616
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1617
- return {
1618
- log: logger,
1619
- handleRuntimeStdio(stdout, stderr) {
1620
- const decoder = new TextDecoder();
1621
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1622
- stderr.forEach(
1623
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1624
- );
1625
- },
1626
- ...getPersistence(
1627
- resolvedViteConfig.root,
1628
- resolvedPluginConfig.persistState
1629
- ),
1630
- workers: [
1631
- ...assetWorkers,
1632
- ...userWorkers.map((workerOptions) => {
1633
- const wrappers = [
1634
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1635
- `export default createWorkerEntrypointWrapper('default');`
1636
- ];
1637
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1638
- workerOptions.name
1639
- );
1640
- assert4(
1641
- workerEntrypointNames,
1642
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1643
- );
1644
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1645
- wrappers.push(
1646
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1647
- );
1648
- }
1649
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1650
- workerOptions.name
1651
- );
1652
- assert4(
1653
- durableObjectClassNames,
1654
- `DurableObject class names not found for worker ${workerOptions.name}`
1655
- );
1656
- for (const className of [...durableObjectClassNames].sort()) {
1657
- wrappers.push(
1658
- `export const ${className} = createDurableObjectWrapper('${className}');`
1659
- );
1660
- }
1661
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1662
- assert4(
1663
- workflowEntrypointClassNames,
1664
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1665
- );
1666
- for (const className of [...workflowEntrypointClassNames].sort()) {
1667
- wrappers.push(
1668
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1669
- );
1670
- }
1671
- return {
1672
- ...workerOptions,
1673
- modules: [
1674
- {
1675
- type: "ESModule",
1676
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1677
- contents: wrappers.join("\n")
1678
- },
1679
- {
1680
- type: "ESModule",
1681
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1682
- contents: fs2.readFileSync(
1683
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1684
- )
1685
- }
1686
- ],
1687
- unsafeUseModuleFallbackService: true
1688
- };
1689
- })
1690
- ],
1691
- unsafeModuleFallbackService(request) {
1692
- const url = new URL(request.url);
1693
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1694
- assert4(
1695
- rawSpecifier,
1696
- `Unexpected error: no specifier in request to module fallback service.`
1697
- );
1698
- const moduleRE = new RegExp(MODULE_PATTERN);
1699
- const match = moduleRE.exec(rawSpecifier);
1700
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1701
- const [full, moduleType, modulePath] = match;
1702
- assert4(
1703
- modulePath,
1704
- `Unexpected error: module path not found in reference ${full}.`
1705
- );
1706
- let source;
1707
- try {
1708
- source = fs2.readFileSync(modulePath);
1709
- } catch (error) {
1710
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1711
- }
1712
- return MiniflareResponse.json({
1713
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1714
- wasm: Array.from(source)
1715
- });
1716
- }
1717
- };
1718
- }
1719
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1720
- const resolvedViteConfig = vitePreviewServer.config;
1721
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1722
- const workerConfigs = configPaths.map(
1723
- (configPath) => unstable_readConfig({ config: configPath })
1724
- );
1725
- const workers = workerConfigs.map((config) => {
1726
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1727
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1728
- return {
1729
- ...workerOptions,
1730
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1731
- name: config.name,
1732
- modules: true,
1733
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1734
- };
1735
- });
1736
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1737
- return {
1738
- log: logger,
1739
- handleRuntimeStdio(stdout, stderr) {
1740
- const decoder = new TextDecoder();
1741
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1742
- stderr.forEach(
1743
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1744
- );
1745
- },
1746
- ...getPersistence(resolvedViteConfig.root, persistState),
1747
- workers
1748
- };
1749
- }
1750
- var ViteMiniflareLogger = class extends Log {
1751
- logger;
1752
- constructor(config) {
1753
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1754
- this.logger = config.logger;
1755
- }
1756
- logWithLevel(level, message) {
1757
- if (/^Ready on http/.test(message)) {
1758
- level = LogLevel.DEBUG;
1759
- }
1760
- switch (level) {
1761
- case LogLevel.ERROR:
1762
- return this.logger.error(message);
1763
- case LogLevel.WARN:
1764
- return this.logger.warn(message);
1765
- case LogLevel.INFO:
1766
- return this.logger.info(message);
1767
- }
1768
- }
1769
- };
1770
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1771
- switch (level) {
1772
- case "error":
1773
- return LogLevel.ERROR;
1774
- case "warn":
1775
- return LogLevel.WARN;
1776
- case "info":
1777
- return LogLevel.INFO;
1778
- case "silent":
1779
- return LogLevel.NONE;
1780
- }
1781
- }
1782
-
1783
- // src/node-js-compat.ts
1784
- import assert6 from "node:assert";
1785
- import { cloudflare } from "@cloudflare/unenv-preset";
1786
- import { getNodeCompat } from "miniflare";
1787
-
1788
- // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1789
- var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
1790
- var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
1791
- var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
1792
- var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
1793
- var reservedWords = {
1794
- 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
1795
- 5: "class enum extends super const export import",
1796
- 6: "enum",
1797
- strict: "implements interface let package private protected public static yield",
1798
- strictBind: "eval arguments"
1799
- };
1800
- var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
1801
- var keywords$1 = {
1802
- 5: ecma5AndLessKeywords,
1803
- "5module": ecma5AndLessKeywords + " export import",
1804
- 6: ecma5AndLessKeywords + " const class extends export import super"
1805
- };
1806
- var keywordRelationalOperator = /^in(stanceof)?$/;
1807
- var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1808
- var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1809
- function isInAstralSet(code, set) {
1810
- var pos = 65536;
1811
- for (var i = 0; i < set.length; i += 2) {
1812
- pos += set[i];
1813
- if (pos > code) {
1814
- return false;
1815
- }
1816
- pos += set[i + 1];
1817
- if (pos >= code) {
1818
- return true;
1819
- }
1820
- }
1821
- return false;
1822
- }
1823
- function isIdentifierStart(code, astral) {
1824
- if (code < 65) {
1825
- return code === 36;
1826
- }
1827
- if (code < 91) {
1828
- return true;
1829
- }
1830
- if (code < 97) {
1831
- return code === 95;
1832
- }
1833
- if (code < 123) {
1834
- return true;
1835
- }
1836
- if (code <= 65535) {
1837
- return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1838
- }
1839
- if (astral === false) {
1840
- return false;
1841
- }
1842
- return isInAstralSet(code, astralIdentifierStartCodes);
1843
- }
1844
- function isIdentifierChar(code, astral) {
1845
- if (code < 48) {
1846
- return code === 36;
1847
- }
1848
- if (code < 58) {
1849
- return true;
1850
- }
1851
- if (code < 65) {
1852
- return false;
1853
- }
1854
- if (code < 91) {
1855
- return true;
1856
- }
1857
- if (code < 97) {
1858
- return code === 95;
1859
- }
1860
- if (code < 123) {
1861
- return true;
1862
- }
1863
- if (code <= 65535) {
1864
- return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1865
- }
1866
- if (astral === false) {
1867
- return false;
1868
- }
1869
- return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1172
+ function isIdentifierChar(code, astral) {
1173
+ if (code < 48) {
1174
+ return code === 36;
1175
+ }
1176
+ if (code < 58) {
1177
+ return true;
1178
+ }
1179
+ if (code < 65) {
1180
+ return false;
1181
+ }
1182
+ if (code < 91) {
1183
+ return true;
1184
+ }
1185
+ if (code < 97) {
1186
+ return code === 95;
1187
+ }
1188
+ if (code < 123) {
1189
+ return true;
1190
+ }
1191
+ if (code <= 65535) {
1192
+ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1193
+ }
1194
+ if (astral === false) {
1195
+ return false;
1196
+ }
1197
+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1870
1198
  }
1871
1199
  var TokenType = function TokenType2(label, conf) {
1872
1200
  if (conf === void 0) conf = {};
@@ -1881,16 +1209,16 @@ var TokenType = function TokenType2(label, conf) {
1881
1209
  this.binop = conf.binop || null;
1882
1210
  this.updateContext = null;
1883
1211
  };
1884
- function binop(name2, prec) {
1885
- return new TokenType(name2, { beforeExpr: true, binop: prec });
1212
+ function binop(name, prec) {
1213
+ return new TokenType(name, { beforeExpr: true, binop: prec });
1886
1214
  }
1887
1215
  var beforeExpr = { beforeExpr: true };
1888
1216
  var startsExpr = { startsExpr: true };
1889
1217
  var keywords = {};
1890
- function kw(name2, options) {
1218
+ function kw(name, options) {
1891
1219
  if (options === void 0) options = {};
1892
- options.keyword = name2;
1893
- return keywords[name2] = new TokenType(name2, options);
1220
+ options.keyword = name;
1221
+ return keywords[name] = new TokenType(name, options);
1894
1222
  }
1895
1223
  var types$1 = {
1896
1224
  num: new TokenType("num", startsExpr),
@@ -2367,18 +1695,18 @@ pp$9.eat = function(type) {
2367
1695
  return false;
2368
1696
  }
2369
1697
  };
2370
- pp$9.isContextual = function(name2) {
2371
- 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;
2372
1700
  };
2373
- pp$9.eatContextual = function(name2) {
2374
- if (!this.isContextual(name2)) {
1701
+ pp$9.eatContextual = function(name) {
1702
+ if (!this.isContextual(name)) {
2375
1703
  return false;
2376
1704
  }
2377
1705
  this.next();
2378
1706
  return true;
2379
1707
  };
2380
- pp$9.expectContextual = function(name2) {
2381
- if (!this.eatContextual(name2)) {
1708
+ pp$9.expectContextual = function(name) {
1709
+ if (!this.eatContextual(name)) {
2382
1710
  this.unexpected();
2383
1711
  }
2384
1712
  };
@@ -2472,8 +1800,8 @@ pp$8.parseTopLevel = function(node) {
2472
1800
  }
2473
1801
  if (this.inModule) {
2474
1802
  for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) {
2475
- var name2 = list[i];
2476
- 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");
2477
1805
  }
2478
1806
  }
2479
1807
  this.adaptDirectivePrologue(node.body);
@@ -3216,26 +2544,26 @@ pp$8.exitClassBody = function() {
3216
2544
  }
3217
2545
  };
3218
2546
  function isPrivateNameConflicted(privateNameMap, element) {
3219
- var name2 = element.key.name;
3220
- var curr = privateNameMap[name2];
2547
+ var name = element.key.name;
2548
+ var curr = privateNameMap[name];
3221
2549
  var next = "true";
3222
2550
  if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
3223
2551
  next = (element.static ? "s" : "i") + element.kind;
3224
2552
  }
3225
2553
  if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
3226
- privateNameMap[name2] = "true";
2554
+ privateNameMap[name] = "true";
3227
2555
  return false;
3228
2556
  } else if (!curr) {
3229
- privateNameMap[name2] = next;
2557
+ privateNameMap[name] = next;
3230
2558
  return false;
3231
2559
  } else {
3232
2560
  return true;
3233
2561
  }
3234
2562
  }
3235
- function checkKeyName(node, name2) {
2563
+ function checkKeyName(node, name) {
3236
2564
  var computed = node.computed;
3237
2565
  var key = node.key;
3238
- 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);
3239
2567
  }
3240
2568
  pp$8.parseExportAllDeclaration = function(node, exports) {
3241
2569
  if (this.options.ecmaVersion >= 11) {
@@ -3323,17 +2651,17 @@ pp$8.parseExportDefaultDeclaration = function() {
3323
2651
  return declaration;
3324
2652
  }
3325
2653
  };
3326
- pp$8.checkExport = function(exports, name2, pos) {
2654
+ pp$8.checkExport = function(exports, name, pos) {
3327
2655
  if (!exports) {
3328
2656
  return;
3329
2657
  }
3330
- if (typeof name2 !== "string") {
3331
- name2 = name2.type === "Identifier" ? name2.name : name2.value;
2658
+ if (typeof name !== "string") {
2659
+ name = name.type === "Identifier" ? name.name : name.value;
3332
2660
  }
3333
- if (hasOwn(exports, name2)) {
3334
- this.raiseRecoverable(pos, "Duplicate export '" + name2 + "'");
2661
+ if (hasOwn(exports, name)) {
2662
+ this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
3335
2663
  }
3336
- exports[name2] = true;
2664
+ exports[name] = true;
3337
2665
  };
3338
2666
  pp$8.checkPatternExport = function(exports, pat) {
3339
2667
  var type = pat.type;
@@ -3913,20 +3241,20 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3913
3241
  return;
3914
3242
  }
3915
3243
  var key = prop.key;
3916
- var name2;
3244
+ var name;
3917
3245
  switch (key.type) {
3918
3246
  case "Identifier":
3919
- name2 = key.name;
3247
+ name = key.name;
3920
3248
  break;
3921
3249
  case "Literal":
3922
- name2 = String(key.value);
3250
+ name = String(key.value);
3923
3251
  break;
3924
3252
  default:
3925
3253
  return;
3926
3254
  }
3927
3255
  var kind = prop.kind;
3928
3256
  if (this.options.ecmaVersion >= 6) {
3929
- if (name2 === "__proto__" && kind === "init") {
3257
+ if (name === "__proto__" && kind === "init") {
3930
3258
  if (propHash.proto) {
3931
3259
  if (refDestructuringErrors) {
3932
3260
  if (refDestructuringErrors.doubleProto < 0) {
@@ -3940,8 +3268,8 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3940
3268
  }
3941
3269
  return;
3942
3270
  }
3943
- name2 = "$" + name2;
3944
- var other = propHash[name2];
3271
+ name = "$" + name;
3272
+ var other = propHash[name];
3945
3273
  if (other) {
3946
3274
  var redefinition;
3947
3275
  if (kind === "init") {
@@ -3953,7 +3281,7 @@ pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
3953
3281
  this.raiseRecoverable(key.start, "Redefinition of property");
3954
3282
  }
3955
3283
  } else {
3956
- other = propHash[name2] = {
3284
+ other = propHash[name] = {
3957
3285
  init: false,
3958
3286
  get: false,
3959
3287
  set: false
@@ -4853,31 +4181,31 @@ pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestruct
4853
4181
  pp$5.checkUnreserved = function(ref2) {
4854
4182
  var start = ref2.start;
4855
4183
  var end = ref2.end;
4856
- var name2 = ref2.name;
4857
- if (this.inGenerator && name2 === "yield") {
4184
+ var name = ref2.name;
4185
+ if (this.inGenerator && name === "yield") {
4858
4186
  this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
4859
4187
  }
4860
- if (this.inAsync && name2 === "await") {
4188
+ if (this.inAsync && name === "await") {
4861
4189
  this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
4862
4190
  }
4863
- if (this.currentThisScope().inClassFieldInit && name2 === "arguments") {
4191
+ if (this.currentThisScope().inClassFieldInit && name === "arguments") {
4864
4192
  this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
4865
4193
  }
4866
- if (this.inClassStaticBlock && (name2 === "arguments" || name2 === "await")) {
4867
- 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");
4868
4196
  }
4869
- if (this.keywords.test(name2)) {
4870
- this.raise(start, "Unexpected keyword '" + name2 + "'");
4197
+ if (this.keywords.test(name)) {
4198
+ this.raise(start, "Unexpected keyword '" + name + "'");
4871
4199
  }
4872
4200
  if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
4873
4201
  return;
4874
4202
  }
4875
4203
  var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
4876
- if (re.test(name2)) {
4877
- if (!this.inAsync && name2 === "await") {
4204
+ if (re.test(name)) {
4205
+ if (!this.inAsync && name === "await") {
4878
4206
  this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
4879
4207
  }
4880
- this.raiseRecoverable(start, "The keyword '" + name2 + "' is reserved");
4208
+ this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
4881
4209
  }
4882
4210
  };
4883
4211
  pp$5.parseIdent = function(liberal) {
@@ -4982,36 +4310,36 @@ pp$3.exitScope = function() {
4982
4310
  pp$3.treatFunctionsAsVarInScope = function(scope) {
4983
4311
  return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
4984
4312
  };
4985
- pp$3.declareName = function(name2, bindingType, pos) {
4313
+ pp$3.declareName = function(name, bindingType, pos) {
4986
4314
  var redeclared = false;
4987
4315
  if (bindingType === BIND_LEXICAL) {
4988
4316
  var scope = this.currentScope();
4989
- redeclared = scope.lexical.indexOf(name2) > -1 || scope.functions.indexOf(name2) > -1 || scope.var.indexOf(name2) > -1;
4990
- 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);
4991
4319
  if (this.inModule && scope.flags & SCOPE_TOP) {
4992
- delete this.undefinedExports[name2];
4320
+ delete this.undefinedExports[name];
4993
4321
  }
4994
4322
  } else if (bindingType === BIND_SIMPLE_CATCH) {
4995
4323
  var scope$1 = this.currentScope();
4996
- scope$1.lexical.push(name2);
4324
+ scope$1.lexical.push(name);
4997
4325
  } else if (bindingType === BIND_FUNCTION) {
4998
4326
  var scope$2 = this.currentScope();
4999
4327
  if (this.treatFunctionsAsVar) {
5000
- redeclared = scope$2.lexical.indexOf(name2) > -1;
4328
+ redeclared = scope$2.lexical.indexOf(name) > -1;
5001
4329
  } else {
5002
- 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;
5003
4331
  }
5004
- scope$2.functions.push(name2);
4332
+ scope$2.functions.push(name);
5005
4333
  } else {
5006
4334
  for (var i = this.scopeStack.length - 1; i >= 0; --i) {
5007
4335
  var scope$3 = this.scopeStack[i];
5008
- 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) {
5009
4337
  redeclared = true;
5010
4338
  break;
5011
4339
  }
5012
- scope$3.var.push(name2);
4340
+ scope$3.var.push(name);
5013
4341
  if (this.inModule && scope$3.flags & SCOPE_TOP) {
5014
- delete this.undefinedExports[name2];
4342
+ delete this.undefinedExports[name];
5015
4343
  }
5016
4344
  if (scope$3.flags & SCOPE_VAR) {
5017
4345
  break;
@@ -5019,7 +4347,7 @@ pp$3.declareName = function(name2, bindingType, pos) {
5019
4347
  }
5020
4348
  }
5021
4349
  if (redeclared) {
5022
- this.raiseRecoverable(pos, "Identifier '" + name2 + "' has already been declared");
4350
+ this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
5023
4351
  }
5024
4352
  };
5025
4353
  pp$3.checkLocalExport = function(id) {
@@ -5339,8 +4667,8 @@ pp$1.regexp_pattern = function(state) {
5339
4667
  state.raise("Invalid escape");
5340
4668
  }
5341
4669
  for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
5342
- var name2 = list[i];
5343
- if (!state.groupNames[name2]) {
4670
+ var name = list[i];
4671
+ if (!state.groupNames[name]) {
5344
4672
  state.raise("Invalid named capture referenced");
5345
4673
  }
5346
4674
  }
@@ -5979,10 +5307,10 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5979
5307
  61
5980
5308
  /* = */
5981
5309
  )) {
5982
- var name2 = state.lastStringValue;
5310
+ var name = state.lastStringValue;
5983
5311
  if (this.regexp_eatUnicodePropertyValue(state)) {
5984
5312
  var value = state.lastStringValue;
5985
- this.regexp_validateUnicodePropertyNameAndValue(state, name2, value);
5313
+ this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
5986
5314
  return CharSetOk;
5987
5315
  }
5988
5316
  }
@@ -5993,11 +5321,11 @@ pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
5993
5321
  }
5994
5322
  return CharSetNone;
5995
5323
  };
5996
- pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name2, value) {
5997
- if (!hasOwn(state.unicodeProperties.nonBinary, name2)) {
5324
+ pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
5325
+ if (!hasOwn(state.unicodeProperties.nonBinary, name)) {
5998
5326
  state.raise("Invalid property name");
5999
5327
  }
6000
- if (!state.unicodeProperties.nonBinary[name2].test(value)) {
5328
+ if (!state.unicodeProperties.nonBinary[name].test(value)) {
6001
5329
  state.raise("Invalid property value");
6002
5330
  }
6003
5331
  };
@@ -7313,8 +6641,8 @@ Parser.acorn = {
7313
6641
  };
7314
6642
 
7315
6643
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7316
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7317
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6644
+ import { builtinModules, createRequire } from "node:module";
6645
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7318
6646
 
7319
6647
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7320
6648
  var r = String.fromCharCode;
@@ -7371,12 +6699,12 @@ var isAbsolute = function(p) {
7371
6699
 
7372
6700
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7373
6701
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7374
- import assert5 from "node:assert";
6702
+ import assert from "node:assert";
7375
6703
  import process$1 from "node:process";
7376
- import path4, { dirname as dirname3 } from "node:path";
6704
+ import path, { dirname as dirname2 } from "node:path";
7377
6705
  import v8 from "node:v8";
7378
6706
  import { format as format2, inspect } from "node:util";
7379
- var BUILTIN_MODULES = new Set(builtinModules2);
6707
+ var BUILTIN_MODULES = new Set(builtinModules);
7380
6708
  function normalizeSlash(path8) {
7381
6709
  return path8.replace(/\\/g, "/");
7382
6710
  }
@@ -7408,31 +6736,31 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7408
6736
  * @param {Array<string> | string} expected
7409
6737
  * @param {unknown} actual
7410
6738
  */
7411
- (name2, expected, actual) => {
7412
- assert5(typeof name2 === "string", "'name' must be a string");
6739
+ (name, expected, actual) => {
6740
+ assert(typeof name === "string", "'name' must be a string");
7413
6741
  if (!Array.isArray(expected)) {
7414
6742
  expected = [expected];
7415
6743
  }
7416
6744
  let message = "The ";
7417
- if (name2.endsWith(" argument")) {
7418
- message += `${name2} `;
6745
+ if (name.endsWith(" argument")) {
6746
+ message += `${name} `;
7419
6747
  } else {
7420
- const type = name2.includes(".") ? "property" : "argument";
7421
- message += `"${name2}" ${type} `;
6748
+ const type = name.includes(".") ? "property" : "argument";
6749
+ message += `"${name}" ${type} `;
7422
6750
  }
7423
6751
  message += "must be ";
7424
6752
  const types2 = [];
7425
6753
  const instances = [];
7426
6754
  const other = [];
7427
6755
  for (const value of expected) {
7428
- assert5(
6756
+ assert(
7429
6757
  typeof value === "string",
7430
6758
  "All expected entries have to be of type string"
7431
6759
  );
7432
6760
  if (kTypes.has(value)) {
7433
6761
  types2.push(value.toLowerCase());
7434
6762
  } else if (classRegExp.exec(value) === null) {
7435
- assert5(
6763
+ assert(
7436
6764
  value !== "object",
7437
6765
  'The value "object" should be written as "Object"'
7438
6766
  );
@@ -7505,14 +6833,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7505
6833
  * @param {boolean} [isImport=false]
7506
6834
  * @param {string} [base]
7507
6835
  */
7508
- (packagePath, key, target, isImport = false, base = void 0) => {
7509
- const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
6836
+ (packagePath, key, target2, isImport = false, base = void 0) => {
6837
+ const relatedError = typeof target2 === "string" && !isImport && target2.length > 0 && !target2.startsWith("./");
7510
6838
  if (key === ".") {
7511
- assert5(isImport === false);
7512
- return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
6839
+ assert(isImport === false);
6840
+ return `Invalid "exports" main target ${JSON.stringify(target2)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7513
6841
  }
7514
6842
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7515
- target
6843
+ target2
7516
6844
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7517
6845
  },
7518
6846
  Error
@@ -7588,13 +6916,13 @@ codes.ERR_INVALID_ARG_VALUE = createError(
7588
6916
  * @param {unknown} value
7589
6917
  * @param {string} [reason='is invalid']
7590
6918
  */
7591
- (name2, value, reason = "is invalid") => {
6919
+ (name, value, reason = "is invalid") => {
7592
6920
  let inspected = inspect(value);
7593
6921
  if (inspected.length > 128) {
7594
6922
  inspected = `${inspected.slice(0, 128)}...`;
7595
6923
  }
7596
- const type = name2.includes(".") ? "property" : "argument";
7597
- return `The ${type} '${name2}' ${reason}. Received ${inspected}`;
6924
+ const type = name.includes(".") ? "property" : "argument";
6925
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`;
7598
6926
  },
7599
6927
  TypeError
7600
6928
  // Note: extra classes have been shaken out.
@@ -7673,9 +7001,9 @@ var captureLargerStackTrace = hideStackFrames(
7673
7001
  );
7674
7002
  function getMessage(key, parameters, self) {
7675
7003
  const message = messages.get(key);
7676
- assert5(message !== void 0, "expected `message` to be found");
7004
+ assert(message !== void 0, "expected `message` to be found");
7677
7005
  if (typeof message === "function") {
7678
- assert5(
7006
+ assert(
7679
7007
  message.length <= parameters.length,
7680
7008
  // Default options do not count.
7681
7009
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -7685,7 +7013,7 @@ function getMessage(key, parameters, self) {
7685
7013
  const regex = /%[dfijoOs]/g;
7686
7014
  let expectedLength = 0;
7687
7015
  while (regex.exec(message) !== null) expectedLength++;
7688
- assert5(
7016
+ assert(
7689
7017
  expectedLength === parameters.length,
7690
7018
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7691
7019
  );
@@ -7722,7 +7050,7 @@ function read(jsonPath, { base, specifier }) {
7722
7050
  }
7723
7051
  let string;
7724
7052
  try {
7725
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7053
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7726
7054
  } catch (error) {
7727
7055
  const exception = (
7728
7056
  /** @type {ErrnoException} */
@@ -7776,1044 +7104,1782 @@ function read(jsonPath, { base, specifier }) {
7776
7104
  result.type = parsed.type;
7777
7105
  }
7778
7106
  }
7779
- cache.set(jsonPath, result);
7780
- return result;
7107
+ cache.set(jsonPath, result);
7108
+ return result;
7109
+ }
7110
+ function getPackageScopeConfig(resolved) {
7111
+ let packageJSONUrl = new URL("package.json", resolved);
7112
+ while (true) {
7113
+ const packageJSONPath2 = packageJSONUrl.pathname;
7114
+ if (packageJSONPath2.endsWith("node_modules/package.json")) {
7115
+ break;
7116
+ }
7117
+ const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
7118
+ specifier: resolved
7119
+ });
7120
+ if (packageConfig.exists) {
7121
+ return packageConfig;
7122
+ }
7123
+ const lastPackageJSONUrl = packageJSONUrl;
7124
+ packageJSONUrl = new URL("../package.json", packageJSONUrl);
7125
+ if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
7126
+ break;
7127
+ }
7128
+ }
7129
+ const packageJSONPath = fileURLToPath$1(packageJSONUrl);
7130
+ return {
7131
+ pjsonPath: packageJSONPath,
7132
+ exists: false,
7133
+ type: "none"
7134
+ };
7135
+ }
7136
+ function getPackageType(url) {
7137
+ return getPackageScopeConfig(url).type;
7138
+ }
7139
+ var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
7140
+ var hasOwnProperty2 = {}.hasOwnProperty;
7141
+ var extensionFormatMap = {
7142
+ // @ts-expect-error: hush.
7143
+ __proto__: null,
7144
+ ".cjs": "commonjs",
7145
+ ".js": "module",
7146
+ ".json": "json",
7147
+ ".mjs": "module"
7148
+ };
7149
+ function mimeToFormat(mime) {
7150
+ if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
7151
+ return "module";
7152
+ if (mime === "application/json") return "json";
7153
+ return null;
7154
+ }
7155
+ var protocolHandlers = {
7156
+ // @ts-expect-error: hush.
7157
+ __proto__: null,
7158
+ "data:": getDataProtocolModuleFormat,
7159
+ "file:": getFileProtocolModuleFormat,
7160
+ "http:": getHttpProtocolModuleFormat,
7161
+ "https:": getHttpProtocolModuleFormat,
7162
+ "node:"() {
7163
+ return "builtin";
7164
+ }
7165
+ };
7166
+ function getDataProtocolModuleFormat(parsed) {
7167
+ const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
7168
+ parsed.pathname
7169
+ ) || [null, null, null];
7170
+ return mimeToFormat(mime);
7171
+ }
7172
+ function extname2(url) {
7173
+ const pathname = url.pathname;
7174
+ let index = pathname.length;
7175
+ while (index--) {
7176
+ const code = pathname.codePointAt(index);
7177
+ if (code === 47) {
7178
+ return "";
7179
+ }
7180
+ if (code === 46) {
7181
+ return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
7182
+ }
7183
+ }
7184
+ return "";
7185
+ }
7186
+ function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
7187
+ const value = extname2(url);
7188
+ if (value === ".js") {
7189
+ const packageType = getPackageType(url);
7190
+ if (packageType !== "none") {
7191
+ return packageType;
7192
+ }
7193
+ return "commonjs";
7194
+ }
7195
+ if (value === "") {
7196
+ const packageType = getPackageType(url);
7197
+ if (packageType === "none" || packageType === "commonjs") {
7198
+ return "commonjs";
7199
+ }
7200
+ return "module";
7201
+ }
7202
+ const format3 = extensionFormatMap[value];
7203
+ if (format3) return format3;
7204
+ if (ignoreErrors) {
7205
+ return void 0;
7206
+ }
7207
+ const filepath = fileURLToPath$1(url);
7208
+ throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7209
+ }
7210
+ function getHttpProtocolModuleFormat() {
7211
+ }
7212
+ function defaultGetFormatWithoutErrors(url, context) {
7213
+ const protocol = url.protocol;
7214
+ if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7215
+ return null;
7216
+ }
7217
+ return protocolHandlers[protocol](url, context, true) || null;
7218
+ }
7219
+ var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
7220
+ var {
7221
+ ERR_NETWORK_IMPORT_DISALLOWED,
7222
+ ERR_INVALID_MODULE_SPECIFIER,
7223
+ ERR_INVALID_PACKAGE_CONFIG,
7224
+ ERR_INVALID_PACKAGE_TARGET,
7225
+ ERR_MODULE_NOT_FOUND,
7226
+ ERR_PACKAGE_IMPORT_NOT_DEFINED,
7227
+ ERR_PACKAGE_PATH_NOT_EXPORTED,
7228
+ ERR_UNSUPPORTED_DIR_IMPORT,
7229
+ ERR_UNSUPPORTED_RESOLVE_REQUEST
7230
+ } = codes;
7231
+ var own = {}.hasOwnProperty;
7232
+ var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
7233
+ var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
7234
+ var invalidPackageNameRegEx = /^\.|%|\\/;
7235
+ var patternRegEx = /\*/g;
7236
+ var encodedSeparatorRegEx = /%2f|%5c/i;
7237
+ var emittedPackageWarnings = /* @__PURE__ */ new Set();
7238
+ var doubleSlashRegEx = /[/\\]{2}/;
7239
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7240
+ if (process$1.noDeprecation) {
7241
+ return;
7242
+ }
7243
+ const pjsonPath = fileURLToPath$1(packageJsonUrl);
7244
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7245
+ process$1.emitWarning(
7246
+ `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target2}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7247
+ "DeprecationWarning",
7248
+ "DEP0166"
7249
+ );
7250
+ }
7251
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7252
+ if (process$1.noDeprecation) {
7253
+ return;
7254
+ }
7255
+ const format3 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
7256
+ if (format3 !== "module") return;
7257
+ const urlPath = fileURLToPath$1(url.href);
7258
+ const packagePath = fileURLToPath$1(new URL$1(".", packageJsonUrl));
7259
+ const basePath = fileURLToPath$1(base);
7260
+ if (!main) {
7261
+ process$1.emitWarning(
7262
+ `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
7263
+ packagePath.length
7264
+ )}", imported from ${basePath}.
7265
+ Default "index" lookups for the main are deprecated for ES modules.`,
7266
+ "DeprecationWarning",
7267
+ "DEP0151"
7268
+ );
7269
+ } else if (path.resolve(packagePath, main) !== urlPath) {
7270
+ process$1.emitWarning(
7271
+ `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7272
+ packagePath.length
7273
+ )}", imported from ${basePath}.
7274
+ Automatic extension resolution of the "main" field is deprecated for ES modules.`,
7275
+ "DeprecationWarning",
7276
+ "DEP0151"
7277
+ );
7278
+ }
7279
+ }
7280
+ function tryStatSync(path8) {
7281
+ try {
7282
+ return statSync(path8);
7283
+ } catch {
7284
+ }
7285
+ }
7286
+ function fileExists(url) {
7287
+ const stats = statSync(url, { throwIfNoEntry: false });
7288
+ const isFile = stats ? stats.isFile() : void 0;
7289
+ return isFile === null || isFile === void 0 ? false : isFile;
7290
+ }
7291
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
7292
+ let guess;
7293
+ if (packageConfig.main !== void 0) {
7294
+ guess = new URL$1(packageConfig.main, packageJsonUrl);
7295
+ if (fileExists(guess)) return guess;
7296
+ const tries2 = [
7297
+ `./${packageConfig.main}.js`,
7298
+ `./${packageConfig.main}.json`,
7299
+ `./${packageConfig.main}.node`,
7300
+ `./${packageConfig.main}/index.js`,
7301
+ `./${packageConfig.main}/index.json`,
7302
+ `./${packageConfig.main}/index.node`
7303
+ ];
7304
+ let i2 = -1;
7305
+ while (++i2 < tries2.length) {
7306
+ guess = new URL$1(tries2[i2], packageJsonUrl);
7307
+ if (fileExists(guess)) break;
7308
+ guess = void 0;
7309
+ }
7310
+ if (guess) {
7311
+ emitLegacyIndexDeprecation(
7312
+ guess,
7313
+ packageJsonUrl,
7314
+ base,
7315
+ packageConfig.main
7316
+ );
7317
+ return guess;
7318
+ }
7319
+ }
7320
+ const tries = ["./index.js", "./index.json", "./index.node"];
7321
+ let i = -1;
7322
+ while (++i < tries.length) {
7323
+ guess = new URL$1(tries[i], packageJsonUrl);
7324
+ if (fileExists(guess)) break;
7325
+ guess = void 0;
7326
+ }
7327
+ if (guess) {
7328
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
7329
+ return guess;
7330
+ }
7331
+ throw new ERR_MODULE_NOT_FOUND(
7332
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7333
+ fileURLToPath$1(base)
7334
+ );
7335
+ }
7336
+ function finalizeResolution(resolved, base, preserveSymlinks) {
7337
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7338
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7339
+ resolved.pathname,
7340
+ 'must not include encoded "/" or "\\" characters',
7341
+ fileURLToPath$1(base)
7342
+ );
7343
+ }
7344
+ let filePath;
7345
+ try {
7346
+ filePath = fileURLToPath$1(resolved);
7347
+ } catch (error) {
7348
+ const cause = (
7349
+ /** @type {ErrnoException} */
7350
+ error
7351
+ );
7352
+ Object.defineProperty(cause, "input", { value: String(resolved) });
7353
+ Object.defineProperty(cause, "module", { value: String(base) });
7354
+ throw cause;
7355
+ }
7356
+ const stats = tryStatSync(
7357
+ filePath.endsWith("/") ? filePath.slice(-1) : filePath
7358
+ );
7359
+ if (stats && stats.isDirectory()) {
7360
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
7361
+ error.url = String(resolved);
7362
+ throw error;
7363
+ }
7364
+ if (!stats || !stats.isFile()) {
7365
+ const error = new ERR_MODULE_NOT_FOUND(
7366
+ filePath || resolved.pathname,
7367
+ base && fileURLToPath$1(base),
7368
+ true
7369
+ );
7370
+ error.url = String(resolved);
7371
+ throw error;
7372
+ }
7373
+ {
7374
+ const real = realpathSync(filePath);
7375
+ const { search, hash } = resolved;
7376
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? "/" : ""));
7377
+ resolved.search = search;
7378
+ resolved.hash = hash;
7379
+ }
7380
+ return resolved;
7781
7381
  }
7782
- function getPackageScopeConfig(resolved) {
7783
- let packageJSONUrl = new URL("package.json", resolved);
7784
- while (true) {
7785
- const packageJSONPath2 = packageJSONUrl.pathname;
7786
- if (packageJSONPath2.endsWith("node_modules/package.json")) {
7787
- break;
7382
+ function importNotDefined(specifier, packageJsonUrl, base) {
7383
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7384
+ specifier,
7385
+ packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7386
+ fileURLToPath$1(base)
7387
+ );
7388
+ }
7389
+ function exportsNotFound(subpath, packageJsonUrl, base) {
7390
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(
7391
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7392
+ subpath,
7393
+ base && fileURLToPath$1(base)
7394
+ );
7395
+ }
7396
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
7397
+ const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
7398
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7399
+ request,
7400
+ reason,
7401
+ base && fileURLToPath$1(base)
7402
+ );
7403
+ }
7404
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
7405
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
7406
+ return new ERR_INVALID_PACKAGE_TARGET(
7407
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7408
+ subpath,
7409
+ target2,
7410
+ internal,
7411
+ base && fileURLToPath$1(base)
7412
+ );
7413
+ }
7414
+ function resolvePackageTargetString(target2, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
7415
+ if (subpath !== "" && !pattern && target2[target2.length - 1] !== "/")
7416
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7417
+ if (!target2.startsWith("./")) {
7418
+ if (internal && !target2.startsWith("../") && !target2.startsWith("/")) {
7419
+ let isURL = false;
7420
+ try {
7421
+ new URL$1(target2);
7422
+ isURL = true;
7423
+ } catch {
7424
+ }
7425
+ if (!isURL) {
7426
+ const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7427
+ patternRegEx,
7428
+ target2,
7429
+ () => subpath
7430
+ ) : target2 + subpath;
7431
+ return packageResolve(exportTarget, packageJsonUrl, conditions);
7432
+ }
7788
7433
  }
7789
- const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
7790
- specifier: resolved
7791
- });
7792
- if (packageConfig.exists) {
7793
- return packageConfig;
7434
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7435
+ }
7436
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
7437
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
7438
+ if (!isPathMap) {
7439
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7440
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7441
+ patternRegEx,
7442
+ target2,
7443
+ () => subpath
7444
+ ) : target2;
7445
+ emitInvalidSegmentDeprecation(
7446
+ resolvedTarget,
7447
+ request,
7448
+ match,
7449
+ packageJsonUrl,
7450
+ internal,
7451
+ base,
7452
+ true
7453
+ );
7454
+ }
7455
+ } else {
7456
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7794
7457
  }
7795
- const lastPackageJSONUrl = packageJSONUrl;
7796
- packageJSONUrl = new URL("../package.json", packageJSONUrl);
7797
- if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
7798
- break;
7458
+ }
7459
+ const resolved = new URL$1(target2, packageJsonUrl);
7460
+ const resolvedPath = resolved.pathname;
7461
+ const packagePath = new URL$1(".", packageJsonUrl).pathname;
7462
+ if (!resolvedPath.startsWith(packagePath))
7463
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7464
+ if (subpath === "") return resolved;
7465
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
7466
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7467
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
7468
+ if (!isPathMap) {
7469
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7470
+ patternRegEx,
7471
+ target2,
7472
+ () => subpath
7473
+ ) : target2;
7474
+ emitInvalidSegmentDeprecation(
7475
+ resolvedTarget,
7476
+ request,
7477
+ match,
7478
+ packageJsonUrl,
7479
+ internal,
7480
+ base,
7481
+ false
7482
+ );
7483
+ }
7484
+ } else {
7485
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7799
7486
  }
7800
7487
  }
7801
- const packageJSONPath = fileURLToPath$1(packageJSONUrl);
7802
- return {
7803
- pjsonPath: packageJSONPath,
7804
- exists: false,
7805
- type: "none"
7806
- };
7807
- }
7808
- function getPackageType(url) {
7809
- return getPackageScopeConfig(url).type;
7488
+ if (pattern) {
7489
+ return new URL$1(
7490
+ RegExpPrototypeSymbolReplace.call(
7491
+ patternRegEx,
7492
+ resolved.href,
7493
+ () => subpath
7494
+ )
7495
+ );
7496
+ }
7497
+ return new URL$1(subpath, resolved);
7810
7498
  }
7811
- var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
7812
- var hasOwnProperty2 = {}.hasOwnProperty;
7813
- var extensionFormatMap = {
7814
- // @ts-expect-error: hush.
7815
- __proto__: null,
7816
- ".cjs": "commonjs",
7817
- ".js": "module",
7818
- ".json": "json",
7819
- ".mjs": "module"
7820
- };
7821
- function mimeToFormat(mime) {
7822
- if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
7823
- return "module";
7824
- if (mime === "application/json") return "json";
7825
- return null;
7499
+ function isArrayIndex(key) {
7500
+ const keyNumber = Number(key);
7501
+ if (`${keyNumber}` !== key) return false;
7502
+ return keyNumber >= 0 && keyNumber < 4294967295;
7826
7503
  }
7827
- var protocolHandlers = {
7828
- // @ts-expect-error: hush.
7829
- __proto__: null,
7830
- "data:": getDataProtocolModuleFormat,
7831
- "file:": getFileProtocolModuleFormat,
7832
- "http:": getHttpProtocolModuleFormat,
7833
- "https:": getHttpProtocolModuleFormat,
7834
- "node:"() {
7835
- return "builtin";
7504
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
7505
+ if (typeof target2 === "string") {
7506
+ return resolvePackageTargetString(
7507
+ target2,
7508
+ subpath,
7509
+ packageSubpath,
7510
+ packageJsonUrl,
7511
+ base,
7512
+ pattern,
7513
+ internal,
7514
+ isPathMap,
7515
+ conditions
7516
+ );
7836
7517
  }
7837
- };
7838
- function getDataProtocolModuleFormat(parsed) {
7839
- const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
7840
- parsed.pathname
7841
- ) || [null, null, null];
7842
- return mimeToFormat(mime);
7843
- }
7844
- function extname2(url) {
7845
- const pathname = url.pathname;
7846
- let index = pathname.length;
7847
- while (index--) {
7848
- const code = pathname.codePointAt(index);
7849
- if (code === 47) {
7850
- return "";
7518
+ if (Array.isArray(target2)) {
7519
+ const targetList = target2;
7520
+ if (targetList.length === 0) return null;
7521
+ let lastException;
7522
+ let i = -1;
7523
+ while (++i < targetList.length) {
7524
+ const targetItem = targetList[i];
7525
+ let resolveResult;
7526
+ try {
7527
+ resolveResult = resolvePackageTarget(
7528
+ packageJsonUrl,
7529
+ targetItem,
7530
+ subpath,
7531
+ packageSubpath,
7532
+ base,
7533
+ pattern,
7534
+ internal,
7535
+ isPathMap,
7536
+ conditions
7537
+ );
7538
+ } catch (error) {
7539
+ const exception = (
7540
+ /** @type {ErrnoException} */
7541
+ error
7542
+ );
7543
+ lastException = exception;
7544
+ if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
7545
+ throw error;
7546
+ }
7547
+ if (resolveResult === void 0) continue;
7548
+ if (resolveResult === null) {
7549
+ lastException = null;
7550
+ continue;
7551
+ }
7552
+ return resolveResult;
7851
7553
  }
7852
- if (code === 46) {
7853
- return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
7554
+ if (lastException === void 0 || lastException === null) {
7555
+ return null;
7854
7556
  }
7557
+ throw lastException;
7855
7558
  }
7856
- return "";
7857
- }
7858
- function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
7859
- const value = extname2(url);
7860
- if (value === ".js") {
7861
- const packageType = getPackageType(url);
7862
- if (packageType !== "none") {
7863
- return packageType;
7559
+ if (typeof target2 === "object" && target2 !== null) {
7560
+ const keys = Object.getOwnPropertyNames(target2);
7561
+ let i = -1;
7562
+ while (++i < keys.length) {
7563
+ const key = keys[i];
7564
+ if (isArrayIndex(key)) {
7565
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7566
+ fileURLToPath$1(packageJsonUrl),
7567
+ base,
7568
+ '"exports" cannot contain numeric property keys.'
7569
+ );
7570
+ }
7864
7571
  }
7865
- return "commonjs";
7866
- }
7867
- if (value === "") {
7868
- const packageType = getPackageType(url);
7869
- if (packageType === "none" || packageType === "commonjs") {
7870
- return "commonjs";
7572
+ i = -1;
7573
+ while (++i < keys.length) {
7574
+ const key = keys[i];
7575
+ if (key === "default" || conditions && conditions.has(key)) {
7576
+ const conditionalTarget = (
7577
+ /** @type {unknown} */
7578
+ target2[key]
7579
+ );
7580
+ const resolveResult = resolvePackageTarget(
7581
+ packageJsonUrl,
7582
+ conditionalTarget,
7583
+ subpath,
7584
+ packageSubpath,
7585
+ base,
7586
+ pattern,
7587
+ internal,
7588
+ isPathMap,
7589
+ conditions
7590
+ );
7591
+ if (resolveResult === void 0) continue;
7592
+ return resolveResult;
7593
+ }
7871
7594
  }
7872
- return "module";
7595
+ return null;
7873
7596
  }
7874
- const format3 = extensionFormatMap[value];
7875
- if (format3) return format3;
7876
- if (ignoreErrors) {
7877
- return void 0;
7597
+ if (target2 === null) {
7598
+ return null;
7878
7599
  }
7879
- const filepath = fileURLToPath$1(url);
7880
- throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7881
- }
7882
- function getHttpProtocolModuleFormat() {
7600
+ throw invalidPackageTarget(
7601
+ packageSubpath,
7602
+ target2,
7603
+ packageJsonUrl,
7604
+ internal,
7605
+ base
7606
+ );
7883
7607
  }
7884
- function defaultGetFormatWithoutErrors(url, context) {
7885
- const protocol = url.protocol;
7886
- if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7887
- return null;
7608
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
7609
+ if (typeof exports === "string" || Array.isArray(exports)) return true;
7610
+ if (typeof exports !== "object" || exports === null) return false;
7611
+ const keys = Object.getOwnPropertyNames(exports);
7612
+ let isConditionalSugar = false;
7613
+ let i = 0;
7614
+ let keyIndex = -1;
7615
+ while (++keyIndex < keys.length) {
7616
+ const key = keys[keyIndex];
7617
+ const currentIsConditionalSugar = key === "" || key[0] !== ".";
7618
+ if (i++ === 0) {
7619
+ isConditionalSugar = currentIsConditionalSugar;
7620
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
7621
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7622
+ fileURLToPath$1(packageJsonUrl),
7623
+ base,
7624
+ `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`
7625
+ );
7626
+ }
7888
7627
  }
7889
- return protocolHandlers[protocol](url, context, true) || null;
7628
+ return isConditionalSugar;
7890
7629
  }
7891
- var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
7892
- var {
7893
- ERR_NETWORK_IMPORT_DISALLOWED,
7894
- ERR_INVALID_MODULE_SPECIFIER,
7895
- ERR_INVALID_PACKAGE_CONFIG,
7896
- ERR_INVALID_PACKAGE_TARGET,
7897
- ERR_MODULE_NOT_FOUND,
7898
- ERR_PACKAGE_IMPORT_NOT_DEFINED,
7899
- ERR_PACKAGE_PATH_NOT_EXPORTED,
7900
- ERR_UNSUPPORTED_DIR_IMPORT,
7901
- ERR_UNSUPPORTED_RESOLVE_REQUEST
7902
- } = codes;
7903
- var own = {}.hasOwnProperty;
7904
- var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
7905
- var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
7906
- var invalidPackageNameRegEx = /^\.|%|\\/;
7907
- var patternRegEx = /\*/g;
7908
- var encodedSeparatorRegEx = /%2f|%5c/i;
7909
- var emittedPackageWarnings = /* @__PURE__ */ new Set();
7910
- var doubleSlashRegEx = /[/\\]{2}/;
7911
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7630
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
7912
7631
  if (process$1.noDeprecation) {
7913
7632
  return;
7914
7633
  }
7915
- const pjsonPath = fileURLToPath$1(packageJsonUrl);
7916
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7634
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
7635
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
7636
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
7917
7637
  process$1.emitWarning(
7918
- `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7638
+ `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
7919
7639
  "DeprecationWarning",
7920
- "DEP0166"
7640
+ "DEP0155"
7921
7641
  );
7922
7642
  }
7923
- function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7924
- if (process$1.noDeprecation) {
7925
- return;
7643
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7644
+ let exports = packageConfig.exports;
7645
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7646
+ exports = { ".": exports };
7926
7647
  }
7927
- const format3 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
7928
- if (format3 !== "module") return;
7929
- const urlPath = fileURLToPath$1(url.href);
7930
- const packagePath = fileURLToPath$1(new URL$1(".", packageJsonUrl));
7931
- const basePath = fileURLToPath$1(base);
7932
- if (!main) {
7933
- process$1.emitWarning(
7934
- `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
7935
- packagePath.length
7936
- )}", imported from ${basePath}.
7937
- Default "index" lookups for the main are deprecated for ES modules.`,
7938
- "DeprecationWarning",
7939
- "DEP0151"
7940
- );
7941
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7942
- process$1.emitWarning(
7943
- `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7944
- packagePath.length
7945
- )}", imported from ${basePath}.
7946
- Automatic extension resolution of the "main" field is deprecated for ES modules.`,
7947
- "DeprecationWarning",
7948
- "DEP0151"
7648
+ if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
7649
+ const target2 = exports[packageSubpath];
7650
+ const resolveResult = resolvePackageTarget(
7651
+ packageJsonUrl,
7652
+ target2,
7653
+ "",
7654
+ packageSubpath,
7655
+ base,
7656
+ false,
7657
+ false,
7658
+ false,
7659
+ conditions
7949
7660
  );
7661
+ if (resolveResult === null || resolveResult === void 0) {
7662
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7663
+ }
7664
+ return resolveResult;
7950
7665
  }
7951
- }
7952
- function tryStatSync(path8) {
7953
- try {
7954
- return statSync2(path8);
7955
- } catch {
7666
+ let bestMatch = "";
7667
+ let bestMatchSubpath = "";
7668
+ const keys = Object.getOwnPropertyNames(exports);
7669
+ let i = -1;
7670
+ while (++i < keys.length) {
7671
+ const key = keys[i];
7672
+ const patternIndex = key.indexOf("*");
7673
+ if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
7674
+ if (packageSubpath.endsWith("/")) {
7675
+ emitTrailingSlashPatternDeprecation(
7676
+ packageSubpath,
7677
+ packageJsonUrl,
7678
+ base
7679
+ );
7680
+ }
7681
+ const patternTrailer = key.slice(patternIndex + 1);
7682
+ if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7683
+ bestMatch = key;
7684
+ bestMatchSubpath = packageSubpath.slice(
7685
+ patternIndex,
7686
+ packageSubpath.length - patternTrailer.length
7687
+ );
7688
+ }
7689
+ }
7690
+ }
7691
+ if (bestMatch) {
7692
+ const target2 = (
7693
+ /** @type {unknown} */
7694
+ exports[bestMatch]
7695
+ );
7696
+ const resolveResult = resolvePackageTarget(
7697
+ packageJsonUrl,
7698
+ target2,
7699
+ bestMatchSubpath,
7700
+ bestMatch,
7701
+ base,
7702
+ true,
7703
+ false,
7704
+ packageSubpath.endsWith("/"),
7705
+ conditions
7706
+ );
7707
+ if (resolveResult === null || resolveResult === void 0) {
7708
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7709
+ }
7710
+ return resolveResult;
7956
7711
  }
7712
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7957
7713
  }
7958
- function fileExists(url) {
7959
- const stats = statSync2(url, { throwIfNoEntry: false });
7960
- const isFile = stats ? stats.isFile() : void 0;
7961
- return isFile === null || isFile === void 0 ? false : isFile;
7714
+ function patternKeyCompare(a, b) {
7715
+ const aPatternIndex = a.indexOf("*");
7716
+ const bPatternIndex = b.indexOf("*");
7717
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
7718
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
7719
+ if (baseLengthA > baseLengthB) return -1;
7720
+ if (baseLengthB > baseLengthA) return 1;
7721
+ if (aPatternIndex === -1) return 1;
7722
+ if (bPatternIndex === -1) return -1;
7723
+ if (a.length > b.length) return -1;
7724
+ if (b.length > a.length) return 1;
7725
+ return 0;
7962
7726
  }
7963
- function legacyMainResolve(packageJsonUrl, packageConfig, base) {
7964
- let guess;
7965
- if (packageConfig.main !== void 0) {
7966
- guess = new URL$1(packageConfig.main, packageJsonUrl);
7967
- if (fileExists(guess)) return guess;
7968
- const tries2 = [
7969
- `./${packageConfig.main}.js`,
7970
- `./${packageConfig.main}.json`,
7971
- `./${packageConfig.main}.node`,
7972
- `./${packageConfig.main}/index.js`,
7973
- `./${packageConfig.main}/index.json`,
7974
- `./${packageConfig.main}/index.node`
7975
- ];
7976
- let i2 = -1;
7977
- while (++i2 < tries2.length) {
7978
- guess = new URL$1(tries2[i2], packageJsonUrl);
7979
- if (fileExists(guess)) break;
7980
- guess = void 0;
7981
- }
7982
- if (guess) {
7983
- emitLegacyIndexDeprecation(
7984
- guess,
7985
- packageJsonUrl,
7986
- base,
7987
- packageConfig.main
7988
- );
7989
- return guess;
7727
+ function packageImportsResolve(name, base, conditions) {
7728
+ if (name === "#" || name.startsWith("#/") || name.endsWith("/")) {
7729
+ const reason = "is not a valid internal imports specifier name";
7730
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base));
7731
+ }
7732
+ let packageJsonUrl;
7733
+ const packageConfig = getPackageScopeConfig(base);
7734
+ if (packageConfig.exists) {
7735
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
7736
+ const imports = packageConfig.imports;
7737
+ if (imports) {
7738
+ if (own.call(imports, name) && !name.includes("*")) {
7739
+ const resolveResult = resolvePackageTarget(
7740
+ packageJsonUrl,
7741
+ imports[name],
7742
+ "",
7743
+ name,
7744
+ base,
7745
+ false,
7746
+ true,
7747
+ false,
7748
+ conditions
7749
+ );
7750
+ if (resolveResult !== null && resolveResult !== void 0) {
7751
+ return resolveResult;
7752
+ }
7753
+ } else {
7754
+ let bestMatch = "";
7755
+ let bestMatchSubpath = "";
7756
+ const keys = Object.getOwnPropertyNames(imports);
7757
+ let i = -1;
7758
+ while (++i < keys.length) {
7759
+ const key = keys[i];
7760
+ const patternIndex = key.indexOf("*");
7761
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
7762
+ const patternTrailer = key.slice(patternIndex + 1);
7763
+ if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7764
+ bestMatch = key;
7765
+ bestMatchSubpath = name.slice(
7766
+ patternIndex,
7767
+ name.length - patternTrailer.length
7768
+ );
7769
+ }
7770
+ }
7771
+ }
7772
+ if (bestMatch) {
7773
+ const target2 = imports[bestMatch];
7774
+ const resolveResult = resolvePackageTarget(
7775
+ packageJsonUrl,
7776
+ target2,
7777
+ bestMatchSubpath,
7778
+ bestMatch,
7779
+ base,
7780
+ true,
7781
+ true,
7782
+ false,
7783
+ conditions
7784
+ );
7785
+ if (resolveResult !== null && resolveResult !== void 0) {
7786
+ return resolveResult;
7787
+ }
7788
+ }
7789
+ }
7990
7790
  }
7991
7791
  }
7992
- const tries = ["./index.js", "./index.json", "./index.node"];
7993
- let i = -1;
7994
- while (++i < tries.length) {
7995
- guess = new URL$1(tries[i], packageJsonUrl);
7996
- if (fileExists(guess)) break;
7997
- guess = void 0;
7792
+ throw importNotDefined(name, packageJsonUrl, base);
7793
+ }
7794
+ function parsePackageName(specifier, base) {
7795
+ let separatorIndex = specifier.indexOf("/");
7796
+ let validPackageName = true;
7797
+ let isScoped = false;
7798
+ if (specifier[0] === "@") {
7799
+ isScoped = true;
7800
+ if (separatorIndex === -1 || specifier.length === 0) {
7801
+ validPackageName = false;
7802
+ } else {
7803
+ separatorIndex = specifier.indexOf("/", separatorIndex + 1);
7804
+ }
7998
7805
  }
7999
- if (guess) {
8000
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
8001
- return guess;
7806
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7807
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7808
+ validPackageName = false;
8002
7809
  }
8003
- throw new ERR_MODULE_NOT_FOUND(
8004
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8005
- fileURLToPath$1(base)
8006
- );
8007
- }
8008
- function finalizeResolution(resolved, base, preserveSymlinks) {
8009
- if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7810
+ if (!validPackageName) {
8010
7811
  throw new ERR_INVALID_MODULE_SPECIFIER(
8011
- resolved.pathname,
8012
- 'must not include encoded "/" or "\\" characters',
7812
+ specifier,
7813
+ "is not a valid package name",
8013
7814
  fileURLToPath$1(base)
8014
7815
  );
8015
7816
  }
8016
- let filePath;
8017
- try {
8018
- filePath = fileURLToPath$1(resolved);
8019
- } catch (error) {
8020
- const cause = (
8021
- /** @type {ErrnoException} */
8022
- error
8023
- );
8024
- Object.defineProperty(cause, "input", { value: String(resolved) });
8025
- Object.defineProperty(cause, "module", { value: String(base) });
8026
- throw cause;
8027
- }
8028
- const stats = tryStatSync(
8029
- filePath.endsWith("/") ? filePath.slice(-1) : filePath
8030
- );
8031
- if (stats && stats.isDirectory()) {
8032
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
8033
- error.url = String(resolved);
8034
- throw error;
8035
- }
8036
- if (!stats || !stats.isFile()) {
8037
- const error = new ERR_MODULE_NOT_FOUND(
8038
- filePath || resolved.pathname,
8039
- base && fileURLToPath$1(base),
8040
- true
8041
- );
8042
- error.url = String(resolved);
8043
- throw error;
8044
- }
8045
- {
8046
- const real = realpathSync(filePath);
8047
- const { search, hash } = resolved;
8048
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
8049
- resolved.search = search;
8050
- resolved.hash = hash;
8051
- }
8052
- return resolved;
7817
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7818
+ return { packageName, packageSubpath, isScoped };
8053
7819
  }
8054
- function importNotDefined(specifier, packageJsonUrl, base) {
8055
- return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7820
+ function packageResolve(specifier, base, conditions) {
7821
+ if (builtinModules.includes(specifier)) {
7822
+ return new URL$1("node:" + specifier);
7823
+ }
7824
+ const { packageName, packageSubpath, isScoped } = parsePackageName(
8056
7825
  specifier,
8057
- packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8058
- fileURLToPath$1(base)
7826
+ base
8059
7827
  );
8060
- }
8061
- function exportsNotFound(subpath, packageJsonUrl, base) {
8062
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
8063
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8064
- subpath,
8065
- base && fileURLToPath$1(base)
7828
+ const packageConfig = getPackageScopeConfig(base);
7829
+ if (packageConfig.exists) {
7830
+ const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
7831
+ if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
7832
+ return packageExportsResolve(
7833
+ packageJsonUrl2,
7834
+ packageSubpath,
7835
+ packageConfig,
7836
+ base,
7837
+ conditions
7838
+ );
7839
+ }
7840
+ }
7841
+ let packageJsonUrl = new URL$1(
7842
+ "./node_modules/" + packageName + "/package.json",
7843
+ base
8066
7844
  );
7845
+ let packageJsonPath = fileURLToPath$1(packageJsonUrl);
7846
+ let lastPath;
7847
+ do {
7848
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
7849
+ if (!stat || !stat.isDirectory()) {
7850
+ lastPath = packageJsonPath;
7851
+ packageJsonUrl = new URL$1(
7852
+ (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
7853
+ packageJsonUrl
7854
+ );
7855
+ packageJsonPath = fileURLToPath$1(packageJsonUrl);
7856
+ continue;
7857
+ }
7858
+ const packageConfig2 = read(packageJsonPath, { base, specifier });
7859
+ if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
7860
+ return packageExportsResolve(
7861
+ packageJsonUrl,
7862
+ packageSubpath,
7863
+ packageConfig2,
7864
+ base,
7865
+ conditions
7866
+ );
7867
+ }
7868
+ if (packageSubpath === ".") {
7869
+ return legacyMainResolve(packageJsonUrl, packageConfig2, base);
7870
+ }
7871
+ return new URL$1(packageSubpath, packageJsonUrl);
7872
+ } while (packageJsonPath.length !== lastPath.length);
7873
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8067
7874
  }
8068
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8069
- const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
8070
- throw new ERR_INVALID_MODULE_SPECIFIER(
8071
- request,
8072
- reason,
8073
- base && fileURLToPath$1(base)
8074
- );
7875
+ function isRelativeSpecifier(specifier) {
7876
+ if (specifier[0] === ".") {
7877
+ if (specifier.length === 1 || specifier[1] === "/") return true;
7878
+ if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
7879
+ return true;
7880
+ }
7881
+ }
7882
+ return false;
8075
7883
  }
8076
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8077
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8078
- return new ERR_INVALID_PACKAGE_TARGET(
8079
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8080
- subpath,
8081
- target,
8082
- internal,
8083
- base && fileURLToPath$1(base)
8084
- );
7884
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
7885
+ if (specifier === "") return false;
7886
+ if (specifier[0] === "/") return true;
7887
+ return isRelativeSpecifier(specifier);
8085
7888
  }
8086
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8087
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8088
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8089
- if (!target.startsWith("./")) {
8090
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8091
- let isURL = false;
8092
- try {
8093
- new URL$1(target);
8094
- isURL = true;
8095
- } catch {
8096
- }
8097
- if (!isURL) {
8098
- const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8099
- patternRegEx,
8100
- target,
8101
- () => subpath
8102
- ) : target + subpath;
8103
- return packageResolve(exportTarget, packageJsonUrl, conditions);
7889
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
7890
+ const protocol = base.protocol;
7891
+ const isData = protocol === "data:";
7892
+ const isRemote = isData || protocol === "http:" || protocol === "https:";
7893
+ let resolved;
7894
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
7895
+ try {
7896
+ resolved = new URL$1(specifier, base);
7897
+ } catch (error_) {
7898
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7899
+ error.cause = error_;
7900
+ throw error;
7901
+ }
7902
+ } else if (protocol === "file:" && specifier[0] === "#") {
7903
+ resolved = packageImportsResolve(specifier, base, conditions);
7904
+ } else {
7905
+ try {
7906
+ resolved = new URL$1(specifier);
7907
+ } catch (error_) {
7908
+ if (isRemote && !builtinModules.includes(specifier)) {
7909
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7910
+ error.cause = error_;
7911
+ throw error;
8104
7912
  }
7913
+ resolved = packageResolve(specifier, base, conditions);
8105
7914
  }
8106
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8107
7915
  }
8108
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8109
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8110
- if (!isPathMap) {
8111
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8112
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8113
- patternRegEx,
8114
- target,
8115
- () => subpath
8116
- ) : target;
8117
- emitInvalidSegmentDeprecation(
8118
- resolvedTarget,
8119
- request,
8120
- match,
8121
- packageJsonUrl,
8122
- internal,
8123
- base,
8124
- true
8125
- );
8126
- }
8127
- } else {
8128
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7916
+ assert(resolved !== void 0, "expected to be defined");
7917
+ if (resolved.protocol !== "file:") {
7918
+ return resolved;
7919
+ }
7920
+ return finalizeResolution(resolved, base);
7921
+ }
7922
+ function fileURLToPath(id) {
7923
+ if (typeof id === "string" && !id.startsWith("file://")) {
7924
+ return normalizeSlash(id);
7925
+ }
7926
+ return normalizeSlash(fileURLToPath$1(id));
7927
+ }
7928
+ function pathToFileURL(id) {
7929
+ return pathToFileURL$1(fileURLToPath(id)).toString();
7930
+ }
7931
+ function normalizeid(id) {
7932
+ if (typeof id !== "string") {
7933
+ id = id.toString();
7934
+ }
7935
+ if (/(node|data|http|https|file):/.test(id)) {
7936
+ return id;
7937
+ }
7938
+ if (BUILTIN_MODULES.has(id)) {
7939
+ return "node:" + id;
7940
+ }
7941
+ return "file://" + encodeURI(normalizeSlash(id));
7942
+ }
7943
+ var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
7944
+ var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
7945
+ var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
7946
+ "ERR_MODULE_NOT_FOUND",
7947
+ "ERR_UNSUPPORTED_DIR_IMPORT",
7948
+ "MODULE_NOT_FOUND",
7949
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
7950
+ ]);
7951
+ function _tryModuleResolve(id, url, conditions) {
7952
+ try {
7953
+ return moduleResolve(id, url, conditions);
7954
+ } catch (error) {
7955
+ if (!NOT_FOUND_ERRORS.has(error?.code)) {
7956
+ throw error;
8129
7957
  }
8130
7958
  }
8131
- const resolved = new URL$1(target, packageJsonUrl);
8132
- const resolvedPath = resolved.pathname;
8133
- const packagePath = new URL$1(".", packageJsonUrl).pathname;
8134
- if (!resolvedPath.startsWith(packagePath))
8135
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8136
- if (subpath === "") return resolved;
8137
- if (invalidSegmentRegEx.exec(subpath) !== null) {
8138
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8139
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
8140
- if (!isPathMap) {
8141
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8142
- patternRegEx,
8143
- target,
8144
- () => subpath
8145
- ) : target;
8146
- emitInvalidSegmentDeprecation(
8147
- resolvedTarget,
8148
- request,
8149
- match,
8150
- packageJsonUrl,
8151
- internal,
8152
- base,
8153
- false
8154
- );
8155
- }
7959
+ }
7960
+ function _resolve(id, options = {}) {
7961
+ if (typeof id !== "string") {
7962
+ if (id instanceof URL) {
7963
+ id = fileURLToPath(id);
8156
7964
  } else {
8157
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7965
+ throw new TypeError("input must be a `string` or `URL`");
8158
7966
  }
8159
7967
  }
8160
- if (pattern) {
8161
- return new URL$1(
8162
- RegExpPrototypeSymbolReplace.call(
8163
- patternRegEx,
8164
- resolved.href,
8165
- () => subpath
8166
- )
8167
- );
7968
+ if (/(node|data|http|https):/.test(id)) {
7969
+ return id;
8168
7970
  }
8169
- return new URL$1(subpath, resolved);
8170
- }
8171
- function isArrayIndex(key) {
8172
- const keyNumber = Number(key);
8173
- if (`${keyNumber}` !== key) return false;
8174
- return keyNumber >= 0 && keyNumber < 4294967295;
8175
- }
8176
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8177
- if (typeof target === "string") {
8178
- return resolvePackageTargetString(
8179
- target,
8180
- subpath,
8181
- packageSubpath,
8182
- packageJsonUrl,
8183
- base,
8184
- pattern,
8185
- internal,
8186
- isPathMap,
8187
- conditions
8188
- );
7971
+ if (BUILTIN_MODULES.has(id)) {
7972
+ return "node:" + id;
8189
7973
  }
8190
- if (Array.isArray(target)) {
8191
- const targetList = target;
8192
- if (targetList.length === 0) return null;
8193
- let lastException;
8194
- let i = -1;
8195
- while (++i < targetList.length) {
8196
- const targetItem = targetList[i];
8197
- let resolveResult;
8198
- try {
8199
- resolveResult = resolvePackageTarget(
8200
- packageJsonUrl,
8201
- targetItem,
8202
- subpath,
8203
- packageSubpath,
8204
- base,
8205
- pattern,
8206
- internal,
8207
- isPathMap,
8208
- conditions
8209
- );
8210
- } catch (error) {
8211
- const exception = (
8212
- /** @type {ErrnoException} */
8213
- error
8214
- );
8215
- lastException = exception;
8216
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8217
- throw error;
7974
+ if (id.startsWith("file://")) {
7975
+ id = fileURLToPath(id);
7976
+ }
7977
+ if (isAbsolute(id)) {
7978
+ try {
7979
+ const stat = statSync(id);
7980
+ if (stat.isFile()) {
7981
+ return pathToFileURL(id);
8218
7982
  }
8219
- if (resolveResult === void 0) continue;
8220
- if (resolveResult === null) {
8221
- lastException = null;
8222
- continue;
7983
+ } catch (error) {
7984
+ if (error?.code !== "ENOENT") {
7985
+ throw error;
8223
7986
  }
8224
- return resolveResult;
8225
7987
  }
8226
- if (lastException === void 0 || lastException === null) {
8227
- return null;
7988
+ }
7989
+ const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
7990
+ const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
7991
+ if (_urls.length === 0) {
7992
+ _urls.push(new URL(pathToFileURL(process.cwd())));
7993
+ }
7994
+ const urls = [..._urls];
7995
+ for (const url of _urls) {
7996
+ if (url.protocol === "file:") {
7997
+ urls.push(
7998
+ new URL("./", url),
7999
+ // If url is directory
8000
+ new URL(joinURL(url.pathname, "_index.js"), url),
8001
+ // TODO: Remove in next major version?
8002
+ new URL("node_modules", url)
8003
+ );
8228
8004
  }
8229
- throw lastException;
8230
8005
  }
8231
- if (typeof target === "object" && target !== null) {
8232
- const keys = Object.getOwnPropertyNames(target);
8233
- let i = -1;
8234
- while (++i < keys.length) {
8235
- const key = keys[i];
8236
- if (isArrayIndex(key)) {
8237
- throw new ERR_INVALID_PACKAGE_CONFIG(
8238
- fileURLToPath$1(packageJsonUrl),
8239
- base,
8240
- '"exports" cannot contain numeric property keys.'
8241
- );
8242
- }
8006
+ let resolved;
8007
+ for (const url of urls) {
8008
+ resolved = _tryModuleResolve(id, url, conditionsSet);
8009
+ if (resolved) {
8010
+ break;
8243
8011
  }
8244
- i = -1;
8245
- while (++i < keys.length) {
8246
- const key = keys[i];
8247
- if (key === "default" || conditions && conditions.has(key)) {
8248
- const conditionalTarget = (
8249
- /** @type {unknown} */
8250
- target[key]
8251
- );
8252
- const resolveResult = resolvePackageTarget(
8253
- packageJsonUrl,
8254
- conditionalTarget,
8255
- subpath,
8256
- packageSubpath,
8257
- base,
8258
- pattern,
8259
- internal,
8260
- isPathMap,
8261
- conditions
8012
+ for (const prefix of ["", "/index"]) {
8013
+ for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8014
+ resolved = _tryModuleResolve(
8015
+ joinURL(id, prefix) + extension,
8016
+ url,
8017
+ conditionsSet
8262
8018
  );
8263
- if (resolveResult === void 0) continue;
8264
- return resolveResult;
8019
+ if (resolved) {
8020
+ break;
8021
+ }
8022
+ }
8023
+ if (resolved) {
8024
+ break;
8265
8025
  }
8266
8026
  }
8267
- return null;
8027
+ if (resolved) {
8028
+ break;
8029
+ }
8268
8030
  }
8269
- if (target === null) {
8270
- return null;
8031
+ if (!resolved) {
8032
+ const error = new Error(
8033
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
8034
+ );
8035
+ error.code = "ERR_MODULE_NOT_FOUND";
8036
+ throw error;
8271
8037
  }
8272
- throw invalidPackageTarget(
8273
- packageSubpath,
8274
- target,
8275
- packageJsonUrl,
8276
- internal,
8277
- base
8278
- );
8038
+ return pathToFileURL(resolved);
8279
8039
  }
8280
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8281
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8282
- if (typeof exports !== "object" || exports === null) return false;
8283
- const keys = Object.getOwnPropertyNames(exports);
8284
- let isConditionalSugar = false;
8285
- let i = 0;
8286
- let keyIndex = -1;
8287
- while (++keyIndex < keys.length) {
8288
- const key = keys[keyIndex];
8289
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8290
- if (i++ === 0) {
8291
- isConditionalSugar = currentIsConditionalSugar;
8292
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8293
- throw new ERR_INVALID_PACKAGE_CONFIG(
8294
- fileURLToPath$1(packageJsonUrl),
8295
- base,
8296
- `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`
8040
+ function resolveSync(id, options) {
8041
+ return _resolve(id, options);
8042
+ }
8043
+ function resolvePathSync(id, options) {
8044
+ return fileURLToPath(resolveSync(id, options));
8045
+ }
8046
+
8047
+ // src/node-js-compat.ts
8048
+ import { defineEnv } from "unenv";
8049
+ var { env } = defineEnv({
8050
+ nodeCompat: true,
8051
+ presets: [cloudflare]
8052
+ });
8053
+ var nodeCompatExternals = new Set(env.external);
8054
+ var nodeCompatEntries = getNodeCompatEntries();
8055
+ function isNodeCompat(workerConfig) {
8056
+ if (workerConfig === void 0) {
8057
+ return false;
8058
+ }
8059
+ const nodeCompatMode = getNodeCompat(
8060
+ workerConfig.compatibility_date,
8061
+ workerConfig.compatibility_flags ?? []
8062
+ ).mode;
8063
+ if (nodeCompatMode === "v2") {
8064
+ return true;
8065
+ }
8066
+ if (nodeCompatMode === "v1") {
8067
+ throw new Error(
8068
+ `Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
8069
+ );
8070
+ }
8071
+ return false;
8072
+ }
8073
+ function injectGlobalCode(id, code) {
8074
+ const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8075
+ if (typeof globalInject === "string") {
8076
+ const moduleSpecifier2 = globalInject;
8077
+ return `import var_${globalName} from "${moduleSpecifier2}";
8078
+ globalThis.${globalName} = var_${globalName};
8079
+ `;
8080
+ }
8081
+ const [moduleSpecifier, exportName] = globalInject;
8082
+ assert2(
8083
+ moduleSpecifier !== void 0,
8084
+ "Expected moduleSpecifier to be defined"
8085
+ );
8086
+ assert2(exportName !== void 0, "Expected exportName to be defined");
8087
+ return `import var_${globalName} from "${moduleSpecifier}";
8088
+ globalThis.${globalName} = var_${globalName}.${exportName};
8089
+ `;
8090
+ }).join("\n");
8091
+ const polyfillCode = env.polyfill.map((polyfillPath) => `import "${polyfillPath}";
8092
+ `).join("");
8093
+ const modified = new MagicString(code);
8094
+ modified.prepend(injectedCode);
8095
+ modified.prepend(polyfillCode);
8096
+ return {
8097
+ code: modified.toString(),
8098
+ map: modified.generateMap({ hires: "boundary", source: id })
8099
+ };
8100
+ }
8101
+ function resolveNodeJSImport(source) {
8102
+ const alias = env.alias[source];
8103
+ if (alias) {
8104
+ return {
8105
+ unresolved: alias,
8106
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8107
+ };
8108
+ }
8109
+ if (nodeCompatEntries.has(source)) {
8110
+ return {
8111
+ unresolved: source,
8112
+ resolved: resolvePathSync(source, { url: import.meta.url })
8113
+ };
8114
+ }
8115
+ }
8116
+ function getNodeCompatEntries() {
8117
+ const entries = new Set(Object.values(env.alias));
8118
+ for (const globalInject of Object.values(env.inject)) {
8119
+ if (typeof globalInject === "string") {
8120
+ entries.add(globalInject);
8121
+ } else {
8122
+ assert2(
8123
+ globalInject[0] !== void 0,
8124
+ "Expected first element of globalInject to be defined"
8297
8125
  );
8126
+ entries.add(globalInject[0]);
8298
8127
  }
8299
8128
  }
8300
- return isConditionalSugar;
8129
+ env.polyfill.forEach((polyfill) => entries.add(polyfill));
8130
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8131
+ return entries;
8301
8132
  }
8302
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8303
- if (process$1.noDeprecation) {
8304
- return;
8305
- }
8306
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8307
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8308
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8309
- process$1.emitWarning(
8310
- `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
8311
- "DeprecationWarning",
8312
- "DEP0155"
8313
- );
8133
+
8134
+ // src/shared.ts
8135
+ var UNKNOWN_HOST = "http://localhost";
8136
+ var INIT_PATH = "/__vite_plugin_cloudflare_init__";
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
+ );
8143
+ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
8144
+
8145
+ // src/utils.ts
8146
+ import * as path2 from "node:path";
8147
+ import { Request as MiniflareRequest } from "miniflare";
8148
+ import "vite";
8149
+ function getOutputDirectory(userConfig, environmentName) {
8150
+ const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
8151
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path2.join(rootOutputDirectory, environmentName);
8314
8152
  }
8315
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8316
- let exports = packageConfig.exports;
8317
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8318
- exports = { ".": exports };
8319
- }
8320
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8321
- const target = exports[packageSubpath];
8322
- const resolveResult = resolvePackageTarget(
8323
- packageJsonUrl,
8324
- target,
8325
- "",
8326
- packageSubpath,
8327
- base,
8328
- false,
8329
- false,
8330
- false,
8331
- conditions
8332
- );
8333
- if (resolveResult === null || resolveResult === void 0) {
8334
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8335
- }
8336
- return resolveResult;
8337
- }
8338
- let bestMatch = "";
8339
- let bestMatchSubpath = "";
8340
- const keys = Object.getOwnPropertyNames(exports);
8341
- let i = -1;
8342
- while (++i < keys.length) {
8343
- const key = keys[i];
8344
- const patternIndex = key.indexOf("*");
8345
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8346
- if (packageSubpath.endsWith("/")) {
8347
- emitTrailingSlashPatternDeprecation(
8348
- packageSubpath,
8349
- packageJsonUrl,
8350
- base
8351
- );
8352
- }
8353
- const patternTrailer = key.slice(patternIndex + 1);
8354
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8355
- bestMatch = key;
8356
- bestMatchSubpath = packageSubpath.slice(
8357
- patternIndex,
8358
- packageSubpath.length - patternTrailer.length
8359
- );
8153
+ function getRouterWorker(miniflare) {
8154
+ return miniflare.getWorker(ROUTER_WORKER_NAME);
8155
+ }
8156
+ function toMiniflareRequest(request) {
8157
+ return new MiniflareRequest(request.url, {
8158
+ method: request.method,
8159
+ headers: [["accept-encoding", "identity"], ...request.headers],
8160
+ body: request.body,
8161
+ duplex: "half"
8162
+ });
8163
+ }
8164
+ function nodeHeadersToWebHeaders(nodeHeaders) {
8165
+ const headers = new Headers();
8166
+ for (const [key, value] of Object.entries(nodeHeaders)) {
8167
+ if (typeof value === "string") {
8168
+ headers.append(key, value);
8169
+ } else if (Array.isArray(value)) {
8170
+ for (const item of value) {
8171
+ headers.append(key, item);
8360
8172
  }
8361
8173
  }
8362
8174
  }
8363
- if (bestMatch) {
8364
- const target = (
8365
- /** @type {unknown} */
8366
- exports[bestMatch]
8367
- );
8368
- const resolveResult = resolvePackageTarget(
8369
- packageJsonUrl,
8370
- target,
8371
- bestMatchSubpath,
8372
- bestMatch,
8373
- base,
8374
- true,
8375
- false,
8376
- packageSubpath.endsWith("/"),
8377
- conditions
8378
- );
8379
- if (resolveResult === null || resolveResult === void 0) {
8380
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8175
+ return headers;
8176
+ }
8177
+ var postfixRE = /[?#].*$/;
8178
+ function cleanUrl(url) {
8179
+ return url.replace(postfixRE, "");
8180
+ }
8181
+
8182
+ // src/cloudflare-environment.ts
8183
+ var webSocketUndefinedError = "The WebSocket is undefined";
8184
+ function createHotChannel(webSocketContainer) {
8185
+ const listenersMap = /* @__PURE__ */ new Map();
8186
+ const client = {
8187
+ send(payload) {
8188
+ const webSocket = webSocketContainer.webSocket;
8189
+ assert3(webSocket, webSocketUndefinedError);
8190
+ webSocket.send(JSON.stringify(payload));
8191
+ }
8192
+ };
8193
+ function onMessage(event) {
8194
+ const payload = JSON.parse(event.data.toString());
8195
+ const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
8196
+ for (const listener of listeners) {
8197
+ listener(payload.data, client);
8381
8198
  }
8382
- return resolveResult;
8383
8199
  }
8384
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8385
- }
8386
- function patternKeyCompare(a, b) {
8387
- const aPatternIndex = a.indexOf("*");
8388
- const bPatternIndex = b.indexOf("*");
8389
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8390
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8391
- if (baseLengthA > baseLengthB) return -1;
8392
- if (baseLengthB > baseLengthA) return 1;
8393
- if (aPatternIndex === -1) return 1;
8394
- if (bPatternIndex === -1) return -1;
8395
- if (a.length > b.length) return -1;
8396
- if (b.length > a.length) return 1;
8397
- return 0;
8200
+ return {
8201
+ send(payload) {
8202
+ const webSocket = webSocketContainer.webSocket;
8203
+ assert3(webSocket, webSocketUndefinedError);
8204
+ webSocket.send(JSON.stringify(payload));
8205
+ },
8206
+ on(event, listener) {
8207
+ const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
8208
+ listeners.add(listener);
8209
+ listenersMap.set(event, listeners);
8210
+ },
8211
+ off(event, listener) {
8212
+ listenersMap.get(event)?.delete(listener);
8213
+ },
8214
+ listen() {
8215
+ const webSocket = webSocketContainer.webSocket;
8216
+ assert3(webSocket, webSocketUndefinedError);
8217
+ webSocket.addEventListener("message", onMessage);
8218
+ },
8219
+ close() {
8220
+ const webSocket = webSocketContainer.webSocket;
8221
+ assert3(webSocket, webSocketUndefinedError);
8222
+ webSocket.removeEventListener("message", onMessage);
8223
+ }
8224
+ };
8398
8225
  }
8399
- function packageImportsResolve(name2, base, conditions) {
8400
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8401
- const reason = "is not a valid internal imports specifier name";
8402
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
8226
+ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
8227
+ #webSocketContainer;
8228
+ #worker;
8229
+ constructor(name, config) {
8230
+ const webSocketContainer = {};
8231
+ super(name, config, {
8232
+ hot: true,
8233
+ transport: createHotChannel(webSocketContainer)
8234
+ });
8235
+ this.#webSocketContainer = webSocketContainer;
8403
8236
  }
8404
- let packageJsonUrl;
8405
- const packageConfig = getPackageScopeConfig(base);
8406
- if (packageConfig.exists) {
8407
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8408
- const imports = packageConfig.imports;
8409
- if (imports) {
8410
- if (own.call(imports, name2) && !name2.includes("*")) {
8411
- const resolveResult = resolvePackageTarget(
8412
- packageJsonUrl,
8413
- imports[name2],
8414
- "",
8415
- name2,
8416
- base,
8417
- false,
8418
- true,
8419
- false,
8420
- conditions
8421
- );
8422
- if (resolveResult !== null && resolveResult !== void 0) {
8423
- return resolveResult;
8424
- }
8425
- } else {
8426
- let bestMatch = "";
8427
- let bestMatchSubpath = "";
8428
- const keys = Object.getOwnPropertyNames(imports);
8429
- let i = -1;
8430
- while (++i < keys.length) {
8431
- const key = keys[i];
8432
- const patternIndex = key.indexOf("*");
8433
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8434
- const patternTrailer = key.slice(patternIndex + 1);
8435
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8436
- bestMatch = key;
8437
- bestMatchSubpath = name2.slice(
8438
- patternIndex,
8439
- name2.length - patternTrailer.length
8440
- );
8441
- }
8442
- }
8443
- }
8444
- if (bestMatch) {
8445
- const target = imports[bestMatch];
8446
- const resolveResult = resolvePackageTarget(
8447
- packageJsonUrl,
8448
- target,
8449
- bestMatchSubpath,
8450
- bestMatch,
8451
- base,
8452
- true,
8453
- true,
8454
- false,
8455
- conditions
8456
- );
8457
- if (resolveResult !== null && resolveResult !== void 0) {
8458
- return resolveResult;
8459
- }
8237
+ async initRunner(worker, root, workerConfig) {
8238
+ this.#worker = worker;
8239
+ const response = await this.#worker.fetch(
8240
+ new URL(INIT_PATH, UNKNOWN_HOST),
8241
+ {
8242
+ headers: {
8243
+ [VITE_DEV_METADATA_HEADER]: JSON.stringify({
8244
+ root,
8245
+ entryPath: workerConfig.main
8246
+ }),
8247
+ upgrade: "websocket"
8460
8248
  }
8461
8249
  }
8462
- }
8463
- }
8464
- throw importNotDefined(name2, packageJsonUrl, base);
8250
+ );
8251
+ assert3(
8252
+ response.ok,
8253
+ `Failed to initialize module runner, error: ${await response.text()}`
8254
+ );
8255
+ const webSocket = response.webSocket;
8256
+ assert3(webSocket, "Failed to establish WebSocket");
8257
+ webSocket.accept();
8258
+ this.#webSocketContainer.webSocket = webSocket;
8259
+ }
8260
+ };
8261
+ var cloudflareBuiltInModules = [
8262
+ "cloudflare:email",
8263
+ "cloudflare:sockets",
8264
+ "cloudflare:workers",
8265
+ "cloudflare:workflows"
8266
+ ];
8267
+ var defaultConditions = ["workerd", "module", "browser"];
8268
+ var target = "es2022";
8269
+ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
8270
+ return {
8271
+ resolve: {
8272
+ // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
8273
+ // dependencies as not external
8274
+ noExternal: true,
8275
+ // We want to use `workerd` package exports if available (e.g. for postgres).
8276
+ conditions: [...defaultConditions, "development|production"],
8277
+ // The Cloudflare ones are proper builtins in the environment
8278
+ builtins: [...cloudflareBuiltInModules]
8279
+ },
8280
+ dev: {
8281
+ createEnvironment(name, config) {
8282
+ return new CloudflareDevEnvironment(name, config);
8283
+ }
8284
+ },
8285
+ build: {
8286
+ createEnvironment(name, config) {
8287
+ return new vite2.BuildEnvironment(name, config);
8288
+ },
8289
+ target,
8290
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
8291
+ emitAssets: true,
8292
+ outDir: getOutputDirectory(userConfig, environmentName),
8293
+ copyPublicDir: false,
8294
+ ssr: true,
8295
+ rollupOptions: {
8296
+ // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
8297
+ // so the input value here serves both as the build input as well as the starting point for
8298
+ // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
8299
+ // optimizeDeps.entries in the dev config)
8300
+ input: workerConfig.main
8301
+ }
8302
+ },
8303
+ optimizeDeps: {
8304
+ // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
8305
+ noDiscovery: false,
8306
+ entries: workerConfig.main,
8307
+ exclude: [...cloudflareBuiltInModules],
8308
+ esbuildOptions: {
8309
+ platform: "neutral",
8310
+ target,
8311
+ conditions: [...defaultConditions, "development"],
8312
+ resolveExtensions: [
8313
+ ".mjs",
8314
+ ".js",
8315
+ ".mts",
8316
+ ".ts",
8317
+ ".jsx",
8318
+ ".tsx",
8319
+ ".json",
8320
+ ".cjs",
8321
+ ".cts",
8322
+ ".ctx"
8323
+ ]
8324
+ }
8325
+ },
8326
+ // if nodeCompat is enabled then let's keep the real process.env so that workerd can manipulate it
8327
+ keepProcessEnv: isNodeCompat(workerConfig)
8328
+ };
8465
8329
  }
8466
- function parsePackageName(specifier, base) {
8467
- let separatorIndex = specifier.indexOf("/");
8468
- let validPackageName = true;
8469
- let isScoped = false;
8470
- if (specifier[0] === "@") {
8471
- isScoped = true;
8472
- if (separatorIndex === -1 || specifier.length === 0) {
8473
- validPackageName = false;
8474
- } else {
8475
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
8476
- }
8477
- }
8478
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8479
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8480
- validPackageName = false;
8481
- }
8482
- if (!validPackageName) {
8483
- throw new ERR_INVALID_MODULE_SPECIFIER(
8484
- specifier,
8485
- "is not a valid package name",
8486
- fileURLToPath$1(base)
8487
- );
8330
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8331
+ if (resolvedPluginConfig.type === "assets-only") {
8332
+ return;
8488
8333
  }
8489
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8490
- return { packageName, packageSubpath, isScoped };
8334
+ return Promise.all(
8335
+ Object.entries(resolvedPluginConfig.workers).map(
8336
+ async ([environmentName, workerConfig]) => {
8337
+ const worker = await miniflare.getWorker(workerConfig.name);
8338
+ return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
8339
+ }
8340
+ )
8341
+ );
8491
8342
  }
8492
- function packageResolve(specifier, base, conditions) {
8493
- if (builtinModules2.includes(specifier)) {
8494
- return new URL$1("node:" + specifier);
8495
- }
8496
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8497
- specifier,
8498
- base
8343
+
8344
+ // src/deploy-config.ts
8345
+ import assert4 from "node:assert";
8346
+ import * as fs2 from "node:fs";
8347
+ import * as path3 from "node:path";
8348
+ import "vite";
8349
+ function getDeployConfigPath(root) {
8350
+ return path3.resolve(root, ".wrangler", "deploy", "config.json");
8351
+ }
8352
+ function getWorkerConfigPaths(root) {
8353
+ const deployConfigPath = getDeployConfigPath(root);
8354
+ const deployConfig = JSON.parse(
8355
+ fs2.readFileSync(deployConfigPath, "utf-8")
8499
8356
  );
8500
- const packageConfig = getPackageScopeConfig(base);
8501
- if (packageConfig.exists) {
8502
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8503
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8504
- return packageExportsResolve(
8505
- packageJsonUrl2,
8506
- packageSubpath,
8507
- packageConfig,
8508
- base,
8509
- conditions
8510
- );
8511
- }
8512
- }
8513
- let packageJsonUrl = new URL$1(
8514
- "./node_modules/" + packageName + "/package.json",
8515
- base
8357
+ return [
8358
+ { configPath: deployConfig.configPath },
8359
+ ...deployConfig.auxiliaryWorkers
8360
+ ].map(
8361
+ ({ configPath }) => path3.resolve(path3.dirname(deployConfigPath), configPath)
8516
8362
  );
8517
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8518
- let lastPath;
8519
- do {
8520
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8521
- if (!stat || !stat.isDirectory()) {
8522
- lastPath = packageJsonPath;
8523
- packageJsonUrl = new URL$1(
8524
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8525
- packageJsonUrl
8526
- );
8527
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8528
- continue;
8529
- }
8530
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8531
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8532
- return packageExportsResolve(
8533
- packageJsonUrl,
8534
- packageSubpath,
8535
- packageConfig2,
8536
- base,
8537
- conditions
8538
- );
8539
- }
8540
- if (packageSubpath === ".") {
8541
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8542
- }
8543
- return new URL$1(packageSubpath, packageJsonUrl);
8544
- } while (packageJsonPath.length !== lastPath.length);
8545
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8546
- }
8547
- function isRelativeSpecifier(specifier) {
8548
- if (specifier[0] === ".") {
8549
- if (specifier.length === 1 || specifier[1] === "/") return true;
8550
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8551
- return true;
8552
- }
8553
- }
8554
- return false;
8555
8363
  }
8556
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8557
- if (specifier === "") return false;
8558
- if (specifier[0] === "/") return true;
8559
- return isRelativeSpecifier(specifier);
8364
+ function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
8365
+ return path3.relative(
8366
+ deployConfigDirectory,
8367
+ path3.resolve(root, outputDirectory, "wrangler.json")
8368
+ );
8560
8369
  }
8561
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8562
- const protocol = base.protocol;
8563
- const isData = protocol === "data:";
8564
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8565
- let resolved;
8566
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8567
- try {
8568
- resolved = new URL$1(specifier, base);
8569
- } catch (error_) {
8570
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8571
- error.cause = error_;
8572
- throw error;
8573
- }
8574
- } else if (protocol === "file:" && specifier[0] === "#") {
8575
- resolved = packageImportsResolve(specifier, base, conditions);
8370
+ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
8371
+ const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
8372
+ const deployConfigDirectory = path3.dirname(deployConfigPath);
8373
+ fs2.mkdirSync(deployConfigDirectory, { recursive: true });
8374
+ if (resolvedPluginConfig.type === "assets-only") {
8375
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
8376
+ assert4(
8377
+ clientOutputDirectory,
8378
+ "Unexpected error: client environment output directory is undefined"
8379
+ );
8380
+ const deployConfig = {
8381
+ configPath: getRelativePathToWorkerConfig(
8382
+ deployConfigDirectory,
8383
+ resolvedViteConfig.root,
8384
+ clientOutputDirectory
8385
+ ),
8386
+ auxiliaryWorkers: []
8387
+ };
8388
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8576
8389
  } else {
8577
- try {
8578
- resolved = new URL$1(specifier);
8579
- } catch (error_) {
8580
- if (isRemote && !builtinModules2.includes(specifier)) {
8581
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8582
- error.cause = error_;
8583
- throw error;
8390
+ let entryWorkerConfigPath;
8391
+ const auxiliaryWorkers = [];
8392
+ for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
8393
+ const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
8394
+ assert4(
8395
+ outputDirectory,
8396
+ `Unexpected error: ${environmentName} environment output directory is undefined`
8397
+ );
8398
+ const configPath = getRelativePathToWorkerConfig(
8399
+ deployConfigDirectory,
8400
+ resolvedViteConfig.root,
8401
+ outputDirectory
8402
+ );
8403
+ if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
8404
+ entryWorkerConfigPath = configPath;
8405
+ } else {
8406
+ auxiliaryWorkers.push({ configPath });
8584
8407
  }
8585
- resolved = packageResolve(specifier, base, conditions);
8586
8408
  }
8409
+ assert4(
8410
+ entryWorkerConfigPath,
8411
+ `Unexpected error: entryWorkerConfigPath is undefined`
8412
+ );
8413
+ const deployConfig = {
8414
+ configPath: entryWorkerConfigPath,
8415
+ auxiliaryWorkers
8416
+ };
8417
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8587
8418
  }
8588
- assert5(resolved !== void 0, "expected to be defined");
8589
- if (resolved.protocol !== "file:") {
8590
- return resolved;
8591
- }
8592
- return finalizeResolution(resolved, base);
8593
8419
  }
8594
- function fileURLToPath2(id) {
8595
- if (typeof id === "string" && !id.startsWith("file://")) {
8596
- return normalizeSlash(id);
8420
+
8421
+ // src/miniflare-options.ts
8422
+ import assert5 from "node:assert";
8423
+ import * as fs3 from "node:fs";
8424
+ import * as fsp from "node:fs/promises";
8425
+ import * as path4 from "node:path";
8426
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
8427
+ import {
8428
+ kCurrentWorker,
8429
+ Log,
8430
+ LogLevel,
8431
+ Response as MiniflareResponse
8432
+ } from "miniflare";
8433
+ import { globSync } from "tinyglobby";
8434
+ import "vite";
8435
+ import {
8436
+ unstable_getMiniflareWorkerOptions,
8437
+ unstable_readConfig
8438
+ } from "wrangler";
8439
+ function getPersistence(root, persistState) {
8440
+ if (persistState === false) {
8441
+ return {};
8597
8442
  }
8598
- return normalizeSlash(fileURLToPath$1(id));
8599
- }
8600
- function pathToFileURL(id) {
8601
- return pathToFileURL$1(fileURLToPath2(id)).toString();
8443
+ const defaultPersistPath = ".wrangler/state";
8444
+ const persistPath = path4.resolve(
8445
+ root,
8446
+ typeof persistState === "object" ? persistState.path : defaultPersistPath,
8447
+ "v3"
8448
+ );
8449
+ return {
8450
+ cachePersist: path4.join(persistPath, "cache"),
8451
+ d1Persist: path4.join(persistPath, "d1"),
8452
+ durableObjectsPersist: path4.join(persistPath, "do"),
8453
+ kvPersist: path4.join(persistPath, "kv"),
8454
+ r2Persist: path4.join(persistPath, "r2"),
8455
+ workflowsPersist: path4.join(persistPath, "workflows")
8456
+ };
8602
8457
  }
8603
- function normalizeid(id) {
8604
- if (typeof id !== "string") {
8605
- id = id.toString();
8606
- }
8607
- if (/(node|data|http|https|file):/.test(id)) {
8608
- return id;
8609
- }
8610
- if (BUILTIN_MODULES.has(id)) {
8611
- return "node:" + id;
8612
- }
8613
- return "file://" + encodeURI(normalizeSlash(id));
8458
+ function missingWorkerErrorMessage(workerName) {
8459
+ return `${workerName} does not match a worker name.`;
8614
8460
  }
8615
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8616
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8617
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8618
- "ERR_MODULE_NOT_FOUND",
8619
- "ERR_UNSUPPORTED_DIR_IMPORT",
8620
- "MODULE_NOT_FOUND",
8621
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8622
- ]);
8623
- function _tryModuleResolve(id, url, conditions) {
8624
- try {
8625
- return moduleResolve(id, url, conditions);
8626
- } catch (error) {
8627
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8628
- throw error;
8461
+ function getWorkerToWorkerEntrypointNamesMap(workers) {
8462
+ const workerToWorkerEntrypointNamesMap = new Map(
8463
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8464
+ );
8465
+ for (const worker of workers) {
8466
+ for (const value of Object.values(worker.serviceBindings ?? {})) {
8467
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
8468
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
8469
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
8470
+ assert5(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8471
+ entrypointNames.add(value.entrypoint);
8472
+ }
8629
8473
  }
8630
8474
  }
8475
+ return workerToWorkerEntrypointNamesMap;
8631
8476
  }
8632
- function _resolve(id, options = {}) {
8633
- if (typeof id !== "string") {
8634
- if (id instanceof URL) {
8635
- id = fileURLToPath2(id);
8636
- } else {
8637
- throw new TypeError("input must be a `string` or `URL`");
8477
+ function getWorkerToDurableObjectClassNamesMap(workers) {
8478
+ const workerToDurableObjectClassNamesMap = new Map(
8479
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8480
+ );
8481
+ for (const worker of workers) {
8482
+ for (const value of Object.values(worker.durableObjects ?? {})) {
8483
+ if (typeof value === "string") {
8484
+ const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
8485
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8486
+ classNames.add(value);
8487
+ } else if (typeof value === "object") {
8488
+ if (value.scriptName) {
8489
+ const classNames = workerToDurableObjectClassNamesMap.get(
8490
+ value.scriptName
8491
+ );
8492
+ assert5(classNames, missingWorkerErrorMessage(value.scriptName));
8493
+ classNames.add(value.className);
8494
+ } else {
8495
+ const classNames = workerToDurableObjectClassNamesMap.get(
8496
+ worker.name
8497
+ );
8498
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8499
+ classNames.add(value.className);
8500
+ }
8501
+ }
8638
8502
  }
8639
8503
  }
8640
- if (/(node|data|http|https):/.test(id)) {
8641
- return id;
8642
- }
8643
- if (BUILTIN_MODULES.has(id)) {
8644
- return "node:" + id;
8504
+ return workerToDurableObjectClassNamesMap;
8505
+ }
8506
+ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
8507
+ const workerToWorkflowEntrypointClassNamesMap = new Map(
8508
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8509
+ );
8510
+ for (const worker of workers) {
8511
+ for (const value of Object.values(worker.workflows ?? {})) {
8512
+ if (value.scriptName) {
8513
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8514
+ value.scriptName
8515
+ );
8516
+ assert5(classNames, missingWorkerErrorMessage(value.scriptName));
8517
+ classNames.add(value.className);
8518
+ } else {
8519
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8520
+ worker.name
8521
+ );
8522
+ assert5(classNames, missingWorkerErrorMessage(worker.name));
8523
+ classNames.add(value.className);
8524
+ }
8525
+ }
8645
8526
  }
8646
- if (id.startsWith("file://")) {
8647
- id = fileURLToPath2(id);
8527
+ return workerToWorkflowEntrypointClassNamesMap;
8528
+ }
8529
+ var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
8530
+ var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
8531
+ var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
8532
+ var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
8533
+ var RUNNER_PATH = "./runner-worker/index.js";
8534
+ function getEntryWorkerConfig(resolvedPluginConfig) {
8535
+ if (resolvedPluginConfig.type === "assets-only") {
8536
+ return;
8648
8537
  }
8649
- if (isAbsolute(id)) {
8650
- try {
8651
- const stat = statSync2(id);
8652
- if (stat.isFile()) {
8653
- return pathToFileURL(id);
8538
+ return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8539
+ }
8540
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8541
+ const resolvedViteConfig = viteDevServer.config;
8542
+ const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
8543
+ const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
8544
+ const assetWorkers = [
8545
+ {
8546
+ name: ROUTER_WORKER_NAME,
8547
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8548
+ modulesRoot: miniflareModulesRoot,
8549
+ modules: [
8550
+ {
8551
+ type: "ESModule",
8552
+ path: path4.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
8553
+ contents: fs3.readFileSync(
8554
+ fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
8555
+ )
8556
+ }
8557
+ ],
8558
+ bindings: {
8559
+ CONFIG: {
8560
+ has_user_worker: resolvedPluginConfig.type === "workers"
8561
+ }
8562
+ },
8563
+ serviceBindings: {
8564
+ ASSET_WORKER: ASSET_WORKER_NAME,
8565
+ ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
8654
8566
  }
8655
- } catch (error) {
8656
- if (error?.code !== "ENOENT") {
8657
- throw error;
8567
+ },
8568
+ {
8569
+ name: ASSET_WORKER_NAME,
8570
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8571
+ modulesRoot: miniflareModulesRoot,
8572
+ modules: [
8573
+ {
8574
+ type: "ESModule",
8575
+ path: path4.join(miniflareModulesRoot, ASSET_WORKER_PATH),
8576
+ contents: fs3.readFileSync(
8577
+ fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
8578
+ )
8579
+ }
8580
+ ],
8581
+ bindings: {
8582
+ CONFIG: {
8583
+ ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
8584
+ ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
8585
+ }
8586
+ },
8587
+ serviceBindings: {
8588
+ __VITE_ASSET_EXISTS__: async (request) => {
8589
+ const { pathname } = new URL(request.url);
8590
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8591
+ let exists;
8592
+ try {
8593
+ exists = fs3.statSync(filePath).isFile();
8594
+ } catch (error) {
8595
+ exists = false;
8596
+ }
8597
+ return MiniflareResponse.json(exists);
8598
+ },
8599
+ __VITE_FETCH_ASSET__: async (request) => {
8600
+ const { pathname } = new URL(request.url);
8601
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8602
+ try {
8603
+ let html = await fsp.readFile(filePath, "utf-8");
8604
+ html = await viteDevServer.transformIndexHtml(pathname, html);
8605
+ return new MiniflareResponse(html, {
8606
+ headers: { "Content-Type": "text/html" }
8607
+ });
8608
+ } catch (error) {
8609
+ throw new Error(`Unexpected error. Failed to load ${pathname}`);
8610
+ }
8611
+ }
8658
8612
  }
8659
8613
  }
8660
- }
8661
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8662
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8663
- if (_urls.length === 0) {
8664
- _urls.push(new URL(pathToFileURL(process.cwd())));
8665
- }
8666
- const urls = [..._urls];
8667
- for (const url of _urls) {
8668
- if (url.protocol === "file:") {
8669
- urls.push(
8670
- new URL("./", url),
8671
- // If url is directory
8672
- new URL(joinURL(url.pathname, "_index.js"), url),
8673
- // TODO: Remove in next major version?
8674
- new URL("node_modules", url)
8614
+ ];
8615
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
8616
+ ([environmentName, workerConfig]) => {
8617
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
8618
+ {
8619
+ ...workerConfig,
8620
+ assets: void 0
8621
+ },
8622
+ resolvedPluginConfig.cloudflareEnv
8675
8623
  );
8624
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
8625
+ const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8626
+ return {
8627
+ externalWorkers: externalWorkers2,
8628
+ worker: {
8629
+ ...workerOptions,
8630
+ name: workerOptions.name ?? workerConfig.name,
8631
+ modulesRoot: miniflareModulesRoot,
8632
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
8633
+ serviceBindings: {
8634
+ ...workerOptions.serviceBindings,
8635
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
8636
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
8637
+ } : {},
8638
+ __VITE_INVOKE_MODULE__: async (request) => {
8639
+ const payload = await request.json();
8640
+ const invokePayloadData = payload.data;
8641
+ assert5(
8642
+ invokePayloadData.name === "fetchModule",
8643
+ `Invalid invoke event: ${invokePayloadData.name}`
8644
+ );
8645
+ const [moduleId] = invokePayloadData.data;
8646
+ if (additionalModuleRE.test(moduleId)) {
8647
+ const result2 = {
8648
+ externalize: moduleId,
8649
+ type: "module"
8650
+ };
8651
+ return MiniflareResponse.json({ result: result2 });
8652
+ }
8653
+ const devEnvironment = viteDevServer.environments[environmentName];
8654
+ const result = await devEnvironment.hot.handleInvoke(payload);
8655
+ return MiniflareResponse.json(result);
8656
+ }
8657
+ }
8658
+ }
8659
+ };
8676
8660
  }
8677
- }
8678
- let resolved;
8679
- for (const url of urls) {
8680
- resolved = _tryModuleResolve(id, url, conditionsSet);
8681
- if (resolved) {
8682
- break;
8683
- }
8684
- for (const prefix of ["", "/index"]) {
8685
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8686
- resolved = _tryModuleResolve(
8687
- joinURL(id, prefix) + extension,
8688
- url,
8689
- conditionsSet
8661
+ ) : [];
8662
+ const userWorkers = workersFromConfig.map((options) => options.worker);
8663
+ const externalWorkers = workersFromConfig.flatMap(
8664
+ (options) => options.externalWorkers
8665
+ );
8666
+ const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
8667
+ const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
8668
+ const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
8669
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8670
+ return {
8671
+ log: logger,
8672
+ handleRuntimeStdio(stdout, stderr) {
8673
+ const decoder = new TextDecoder();
8674
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8675
+ stderr.forEach(
8676
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8677
+ );
8678
+ },
8679
+ ...getPersistence(
8680
+ resolvedViteConfig.root,
8681
+ resolvedPluginConfig.persistState
8682
+ ),
8683
+ workers: [
8684
+ ...assetWorkers,
8685
+ ...externalWorkers,
8686
+ ...userWorkers.map((workerOptions) => {
8687
+ const wrappers = [
8688
+ `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
8689
+ `export default createWorkerEntrypointWrapper('default');`
8690
+ ];
8691
+ const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
8692
+ workerOptions.name
8693
+ );
8694
+ assert5(
8695
+ workerEntrypointNames,
8696
+ `WorkerEntrypoint names not found for worker ${workerOptions.name}`
8697
+ );
8698
+ for (const entrypointName of [...workerEntrypointNames].sort()) {
8699
+ wrappers.push(
8700
+ `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
8701
+ );
8702
+ }
8703
+ const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8704
+ workerOptions.name
8705
+ );
8706
+ assert5(
8707
+ durableObjectClassNames,
8708
+ `DurableObject class names not found for worker ${workerOptions.name}`
8709
+ );
8710
+ for (const className of [...durableObjectClassNames].sort()) {
8711
+ wrappers.push(
8712
+ `export const ${className} = createDurableObjectWrapper('${className}');`
8713
+ );
8714
+ }
8715
+ const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
8716
+ assert5(
8717
+ workflowEntrypointClassNames,
8718
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
8690
8719
  );
8691
- if (resolved) {
8692
- break;
8720
+ for (const className of [...workflowEntrypointClassNames].sort()) {
8721
+ wrappers.push(
8722
+ `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
8723
+ );
8693
8724
  }
8725
+ return {
8726
+ ...workerOptions,
8727
+ modules: [
8728
+ {
8729
+ type: "ESModule",
8730
+ path: path4.join(miniflareModulesRoot, WRAPPER_PATH),
8731
+ contents: wrappers.join("\n")
8732
+ },
8733
+ {
8734
+ type: "ESModule",
8735
+ path: path4.join(miniflareModulesRoot, RUNNER_PATH),
8736
+ contents: fs3.readFileSync(
8737
+ fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
8738
+ )
8739
+ }
8740
+ ],
8741
+ unsafeUseModuleFallbackService: true
8742
+ };
8743
+ })
8744
+ ],
8745
+ async unsafeModuleFallbackService(request) {
8746
+ const url = new URL(request.url);
8747
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
8748
+ assert5(
8749
+ rawSpecifier,
8750
+ `Unexpected error: no specifier in request to module fallback service.`
8751
+ );
8752
+ const match = additionalModuleRE.exec(rawSpecifier);
8753
+ assert5(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8754
+ const [full, moduleType, modulePath] = match;
8755
+ assert5(
8756
+ moduleType,
8757
+ `Unexpected error: module type not found in reference: ${full}.`
8758
+ );
8759
+ assert5(
8760
+ modulePath,
8761
+ `Unexpected error: module path not found in reference: ${full}.`
8762
+ );
8763
+ let contents;
8764
+ try {
8765
+ contents = await fsp.readFile(modulePath);
8766
+ } catch (error) {
8767
+ throw new Error(
8768
+ `Import "${modulePath}" not found. Does the file exist?`
8769
+ );
8694
8770
  }
8695
- if (resolved) {
8696
- break;
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
+ }
8697
8784
  }
8698
8785
  }
8699
- if (resolved) {
8700
- break;
8701
- }
8702
- }
8703
- if (!resolved) {
8704
- const error = new Error(
8705
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8706
- );
8707
- error.code = "ERR_MODULE_NOT_FOUND";
8708
- throw error;
8709
- }
8710
- return pathToFileURL(resolved);
8711
- }
8712
- function resolveSync(id, options) {
8713
- return _resolve(id, options);
8714
- }
8715
- function resolvePathSync(id, options) {
8716
- return fileURLToPath2(resolveSync(id, options));
8717
- }
8718
-
8719
- // src/node-js-compat.ts
8720
- import { defineEnv } from "unenv";
8721
- var { env } = defineEnv({
8722
- nodeCompat: true,
8723
- presets: [cloudflare]
8724
- });
8725
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8726
- function isNodeCompat(workerConfig) {
8727
- if (workerConfig === void 0) {
8728
- return false;
8729
- }
8730
- const nodeCompatMode = getNodeCompat(
8731
- workerConfig.compatibility_date,
8732
- workerConfig.compatibility_flags ?? []
8733
- ).mode;
8734
- if (nodeCompatMode === "v2") {
8735
- return true;
8736
- }
8737
- if (nodeCompatMode === "legacy") {
8738
- throw new Error(
8739
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8740
- );
8741
- }
8742
- if (nodeCompatMode === "v1") {
8743
- throw new Error(
8744
- `Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
8745
- );
8746
- }
8747
- return false;
8786
+ };
8748
8787
  }
8749
- function injectGlobalCode(id, code) {
8750
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8751
- if (typeof globalInject === "string") {
8752
- const moduleSpecifier2 = globalInject;
8753
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8754
- globalThis.${globalName} = var_${globalName};
8755
- `;
8756
- }
8757
- const [moduleSpecifier, exportName] = globalInject;
8758
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8759
- globalThis.${globalName} = var_${globalName}.${exportName};
8760
- `;
8761
- }).join("\n");
8762
- const modified = new MagicString(code);
8763
- modified.prepend(injectedCode);
8788
+ function getPreviewModules(main, modulesRules) {
8789
+ assert5(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8790
+ const rootPath = path4.dirname(main);
8791
+ const entryPath = path4.basename(main);
8764
8792
  return {
8765
- code: modified.toString(),
8766
- map: modified.generateMap({ hires: "boundary", source: id })
8793
+ rootPath,
8794
+ modules: [
8795
+ {
8796
+ type: "ESModule",
8797
+ path: entryPath
8798
+ },
8799
+ ...modulesRules.flatMap(
8800
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
8801
+ type,
8802
+ path: path8
8803
+ }))
8804
+ )
8805
+ ]
8767
8806
  };
8768
8807
  }
8769
- function getNodeCompatAliases() {
8770
- const aliases = {};
8771
- Object.keys(env.alias).forEach((key) => {
8772
- if (!env.external.includes(key)) {
8773
- aliases[key] = CLOUDFLARE_VIRTUAL_PREFIX + key;
8774
- }
8775
- });
8776
- return aliases;
8777
- }
8778
- function getNodeCompatExternals() {
8779
- return env.external;
8780
- }
8781
- function maybeStripNodeJsVirtualPrefix(source) {
8782
- return source.startsWith(CLOUDFLARE_VIRTUAL_PREFIX) ? source.slice(CLOUDFLARE_VIRTUAL_PREFIX.length) : void 0;
8783
- }
8784
- function resolveNodeJSImport(source) {
8785
- const alias = env.alias[source];
8786
- if (alias) {
8787
- assert6(
8788
- !env.external.includes(alias),
8789
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8790
- );
8791
- source = alias;
8792
- }
8793
- const resolved = resolvePathSync(source, {
8794
- url: import.meta.url
8808
+ function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
8809
+ const resolvedViteConfig = vitePreviewServer.config;
8810
+ const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
8811
+ const workerConfigs = configPaths.map(
8812
+ (configPath) => unstable_readConfig({ config: configPath })
8813
+ );
8814
+ const workers = workerConfigs.flatMap((config) => {
8815
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
8816
+ const { externalWorkers } = miniflareWorkerOptions;
8817
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8818
+ return [
8819
+ {
8820
+ ...workerOptions,
8821
+ name: workerOptions.name ?? config.name,
8822
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
8823
+ },
8824
+ ...externalWorkers
8825
+ ];
8795
8826
  });
8827
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8796
8828
  return {
8797
- unresolved: source,
8798
- resolved
8829
+ log: logger,
8830
+ handleRuntimeStdio(stdout, stderr) {
8831
+ const decoder = new TextDecoder();
8832
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8833
+ stderr.forEach(
8834
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8835
+ );
8836
+ },
8837
+ ...getPersistence(resolvedViteConfig.root, persistState),
8838
+ workers
8799
8839
  };
8800
8840
  }
8841
+ var ViteMiniflareLogger = class extends Log {
8842
+ logger;
8843
+ constructor(config) {
8844
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8845
+ this.logger = config.logger;
8846
+ }
8847
+ logWithLevel(level, message) {
8848
+ if (/^Ready on http/.test(message)) {
8849
+ level = LogLevel.DEBUG;
8850
+ }
8851
+ switch (level) {
8852
+ case LogLevel.ERROR:
8853
+ return this.logger.error(message);
8854
+ case LogLevel.WARN:
8855
+ return this.logger.warn(message);
8856
+ case LogLevel.INFO:
8857
+ return this.logger.info(message);
8858
+ }
8859
+ }
8860
+ };
8861
+ function miniflareLogLevelFromViteLogLevel(level = "info") {
8862
+ switch (level) {
8863
+ case "error":
8864
+ return LogLevel.ERROR;
8865
+ case "warn":
8866
+ return LogLevel.WARN;
8867
+ case "info":
8868
+ return LogLevel.INFO;
8869
+ case "silent":
8870
+ return LogLevel.NONE;
8871
+ }
8872
+ }
8801
8873
 
8802
8874
  // src/plugin-config.ts
8803
- import assert8 from "node:assert";
8875
+ import assert6 from "node:assert";
8804
8876
  import * as path6 from "node:path";
8805
8877
  import * as vite5 from "vite";
8806
8878
 
8807
8879
  // src/workers-configs.ts
8808
- import assert7 from "node:assert";
8809
8880
  import * as fs4 from "node:fs";
8810
8881
  import * as path5 from "node:path";
8811
8882
  import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
8812
-
8813
- // package.json
8814
- var name = "@cloudflare/vite-plugin";
8815
-
8816
- // src/workers-configs.ts
8817
8883
  var nonApplicableWorkerConfigs = {
8818
8884
  /**
8819
8885
  * Object containing configs that have a vite replacement, the object's field contain details about the config's replacement
@@ -8841,16 +8907,12 @@ var nonApplicableWorkerConfigs = {
8841
8907
  "build",
8842
8908
  "find_additional_modules",
8843
8909
  "no_bundle",
8844
- "node_compat",
8845
8910
  "preserve_file_names",
8911
+ "rules",
8846
8912
  "site",
8847
8913
  "tsconfig",
8848
8914
  "upload_source_maps"
8849
- ],
8850
- /**
8851
- * All the configs that get overridden by our plugin
8852
- */
8853
- overridden: ["rules"]
8915
+ ]
8854
8916
  };
8855
8917
  var nullableNonApplicable = [
8856
8918
  "alias",
@@ -8858,7 +8920,6 @@ var nullableNonApplicable = [
8858
8920
  "find_additional_modules",
8859
8921
  "minify",
8860
8922
  "no_bundle",
8861
- "node_compat",
8862
8923
  "preserve_file_names",
8863
8924
  "site",
8864
8925
  "tsconfig",
@@ -8867,8 +8928,7 @@ var nullableNonApplicable = [
8867
8928
  function readWorkerConfig(configPath, env2) {
8868
8929
  const nonApplicable = {
8869
8930
  replacedByVite: /* @__PURE__ */ new Set(),
8870
- notRelevant: /* @__PURE__ */ new Set(),
8871
- overridden: /* @__PURE__ */ new Set()
8931
+ notRelevant: /* @__PURE__ */ new Set()
8872
8932
  };
8873
8933
  const config = unstable_readConfig2({ config: configPath, env: env2 }, {});
8874
8934
  const raw = structuredClone(config);
@@ -8880,9 +8940,6 @@ function readWorkerConfig(configPath, env2) {
8880
8940
  if (isNotRelevant(prop)) {
8881
8941
  nonApplicable.notRelevant.add(prop);
8882
8942
  }
8883
- if (isOverridden(prop)) {
8884
- nonApplicable.overridden.add(prop);
8885
- }
8886
8943
  }
8887
8944
  delete config[prop];
8888
8945
  });
@@ -8895,7 +8952,7 @@ function readWorkerConfig(configPath, env2) {
8895
8952
  }
8896
8953
  delete config["define"];
8897
8954
  if (config.rules.length > 0) {
8898
- nonApplicable.overridden.add("rules");
8955
+ nonApplicable.notRelevant.add("rules");
8899
8956
  }
8900
8957
  return {
8901
8958
  raw,
@@ -8947,7 +9004,7 @@ function getWarningForWorkersConfigs(configs) {
8947
9004
  }
8948
9005
  function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8949
9006
  const lines = [];
8950
- const { replacedByVite, notRelevant, overridden } = workerConfig.nonApplicable;
9007
+ const { replacedByVite, notRelevant } = workerConfig.nonApplicable;
8951
9008
  for (const config of replacedByVite) {
8952
9009
  lines.push(
8953
9010
  `${linePrefix}\`${config}\` which is replaced by Vite's \`${nonApplicableWorkerConfigs.replacedByVite[config].viteReplacement}\` (docs: ${nonApplicableWorkerConfigs.replacedByVite[config].viteDocs})`
@@ -8957,10 +9014,6 @@ function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
8957
9014
  lines.push(
8958
9015
  `${linePrefix}${[...notRelevant].map((config) => `\`${config}\``).join(", ")} which ${notRelevant.size > 1 ? "are" : "is"} not relevant in the context of a Vite project`
8959
9016
  );
8960
- if (overridden.size > 0)
8961
- lines.push(
8962
- `${linePrefix}${[...overridden].map((config) => `\`${config}\``).join(", ")} which ${overridden.size > 1 ? "are" : "is"} overridden by \`${name}\``
8963
- );
8964
9017
  return lines;
8965
9018
  }
8966
9019
  function isReplacedByVite(configName) {
@@ -8969,9 +9022,6 @@ function isReplacedByVite(configName) {
8969
9022
  function isNotRelevant(configName) {
8970
9023
  return nonApplicableWorkerConfigs.notRelevant.includes(configName);
8971
9024
  }
8972
- function isOverridden(configName) {
8973
- return nonApplicableWorkerConfigs.overridden.includes(configName);
8974
- }
8975
9025
  function missingFieldErrorMessage(field, configPath, env2) {
8976
9026
  return `No ${field} field provided in '${configPath}'${env2 ? ` for '${env2}' environment` : ""}`;
8977
9027
  }
@@ -8981,42 +9031,55 @@ function getWorkerConfig(configPath, env2, opts) {
8981
9031
  }
8982
9032
  const { raw, config, nonApplicable } = readWorkerConfig(configPath, env2);
8983
9033
  opts?.visitedConfigPaths?.add(configPath);
8984
- assert7(
8985
- config.topLevelName,
8986
- missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
8987
- );
8988
- assert7(config.name, missingFieldErrorMessage(`'name'`, configPath, env2));
8989
- assert7(
8990
- config.compatibility_date,
8991
- missingFieldErrorMessage(`'compatibility_date'`, configPath, env2)
8992
- );
8993
- if (opts?.isEntryWorker && !config.main) {
8994
- assert7(
8995
- config.assets,
8996
- 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)
8997
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) {
8998
9053
  return {
8999
9054
  type: "assets-only",
9000
9055
  raw,
9001
9056
  config: {
9002
9057
  ...config,
9003
- topLevelName: config.topLevelName,
9004
- name: config.name,
9005
- compatibility_date: config.compatibility_date,
9006
- assets: config.assets
9058
+ ...requiredFields
9007
9059
  },
9008
9060
  nonApplicable
9009
9061
  };
9010
9062
  }
9011
- assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9063
+ if (!config.main) {
9064
+ throw new Error(missingFieldErrorMessage(`'main'`, configPath, env2));
9065
+ }
9066
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9067
+ if (!mainStat) {
9068
+ throw new Error(
9069
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9070
+ );
9071
+ }
9072
+ if (mainStat.isDirectory()) {
9073
+ throw new Error(
9074
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9075
+ );
9076
+ }
9012
9077
  return {
9013
9078
  type: "worker",
9014
9079
  raw,
9015
9080
  config: {
9016
9081
  ...config,
9017
- topLevelName: config.topLevelName,
9018
- name: config.name,
9019
- compatibility_date: config.compatibility_date,
9082
+ ...requiredFields,
9020
9083
  main: config.main
9021
9084
  },
9022
9085
  nonApplicable
@@ -9046,10 +9109,11 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9046
9109
  ""
9047
9110
  );
9048
9111
  const configPath = pluginConfig.configPath ? path6.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
9049
- assert8(
9050
- configPath,
9051
- `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9052
- );
9112
+ if (!configPath) {
9113
+ throw new Error(
9114
+ `Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
9115
+ );
9116
+ }
9053
9117
  const entryWorkerResolvedConfig = getWorkerConfig(configPath, cloudflareEnv, {
9054
9118
  visitedConfigPaths: configPaths,
9055
9119
  isEntryWorker: true
@@ -9081,7 +9145,7 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9081
9145
  }
9082
9146
  );
9083
9147
  auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
9084
- assert8(
9148
+ assert6(
9085
9149
  workerResolvedConfig.type === "worker",
9086
9150
  "Unexpected error: received AssetsOnlyResult with auxiliary workers."
9087
9151
  );
@@ -9109,9 +9173,10 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9173
  }
9110
9174
 
9111
9175
  // src/websockets.ts
9112
- import ws from "ws";
9113
- function handleWebSocket(httpServer, fetcher, logger) {
9114
- const nodeWebSocket = new ws.Server({ noServer: true });
9176
+ import { coupleWebSocket } from "miniflare";
9177
+ import { WebSocketServer } from "ws";
9178
+ function handleWebSocket(httpServer, fetcher) {
9179
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9180
  httpServer.on(
9116
9181
  "upgrade",
9117
9182
  async (request, socket, head) => {
@@ -9134,34 +9199,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9134
9199
  socket,
9135
9200
  head,
9136
9201
  async (clientWebSocket) => {
9137
- workerWebSocket.accept();
9138
- workerWebSocket.addEventListener("message", (event) => {
9139
- clientWebSocket.send(event.data);
9140
- });
9141
- workerWebSocket.addEventListener("error", (event) => {
9142
- logger.error(
9143
- `WebSocket error:
9144
- ${event.error?.stack || event.error?.message}`,
9145
- { error: event.error }
9146
- );
9147
- });
9148
- workerWebSocket.addEventListener("close", () => {
9149
- clientWebSocket.close();
9150
- });
9151
- clientWebSocket.on("message", (data2, isBinary) => {
9152
- workerWebSocket.send(
9153
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9154
- );
9155
- });
9156
- clientWebSocket.on("error", (error) => {
9157
- logger.error(`WebSocket error:
9158
- ${error.stack || error.message}`, {
9159
- error
9160
- });
9161
- });
9162
- clientWebSocket.on("close", () => {
9163
- workerWebSocket.close();
9164
- });
9202
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9165
9203
  nodeWebSocket.emit("connection", clientWebSocket, request);
9166
9204
  }
9167
9205
  );
@@ -9170,14 +9208,18 @@ ${error.stack || error.message}`, {
9170
9208
  }
9171
9209
 
9172
9210
  // src/index.ts
9211
+ var workersConfigsWarningShown = false;
9173
9212
  function cloudflare2(pluginConfig = {}) {
9174
9213
  let resolvedPluginConfig;
9175
9214
  let resolvedViteConfig;
9176
9215
  let miniflare;
9177
- let workersConfigsWarningShown = false;
9216
+ const additionalModulePaths = /* @__PURE__ */ new Set();
9217
+ let hasClientBuild = false;
9178
9218
  return [
9179
9219
  {
9180
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,
9181
9223
  config(userConfig, env2) {
9182
9224
  if (env2.isPreview) {
9183
9225
  return { appType: "custom" };
@@ -9220,7 +9262,7 @@ function cloudflare2(pluginConfig = {}) {
9220
9262
  }
9221
9263
  } : void 0,
9222
9264
  builder: {
9223
- async buildApp(builder) {
9265
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9224
9266
  const clientEnvironment = builder.environments.client;
9225
9267
  const defaultHtmlPath = path7.resolve(
9226
9268
  builder.config.root,
@@ -9234,7 +9276,7 @@ function cloudflare2(pluginConfig = {}) {
9234
9276
  resolvedPluginConfig.workers
9235
9277
  ).map((environmentName) => {
9236
9278
  const environment = builder.environments[environmentName];
9237
- assert9(
9279
+ assert7(
9238
9280
  environment,
9239
9281
  `${environmentName} environment not found`
9240
9282
  );
@@ -9246,10 +9288,13 @@ function cloudflare2(pluginConfig = {}) {
9246
9288
  )
9247
9289
  );
9248
9290
  }
9249
- }
9291
+ })
9250
9292
  }
9251
9293
  };
9252
9294
  },
9295
+ buildStart() {
9296
+ workersConfigsWarningShown = false;
9297
+ },
9253
9298
  configResolved(config) {
9254
9299
  resolvedViteConfig = config;
9255
9300
  },
@@ -9264,18 +9309,27 @@ function cloudflare2(pluginConfig = {}) {
9264
9309
  return;
9265
9310
  }
9266
9311
  workerConfig.main = entryChunk[0];
9312
+ workerConfig.no_bundle = true;
9313
+ workerConfig.rules = [
9314
+ { type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }
9315
+ ];
9267
9316
  const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
9268
- if (isEntryWorker && workerConfig.assets) {
9317
+ if (isEntryWorker && hasClientBuild) {
9269
9318
  const workerOutputDirectory = this.environment.config.build.outDir;
9270
9319
  const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
9271
- assert9(
9320
+ assert7(
9272
9321
  clientOutputDirectory,
9273
9322
  "Unexpected error: client output directory is undefined"
9274
9323
  );
9275
- workerConfig.assets.directory = path7.relative(
9276
- path7.resolve(resolvedViteConfig.root, workerOutputDirectory),
9277
- path7.resolve(resolvedViteConfig.root, clientOutputDirectory)
9278
- );
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;
9279
9333
  }
9280
9334
  config = workerConfig;
9281
9335
  if (workerConfig.configPath) {
@@ -9293,7 +9347,10 @@ function cloudflare2(pluginConfig = {}) {
9293
9347
  }
9294
9348
  } else if (this.environment.name === "client") {
9295
9349
  const assetsOnlyConfig = resolvedPluginConfig.config;
9296
- assetsOnlyConfig.assets.directory = ".";
9350
+ assetsOnlyConfig.assets = {
9351
+ ...assetsOnlyConfig.assets,
9352
+ directory: "."
9353
+ };
9297
9354
  const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
9298
9355
  this.emitFile({
9299
9356
  type: "asset",
@@ -9306,8 +9363,6 @@ function cloudflare2(pluginConfig = {}) {
9306
9363
  if (!config) {
9307
9364
  return;
9308
9365
  }
9309
- config.no_bundle = true;
9310
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9311
9366
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9312
9367
  config.unsafe = void 0;
9313
9368
  }
@@ -9318,6 +9373,9 @@ function cloudflare2(pluginConfig = {}) {
9318
9373
  });
9319
9374
  },
9320
9375
  writeBundle() {
9376
+ if (this.environment.name === "client") {
9377
+ hasClientBuild = true;
9378
+ }
9321
9379
  if (this.environment.name === (resolvedPluginConfig.type === "assets-only" ? "client" : resolvedPluginConfig.entryWorkerEnvironmentName)) {
9322
9380
  writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
9323
9381
  }
@@ -9334,7 +9392,7 @@ function cloudflare2(pluginConfig = {}) {
9334
9392
  }
9335
9393
  },
9336
9394
  async configureServer(viteDevServer) {
9337
- assert9(
9395
+ assert7(
9338
9396
  viteDevServer.httpServer,
9339
9397
  "Unexpected error: No Vite HTTP server"
9340
9398
  );
@@ -9342,23 +9400,16 @@ function cloudflare2(pluginConfig = {}) {
9342
9400
  getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
9343
9401
  );
9344
9402
  await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
9345
- const entryWorker = await getDevEntryWorker(
9346
- resolvedPluginConfig,
9347
- miniflare
9348
- );
9403
+ const routerWorker = await getRouterWorker(miniflare);
9349
9404
  const middleware = createMiddleware(
9350
9405
  ({ request }) => {
9351
- return entryWorker.fetch(toMiniflareRequest(request), {
9406
+ return routerWorker.fetch(toMiniflareRequest(request), {
9352
9407
  redirect: "manual"
9353
9408
  });
9354
9409
  },
9355
9410
  { alwaysCallNext: false }
9356
9411
  );
9357
- handleWebSocket(
9358
- viteDevServer.httpServer,
9359
- entryWorker.fetch,
9360
- viteDevServer.config.logger
9361
- );
9412
+ handleWebSocket(viteDevServer.httpServer, routerWorker.fetch);
9362
9413
  return () => {
9363
9414
  viteDevServer.middlewares.use((req, res, next) => {
9364
9415
  middleware(req, res, next);
@@ -9380,58 +9431,61 @@ function cloudflare2(pluginConfig = {}) {
9380
9431
  },
9381
9432
  { alwaysCallNext: false }
9382
9433
  );
9383
- handleWebSocket(
9384
- vitePreviewServer.httpServer,
9385
- miniflare2.dispatchFetch,
9386
- vitePreviewServer.config.logger
9387
- );
9388
- return () => {
9389
- vitePreviewServer.middlewares.use((req, res, next) => {
9390
- middleware(req, res, next);
9391
- });
9392
- };
9434
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9435
+ vitePreviewServer.middlewares.use((req, res, next) => {
9436
+ middleware(req, res, next);
9437
+ });
9393
9438
  }
9394
9439
  },
9395
- // Plugin to support `CompiledWasm` modules
9440
+ // Plugin to support additional modules
9396
9441
  {
9397
- name: "vite-plugin-cloudflare:modules",
9442
+ name: "vite-plugin-cloudflare:additional-modules",
9398
9443
  // We set `enforce: "pre"` so that this plugin runs before the Vite core plugins.
9399
9444
  // Otherwise the `vite:wasm-fallback` plugin prevents the `.wasm` extension being used for module imports.
9400
9445
  enforce: "pre",
9401
9446
  applyToEnvironment(environment) {
9402
9447
  return getWorkerConfig2(environment.name) !== void 0;
9403
9448
  },
9404
- async resolveId(source, importer) {
9405
- if (!source.endsWith(".wasm")) {
9449
+ async resolveId(source, importer, options) {
9450
+ const additionalModuleType = matchAdditionalModule(source);
9451
+ if (!additionalModuleType) {
9406
9452
  return;
9407
9453
  }
9408
- const resolved = await this.resolve(source, importer);
9409
- assert9(
9410
- resolved,
9411
- `Unexpected error: could not resolve Wasm module ${source}`
9454
+ const resolved = await this.resolve(
9455
+ cleanUrl(source),
9456
+ importer,
9457
+ options
9412
9458
  );
9459
+ if (!resolved) {
9460
+ throw new Error(`Import "${source}" not found. Does the file exist?`);
9461
+ }
9462
+ additionalModulePaths.add(resolved.id);
9413
9463
  return {
9414
9464
  external: true,
9415
- id: createModuleReference("CompiledWasm", resolved.id)
9465
+ id: createModuleReference(additionalModuleType, resolved.id)
9416
9466
  };
9417
9467
  },
9418
- renderChunk(code, chunk) {
9419
- const moduleRE = new RegExp(MODULE_PATTERN, "g");
9420
- 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);
9421
9475
  let magicString;
9422
- while (match = moduleRE.exec(code)) {
9476
+ for (const match of matches) {
9423
9477
  magicString ??= new MagicString(code);
9424
- const [full, moduleType, modulePath] = match;
9425
- assert9(
9478
+ const [full, _, modulePath] = match;
9479
+ assert7(
9426
9480
  modulePath,
9427
9481
  `Unexpected error: module path not found in reference ${full}.`
9428
9482
  );
9429
9483
  let source;
9430
9484
  try {
9431
- source = fs5.readFileSync(modulePath);
9485
+ source = await fsp2.readFile(modulePath);
9432
9486
  } catch (error) {
9433
9487
  throw new Error(
9434
- `Import ${modulePath} not found. Does the file exist?`
9488
+ `Import "${modulePath}" not found. Does the file exist?`
9435
9489
  );
9436
9490
  }
9437
9491
  const referenceId = this.emitFile({
@@ -9465,49 +9519,61 @@ function cloudflare2(pluginConfig = {}) {
9465
9519
  apply(_config, env2) {
9466
9520
  return !env2.isPreview;
9467
9521
  },
9468
- config() {
9469
- return {
9470
- resolve: {
9471
- alias: getNodeCompatAliases()
9472
- }
9473
- };
9474
- },
9475
- configEnvironment(environmentName) {
9476
- const workerConfig = getWorkerConfig2(environmentName);
9477
- if (isNodeCompat(workerConfig)) {
9522
+ configEnvironment(name) {
9523
+ if (isNodeCompat(getWorkerConfig2(name))) {
9478
9524
  return {
9479
- build: {
9480
- rollupOptions: {
9481
- external: getNodeCompatExternals()
9482
- }
9525
+ resolve: {
9526
+ builtins: [...nodeCompatExternals]
9527
+ },
9528
+ optimizeDeps: {
9529
+ // This is a list of dependency entry-points that should be pre-bundled.
9530
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9531
+ // ready ahead the first request to the dev server.
9532
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9533
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9534
+ // TODO: work out how to re-enable pre-bundling of these
9535
+ // include: [...getNodeCompatEntries()],
9536
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9537
+ // In this case we provide a list of all the Node.js modules, both those built-in to workerd and those that will be polyfilled.
9538
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9539
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9540
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9541
+ exclude: [
9542
+ ...builtinModules2,
9543
+ ...builtinModules2.map((m) => `node:${m}`)
9544
+ ]
9483
9545
  }
9484
9546
  };
9485
9547
  }
9486
9548
  },
9549
+ applyToEnvironment(environment) {
9550
+ return isNodeCompat(getWorkerConfig2(environment.name));
9551
+ },
9552
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9553
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9554
+ // rather than allowing the resolve hook here to alias then to polyfills.
9555
+ enforce: "pre",
9487
9556
  async resolveId(source, importer, options) {
9488
- const strippedSource = maybeStripNodeJsVirtualPrefix(source);
9489
- if (!strippedSource) {
9490
- return;
9491
- }
9492
- const workerConfig = getWorkerConfig2(this.environment.name);
9493
- if (!isNodeCompat(workerConfig)) {
9494
- return this.resolve(strippedSource, importer, options);
9557
+ const result = resolveNodeJSImport(source);
9558
+ if (!result) {
9559
+ return this.resolve(source, importer, options);
9495
9560
  }
9496
- const { unresolved, resolved } = resolveNodeJSImport(strippedSource);
9497
- if (this.environment.mode === "dev" && this.environment.depsOptimizer) {
9498
- const optimized = this.environment.depsOptimizer.registerMissingImport(
9499
- unresolved,
9500
- resolved
9501
- ).id;
9502
- return this.resolve(optimized, importer, options);
9561
+ if (this.environment.mode === "dev") {
9562
+ assert7(
9563
+ this.environment.depsOptimizer,
9564
+ "depsOptimizer is required in dev mode"
9565
+ );
9566
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9567
+ result.unresolved,
9568
+ result.resolved
9569
+ );
9570
+ return this.resolve(id, importer, options);
9503
9571
  }
9504
- return this.resolve(resolved, importer, options);
9572
+ return this.resolve(result.resolved, importer, options);
9505
9573
  },
9506
9574
  async transform(code, id) {
9507
9575
  const workerConfig = getWorkerConfig2(this.environment.name);
9508
- if (!isNodeCompat(workerConfig)) {
9509
- return;
9510
- }
9576
+ assert7(workerConfig, "Expected a worker config");
9511
9577
  const resolvedId = await this.resolve(workerConfig.main);
9512
9578
  if (id === resolvedId?.id) {
9513
9579
  return injectGlobalCode(id, code);
@@ -9516,7 +9582,7 @@ function cloudflare2(pluginConfig = {}) {
9516
9582
  }
9517
9583
  ];
9518
9584
  function getWorkerConfig2(environmentName) {
9519
- assert9(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9585
+ assert7(resolvedPluginConfig, "Expected resolvedPluginConfig to be defined");
9520
9586
  return resolvedPluginConfig.type !== "assets-only" ? resolvedPluginConfig.workers[environmentName] : void 0;
9521
9587
  }
9522
9588
  }
@@ -9531,9 +9597,6 @@ function getDotDevDotVarsContent(configPath, cloudflareEnv) {
9531
9597
  }
9532
9598
  return null;
9533
9599
  }
9534
- function createModuleReference(type, id) {
9535
- return `__CLOUDFLARE_MODULE__${type}__${id}__`;
9536
- }
9537
9600
  export {
9538
9601
  cloudflare2 as cloudflare
9539
9602
  };