@cloudflare/vite-plugin 0.0.0-0f3ace7fc → 0.0.0-0fe326071

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,705 +1074,11 @@ 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";
1078
- import * as vite2 from "vite";
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
- }
1120
-
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));
1130
- }
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);
1137
- }
1138
- }
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
- };
1164
- }
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;
1175
- }
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;
1194
- }
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
- };
1261
- }
1262
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
1263
- if (resolvedPluginConfig.type === "assets-only") {
1264
- return;
1265
- }
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
- );
1274
- }
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");
1283
- }
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
- );
1295
- }
1296
- function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
1297
- return path2.relative(
1298
- deployConfigDirectory,
1299
- path2.resolve(root, outputDirectory, "wrangler.json")
1300
- );
1301
- }
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
- }
1340
- }
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
- }
1351
- }
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);
1359
- }
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 { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
1368
- import "vite";
1369
- import {
1370
- unstable_getMiniflareWorkerOptions,
1371
- unstable_readConfig
1372
- } from "wrangler";
1373
- function getPersistence(root, persistState) {
1374
- if (persistState === false) {
1375
- return {};
1376
- }
1377
- const defaultPersistPath = ".wrangler/state";
1378
- const persistPath = path3.resolve(
1379
- root,
1380
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1381
- "v3"
1382
- );
1383
- return {
1384
- cachePersist: path3.join(persistPath, "cache"),
1385
- d1Persist: path3.join(persistPath, "d1"),
1386
- durableObjectsPersist: path3.join(persistPath, "do"),
1387
- kvPersist: path3.join(persistPath, "kv"),
1388
- r2Persist: path3.join(persistPath, "r2"),
1389
- workflowsPersist: path3.join(persistPath, "workflows")
1390
- };
1391
- }
1392
- function missingWorkerErrorMessage(workerName) {
1393
- return `${workerName} does not match a worker name.`;
1394
- }
1395
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1396
- const workerToWorkerEntrypointNamesMap = new Map(
1397
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1398
- );
1399
- for (const worker of workers) {
1400
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1401
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1402
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1403
- value.name
1404
- );
1405
- assert4(entrypointNames, missingWorkerErrorMessage(value.name));
1406
- entrypointNames.add(value.entrypoint);
1407
- }
1408
- }
1409
- }
1410
- return workerToWorkerEntrypointNamesMap;
1411
- }
1412
- function getWorkerToDurableObjectClassNamesMap(workers) {
1413
- const workerToDurableObjectClassNamesMap = new Map(
1414
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1415
- );
1416
- for (const worker of workers) {
1417
- for (const value of Object.values(worker.durableObjects ?? {})) {
1418
- if (typeof value === "string") {
1419
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1420
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1421
- classNames.add(value);
1422
- } else if (typeof value === "object") {
1423
- if (value.scriptName) {
1424
- const classNames = workerToDurableObjectClassNamesMap.get(
1425
- value.scriptName
1426
- );
1427
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1428
- classNames.add(value.className);
1429
- } else {
1430
- const classNames = workerToDurableObjectClassNamesMap.get(
1431
- worker.name
1432
- );
1433
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1434
- classNames.add(value.className);
1435
- }
1436
- }
1437
- }
1438
- }
1439
- return workerToDurableObjectClassNamesMap;
1440
- }
1441
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1442
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1443
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1444
- );
1445
- for (const worker of workers) {
1446
- for (const value of Object.values(worker.workflows ?? {})) {
1447
- if (value.scriptName) {
1448
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1449
- value.scriptName
1450
- );
1451
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1452
- classNames.add(value.className);
1453
- } else {
1454
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1455
- worker.name
1456
- );
1457
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1458
- classNames.add(value.className);
1459
- }
1460
- }
1461
- }
1462
- return workerToWorkflowEntrypointClassNamesMap;
1463
- }
1464
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1465
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1466
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1467
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1468
- var RUNNER_PATH = "./runner-worker/index.js";
1469
- function getEntryWorkerConfig(resolvedPluginConfig) {
1470
- if (resolvedPluginConfig.type === "assets-only") {
1471
- return;
1472
- }
1473
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1474
- }
1475
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1476
- const resolvedViteConfig = viteDevServer.config;
1477
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1478
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1479
- const assetWorkers = [
1480
- {
1481
- name: ROUTER_WORKER_NAME,
1482
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1483
- modulesRoot: miniflareModulesRoot,
1484
- modules: [
1485
- {
1486
- type: "ESModule",
1487
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1488
- contents: fs2.readFileSync(
1489
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1490
- )
1491
- }
1492
- ],
1493
- bindings: {
1494
- CONFIG: {
1495
- has_user_worker: resolvedPluginConfig.type === "workers"
1496
- }
1497
- },
1498
- serviceBindings: {
1499
- ASSET_WORKER: ASSET_WORKER_NAME,
1500
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1501
- }
1502
- },
1503
- {
1504
- name: ASSET_WORKER_NAME,
1505
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1506
- modulesRoot: miniflareModulesRoot,
1507
- modules: [
1508
- {
1509
- type: "ESModule",
1510
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1511
- contents: fs2.readFileSync(
1512
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1513
- )
1514
- }
1515
- ],
1516
- bindings: {
1517
- CONFIG: {
1518
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1519
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1520
- }
1521
- },
1522
- serviceBindings: {
1523
- __VITE_ASSET_EXISTS__: async (request) => {
1524
- const { pathname } = new URL(request.url);
1525
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1526
- let exists;
1527
- try {
1528
- exists = fs2.statSync(filePath).isFile();
1529
- } catch (error) {
1530
- exists = false;
1531
- }
1532
- return MiniflareResponse.json(exists);
1533
- },
1534
- __VITE_FETCH_ASSET__: async (request) => {
1535
- const { pathname } = new URL(request.url);
1536
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1537
- try {
1538
- let html = await fsp.readFile(filePath, "utf-8");
1539
- html = await viteDevServer.transformIndexHtml(pathname, html);
1540
- return new MiniflareResponse(html, {
1541
- headers: { "Content-Type": "text/html" }
1542
- });
1543
- } catch (error) {
1544
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1545
- }
1546
- }
1547
- }
1548
- }
1549
- ];
1550
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1551
- ([environmentName, workerConfig]) => {
1552
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1553
- {
1554
- ...workerConfig,
1555
- assets: void 0
1556
- },
1557
- resolvedPluginConfig.cloudflareEnv
1558
- );
1559
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1560
- return {
1561
- ...workerOptions,
1562
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1563
- name: workerConfig.name,
1564
- modulesRoot: miniflareModulesRoot,
1565
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1566
- bindings: {
1567
- ...workerOptions.bindings,
1568
- __VITE_ROOT__: resolvedViteConfig.root,
1569
- __VITE_ENTRY_PATH__: workerConfig.main
1570
- },
1571
- serviceBindings: {
1572
- ...workerOptions.serviceBindings,
1573
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1574
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1575
- } : {},
1576
- __VITE_INVOKE_MODULE__: async (request) => {
1577
- const payload = await request.json();
1578
- const invokePayloadData = payload.data;
1579
- assert4(
1580
- invokePayloadData.name === "fetchModule",
1581
- `Invalid invoke event: ${invokePayloadData.name}`
1582
- );
1583
- const [moduleId] = invokePayloadData.data;
1584
- const moduleRE = new RegExp(MODULE_PATTERN);
1585
- const shouldExternalize = (
1586
- // Worker modules (CompiledWasm, Text, Data)
1587
- moduleRE.test(moduleId)
1588
- );
1589
- if (shouldExternalize) {
1590
- const result2 = {
1591
- externalize: moduleId,
1592
- type: "module"
1593
- };
1594
- return MiniflareResponse.json({ result: result2 });
1595
- }
1596
- const devEnvironment = viteDevServer.environments[environmentName];
1597
- const result = await devEnvironment.hot.handleInvoke(payload);
1598
- return MiniflareResponse.json(result);
1599
- }
1600
- }
1601
- };
1602
- }
1603
- ) : [];
1604
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1605
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1606
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1607
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1608
- return {
1609
- log: logger,
1610
- handleRuntimeStdio(stdout, stderr) {
1611
- const decoder = new TextDecoder();
1612
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1613
- stderr.forEach(
1614
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1615
- );
1616
- },
1617
- ...getPersistence(
1618
- resolvedViteConfig.root,
1619
- resolvedPluginConfig.persistState
1620
- ),
1621
- workers: [
1622
- ...assetWorkers,
1623
- ...userWorkers.map((workerOptions) => {
1624
- const wrappers = [
1625
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1626
- `export default createWorkerEntrypointWrapper('default');`
1627
- ];
1628
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1629
- workerOptions.name
1630
- );
1631
- assert4(
1632
- workerEntrypointNames,
1633
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1634
- );
1635
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1636
- wrappers.push(
1637
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1638
- );
1639
- }
1640
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1641
- workerOptions.name
1642
- );
1643
- assert4(
1644
- durableObjectClassNames,
1645
- `DurableObject class names not found for worker ${workerOptions.name}`
1646
- );
1647
- for (const className of [...durableObjectClassNames].sort()) {
1648
- wrappers.push(
1649
- `export const ${className} = createDurableObjectWrapper('${className}');`
1650
- );
1651
- }
1652
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1653
- assert4(
1654
- workflowEntrypointClassNames,
1655
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1656
- );
1657
- for (const className of [...workflowEntrypointClassNames].sort()) {
1658
- wrappers.push(
1659
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1660
- );
1661
- }
1662
- return {
1663
- ...workerOptions,
1664
- modules: [
1665
- {
1666
- type: "ESModule",
1667
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1668
- contents: wrappers.join("\n")
1669
- },
1670
- {
1671
- type: "ESModule",
1672
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1673
- contents: fs2.readFileSync(
1674
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1675
- )
1676
- }
1677
- ],
1678
- unsafeUseModuleFallbackService: true
1679
- };
1680
- })
1681
- ],
1682
- unsafeModuleFallbackService(request) {
1683
- const url = new URL(request.url);
1684
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1685
- assert4(
1686
- rawSpecifier,
1687
- `Unexpected error: no specifier in request to module fallback service.`
1688
- );
1689
- const moduleRE = new RegExp(MODULE_PATTERN);
1690
- const match = moduleRE.exec(rawSpecifier);
1691
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1692
- const [full, moduleType, modulePath] = match;
1693
- assert4(
1694
- modulePath,
1695
- `Unexpected error: module path not found in reference ${full}.`
1696
- );
1697
- let source;
1698
- try {
1699
- source = fs2.readFileSync(modulePath);
1700
- } catch (error) {
1701
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1702
- }
1703
- return MiniflareResponse.json({
1704
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1705
- wasm: Array.from(source)
1706
- });
1707
- }
1708
- };
1709
- }
1710
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1711
- const resolvedViteConfig = vitePreviewServer.config;
1712
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1713
- const workerConfigs = configPaths.map(
1714
- (configPath) => unstable_readConfig({ config: configPath })
1715
- );
1716
- const workers = workerConfigs.map((config) => {
1717
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1718
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1719
- return {
1720
- ...workerOptions,
1721
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1722
- name: config.name,
1723
- modules: true,
1724
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1725
- };
1726
- });
1727
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1728
- return {
1729
- log: logger,
1730
- handleRuntimeStdio(stdout, stderr) {
1731
- const decoder = new TextDecoder();
1732
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1733
- stderr.forEach(
1734
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1735
- );
1736
- },
1737
- ...getPersistence(resolvedViteConfig.root, persistState),
1738
- workers
1739
- };
1740
- }
1741
- var ViteMiniflareLogger = class extends Log {
1742
- logger;
1743
- constructor(config) {
1744
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1745
- this.logger = config.logger;
1746
- }
1747
- logWithLevel(level, message) {
1748
- if (/^Ready on http/.test(message)) {
1749
- level = LogLevel.DEBUG;
1750
- }
1751
- switch (level) {
1752
- case LogLevel.ERROR:
1753
- return this.logger.error(message);
1754
- case LogLevel.WARN:
1755
- return this.logger.warn(message);
1756
- case LogLevel.INFO:
1757
- return this.logger.info(message);
1758
- }
1759
- }
1760
- };
1761
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1762
- switch (level) {
1763
- case "error":
1764
- return LogLevel.ERROR;
1765
- case "warn":
1766
- return LogLevel.WARN;
1767
- case "info":
1768
- return LogLevel.INFO;
1769
- case "silent":
1770
- return LogLevel.NONE;
1771
- }
1772
- }
1077
+ import assert3 from "node:assert";
1078
+ import * as vite2 from "vite";
1773
1079
 
