@cloudflare/vite-plugin 0.0.0-c48dce61d → 0.0.0-c4fa349da

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
@@ -1074,982 +1074,251 @@ import { Miniflare } from "miniflare";
1074
1074
  import * as vite6 from "vite";
1075
1075
 
1076
1076
  // src/cloudflare-environment.ts
1077
- import assert from "node:assert";
1077
+ import assert3 from "node:assert";
1078
1078
  import * as vite2 from "vite";
1079
1079
 
1080
- // src/constants.ts
1081
- var ROUTER_WORKER_NAME = "__router-worker__";
1082
- var ASSET_WORKER_NAME = "__asset-worker__";
1083
- var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1084
- var MODULE_TYPES = ["CompiledWasm"];
1085
-
1086
- // src/shared.ts
1087
- var UNKNOWN_HOST = "http://localhost";
1088
- var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1089
- var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1090
-
1091
- // src/utils.ts
1092
- import * as path from "node:path";
1093
- import { Request as MiniflareRequest } from "miniflare";
1094
- import "vite";
1095
- function getOutputDirectory(userConfig, environmentName) {
1096
- const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
1097
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
1098
- }
1099
- function toMiniflareRequest(request) {
1100
- return new MiniflareRequest(request.url, {
1101
- method: request.method,
1102
- headers: [["accept-encoding", "identity"], ...request.headers],
1103
- body: request.body,
1104
- duplex: "half"
1105
- });
1106
- }
1107
- function nodeHeadersToWebHeaders(nodeHeaders) {
1108
- const headers = new Headers();
1109
- for (const [key, value] of Object.entries(nodeHeaders)) {
1110
- if (typeof value === "string") {
1111
- headers.append(key, value);
1112
- } else if (Array.isArray(value)) {
1113
- for (const item of value) {
1114
- headers.append(key, item);
1115
- }
1116
- }
1117
- }
1118
- return headers;
1119
- }
1080
+ // src/node-js-compat.ts
1081
+ import assert2 from "node:assert";
1082
+ import { cloudflare } from "@cloudflare/unenv-preset";
1083
+ import { getNodeCompat } from "miniflare";
1120
1084
 
1121
- // src/cloudflare-environment.ts
1122
- var webSocketUndefinedError = "The WebSocket is undefined";
1123
- function createHotChannel(webSocketContainer) {
1124
- const listenersMap = /* @__PURE__ */ new Map();
1125
- const client = {
1126
- send(payload) {
1127
- const webSocket = webSocketContainer.webSocket;
1128
- assert(webSocket, webSocketUndefinedError);
1129
- webSocket.send(JSON.stringify(payload));
1085
+ // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1086
+ 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];
1087
+ 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];
1088
+ 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";
1089
+ 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";
1090
+ var reservedWords = {
1091
+ 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",
1092
+ 5: "class enum extends super const export import",
1093
+ 6: "enum",
1094
+ strict: "implements interface let package private protected public static yield",
1095
+ strictBind: "eval arguments"
1096
+ };
1097
+ 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";
1098
+ var keywords$1 = {
1099
+ 5: ecma5AndLessKeywords,
1100
+ "5module": ecma5AndLessKeywords + " export import",
1101
+ 6: ecma5AndLessKeywords + " const class extends export import super"
1102
+ };
1103
+ var keywordRelationalOperator = /^in(stanceof)?$/;
1104
+ var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1105
+ var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1106
+ function isInAstralSet(code, set) {
1107
+ var pos = 65536;
1108
+ for (var i = 0; i < set.length; i += 2) {
1109
+ pos += set[i];
1110
+ if (pos > code) {
1111
+ return false;
1130
1112
  }
1131
- };
1132
- function onMessage(event) {
1133
- const payload = JSON.parse(event.data.toString());
1134
- const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
1135
- for (const listener of listeners) {
1136
- listener(payload.data, client);
1113
+ pos += set[i + 1];
1114
+ if (pos >= code) {
1115
+ return true;
1137
1116
  }
1138
1117
  }
1139
- return {
1140
- send(payload) {
1141
- const webSocket = webSocketContainer.webSocket;
1142
- assert(webSocket, webSocketUndefinedError);
1143
- webSocket.send(JSON.stringify(payload));
1144
- },
1145
- on(event, listener) {
1146
- const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
1147
- listeners.add(listener);
1148
- listenersMap.set(event, listeners);
1149
- },
1150
- off(event, listener) {
1151
- listenersMap.get(event)?.delete(listener);
1152
- },
1153
- listen() {
1154
- const webSocket = webSocketContainer.webSocket;
1155
- assert(webSocket, webSocketUndefinedError);
1156
- webSocket.addEventListener("message", onMessage);
1157
- },
1158
- close() {
1159
- const webSocket = webSocketContainer.webSocket;
1160
- assert(webSocket, webSocketUndefinedError);
1161
- webSocket.removeEventListener("message", onMessage);
1162
- }
1163
- };
1118
+ return false;
1164
1119
  }
1165
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
1166
- #webSocketContainer;
1167
- #worker;
1168
- constructor(name2, config) {
1169
- const webSocketContainer = {};
1170
- super(name2, config, {
1171
- hot: true,
1172
- transport: createHotChannel(webSocketContainer)
1173
- });
1174
- this.#webSocketContainer = webSocketContainer;
1120
+ function isIdentifierStart(code, astral) {
1121
+ if (code < 65) {
1122
+ return code === 36;
1175
1123
  }
1176
- async initRunner(worker) {
1177
- this.#worker = worker;
1178
- const response = await this.#worker.fetch(
1179
- new URL(INIT_PATH, UNKNOWN_HOST),
1180
- {
1181
- headers: {
1182
- upgrade: "websocket"
1183
- }
1184
- }
1185
- );
1186
- assert(
1187
- response.ok,
1188
- `Failed to initialize module runner, error: ${await response.text()}`
1189
- );
1190
- const webSocket = response.webSocket;
1191
- assert(webSocket, "Failed to establish WebSocket");
1192
- webSocket.accept();
1193
- this.#webSocketContainer.webSocket = webSocket;
1124
+ if (code < 91) {
1125
+ return true;
1194
1126
  }
1195
- };
1196
- var cloudflareBuiltInModules = [
1197
- "cloudflare:email",
1198
- "cloudflare:sockets",
1199
- "cloudflare:workers",
1200
- "cloudflare:workflows"
1201
- ];
1202
- var defaultConditions = ["workerd", "module", "browser"];
1203
- function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1204
- return {
1205
- resolve: {
1206
- // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
1207
- // dependencies as not external
1208
- noExternal: true,
1209
- // We want to use `workerd` package exports if available (e.g. for postgres).
1210
- conditions: [...defaultConditions, "development|production"],
1211
- // The Cloudflare ones are proper builtins in the environment
1212
- builtins: [...cloudflareBuiltInModules]
1213
- },
1214
- dev: {
1215
- createEnvironment(name2, config) {
1216
- return new CloudflareDevEnvironment(name2, config);
1217
- }
1218
- },
1219
- build: {
1220
- createEnvironment(name2, config) {
1221
- return new vite2.BuildEnvironment(name2, config);
1222
- },
1223
- target: "es2022",
1224
- // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1225
- emitAssets: true,
1226
- outDir: getOutputDirectory(userConfig, environmentName),
1227
- copyPublicDir: false,
1228
- ssr: true,
1229
- rollupOptions: {
1230
- // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
1231
- // so the input value here serves both as the build input as well as the starting point for
1232
- // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
1233
- // optimizeDeps.entries in the dev config)
1234
- input: workerConfig.main
1235
- }
1236
- },
1237
- optimizeDeps: {
1238
- // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1239
- noDiscovery: false,
1240
- entries: workerConfig.main,
1241
- exclude: [...cloudflareBuiltInModules],
1242
- esbuildOptions: {
1243
- platform: "neutral",
1244
- conditions: [...defaultConditions, "development"],
1245
- resolveExtensions: [
1246
- ".mjs",
1247
- ".js",
1248
- ".mts",
1249
- ".ts",
1250
- ".jsx",
1251
- ".tsx",
1252
- ".json",
1253
- ".cjs",
1254
- ".cts",
1255
- ".ctx"
1256
- ]
1257
- }
1258
- },
1259
- keepProcessEnv: false
1260
- };
1127
+ if (code < 97) {
1128
+ return code === 95;
1129
+ }
1130
+ if (code < 123) {
1131
+ return true;
1132
+ }
1133
+ if (code <= 65535) {
1134
+ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1135
+ }
1136
+ if (astral === false) {
1137
+ return false;
1138
+ }
1139
+ return isInAstralSet(code, astralIdentifierStartCodes);
1261
1140
  }
1262
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
1263
- if (resolvedPluginConfig.type === "assets-only") {
1264
- return;
1141
+ function isIdentifierChar(code, astral) {
1142
+ if (code < 48) {
1143
+ return code === 36;
1265
1144
  }
1266
- return Promise.all(
1267
- Object.entries(resolvedPluginConfig.workers).map(
1268
- async ([environmentName, workerConfig]) => {
1269
- const worker = await miniflare.getWorker(workerConfig.name);
1270
- return viteDevServer.environments[environmentName].initRunner(worker);
1271
- }
1272
- )
1273
- );
1145
+ if (code < 58) {
1146
+ return true;
1147
+ }
1148
+ if (code < 65) {
1149
+ return false;
1150
+ }
1151
+ if (code < 91) {
1152
+ return true;
1153
+ }
1154
+ if (code < 97) {
1155
+ return code === 95;
1156
+ }
1157
+ if (code < 123) {
1158
+ return true;
1159
+ }
1160
+ if (code <= 65535) {
1161
+ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1162
+ }
1163
+ if (astral === false) {
1164
+ return false;
1165
+ }
1166
+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1274
1167
  }
1275
-
1276
- // src/deploy-config.ts
1277
- import assert2 from "node:assert";
1278
- import * as fs from "node:fs";
1279
- import * as path2 from "node:path";
1280
- import "vite";
1281
- function getDeployConfigPath(root) {
1282
- return path2.resolve(root, ".wrangler", "deploy", "config.json");
1168
+ var TokenType = function TokenType2(label, conf) {
1169
+ if (conf === void 0) conf = {};
1170
+ this.label = label;
1171
+ this.keyword = conf.keyword;
1172
+ this.beforeExpr = !!conf.beforeExpr;
1173
+ this.startsExpr = !!conf.startsExpr;
1174
+ this.isLoop = !!conf.isLoop;
1175
+ this.isAssign = !!conf.isAssign;
1176
+ this.prefix = !!conf.prefix;
1177
+ this.postfix = !!conf.postfix;
1178
+ this.binop = conf.binop || null;
1179
+ this.updateContext = null;
1180
+ };
1181
+ function binop(name2, prec) {
1182
+ return new TokenType(name2, { beforeExpr: true, binop: prec });
1283
1183
  }
1284
- function getWorkerConfigPaths(root) {
1285
- const deployConfigPath = getDeployConfigPath(root);
1286
- const deployConfig = JSON.parse(
1287
- fs.readFileSync(deployConfigPath, "utf-8")
1288
- );
1289
- return [
1290
- { configPath: deployConfig.configPath },
1291
- ...deployConfig.auxiliaryWorkers
1292
- ].map(
1293
- ({ configPath }) => path2.resolve(path2.dirname(deployConfigPath), configPath)
1294
- );
1184
+ var beforeExpr = { beforeExpr: true };
1185
+ var startsExpr = { startsExpr: true };
1186
+ var keywords = {};
1187
+ function kw(name2, options) {
1188
+ if (options === void 0) options = {};
1189
+ options.keyword = name2;
1190
+ return keywords[name2] = new TokenType(name2, options);
1295
1191
  }
1296
- function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
1297
- return path2.relative(
1298
- deployConfigDirectory,
1299
- path2.resolve(root, outputDirectory, "wrangler.json")
1300
- );
1192
+ var types$1 = {
1193
+ num: new TokenType("num", startsExpr),
1194
+ regexp: new TokenType("regexp", startsExpr),
1195
+ string: new TokenType("string", startsExpr),
1196
+ name: new TokenType("name", startsExpr),
1197
+ privateId: new TokenType("privateId", startsExpr),
1198
+ eof: new TokenType("eof"),
1199
+ // Punctuation token types.
1200
+ bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
1201
+ bracketR: new TokenType("]"),
1202
+ braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
1203
+ braceR: new TokenType("}"),
1204
+ parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
1205
+ parenR: new TokenType(")"),
1206
+ comma: new TokenType(",", beforeExpr),
1207
+ semi: new TokenType(";", beforeExpr),
1208
+ colon: new TokenType(":", beforeExpr),
1209
+ dot: new TokenType("."),
1210
+ question: new TokenType("?", beforeExpr),
1211
+ questionDot: new TokenType("?."),
1212
+ arrow: new TokenType("=>", beforeExpr),
1213
+ template: new TokenType("template"),
1214
+ invalidTemplate: new TokenType("invalidTemplate"),
1215
+ ellipsis: new TokenType("...", beforeExpr),
1216
+ backQuote: new TokenType("`", startsExpr),
1217
+ dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
1218
+ // Operators. These carry several kinds of properties to help the
1219
+ // parser use them properly (the presence of these properties is
1220
+ // what categorizes them as operators).
1221
+ //
1222
+ // `binop`, when present, specifies that this operator is a binary
1223
+ // operator, and will refer to its precedence.
1224
+ //
1225
+ // `prefix` and `postfix` mark the operator as a prefix or postfix
1226
+ // unary operator.
1227
+ //
1228
+ // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
1229
+ // binary operators with a very low precedence, that should result
1230
+ // in AssignmentExpression nodes.
1231
+ eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
1232
+ assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
1233
+ incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
1234
+ prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
1235
+ logicalOR: binop("||", 1),
1236
+ logicalAND: binop("&&", 2),
1237
+ bitwiseOR: binop("|", 3),
1238
+ bitwiseXOR: binop("^", 4),
1239
+ bitwiseAND: binop("&", 5),
1240
+ equality: binop("==/!=/===/!==", 6),
1241
+ relational: binop("</>/<=/>=", 7),
1242
+ bitShift: binop("<</>>/>>>", 8),
1243
+ plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
1244
+ modulo: binop("%", 10),
1245
+ star: binop("*", 10),
1246
+ slash: binop("/", 10),
1247
+ starstar: new TokenType("**", { beforeExpr: true }),
1248
+ coalesce: binop("??", 1),
1249
+ // Keyword token types.
1250
+ _break: kw("break"),
1251
+ _case: kw("case", beforeExpr),
1252
+ _catch: kw("catch"),
1253
+ _continue: kw("continue"),
1254
+ _debugger: kw("debugger"),
1255
+ _default: kw("default", beforeExpr),
1256
+ _do: kw("do", { isLoop: true, beforeExpr: true }),
1257
+ _else: kw("else", beforeExpr),
1258
+ _finally: kw("finally"),
1259
+ _for: kw("for", { isLoop: true }),
1260
+ _function: kw("function", startsExpr),
1261
+ _if: kw("if"),
1262
+ _return: kw("return", beforeExpr),
1263
+ _switch: kw("switch"),
1264
+ _throw: kw("throw", beforeExpr),
1265
+ _try: kw("try"),
1266
+ _var: kw("var"),
1267
+ _const: kw("const"),
1268
+ _while: kw("while", { isLoop: true }),
1269
+ _with: kw("with"),
1270
+ _new: kw("new", { beforeExpr: true, startsExpr: true }),
1271
+ _this: kw("this", startsExpr),
1272
+ _super: kw("super", startsExpr),
1273
+ _class: kw("class", startsExpr),
1274
+ _extends: kw("extends", beforeExpr),
1275
+ _export: kw("export"),
1276
+ _import: kw("import", startsExpr),
1277
+ _null: kw("null", startsExpr),
1278
+ _true: kw("true", startsExpr),
1279
+ _false: kw("false", startsExpr),
1280
+ _in: kw("in", { beforeExpr: true, binop: 7 }),
1281
+ _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }),
1282
+ _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
1283
+ _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }),
1284
+ _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true })
1285
+ };
1286
+ var lineBreak = /\r\n?|\n|\u2028|\u2029/;
1287
+ var lineBreakG = new RegExp(lineBreak.source, "g");
1288
+ function isNewLine(code) {
1289
+ return code === 10 || code === 13 || code === 8232 || code === 8233;
1301
1290
  }