1774
1080
  // src/node-js-compat.ts
1775
- import assert6 from "node:assert";
1081
+ import assert2 from "node:assert";
1776
1082
  import { cloudflare } from "@cloudflare/unenv-preset";
1777
1083
  import { getNodeCompat } from "miniflare";
1778
1084
 
@@ -7305,7 +6611,7 @@ Parser.acorn = {
7305
6611
 
7306
6612
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7307
6613
  import { builtinModules, createRequire } from "node:module";
7308
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6614
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7309
6615
 
7310
6616
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7311
6617
  var r = String.fromCharCode;
@@ -7362,9 +6668,9 @@ var isAbsolute = function(p) {
7362
6668
 
7363
6669
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7364
6670
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7365
- import assert5 from "node:assert";
6671
+ import assert from "node:assert";
7366
6672
  import process$1 from "node:process";
7367
- import path4, { dirname as dirname3 } from "node:path";
6673
+ import path, { dirname as dirname2 } from "node:path";
7368
6674
  import v8 from "node:v8";
7369
6675
  import { format as format2, inspect } from "node:util";
7370
6676
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7400,7 +6706,7 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7400
6706
  * @param {unknown} actual
7401
6707
  */
7402
6708
  (name2, expected, actual) => {
7403
- assert5(typeof name2 === "string", "'name' must be a string");
6709
+ assert(typeof name2 === "string", "'name' must be a string");
7404
6710
  if (!Array.isArray(expected)) {
7405
6711
  expected = [expected];
7406
6712
  }
@@ -7416,14 +6722,14 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7416
6722
  const instances = [];
7417
6723
  const other = [];
7418
6724
  for (const value of expected) {
7419
- assert5(
6725
+ assert(
7420
6726
  typeof value === "string",
7421
6727
  "All expected entries have to be of type string"
7422
6728
  );
7423
6729
  if (kTypes.has(value)) {
7424
6730
  types2.push(value.toLowerCase());
7425
6731
  } else if (classRegExp.exec(value) === null) {
7426
- assert5(
6732
+ assert(
7427
6733
  value !== "object",
7428
6734
  'The value "object" should be written as "Object"'
7429
6735
  );
@@ -7496,14 +6802,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7496
6802
  * @param {boolean} [isImport=false]
7497
6803
  * @param {string} [base]
7498
6804
  */
7499
- (packagePath, key, target, isImport = false, base = void 0) => {
7500
- 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("./");
7501
6807
  if (key === ".") {
7502
- assert5(isImport === false);
7503
- 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 "./"' : ""}`;
7504
6810
  }
7505
6811
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7506
- target
6812
+ target2
7507
6813
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7508
6814
  },
7509
6815
  Error
@@ -7632,1163 +6938,1895 @@ function isErrorStackTraceLimitWritable() {
7632
6938
  if (v8.startupSnapshot.isBuildingSnapshot()) {
7633
6939
  return false;
7634
6940
  }
7635
- } catch {
6941
+ } catch {
6942
+ }
6943
+ const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
6944
+ if (desc === void 0) {
6945
+ return Object.isExtensible(Error);
6946
+ }
6947
+ return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
6948
+ }
6949
+ function hideStackFrames(wrappedFunction) {
6950
+ const hidden = nodeInternalPrefix + wrappedFunction.name;
6951
+ Object.defineProperty(wrappedFunction, "name", { value: hidden });
6952
+ return wrappedFunction;
6953
+ }
6954
+ var captureLargerStackTrace = hideStackFrames(
6955
+ /**
6956
+ * @param {Error} error
6957
+ * @returns {Error}
6958
+ */
6959
+ // @ts-expect-error: fine
6960
+ function(error) {
6961
+ const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
6962
+ if (stackTraceLimitIsWritable) {
6963
+ userStackTraceLimit = Error.stackTraceLimit;
6964
+ Error.stackTraceLimit = Number.POSITIVE_INFINITY;
6965
+ }
6966
+ Error.captureStackTrace(error);
6967
+ if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
6968
+ return error;
6969
+ }
6970
+ );
6971
+ function getMessage(key, parameters, self) {
6972
+ const message = messages.get(key);
6973
+ assert(message !== void 0, "expected `message` to be found");
6974
+ if (typeof message === "function") {
6975
+ assert(
6976
+ message.length <= parameters.length,
6977
+ // Default options do not count.
6978
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
6979
+ );
6980
+ return Reflect.apply(message, self, parameters);
6981
+ }
6982
+ const regex = /%[dfijoOs]/g;
6983
+ let expectedLength = 0;
6984
+ while (regex.exec(message) !== null) expectedLength++;
6985
+ assert(
6986
+ expectedLength === parameters.length,
6987
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
6988
+ );
6989
+ if (parameters.length === 0) return message;
6990
+ parameters.unshift(message);
6991
+ return Reflect.apply(format2, null, parameters);
6992
+ }
6993
+ function determineSpecificType(value) {
6994
+ if (value === null || value === void 0) {
6995
+ return String(value);
6996
+ }
6997
+ if (typeof value === "function" && value.name) {
6998
+ return `function ${value.name}`;
6999
+ }
7000
+ if (typeof value === "object") {
7001
+ if (value.constructor && value.constructor.name) {
7002
+ return `an instance of ${value.constructor.name}`;
7003
+ }
7004
+ return `${inspect(value, { depth: -1 })}`;
7005
+ }
7006
+ let inspected = inspect(value, { colors: false });
7007
+ if (inspected.length > 28) {
7008
+ inspected = `${inspected.slice(0, 25)}...`;
7009
+ }
7010
+ return `type ${typeof value} (${inspected})`;
7011
+ }
7012
+ var hasOwnProperty$1 = {}.hasOwnProperty;
7013
+ var { ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1 } = codes;
7014
+ var cache = /* @__PURE__ */ new Map();
7015
+ function read(jsonPath, { base, specifier }) {
7016
+ const existing = cache.get(jsonPath);
7017
+ if (existing) {
7018
+ return existing;
7019
+ }
7020
+ let string;
7021
+ try {
7022
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7023
+ } catch (error) {
7024
+ const exception = (
7025
+ /** @type {ErrnoException} */
7026
+ error
7027
+ );
7028
+ if (exception.code !== "ENOENT") {
7029
+ throw exception;
7030
+ }
7031
+ }
7032
+ const result = {
7033
+ exists: false,
7034
+ pjsonPath: jsonPath,
7035
+ main: void 0,
7036
+ name: void 0,
7037
+ type: "none",
7038
+ // Ignore unknown types for forwards compatibility
7039
+ exports: void 0,
7040
+ imports: void 0
7041
+ };
7042
+ if (string !== void 0) {
7043
+ let parsed;
7044
+ try {
7045
+ parsed = JSON.parse(string);
7046
+ } catch (error_) {
7047
+ const cause = (
7048
+ /** @type {ErrnoException} */
7049
+ error_
7050
+ );
7051
+ const error = new ERR_INVALID_PACKAGE_CONFIG$1(
7052
+ jsonPath,
7053
+ (base ? `"${specifier}" from ` : "") + fileURLToPath$1(base || specifier),
7054
+ cause.message
7055
+ );
7056
+ error.cause = cause;
7057
+ throw error;
7058
+ }
7059
+ result.exists = true;
7060
+ if (hasOwnProperty$1.call(parsed, "name") && typeof parsed.name === "string") {
7061
+ result.name = parsed.name;
7062
+ }
7063
+ if (hasOwnProperty$1.call(parsed, "main") && typeof parsed.main === "string") {
7064
+ result.main = parsed.main;
7065
+ }
7066
+ if (hasOwnProperty$1.call(parsed, "exports")) {
7067
+ result.exports = parsed.exports;
7068
+ }
7069
+ if (hasOwnProperty$1.call(parsed, "imports")) {
7070
+ result.imports = parsed.imports;
7071
+ }
7072
+ if (hasOwnProperty$1.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) {
7073
+ result.type = parsed.type;
7074
+ }
7075
+ }
7076
+ cache.set(jsonPath, result);
7077
+ return result;
7078
+ }
7079
+ function getPackageScopeConfig(resolved) {
7080
+ let packageJSONUrl = new URL("package.json", resolved);
7081
+ while (true) {
7082
+ const packageJSONPath2 = packageJSONUrl.pathname;
7083
+ if (packageJSONPath2.endsWith("node_modules/package.json")) {
7084
+ break;
7085
+ }
7086
+ const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
7087
+ specifier: resolved
7088
+ });
7089
+ if (packageConfig.exists) {
7090
+ return packageConfig;
7091
+ }
7092
+ const lastPackageJSONUrl = packageJSONUrl;
7093
+ packageJSONUrl = new URL("../package.json", packageJSONUrl);
7094
+ if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
7095
+ break;
7096
+ }
7097
+ }
7098
+ const packageJSONPath = fileURLToPath$1(packageJSONUrl);
7099
+ return {
7100
+ pjsonPath: packageJSONPath,
7101
+ exists: false,
7102
+ type: "none"
7103
+ };
7104
+ }
7105
+ function getPackageType(url) {
7106
+ return getPackageScopeConfig(url).type;
7107
+ }
7108
+ var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
7109
+ var hasOwnProperty2 = {}.hasOwnProperty;
7110
+ var extensionFormatMap = {
7111
+ // @ts-expect-error: hush.
7112
+ __proto__: null,
7113
+ ".cjs": "commonjs",
7114
+ ".js": "module",
7115
+ ".json": "json",
7116
+ ".mjs": "module"
7117
+ };
7118
+ function mimeToFormat(mime) {
7119
+ if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
7120
+ return "module";
7121
+ if (mime === "application/json") return "json";
7122
+ return null;
7123
+ }
7124
+ var protocolHandlers = {
7125
+ // @ts-expect-error: hush.
7126
+ __proto__: null,
7127
+ "data:": getDataProtocolModuleFormat,
7128
+ "file:": getFileProtocolModuleFormat,
7129
+ "http:": getHttpProtocolModuleFormat,
7130
+ "https:": getHttpProtocolModuleFormat,
7131
+ "node:"() {
7132
+ return "builtin";
7133
+ }
7134
+ };
7135
+ function getDataProtocolModuleFormat(parsed) {
7136
+ const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
7137
+ parsed.pathname
7138
+ ) || [null, null, null];
7139
+ return mimeToFormat(mime);
7140
+ }
7141
+ function extname2(url) {
7142
+ const pathname = url.pathname;
7143
+ let index = pathname.length;
7144
+ while (index--) {
7145
+ const code = pathname.codePointAt(index);
7146
+ if (code === 47) {
7147
+ return "";
7148
+ }
7149
+ if (code === 46) {
7150
+ return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
7151
+ }
7152
+ }
7153
+ return "";
7154
+ }
7155
+ function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
7156
+ const value = extname2(url);
7157
+ if (value === ".js") {
7158
+ const packageType = getPackageType(url);
7159
+ if (packageType !== "none") {
7160
+ return packageType;
7161
+ }
7162
+ return "commonjs";
7163
+ }
7164
+ if (value === "") {
7165
+ const packageType = getPackageType(url);
7166
+ if (packageType === "none" || packageType === "commonjs") {
7167
+ return "commonjs";
7168
+ }
7169
+ return "module";
7636
7170
  }
7637
- const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
7638
- if (desc === void 0) {
7639
- return Object.isExtensible(Error);
7171
+ const format3 = extensionFormatMap[value];
7172
+ if (format3) return format3;
7173
+ if (ignoreErrors) {
7174
+ return void 0;
7640
7175
  }
7641
- return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
7176
+ const filepath = fileURLToPath$1(url);
7177
+ throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7642
7178
  }
7643
- function hideStackFrames(wrappedFunction) {
7644
- const hidden = nodeInternalPrefix + wrappedFunction.name;
7645
- Object.defineProperty(wrappedFunction, "name", { value: hidden });
7646
- return wrappedFunction;
7179
+ function getHttpProtocolModuleFormat() {
7647
7180
  }
7648
- var captureLargerStackTrace = hideStackFrames(
7649
- /**
7650
- * @param {Error} error
7651
- * @returns {Error}
7652
- */
7653
- // @ts-expect-error: fine
7654
- function(error) {
7655
- const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
7656
- if (stackTraceLimitIsWritable) {
7657
- userStackTraceLimit = Error.stackTraceLimit;
7658
- Error.stackTraceLimit = Number.POSITIVE_INFINITY;
7659
- }
7660
- Error.captureStackTrace(error);
7661
- if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
7662
- return error;
7181
+ function defaultGetFormatWithoutErrors(url, context) {
7182
+ const protocol = url.protocol;
7183
+ if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7184
+ return null;
7663
7185
  }
7664
- );
7665
- function getMessage(key, parameters, self) {
7666
- const message = messages.get(key);
7667
- assert5(message !== void 0, "expected `message` to be found");
7668
- if (typeof message === "function") {
7669
- assert5(
7670
- message.length <= parameters.length,
7671
- // Default options do not count.
7672
- `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
7673
- );
7674
- return Reflect.apply(message, self, parameters);
7186
+ return protocolHandlers[protocol](url, context, true) || null;
7187
+ }
7188
+ var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
7189
+ var {
7190
+ ERR_NETWORK_IMPORT_DISALLOWED,
7191
+ ERR_INVALID_MODULE_SPECIFIER,
7192
+ ERR_INVALID_PACKAGE_CONFIG,
7193
+ ERR_INVALID_PACKAGE_TARGET,
7194
+ ERR_MODULE_NOT_FOUND,
7195
+ ERR_PACKAGE_IMPORT_NOT_DEFINED,
7196
+ ERR_PACKAGE_PATH_NOT_EXPORTED,
7197
+ ERR_UNSUPPORTED_DIR_IMPORT,
7198
+ ERR_UNSUPPORTED_RESOLVE_REQUEST
7199
+ } = codes;
7200
+ var own = {}.hasOwnProperty;
7201
+ var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
7202
+ var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
7203
+ var invalidPackageNameRegEx = /^\.|%|\\/;
7204
+ var patternRegEx = /\*/g;
7205
+ var encodedSeparatorRegEx = /%2f|%5c/i;
7206
+ var emittedPackageWarnings = /* @__PURE__ */ new Set();
7207
+ var doubleSlashRegEx = /[/\\]{2}/;
7208
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7209
+ if (process$1.noDeprecation) {
7210
+ return;
7675
7211
  }
7676
- const regex = /%[dfijoOs]/g;
7677
- let expectedLength = 0;
7678
- while (regex.exec(message) !== null) expectedLength++;
7679
- assert5(
7680
- expectedLength === parameters.length,
7681
- `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7212
+ const pjsonPath = fileURLToPath$1(packageJsonUrl);
7213
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7214
+ process$1.emitWarning(
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)}` : ""}.`,
7216
+ "DeprecationWarning",
7217
+ "DEP0166"
7682
7218
  );
7683
- if (parameters.length === 0) return message;
7684
- parameters.unshift(message);
7685
- return Reflect.apply(format2, null, parameters);
7686
7219
  }
7687
- function determineSpecificType(value) {
7688
- if (value === null || value === void 0) {
7689
- return String(value);
7220
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7221
+ if (process$1.noDeprecation) {
7222
+ return;
7690
7223
  }
7691
- if (typeof value === "function" && value.name) {
7692
- return `function ${value.name}`;
7224
+ const format3 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
7225
+ if (format3 !== "module") return;
7226
+ const urlPath = fileURLToPath$1(url.href);
7227
+ const packagePath = fileURLToPath$1(new URL$1(".", packageJsonUrl));
7228
+ const basePath = fileURLToPath$1(base);
7229
+ if (!main) {
7230
+ process$1.emitWarning(
7231
+ `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
7232
+ packagePath.length
7233
+ )}", imported from ${basePath}.
7234
+ Default "index" lookups for the main are deprecated for ES modules.`,
7235
+ "DeprecationWarning",
7236
+ "DEP0151"
7237
+ );
7238
+ } else if (path.resolve(packagePath, main) !== urlPath) {
7239
+ process$1.emitWarning(
7240
+ `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7241
+ packagePath.length
7242
+ )}", imported from ${basePath}.
7243
+ Automatic extension resolution of the "main" field is deprecated for ES modules.`,
7244
+ "DeprecationWarning",
7245
+ "DEP0151"
7246
+ );
7693
7247
  }
7694
- if (typeof value === "object") {
7695
- if (value.constructor && value.constructor.name) {
7696
- return `an instance of ${value.constructor.name}`;
7248
+ }
7249
+ function tryStatSync(path8) {
7250
+ try {
7251
+ return statSync(path8);
7252
+ } catch {
7253
+ }
7254
+ }
7255
+ function fileExists(url) {
7256
+ const stats = statSync(url, { throwIfNoEntry: false });
7257
+ const isFile = stats ? stats.isFile() : void 0;
7258
+ return isFile === null || isFile === void 0 ? false : isFile;
7259
+ }
7260
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
7261
+ let guess;
7262
+ if (packageConfig.main !== void 0) {
7263
+ guess = new URL$1(packageConfig.main, packageJsonUrl);
7264
+ if (fileExists(guess)) return guess;
7265
+ const tries2 = [
7266
+ `./${packageConfig.main}.js`,
7267
+ `./${packageConfig.main}.json`,
7268
+ `./${packageConfig.main}.node`,
7269
+ `./${packageConfig.main}/index.js`,
7270
+ `./${packageConfig.main}/index.json`,
7271
+ `./${packageConfig.main}/index.node`
7272
+ ];
7273
+ let i2 = -1;
7274
+ while (++i2 < tries2.length) {
7275
+ guess = new URL$1(tries2[i2], packageJsonUrl);
7276
+ if (fileExists(guess)) break;
7277
+ guess = void 0;
7278
+ }
7279
+ if (guess) {
7280
+ emitLegacyIndexDeprecation(
7281
+ guess,
7282
+ packageJsonUrl,
7283
+ base,
7284
+ packageConfig.main
7285
+ );
7286
+ return guess;
7697
7287
  }
7698
- return `${inspect(value, { depth: -1 })}`;
7699
7288
  }
7700
- let inspected = inspect(value, { colors: false });
7701
- if (inspected.length > 28) {
7702
- inspected = `${inspected.slice(0, 25)}...`;
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;
7703
7295
  }
7704
- return `type ${typeof value} (${inspected})`;
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
+ );
7705
7304
  }
7706
- var hasOwnProperty$1 = {}.hasOwnProperty;
7707
- var { ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1 } = codes;
7708
- var cache = /* @__PURE__ */ new Map();
7709
- function read(jsonPath, { base, specifier }) {
7710
- const existing = cache.get(jsonPath);
7711
- if (existing) {
7712
- return existing;
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
+ );
7713
7312
  }
7714
- let string;
7313
+ let filePath;
7715
7314
  try {
7716
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7315
+ filePath = fileURLToPath$1(resolved);
7717
7316
  } catch (error) {
7718
- const exception = (
7317
+ const cause = (
7719
7318
  /** @type {ErrnoException} */
7720
7319
  error
7721
7320
  );
7722
- if (exception.code !== "ENOENT") {
7723
- throw exception;
7724
- }
7321
+ Object.defineProperty(cause, "input", { value: String(resolved) });
7322
+ Object.defineProperty(cause, "module", { value: String(base) });
7323
+ throw cause;
7725
7324
  }
7726
- const result = {
7727
- exists: false,
7728
- pjsonPath: jsonPath,
7729
- main: void 0,
7730
- name: void 0,
7731
- type: "none",
7732
- // Ignore unknown types for forwards compatibility
7733
- exports: void 0,
7734
- imports: void 0
7735
- };
7736
- if (string !== void 0) {
7737
- let parsed;
7738
- try {
7739
- parsed = JSON.parse(string);
7740
- } catch (error_) {
7741
- const cause = (
7742
- /** @type {ErrnoException} */
7743
- error_
7744
- );
7745
- const error = new ERR_INVALID_PACKAGE_CONFIG$1(
7746
- jsonPath,
7747
- (base ? `"${specifier}" from ` : "") + fileURLToPath$1(base || specifier),
7748
- cause.message
7749
- );
7750
- error.cause = cause;
7751
- throw error;
7752
- }
7753
- result.exists = true;
7754
- if (hasOwnProperty$1.call(parsed, "name") && typeof parsed.name === "string") {
7755
- result.name = parsed.name;
7756
- }
7757
- if (hasOwnProperty$1.call(parsed, "main") && typeof parsed.main === "string") {
7758
- result.main = parsed.main;
7759
- }
7760
- if (hasOwnProperty$1.call(parsed, "exports")) {
7761
- result.exports = parsed.exports;
7762
- }
7763
- if (hasOwnProperty$1.call(parsed, "imports")) {
7764
- result.imports = parsed.imports;
7765
- }
7766
- if (hasOwnProperty$1.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) {
7767
- result.type = parsed.type;
7768
- }
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;
7769
7341
  }
7770
- cache.set(jsonPath, result);
7771
- return result;
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;
7772
7350
  }
7773
- function getPackageScopeConfig(resolved) {
7774
- let packageJSONUrl = new URL("package.json", resolved);
7775
- while (true) {
7776
- const packageJSONPath2 = packageJSONUrl.pathname;
7777
- if (packageJSONPath2.endsWith("node_modules/package.json")) {
7778
- break;
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
+ }
7779
7402
  }
7780
- const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
7781
- specifier: resolved
7782
- });
7783
- if (packageConfig.exists) {
7784
- return packageConfig;
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);
7785
7426
  }
7786
- const lastPackageJSONUrl = packageJSONUrl;
7787
- packageJSONUrl = new URL("../package.json", packageJSONUrl);
7788
- if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
7789
- break;
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);
7790
7455
  }
7791
7456
  }
7792
- const packageJSONPath = fileURLToPath$1(packageJSONUrl);
7793
- return {
7794
- pjsonPath: packageJSONPath,
7795
- exists: false,
7796
- type: "none"
7797
- };
7798
- }
7799
- function getPackageType(url) {
7800
- return getPackageScopeConfig(url).type;
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);
7801
7467
  }
7802
- var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
7803
- var hasOwnProperty2 = {}.hasOwnProperty;
7804
- var extensionFormatMap = {
7805
- // @ts-expect-error: hush.
7806
- __proto__: null,
7807
- ".cjs": "commonjs",
7808
- ".js": "module",
7809
- ".json": "json",
7810
- ".mjs": "module"
7811
- };
7812
- function mimeToFormat(mime) {
7813
- if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
7814
- return "module";
7815
- if (mime === "application/json") return "json";
7816
- return null;
7468
+ function isArrayIndex(key) {
7469
+ const keyNumber = Number(key);
7470
+ if (`${keyNumber}` !== key) return false;
7471
+ return keyNumber >= 0 && keyNumber < 4294967295;
7817
7472
  }
7818
- var protocolHandlers = {
7819
- // @ts-expect-error: hush.
7820
- __proto__: null,
7821
- "data:": getDataProtocolModuleFormat,
7822
- "file:": getFileProtocolModuleFormat,
7823
- "http:": getHttpProtocolModuleFormat,
7824
- "https:": getHttpProtocolModuleFormat,
7825
- "node:"() {
7826
- return "builtin";
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
+ );
7827
7486
  }
7828
- };
7829
- function getDataProtocolModuleFormat(parsed) {
7830
- const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
7831
- parsed.pathname
7832
- ) || [null, null, null];
7833
- return mimeToFormat(mime);
7834
- }
7835
- function extname2(url) {
7836
- const pathname = url.pathname;
7837
- let index = pathname.length;
7838
- while (index--) {
7839
- const code = pathname.codePointAt(index);
7840
- if (code === 47) {
7841
- return "";
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;
7842
7522
  }
7843
- if (code === 46) {
7844
- return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
7523
+ if (lastException === void 0 || lastException === null) {
7524
+ return null;
7845
7525
  }
7526
+ throw lastException;
7846
7527
  }
7847
- return "";
7848
- }
7849
- function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
7850
- const value = extname2(url);
7851
- if (value === ".js") {
7852
- const packageType = getPackageType(url);
7853
- if (packageType !== "none") {
7854
- return packageType;
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
+ }
7855
7540
  }
7856
- return "commonjs";
7857
- }
7858
- if (value === "") {
7859
- const packageType = getPackageType(url);
7860
- if (packageType === "none" || packageType === "commonjs") {
7861
- return "commonjs";
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
+ }
7862
7563
  }