1302
- function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1303
- const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
1304
- const deployConfigDirectory = path2.dirname(deployConfigPath);
1305
- fs.mkdirSync(deployConfigDirectory, { recursive: true });
1306
- if (resolvedPluginConfig.type === "assets-only") {
1307
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
1308
- assert2(
1309
- clientOutputDirectory,
1310
- "Unexpected error: client environment output directory is undefined"
1311
- );
1312
- const deployConfig = {
1313
- configPath: getRelativePathToWorkerConfig(
1314
- deployConfigDirectory,
1315
- resolvedViteConfig.root,
1316
- clientOutputDirectory
1317
- ),
1318
- auxiliaryWorkers: []
1319
- };
1320
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1321
- } else {
1322
- let entryWorkerConfigPath;
1323
- const auxiliaryWorkers = [];
1324
- for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
1325
- const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
1326
- assert2(
1327
- outputDirectory,
1328
- `Unexpected error: ${environmentName} environment output directory is undefined`
1329
- );
1330
- const configPath = getRelativePathToWorkerConfig(
1331
- deployConfigDirectory,
1332
- resolvedViteConfig.root,
1333
- outputDirectory
1334
- );
1335
- if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
1336
- entryWorkerConfigPath = configPath;
1337
- } else {
1338
- auxiliaryWorkers.push({ configPath });
1339
- }
1291
+ function nextLineBreak(code, from, end) {
1292
+ if (end === void 0) end = code.length;
1293
+ for (var i = from; i < end; i++) {
1294
+ var next = code.charCodeAt(i);
1295
+ if (isNewLine(next)) {
1296
+ return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1;
1340
1297
  }
1341
- assert2(
1342
- entryWorkerConfigPath,
1343
- `Unexpected error: entryWorkerConfigPath is undefined`
1344
- );
1345
- const deployConfig = {
1346
- configPath: entryWorkerConfigPath,
1347
- auxiliaryWorkers
1348
- };
1349
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1350
1298
  }
1299
+ return -1;
1351
1300
  }
1352
-
1353
- // src/dev.ts
1354
- import assert3 from "node:assert";
1355
- function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1356
- const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1357
- assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
1358
- return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
1301
+ var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
1302
+ var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
1303
+ var ref = Object.prototype;
1304
+ var hasOwnProperty = ref.hasOwnProperty;
1305
+ var toString2 = ref.toString;
1306
+ var hasOwn = Object.hasOwn || function(obj, propName) {
1307
+ return hasOwnProperty.call(obj, propName);
1308
+ };
1309
+ var isArray = Array.isArray || function(obj) {
1310
+ return toString2.call(obj) === "[object Array]";
1311
+ };
1312
+ var regexpCache = /* @__PURE__ */ Object.create(null);
1313
+ function wordsRegexp(words) {
1314
+ return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));
1359
1315
  }
1360
-
1361
- // src/miniflare-options.ts
1362
- import assert4 from "node:assert";
1363
- import * as fs2 from "node:fs";
1364
- import * as fsp from "node:fs/promises";
1365
- import * as path3 from "node:path";
1366
- import { fileURLToPath } from "node:url";
1367
- import {
1368
- kCurrentWorker,
1369
- Log,
1370
- LogLevel,
1371
- Response as MiniflareResponse
1372
- } from "miniflare";
1373
- import { globSync } from "tinyglobby";
1374
- import "vite";
1375
- import {
1376
- unstable_getMiniflareWorkerOptions,
1377
- unstable_readConfig
1378
- } from "wrangler";
1379
- function getPersistence(root, persistState) {
1380
- if (persistState === false) {
1381
- return {};
1316
+ function codePointToString(code) {
1317
+ if (code <= 65535) {
1318
+ return String.fromCharCode(code);
1382
1319
  }
1383
- const defaultPersistPath = ".wrangler/state";
1384
- const persistPath = path3.resolve(
1385
- root,
1386
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1387
- "v3"
1388
- );
1389
- return {
1390
- cachePersist: path3.join(persistPath, "cache"),
1391
- d1Persist: path3.join(persistPath, "d1"),
1392
- durableObjectsPersist: path3.join(persistPath, "do"),
1393
- kvPersist: path3.join(persistPath, "kv"),
1394
- r2Persist: path3.join(persistPath, "r2"),
1395
- workflowsPersist: path3.join(persistPath, "workflows")
1396
- };
1397
- }
1398
- function missingWorkerErrorMessage(workerName) {
1399
- return `${workerName} does not match a worker name.`;
1400
- }
1401
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1402
- const workerToWorkerEntrypointNamesMap = new Map(
1403
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1404
- );
1405
- for (const worker of workers) {
1406
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1407
- if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1408
- const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1409
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1410
- assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1411
- entrypointNames.add(value.entrypoint);
1412
- }
1413
- }
1414
- }
1415
- return workerToWorkerEntrypointNamesMap;
1416
- }
1417
- function getWorkerToDurableObjectClassNamesMap(workers) {
1418
- const workerToDurableObjectClassNamesMap = new Map(
1419
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1420
- );
1421
- for (const worker of workers) {
1422
- for (const value of Object.values(worker.durableObjects ?? {})) {
1423
- if (typeof value === "string") {
1424
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1425
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1426
- classNames.add(value);
1427
- } else if (typeof value === "object") {
1428
- if (value.scriptName) {
1429
- const classNames = workerToDurableObjectClassNamesMap.get(
1430
- value.scriptName
1431
- );
1432
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1433
- classNames.add(value.className);
1434
- } else {
1435
- const classNames = workerToDurableObjectClassNamesMap.get(
1436
- worker.name
1437
- );
1438
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1439
- classNames.add(value.className);
1440
- }
1441
- }
1442
- }
1443
- }
1444
- return workerToDurableObjectClassNamesMap;
1445
- }
1446
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1447
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1448
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1449
- );
1450
- for (const worker of workers) {
1451
- for (const value of Object.values(worker.workflows ?? {})) {
1452
- if (value.scriptName) {
1453
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1454
- value.scriptName
1455
- );
1456
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1457
- classNames.add(value.className);
1458
- } else {
1459
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1460
- worker.name
1461
- );
1462
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1463
- classNames.add(value.className);
1464
- }
1465
- }
1466
- }
1467
- return workerToWorkflowEntrypointClassNamesMap;
1468
- }
1469
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1470
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1471
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1472
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1473
- var RUNNER_PATH = "./runner-worker/index.js";
1474
- function getEntryWorkerConfig(resolvedPluginConfig) {
1475
- if (resolvedPluginConfig.type === "assets-only") {
1476
- return;
1477
- }
1478
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1479
- }
1480
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1481
- const resolvedViteConfig = viteDevServer.config;
1482
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1483
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1484
- const assetWorkers = [
1485
- {
1486
- name: ROUTER_WORKER_NAME,
1487
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1488
- modulesRoot: miniflareModulesRoot,
1489
- modules: [
1490
- {
1491
- type: "ESModule",
1492
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1493
- contents: fs2.readFileSync(
1494
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1495
- )
1496
- }
1497
- ],
1498
- bindings: {
1499
- CONFIG: {
1500
- has_user_worker: resolvedPluginConfig.type === "workers"
1501
- }
1502
- },
1503
- serviceBindings: {
1504
- ASSET_WORKER: ASSET_WORKER_NAME,
1505
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1506
- }
1507
- },
1508
- {
1509
- name: ASSET_WORKER_NAME,
1510
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1511
- modulesRoot: miniflareModulesRoot,
1512
- modules: [
1513
- {
1514
- type: "ESModule",
1515
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1516
- contents: fs2.readFileSync(
1517
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1518
- )
1519
- }
1520
- ],
1521
- bindings: {
1522
- CONFIG: {
1523
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1524
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1525
- }
1526
- },
1527
- serviceBindings: {
1528
- __VITE_ASSET_EXISTS__: async (request) => {
1529
- const { pathname } = new URL(request.url);
1530
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1531
- let exists;
1532
- try {
1533
- exists = fs2.statSync(filePath).isFile();
1534
- } catch (error) {
1535
- exists = false;
1536
- }
1537
- return MiniflareResponse.json(exists);
1538
- },
1539
- __VITE_FETCH_ASSET__: async (request) => {
1540
- const { pathname } = new URL(request.url);
1541
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1542
- try {
1543
- let html = await fsp.readFile(filePath, "utf-8");
1544
- html = await viteDevServer.transformIndexHtml(pathname, html);
1545
- return new MiniflareResponse(html, {
1546
- headers: { "Content-Type": "text/html" }
1547
- });
1548
- } catch (error) {
1549
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1550
- }
1551
- }
1552
- }
1553
- }
1554
- ];
1555
- const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1556
- ([environmentName, workerConfig]) => {
1557
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1558
- {
1559
- ...workerConfig,
1560
- assets: void 0
1561
- },
1562
- resolvedPluginConfig.cloudflareEnv
1563
- );
1564
- const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
1565
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1566
- return {
1567
- externalWorkers: externalWorkers2,
1568
- worker: {
1569
- ...workerOptions,
1570
- name: workerOptions.name ?? workerConfig.name,
1571
- modulesRoot: miniflareModulesRoot,
1572
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1573
- bindings: {
1574
- ...workerOptions.bindings,
1575
- __VITE_ROOT__: resolvedViteConfig.root,
1576
- __VITE_ENTRY_PATH__: workerConfig.main
1577
- },
1578
- serviceBindings: {
1579
- ...workerOptions.serviceBindings,
1580
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1581
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1582
- } : {},
1583
- __VITE_INVOKE_MODULE__: async (request) => {
1584
- const payload = await request.json();
1585
- const invokePayloadData = payload.data;
1586
- assert4(
1587
- invokePayloadData.name === "fetchModule",
1588
- `Invalid invoke event: ${invokePayloadData.name}`
1589
- );
1590
- const [moduleId] = invokePayloadData.data;
1591
- const moduleRE = new RegExp(MODULE_PATTERN);
1592
- const shouldExternalize = (
1593
- // Worker modules (CompiledWasm, Text, Data)
1594
- moduleRE.test(moduleId)
1595
- );
1596
- if (shouldExternalize) {
1597
- const result2 = {
1598
- externalize: moduleId,
1599
- type: "module"
1600
- };
1601
- return MiniflareResponse.json({ result: result2 });
1602
- }
1603
- const devEnvironment = viteDevServer.environments[environmentName];
1604
- const result = await devEnvironment.hot.handleInvoke(payload);
1605
- return MiniflareResponse.json(result);
1606
- }
1607
- }
1608
- }
1609
- };
1610
- }
1611
- ) : [];
1612
- const userWorkers = workersFromConfig.map((options) => options.worker);
1613
- const externalWorkers = workersFromConfig.flatMap(
1614
- (options) => options.externalWorkers
1615
- );
1616
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1617
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1618
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1619
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1620
- return {
1621
- log: logger,
1622
- handleRuntimeStdio(stdout, stderr) {
1623
- const decoder = new TextDecoder();
1624
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1625
- stderr.forEach(
1626
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1627
- );
1628
- },
1629
- ...getPersistence(
1630
- resolvedViteConfig.root,
1631
- resolvedPluginConfig.persistState
1632
- ),
1633
- workers: [
1634
- ...assetWorkers,
1635
- ...externalWorkers,
1636
- ...userWorkers.map((workerOptions) => {
1637
- const wrappers = [
1638
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1639
- `export default createWorkerEntrypointWrapper('default');`
1640
- ];
1641
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1642
- workerOptions.name
1643
- );
1644
- assert4(
1645
- workerEntrypointNames,
1646
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1647
- );
1648
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1649
- wrappers.push(
1650
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1651
- );
1652
- }
1653
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1654
- workerOptions.name
1655
- );
1656
- assert4(
1657
- durableObjectClassNames,
1658
- `DurableObject class names not found for worker ${workerOptions.name}`
1659
- );
1660
- for (const className of [...durableObjectClassNames].sort()) {
1661
- wrappers.push(
1662
- `export const ${className} = createDurableObjectWrapper('${className}');`
1663
- );
1664
- }
1665
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1666
- assert4(
1667
- workflowEntrypointClassNames,
1668
- `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
1669
- );
1670
- for (const className of [...workflowEntrypointClassNames].sort()) {
1671
- wrappers.push(
1672
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1673
- );
1674
- }
1675
- return {
1676
- ...workerOptions,
1677
- modules: [
1678
- {
1679
- type: "ESModule",
1680
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1681
- contents: wrappers.join("\n")
1682
- },
1683
- {
1684
- type: "ESModule",
1685
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1686
- contents: fs2.readFileSync(
1687
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1688
- )
1689
- }
1690
- ],
1691
- unsafeUseModuleFallbackService: true
1692
- };
1693
- })
1694
- ],
1695
- unsafeModuleFallbackService(request) {
1696
- const url = new URL(request.url);
1697
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1698
- assert4(
1699
- rawSpecifier,
1700
- `Unexpected error: no specifier in request to module fallback service.`
1701
- );
1702
- const moduleRE = new RegExp(MODULE_PATTERN);
1703
- const match = moduleRE.exec(rawSpecifier);
1704
- assert4(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
1705
- const [full, moduleType, modulePath] = match;
1706
- assert4(
1707
- modulePath,
1708
- `Unexpected error: module path not found in reference: ${full}.`
1709
- );
1710
- let source;
1711
- try {
1712
- source = fs2.readFileSync(modulePath);
1713
- } catch (error) {
1714
- throw new Error(
1715
- `Import "${modulePath}" not found. Does the file exist?`
1716
- );
1717
- }
1718
- return MiniflareResponse.json({
1719
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1720
- wasm: Array.from(source)
1721
- });
1722
- }
1723
- };
1724
- }
1725
- function getPreviewModules(main, modulesRules) {
1726
- assert4(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
1727
- const rootPath = path3.dirname(main);
1728
- const entryPath = path3.basename(main);
1729
- return {
1730
- rootPath,
1731
- modules: [
1732
- {
1733
- type: "ESModule",
1734
- path: entryPath
1735
- },
1736
- ...modulesRules.flatMap(
1737
- ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
1738
- type,
1739
- path: path8
1740
- }))
1741
- )
1742
- ]
1743
- };
1744
- }
1745
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1746
- const resolvedViteConfig = vitePreviewServer.config;
1747
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1748
- const workerConfigs = configPaths.map(
1749
- (configPath) => unstable_readConfig({ config: configPath })
1750
- );
1751
- const workers = workerConfigs.flatMap((config) => {
1752
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1753
- const { externalWorkers } = miniflareWorkerOptions;
1754
- const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1755
- return [
1756
- {
1757
- ...workerOptions,
1758
- name: workerOptions.name ?? config.name,
1759
- ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
1760
- },
1761
- ...externalWorkers
1762
- ];
1763
- });
1764
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1765
- return {
1766
- log: logger,
1767
- handleRuntimeStdio(stdout, stderr) {
1768
- const decoder = new TextDecoder();
1769
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1770
- stderr.forEach(
1771
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1772
- );
1773
- },
1774
- ...getPersistence(resolvedViteConfig.root, persistState),
1775
- workers
1776
- };
1777
- }
1778
- var ViteMiniflareLogger = class extends Log {
1779
- logger;
1780
- constructor(config) {
1781
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1782
- this.logger = config.logger;
1783
- }
1784
- logWithLevel(level, message) {
1785
- if (/^Ready on http/.test(message)) {
1786
- level = LogLevel.DEBUG;
1787
- }
1788
- switch (level) {
1789
- case LogLevel.ERROR:
1790
- return this.logger.error(message);
1791
- case LogLevel.WARN:
1792
- return this.logger.warn(message);
1793
- case LogLevel.INFO:
1794
- return this.logger.info(message);
1795
- }
1796
- }
1797
- };
1798
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1799
- switch (level) {
1800
- case "error":
1801
- return LogLevel.ERROR;
1802
- case "warn":
1803
- return LogLevel.WARN;
1804
- case "info":
1805
- return LogLevel.INFO;
1806
- case "silent":
1807
- return LogLevel.NONE;
1808
- }
1809
- }
1810
-
1811
- // src/node-js-compat.ts
1812
- import assert6 from "node:assert";
1813
- import { cloudflare } from "@cloudflare/unenv-preset";
1814
- import { getNodeCompat } from "miniflare";
1815
-
1816
- // ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
1817
- 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];
1818
- 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];
1819
- 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";
1820
- 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";
1821
- var reservedWords = {
1822
- 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",
1823
- 5: "class enum extends super const export import",
1824
- 6: "enum",
1825
- strict: "implements interface let package private protected public static yield",
1826
- strictBind: "eval arguments"
1827
- };
1828
- 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";
1829
- var keywords$1 = {
1830
- 5: ecma5AndLessKeywords,
1831
- "5module": ecma5AndLessKeywords + " export import",
1832
- 6: ecma5AndLessKeywords + " const class extends export import super"
1833
- };
1834
- var keywordRelationalOperator = /^in(stanceof)?$/;
1835
- var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1836
- var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1837
- function isInAstralSet(code, set) {
1838
- var pos = 65536;
1839
- for (var i = 0; i < set.length; i += 2) {
1840
- pos += set[i];
1841
- if (pos > code) {
1842
- return false;
1843
- }
1844
- pos += set[i + 1];
1845
- if (pos >= code) {
1846
- return true;
1847
- }
1848
- }
1849
- return false;
1850
- }
1851
- function isIdentifierStart(code, astral) {
1852
- if (code < 65) {
1853
- return code === 36;
1854
- }
1855
- if (code < 91) {
1856
- return true;
1857
- }
1858
- if (code < 97) {
1859
- return code === 95;
1860
- }
1861
- if (code < 123) {
1862
- return true;
1863
- }
1864
- if (code <= 65535) {
1865
- return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
1866
- }
1867
- if (astral === false) {
1868
- return false;
1869
- }
1870
- return isInAstralSet(code, astralIdentifierStartCodes);
1871
- }
1872
- function isIdentifierChar(code, astral) {
1873
- if (code < 48) {
1874
- return code === 36;
1875
- }
1876
- if (code < 58) {
1877
- return true;
1878
- }
1879
- if (code < 65) {
1880
- return false;
1881
- }
1882
- if (code < 91) {
1883
- return true;
1884
- }
1885
- if (code < 97) {
1886
- return code === 95;
1887
- }
1888
- if (code < 123) {
1889
- return true;
1890
- }
1891
- if (code <= 65535) {
1892
- return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
1893
- }
1894
- if (astral === false) {
1895
- return false;
1896
- }
1897
- return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1898
- }
1899
- var TokenType = function TokenType2(label, conf) {
1900
- if (conf === void 0) conf = {};
1901
- this.label = label;
1902
- this.keyword = conf.keyword;
1903
- this.beforeExpr = !!conf.beforeExpr;
1904
- this.startsExpr = !!conf.startsExpr;
1905
- this.isLoop = !!conf.isLoop;
1906
- this.isAssign = !!conf.isAssign;
1907
- this.prefix = !!conf.prefix;
1908
- this.postfix = !!conf.postfix;
1909
- this.binop = conf.binop || null;
1910
- this.updateContext = null;
1911
- };
1912
- function binop(name2, prec) {
1913
- return new TokenType(name2, { beforeExpr: true, binop: prec });
1914
- }
1915
- var beforeExpr = { beforeExpr: true };
1916
- var startsExpr = { startsExpr: true };
1917
- var keywords = {};
1918
- function kw(name2, options) {
1919
- if (options === void 0) options = {};
1920
- options.keyword = name2;
1921
- return keywords[name2] = new TokenType(name2, options);
1922
- }
1923
- var types$1 = {
1924
- num: new TokenType("num", startsExpr),
1925
- regexp: new TokenType("regexp", startsExpr),
1926
- string: new TokenType("string", startsExpr),
1927
- name: new TokenType("name", startsExpr),
1928
- privateId: new TokenType("privateId", startsExpr),
1929
- eof: new TokenType("eof"),
1930
- // Punctuation token types.
1931
- bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
1932
- bracketR: new TokenType("]"),
1933
- braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
1934
- braceR: new TokenType("}"),
1935
- parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
1936
- parenR: new TokenType(")"),
1937
- comma: new TokenType(",", beforeExpr),
1938
- semi: new TokenType(";", beforeExpr),
1939
- colon: new TokenType(":", beforeExpr),
1940
- dot: new TokenType("."),
1941
- question: new TokenType("?", beforeExpr),
1942
- questionDot: new TokenType("?."),
1943
- arrow: new TokenType("=>", beforeExpr),
1944
- template: new TokenType("template"),
1945
- invalidTemplate: new TokenType("invalidTemplate"),
1946
- ellipsis: new TokenType("...", beforeExpr),
1947
- backQuote: new TokenType("`", startsExpr),
1948
- dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
1949
- // Operators. These carry several kinds of properties to help the
1950
- // parser use them properly (the presence of these properties is
1951
- // what categorizes them as operators).
1952
- //
1953
- // `binop`, when present, specifies that this operator is a binary
1954
- // operator, and will refer to its precedence.
1955
- //
1956
- // `prefix` and `postfix` mark the operator as a prefix or postfix
1957
- // unary operator.
1958
- //
1959
- // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
1960
- // binary operators with a very low precedence, that should result
1961
- // in AssignmentExpression nodes.
1962
- eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
1963
- assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
1964
- incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
1965
- prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }),
1966
- logicalOR: binop("||", 1),
1967
- logicalAND: binop("&&", 2),
1968
- bitwiseOR: binop("|", 3),
1969
- bitwiseXOR: binop("^", 4),
1970
- bitwiseAND: binop("&", 5),
1971
- equality: binop("==/!=/===/!==", 6),
1972
- relational: binop("</>/<=/>=", 7),
1973
- bitShift: binop("<</>>/>>>", 8),
1974
- plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
1975
- modulo: binop("%", 10),
1976
- star: binop("*", 10),
1977
- slash: binop("/", 10),
1978
- starstar: new TokenType("**", { beforeExpr: true }),
1979
- coalesce: binop("??", 1),
1980
- // Keyword token types.
1981
- _break: kw("break"),
1982
- _case: kw("case", beforeExpr),
1983
- _catch: kw("catch"),
1984
- _continue: kw("continue"),
1985
- _debugger: kw("debugger"),
1986
- _default: kw("default", beforeExpr),
1987
- _do: kw("do", { isLoop: true, beforeExpr: true }),
1988
- _else: kw("else", beforeExpr),
1989
- _finally: kw("finally"),
1990
- _for: kw("for", { isLoop: true }),
1991
- _function: kw("function", startsExpr),
1992
- _if: kw("if"),
1993
- _return: kw("return", beforeExpr),
1994
- _switch: kw("switch"),
1995
- _throw: kw("throw", beforeExpr),
1996
- _try: kw("try"),
1997
- _var: kw("var"),
1998
- _const: kw("const"),
1999
- _while: kw("while", { isLoop: true }),
2000
- _with: kw("with"),
2001
- _new: kw("new", { beforeExpr: true, startsExpr: true }),
2002
- _this: kw("this", startsExpr),
2003
- _super: kw("super", startsExpr),
2004
- _class: kw("class", startsExpr),
2005
- _extends: kw("extends", beforeExpr),
2006
- _export: kw("export"),
2007
- _import: kw("import", startsExpr),
2008
- _null: kw("null", startsExpr),
2009
- _true: kw("true", startsExpr),
2010
- _false: kw("false", startsExpr),
2011
- _in: kw("in", { beforeExpr: true, binop: 7 }),
2012
- _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }),
2013
- _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }),
2014
- _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }),
2015
- _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true })
2016
- };
2017
- var lineBreak = /\r\n?|\n|\u2028|\u2029/;
2018
- var lineBreakG = new RegExp(lineBreak.source, "g");
2019
- function isNewLine(code) {
2020
- return code === 10 || code === 13 || code === 8232 || code === 8233;
2021
- }
2022
- function nextLineBreak(code, from, end) {
2023
- if (end === void 0) end = code.length;
2024
- for (var i = from; i < end; i++) {
2025
- var next = code.charCodeAt(i);
2026
- if (isNewLine(next)) {
2027
- return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1;
2028
- }
2029
- }
2030
- return -1;
2031
- }
2032
- var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
2033
- var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
2034
- var ref = Object.prototype;
2035
- var hasOwnProperty = ref.hasOwnProperty;
2036
- var toString2 = ref.toString;
2037
- var hasOwn = Object.hasOwn || function(obj, propName) {
2038
- return hasOwnProperty.call(obj, propName);
2039
- };
2040
- var isArray = Array.isArray || function(obj) {
2041
- return toString2.call(obj) === "[object Array]";
2042
- };
2043
- var regexpCache = /* @__PURE__ */ Object.create(null);
2044
- function wordsRegexp(words) {
2045
- return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));
2046
- }
2047
- function codePointToString(code) {
2048
- if (code <= 65535) {
2049
- return String.fromCharCode(code);
2050
- }
2051
- code -= 65536;
2052
- return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
1320
+ code -= 65536;
1321
+ return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
2053
1322
  }
2054
1323
  var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
2055
1324
  var Position = function Position2(line, col) {
@@ -7342,7 +6611,7 @@ Parser.acorn = {
7342
6611
 
7343
6612
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7344
6613
  import { builtinModules, createRequire } from "node:module";
7345
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6614
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7346
6615
 
7347
6616
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7348
6617
  var r = String.fromCharCode;
@@ -7399,9 +6668,9 @@ var isAbsolute = function(p) {
7399
6668
 
7400
6669
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7401
6670
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7402
- import assert5 from "node:assert";
6671
+ import assert from "node:assert";
7403
6672
  import process$1 from "node:process";
7404
- import path4, { dirname as dirname4 } from "node:path";
6673
+ import path, { dirname as dirname2 } from "node:path";
7405
6674
  import v8 from "node:v8";
7406
6675
  import { format as format2, inspect } from "node:util";
7407
6676
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7437,7 +6706,7 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7437
6706
  * @param {unknown} actual
7438
6707
  */
7439
6708
  (name2, expected, actual) => {
7440
- assert5(typeof name2 === "string", "'name' must be a string");
6709
+ assert(typeof name2 === "string", "'name' must be a string");
7441
6710
  if (!Array.isArray(expected)) {
7442
6711
  expected = [expected];
7443
6712
  }
@@ -7453,14 +6722,14 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7453
6722
  const instances = [];
7454
6723
  const other = [];
7455
6724
  for (const value of expected) {
7456
- assert5(
6725
+ assert(
7457
6726
  typeof value === "string",
7458
6727
  "All expected entries have to be of type string"
7459
6728
  );
7460
6729
  if (kTypes.has(value)) {
7461
6730
  types2.push(value.toLowerCase());
7462
6731
  } else if (classRegExp.exec(value) === null) {
7463
- assert5(
6732
+ assert(
7464
6733
  value !== "object",
7465
6734
  'The value "object" should be written as "Object"'
7466
6735
  );
@@ -7533,14 +6802,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7533
6802
  * @param {boolean} [isImport=false]
7534
6803
  * @param {string} [base]
7535
6804
  */
7536
- (packagePath, key, target, isImport = false, base = void 0) => {
7537
- const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
6805
+ (packagePath, key, target2, isImport = false, base = void 0) => {
6806
+ const relatedError = typeof target2 === "string" && !isImport && target2.length > 0 && !target2.startsWith("./");
7538
6807
  if (key === ".") {
7539
- assert5(isImport === false);
7540
- 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 "./"' : ""}`;
6808
+ assert(isImport === false);
6809
+ 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 "./"' : ""}`;
7541
6810
  }
7542
6811
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7543
- target
6812
+ target2
7544
6813
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7545
6814
  },
7546
6815
  Error
@@ -7701,9 +6970,9 @@ var captureLargerStackTrace = hideStackFrames(
7701
6970
  );
7702
6971
  function getMessage(key, parameters, self) {
7703
6972
  const message = messages.get(key);
7704
- assert5(message !== void 0, "expected `message` to be found");
6973
+ assert(message !== void 0, "expected `message` to be found");
7705
6974
  if (typeof message === "function") {
7706
- assert5(
6975
+ assert(
7707
6976
  message.length <= parameters.length,
7708
6977
  // Default options do not count.
7709
6978
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -7713,7 +6982,7 @@ function getMessage(key, parameters, self) {
7713
6982
  const regex = /%[dfijoOs]/g;
7714
6983
  let expectedLength = 0;
7715
6984
  while (regex.exec(message) !== null) expectedLength++;
7716
- assert5(
6985
+ assert(
7717
6986
  expectedLength === parameters.length,
7718
6987
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7719
6988
  );
@@ -7750,7 +7019,7 @@ function read(jsonPath, { base, specifier }) {
7750
7019
  }
7751
7020
  let string;
7752
7021
  try {
7753
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7022
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7754
7023
  } catch (error) {
7755
7024
  const exception = (
7756
7025
  /** @type {ErrnoException} */
@@ -7936,14 +7205,14 @@ var patternRegEx = /\*/g;
7936
7205
  var encodedSeparatorRegEx = /%2f|%5c/i;
7937
7206
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7938
7207
  var doubleSlashRegEx = /[/\\]{2}/;
7939
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7208
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7940
7209
  if (process$1.noDeprecation) {
7941
7210
  return;
7942
7211
  }
7943
7212
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7944
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7213
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7945
7214
  process$1.emitWarning(
7946
- `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)}` : ""}.`,
7215
+ `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)}` : ""}.`,
7947
7216
  "DeprecationWarning",
7948
7217
  "DEP0166"
7949
7218
  );
@@ -7966,7 +7235,7 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7966
7235
  "DeprecationWarning",
7967
7236
  "DEP0151"
7968
7237
  );
7969
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7238
+ } else if (path.resolve(packagePath, main) !== urlPath) {
7970
7239
  process$1.emitWarning(
7971
7240
  `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7972
7241
  packagePath.length
@@ -7979,12 +7248,12 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7979
7248
  }
7980
7249
  function tryStatSync(path8) {
7981
7250
  try {
7982
- return statSync2(path8);
7251
+ return statSync(path8);
7983
7252
  } catch {
7984
7253
  }
7985
7254
  }
7986
7255
  function fileExists(url) {
7987
- const stats = statSync2(url, { throwIfNoEntry: false });
7256
+ const stats = statSync(url, { throwIfNoEntry: false });
7988
7257
  const isFile = stats ? stats.isFile() : void 0;
7989
7258
  return isFile === null || isFile === void 0 ? false : isFile;
7990
7259
  }
@@ -8007,824 +7276,1558 @@ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
8007
7276
  if (fileExists(guess)) break;
8008
7277
  guess = void 0;
8009
7278
  }
8010
- if (guess) {
8011
- emitLegacyIndexDeprecation(
8012
- guess,
8013
- packageJsonUrl,
7279
+ if (guess) {
7280
+ emitLegacyIndexDeprecation(
7281
+ guess,
7282
+ packageJsonUrl,
7283
+ base,
7284
+ packageConfig.main
7285
+ );
7286
+ return guess;
7287
+ }
7288
+ }
7289
+ const tries = ["./index.js", "./index.json", "./index.node"];
7290
+ let i = -1;
7291
+ while (++i < tries.length) {
7292
+ guess = new URL$1(tries[i], packageJsonUrl);
7293
+ if (fileExists(guess)) break;
7294
+ guess = void 0;
7295
+ }
7296
+ if (guess) {
7297
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
7298
+ return guess;
7299
+ }
7300
+ throw new ERR_MODULE_NOT_FOUND(
7301
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7302
+ fileURLToPath$1(base)
7303
+ );
7304
+ }
7305
+ function finalizeResolution(resolved, base, preserveSymlinks) {
7306
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7307
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7308
+ resolved.pathname,
7309
+ 'must not include encoded "/" or "\\" characters',
7310
+ fileURLToPath$1(base)
7311
+ );
7312
+ }
7313
+ let filePath;
7314
+ try {
7315
+ filePath = fileURLToPath$1(resolved);
7316
+ } catch (error) {
7317
+ const cause = (
7318
+ /** @type {ErrnoException} */
7319
+ error
7320
+ );
7321
+ Object.defineProperty(cause, "input", { value: String(resolved) });
7322
+ Object.defineProperty(cause, "module", { value: String(base) });
7323
+ throw cause;
7324
+ }
7325
+ const stats = tryStatSync(
7326
+ filePath.endsWith("/") ? filePath.slice(-1) : filePath
7327
+ );
7328
+ if (stats && stats.isDirectory()) {
7329
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
7330
+ error.url = String(resolved);
7331
+ throw error;
7332
+ }
7333
+ if (!stats || !stats.isFile()) {
7334
+ const error = new ERR_MODULE_NOT_FOUND(
7335
+ filePath || resolved.pathname,
7336
+ base && fileURLToPath$1(base),
7337
+ true
7338
+ );
7339
+ error.url = String(resolved);
7340
+ throw error;
7341
+ }
7342
+ {
7343
+ const real = realpathSync(filePath);
7344
+ const { search, hash } = resolved;
7345
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? "/" : ""));
7346
+ resolved.search = search;
7347
+ resolved.hash = hash;
7348
+ }
7349
+ return resolved;
7350
+ }
7351
+ function importNotDefined(specifier, packageJsonUrl, base) {
7352
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7353
+ specifier,
7354
+ packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7355
+ fileURLToPath$1(base)
7356
+ );
7357
+ }
7358
+ function exportsNotFound(subpath, packageJsonUrl, base) {
7359
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(
7360
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7361
+ subpath,
7362
+ base && fileURLToPath$1(base)
7363
+ );
7364
+ }
7365
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
7366
+ const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
7367
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7368
+ request,
7369
+ reason,
7370
+ base && fileURLToPath$1(base)
7371
+ );
7372
+ }
7373
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
7374
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
7375
+ return new ERR_INVALID_PACKAGE_TARGET(
7376
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7377
+ subpath,
7378
+ target2,
7379
+ internal,
7380
+ base && fileURLToPath$1(base)
7381
+ );
7382
+ }
7383
+ function resolvePackageTargetString(target2, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
7384
+ if (subpath !== "" && !pattern && target2[target2.length - 1] !== "/")
7385
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7386
+ if (!target2.startsWith("./")) {
7387
+ if (internal && !target2.startsWith("../") && !target2.startsWith("/")) {
7388
+ let isURL = false;
7389
+ try {
7390
+ new URL$1(target2);
7391
+ isURL = true;
7392
+ } catch {
7393
+ }
7394
+ if (!isURL) {
7395
+ const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7396
+ patternRegEx,
7397
+ target2,
7398
+ () => subpath
7399
+ ) : target2 + subpath;
7400
+ return packageResolve(exportTarget, packageJsonUrl, conditions);
7401
+ }
7402
+ }
7403
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7404
+ }
7405
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
7406
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
7407
+ if (!isPathMap) {
7408
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7409
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7410
+ patternRegEx,
7411
+ target2,
7412
+ () => subpath
7413
+ ) : target2;
7414
+ emitInvalidSegmentDeprecation(
7415
+ resolvedTarget,
7416
+ request,
7417
+ match,
7418
+ packageJsonUrl,
7419
+ internal,
7420
+ base,
7421
+ true
7422
+ );
7423
+ }
7424
+ } else {
7425
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7426
+ }
7427
+ }
7428
+ const resolved = new URL$1(target2, packageJsonUrl);
7429
+ const resolvedPath = resolved.pathname;
7430
+ const packagePath = new URL$1(".", packageJsonUrl).pathname;
7431
+ if (!resolvedPath.startsWith(packagePath))
7432
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7433
+ if (subpath === "") return resolved;
7434
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
7435
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7436
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
7437
+ if (!isPathMap) {
7438
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7439
+ patternRegEx,
7440
+ target2,
7441
+ () => subpath
7442
+ ) : target2;
7443
+ emitInvalidSegmentDeprecation(
7444
+ resolvedTarget,
7445
+ request,
7446
+ match,
7447
+ packageJsonUrl,
7448
+ internal,
7449
+ base,
7450
+ false
7451
+ );
7452
+ }
7453
+ } else {
7454
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7455
+ }
7456
+ }
7457
+ if (pattern) {
7458
+ return new URL$1(
7459
+ RegExpPrototypeSymbolReplace.call(
7460
+ patternRegEx,
7461
+ resolved.href,
7462
+ () => subpath
7463
+ )
7464
+ );
7465
+ }
7466
+ return new URL$1(subpath, resolved);
7467
+ }
7468
+ function isArrayIndex(key) {
7469
+ const keyNumber = Number(key);
7470
+ if (`${keyNumber}` !== key) return false;
7471
+ return keyNumber >= 0 && keyNumber < 4294967295;
7472
+ }
7473
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
7474
+ if (typeof target2 === "string") {
7475
+ return resolvePackageTargetString(
7476
+ target2,
7477
+ subpath,
7478
+ packageSubpath,
7479
+ packageJsonUrl,
7480
+ base,
7481
+ pattern,
7482
+ internal,
7483
+ isPathMap,
7484
+ conditions
7485
+ );
7486
+ }
7487
+ if (Array.isArray(target2)) {
7488
+ const targetList = target2;
7489
+ if (targetList.length === 0) return null;
7490
+ let lastException;
7491
+ let i = -1;
7492
+ while (++i < targetList.length) {
7493
+ const targetItem = targetList[i];
7494
+ let resolveResult;
7495
+ try {
7496
+ resolveResult = resolvePackageTarget(
7497
+ packageJsonUrl,
7498
+ targetItem,
7499
+ subpath,
7500
+ packageSubpath,
7501
+ base,
7502
+ pattern,
7503
+ internal,
7504
+ isPathMap,
7505
+ conditions
7506
+ );
7507
+ } catch (error) {
7508
+ const exception = (
7509
+ /** @type {ErrnoException} */
7510
+ error
7511
+ );
7512
+ lastException = exception;
7513
+ if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
7514
+ throw error;
7515
+ }
7516
+ if (resolveResult === void 0) continue;
7517
+ if (resolveResult === null) {
7518
+ lastException = null;
7519
+ continue;
7520
+ }
7521
+ return resolveResult;
7522
+ }
7523
+ if (lastException === void 0 || lastException === null) {
7524
+ return null;
7525
+ }
7526
+ throw lastException;
7527
+ }
7528
+ if (typeof target2 === "object" && target2 !== null) {
7529
+ const keys = Object.getOwnPropertyNames(target2);
7530
+ let i = -1;
7531
+ while (++i < keys.length) {
7532
+ const key = keys[i];
7533
+ if (isArrayIndex(key)) {
7534
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7535
+ fileURLToPath$1(packageJsonUrl),
7536
+ base,
7537
+ '"exports" cannot contain numeric property keys.'
7538
+ );
7539
+ }
7540
+ }
7541
+ i = -1;
7542
+ while (++i < keys.length) {
7543
+ const key = keys[i];
7544
+ if (key === "default" || conditions && conditions.has(key)) {
7545
+ const conditionalTarget = (
7546
+ /** @type {unknown} */
7547
+ target2[key]
7548
+ );
7549
+ const resolveResult = resolvePackageTarget(
7550
+ packageJsonUrl,
7551
+ conditionalTarget,
7552
+ subpath,
7553
+ packageSubpath,
7554
+ base,
7555
+ pattern,
7556
+ internal,
7557
+ isPathMap,
7558
+ conditions
7559
+ );
7560
+ if (resolveResult === void 0) continue;
7561
+ return resolveResult;
7562
+ }
7563
+ }
7564
+ return null;
7565
+ }
7566
+ if (target2 === null) {
7567
+ return null;
7568
+ }
7569
+ throw invalidPackageTarget(
7570
+ packageSubpath,
7571
+ target2,
7572
+ packageJsonUrl,
7573
+ internal,
7574
+ base
7575
+ );
7576
+ }
7577
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
7578
+ if (typeof exports === "string" || Array.isArray(exports)) return true;
7579
+ if (typeof exports !== "object" || exports === null) return false;
7580
+ const keys = Object.getOwnPropertyNames(exports);
7581
+ let isConditionalSugar = false;
7582
+ let i = 0;
7583
+ let keyIndex = -1;
7584
+ while (++keyIndex < keys.length) {
7585
+ const key = keys[keyIndex];
7586
+ const currentIsConditionalSugar = key === "" || key[0] !== ".";
7587
+ if (i++ === 0) {
7588
+ isConditionalSugar = currentIsConditionalSugar;
7589
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
7590
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7591
+ fileURLToPath$1(packageJsonUrl),
8014
7592
  base,
8015
- packageConfig.main
7593
+ `"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.`
8016
7594
  );
8017
- return guess;
8018
7595
  }
8019
7596
  }
8020
- const tries = ["./index.js", "./index.json", "./index.node"];
8021
- let i = -1;
8022
- while (++i < tries.length) {
8023
- guess = new URL$1(tries[i], packageJsonUrl);
8024
- if (fileExists(guess)) break;
8025
- guess = void 0;
8026
- }
8027
- if (guess) {
8028
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
8029
- return guess;
7597
+ return isConditionalSugar;
7598
+ }
7599
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
7600
+ if (process$1.noDeprecation) {
7601
+ return;
8030
7602
  }
8031
- throw new ERR_MODULE_NOT_FOUND(
8032
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8033
- fileURLToPath$1(base)
7603
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
7604
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
7605
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
7606
+ process$1.emitWarning(
7607
+ `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.`,
7608
+ "DeprecationWarning",
7609
+ "DEP0155"
8034
7610
  );
8035
7611
  }
8036
- function finalizeResolution(resolved, base, preserveSymlinks) {
8037
- if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
8038
- throw new ERR_INVALID_MODULE_SPECIFIER(
8039
- resolved.pathname,
8040
- 'must not include encoded "/" or "\\" characters',
8041
- fileURLToPath$1(base)
8042
- );
7612
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7613
+ let exports = packageConfig.exports;
7614
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7615
+ exports = { ".": exports };
8043
7616
  }
8044
- let filePath;
8045
- try {
8046
- filePath = fileURLToPath$1(resolved);
8047
- } catch (error) {
8048
- const cause = (
8049
- /** @type {ErrnoException} */
8050
- error
7617
+ if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
7618
+ const target2 = exports[packageSubpath];
7619
+ const resolveResult = resolvePackageTarget(
7620
+ packageJsonUrl,
7621
+ target2,
7622
+ "",
7623
+ packageSubpath,
7624
+ base,
7625
+ false,
7626
+ false,
7627
+ false,
7628
+ conditions
8051
7629
  );
8052
- Object.defineProperty(cause, "input", { value: String(resolved) });
8053
- Object.defineProperty(cause, "module", { value: String(base) });
8054
- throw cause;
7630
+ if (resolveResult === null || resolveResult === void 0) {
7631
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7632
+ }
7633
+ return resolveResult;
8055
7634
  }
8056
- const stats = tryStatSync(
8057
- filePath.endsWith("/") ? filePath.slice(-1) : filePath
8058
- );
8059
- if (stats && stats.isDirectory()) {
8060
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
8061
- error.url = String(resolved);
8062
- throw error;
7635
+ let bestMatch = "";
7636
+ let bestMatchSubpath = "";
7637
+ const keys = Object.getOwnPropertyNames(exports);
7638
+ let i = -1;
7639
+ while (++i < keys.length) {
7640
+ const key = keys[i];
7641
+ const patternIndex = key.indexOf("*");
7642
+ if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
7643
+ if (packageSubpath.endsWith("/")) {
7644
+ emitTrailingSlashPatternDeprecation(
7645
+ packageSubpath,
7646
+ packageJsonUrl,
7647
+ base
7648
+ );
7649
+ }
7650
+ const patternTrailer = key.slice(patternIndex + 1);
7651
+ if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7652
+ bestMatch = key;
7653
+ bestMatchSubpath = packageSubpath.slice(
7654
+ patternIndex,
7655
+ packageSubpath.length - patternTrailer.length
7656
+ );
7657
+ }
7658
+ }
8063
7659
  }
8064
- if (!stats || !stats.isFile()) {
8065
- const error = new ERR_MODULE_NOT_FOUND(
8066
- filePath || resolved.pathname,
8067
- base && fileURLToPath$1(base),
8068
- true
7660
+ if (bestMatch) {
7661
+ const target2 = (
7662
+ /** @type {unknown} */
7663
+ exports[bestMatch]
8069
7664
  );
8070
- error.url = String(resolved);
8071
- throw error;
7665
+ const resolveResult = resolvePackageTarget(
7666
+ packageJsonUrl,
7667
+ target2,
7668
+ bestMatchSubpath,
7669
+ bestMatch,
7670
+ base,
7671
+ true,
7672
+ false,
7673
+ packageSubpath.endsWith("/"),
7674
+ conditions
7675
+ );
7676
+ if (resolveResult === null || resolveResult === void 0) {
7677
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7678
+ }
7679
+ return resolveResult;
8072
7680
  }
8073
- {
8074
- const real = realpathSync(filePath);
8075
- const { search, hash } = resolved;
8076
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
8077
- resolved.search = search;
8078
- resolved.hash = hash;
7681
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7682
+ }
7683
+ function patternKeyCompare(a, b) {
7684
+ const aPatternIndex = a.indexOf("*");
7685
+ const bPatternIndex = b.indexOf("*");
7686
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
7687
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
7688
+ if (baseLengthA > baseLengthB) return -1;
7689
+ if (baseLengthB > baseLengthA) return 1;
7690
+ if (aPatternIndex === -1) return 1;
7691
+ if (bPatternIndex === -1) return -1;
7692
+ if (a.length > b.length) return -1;
7693
+ if (b.length > a.length) return 1;
7694
+ return 0;
7695
+ }
7696
+ function packageImportsResolve(name2, base, conditions) {
7697
+ if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
7698
+ const reason = "is not a valid internal imports specifier name";
7699
+ throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
7700
+ }
7701
+ let packageJsonUrl;
7702
+ const packageConfig = getPackageScopeConfig(base);
7703
+ if (packageConfig.exists) {
7704
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
7705
+ const imports = packageConfig.imports;
7706
+ if (imports) {
7707
+ if (own.call(imports, name2) && !name2.includes("*")) {
7708
+ const resolveResult = resolvePackageTarget(
7709
+ packageJsonUrl,
7710
+ imports[name2],
7711
+ "",
7712
+ name2,
7713
+ base,
7714
+ false,
7715
+ true,
7716
+ false,
7717
+ conditions
7718
+ );
7719
+ if (resolveResult !== null && resolveResult !== void 0) {
7720
+ return resolveResult;
7721
+ }
7722
+ } else {
7723
+ let bestMatch = "";
7724
+ let bestMatchSubpath = "";
7725
+ const keys = Object.getOwnPropertyNames(imports);
7726
+ let i = -1;
7727
+ while (++i < keys.length) {
7728
+ const key = keys[i];
7729
+ const patternIndex = key.indexOf("*");
7730
+ if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
7731
+ const patternTrailer = key.slice(patternIndex + 1);
7732
+ if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7733
+ bestMatch = key;
7734
+ bestMatchSubpath = name2.slice(
7735
+ patternIndex,
7736
+ name2.length - patternTrailer.length
7737
+ );
7738
+ }
7739
+ }
7740
+ }
7741
+ if (bestMatch) {
7742
+ const target2 = imports[bestMatch];
7743
+ const resolveResult = resolvePackageTarget(
7744
+ packageJsonUrl,
7745
+ target2,
7746
+ bestMatchSubpath,
7747
+ bestMatch,
7748
+ base,
7749
+ true,
7750
+ true,
7751
+ false,
7752
+ conditions
7753
+ );
7754
+ if (resolveResult !== null && resolveResult !== void 0) {
7755
+ return resolveResult;
7756
+ }
7757
+ }
7758
+ }
7759
+ }
7760
+ }
7761
+ throw importNotDefined(name2, packageJsonUrl, base);
7762
+ }
7763
+ function parsePackageName(specifier, base) {
7764
+ let separatorIndex = specifier.indexOf("/");
7765
+ let validPackageName = true;
7766
+ let isScoped = false;
7767
+ if (specifier[0] === "@") {
7768
+ isScoped = true;
7769
+ if (separatorIndex === -1 || specifier.length === 0) {
7770
+ validPackageName = false;
7771
+ } else {
7772
+ separatorIndex = specifier.indexOf("/", separatorIndex + 1);
7773
+ }
7774
+ }
7775
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7776
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7777
+ validPackageName = false;
7778
+ }
7779
+ if (!validPackageName) {
7780
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7781
+ specifier,
7782
+ "is not a valid package name",
7783
+ fileURLToPath$1(base)
7784
+ );
8079
7785
  }
8080
- return resolved;
7786
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7787
+ return { packageName, packageSubpath, isScoped };
8081
7788
  }
8082
- function importNotDefined(specifier, packageJsonUrl, base) {
8083
- return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
7789
+ function packageResolve(specifier, base, conditions) {
7790
+ if (builtinModules.includes(specifier)) {
7791
+ return new URL$1("node:" + specifier);
7792
+ }
7793
+ const { packageName, packageSubpath, isScoped } = parsePackageName(
8084
7794
  specifier,
8085
- packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8086
- fileURLToPath$1(base)
7795
+ base
8087
7796
  );
8088
- }
8089
- function exportsNotFound(subpath, packageJsonUrl, base) {
8090
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
8091
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8092
- subpath,
8093
- base && fileURLToPath$1(base)
7797
+ const packageConfig = getPackageScopeConfig(base);
7798
+ if (packageConfig.exists) {
7799
+ const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
7800
+ if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
7801
+ return packageExportsResolve(
7802
+ packageJsonUrl2,
7803
+ packageSubpath,
7804
+ packageConfig,
7805
+ base,
7806
+ conditions
7807
+ );
7808
+ }
7809
+ }
7810
+ let packageJsonUrl = new URL$1(
7811
+ "./node_modules/" + packageName + "/package.json",
7812
+ base
8094
7813
  );
7814
+ let packageJsonPath = fileURLToPath$1(packageJsonUrl);
7815
+ let lastPath;
7816
+ do {
7817
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
7818
+ if (!stat || !stat.isDirectory()) {
7819
+ lastPath = packageJsonPath;
7820
+ packageJsonUrl = new URL$1(
7821
+ (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
7822
+ packageJsonUrl
7823
+ );
7824
+ packageJsonPath = fileURLToPath$1(packageJsonUrl);
7825
+ continue;
7826
+ }
7827
+ const packageConfig2 = read(packageJsonPath, { base, specifier });
7828
+ if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
7829
+ return packageExportsResolve(
7830
+ packageJsonUrl,
7831
+ packageSubpath,
7832
+ packageConfig2,
7833
+ base,
7834
+ conditions
7835
+ );
7836
+ }
7837
+ if (packageSubpath === ".") {
7838
+ return legacyMainResolve(packageJsonUrl, packageConfig2, base);
7839
+ }
7840
+ return new URL$1(packageSubpath, packageJsonUrl);
7841
+ } while (packageJsonPath.length !== lastPath.length);
7842
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8095
7843
  }
8096
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8097
- const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
8098
- throw new ERR_INVALID_MODULE_SPECIFIER(
8099
- request,
8100
- reason,
8101
- base && fileURLToPath$1(base)
8102
- );
7844
+ function isRelativeSpecifier(specifier) {
7845
+ if (specifier[0] === ".") {
7846
+ if (specifier.length === 1 || specifier[1] === "/") return true;
7847
+ if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
7848
+ return true;
7849
+ }
7850
+ }
7851
+ return false;
8103
7852
  }
8104
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8105
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8106
- return new ERR_INVALID_PACKAGE_TARGET(
8107
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8108
- subpath,
8109
- target,
8110
- internal,
8111
- base && fileURLToPath$1(base)
8112
- );
7853
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
7854
+ if (specifier === "") return false;
7855
+ if (specifier[0] === "/") return true;
7856
+ return isRelativeSpecifier(specifier);
8113
7857
  }
8114
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8115
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8116
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8117
- if (!target.startsWith("./")) {
8118
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8119
- let isURL = false;
8120
- try {
8121
- new URL$1(target);
8122
- isURL = true;
8123
- } catch {
8124
- }
8125
- if (!isURL) {
8126
- const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8127
- patternRegEx,
8128
- target,
8129
- () => subpath
8130
- ) : target + subpath;
8131
- return packageResolve(exportTarget, packageJsonUrl, conditions);
8132
- }
7858
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
7859
+ const protocol = base.protocol;
7860
+ const isData = protocol === "data:";
7861
+ const isRemote = isData || protocol === "http:" || protocol === "https:";
7862
+ let resolved;
7863
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
7864
+ try {
7865
+ resolved = new URL$1(specifier, base);
7866
+ } catch (error_) {
7867
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7868
+ error.cause = error_;
7869
+ throw error;
8133
7870
  }
8134
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8135
- }
8136
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8137
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8138
- if (!isPathMap) {
8139
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8140
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8141
- patternRegEx,
8142
- target,
8143
- () => subpath
8144
- ) : target;
8145
- emitInvalidSegmentDeprecation(
8146
- resolvedTarget,
8147
- request,
8148
- match,
8149
- packageJsonUrl,
8150
- internal,
8151
- base,
8152
- true
8153
- );
7871
+ } else if (protocol === "file:" && specifier[0] === "#") {
7872
+ resolved = packageImportsResolve(specifier, base, conditions);
7873
+ } else {
7874
+ try {
7875
+ resolved = new URL$1(specifier);
7876
+ } catch (error_) {
7877
+ if (isRemote && !builtinModules.includes(specifier)) {
7878
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
7879
+ error.cause = error_;
7880
+ throw error;
8154
7881
  }
8155
- } else {
8156
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7882
+ resolved = packageResolve(specifier, base, conditions);
8157
7883
  }
8158
7884
  }
8159
- const resolved = new URL$1(target, packageJsonUrl);
8160
- const resolvedPath = resolved.pathname;
8161
- const packagePath = new URL$1(".", packageJsonUrl).pathname;
8162
- if (!resolvedPath.startsWith(packagePath))
8163
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8164
- if (subpath === "") return resolved;
8165
- if (invalidSegmentRegEx.exec(subpath) !== null) {
8166
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8167
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
8168
- if (!isPathMap) {
8169
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8170
- patternRegEx,
8171
- target,
8172
- () => subpath
8173
- ) : target;
8174
- emitInvalidSegmentDeprecation(
8175
- resolvedTarget,
8176
- request,
8177
- match,
8178
- packageJsonUrl,
8179
- internal,
8180
- base,
8181
- false
8182
- );
8183
- }
8184
- } else {
8185
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
8186
- }
7885
+ assert(resolved !== void 0, "expected to be defined");
7886
+ if (resolved.protocol !== "file:") {
7887
+ return resolved;
8187
7888
  }
8188
- if (pattern) {
8189
- return new URL$1(
8190
- RegExpPrototypeSymbolReplace.call(
8191
- patternRegEx,
8192
- resolved.href,
8193
- () => subpath
8194
- )
8195
- );
7889
+ return finalizeResolution(resolved, base);
7890
+ }
7891
+ function fileURLToPath(id) {
7892
+ if (typeof id === "string" && !id.startsWith("file://")) {
7893
+ return normalizeSlash(id);
8196
7894
  }
8197
- return new URL$1(subpath, resolved);
7895
+ return normalizeSlash(fileURLToPath$1(id));
8198
7896
  }
8199
- function isArrayIndex(key) {
8200
- const keyNumber = Number(key);
8201
- if (`${keyNumber}` !== key) return false;
8202
- return keyNumber >= 0 && keyNumber < 4294967295;
7897
+ function pathToFileURL(id) {
7898
+ return pathToFileURL$1(fileURLToPath(id)).toString();
8203
7899
  }
8204
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8205
- if (typeof target === "string") {
8206
- return resolvePackageTargetString(
8207
- target,
8208
- subpath,
8209
- packageSubpath,
8210
- packageJsonUrl,
8211
- base,
8212
- pattern,
8213
- internal,
8214
- isPathMap,
8215
- conditions
8216
- );
7900
+ function normalizeid(id) {
7901
+ if (typeof id !== "string") {
7902
+ id = id.toString();
8217
7903
  }
8218
- if (Array.isArray(target)) {
8219
- const targetList = target;
8220
- if (targetList.length === 0) return null;
8221
- let lastException;
8222
- let i = -1;
8223
- while (++i < targetList.length) {
8224
- const targetItem = targetList[i];
8225
- let resolveResult;
8226
- try {
8227
- resolveResult = resolvePackageTarget(
8228
- packageJsonUrl,
8229
- targetItem,
8230
- subpath,
8231
- packageSubpath,
8232
- base,
8233
- pattern,
8234
- internal,
8235
- isPathMap,
8236
- conditions
8237
- );
8238
- } catch (error) {
8239
- const exception = (
8240
- /** @type {ErrnoException} */
8241
- error
8242
- );
8243
- lastException = exception;
8244
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8245
- throw error;
7904
+ if (/(node|data|http|https|file):/.test(id)) {
7905
+ return id;
7906
+ }
7907
+ if (BUILTIN_MODULES.has(id)) {
7908
+ return "node:" + id;
7909
+ }
7910
+ return "file://" + encodeURI(normalizeSlash(id));
7911
+ }
7912
+ var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
7913
+ var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
7914
+ var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
7915
+ "ERR_MODULE_NOT_FOUND",
7916
+ "ERR_UNSUPPORTED_DIR_IMPORT",
7917
+ "MODULE_NOT_FOUND",
7918
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
7919
+ ]);
7920
+ function _tryModuleResolve(id, url, conditions) {
7921
+ try {
7922
+ return moduleResolve(id, url, conditions);
7923
+ } catch (error) {
7924
+ if (!NOT_FOUND_ERRORS.has(error?.code)) {
7925
+ throw error;
7926
+ }
7927
+ }
7928
+ }
7929
+ function _resolve(id, options = {}) {
7930
+ if (typeof id !== "string") {
7931
+ if (id instanceof URL) {
7932
+ id = fileURLToPath(id);
7933
+ } else {
7934
+ throw new TypeError("input must be a `string` or `URL`");
7935
+ }
7936
+ }
7937
+ if (/(node|data|http|https):/.test(id)) {
7938
+ return id;
7939
+ }
7940
+ if (BUILTIN_MODULES.has(id)) {
7941
+ return "node:" + id;
7942
+ }
7943
+ if (id.startsWith("file://")) {
7944
+ id = fileURLToPath(id);
7945
+ }
7946
+ if (isAbsolute(id)) {
7947
+ try {
7948
+ const stat = statSync(id);
7949
+ if (stat.isFile()) {
7950
+ return pathToFileURL(id);
8246
7951
  }
8247
- if (resolveResult === void 0) continue;
8248
- if (resolveResult === null) {
8249
- lastException = null;
8250
- continue;
7952
+ } catch (error) {
7953
+ if (error?.code !== "ENOENT") {
7954
+ throw error;
8251
7955
  }
8252
- return resolveResult;
8253
7956
  }
8254
- if (lastException === void 0 || lastException === null) {
8255
- return null;
7957
+ }
7958
+ const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
7959
+ const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
7960
+ if (_urls.length === 0) {
7961
+ _urls.push(new URL(pathToFileURL(process.cwd())));
7962
+ }
7963
+ const urls = [..._urls];
7964
+ for (const url of _urls) {
7965
+ if (url.protocol === "file:") {
7966
+ urls.push(
7967
+ new URL("./", url),
7968
+ // If url is directory
7969
+ new URL(joinURL(url.pathname, "_index.js"), url),
7970
+ // TODO: Remove in next major version?
7971
+ new URL("node_modules", url)
7972
+ );
8256
7973
  }
8257
- throw lastException;
8258
7974
  }
8259
- if (typeof target === "object" && target !== null) {
8260
- const keys = Object.getOwnPropertyNames(target);
8261
- let i = -1;
8262
- while (++i < keys.length) {
8263
- const key = keys[i];
8264
- if (isArrayIndex(key)) {
8265
- throw new ERR_INVALID_PACKAGE_CONFIG(
8266
- fileURLToPath$1(packageJsonUrl),
8267
- base,
8268
- '"exports" cannot contain numeric property keys.'
8269
- );
8270
- }
7975
+ let resolved;
7976
+ for (const url of urls) {
7977
+ resolved = _tryModuleResolve(id, url, conditionsSet);
7978
+ if (resolved) {
7979
+ break;
8271
7980
  }
8272
- i = -1;
8273
- while (++i < keys.length) {
8274
- const key = keys[i];
8275
- if (key === "default" || conditions && conditions.has(key)) {
8276
- const conditionalTarget = (
8277
- /** @type {unknown} */
8278
- target[key]
8279
- );
8280
- const resolveResult = resolvePackageTarget(
8281
- packageJsonUrl,
8282
- conditionalTarget,
8283
- subpath,
8284
- packageSubpath,
8285
- base,
8286
- pattern,
8287
- internal,
8288
- isPathMap,
8289
- conditions
7981
+ for (const prefix of ["", "/index"]) {
7982
+ for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
7983
+ resolved = _tryModuleResolve(
7984
+ joinURL(id, prefix) + extension,
7985
+ url,
7986
+ conditionsSet
8290
7987
  );
8291
- if (resolveResult === void 0) continue;
8292
- return resolveResult;
7988
+ if (resolved) {
7989
+ break;
7990
+ }
7991
+ }
7992
+ if (resolved) {
7993
+ break;
8293
7994
  }
8294
7995
  }
8295
- return null;
7996
+ if (resolved) {
7997
+ break;
7998
+ }
8296
7999
  }
8297
- if (target === null) {
8298
- return null;
8000
+ if (!resolved) {
8001
+ const error = new Error(
8002
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
8003
+ );
8004
+ error.code = "ERR_MODULE_NOT_FOUND";
8005
+ throw error;
8299
8006
  }
8300
- throw invalidPackageTarget(
8301
- packageSubpath,
8302
- target,
8303
- packageJsonUrl,
8304
- internal,
8305
- base
8306
- );
8007
+ return pathToFileURL(resolved);
8307
8008
  }
8308
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8309
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8310
- if (typeof exports !== "object" || exports === null) return false;
8311
- const keys = Object.getOwnPropertyNames(exports);
8312
- let isConditionalSugar = false;
8313
- let i = 0;
8314
- let keyIndex = -1;
8315
- while (++keyIndex < keys.length) {
8316
- const key = keys[keyIndex];
8317
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8318
- if (i++ === 0) {
8319
- isConditionalSugar = currentIsConditionalSugar;
8320
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8321
- throw new ERR_INVALID_PACKAGE_CONFIG(
8322
- fileURLToPath$1(packageJsonUrl),
8323
- base,
8324
- `"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.`
8325
- );
8326
- }
8327
- }
8328
- return isConditionalSugar;
8009
+ function resolveSync(id, options) {
8010
+ return _resolve(id, options);
8329
8011
  }
8330
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8331
- if (process$1.noDeprecation) {
8332
- return;
8333
- }
8334
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8335
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8336
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8337
- process$1.emitWarning(
8338
- `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.`,
8339
- "DeprecationWarning",
8340
- "DEP0155"
8341
- );
8012
+ function resolvePathSync(id, options) {
8013
+ return fileURLToPath(resolveSync(id, options));
8342
8014
  }
8343
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8344
- let exports = packageConfig.exports;
8345
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8346
- exports = { ".": exports };
8015
+
8016
+ // src/node-js-compat.ts
8017
+ import { defineEnv } from "unenv";
8018
+ var { env } = defineEnv({
8019
+ nodeCompat: true,
8020
+ presets: [cloudflare]
8021
+ });
8022
+ var nodeCompatExternals = new Set(env.external);
8023
+ var nodeCompatEntries = getNodeCompatEntries();
8024
+ function isNodeCompat(workerConfig) {
8025
+ if (workerConfig === void 0) {
8026
+ return false;
8347
8027
  }
8348
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8349
- const target = exports[packageSubpath];
8350
- const resolveResult = resolvePackageTarget(
8351
- packageJsonUrl,
8352
- target,
8353
- "",
8354
- packageSubpath,
8355
- base,
8356
- false,
8357
- false,
8358
- false,
8359
- conditions
8028
+ const nodeCompatMode = getNodeCompat(
8029
+ workerConfig.compatibility_date,
8030
+ workerConfig.compatibility_flags ?? []
8031
+ ).mode;
8032
+ if (nodeCompatMode === "v2") {
8033
+ return true;
8034
+ }
8035
+ if (nodeCompatMode === "v1") {
8036
+ throw new Error(
8037
+ `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`
8360
8038
  );
8361
- if (resolveResult === null || resolveResult === void 0) {
8362
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8039
+ }
8040
+ return false;
8041
+ }
8042
+ function injectGlobalCode(id, code) {
8043
+ const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8044
+ if (typeof globalInject === "string") {
8045
+ const moduleSpecifier2 = globalInject;
8046
+ return `import var_${globalName} from "${moduleSpecifier2}";
8047
+ globalThis.${globalName} = var_${globalName};
8048
+ `;
8363
8049
  }
8364
- return resolveResult;
8050
+ const [moduleSpecifier, exportName] = globalInject;
8051
+ assert2(
8052
+ moduleSpecifier !== void 0,
8053
+ "Expected moduleSpecifier to be defined"
8054
+ );
8055
+ assert2(exportName !== void 0, "Expected exportName to be defined");
8056
+ return `import var_${globalName} from "${moduleSpecifier}";
8057
+ globalThis.${globalName} = var_${globalName}.${exportName};
8058
+ `;
8059
+ }).join("\n");
8060
+ const modified = new MagicString(code);
8061
+ modified.prepend(injectedCode);
8062
+ return {
8063
+ code: modified.toString(),
8064
+ map: modified.generateMap({ hires: "boundary", source: id })
8065
+ };
8066
+ }
8067
+ function resolveNodeJSImport(source) {
8068
+ const alias = env.alias[source];
8069
+ if (alias) {
8070
+ return {
8071
+ unresolved: alias,
8072
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8073
+ };
8365
8074
  }
8366
- let bestMatch = "";
8367
- let bestMatchSubpath = "";
8368
- const keys = Object.getOwnPropertyNames(exports);
8369
- let i = -1;
8370
- while (++i < keys.length) {
8371
- const key = keys[i];
8372
- const patternIndex = key.indexOf("*");
8373
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8374
- if (packageSubpath.endsWith("/")) {
8375
- emitTrailingSlashPatternDeprecation(
8376
- packageSubpath,
8377
- packageJsonUrl,
8378
- base
8379
- );
8380
- }
8381
- const patternTrailer = key.slice(patternIndex + 1);
8382
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8383
- bestMatch = key;
8384
- bestMatchSubpath = packageSubpath.slice(
8385
- patternIndex,
8386
- packageSubpath.length - patternTrailer.length
8387
- );
8388
- }
8075
+ if (nodeCompatEntries.has(source)) {
8076
+ return {
8077
+ unresolved: source,
8078
+ resolved: resolvePathSync(source, { url: import.meta.url })
8079
+ };
8080
+ }
8081
+ }
8082
+ function getNodeCompatEntries() {
8083
+ const entries = new Set(Object.values(env.alias));
8084
+ for (const globalInject of Object.values(env.inject)) {
8085
+ if (typeof globalInject === "string") {
8086
+ entries.add(globalInject);
8087
+ } else {
8088
+ assert2(
8089
+ globalInject[0] !== void 0,
8090
+ "Expected first element of globalInject to be defined"
8091
+ );
8092
+ entries.add(globalInject[0]);
8389
8093
  }
8390
8094
  }
8391
- if (bestMatch) {
8392
- const target = (
8393
- /** @type {unknown} */
8394
- exports[bestMatch]
8395
- );
8396
- const resolveResult = resolvePackageTarget(
8397
- packageJsonUrl,
8398
- target,
8399
- bestMatchSubpath,
8400
- bestMatch,
8401
- base,
8402
- true,
8403
- false,
8404
- packageSubpath.endsWith("/"),
8405
- conditions
8406
- );
8407
- if (resolveResult === null || resolveResult === void 0) {
8408
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8095
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8096
+ return entries;
8097
+ }
8098
+
8099
+ // src/constants.ts
8100
+ var ROUTER_WORKER_NAME = "__router-worker__";
8101
+ var ASSET_WORKER_NAME = "__asset-worker__";
8102
+ var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
8103
+ var MODULE_TYPES = ["CompiledWasm"];
8104
+
8105
+ // src/shared.ts
8106
+ var UNKNOWN_HOST = "http://localhost";
8107
+ var INIT_PATH = "/__vite_plugin_cloudflare_init__";
8108
+ var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
8109
+ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
8110
+
8111
+ // src/utils.ts
8112
+ import * as path2 from "node:path";
8113
+ import { Request as MiniflareRequest } from "miniflare";
8114
+ import "vite";
8115
+ function getOutputDirectory(userConfig, environmentName) {
8116
+ const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
8117
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path2.join(rootOutputDirectory, environmentName);
8118
+ }
8119
+ function toMiniflareRequest(request) {
8120
+ return new MiniflareRequest(request.url, {
8121
+ method: request.method,
8122
+ headers: [["accept-encoding", "identity"], ...request.headers],
8123
+ body: request.body,
8124
+ duplex: "half"
8125
+ });
8126
+ }
8127
+ function nodeHeadersToWebHeaders(nodeHeaders) {
8128
+ const headers = new Headers();
8129
+ for (const [key, value] of Object.entries(nodeHeaders)) {
8130
+ if (typeof value === "string") {
8131
+ headers.append(key, value);
8132
+ } else if (Array.isArray(value)) {
8133
+ for (const item of value) {
8134
+ headers.append(key, item);
8135
+ }
8409
8136
  }
8410
- return resolveResult;
8411
8137
  }
8412
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8138
+ return headers;
8413
8139
  }
8414
- function patternKeyCompare(a, b) {
8415
- const aPatternIndex = a.indexOf("*");
8416
- const bPatternIndex = b.indexOf("*");
8417
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8418
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8419
- if (baseLengthA > baseLengthB) return -1;
8420
- if (baseLengthB > baseLengthA) return 1;
8421
- if (aPatternIndex === -1) return 1;
8422
- if (bPatternIndex === -1) return -1;
8423
- if (a.length > b.length) return -1;
8424
- if (b.length > a.length) return 1;
8425
- return 0;
8140
+
8141
+ // src/cloudflare-environment.ts
8142
+ var webSocketUndefinedError = "The WebSocket is undefined";
8143
+ function createHotChannel(webSocketContainer) {
8144
+ const listenersMap = /* @__PURE__ */ new Map();
8145
+ const client = {
8146
+ send(payload) {
8147
+ const webSocket = webSocketContainer.webSocket;
8148
+ assert3(webSocket, webSocketUndefinedError);
8149
+ webSocket.send(JSON.stringify(payload));
8150
+ }
8151
+ };
8152
+ function onMessage(event) {
8153
+ const payload = JSON.parse(event.data.toString());
8154
+ const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
8155
+ for (const listener of listeners) {
8156
+ listener(payload.data, client);
8157
+ }
8158
+ }
8159
+ return {
8160
+ send(payload) {
8161
+ const webSocket = webSocketContainer.webSocket;
8162
+ assert3(webSocket, webSocketUndefinedError);
8163
+ webSocket.send(JSON.stringify(payload));
8164
+ },
8165
+ on(event, listener) {
8166
+ const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
8167
+ listeners.add(listener);
8168
+ listenersMap.set(event, listeners);
8169
+ },
8170
+ off(event, listener) {
8171
+ listenersMap.get(event)?.delete(listener);
8172
+ },
8173
+ listen() {
8174
+ const webSocket = webSocketContainer.webSocket;
8175
+ assert3(webSocket, webSocketUndefinedError);
8176
+ webSocket.addEventListener("message", onMessage);
8177
+ },
8178
+ close() {
8179
+ const webSocket = webSocketContainer.webSocket;
8180
+ assert3(webSocket, webSocketUndefinedError);
8181
+ webSocket.removeEventListener("message", onMessage);
8182
+ }
8183
+ };
8426
8184
  }
8427
- function packageImportsResolve(name2, base, conditions) {
8428
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8429
- const reason = "is not a valid internal imports specifier name";
8430
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
8185
+ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
8186
+ #webSocketContainer;
8187
+ #worker;
8188
+ constructor(name2, config) {
8189
+ const webSocketContainer = {};
8190
+ super(name2, config, {
8191
+ hot: true,
8192
+ transport: createHotChannel(webSocketContainer)
8193
+ });
8194
+ this.#webSocketContainer = webSocketContainer;
8431
8195
  }
8432
- let packageJsonUrl;
8433
- const packageConfig = getPackageScopeConfig(base);
8434
- if (packageConfig.exists) {
8435
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8436
- const imports = packageConfig.imports;
8437
- if (imports) {
8438
- if (own.call(imports, name2) && !name2.includes("*")) {
8439
- const resolveResult = resolvePackageTarget(
8440
- packageJsonUrl,
8441
- imports[name2],
8442
- "",
8443
- name2,
8444
- base,
8445
- false,
8446
- true,
8447
- false,
8448
- conditions
8449
- );
8450
- if (resolveResult !== null && resolveResult !== void 0) {
8451
- return resolveResult;
8452
- }
8453
- } else {
8454
- let bestMatch = "";
8455
- let bestMatchSubpath = "";
8456
- const keys = Object.getOwnPropertyNames(imports);
8457
- let i = -1;
8458
- while (++i < keys.length) {
8459
- const key = keys[i];
8460
- const patternIndex = key.indexOf("*");
8461
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8462
- const patternTrailer = key.slice(patternIndex + 1);
8463
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8464
- bestMatch = key;
8465
- bestMatchSubpath = name2.slice(
8466
- patternIndex,
8467
- name2.length - patternTrailer.length
8468
- );
8469
- }
8470
- }
8471
- }
8472
- if (bestMatch) {
8473
- const target = imports[bestMatch];
8474
- const resolveResult = resolvePackageTarget(
8475
- packageJsonUrl,
8476
- target,
8477
- bestMatchSubpath,
8478
- bestMatch,
8479
- base,
8480
- true,
8481
- true,
8482
- false,
8483
- conditions
8484
- );
8485
- if (resolveResult !== null && resolveResult !== void 0) {
8486
- return resolveResult;
8487
- }
8196
+ async initRunner(worker, root, workerConfig) {
8197
+ this.#worker = worker;
8198
+ const response = await this.#worker.fetch(
8199
+ new URL(INIT_PATH, UNKNOWN_HOST),
8200
+ {
8201
+ headers: {
8202
+ [VITE_DEV_METADATA_HEADER]: JSON.stringify({
8203
+ root,
8204
+ entryPath: workerConfig.main
8205
+ }),
8206
+ upgrade: "websocket"
8488
8207
  }
8489
8208
  }
8490
- }
8491
- }
8492
- throw importNotDefined(name2, packageJsonUrl, base);
8209
+ );
8210
+ assert3(
8211
+ response.ok,
8212
+ `Failed to initialize module runner, error: ${await response.text()}`
8213
+ );
8214
+ const webSocket = response.webSocket;
8215
+ assert3(webSocket, "Failed to establish WebSocket");
8216
+ webSocket.accept();
8217
+ this.#webSocketContainer.webSocket = webSocket;
8218
+ }
8219
+ };
8220
+ var cloudflareBuiltInModules = [
8221
+ "cloudflare:email",
8222
+ "cloudflare:sockets",
8223
+ "cloudflare:workers",
8224
+ "cloudflare:workflows"
8225
+ ];
8226
+ var defaultConditions = ["workerd", "module", "browser"];
8227
+ var target = "es2022";
8228
+ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
8229
+ return {
8230
+ resolve: {
8231
+ // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
8232
+ // dependencies as not external
8233
+ noExternal: true,
8234
+ // We want to use `workerd` package exports if available (e.g. for postgres).
8235
+ conditions: [...defaultConditions, "development|production"],
8236
+ // The Cloudflare ones are proper builtins in the environment
8237
+ builtins: [...cloudflareBuiltInModules]
8238
+ },
8239
+ dev: {
8240
+ createEnvironment(name2, config) {
8241
+ return new CloudflareDevEnvironment(name2, config);
8242
+ }
8243
+ },
8244
+ build: {
8245
+ createEnvironment(name2, config) {
8246
+ return new vite2.BuildEnvironment(name2, config);
8247
+ },
8248
+ target,
8249
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
8250
+ emitAssets: true,
8251
+ outDir: getOutputDirectory(userConfig, environmentName),
8252
+ copyPublicDir: false,
8253
+ ssr: true,
8254
+ rollupOptions: {
8255
+ // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
8256
+ // so the input value here serves both as the build input as well as the starting point for
8257
+ // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
8258
+ // optimizeDeps.entries in the dev config)
8259
+ input: workerConfig.main
8260
+ }
8261
+ },
8262
+ optimizeDeps: {
8263
+ // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
8264
+ noDiscovery: false,
8265
+ entries: workerConfig.main,
8266
+ exclude: [...cloudflareBuiltInModules],
8267
+ esbuildOptions: {
8268
+ platform: "neutral",
8269
+ target,
8270
+ conditions: [...defaultConditions, "development"],
8271
+ resolveExtensions: [
8272
+ ".mjs",
8273
+ ".js",
8274
+ ".mts",
8275
+ ".ts",
8276
+ ".jsx",
8277
+ ".tsx",
8278
+ ".json",
8279
+ ".cjs",
8280
+ ".cts",
8281
+ ".ctx"
8282
+ ]
8283
+ }
8284
+ },
8285
+ // if nodeCompat is enabled then let's keep the real process.env so that workerd can manipulate it
8286
+ keepProcessEnv: isNodeCompat(workerConfig)
8287
+ };
8493
8288
  }
8494
- function parsePackageName(specifier, base) {
8495
- let separatorIndex = specifier.indexOf("/");
8496
- let validPackageName = true;
8497
- let isScoped = false;
8498
- if (specifier[0] === "@") {
8499
- isScoped = true;
8500
- if (separatorIndex === -1 || specifier.length === 0) {
8501
- validPackageName = false;
8502
- } else {
8503
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
8504
- }
8505
- }
8506
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8507
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8508
- validPackageName = false;
8509
- }
8510
- if (!validPackageName) {
8511
- throw new ERR_INVALID_MODULE_SPECIFIER(
8512
- specifier,
8513
- "is not a valid package name",
8514
- fileURLToPath$1(base)
8515
- );
8289
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8290
+ if (resolvedPluginConfig.type === "assets-only") {
8291
+ return;
8516
8292
  }
8517
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8518
- return { packageName, packageSubpath, isScoped };
8293
+ return Promise.all(
8294
+ Object.entries(resolvedPluginConfig.workers).map(
8295
+ async ([environmentName, workerConfig]) => {
8296
+ const worker = await miniflare.getWorker(workerConfig.name);
8297
+ return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
8298
+ }
8299
+ )
8300
+ );
8519
8301
  }
8520
- function packageResolve(specifier, base, conditions) {
8521
- if (builtinModules.includes(specifier)) {
8522
- return new URL$1("node:" + specifier);
8523
- }
8524
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8525
- specifier,
8526
- base
8302
+
8303
+ // src/deploy-config.ts
8304
+ import assert4 from "node:assert";
8305
+ import * as fs2 from "node:fs";
8306
+ import * as path3 from "node:path";
8307
+ import "vite";
8308
+ function getDeployConfigPath(root) {
8309
+ return path3.resolve(root, ".wrangler", "deploy", "config.json");
8310
+ }
8311
+ function getWorkerConfigPaths(root) {
8312
+ const deployConfigPath = getDeployConfigPath(root);
8313
+ const deployConfig = JSON.parse(
8314
+ fs2.readFileSync(deployConfigPath, "utf-8")
8527
8315
  );
8528
- const packageConfig = getPackageScopeConfig(base);
8529
- if (packageConfig.exists) {
8530
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8531
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8532
- return packageExportsResolve(
8533
- packageJsonUrl2,
8534
- packageSubpath,
8535
- packageConfig,
8536
- base,
8537
- conditions
8538
- );
8539
- }
8540
- }
8541
- let packageJsonUrl = new URL$1(
8542
- "./node_modules/" + packageName + "/package.json",
8543
- base
8316
+ return [
8317
+ { configPath: deployConfig.configPath },
8318
+ ...deployConfig.auxiliaryWorkers
8319
+ ].map(
8320
+ ({ configPath }) => path3.resolve(path3.dirname(deployConfigPath), configPath)
8544
8321
  );
8545
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8546
- let lastPath;
8547
- do {
8548
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8549
- if (!stat || !stat.isDirectory()) {
8550
- lastPath = packageJsonPath;
8551
- packageJsonUrl = new URL$1(
8552
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8553
- packageJsonUrl
8554
- );
8555
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8556
- continue;
8557
- }
8558
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8559
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8560
- return packageExportsResolve(
8561
- packageJsonUrl,
8562
- packageSubpath,
8563
- packageConfig2,
8564
- base,
8565
- conditions
8566
- );
8567
- }
8568
- if (packageSubpath === ".") {
8569
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8570
- }
8571
- return new URL$1(packageSubpath, packageJsonUrl);
8572
- } while (packageJsonPath.length !== lastPath.length);
8573
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8574
- }
8575
- function isRelativeSpecifier(specifier) {
8576
- if (specifier[0] === ".") {
8577
- if (specifier.length === 1 || specifier[1] === "/") return true;
8578
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8579
- return true;
8580
- }
8581
- }
8582
- return false;
8583
8322
  }
8584
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8585
- if (specifier === "") return false;
8586
- if (specifier[0] === "/") return true;
8587
- return isRelativeSpecifier(specifier);
8323
+ function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
8324
+ return path3.relative(
8325
+ deployConfigDirectory,
8326
+ path3.resolve(root, outputDirectory, "wrangler.json")
8327
+ );
8588
8328
  }
8589
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8590
- const protocol = base.protocol;
8591
- const isData = protocol === "data:";
8592
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8593
- let resolved;
8594
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8595
- try {
8596
- resolved = new URL$1(specifier, base);
8597
- } catch (error_) {
8598
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8599
- error.cause = error_;
8600
- throw error;
8601
- }
8602
- } else if (protocol === "file:" && specifier[0] === "#") {
8603
- resolved = packageImportsResolve(specifier, base, conditions);
8329
+ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
8330
+ const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
8331
+ const deployConfigDirectory = path3.dirname(deployConfigPath);
8332
+ fs2.mkdirSync(deployConfigDirectory, { recursive: true });
8333
+ if (resolvedPluginConfig.type === "assets-only") {
8334
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
8335
+ assert4(
8336
+ clientOutputDirectory,
8337
+ "Unexpected error: client environment output directory is undefined"
8338
+ );
8339
+ const deployConfig = {
8340
+ configPath: getRelativePathToWorkerConfig(
8341
+ deployConfigDirectory,
8342
+ resolvedViteConfig.root,
8343
+ clientOutputDirectory
8344
+ ),
8345
+ auxiliaryWorkers: []
8346
+ };
8347
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8604
8348
  } else {
8605
- try {
8606
- resolved = new URL$1(specifier);
8607
- } catch (error_) {
8608
- if (isRemote && !builtinModules.includes(specifier)) {
8609
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8610
- error.cause = error_;
8611
- throw error;
8349
+ let entryWorkerConfigPath;
8350
+ const auxiliaryWorkers = [];
8351
+ for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
8352
+ const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
8353
+ assert4(
8354
+ outputDirectory,
8355
+ `Unexpected error: ${environmentName} environment output directory is undefined`
8356
+ );
8357
+ const configPath = getRelativePathToWorkerConfig(
8358
+ deployConfigDirectory,
8359
+ resolvedViteConfig.root,
8360
+ outputDirectory
8361
+ );
8362
+ if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
8363
+ entryWorkerConfigPath = configPath;
8364
+ } else {
8365
+ auxiliaryWorkers.push({ configPath });
8612
8366
  }
8613
- resolved = packageResolve(specifier, base, conditions);
8614
8367
  }
8368
+ assert4(
8369
+ entryWorkerConfigPath,
8370
+ `Unexpected error: entryWorkerConfigPath is undefined`
8371
+ );
8372
+ const deployConfig = {
8373
+ configPath: entryWorkerConfigPath,
8374
+ auxiliaryWorkers
8375
+ };
8376
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8615
8377
  }
8616
- assert5(resolved !== void 0, "expected to be defined");
8617
- if (resolved.protocol !== "file:") {
8618
- return resolved;
8619
- }
8620
- return finalizeResolution(resolved, base);
8621
- }
8622
- function fileURLToPath2(id) {
8623
- if (typeof id === "string" && !id.startsWith("file://")) {
8624
- return normalizeSlash(id);
8625
- }
8626
- return normalizeSlash(fileURLToPath$1(id));
8627
8378
  }
8628
- function pathToFileURL(id) {
8629
- return pathToFileURL$1(fileURLToPath2(id)).toString();
8379
+
8380
+ // src/dev.ts
8381
+ import assert5 from "node:assert";
8382
+ function getDevEntryWorker(resolvedPluginConfig, miniflare) {
8383
+ const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8384
+ assert5(entryWorkerConfig, "Unexpected error: No entry worker configuration");
8385
+ return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
8630
8386
  }
8631
- function normalizeid(id) {
8632
- if (typeof id !== "string") {
8633
- id = id.toString();
8634
- }
8635
- if (/(node|data|http|https|file):/.test(id)) {
8636
- return id;
8637
- }
8638
- if (BUILTIN_MODULES.has(id)) {
8639
- return "node:" + id;
8387
+
8388
+ // src/miniflare-options.ts
8389
+ import assert6 from "node:assert";
8390
+ import * as fs3 from "node:fs";
8391
+ import * as fsp from "node:fs/promises";
8392
+ import * as path4 from "node:path";
8393
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
8394
+ import {
8395
+ kCurrentWorker,
8396
+ Log,
8397
+ LogLevel,
8398
+ Response as MiniflareResponse
8399
+ } from "miniflare";
8400
+ import { globSync } from "tinyglobby";
8401
+ import "vite";
8402
+ import {
8403
+ unstable_getMiniflareWorkerOptions,
8404
+ unstable_readConfig
8405
+ } from "wrangler";
8406
+ function getPersistence(root, persistState) {
8407
+ if (persistState === false) {
8408
+ return {};
8640
8409
  }
8641
- return "file://" + encodeURI(normalizeSlash(id));
8410
+ const defaultPersistPath = ".wrangler/state";
8411
+ const persistPath = path4.resolve(
8412
+ root,
8413
+ typeof persistState === "object" ? persistState.path : defaultPersistPath,
8414
+ "v3"
8415
+ );
8416
+ return {
8417
+ cachePersist: path4.join(persistPath, "cache"),
8418
+ d1Persist: path4.join(persistPath, "d1"),
8419
+ durableObjectsPersist: path4.join(persistPath, "do"),
8420
+ kvPersist: path4.join(persistPath, "kv"),
8421
+ r2Persist: path4.join(persistPath, "r2"),
8422
+ workflowsPersist: path4.join(persistPath, "workflows")
8423
+ };
8642
8424
  }
8643
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8644
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8645
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8646
- "ERR_MODULE_NOT_FOUND",
8647
- "ERR_UNSUPPORTED_DIR_IMPORT",
8648
- "MODULE_NOT_FOUND",
8649
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8650
- ]);
8651
- function _tryModuleResolve(id, url, conditions) {
8652
- try {
8653
- return moduleResolve(id, url, conditions);
8654
- } catch (error) {
8655
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8656
- throw error;
8425
+ function missingWorkerErrorMessage(workerName) {
8426
+ return `${workerName} does not match a worker name.`;
8427
+ }
8428
+ function getWorkerToWorkerEntrypointNamesMap(workers) {
8429
+ const workerToWorkerEntrypointNamesMap = new Map(
8430
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8431
+ );
8432
+ for (const worker of workers) {
8433
+ for (const value of Object.values(worker.serviceBindings ?? {})) {
8434
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
8435
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
8436
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
8437
+ assert6(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8438
+ entrypointNames.add(value.entrypoint);
8439
+ }
8657
8440
  }
8658
8441
  }
8442
+ return workerToWorkerEntrypointNamesMap;
8659
8443
  }
8660
- function _resolve(id, options = {}) {
8661
- if (typeof id !== "string") {
8662
- if (id instanceof URL) {
8663
- id = fileURLToPath2(id);
8664
- } else {
8665
- throw new TypeError("input must be a `string` or `URL`");
8444
+ function getWorkerToDurableObjectClassNamesMap(workers) {
8445
+ const workerToDurableObjectClassNamesMap = new Map(
8446
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8447
+ );
8448
+ for (const worker of workers) {
8449
+ for (const value of Object.values(worker.durableObjects ?? {})) {
8450
+ if (typeof value === "string") {
8451
+ const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
8452
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8453
+ classNames.add(value);
8454
+ } else if (typeof value === "object") {
8455
+ if (value.scriptName) {
8456
+ const classNames = workerToDurableObjectClassNamesMap.get(
8457
+ value.scriptName
8458
+ );
8459
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8460
+ classNames.add(value.className);
8461
+ } else {
8462
+ const classNames = workerToDurableObjectClassNamesMap.get(
8463
+ worker.name
8464
+ );
8465
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8466
+ classNames.add(value.className);
8467
+ }
8468
+ }
8666
8469
  }
8667
8470
  }
8668
- if (/(node|data|http|https):/.test(id)) {
8669
- return id;
8670
- }
8671
- if (BUILTIN_MODULES.has(id)) {
8672
- return "node:" + id;
8471
+ return workerToDurableObjectClassNamesMap;
8472
+ }
8473
+ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
8474
+ const workerToWorkflowEntrypointClassNamesMap = new Map(
8475
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8476
+ );
8477
+ for (const worker of workers) {
8478
+ for (const value of Object.values(worker.workflows ?? {})) {
8479
+ if (value.scriptName) {
8480
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8481
+ value.scriptName
8482
+ );
8483
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8484
+ classNames.add(value.className);
8485
+ } else {
8486
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8487
+ worker.name
8488
+ );
8489
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8490
+ classNames.add(value.className);
8491
+ }
8492
+ }
8673
8493
  }
8674
- if (id.startsWith("file://")) {
8675
- id = fileURLToPath2(id);
8494
+ return workerToWorkflowEntrypointClassNamesMap;
8495
+ }
8496
+ var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
8497
+ var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
8498
+ var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
8499
+ var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
8500
+ var RUNNER_PATH = "./runner-worker/index.js";
8501
+ function getEntryWorkerConfig(resolvedPluginConfig) {
8502
+ if (resolvedPluginConfig.type === "assets-only") {
8503
+ return;
8676
8504
  }
8677
- if (isAbsolute(id)) {
8678
- try {
8679
- const stat = statSync2(id);
8680
- if (stat.isFile()) {
8681
- return pathToFileURL(id);
8505
+ return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8506
+ }
8507
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8508
+ const resolvedViteConfig = viteDevServer.config;
8509
+ const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
8510
+ const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
8511
+ const assetWorkers = [
8512
+ {
8513
+ name: ROUTER_WORKER_NAME,
8514
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8515
+ modulesRoot: miniflareModulesRoot,
8516
+ modules: [
8517
+ {
8518
+ type: "ESModule",
8519
+ path: path4.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
8520
+ contents: fs3.readFileSync(
8521
+ fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
8522
+ )
8523
+ }
8524
+ ],
8525
+ bindings: {
8526
+ CONFIG: {
8527
+ has_user_worker: resolvedPluginConfig.type === "workers"
8528
+ }
8529
+ },
8530
+ serviceBindings: {
8531
+ ASSET_WORKER: ASSET_WORKER_NAME,
8532
+ ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
8682
8533
  }
8683
- } catch (error) {
8684
- if (error?.code !== "ENOENT") {
8685
- throw error;
8534
+ },
8535
+ {
8536
+ name: ASSET_WORKER_NAME,
8537
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8538
+ modulesRoot: miniflareModulesRoot,
8539
+ modules: [
8540
+ {
8541
+ type: "ESModule",
8542
+ path: path4.join(miniflareModulesRoot, ASSET_WORKER_PATH),
8543
+ contents: fs3.readFileSync(
8544
+ fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
8545
+ )
8546
+ }
8547
+ ],
8548
+ bindings: {
8549
+ CONFIG: {
8550
+ ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
8551
+ ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
8552
+ }
8553
+ },
8554
+ serviceBindings: {
8555
+ __VITE_ASSET_EXISTS__: async (request) => {
8556
+ const { pathname } = new URL(request.url);
8557
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8558
+ let exists;
8559
+ try {
8560
+ exists = fs3.statSync(filePath).isFile();
8561
+ } catch (error) {
8562
+ exists = false;
8563
+ }
8564
+ return MiniflareResponse.json(exists);
8565
+ },
8566
+ __VITE_FETCH_ASSET__: async (request) => {
8567
+ const { pathname } = new URL(request.url);
8568
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8569
+ try {
8570
+ let html = await fsp.readFile(filePath, "utf-8");
8571
+ html = await viteDevServer.transformIndexHtml(pathname, html);
8572
+ return new MiniflareResponse(html, {
8573
+ headers: { "Content-Type": "text/html" }
8574
+ });
8575
+ } catch (error) {
8576
+ throw new Error(`Unexpected error. Failed to load ${pathname}`);
8577
+ }
8578
+ }
8686
8579
  }
8687
8580
  }
8688
- }
8689
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8690
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8691
- if (_urls.length === 0) {
8692
- _urls.push(new URL(pathToFileURL(process.cwd())));
8693
- }
8694
- const urls = [..._urls];
8695
- for (const url of _urls) {
8696
- if (url.protocol === "file:") {
8697
- urls.push(
8698
- new URL("./", url),
8699
- // If url is directory
8700
- new URL(joinURL(url.pathname, "_index.js"), url),
8701
- // TODO: Remove in next major version?
8702
- new URL("node_modules", url)
8581
+ ];
8582
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
8583
+ ([environmentName, workerConfig]) => {
8584
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
8585
+ {
8586
+ ...workerConfig,
8587
+ assets: void 0
8588
+ },
8589
+ resolvedPluginConfig.cloudflareEnv
8703
8590
  );
8591
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
8592
+ const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8593
+ return {
8594
+ externalWorkers: externalWorkers2,
8595
+ worker: {
8596
+ ...workerOptions,
8597
+ name: workerOptions.name ?? workerConfig.name,
8598
+ modulesRoot: miniflareModulesRoot,
8599
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
8600
+ serviceBindings: {
8601
+ ...workerOptions.serviceBindings,
8602
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
8603
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
8604
+ } : {},
8605
+ __VITE_INVOKE_MODULE__: async (request) => {
8606
+ const payload = await request.json();
8607
+ const invokePayloadData = payload.data;
8608
+ assert6(
8609
+ invokePayloadData.name === "fetchModule",
8610
+ `Invalid invoke event: ${invokePayloadData.name}`
8611
+ );
8612
+ const [moduleId] = invokePayloadData.data;
8613
+ const moduleRE = new RegExp(MODULE_PATTERN);
8614
+ const shouldExternalize = (
8615
+ // Worker modules (CompiledWasm, Text, Data)
8616
+ moduleRE.test(moduleId)
8617
+ );
8618
+ if (shouldExternalize) {
8619
+ const result2 = {
8620
+ externalize: moduleId,
8621
+ type: "module"
8622
+ };
8623
+ return MiniflareResponse.json({ result: result2 });
8624
+ }
8625
+ const devEnvironment = viteDevServer.environments[environmentName];
8626
+ const result = await devEnvironment.hot.handleInvoke(payload);
8627
+ return MiniflareResponse.json(result);
8628
+ }
8629
+ }
8630
+ }
8631
+ };
8704
8632
  }
8705
- }
8706
- let resolved;
8707
- for (const url of urls) {
8708
- resolved = _tryModuleResolve(id, url, conditionsSet);
8709
- if (resolved) {
8710
- break;
8711
- }
8712
- for (const prefix of ["", "/index"]) {
8713
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8714
- resolved = _tryModuleResolve(
8715
- joinURL(id, prefix) + extension,
8716
- url,
8717
- conditionsSet
8633
+ ) : [];
8634
+ const userWorkers = workersFromConfig.map((options) => options.worker);
8635
+ const externalWorkers = workersFromConfig.flatMap(
8636
+ (options) => options.externalWorkers
8637
+ );
8638
+ const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
8639
+ const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
8640
+ const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
8641
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8642
+ return {
8643
+ log: logger,
8644
+ handleRuntimeStdio(stdout, stderr) {
8645
+ const decoder = new TextDecoder();
8646
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8647
+ stderr.forEach(
8648
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8649
+ );
8650
+ },
8651
+ ...getPersistence(
8652
+ resolvedViteConfig.root,
8653
+ resolvedPluginConfig.persistState
8654
+ ),
8655
+ workers: [
8656
+ ...assetWorkers,
8657
+ ...externalWorkers,
8658
+ ...userWorkers.map((workerOptions) => {
8659
+ const wrappers = [
8660
+ `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
8661
+ `export default createWorkerEntrypointWrapper('default');`
8662
+ ];
8663
+ const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
8664
+ workerOptions.name
8665
+ );
8666
+ assert6(
8667
+ workerEntrypointNames,
8668
+ `WorkerEntrypoint names not found for worker ${workerOptions.name}`
8669
+ );
8670
+ for (const entrypointName of [...workerEntrypointNames].sort()) {
8671
+ wrappers.push(
8672
+ `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
8673
+ );
8674
+ }
8675
+ const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8676
+ workerOptions.name
8718
8677
  );
8719
- if (resolved) {
8720
- break;
8678
+ assert6(
8679
+ durableObjectClassNames,
8680
+ `DurableObject class names not found for worker ${workerOptions.name}`
8681
+ );
8682
+ for (const className of [...durableObjectClassNames].sort()) {
8683
+ wrappers.push(
8684
+ `export const ${className} = createDurableObjectWrapper('${className}');`
8685
+ );
8721
8686
  }
8687
+ const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
8688
+ assert6(
8689
+ workflowEntrypointClassNames,
8690
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
8691
+ );
8692
+ for (const className of [...workflowEntrypointClassNames].sort()) {
8693
+ wrappers.push(
8694
+ `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
8695
+ );
8696
+ }
8697
+ return {
8698
+ ...workerOptions,
8699
+ modules: [
8700
+ {
8701
+ type: "ESModule",
8702
+ path: path4.join(miniflareModulesRoot, WRAPPER_PATH),
8703
+ contents: wrappers.join("\n")
8704
+ },
8705
+ {
8706
+ type: "ESModule",
8707
+ path: path4.join(miniflareModulesRoot, RUNNER_PATH),
8708
+ contents: fs3.readFileSync(
8709
+ fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
8710
+ )
8711
+ }
8712
+ ],
8713
+ unsafeUseModuleFallbackService: true
8714
+ };
8715
+ })
8716
+ ],
8717
+ unsafeModuleFallbackService(request) {
8718
+ const url = new URL(request.url);
8719
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
8720
+ assert6(
8721
+ rawSpecifier,
8722
+ `Unexpected error: no specifier in request to module fallback service.`
8723
+ );
8724
+ const moduleRE = new RegExp(MODULE_PATTERN);
8725
+ const match = moduleRE.exec(rawSpecifier);
8726
+ assert6(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8727
+ const [full, moduleType, modulePath] = match;
8728
+ assert6(
8729
+ modulePath,
8730
+ `Unexpected error: module path not found in reference: ${full}.`
8731
+ );
8732
+ let source;
8733
+ try {
8734
+ source = fs3.readFileSync(modulePath);
8735
+ } catch (error) {
8736
+ throw new Error(
8737
+ `Import "${modulePath}" not found. Does the file exist?`
8738
+ );
8722
8739
  }
8723
- if (resolved) {
8724
- break;
8725
- }
8726
- }
8727
- if (resolved) {
8728
- break;
8740
+ return MiniflareResponse.json({
8741
+ // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
8742
+ wasm: Array.from(source)
8743
+ });
8729
8744
  }
8730
- }
8731
- if (!resolved) {
8732
- const error = new Error(
8733
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8734
- );
8735
- error.code = "ERR_MODULE_NOT_FOUND";
8736
- throw error;
8737
- }
8738
- return pathToFileURL(resolved);
8739
- }
8740
- function resolveSync(id, options) {
8741
- return _resolve(id, options);
8742
- }
8743
- function resolvePathSync(id, options) {
8744
- return fileURLToPath2(resolveSync(id, options));
8745
+ };
8745
8746
  }
8746
-
8747
- // src/node-js-compat.ts
8748
- import { defineEnv } from "unenv";
8749
- var { env } = defineEnv({
8750
- nodeCompat: true,
8751
- presets: [cloudflare]
8752
- });
8753
- var nodeCompatExternals = new Set(env.external);
8754
- var nodeCompatEntries = getNodeCompatEntries();
8755
- function isNodeCompat(workerConfig) {
8756
- if (workerConfig === void 0) {
8757
- return false;
8758
- }
8759
- const nodeCompatMode = getNodeCompat(
8760
- workerConfig.compatibility_date,
8761
- workerConfig.compatibility_flags ?? []
8762
- ).mode;
8763
- if (nodeCompatMode === "v2") {
8764
- return true;
8765
- }
8766
- if (nodeCompatMode === "v1") {
8767
- throw new Error(
8768
- `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`
8769
- );
8770
- }
8771
- return false;
8747
+ function getPreviewModules(main, modulesRules) {
8748
+ assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8749
+ const rootPath = path4.dirname(main);
8750
+ const entryPath = path4.basename(main);
8751
+ return {
8752
+ rootPath,
8753
+ modules: [
8754
+ {
8755
+ type: "ESModule",
8756
+ path: entryPath
8757
+ },
8758
+ ...modulesRules.flatMap(
8759
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
8760
+ type,
8761
+ path: path8
8762
+ }))
8763
+ )
8764
+ ]
8765
+ };
8772
8766
  }
8773
- function injectGlobalCode(id, code) {
8774
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8775
- if (typeof globalInject === "string") {
8776
- const moduleSpecifier2 = globalInject;
8777
- return `import var_${globalName} from "${moduleSpecifier2}";
8778
- globalThis.${globalName} = var_${globalName};
8779
- `;
8780
- }
8781
- const [moduleSpecifier, exportName] = globalInject;
8782
- assert6(
8783
- moduleSpecifier !== void 0,
8784
- "Expected moduleSpecifier to be defined"
8785
- );
8786
- assert6(exportName !== void 0, "Expected exportName to be defined");
8787
- return `import var_${globalName} from "${moduleSpecifier}";
8788
- globalThis.${globalName} = var_${globalName}.${exportName};
8789
- `;
8790
- }).join("\n");
8791
- const modified = new MagicString(code);
8792
- modified.prepend(injectedCode);
8767
+ function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
8768
+ const resolvedViteConfig = vitePreviewServer.config;
8769
+ const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
8770
+ const workerConfigs = configPaths.map(
8771
+ (configPath) => unstable_readConfig({ config: configPath })
8772
+ );
8773
+ const workers = workerConfigs.flatMap((config) => {
8774
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
8775
+ const { externalWorkers } = miniflareWorkerOptions;
8776
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8777
+ return [
8778
+ {
8779
+ ...workerOptions,
8780
+ name: workerOptions.name ?? config.name,
8781
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
8782
+ },
8783
+ ...externalWorkers
8784
+ ];
8785
+ });
8786
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8793
8787
  return {
8794
- code: modified.toString(),
8795
- map: modified.generateMap({ hires: "boundary", source: id })
8788
+ log: logger,
8789
+ handleRuntimeStdio(stdout, stderr) {
8790
+ const decoder = new TextDecoder();
8791
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8792
+ stderr.forEach(
8793
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8794
+ );
8795
+ },
8796
+ ...getPersistence(resolvedViteConfig.root, persistState),
8797
+ workers
8796
8798
  };
8797
8799
  }
8798
- function resolveNodeJSImport(source) {
8799
- const alias = env.alias[source];
8800
- if (alias) {
8801
- return {
8802
- unresolved: alias,
8803
- resolved: resolvePathSync(alias, { url: import.meta.url })
8804
- };
8805
- }
8806
- if (nodeCompatEntries.has(source)) {
8807
- return {
8808
- unresolved: source,
8809
- resolved: resolvePathSync(source, { url: import.meta.url })
8810
- };
8800
+ var ViteMiniflareLogger = class extends Log {
8801
+ logger;
8802
+ constructor(config) {
8803
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8804
+ this.logger = config.logger;
8811
8805
  }
8812
- }
8813
- function getNodeCompatEntries() {
8814
- const entries = new Set(Object.values(env.alias));
8815
- for (const globalInject of Object.values(env.inject)) {
8816
- if (typeof globalInject === "string") {
8817
- entries.add(globalInject);
8818
- } else {
8819
- assert6(
8820
- globalInject[0] !== void 0,
8821
- "Expected first element of globalInject to be defined"
8822
- );
8823
- entries.add(globalInject[0]);
8806
+ logWithLevel(level, message) {
8807
+ if (/^Ready on http/.test(message)) {
8808
+ level = LogLevel.DEBUG;
8809
+ }
8810
+ switch (level) {
8811
+ case LogLevel.ERROR:
8812
+ return this.logger.error(message);
8813
+ case LogLevel.WARN:
8814
+ return this.logger.warn(message);
8815
+ case LogLevel.INFO:
8816
+ return this.logger.info(message);
8824
8817
  }
8825
8818
  }
8826
- nodeCompatExternals.forEach((external) => entries.delete(external));
8827
- return entries;
8819
+ };
8820
+ function miniflareLogLevelFromViteLogLevel(level = "info") {
8821
+ switch (level) {
8822
+ case "error":
8823
+ return LogLevel.ERROR;
8824
+ case "warn":
8825
+ return LogLevel.WARN;
8826
+ case "info":
8827
+ return LogLevel.INFO;
8828
+ case "silent":
8829
+ return LogLevel.NONE;
8830
+ }
8828
8831
  }
8829
8832
 
8830
8833
  // src/plugin-config.ts
@@ -9035,6 +9038,17 @@ function getWorkerConfig(configPath, env2, opts) {
9035
9038
  };
9036
9039
  }
9037
9040
  assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9041
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9042
+ if (!mainStat) {
9043
+ throw new Error(
9044
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9045
+ );
9046
+ }
9047
+ if (mainStat.isDirectory()) {
9048
+ throw new Error(
9049
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9050
+ );
9051
+ }
9038
9052
  return {
9039
9053
  type: "worker",
9040
9054
  raw,
@@ -9135,8 +9149,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9135
9149
  }
9136
9150
 
9137
9151
  // src/websockets.ts
9152
+ import { coupleWebSocket } from "miniflare";
9138
9153
  import { WebSocketServer } from "ws";
9139
- function handleWebSocket(httpServer, fetcher, logger) {
9154
+ function handleWebSocket(httpServer, fetcher) {
9140
9155
  const nodeWebSocket = new WebSocketServer({ noServer: true });
9141
9156
  httpServer.on(
9142
9157
  "upgrade",
@@ -9160,34 +9175,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9160
9175
  socket,
9161
9176
  head,
9162
9177
  async (clientWebSocket) => {
9163
- workerWebSocket.accept();
9164
- workerWebSocket.addEventListener("message", (event) => {
9165
- clientWebSocket.send(event.data);
9166
- });
9167
- workerWebSocket.addEventListener("error", (event) => {
9168
- logger.error(
9169
- `WebSocket error:
9170
- ${event.error?.stack || event.error?.message}`,
9171
- { error: event.error }
9172
- );
9173
- });
9174
- workerWebSocket.addEventListener("close", () => {
9175
- clientWebSocket.close();
9176
- });
9177
- clientWebSocket.on("message", (data2, isBinary) => {
9178
- workerWebSocket.send(
9179
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9180
- );
9181
- });
9182
- clientWebSocket.on("error", (error) => {
9183
- logger.error(`WebSocket error:
9184
- ${error.stack || error.message}`, {
9185
- error
9186
- });
9187
- });
9188
- clientWebSocket.on("close", () => {
9189
- workerWebSocket.close();
9190
- });
9178
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9191
9179
  nodeWebSocket.emit("connection", clientWebSocket, request);
9192
9180
  }
9193
9181
  );
@@ -9380,11 +9368,7 @@ function cloudflare2(pluginConfig = {}) {
9380
9368
  },
9381
9369
  { alwaysCallNext: false }
9382
9370
  );
9383
- handleWebSocket(
9384
- viteDevServer.httpServer,
9385
- entryWorker.fetch,
9386
- viteDevServer.config.logger
9387
- );
9371
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9388
9372
  return () => {
9389
9373
  viteDevServer.middlewares.use((req, res, next) => {
9390
9374
  middleware(req, res, next);
@@ -9406,16 +9390,10 @@ function cloudflare2(pluginConfig = {}) {
9406
9390
  },
9407
9391
  { alwaysCallNext: false }
9408
9392
  );
9409
- handleWebSocket(
9410
- vitePreviewServer.httpServer,
9411
- miniflare2.dispatchFetch,
9412
- vitePreviewServer.config.logger
9413
- );
9414
- return () => {
9415
- vitePreviewServer.middlewares.use((req, res, next) => {
9416
- middleware(req, res, next);
9417
- });
9418
- };
9393
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9394
+ vitePreviewServer.middlewares.use((req, res, next) => {
9395
+ middleware(req, res, next);
9396
+ });
9419
9397
  }
9420
9398
  },
9421
9399
  // Plugin to support `CompiledWasm` modules