7863
- return "module";
7564
+ return null;
7864
7565
  }
7865
- const format3 = extensionFormatMap[value];
7866
- if (format3) return format3;
7867
- if (ignoreErrors) {
7868
- return void 0;
7566
+ if (target2 === null) {
7567
+ return null;
7869
7568
  }
7870
- const filepath = fileURLToPath$1(url);
7871
- throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7872
- }
7873
- function getHttpProtocolModuleFormat() {
7569
+ throw invalidPackageTarget(
7570
+ packageSubpath,
7571
+ target2,
7572
+ packageJsonUrl,
7573
+ internal,
7574
+ base
7575
+ );
7874
7576
  }
7875
- function defaultGetFormatWithoutErrors(url, context) {
7876
- const protocol = url.protocol;
7877
- if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7878
- return null;
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),
7592
+ base,
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.`
7594
+ );
7595
+ }
7879
7596
  }
7880
- return protocolHandlers[protocol](url, context, true) || null;
7597
+ return isConditionalSugar;
7881
7598
  }
7882
- var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
7883
- var {
7884
- ERR_NETWORK_IMPORT_DISALLOWED,
7885
- ERR_INVALID_MODULE_SPECIFIER,
7886
- ERR_INVALID_PACKAGE_CONFIG,
7887
- ERR_INVALID_PACKAGE_TARGET,
7888
- ERR_MODULE_NOT_FOUND,
7889
- ERR_PACKAGE_IMPORT_NOT_DEFINED,
7890
- ERR_PACKAGE_PATH_NOT_EXPORTED,
7891
- ERR_UNSUPPORTED_DIR_IMPORT,
7892
- ERR_UNSUPPORTED_RESOLVE_REQUEST
7893
- } = codes;
7894
- var own = {}.hasOwnProperty;
7895
- var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
7896
- var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
7897
- var invalidPackageNameRegEx = /^\.|%|\\/;
7898
- var patternRegEx = /\*/g;
7899
- var encodedSeparatorRegEx = /%2f|%5c/i;
7900
- var emittedPackageWarnings = /* @__PURE__ */ new Set();
7901
- var doubleSlashRegEx = /[/\\]{2}/;
7902
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7599
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
7903
7600
  if (process$1.noDeprecation) {
7904
7601
  return;
7905
7602
  }
7906
- const pjsonPath = fileURLToPath$1(packageJsonUrl);
7907
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7603
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
7604
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
7605
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
7908
7606
  process$1.emitWarning(
7909
- `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)}` : ""}.`,
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.`,
7910
7608
  "DeprecationWarning",
7911
- "DEP0166"
7609
+ "DEP0155"
7912
7610
  );
7913
7611
  }
7914
- function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7915
- if (process$1.noDeprecation) {
7916
- return;
7612
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7613
+ let exports = packageConfig.exports;
7614
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7615
+ exports = { ".": exports };
7917
7616
  }
7918
- const format3 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
7919
- if (format3 !== "module") return;
7920
- const urlPath = fileURLToPath$1(url.href);
7921
- const packagePath = fileURLToPath$1(new URL$1(".", packageJsonUrl));
7922
- const basePath = fileURLToPath$1(base);
7923
- if (!main) {
7924
- process$1.emitWarning(
7925
- `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
7926
- packagePath.length
7927
- )}", imported from ${basePath}.
7928
- Default "index" lookups for the main are deprecated for ES modules.`,
7929
- "DeprecationWarning",
7930
- "DEP0151"
7931
- );
7932
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7933
- process$1.emitWarning(
7934
- `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7935
- packagePath.length
7936
- )}", imported from ${basePath}.
7937
- Automatic extension resolution of the "main" field is deprecated for ES modules.`,
7938
- "DeprecationWarning",
7939
- "DEP0151"
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
7940
7629
  );
7630
+ if (resolveResult === null || resolveResult === void 0) {
7631
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7632
+ }
7633
+ return resolveResult;
7941
7634
  }
7942
- }
7943
- function tryStatSync(path8) {
7944
- try {
7945
- return statSync2(path8);
7946
- } catch {
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
+ }
7659
+ }
7660
+ if (bestMatch) {
7661
+ const target2 = (
7662
+ /** @type {unknown} */
7663
+ exports[bestMatch]
7664
+ );
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;
7947
7680
  }
7681
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7948
7682
  }
7949
- function fileExists(url) {
7950
- const stats = statSync2(url, { throwIfNoEntry: false });
7951
- const isFile = stats ? stats.isFile() : void 0;
7952
- return isFile === null || isFile === void 0 ? false : isFile;
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;
7953
7695
  }
7954
- function legacyMainResolve(packageJsonUrl, packageConfig, base) {
7955
- let guess;
7956
- if (packageConfig.main !== void 0) {
7957
- guess = new URL$1(packageConfig.main, packageJsonUrl);
7958
- if (fileExists(guess)) return guess;
7959
- const tries2 = [
7960
- `./${packageConfig.main}.js`,
7961
- `./${packageConfig.main}.json`,
7962
- `./${packageConfig.main}.node`,
7963
- `./${packageConfig.main}/index.js`,
7964
- `./${packageConfig.main}/index.json`,
7965
- `./${packageConfig.main}/index.node`
7966
- ];
7967
- let i2 = -1;
7968
- while (++i2 < tries2.length) {
7969
- guess = new URL$1(tries2[i2], packageJsonUrl);
7970
- if (fileExists(guess)) break;
7971
- guess = void 0;
7972
- }
7973
- if (guess) {
7974
- emitLegacyIndexDeprecation(
7975
- guess,
7976
- packageJsonUrl,
7977
- base,
7978
- packageConfig.main
7979
- );
7980
- return guess;
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
+ }
7981
7759
  }
7982
7760
  }
7983
- const tries = ["./index.js", "./index.json", "./index.node"];
7984
- let i = -1;
7985
- while (++i < tries.length) {
7986
- guess = new URL$1(tries[i], packageJsonUrl);
7987
- if (fileExists(guess)) break;
7988
- guess = void 0;
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
+ }
7989
7774
  }
7990
- if (guess) {
7991
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
7992
- return guess;
7775
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7776
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7777
+ validPackageName = false;
7993
7778
  }
7994
- throw new ERR_MODULE_NOT_FOUND(
7995
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7996
- fileURLToPath$1(base)
7997
- );
7998
- }
7999
- function finalizeResolution(resolved, base, preserveSymlinks) {
8000
- if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7779
+ if (!validPackageName) {
8001
7780
  throw new ERR_INVALID_MODULE_SPECIFIER(
8002
- resolved.pathname,
8003
- 'must not include encoded "/" or "\\" characters',
7781
+ specifier,
7782
+ "is not a valid package name",
8004
7783
  fileURLToPath$1(base)
8005
7784
  );
8006
7785
  }
8007
- let filePath;
8008
- try {
8009
- filePath = fileURLToPath$1(resolved);
8010
- } catch (error) {
8011
- const cause = (
8012
- /** @type {ErrnoException} */
8013
- error
8014
- );
8015
- Object.defineProperty(cause, "input", { value: String(resolved) });
8016
- Object.defineProperty(cause, "module", { value: String(base) });
8017
- throw cause;
8018
- }
8019
- const stats = tryStatSync(
8020
- filePath.endsWith("/") ? filePath.slice(-1) : filePath
8021
- );
8022
- if (stats && stats.isDirectory()) {
8023
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
8024
- error.url = String(resolved);
8025
- throw error;
8026
- }
8027
- if (!stats || !stats.isFile()) {
8028
- const error = new ERR_MODULE_NOT_FOUND(
8029
- filePath || resolved.pathname,
8030
- base && fileURLToPath$1(base),
8031
- true
8032
- );
8033
- error.url = String(resolved);
8034
- throw error;
8035
- }
8036
- {
8037
- const real = realpathSync(filePath);
8038
- const { search, hash } = resolved;
8039
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
8040
- resolved.search = search;
8041
- resolved.hash = hash;
8042
- }
8043
- return resolved;
7786
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7787
+ return { packageName, packageSubpath, isScoped };
8044
7788
  }
8045
- function importNotDefined(specifier, packageJsonUrl, base) {
8046
- 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(
8047
7794
  specifier,
8048
- packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8049
- fileURLToPath$1(base)
7795
+ base
8050
7796
  );
8051
- }
8052
- function exportsNotFound(subpath, packageJsonUrl, base) {
8053
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
8054
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8055
- subpath,
8056
- 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
8057
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);
8058
7843
  }
8059
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8060
- const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
8061
- throw new ERR_INVALID_MODULE_SPECIFIER(
8062
- request,
8063
- reason,
8064
- base && fileURLToPath$1(base)
8065
- );
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;
8066
7852
  }
8067
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8068
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8069
- return new ERR_INVALID_PACKAGE_TARGET(
8070
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8071
- subpath,
8072
- target,
8073
- internal,
8074
- base && fileURLToPath$1(base)
8075
- );
7853
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
7854
+ if (specifier === "") return false;
7855
+ if (specifier[0] === "/") return true;
7856
+ return isRelativeSpecifier(specifier);
8076
7857
  }
8077
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8078
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8079
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8080
- if (!target.startsWith("./")) {
8081
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8082
- let isURL = false;
8083
- try {
8084
- new URL$1(target);
8085
- isURL = true;
8086
- } catch {
8087
- }
8088
- if (!isURL) {
8089
- const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8090
- patternRegEx,
8091
- target,
8092
- () => subpath
8093
- ) : target + subpath;
8094
- return packageResolve(exportTarget, packageJsonUrl, conditions);
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;
7870
+ }
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;
8095
7881
  }
7882
+ resolved = packageResolve(specifier, base, conditions);
8096
7883
  }
8097
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8098
7884
  }
8099
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8100
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8101
- if (!isPathMap) {
8102
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8103
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8104
- patternRegEx,
8105
- target,
8106
- () => subpath
8107
- ) : target;
8108
- emitInvalidSegmentDeprecation(
8109
- resolvedTarget,
8110
- request,
8111
- match,
8112
- packageJsonUrl,
8113
- internal,
8114
- base,
8115
- true
8116
- );
8117
- }
8118
- } else {
8119
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7885
+ assert(resolved !== void 0, "expected to be defined");
7886
+ if (resolved.protocol !== "file:") {
7887
+ return resolved;
7888
+ }
7889
+ return finalizeResolution(resolved, base);
7890
+ }
7891
+ function fileURLToPath(id) {
7892
+ if (typeof id === "string" && !id.startsWith("file://")) {
7893
+ return normalizeSlash(id);
7894
+ }
7895
+ return normalizeSlash(fileURLToPath$1(id));
7896
+ }
7897
+ function pathToFileURL(id) {
7898
+ return pathToFileURL$1(fileURLToPath(id)).toString();
7899
+ }
7900
+ function normalizeid(id) {
7901
+ if (typeof id !== "string") {
7902
+ id = id.toString();
7903
+ }
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;
8120
7926
  }
8121
7927
  }
8122
- const resolved = new URL$1(target, packageJsonUrl);
8123
- const resolvedPath = resolved.pathname;
8124
- const packagePath = new URL$1(".", packageJsonUrl).pathname;
8125
- if (!resolvedPath.startsWith(packagePath))
8126
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8127
- if (subpath === "") return resolved;
8128
- if (invalidSegmentRegEx.exec(subpath) !== null) {
8129
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8130
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
8131
- if (!isPathMap) {
8132
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8133
- patternRegEx,
8134
- target,
8135
- () => subpath
8136
- ) : target;
8137
- emitInvalidSegmentDeprecation(
8138
- resolvedTarget,
8139
- request,
8140
- match,
8141
- packageJsonUrl,
8142
- internal,
8143
- base,
8144
- false
8145
- );
8146
- }
7928
+ }
7929
+ function _resolve(id, options = {}) {
7930
+ if (typeof id !== "string") {
7931
+ if (id instanceof URL) {
7932
+ id = fileURLToPath(id);
8147
7933
  } else {
8148
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7934
+ throw new TypeError("input must be a `string` or `URL`");
8149
7935
  }
8150
7936
  }
8151
- if (pattern) {
8152
- return new URL$1(
8153
- RegExpPrototypeSymbolReplace.call(
8154
- patternRegEx,
8155
- resolved.href,
8156
- () => subpath
8157
- )
8158
- );
7937
+ if (/(node|data|http|https):/.test(id)) {
7938
+ return id;
8159
7939
  }
8160
- return new URL$1(subpath, resolved);
8161
- }
8162
- function isArrayIndex(key) {
8163
- const keyNumber = Number(key);
8164
- if (`${keyNumber}` !== key) return false;
8165
- return keyNumber >= 0 && keyNumber < 4294967295;
8166
- }
8167
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8168
- if (typeof target === "string") {
8169
- return resolvePackageTargetString(
8170
- target,
8171
- subpath,
8172
- packageSubpath,
8173
- packageJsonUrl,
8174
- base,
8175
- pattern,
8176
- internal,
8177
- isPathMap,
8178
- conditions
8179
- );
7940
+ if (BUILTIN_MODULES.has(id)) {
7941
+ return "node:" + id;
8180
7942
  }
8181
- if (Array.isArray(target)) {
8182
- const targetList = target;
8183
- if (targetList.length === 0) return null;
8184
- let lastException;
8185
- let i = -1;
8186
- while (++i < targetList.length) {
8187
- const targetItem = targetList[i];
8188
- let resolveResult;
8189
- try {
8190
- resolveResult = resolvePackageTarget(
8191
- packageJsonUrl,
8192
- targetItem,
8193
- subpath,
8194
- packageSubpath,
8195
- base,
8196
- pattern,
8197
- internal,
8198
- isPathMap,
8199
- conditions
8200
- );
8201
- } catch (error) {
8202
- const exception = (
8203
- /** @type {ErrnoException} */
8204
- error
8205
- );
8206
- lastException = exception;
8207
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8208
- throw error;
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);
8209
7951
  }
8210
- if (resolveResult === void 0) continue;
8211
- if (resolveResult === null) {
8212
- lastException = null;
8213
- continue;
7952
+ } catch (error) {
7953
+ if (error?.code !== "ENOENT") {
7954
+ throw error;
8214
7955
  }
8215
- return resolveResult;
8216
7956
  }
8217
- if (lastException === void 0 || lastException === null) {
8218
- 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
+ );
8219
7973
  }
8220
- throw lastException;
8221
7974
  }
8222
- if (typeof target === "object" && target !== null) {
8223
- const keys = Object.getOwnPropertyNames(target);
8224
- let i = -1;
8225
- while (++i < keys.length) {
8226
- const key = keys[i];
8227
- if (isArrayIndex(key)) {
8228
- throw new ERR_INVALID_PACKAGE_CONFIG(
8229
- fileURLToPath$1(packageJsonUrl),
8230
- base,
8231
- '"exports" cannot contain numeric property keys.'
8232
- );
8233
- }
7975
+ let resolved;
7976
+ for (const url of urls) {
7977
+ resolved = _tryModuleResolve(id, url, conditionsSet);
7978
+ if (resolved) {
7979
+ break;
8234
7980
  }
8235
- i = -1;
8236
- while (++i < keys.length) {
8237
- const key = keys[i];
8238
- if (key === "default" || conditions && conditions.has(key)) {
8239
- const conditionalTarget = (
8240
- /** @type {unknown} */
8241
- target[key]
8242
- );
8243
- const resolveResult = resolvePackageTarget(
8244
- packageJsonUrl,
8245
- conditionalTarget,
8246
- subpath,
8247
- packageSubpath,
8248
- base,
8249
- pattern,
8250
- internal,
8251
- isPathMap,
8252
- 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
8253
7987
  );
8254
- if (resolveResult === void 0) continue;
8255
- return resolveResult;
7988
+ if (resolved) {
7989
+ break;
7990
+ }
7991
+ }
7992
+ if (resolved) {
7993
+ break;
8256
7994
  }
8257
7995
  }
8258
- return null;
7996
+ if (resolved) {
7997
+ break;
7998
+ }
8259
7999
  }
8260
- if (target === null) {
8261
- 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;
8262
8006
  }
8263
- throw invalidPackageTarget(
8264
- packageSubpath,
8265
- target,
8266
- packageJsonUrl,
8267
- internal,
8268
- base
8269
- );
8007
+ return pathToFileURL(resolved);
8270
8008
  }
8271
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8272
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8273
- if (typeof exports !== "object" || exports === null) return false;
8274
- const keys = Object.getOwnPropertyNames(exports);
8275
- let isConditionalSugar = false;
8276
- let i = 0;
8277
- let keyIndex = -1;
8278
- while (++keyIndex < keys.length) {
8279
- const key = keys[keyIndex];
8280
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8281
- if (i++ === 0) {
8282
- isConditionalSugar = currentIsConditionalSugar;
8283
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8284
- throw new ERR_INVALID_PACKAGE_CONFIG(
8285
- fileURLToPath$1(packageJsonUrl),
8286
- base,
8287
- `"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.`
8288
- );
8289
- }
8290
- }
8291
- return isConditionalSugar;
8009
+ function resolveSync(id, options) {
8010
+ return _resolve(id, options);
8292
8011
  }
8293
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8294
- if (process$1.noDeprecation) {
8295
- return;
8296
- }
8297
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8298
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8299
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8300
- process$1.emitWarning(
8301
- `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.`,
8302
- "DeprecationWarning",
8303
- "DEP0155"
8304
- );
8012
+ function resolvePathSync(id, options) {
8013
+ return fileURLToPath(resolveSync(id, options));
8305
8014
  }
8306
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8307
- let exports = packageConfig.exports;
8308
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8309
- 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;
8310
8027
  }
8311
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8312
- const target = exports[packageSubpath];
8313
- const resolveResult = resolvePackageTarget(
8314
- packageJsonUrl,
8315
- target,
8316
- "",
8317
- packageSubpath,
8318
- base,
8319
- false,
8320
- false,
8321
- false,
8322
- 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`
8323
8038
  );
8324
- if (resolveResult === null || resolveResult === void 0) {
8325
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8326
- }
8327
- return resolveResult;
8328
8039
  }
8329
- let bestMatch = "";
8330
- let bestMatchSubpath = "";
8331
- const keys = Object.getOwnPropertyNames(exports);
8332
- let i = -1;
8333
- while (++i < keys.length) {
8334
- const key = keys[i];
8335
- const patternIndex = key.indexOf("*");
8336
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8337
- if (packageSubpath.endsWith("/")) {
8338
- emitTrailingSlashPatternDeprecation(
8339
- packageSubpath,
8340
- packageJsonUrl,
8341
- base
8342
- );
8343
- }
8344
- const patternTrailer = key.slice(patternIndex + 1);
8345
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8346
- bestMatch = key;
8347
- bestMatchSubpath = packageSubpath.slice(
8348
- patternIndex,
8349
- packageSubpath.length - patternTrailer.length
8350
- );
8351
- }
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
+ `;
8352
8049
  }
8353
- }
8354
- if (bestMatch) {
8355
- const target = (
8356
- /** @type {unknown} */
8357
- exports[bestMatch]
8358
- );
8359
- const resolveResult = resolvePackageTarget(
8360
- packageJsonUrl,
8361
- target,
8362
- bestMatchSubpath,
8363
- bestMatch,
8364
- base,
8365
- true,
8366
- false,
8367
- packageSubpath.endsWith("/"),
8368
- conditions
8050
+ const [moduleSpecifier, exportName] = globalInject;
8051
+ assert2(
8052
+ moduleSpecifier !== void 0,
8053
+ "Expected moduleSpecifier to be defined"
8369
8054
  );
8370
- if (resolveResult === null || resolveResult === void 0) {
8371
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
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
+ };
8074
+ }
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]);
8372
8093
  }
8373
- return resolveResult;
8374
8094
  }
8375
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8095
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8096
+ return entries;
8376
8097
  }
8377
- function patternKeyCompare(a, b) {
8378
- const aPatternIndex = a.indexOf("*");
8379
- const bPatternIndex = b.indexOf("*");
8380
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8381
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8382
- if (baseLengthA > baseLengthB) return -1;
8383
- if (baseLengthB > baseLengthA) return 1;
8384
- if (aPatternIndex === -1) return 1;
8385
- if (bPatternIndex === -1) return -1;
8386
- if (a.length > b.length) return -1;
8387
- if (b.length > a.length) return 1;
8388
- return 0;
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);
8389
8118
  }
8390
- function packageImportsResolve(name2, base, conditions) {
8391
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8392
- const reason = "is not a valid internal imports specifier name";
8393
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
8394
- }
8395
- let packageJsonUrl;
8396
- const packageConfig = getPackageScopeConfig(base);
8397
- if (packageConfig.exists) {
8398
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8399
- const imports = packageConfig.imports;
8400
- if (imports) {
8401
- if (own.call(imports, name2) && !name2.includes("*")) {
8402
- const resolveResult = resolvePackageTarget(
8403
- packageJsonUrl,
8404
- imports[name2],
8405
- "",
8406
- name2,
8407
- base,
8408
- false,
8409
- true,
8410
- false,
8411
- conditions
8412
- );
8413
- if (resolveResult !== null && resolveResult !== void 0) {
8414
- return resolveResult;
8415
- }
8416
- } else {
8417
- let bestMatch = "";
8418
- let bestMatchSubpath = "";
8419
- const keys = Object.getOwnPropertyNames(imports);
8420
- let i = -1;
8421
- while (++i < keys.length) {
8422
- const key = keys[i];
8423
- const patternIndex = key.indexOf("*");
8424
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8425
- const patternTrailer = key.slice(patternIndex + 1);
8426
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8427
- bestMatch = key;
8428
- bestMatchSubpath = name2.slice(
8429
- patternIndex,
8430
- name2.length - patternTrailer.length
8431
- );
8432
- }
8433
- }
8434
- }
8435
- if (bestMatch) {
8436
- const target = imports[bestMatch];
8437
- const resolveResult = resolvePackageTarget(
8438
- packageJsonUrl,
8439
- target,
8440
- bestMatchSubpath,
8441
- bestMatch,
8442
- base,
8443
- true,
8444
- true,
8445
- false,
8446
- conditions
8447
- );
8448
- if (resolveResult !== null && resolveResult !== void 0) {
8449
- return resolveResult;
8450
- }
8451
- }
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);
8452
8135
  }
8453
8136
  }
8454
8137
  }
8455
- throw importNotDefined(name2, packageJsonUrl, base);
8138
+ return headers;
8456
8139
  }
8457
- function parsePackageName(specifier, base) {
8458
- let separatorIndex = specifier.indexOf("/");
8459
- let validPackageName = true;
8460
- let isScoped = false;
8461
- if (specifier[0] === "@") {
8462
- isScoped = true;
8463
- if (separatorIndex === -1 || specifier.length === 0) {
8464
- validPackageName = false;
8465
- } else {
8466
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
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);
8467
8157
  }
8468
8158
  }
8469
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8470
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8471
- validPackageName = false;
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
+ };
8184
+ }
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;
8472
8195
  }
8473
- if (!validPackageName) {
8474
- throw new ERR_INVALID_MODULE_SPECIFIER(
8475
- specifier,
8476
- "is not a valid package name",
8477
- fileURLToPath$1(base)
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"
8207
+ }
8208
+ }
8209
+ );
8210
+ assert3(
8211
+ response.ok,
8212
+ `Failed to initialize module runner, error: ${await response.text()}`
8478
8213
  );
8214
+ const webSocket = response.webSocket;
8215
+ assert3(webSocket, "Failed to establish WebSocket");
8216
+ webSocket.accept();
8217
+ this.#webSocketContainer.webSocket = webSocket;
8479
8218
  }
8480
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8481
- return { packageName, packageSubpath, isScoped };
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
+ };
8482
8288
  }
8483
- function packageResolve(specifier, base, conditions) {
8484
- if (builtinModules.includes(specifier)) {
8485
- return new URL$1("node:" + specifier);
8486
- }
8487
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8488
- specifier,
8489
- base
8490
- );
8491
- const packageConfig = getPackageScopeConfig(base);
8492
- if (packageConfig.exists) {
8493
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8494
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8495
- return packageExportsResolve(
8496
- packageJsonUrl2,
8497
- packageSubpath,
8498
- packageConfig,
8499
- base,
8500
- conditions
8501
- );
8502
- }
8289
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8290
+ if (resolvedPluginConfig.type === "assets-only") {
8291
+ return;
8503
8292
  }
8504
- let packageJsonUrl = new URL$1(
8505
- "./node_modules/" + packageName + "/package.json",
8506
- base
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
+ )
8507
8300
  );
8508
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8509
- let lastPath;
8510
- do {
8511
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8512
- if (!stat || !stat.isDirectory()) {
8513
- lastPath = packageJsonPath;
8514
- packageJsonUrl = new URL$1(
8515
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8516
- packageJsonUrl
8517
- );
8518
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8519
- continue;
8520
- }
8521
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8522
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8523
- return packageExportsResolve(
8524
- packageJsonUrl,
8525
- packageSubpath,
8526
- packageConfig2,
8527
- base,
8528
- conditions
8529
- );
8530
- }
8531
- if (packageSubpath === ".") {
8532
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8533
- }
8534
- return new URL$1(packageSubpath, packageJsonUrl);
8535
- } while (packageJsonPath.length !== lastPath.length);
8536
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8537
8301
  }
8538
- function isRelativeSpecifier(specifier) {
8539
- if (specifier[0] === ".") {
8540
- if (specifier.length === 1 || specifier[1] === "/") return true;
8541
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8542
- return true;
8543
- }
8544
- }
8545
- return false;
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");
8546
8310
  }
8547
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8548
- if (specifier === "") return false;
8549
- if (specifier[0] === "/") return true;
8550
- return isRelativeSpecifier(specifier);
8311
+ function getWorkerConfigPaths(root) {
8312
+ const deployConfigPath = getDeployConfigPath(root);
8313
+ const deployConfig = JSON.parse(
8314
+ fs2.readFileSync(deployConfigPath, "utf-8")
8315
+ );
8316
+ return [
8317
+ { configPath: deployConfig.configPath },
8318
+ ...deployConfig.auxiliaryWorkers
8319
+ ].map(
8320
+ ({ configPath }) => path3.resolve(path3.dirname(deployConfigPath), configPath)
8321
+ );
8551
8322
  }
8552
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8553
- const protocol = base.protocol;
8554
- const isData = protocol === "data:";
8555
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8556
- let resolved;
8557
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8558
- try {
8559
- resolved = new URL$1(specifier, base);
8560
- } catch (error_) {
8561
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8562
- error.cause = error_;
8563
- throw error;
8564
- }
8565
- } else if (protocol === "file:" && specifier[0] === "#") {
8566
- resolved = packageImportsResolve(specifier, base, conditions);
8323
+ function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
8324
+ return path3.relative(
8325
+ deployConfigDirectory,
8326
+ path3.resolve(root, outputDirectory, "wrangler.json")
8327
+ );
8328
+ }
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));
8567
8348
  } else {
8568
- try {
8569
- resolved = new URL$1(specifier);
8570
- } catch (error_) {
8571
- if (isRemote && !builtinModules.includes(specifier)) {
8572
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8573
- error.cause = error_;
8574
- 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 });
8575
8366
  }
8576
- resolved = packageResolve(specifier, base, conditions);
8577
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));
8578
8377
  }
8579
- assert5(resolved !== void 0, "expected to be defined");
8580
- if (resolved.protocol !== "file:") {
8581
- return resolved;
8582
- }
8583
- return finalizeResolution(resolved, base);
8584
- }
8585
- function fileURLToPath2(id) {
8586
- if (typeof id === "string" && !id.startsWith("file://")) {
8587
- return normalizeSlash(id);
8588
- }
8589
- return normalizeSlash(fileURLToPath$1(id));
8590
8378
  }
8591
- function pathToFileURL(id) {
8592
- 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);
8593
8386
  }
8594
- function normalizeid(id) {
8595
- if (typeof id !== "string") {
8596
- id = id.toString();
8597
- }
8598
- if (/(node|data|http|https|file):/.test(id)) {
8599
- return id;
8600
- }
8601
- if (BUILTIN_MODULES.has(id)) {
8602
- 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 {};
8603
8409
  }
8604
- 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
+ };
8605
8424
  }
8606
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8607
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8608
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8609
- "ERR_MODULE_NOT_FOUND",
8610
- "ERR_UNSUPPORTED_DIR_IMPORT",
8611
- "MODULE_NOT_FOUND",
8612
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8613
- ]);
8614
- function _tryModuleResolve(id, url, conditions) {
8615
- try {
8616
- return moduleResolve(id, url, conditions);
8617
- } catch (error) {
8618
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8619
- 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
+ }
8620
8440
  }
8621
8441
  }
8442
+ return workerToWorkerEntrypointNamesMap;
8622
8443
  }
8623
- function _resolve(id, options = {}) {
8624
- if (typeof id !== "string") {
8625
- if (id instanceof URL) {
8626
- id = fileURLToPath2(id);
8627
- } else {
8628
- 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
+ }
8629
8469
  }
8630
8470
  }
8631
- if (/(node|data|http|https):/.test(id)) {
8632
- return id;
8633
- }
8634
- if (BUILTIN_MODULES.has(id)) {
8635
- 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
+ }
8636
8493
  }
8637
- if (id.startsWith("file://")) {
8638
- 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;
8639
8504
  }
8640
- if (isAbsolute(id)) {
8641
- try {
8642
- const stat = statSync2(id);
8643
- if (stat.isFile()) {
8644
- 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 } : {}
8645
8533
  }
8646
- } catch (error) {
8647
- if (error?.code !== "ENOENT") {
8648
- 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
+ }
8649
8579
  }
8650
8580
  }
8651
- }
8652
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8653
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8654
- if (_urls.length === 0) {
8655
- _urls.push(new URL(pathToFileURL(process.cwd())));
8656
- }
8657
- const urls = [..._urls];
8658
- for (const url of _urls) {
8659
- if (url.protocol === "file:") {
8660
- urls.push(
8661
- new URL("./", url),
8662
- // If url is directory
8663
- new URL(joinURL(url.pathname, "_index.js"), url),
8664
- // TODO: Remove in next major version?
8665
- 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
8666
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
+ };
8667
8632
  }
8668
- }
8669
- let resolved;
8670
- for (const url of urls) {
8671
- resolved = _tryModuleResolve(id, url, conditionsSet);
8672
- if (resolved) {
8673
- break;
8674
- }
8675
- for (const prefix of ["", "/index"]) {
8676
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8677
- resolved = _tryModuleResolve(
8678
- joinURL(id, prefix) + extension,
8679
- url,
8680
- 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
8681
8665
  );
8682
- if (resolved) {
8683
- break;
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
+ );
8684
8674
  }
8685
- }
8686
- if (resolved) {
8687
- break;
8688
- }
8689
- }
8690
- if (resolved) {
8691
- break;
8692
- }
8693
- }
8694
- if (!resolved) {
8695
- const error = new Error(
8696
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8697
- );
8698
- error.code = "ERR_MODULE_NOT_FOUND";
8699
- throw error;
8700
- }
8701
- return pathToFileURL(resolved);
8702
- }
8703
- function resolveSync(id, options) {
8704
- return _resolve(id, options);
8705
- }
8706
- function resolvePathSync(id, options) {
8707
- return fileURLToPath2(resolveSync(id, options));
8708
- }
8709
-
8710
- // src/node-js-compat.ts
8711
- import { defineEnv } from "unenv";
8712
- var { env } = defineEnv({
8713
- nodeCompat: true,
8714
- presets: [cloudflare]
8715
- });
8716
- function isNodeCompat(workerConfig) {
8717
- if (workerConfig === void 0) {
8718
- return false;
8719
- }
8720
- const nodeCompatMode = getNodeCompat(
8721
- workerConfig.compatibility_date,
8722
- workerConfig.compatibility_flags ?? []
8723
- ).mode;
8724
- if (nodeCompatMode === "v2") {
8725
- return true;
8726
- }
8727
- if (nodeCompatMode === "legacy") {
8728
- throw new Error(
8729
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8730
- );
8731
- }
8732
- if (nodeCompatMode === "v1") {
8733
- throw new Error(
8734
- `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`
8735
- );
8736
- }
8737
- return false;
8738
- }
8739
- function getNodeCompatEntries() {
8740
- const entries = new Set(Object.values(env.alias));
8741
- for (const globalInject of Object.values(env.inject)) {
8742
- if (typeof globalInject === "string") {
8743
- entries.add(globalInject);
8744
- } else {
8675
+ const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8676
+ workerOptions.name
8677
+ );
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
+ );
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");
8745
8720
  assert6(
8746
- globalInject[0] !== void 0,
8747
- "Expected first element of globalInject to be defined"
8721
+ rawSpecifier,
8722
+ `Unexpected error: no specifier in request to module fallback service.`
8748
8723
  );
8749
- entries.add(globalInject[0]);
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
+ );
8739
+ }
8740
+ return MiniflareResponse.json({
8741
+ // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
8742
+ wasm: Array.from(source)
8743
+ });
8750
8744
  }
8751
- }
8752
- for (const external of env.external) {
8753
- entries.delete(external);
8754
- }
8755
- return entries;
8745
+ };
8756
8746
  }
8757
- function injectGlobalCode(id, code) {
8758
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8759
- if (typeof globalInject === "string") {
8760
- const moduleSpecifier2 = globalInject;
8761
- return `import var_${globalName} from "${moduleSpecifier2}";
8762
- globalThis.${globalName} = var_${globalName};
8763
- `;
8764
- }
8765
- const [moduleSpecifier, exportName] = globalInject;
8766
- assert6(
8767
- moduleSpecifier !== void 0,
8768
- "Expected moduleSpecifier to be defined"
8769
- );
8770
- assert6(exportName !== void 0, "Expected exportName to be defined");
8771
- return `import var_${globalName} from "${moduleSpecifier}";
8772
- globalThis.${globalName} = var_${globalName}.${exportName};
8773
- `;
8774
- }).join("\n");
8775
- const modified = new MagicString(code);
8776
- modified.prepend(injectedCode);
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);
8777
8751
  return {
8778
- code: modified.toString(),
8779
- map: modified.generateMap({ hires: "boundary", source: id })
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
+ ]
8780
8765
  };
8781
8766
  }
8782
- function getNodeCompatExternals() {
8783
- return env.external;
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);
8787
+ return {
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
8798
+ };
8784
8799
  }
8785
- function resolveNodeJSImport(source) {
8786
- const alias = env.alias[source];
8787
- if (alias) {
8788
- return {
8789
- unresolved: alias,
8790
- resolved: resolvePathSync(alias, { url: import.meta.url })
8791
- };
8800
+ var ViteMiniflareLogger = class extends Log {
8801
+ logger;
8802
+ constructor(config) {
8803
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8804
+ this.logger = config.logger;
8805
+ }
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);
8817
+ }
8818
+ }
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;
8792
8830
  }
8793
8831
  }
8794
8832
 
@@ -8834,7 +8872,6 @@ var nonApplicableWorkerConfigs = {
8834
8872
  "build",
8835
8873
  "find_additional_modules",
8836
8874
  "no_bundle",
8837
- "node_compat",
8838
8875
  "preserve_file_names",
8839
8876
  "site",
8840
8877
  "tsconfig",
@@ -8851,7 +8888,6 @@ var nullableNonApplicable = [
8851
8888
  "find_additional_modules",
8852
8889
  "minify",
8853
8890
  "no_bundle",
8854
- "node_compat",
8855
8891
  "preserve_file_names",
8856
8892
  "site",
8857
8893
  "tsconfig",
@@ -9002,6 +9038,17 @@ function getWorkerConfig(configPath, env2, opts) {
9002
9038
  };
9003
9039
  }
9004
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
+ }
9005
9052
  return {
9006
9053
  type: "worker",
9007
9054
  raw,
@@ -9102,9 +9149,10 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9102
9149
  }
9103
9150
 
9104
9151
  // src/websockets.ts
9105
- import ws from "ws";
9106
- function handleWebSocket(httpServer, fetcher, logger) {
9107
- const nodeWebSocket = new ws.Server({ noServer: true });
9152
+ import { coupleWebSocket } from "miniflare";
9153
+ import { WebSocketServer } from "ws";
9154
+ function handleWebSocket(httpServer, fetcher) {
9155
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9108
9156
  httpServer.on(
9109
9157
  "upgrade",
9110
9158
  async (request, socket, head) => {
@@ -9127,34 +9175,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9127
9175
  socket,
9128
9176
  head,
9129
9177
  async (clientWebSocket) => {
9130
- workerWebSocket.accept();
9131
- workerWebSocket.addEventListener("message", (event) => {
9132
- clientWebSocket.send(event.data);
9133
- });
9134
- workerWebSocket.addEventListener("error", (event) => {
9135
- logger.error(
9136
- `WebSocket error:
9137
- ${event.error?.stack || event.error?.message}`,
9138
- { error: event.error }
9139
- );
9140
- });
9141
- workerWebSocket.addEventListener("close", () => {
9142
- clientWebSocket.close();
9143
- });
9144
- clientWebSocket.on("message", (data2, isBinary) => {
9145
- workerWebSocket.send(
9146
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9147
- );
9148
- });
9149
- clientWebSocket.on("error", (error) => {
9150
- logger.error(`WebSocket error:
9151
- ${error.stack || error.message}`, {
9152
- error
9153
- });
9154
- });
9155
- clientWebSocket.on("close", () => {
9156
- workerWebSocket.close();
9157
- });
9178
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9158
9179
  nodeWebSocket.emit("connection", clientWebSocket, request);
9159
9180
  }
9160
9181
  );
@@ -9213,7 +9234,7 @@ function cloudflare2(pluginConfig = {}) {
9213
9234
  }
9214
9235
  } : void 0,
9215
9236
  builder: {
9216
- async buildApp(builder) {
9237
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9217
9238
  const clientEnvironment = builder.environments.client;
9218
9239
  const defaultHtmlPath = path7.resolve(
9219
9240
  builder.config.root,
@@ -9239,7 +9260,7 @@ function cloudflare2(pluginConfig = {}) {
9239
9260
  )
9240
9261
  );
9241
9262
  }
9242
- }
9263
+ })
9243
9264
  }
9244
9265
  };
9245
9266
  },
@@ -9300,7 +9321,7 @@ function cloudflare2(pluginConfig = {}) {
9300
9321
  return;
9301
9322
  }
9302
9323
  config.no_bundle = true;
9303
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9324
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9304
9325
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9305
9326
  config.unsafe = void 0;
9306
9327
  }
@@ -9347,11 +9368,7 @@ function cloudflare2(pluginConfig = {}) {
9347
9368
  },
9348
9369
  { alwaysCallNext: false }
9349
9370
  );
9350
- handleWebSocket(
9351
- viteDevServer.httpServer,
9352
- entryWorker.fetch,
9353
- viteDevServer.config.logger
9354
- );
9371
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9355
9372
  return () => {
9356
9373
  viteDevServer.middlewares.use((req, res, next) => {
9357
9374
  middleware(req, res, next);
@@ -9373,16 +9390,10 @@ function cloudflare2(pluginConfig = {}) {
9373
9390
  },
9374
9391
  { alwaysCallNext: false }
9375
9392
  );
9376
- handleWebSocket(
9377
- vitePreviewServer.httpServer,
9378
- miniflare2.dispatchFetch,
9379
- vitePreviewServer.config.logger
9380
- );
9381
- return () => {
9382
- vitePreviewServer.middlewares.use((req, res, next) => {
9383
- middleware(req, res, next);
9384
- });
9385
- };
9393
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9394
+ vitePreviewServer.middlewares.use((req, res, next) => {
9395
+ middleware(req, res, next);
9396
+ });
9386
9397
  }
9387
9398
  },
9388
9399
  // Plugin to support `CompiledWasm` modules
@@ -9462,7 +9473,7 @@ function cloudflare2(pluginConfig = {}) {
9462
9473
  if (isNodeCompat(getWorkerConfig2(name2))) {
9463
9474
  return {
9464
9475
  resolve: {
9465
- builtins: getNodeCompatExternals()
9476
+ builtins: [...nodeCompatExternals]
9466
9477
  },
9467
9478
  optimizeDeps: {
9468
9479
  // This is a list of dependency entry-points that should be pre-bundled.
@@ -9470,7 +9481,8 @@ function cloudflare2(pluginConfig = {}) {
9470
9481
  // ready ahead the first request to the dev server.
9471
9482
  // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9472
9483
  // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9473
- include: [...getNodeCompatEntries()],
9484
+ // TODO: work out how to re-enable pre-bundling of these
9485
+ // include: [...getNodeCompatEntries()],
9474
9486
  // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9475
9487
  // In this case we provide a list of all the Node.js modules, both those built-in to workerd and those that will be polyfilled.
9476
9488
  // Obviously we don't want/need the optimizer to try to process modules that are built-in;
@@ -9501,7 +9513,11 @@ function cloudflare2(pluginConfig = {}) {
9501
9513
  this.environment.depsOptimizer,
9502
9514
  "depsOptimizer is required in dev mode"
9503
9515
  );
9504
- return this.resolve(result.unresolved, importer, options);
9516
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9517
+ result.unresolved,
9518
+ result.resolved
9519
+ );
9520
+ return this.resolve(id, importer, options);
9505
9521
  }
9506
9522
  return this.resolve(result.resolved, importer, options);
9507
9523
  },