@cloudflare/vite-plugin 0.0.0-62aaf44c0 → 0.0.0-62d5471ea

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // src/index.ts
2
2
  import assert9 from "node:assert";
3
3
  import * as fs5 from "node:fs";
4
+ import { builtinModules as builtinModules2 } from "node:module";
4
5
  import * as path7 from "node:path";
5
6
  import { createMiddleware } from "@hattip/adapter-node";
6
7
 
@@ -1073,715 +1074,11 @@ import { Miniflare } from "miniflare";
1073
1074
  import * as vite6 from "vite";
1074
1075
 
1075
1076
  // src/cloudflare-environment.ts
1076
- import assert from "node:assert";
1077
- import * as vite2 from "vite";
1078
-
1079
- // src/constants.ts
1080
- var ROUTER_WORKER_NAME = "__router-worker__";
1081
- var ASSET_WORKER_NAME = "__asset-worker__";
1082
- var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1083
- var MODULE_TYPES = ["CompiledWasm"];
1084
-
1085
- // src/shared.ts
1086
- var UNKNOWN_HOST = "http://localhost";
1087
- var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1088
- var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1089
-
1090
- // src/utils.ts
1091
- import { builtinModules } from "node:module";
1092
- import * as path from "node:path";
1093
- import { Request as MiniflareRequest } from "miniflare";
1094
- import "vite";
1095
- var nodeBuiltInModules = new Set(
1096
- builtinModules.concat(builtinModules.map((m) => `node:${m}`))
1097
- );
1098
- function getOutputDirectory(userConfig, environmentName) {
1099
- const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
1100
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
1101
- }
1102
- function toMiniflareRequest(request) {
1103
- return new MiniflareRequest(request.url, {
1104
- method: request.method,
1105
- headers: [["accept-encoding", "identity"], ...request.headers],
1106
- body: request.body,
1107
- duplex: "half"
1108
- });
1109
- }
1110
- function nodeHeadersToWebHeaders(nodeHeaders) {
1111
- const headers = new Headers();
1112
- for (const [key, value] of Object.entries(nodeHeaders)) {
1113
- if (typeof value === "string") {
1114
- headers.append(key, value);
1115
- } else if (Array.isArray(value)) {
1116
- for (const item of value) {
1117
- headers.append(key, item);
1118
- }
1119
- }
1120
- }
1121
- return headers;
1122
- }
1123
-
1124
- // src/cloudflare-environment.ts
1125
- var webSocketUndefinedError = "The WebSocket is undefined";
1126
- function createHotChannel(webSocketContainer) {
1127
- const listenersMap = /* @__PURE__ */ new Map();
1128
- const client = {
1129
- send(payload) {
1130
- const webSocket = webSocketContainer.webSocket;
1131
- assert(webSocket, webSocketUndefinedError);
1132
- webSocket.send(JSON.stringify(payload));
1133
- }
1134
- };
1135
- function onMessage(event) {
1136
- const payload = JSON.parse(event.data.toString());
1137
- const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
1138
- for (const listener of listeners) {
1139
- listener(payload.data, client);
1140
- }
1141
- }
1142
- return {
1143
- send(payload) {
1144
- const webSocket = webSocketContainer.webSocket;
1145
- assert(webSocket, webSocketUndefinedError);
1146
- webSocket.send(JSON.stringify(payload));
1147
- },
1148
- on(event, listener) {
1149
- const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
1150
- listeners.add(listener);
1151
- listenersMap.set(event, listeners);
1152
- },
1153
- off(event, listener) {
1154
- listenersMap.get(event)?.delete(listener);
1155
- },
1156
- listen() {
1157
- const webSocket = webSocketContainer.webSocket;
1158
- assert(webSocket, webSocketUndefinedError);
1159
- webSocket.addEventListener("message", onMessage);
1160
- },
1161
- close() {
1162
- const webSocket = webSocketContainer.webSocket;
1163
- assert(webSocket, webSocketUndefinedError);
1164
- webSocket.removeEventListener("message", onMessage);
1165
- }
1166
- };
1167
- }
1168
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
1169
- #webSocketContainer;
1170
- #worker;
1171
- constructor(name2, config) {
1172
- const webSocketContainer = {};
1173
- super(name2, config, {
1174
- hot: true,
1175
- transport: createHotChannel(webSocketContainer)
1176
- });
1177
- this.#webSocketContainer = webSocketContainer;
1178
- }
1179
- async initRunner(worker) {
1180
- this.#worker = worker;
1181
- const response = await this.#worker.fetch(
1182
- new URL(INIT_PATH, UNKNOWN_HOST),
1183
- {
1184
- headers: {
1185
- upgrade: "websocket"
1186
- }
1187
- }
1188
- );
1189
- assert(
1190
- response.ok,
1191
- `Failed to initialize module runner, error: ${await response.text()}`
1192
- );
1193
- const webSocket = response.webSocket;
1194
- assert(webSocket, "Failed to establish WebSocket");
1195
- webSocket.accept();
1196
- this.#webSocketContainer.webSocket = webSocket;
1197
- }
1198
- };
1199
- var cloudflareBuiltInModules = [
1200
- "cloudflare:email",
1201
- "cloudflare:sockets",
1202
- "cloudflare:workers",
1203
- "cloudflare:workflows"
1204
- ];
1205
- var defaultConditions = ["workerd", "module", "browser"];
1206
- function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1207
- return {
1208
- resolve: {
1209
- // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
1210
- // dependencies as not external
1211
- noExternal: true,
1212
- // We want to use `workerd` package exports if available (e.g. for postgres).
1213
- conditions: [...defaultConditions, "development|production"],
1214
- // The Cloudflare ones are proper builtins in the environment
1215
- builtins: [...cloudflareBuiltInModules],
1216
- // The Node.js ones are no proper builtins in the environment since we also polyfill them using unenv
1217
- external: [...nodeBuiltInModules]
1218
- },
1219
- dev: {
1220
- createEnvironment(name2, config) {
1221
- return new CloudflareDevEnvironment(name2, config);
1222
- }
1223
- },
1224
- build: {
1225
- createEnvironment(name2, config) {
1226
- return new vite2.BuildEnvironment(name2, config);
1227
- },
1228
- target: "es2022",
1229
- // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1230
- emitAssets: true,
1231
- outDir: getOutputDirectory(userConfig, environmentName),
1232
- copyPublicDir: false,
1233
- ssr: true,
1234
- rollupOptions: {
1235
- // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
1236
- // so the input value here serves both as the build input as well as the starting point for
1237
- // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
1238
- // optimizeDeps.entries in the dev config)
1239
- input: workerConfig.main
1240
- }
1241
- },
1242
- optimizeDeps: {
1243
- // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1244
- noDiscovery: false,
1245
- entries: workerConfig.main,
1246
- exclude: [
1247
- // we have to exclude all node modules to work in dev-mode not just the unenv externals...
1248
- ...nodeBuiltInModules
1249
- ],
1250
- esbuildOptions: {
1251
- platform: "neutral",
1252
- conditions: [...defaultConditions, "development"],
1253
- resolveExtensions: [
1254
- ".mjs",
1255
- ".js",
1256
- ".mts",
1257
- ".ts",
1258
- ".jsx",
1259
- ".tsx",
1260
- ".json",
1261
- ".cjs",
1262
- ".cts",
1263
- ".ctx"
1264
- ]
1265
- }
1266
- },
1267
- keepProcessEnv: false
1268
- };
1269
- }
1270
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
1271
- if (resolvedPluginConfig.type === "assets-only") {
1272
- return;
1273
- }
1274
- return Promise.all(
1275
- Object.entries(resolvedPluginConfig.workers).map(
1276
- async ([environmentName, workerConfig]) => {
1277
- const worker = await miniflare.getWorker(workerConfig.name);
1278
- return viteDevServer.environments[environmentName].initRunner(worker);
1279
- }
1280
- )
1281
- );
1282
- }
1283
-
1284
- // src/deploy-config.ts
1285
- import assert2 from "node:assert";
1286
- import * as fs from "node:fs";
1287
- import * as path2 from "node:path";
1288
- import "vite";
1289
- function getDeployConfigPath(root) {
1290
- return path2.resolve(root, ".wrangler", "deploy", "config.json");
1291
- }
1292
- function getWorkerConfigPaths(root) {
1293
- const deployConfigPath = getDeployConfigPath(root);
1294
- const deployConfig = JSON.parse(
1295
- fs.readFileSync(deployConfigPath, "utf-8")
1296
- );
1297
- return [
1298
- { configPath: deployConfig.configPath },
1299
- ...deployConfig.auxiliaryWorkers
1300
- ].map(
1301
- ({ configPath }) => path2.resolve(path2.dirname(deployConfigPath), configPath)
1302
- );
1303
- }
1304
- function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
1305
- return path2.relative(
1306
- deployConfigDirectory,
1307
- path2.resolve(root, outputDirectory, "wrangler.json")
1308
- );
1309
- }
1310
- function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1311
- const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
1312
- const deployConfigDirectory = path2.dirname(deployConfigPath);
1313
- fs.mkdirSync(deployConfigDirectory, { recursive: true });
1314
- if (resolvedPluginConfig.type === "assets-only") {
1315
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
1316
- assert2(
1317
- clientOutputDirectory,
1318
- "Unexpected error: client environment output directory is undefined"
1319
- );
1320
- const deployConfig = {
1321
- configPath: getRelativePathToWorkerConfig(
1322
- deployConfigDirectory,
1323
- resolvedViteConfig.root,
1324
- clientOutputDirectory
1325
- ),
1326
- auxiliaryWorkers: []
1327
- };
1328
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1329
- } else {
1330
- let entryWorkerConfigPath;
1331
- const auxiliaryWorkers = [];
1332
- for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
1333
- const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
1334
- assert2(
1335
- outputDirectory,
1336
- `Unexpected error: ${environmentName} environment output directory is undefined`
1337
- );
1338
- const configPath = getRelativePathToWorkerConfig(
1339
- deployConfigDirectory,
1340
- resolvedViteConfig.root,
1341
- outputDirectory
1342
- );
1343
- if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
1344
- entryWorkerConfigPath = configPath;
1345
- } else {
1346
- auxiliaryWorkers.push({ configPath });
1347
- }
1348
- }
1349
- assert2(
1350
- entryWorkerConfigPath,
1351
- `Unexpected error: entryWorkerConfigPath is undefined`
1352
- );
1353
- const deployConfig = {
1354
- configPath: entryWorkerConfigPath,
1355
- auxiliaryWorkers
1356
- };
1357
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1358
- }
1359
- }
1360
-
1361
- // src/dev.ts
1362
- import assert3 from "node:assert";
1363
- function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1364
- const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1365
- assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
1366
- return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
1367
- }
1368
-
1369
- // src/miniflare-options.ts
1370
- import assert4 from "node:assert";
1371
- import * as fs2 from "node:fs";
1372
- import * as fsp from "node:fs/promises";
1373
- import * as path3 from "node:path";
1374
- import { fileURLToPath } from "node:url";
1375
- import { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
1376
- import "vite";
1377
- import {
1378
- unstable_getMiniflareWorkerOptions,
1379
- unstable_readConfig
1380
- } from "wrangler";
1381
- function getPersistence(root, persistState) {
1382
- if (persistState === false) {
1383
- return {};
1384
- }
1385
- const defaultPersistPath = ".wrangler/state";
1386
- const persistPath = path3.resolve(
1387
- root,
1388
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1389
- "v3"
1390
- );
1391
- return {
1392
- cachePersist: path3.join(persistPath, "cache"),
1393
- d1Persist: path3.join(persistPath, "d1"),
1394
- durableObjectsPersist: path3.join(persistPath, "do"),
1395
- kvPersist: path3.join(persistPath, "kv"),
1396
- r2Persist: path3.join(persistPath, "r2"),
1397
- workflowsPersist: path3.join(persistPath, "workflows")
1398
- };
1399
- }
1400
- function missingWorkerErrorMessage(workerName) {
1401
- return `${workerName} does not match a worker name.`;
1402
- }
1403
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1404
- const workerToWorkerEntrypointNamesMap = new Map(
1405
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1406
- );
1407
- for (const worker of workers) {
1408
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1409
- if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1410
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(
1411
- value.name
1412
- );
1413
- assert4(entrypointNames, missingWorkerErrorMessage(value.name));
1414
- entrypointNames.add(value.entrypoint);
1415
- }
1416
- }
1417
- }
1418
- return workerToWorkerEntrypointNamesMap;
1419
- }
1420
- function getWorkerToDurableObjectClassNamesMap(workers) {
1421
- const workerToDurableObjectClassNamesMap = new Map(
1422
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1423
- );
1424
- for (const worker of workers) {
1425
- for (const value of Object.values(worker.durableObjects ?? {})) {
1426
- if (typeof value === "string") {
1427
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1428
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1429
- classNames.add(value);
1430
- } else if (typeof value === "object") {
1431
- if (value.scriptName) {
1432
- const classNames = workerToDurableObjectClassNamesMap.get(
1433
- value.scriptName
1434
- );
1435
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1436
- classNames.add(value.className);
1437
- } else {
1438
- const classNames = workerToDurableObjectClassNamesMap.get(
1439
- worker.name
1440
- );
1441
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1442
- classNames.add(value.className);
1443
- }
1444
- }
1445
- }
1446
- }
1447
- return workerToDurableObjectClassNamesMap;
1448
- }
1449
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1450
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1451
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1452
- );
1453
- for (const worker of workers) {
1454
- for (const value of Object.values(worker.workflows ?? {})) {
1455
- if (value.scriptName) {
1456
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1457
- value.scriptName
1458
- );
1459
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1460
- classNames.add(value.className);
1461
- } else {
1462
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1463
- worker.name
1464
- );
1465
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1466
- classNames.add(value.className);
1467
- }
1468
- }
1469
- }
1470
- return workerToWorkflowEntrypointClassNamesMap;
1471
- }
1472
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1473
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1474
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1475
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1476
- var RUNNER_PATH = "./runner-worker/index.js";
1477
- function getEntryWorkerConfig(resolvedPluginConfig) {
1478
- if (resolvedPluginConfig.type === "assets-only") {
1479
- return;
1480
- }
1481
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1482
- }
1483
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1484
- const resolvedViteConfig = viteDevServer.config;
1485
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1486
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1487
- const assetWorkers = [
1488
- {
1489
- name: ROUTER_WORKER_NAME,
1490
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1491
- modulesRoot: miniflareModulesRoot,
1492
- modules: [
1493
- {
1494
- type: "ESModule",
1495
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1496
- contents: fs2.readFileSync(
1497
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1498
- )
1499
- }
1500
- ],
1501
- bindings: {
1502
- CONFIG: {
1503
- has_user_worker: resolvedPluginConfig.type === "workers"
1504
- }
1505
- },
1506
- serviceBindings: {
1507
- ASSET_WORKER: ASSET_WORKER_NAME,
1508
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1509
- }
1510
- },
1511
- {
1512
- name: ASSET_WORKER_NAME,
1513
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1514
- modulesRoot: miniflareModulesRoot,
1515
- modules: [
1516
- {
1517
- type: "ESModule",
1518
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1519
- contents: fs2.readFileSync(
1520
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1521
- )
1522
- }
1523
- ],
1524
- bindings: {
1525
- CONFIG: {
1526
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1527
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1528
- }
1529
- },
1530
- serviceBindings: {
1531
- __VITE_ASSET_EXISTS__: async (request) => {
1532
- const { pathname } = new URL(request.url);
1533
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1534
- let exists;
1535
- try {
1536
- exists = fs2.statSync(filePath).isFile();
1537
- } catch (error) {
1538
- exists = false;
1539
- }
1540
- return MiniflareResponse.json(exists);
1541
- },
1542
- __VITE_FETCH_ASSET__: async (request) => {
1543
- const { pathname } = new URL(request.url);
1544
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1545
- try {
1546
- let html = await fsp.readFile(filePath, "utf-8");
1547
- html = await viteDevServer.transformIndexHtml(pathname, html);
1548
- return new MiniflareResponse(html, {
1549
- headers: { "Content-Type": "text/html" }
1550
- });
1551
- } catch (error) {
1552
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1553
- }
1554
- }
1555
- }
1556
- }
1557
- ];
1558
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1559
- ([environmentName, workerConfig]) => {
1560
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1561
- {
1562
- ...workerConfig,
1563
- assets: void 0
1564
- },
1565
- resolvedPluginConfig.cloudflareEnv
1566
- );
1567
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1568
- return {
1569
- ...workerOptions,
1570
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1571
- name: workerConfig.name,
1572
- modulesRoot: miniflareModulesRoot,
1573
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1574
- bindings: {
1575
- ...workerOptions.bindings,
1576
- __VITE_ROOT__: resolvedViteConfig.root,
1577
- __VITE_ENTRY_PATH__: workerConfig.main
1578
- },
1579
- serviceBindings: {
1580
- ...workerOptions.serviceBindings,
1581
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1582
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1583
- } : {},
1584
- __VITE_INVOKE_MODULE__: async (request) => {
1585
- const payload = await request.json();
1586
- const invokePayloadData = payload.data;
1587
- assert4(
1588
- invokePayloadData.name === "fetchModule",
1589
- `Invalid invoke event: ${invokePayloadData.name}`
1590
- );
1591
- const [moduleId] = invokePayloadData.data;
1592
- const moduleRE = new RegExp(MODULE_PATTERN);
1593
- const shouldExternalize = (
1594
- // Worker modules (CompiledWasm, Text, Data)
1595
- moduleRE.test(moduleId) || // Node.js builtin node modules (they will be resolved to unenv aliases)
1596
- nodeBuiltInModules.has(moduleId)
1597
- );
1598
- if (shouldExternalize) {
1599
- const result2 = {
1600
- externalize: moduleId,
1601
- type: "module"
1602
- };
1603
- return MiniflareResponse.json({ result: result2 });
1604
- }
1605
- const devEnvironment = viteDevServer.environments[environmentName];
1606
- const result = await devEnvironment.hot.handleInvoke(payload);
1607
- return MiniflareResponse.json(result);
1608
- }
1609
- }
1610
- };
1611
- }
1612
- ) : [];
1613
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1614
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1615
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1616
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1617
- return {
1618
- log: logger,
1619
- handleRuntimeStdio(stdout, stderr) {
1620
- const decoder = new TextDecoder();
1621
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1622
- stderr.forEach(
1623
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1624
- );
1625
- },
1626
- ...getPersistence(
1627
- resolvedViteConfig.root,
1628
- resolvedPluginConfig.persistState
1629
- ),
1630
- workers: [
1631
- ...assetWorkers,
1632
- ...userWorkers.map((workerOptions) => {
1633
- const wrappers = [
1634
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1635
- `export default createWorkerEntrypointWrapper('default');`
1636
- ];
1637
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1638
- workerOptions.name
1639
- );
1640
- assert4(
1641
- workerEntrypointNames,
1642
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1643
- );
1644
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1645
- wrappers.push(
1646
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1647
- );
1648
- }
1649
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1650
- workerOptions.name
1651
- );
1652
- assert4(
1653
- durableObjectClassNames,
1654
- `DurableObject class names not found for worker ${workerOptions.name}`
1655
- );
1656
- for (const className of [...durableObjectClassNames].sort()) {
1657
- wrappers.push(
1658
- `export const ${className} = createDurableObjectWrapper('${className}');`
1659
- );
1660
- }
1661
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1662
- assert4(
1663
- workflowEntrypointClassNames,
1664
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1665
- );
1666
- for (const className of [...workflowEntrypointClassNames].sort()) {
1667
- wrappers.push(
1668
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1669
- );
1670
- }
1671
- return {
1672
- ...workerOptions,
1673
- modules: [
1674
- {
1675
- type: "ESModule",
1676
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1677
- contents: wrappers.join("\n")
1678
- },
1679
- {
1680
- type: "ESModule",
1681
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1682
- contents: fs2.readFileSync(
1683
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1684
- )
1685
- }
1686
- ],
1687
- unsafeUseModuleFallbackService: true
1688
- };
1689
- })
1690
- ],
1691
- unsafeModuleFallbackService(request) {
1692
- const url = new URL(request.url);
1693
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1694
- assert4(
1695
- rawSpecifier,
1696
- `Unexpected error: no specifier in request to module fallback service.`
1697
- );
1698
- const moduleRE = new RegExp(MODULE_PATTERN);
1699
- const match = moduleRE.exec(rawSpecifier);
1700
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1701
- const [full, moduleType, modulePath] = match;
1702
- assert4(
1703
- modulePath,
1704
- `Unexpected error: module path not found in reference ${full}.`
1705
- );
1706
- let source;
1707
- try {
1708
- source = fs2.readFileSync(modulePath);
1709
- } catch (error) {
1710
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1711
- }
1712
- return MiniflareResponse.json({
1713
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1714
- wasm: Array.from(source)
1715
- });
1716
- }
1717
- };
1718
- }
1719
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1720
- const resolvedViteConfig = vitePreviewServer.config;
1721
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1722
- const workerConfigs = configPaths.map(
1723
- (configPath) => unstable_readConfig({ config: configPath })
1724
- );
1725
- const workers = workerConfigs.map((config) => {
1726
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1727
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1728
- return {
1729
- ...workerOptions,
1730
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1731
- name: config.name,
1732
- modules: true,
1733
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1734
- };
1735
- });
1736
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1737
- return {
1738
- log: logger,
1739
- handleRuntimeStdio(stdout, stderr) {
1740
- const decoder = new TextDecoder();
1741
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1742
- stderr.forEach(
1743
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1744
- );
1745
- },
1746
- ...getPersistence(resolvedViteConfig.root, persistState),
1747
- workers
1748
- };
1749
- }
1750
- var ViteMiniflareLogger = class extends Log {
1751
- logger;
1752
- constructor(config) {
1753
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1754
- this.logger = config.logger;
1755
- }
1756
- logWithLevel(level, message) {
1757
- if (/^Ready on http/.test(message)) {
1758
- level = LogLevel.DEBUG;
1759
- }
1760
- switch (level) {
1761
- case LogLevel.ERROR:
1762
- return this.logger.error(message);
1763
- case LogLevel.WARN:
1764
- return this.logger.warn(message);
1765
- case LogLevel.INFO:
1766
- return this.logger.info(message);
1767
- }
1768
- }
1769
- };
1770
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1771
- switch (level) {
1772
- case "error":
1773
- return LogLevel.ERROR;
1774
- case "warn":
1775
- return LogLevel.WARN;
1776
- case "info":
1777
- return LogLevel.INFO;
1778
- case "silent":
1779
- return LogLevel.NONE;
1780
- }
1781
- }
1077
+ import assert3 from "node:assert";
1078
+ import * as vite2 from "vite";
1782
1079
 
1783
1080
  // src/node-js-compat.ts
1784
- import assert6 from "node:assert";
1081
+ import assert2 from "node:assert";
1785
1082
  import { cloudflare } from "@cloudflare/unenv-preset";
1786
1083
  import { getNodeCompat } from "miniflare";
1787
1084
 
@@ -7313,8 +6610,8 @@ Parser.acorn = {
7313
6610
  };
7314
6611
 
7315
6612
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7316
- import { builtinModules as builtinModules2, createRequire } from "node:module";
7317
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6613
+ import { builtinModules, createRequire } from "node:module";
6614
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7318
6615
 
7319
6616
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7320
6617
  var r = String.fromCharCode;
@@ -7371,12 +6668,12 @@ var isAbsolute = function(p) {
7371
6668
 
7372
6669
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7373
6670
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7374
- import assert5 from "node:assert";
6671
+ import assert from "node:assert";
7375
6672
  import process$1 from "node:process";
7376
- import path4, { dirname as dirname3 } from "node:path";
6673
+ import path, { dirname as dirname2 } from "node:path";
7377
6674
  import v8 from "node:v8";
7378
6675
  import { format as format2, inspect } from "node:util";
7379
- var BUILTIN_MODULES = new Set(builtinModules2);
6676
+ var BUILTIN_MODULES = new Set(builtinModules);
7380
6677
  function normalizeSlash(path8) {
7381
6678
  return path8.replace(/\\/g, "/");
7382
6679
  }
@@ -7409,7 +6706,7 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7409
6706
  * @param {unknown} actual
7410
6707
  */
7411
6708
  (name2, expected, actual) => {
7412
- assert5(typeof name2 === "string", "'name' must be a string");
6709
+ assert(typeof name2 === "string", "'name' must be a string");
7413
6710
  if (!Array.isArray(expected)) {
7414
6711
  expected = [expected];
7415
6712
  }
@@ -7425,14 +6722,14 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7425
6722
  const instances = [];
7426
6723
  const other = [];
7427
6724
  for (const value of expected) {
7428
- assert5(
6725
+ assert(
7429
6726
  typeof value === "string",
7430
6727
  "All expected entries have to be of type string"
7431
6728
  );
7432
6729
  if (kTypes.has(value)) {
7433
6730
  types2.push(value.toLowerCase());
7434
6731
  } else if (classRegExp.exec(value) === null) {
7435
- assert5(
6732
+ assert(
7436
6733
  value !== "object",
7437
6734
  'The value "object" should be written as "Object"'
7438
6735
  );
@@ -7505,14 +6802,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7505
6802
  * @param {boolean} [isImport=false]
7506
6803
  * @param {string} [base]
7507
6804
  */
7508
- (packagePath, key, target, isImport = false, base = void 0) => {
7509
- 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("./");
7510
6807
  if (key === ".") {
7511
- assert5(isImport === false);
7512
- return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
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 "./"' : ""}`;
7513
6810
  }
7514
6811
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7515
- target
6812
+ target2
7516
6813
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7517
6814
  },
7518
6815
  Error
@@ -7673,9 +6970,9 @@ var captureLargerStackTrace = hideStackFrames(
7673
6970
  );
7674
6971
  function getMessage(key, parameters, self) {
7675
6972
  const message = messages.get(key);
7676
- assert5(message !== void 0, "expected `message` to be found");
6973
+ assert(message !== void 0, "expected `message` to be found");
7677
6974
  if (typeof message === "function") {
7678
- assert5(
6975
+ assert(
7679
6976
  message.length <= parameters.length,
7680
6977
  // Default options do not count.
7681
6978
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -7685,7 +6982,7 @@ function getMessage(key, parameters, self) {
7685
6982
  const regex = /%[dfijoOs]/g;
7686
6983
  let expectedLength = 0;
7687
6984
  while (regex.exec(message) !== null) expectedLength++;
7688
- assert5(
6985
+ assert(
7689
6986
  expectedLength === parameters.length,
7690
6987
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7691
6988
  );
@@ -7722,7 +7019,7 @@ function read(jsonPath, { base, specifier }) {
7722
7019
  }
7723
7020
  let string;
7724
7021
  try {
7725
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7022
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7726
7023
  } catch (error) {
7727
7024
  const exception = (
7728
7025
  /** @type {ErrnoException} */
@@ -7776,1028 +7073,1766 @@ function read(jsonPath, { base, specifier }) {
7776
7073
  result.type = parsed.type;
7777
7074
  }
7778
7075
  }
7779
- cache.set(jsonPath, result);
7780
- return result;
7781
- }
7782
- function getPackageScopeConfig(resolved) {
7783
- let packageJSONUrl = new URL("package.json", resolved);
7784
- while (true) {
7785
- const packageJSONPath2 = packageJSONUrl.pathname;
7786
- if (packageJSONPath2.endsWith("node_modules/package.json")) {
7787
- break;
7788
- }
7789
- const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
7790
- specifier: resolved
7791
- });
7792
- if (packageConfig.exists) {
7793
- return packageConfig;
7794
- }
7795
- const lastPackageJSONUrl = packageJSONUrl;
7796
- packageJSONUrl = new URL("../package.json", packageJSONUrl);
7797
- if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
7798
- break;
7799
- }
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";
7170
+ }
7171
+ const format3 = extensionFormatMap[value];
7172
+ if (format3) return format3;
7173
+ if (ignoreErrors) {
7174
+ return void 0;
7175
+ }
7176
+ const filepath = fileURLToPath$1(url);
7177
+ throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7178
+ }
7179
+ function getHttpProtocolModuleFormat() {
7180
+ }
7181
+ function defaultGetFormatWithoutErrors(url, context) {
7182
+ const protocol = url.protocol;
7183
+ if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7184
+ return null;
7185
+ }
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;
7211
+ }
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"
7218
+ );
7219
+ }
7220
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7221
+ if (process$1.noDeprecation) {
7222
+ return;
7223
+ }
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
+ );
7247
+ }
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;
7287
+ }
7288
+ }
7289
+ const tries = ["./index.js", "./index.json", "./index.node"];
7290
+ let i = -1;
7291
+ while (++i < tries.length) {
7292
+ guess = new URL$1(tries[i], packageJsonUrl);
7293
+ if (fileExists(guess)) break;
7294
+ guess = void 0;
7295
+ }
7296
+ if (guess) {
7297
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
7298
+ return guess;
7299
+ }
7300
+ throw new ERR_MODULE_NOT_FOUND(
7301
+ fileURLToPath$1(new URL$1(".", packageJsonUrl)),
7302
+ fileURLToPath$1(base)
7303
+ );
7304
+ }
7305
+ function finalizeResolution(resolved, base, preserveSymlinks) {
7306
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7307
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7308
+ resolved.pathname,
7309
+ 'must not include encoded "/" or "\\" characters',
7310
+ fileURLToPath$1(base)
7311
+ );
7312
+ }
7313
+ let filePath;
7314
+ try {
7315
+ filePath = fileURLToPath$1(resolved);
7316
+ } catch (error) {
7317
+ const cause = (
7318
+ /** @type {ErrnoException} */
7319
+ error
7320
+ );
7321
+ Object.defineProperty(cause, "input", { value: String(resolved) });
7322
+ Object.defineProperty(cause, "module", { value: String(base) });
7323
+ throw cause;
7324
+ }
7325
+ const stats = tryStatSync(
7326
+ filePath.endsWith("/") ? filePath.slice(-1) : filePath
7327
+ );
7328
+ if (stats && stats.isDirectory()) {
7329
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
7330
+ error.url = String(resolved);
7331
+ throw error;
7800
7332
  }
7801
- const packageJSONPath = fileURLToPath$1(packageJSONUrl);
7802
- return {
7803
- pjsonPath: packageJSONPath,
7804
- exists: false,
7805
- type: "none"
7806
- };
7333
+ if (!stats || !stats.isFile()) {
7334
+ const error = new ERR_MODULE_NOT_FOUND(
7335
+ filePath || resolved.pathname,
7336
+ base && fileURLToPath$1(base),
7337
+ true
7338
+ );
7339
+ error.url = String(resolved);
7340
+ throw error;
7341
+ }
7342
+ {
7343
+ const real = realpathSync(filePath);
7344
+ const { search, hash } = resolved;
7345
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? "/" : ""));
7346
+ resolved.search = search;
7347
+ resolved.hash = hash;
7348
+ }
7349
+ return resolved;
7807
7350
  }
7808
- function getPackageType(url) {
7809
- return getPackageScopeConfig(url).type;
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
+ );
7810
7357
  }
7811
- var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
7812
- var hasOwnProperty2 = {}.hasOwnProperty;
7813
- var extensionFormatMap = {
7814
- // @ts-expect-error: hush.
7815
- __proto__: null,
7816
- ".cjs": "commonjs",
7817
- ".js": "module",
7818
- ".json": "json",
7819
- ".mjs": "module"
7820
- };
7821
- function mimeToFormat(mime) {
7822
- if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
7823
- return "module";
7824
- if (mime === "application/json") return "json";
7825
- return null;
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
+ );
7826
7364
  }
7827
- var protocolHandlers = {
7828
- // @ts-expect-error: hush.
7829
- __proto__: null,
7830
- "data:": getDataProtocolModuleFormat,
7831
- "file:": getFileProtocolModuleFormat,
7832
- "http:": getHttpProtocolModuleFormat,
7833
- "https:": getHttpProtocolModuleFormat,
7834
- "node:"() {
7835
- return "builtin";
7836
- }
7837
- };
7838
- function getDataProtocolModuleFormat(parsed) {
7839
- const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
7840
- parsed.pathname
7841
- ) || [null, null, null];
7842
- return mimeToFormat(mime);
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
+ );
7843
7372
  }
7844
- function extname2(url) {
7845
- const pathname = url.pathname;
7846
- let index = pathname.length;
7847
- while (index--) {
7848
- const code = pathname.codePointAt(index);
7849
- if (code === 47) {
7850
- return "";
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
+ }
7851
7402
  }
7852
- if (code === 46) {
7853
- return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
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);
7854
7426
  }
7855
7427
  }
7856
- return "";
7428
+ const resolved = new URL$1(target2, packageJsonUrl);
7429
+ const resolvedPath = resolved.pathname;
7430
+ const packagePath = new URL$1(".", packageJsonUrl).pathname;
7431
+ if (!resolvedPath.startsWith(packagePath))
7432
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7433
+ if (subpath === "") return resolved;
7434
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
7435
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7436
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
7437
+ if (!isPathMap) {
7438
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7439
+ patternRegEx,
7440
+ target2,
7441
+ () => subpath
7442
+ ) : target2;
7443
+ emitInvalidSegmentDeprecation(
7444
+ resolvedTarget,
7445
+ request,
7446
+ match,
7447
+ packageJsonUrl,
7448
+ internal,
7449
+ base,
7450
+ false
7451
+ );
7452
+ }
7453
+ } else {
7454
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7455
+ }
7456
+ }
7457
+ if (pattern) {
7458
+ return new URL$1(
7459
+ RegExpPrototypeSymbolReplace.call(
7460
+ patternRegEx,
7461
+ resolved.href,
7462
+ () => subpath
7463
+ )
7464
+ );
7465
+ }
7466
+ return new URL$1(subpath, resolved);
7857
7467
  }
7858
- function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
7859
- const value = extname2(url);
7860
- if (value === ".js") {
7861
- const packageType = getPackageType(url);
7862
- if (packageType !== "none") {
7863
- return packageType;
7468
+ function isArrayIndex(key) {
7469
+ const keyNumber = Number(key);
7470
+ if (`${keyNumber}` !== key) return false;
7471
+ return keyNumber >= 0 && keyNumber < 4294967295;
7472
+ }
7473
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
7474
+ if (typeof target2 === "string") {
7475
+ return resolvePackageTargetString(
7476
+ target2,
7477
+ subpath,
7478
+ packageSubpath,
7479
+ packageJsonUrl,
7480
+ base,
7481
+ pattern,
7482
+ internal,
7483
+ isPathMap,
7484
+ conditions
7485
+ );
7486
+ }
7487
+ if (Array.isArray(target2)) {
7488
+ const targetList = target2;
7489
+ if (targetList.length === 0) return null;
7490
+ let lastException;
7491
+ let i = -1;
7492
+ while (++i < targetList.length) {
7493
+ const targetItem = targetList[i];
7494
+ let resolveResult;
7495
+ try {
7496
+ resolveResult = resolvePackageTarget(
7497
+ packageJsonUrl,
7498
+ targetItem,
7499
+ subpath,
7500
+ packageSubpath,
7501
+ base,
7502
+ pattern,
7503
+ internal,
7504
+ isPathMap,
7505
+ conditions
7506
+ );
7507
+ } catch (error) {
7508
+ const exception = (
7509
+ /** @type {ErrnoException} */
7510
+ error
7511
+ );
7512
+ lastException = exception;
7513
+ if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
7514
+ throw error;
7515
+ }
7516
+ if (resolveResult === void 0) continue;
7517
+ if (resolveResult === null) {
7518
+ lastException = null;
7519
+ continue;
7520
+ }
7521
+ return resolveResult;
7864
7522
  }
7865
- return "commonjs";
7523
+ if (lastException === void 0 || lastException === null) {
7524
+ return null;
7525
+ }
7526
+ throw lastException;
7866
7527
  }
7867
- if (value === "") {
7868
- const packageType = getPackageType(url);
7869
- if (packageType === "none" || packageType === "commonjs") {
7870
- return "commonjs";
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
+ }
7871
7540
  }
7872
- return "module";
7541
+ i = -1;
7542
+ while (++i < keys.length) {
7543
+ const key = keys[i];
7544
+ if (key === "default" || conditions && conditions.has(key)) {
7545
+ const conditionalTarget = (
7546
+ /** @type {unknown} */
7547
+ target2[key]
7548
+ );
7549
+ const resolveResult = resolvePackageTarget(
7550
+ packageJsonUrl,
7551
+ conditionalTarget,
7552
+ subpath,
7553
+ packageSubpath,
7554
+ base,
7555
+ pattern,
7556
+ internal,
7557
+ isPathMap,
7558
+ conditions
7559
+ );
7560
+ if (resolveResult === void 0) continue;
7561
+ return resolveResult;
7562
+ }
7563
+ }
7564
+ return null;
7873
7565
  }
7874
- const format3 = extensionFormatMap[value];
7875
- if (format3) return format3;
7876
- if (ignoreErrors) {
7877
- return void 0;
7566
+ if (target2 === null) {
7567
+ return null;
7878
7568
  }
7879
- const filepath = fileURLToPath$1(url);
7880
- throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
7881
- }
7882
- function getHttpProtocolModuleFormat() {
7569
+ throw invalidPackageTarget(
7570
+ packageSubpath,
7571
+ target2,
7572
+ packageJsonUrl,
7573
+ internal,
7574
+ base
7575
+ );
7883
7576
  }
7884
- function defaultGetFormatWithoutErrors(url, context) {
7885
- const protocol = url.protocol;
7886
- if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
7887
- 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
+ }
7888
7596
  }
7889
- return protocolHandlers[protocol](url, context, true) || null;
7597
+ return isConditionalSugar;
7890
7598
  }
7891
- var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
7892
- var {
7893
- ERR_NETWORK_IMPORT_DISALLOWED,
7894
- ERR_INVALID_MODULE_SPECIFIER,
7895
- ERR_INVALID_PACKAGE_CONFIG,
7896
- ERR_INVALID_PACKAGE_TARGET,
7897
- ERR_MODULE_NOT_FOUND,
7898
- ERR_PACKAGE_IMPORT_NOT_DEFINED,
7899
- ERR_PACKAGE_PATH_NOT_EXPORTED,
7900
- ERR_UNSUPPORTED_DIR_IMPORT,
7901
- ERR_UNSUPPORTED_RESOLVE_REQUEST
7902
- } = codes;
7903
- var own = {}.hasOwnProperty;
7904
- var invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
7905
- var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
7906
- var invalidPackageNameRegEx = /^\.|%|\\/;
7907
- var patternRegEx = /\*/g;
7908
- var encodedSeparatorRegEx = /%2f|%5c/i;
7909
- var emittedPackageWarnings = /* @__PURE__ */ new Set();
7910
- var doubleSlashRegEx = /[/\\]{2}/;
7911
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7599
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
7912
7600
  if (process$1.noDeprecation) {
7913
7601
  return;
7914
7602
  }
7915
- const pjsonPath = fileURLToPath$1(packageJsonUrl);
7916
- 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);
7917
7606
  process$1.emitWarning(
7918
- `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
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.`,
7919
7608
  "DeprecationWarning",
7920
- "DEP0166"
7609
+ "DEP0155"
7921
7610
  );
7922
7611
  }
7923
- function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
7924
- if (process$1.noDeprecation) {
7925
- return;
7612
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7613
+ let exports = packageConfig.exports;
7614
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7615
+ exports = { ".": exports };
7926
7616
  }
7927
- const format3 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
7928
- if (format3 !== "module") return;
7929
- const urlPath = fileURLToPath$1(url.href);
7930
- const packagePath = fileURLToPath$1(new URL$1(".", packageJsonUrl));
7931
- const basePath = fileURLToPath$1(base);
7932
- if (!main) {
7933
- process$1.emitWarning(
7934
- `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
7935
- packagePath.length
7936
- )}", imported from ${basePath}.
7937
- Default "index" lookups for the main are deprecated for ES modules.`,
7938
- "DeprecationWarning",
7939
- "DEP0151"
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
  );
7941
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7942
- process$1.emitWarning(
7943
- `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7944
- packagePath.length
7945
- )}", imported from ${basePath}.
7946
- Automatic extension resolution of the "main" field is deprecated for ES modules.`,
7947
- "DeprecationWarning",
7948
- "DEP0151"
7630
+ if (resolveResult === null || resolveResult === void 0) {
7631
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7632
+ }
7633
+ return resolveResult;
7634
+ }
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
7949
7675
  );
7676
+ if (resolveResult === null || resolveResult === void 0) {
7677
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7678
+ }
7679
+ return resolveResult;
7950
7680
  }
7681
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7951
7682
  }
7952
- function tryStatSync(path8) {
7953
- try {
7954
- return statSync2(path8);
7955
- } catch {
7683
+ function patternKeyCompare(a, b) {
7684
+ const aPatternIndex = a.indexOf("*");
7685
+ const bPatternIndex = b.indexOf("*");
7686
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
7687
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
7688
+ if (baseLengthA > baseLengthB) return -1;
7689
+ if (baseLengthB > baseLengthA) return 1;
7690
+ if (aPatternIndex === -1) return 1;
7691
+ if (bPatternIndex === -1) return -1;
7692
+ if (a.length > b.length) return -1;
7693
+ if (b.length > a.length) return 1;
7694
+ return 0;
7695
+ }
7696
+ function packageImportsResolve(name2, base, conditions) {
7697
+ if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
7698
+ const reason = "is not a valid internal imports specifier name";
7699
+ throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
7700
+ }
7701
+ let packageJsonUrl;
7702
+ const packageConfig = getPackageScopeConfig(base);
7703
+ if (packageConfig.exists) {
7704
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
7705
+ const imports = packageConfig.imports;
7706
+ if (imports) {
7707
+ if (own.call(imports, name2) && !name2.includes("*")) {
7708
+ const resolveResult = resolvePackageTarget(
7709
+ packageJsonUrl,
7710
+ imports[name2],
7711
+ "",
7712
+ name2,
7713
+ base,
7714
+ false,
7715
+ true,
7716
+ false,
7717
+ conditions
7718
+ );
7719
+ if (resolveResult !== null && resolveResult !== void 0) {
7720
+ return resolveResult;
7721
+ }
7722
+ } else {
7723
+ let bestMatch = "";
7724
+ let bestMatchSubpath = "";
7725
+ const keys = Object.getOwnPropertyNames(imports);
7726
+ let i = -1;
7727
+ while (++i < keys.length) {
7728
+ const key = keys[i];
7729
+ const patternIndex = key.indexOf("*");
7730
+ if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
7731
+ const patternTrailer = key.slice(patternIndex + 1);
7732
+ if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
7733
+ bestMatch = key;
7734
+ bestMatchSubpath = name2.slice(
7735
+ patternIndex,
7736
+ name2.length - patternTrailer.length
7737
+ );
7738
+ }
7739
+ }
7740
+ }
7741
+ if (bestMatch) {
7742
+ const target2 = imports[bestMatch];
7743
+ const resolveResult = resolvePackageTarget(
7744
+ packageJsonUrl,
7745
+ target2,
7746
+ bestMatchSubpath,
7747
+ bestMatch,
7748
+ base,
7749
+ true,
7750
+ true,
7751
+ false,
7752
+ conditions
7753
+ );
7754
+ if (resolveResult !== null && resolveResult !== void 0) {
7755
+ return resolveResult;
7756
+ }
7757
+ }
7758
+ }
7759
+ }
7956
7760
  }
7761
+ throw importNotDefined(name2, packageJsonUrl, base);
7957
7762
  }
7958
- function fileExists(url) {
7959
- const stats = statSync2(url, { throwIfNoEntry: false });
7960
- const isFile = stats ? stats.isFile() : void 0;
7961
- return isFile === null || isFile === void 0 ? false : isFile;
7962
- }
7963
- function legacyMainResolve(packageJsonUrl, packageConfig, base) {
7964
- let guess;
7965
- if (packageConfig.main !== void 0) {
7966
- guess = new URL$1(packageConfig.main, packageJsonUrl);
7967
- if (fileExists(guess)) return guess;
7968
- const tries2 = [
7969
- `./${packageConfig.main}.js`,
7970
- `./${packageConfig.main}.json`,
7971
- `./${packageConfig.main}.node`,
7972
- `./${packageConfig.main}/index.js`,
7973
- `./${packageConfig.main}/index.json`,
7974
- `./${packageConfig.main}/index.node`
7975
- ];
7976
- let i2 = -1;
7977
- while (++i2 < tries2.length) {
7978
- guess = new URL$1(tries2[i2], packageJsonUrl);
7979
- if (fileExists(guess)) break;
7980
- guess = void 0;
7981
- }
7982
- if (guess) {
7983
- emitLegacyIndexDeprecation(
7984
- guess,
7985
- packageJsonUrl,
7986
- base,
7987
- packageConfig.main
7988
- );
7989
- return guess;
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);
7990
7773
  }
7991
7774
  }
7992
- const tries = ["./index.js", "./index.json", "./index.node"];
7993
- let i = -1;
7994
- while (++i < tries.length) {
7995
- guess = new URL$1(tries[i], packageJsonUrl);
7996
- if (fileExists(guess)) break;
7997
- guess = void 0;
7998
- }
7999
- if (guess) {
8000
- emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
8001
- return guess;
7775
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7776
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7777
+ validPackageName = false;
8002
7778
  }
8003
- throw new ERR_MODULE_NOT_FOUND(
8004
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8005
- fileURLToPath$1(base)
8006
- );
8007
- }
8008
- function finalizeResolution(resolved, base, preserveSymlinks) {
8009
- if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
7779
+ if (!validPackageName) {
8010
7780
  throw new ERR_INVALID_MODULE_SPECIFIER(
8011
- resolved.pathname,
8012
- 'must not include encoded "/" or "\\" characters',
7781
+ specifier,
7782
+ "is not a valid package name",
8013
7783
  fileURLToPath$1(base)
8014
7784
  );
8015
7785
  }
8016
- let filePath;
8017
- try {
8018
- filePath = fileURLToPath$1(resolved);
8019
- } catch (error) {
8020
- const cause = (
8021
- /** @type {ErrnoException} */
8022
- error
8023
- );
8024
- Object.defineProperty(cause, "input", { value: String(resolved) });
8025
- Object.defineProperty(cause, "module", { value: String(base) });
8026
- throw cause;
8027
- }
8028
- const stats = tryStatSync(
8029
- filePath.endsWith("/") ? filePath.slice(-1) : filePath
8030
- );
8031
- if (stats && stats.isDirectory()) {
8032
- const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
8033
- error.url = String(resolved);
8034
- throw error;
8035
- }
8036
- if (!stats || !stats.isFile()) {
8037
- const error = new ERR_MODULE_NOT_FOUND(
8038
- filePath || resolved.pathname,
8039
- base && fileURLToPath$1(base),
8040
- true
8041
- );
8042
- error.url = String(resolved);
8043
- throw error;
8044
- }
8045
- {
8046
- const real = realpathSync(filePath);
8047
- const { search, hash } = resolved;
8048
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
8049
- resolved.search = search;
8050
- resolved.hash = hash;
8051
- }
8052
- return resolved;
7786
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7787
+ return { packageName, packageSubpath, isScoped };
8053
7788
  }
8054
- function importNotDefined(specifier, packageJsonUrl, base) {
8055
- 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(
8056
7794
  specifier,
8057
- packageJsonUrl && fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8058
- fileURLToPath$1(base)
8059
- );
8060
- }
8061
- function exportsNotFound(subpath, packageJsonUrl, base) {
8062
- return new ERR_PACKAGE_PATH_NOT_EXPORTED(
8063
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8064
- subpath,
8065
- base && fileURLToPath$1(base)
8066
- );
8067
- }
8068
- function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8069
- const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
8070
- throw new ERR_INVALID_MODULE_SPECIFIER(
8071
- request,
8072
- reason,
8073
- base && fileURLToPath$1(base)
7795
+ base
8074
7796
  );
8075
- }
8076
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8077
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
8078
- return new ERR_INVALID_PACKAGE_TARGET(
8079
- fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8080
- subpath,
8081
- target,
8082
- internal,
8083
- base && fileURLToPath$1(base)
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
8084
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);
8085
7843
  }
8086
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8087
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8088
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8089
- if (!target.startsWith("./")) {
8090
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
8091
- let isURL = false;
8092
- try {
8093
- new URL$1(target);
8094
- isURL = true;
8095
- } catch {
8096
- }
8097
- if (!isURL) {
8098
- const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8099
- patternRegEx,
8100
- target,
8101
- () => subpath
8102
- ) : target + subpath;
8103
- return packageResolve(exportTarget, packageJsonUrl, conditions);
8104
- }
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;
8105
7849
  }
8106
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8107
7850
  }
8108
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8109
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
8110
- if (!isPathMap) {
8111
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8112
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8113
- patternRegEx,
8114
- target,
8115
- () => subpath
8116
- ) : target;
8117
- emitInvalidSegmentDeprecation(
8118
- resolvedTarget,
8119
- request,
8120
- match,
8121
- packageJsonUrl,
8122
- internal,
8123
- base,
8124
- true
8125
- );
8126
- }
8127
- } else {
8128
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7851
+ return false;
7852
+ }
7853
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
7854
+ if (specifier === "") return false;
7855
+ if (specifier[0] === "/") return true;
7856
+ return isRelativeSpecifier(specifier);
7857
+ }
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;
8129
7870
  }
8130
- }
8131
- const resolved = new URL$1(target, packageJsonUrl);
8132
- const resolvedPath = resolved.pathname;
8133
- const packagePath = new URL$1(".", packageJsonUrl).pathname;
8134
- if (!resolvedPath.startsWith(packagePath))
8135
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8136
- if (subpath === "") return resolved;
8137
- if (invalidSegmentRegEx.exec(subpath) !== null) {
8138
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8139
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
8140
- if (!isPathMap) {
8141
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8142
- patternRegEx,
8143
- target,
8144
- () => subpath
8145
- ) : target;
8146
- emitInvalidSegmentDeprecation(
8147
- resolvedTarget,
8148
- request,
8149
- match,
8150
- packageJsonUrl,
8151
- internal,
8152
- base,
8153
- false
8154
- );
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;
8155
7881
  }
8156
- } else {
8157
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7882
+ resolved = packageResolve(specifier, base, conditions);
8158
7883
  }
8159
7884
  }
8160
- if (pattern) {
8161
- return new URL$1(
8162
- RegExpPrototypeSymbolReplace.call(
8163
- patternRegEx,
8164
- resolved.href,
8165
- () => subpath
8166
- )
8167
- );
7885
+ assert(resolved !== void 0, "expected to be defined");
7886
+ if (resolved.protocol !== "file:") {
7887
+ return resolved;
8168
7888
  }
8169
- return new URL$1(subpath, resolved);
7889
+ return finalizeResolution(resolved, base);
8170
7890
  }
8171
- function isArrayIndex(key) {
8172
- const keyNumber = Number(key);
8173
- if (`${keyNumber}` !== key) return false;
8174
- return keyNumber >= 0 && keyNumber < 4294967295;
7891
+ function fileURLToPath(id) {
7892
+ if (typeof id === "string" && !id.startsWith("file://")) {
7893
+ return normalizeSlash(id);
7894
+ }
7895
+ return normalizeSlash(fileURLToPath$1(id));
8175
7896
  }
8176
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8177
- if (typeof target === "string") {
8178
- return resolvePackageTargetString(
8179
- target,
8180
- subpath,
8181
- packageSubpath,
8182
- packageJsonUrl,
8183
- base,
8184
- pattern,
8185
- internal,
8186
- isPathMap,
8187
- conditions
8188
- );
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();
8189
7903
  }
8190
- if (Array.isArray(target)) {
8191
- const targetList = target;
8192
- if (targetList.length === 0) return null;
8193
- let lastException;
8194
- let i = -1;
8195
- while (++i < targetList.length) {
8196
- const targetItem = targetList[i];
8197
- let resolveResult;
8198
- try {
8199
- resolveResult = resolvePackageTarget(
8200
- packageJsonUrl,
8201
- targetItem,
8202
- subpath,
8203
- packageSubpath,
8204
- base,
8205
- pattern,
8206
- internal,
8207
- isPathMap,
8208
- conditions
8209
- );
8210
- } catch (error) {
8211
- const exception = (
8212
- /** @type {ErrnoException} */
8213
- error
8214
- );
8215
- lastException = exception;
8216
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8217
- throw error;
8218
- }
8219
- if (resolveResult === void 0) continue;
8220
- if (resolveResult === null) {
8221
- lastException = null;
8222
- continue;
8223
- }
8224
- return resolveResult;
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;
8225
7926
  }
8226
- if (lastException === void 0 || lastException === null) {
8227
- return null;
7927
+ }
7928
+ }
7929
+ function _resolve(id, options = {}) {
7930
+ if (typeof id !== "string") {
7931
+ if (id instanceof URL) {
7932
+ id = fileURLToPath(id);
7933
+ } else {
7934
+ throw new TypeError("input must be a `string` or `URL`");
8228
7935
  }
8229
- throw lastException;
8230
7936
  }
8231
- if (typeof target === "object" && target !== null) {
8232
- const keys = Object.getOwnPropertyNames(target);
8233
- let i = -1;
8234
- while (++i < keys.length) {
8235
- const key = keys[i];
8236
- if (isArrayIndex(key)) {
8237
- throw new ERR_INVALID_PACKAGE_CONFIG(
8238
- fileURLToPath$1(packageJsonUrl),
8239
- base,
8240
- '"exports" cannot contain numeric property keys.'
8241
- );
7937
+ if (/(node|data|http|https):/.test(id)) {
7938
+ return id;
7939
+ }
7940
+ if (BUILTIN_MODULES.has(id)) {
7941
+ return "node:" + id;
7942
+ }
7943
+ if (id.startsWith("file://")) {
7944
+ id = fileURLToPath(id);
7945
+ }
7946
+ if (isAbsolute(id)) {
7947
+ try {
7948
+ const stat = statSync(id);
7949
+ if (stat.isFile()) {
7950
+ return pathToFileURL(id);
8242
7951
  }
8243
- }
8244
- i = -1;
8245
- while (++i < keys.length) {
8246
- const key = keys[i];
8247
- if (key === "default" || conditions && conditions.has(key)) {
8248
- const conditionalTarget = (
8249
- /** @type {unknown} */
8250
- target[key]
8251
- );
8252
- const resolveResult = resolvePackageTarget(
8253
- packageJsonUrl,
8254
- conditionalTarget,
8255
- subpath,
8256
- packageSubpath,
8257
- base,
8258
- pattern,
8259
- internal,
8260
- isPathMap,
8261
- conditions
8262
- );
8263
- if (resolveResult === void 0) continue;
8264
- return resolveResult;
7952
+ } catch (error) {
7953
+ if (error?.code !== "ENOENT") {
7954
+ throw error;
8265
7955
  }
8266
7956
  }
8267
- return null;
8268
7957
  }
8269
- if (target === null) {
8270
- return null;
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())));
8271
7962
  }
8272
- throw invalidPackageTarget(
8273
- packageSubpath,
8274
- target,
8275
- packageJsonUrl,
8276
- internal,
8277
- base
8278
- );
8279
- }
8280
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8281
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8282
- if (typeof exports !== "object" || exports === null) return false;
8283
- const keys = Object.getOwnPropertyNames(exports);
8284
- let isConditionalSugar = false;
8285
- let i = 0;
8286
- let keyIndex = -1;
8287
- while (++keyIndex < keys.length) {
8288
- const key = keys[keyIndex];
8289
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8290
- if (i++ === 0) {
8291
- isConditionalSugar = currentIsConditionalSugar;
8292
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8293
- throw new ERR_INVALID_PACKAGE_CONFIG(
8294
- fileURLToPath$1(packageJsonUrl),
8295
- base,
8296
- `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`
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)
8297
7972
  );
8298
7973
  }
8299
7974
  }
8300
- return isConditionalSugar;
8301
- }
8302
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8303
- if (process$1.noDeprecation) {
8304
- return;
8305
- }
8306
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8307
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8308
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8309
- process$1.emitWarning(
8310
- `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
8311
- "DeprecationWarning",
8312
- "DEP0155"
8313
- );
8314
- }
8315
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8316
- let exports = packageConfig.exports;
8317
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8318
- exports = { ".": exports };
8319
- }
8320
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8321
- const target = exports[packageSubpath];
8322
- const resolveResult = resolvePackageTarget(
8323
- packageJsonUrl,
8324
- target,
8325
- "",
8326
- packageSubpath,
8327
- base,
8328
- false,
8329
- false,
8330
- false,
8331
- conditions
8332
- );
8333
- if (resolveResult === null || resolveResult === void 0) {
8334
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7975
+ let resolved;
7976
+ for (const url of urls) {
7977
+ resolved = _tryModuleResolve(id, url, conditionsSet);
7978
+ if (resolved) {
7979
+ break;
8335
7980
  }
8336
- return resolveResult;
8337
- }
8338
- let bestMatch = "";
8339
- let bestMatchSubpath = "";
8340
- const keys = Object.getOwnPropertyNames(exports);
8341
- let i = -1;
8342
- while (++i < keys.length) {
8343
- const key = keys[i];
8344
- const patternIndex = key.indexOf("*");
8345
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8346
- if (packageSubpath.endsWith("/")) {
8347
- emitTrailingSlashPatternDeprecation(
8348
- packageSubpath,
8349
- packageJsonUrl,
8350
- base
8351
- );
8352
- }
8353
- const patternTrailer = key.slice(patternIndex + 1);
8354
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8355
- bestMatch = key;
8356
- bestMatchSubpath = packageSubpath.slice(
8357
- patternIndex,
8358
- packageSubpath.length - patternTrailer.length
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
8359
7987
  );
7988
+ if (resolved) {
7989
+ break;
7990
+ }
8360
7991
  }
7992
+ if (resolved) {
7993
+ break;
7994
+ }
7995
+ }
7996
+ if (resolved) {
7997
+ break;
8361
7998
  }
8362
7999
  }
8363
- if (bestMatch) {
8364
- const target = (
8365
- /** @type {unknown} */
8366
- exports[bestMatch]
8000
+ if (!resolved) {
8001
+ const error = new Error(
8002
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
8367
8003
  );
8368
- const resolveResult = resolvePackageTarget(
8369
- packageJsonUrl,
8370
- target,
8371
- bestMatchSubpath,
8372
- bestMatch,
8373
- base,
8374
- true,
8375
- false,
8376
- packageSubpath.endsWith("/"),
8377
- conditions
8004
+ error.code = "ERR_MODULE_NOT_FOUND";
8005
+ throw error;
8006
+ }
8007
+ return pathToFileURL(resolved);
8008
+ }
8009
+ function resolveSync(id, options) {
8010
+ return _resolve(id, options);
8011
+ }
8012
+ function resolvePathSync(id, options) {
8013
+ return fileURLToPath(resolveSync(id, options));
8014
+ }
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;
8027
+ }
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`
8378
8038
  );
8379
- if (resolveResult === null || resolveResult === void 0) {
8380
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8381
- }
8382
- return resolveResult;
8383
8039
  }
8384
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8040
+ return false;
8385
8041
  }
8386
- function patternKeyCompare(a, b) {
8387
- const aPatternIndex = a.indexOf("*");
8388
- const bPatternIndex = b.indexOf("*");
8389
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8390
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8391
- if (baseLengthA > baseLengthB) return -1;
8392
- if (baseLengthB > baseLengthA) return 1;
8393
- if (aPatternIndex === -1) return 1;
8394
- if (bPatternIndex === -1) return -1;
8395
- if (a.length > b.length) return -1;
8396
- if (b.length > a.length) return 1;
8397
- return 0;
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
+ `;
8049
+ }
8050
+ const [moduleSpecifier, exportName] = globalInject;
8051
+ assert2(
8052
+ moduleSpecifier !== void 0,
8053
+ "Expected moduleSpecifier to be defined"
8054
+ );
8055
+ assert2(exportName !== void 0, "Expected exportName to be defined");
8056
+ return `import var_${globalName} from "${moduleSpecifier}";
8057
+ globalThis.${globalName} = var_${globalName}.${exportName};
8058
+ `;
8059
+ }).join("\n");
8060
+ const polyfillCode = env.polyfill.map((polyfillPath) => `import "${polyfillPath}";
8061
+ `).join("");
8062
+ const modified = new MagicString(code);
8063
+ modified.prepend(injectedCode);
8064
+ modified.prepend(polyfillCode);
8065
+ return {
8066
+ code: modified.toString(),
8067
+ map: modified.generateMap({ hires: "boundary", source: id })
8068
+ };
8398
8069
  }
8399
- function packageImportsResolve(name2, base, conditions) {
8400
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8401
- const reason = "is not a valid internal imports specifier name";
8402
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
8070
+ function resolveNodeJSImport(source) {
8071
+ const alias = env.alias[source];
8072
+ if (alias) {
8073
+ return {
8074
+ unresolved: alias,
8075
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8076
+ };
8403
8077
  }
8404
- let packageJsonUrl;
8405
- const packageConfig = getPackageScopeConfig(base);
8406
- if (packageConfig.exists) {
8407
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8408
- const imports = packageConfig.imports;
8409
- if (imports) {
8410
- if (own.call(imports, name2) && !name2.includes("*")) {
8411
- const resolveResult = resolvePackageTarget(
8412
- packageJsonUrl,
8413
- imports[name2],
8414
- "",
8415
- name2,
8416
- base,
8417
- false,
8418
- true,
8419
- false,
8420
- conditions
8421
- );
8422
- if (resolveResult !== null && resolveResult !== void 0) {
8423
- return resolveResult;
8424
- }
8425
- } else {
8426
- let bestMatch = "";
8427
- let bestMatchSubpath = "";
8428
- const keys = Object.getOwnPropertyNames(imports);
8429
- let i = -1;
8430
- while (++i < keys.length) {
8431
- const key = keys[i];
8432
- const patternIndex = key.indexOf("*");
8433
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8434
- const patternTrailer = key.slice(patternIndex + 1);
8435
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8436
- bestMatch = key;
8437
- bestMatchSubpath = name2.slice(
8438
- patternIndex,
8439
- name2.length - patternTrailer.length
8440
- );
8441
- }
8442
- }
8443
- }
8444
- if (bestMatch) {
8445
- const target = imports[bestMatch];
8446
- const resolveResult = resolvePackageTarget(
8447
- packageJsonUrl,
8448
- target,
8449
- bestMatchSubpath,
8450
- bestMatch,
8451
- base,
8452
- true,
8453
- true,
8454
- false,
8455
- conditions
8456
- );
8457
- if (resolveResult !== null && resolveResult !== void 0) {
8458
- return resolveResult;
8459
- }
8460
- }
8078
+ if (nodeCompatEntries.has(source)) {
8079
+ return {
8080
+ unresolved: source,
8081
+ resolved: resolvePathSync(source, { url: import.meta.url })
8082
+ };
8083
+ }
8084
+ }
8085
+ function getNodeCompatEntries() {
8086
+ const entries = new Set(Object.values(env.alias));
8087
+ for (const globalInject of Object.values(env.inject)) {
8088
+ if (typeof globalInject === "string") {
8089
+ entries.add(globalInject);
8090
+ } else {
8091
+ assert2(
8092
+ globalInject[0] !== void 0,
8093
+ "Expected first element of globalInject to be defined"
8094
+ );
8095
+ entries.add(globalInject[0]);
8096
+ }
8097
+ }
8098
+ env.polyfill.forEach((polyfill) => entries.add(polyfill));
8099
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8100
+ return entries;
8101
+ }
8102
+
8103
+ // src/constants.ts
8104
+ var ROUTER_WORKER_NAME = "__router-worker__";
8105
+ var ASSET_WORKER_NAME = "__asset-worker__";
8106
+ var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
8107
+ var MODULE_TYPES = ["CompiledWasm"];
8108
+
8109
+ // src/shared.ts
8110
+ var UNKNOWN_HOST = "http://localhost";
8111
+ var INIT_PATH = "/__vite_plugin_cloudflare_init__";
8112
+ var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
8113
+ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
8114
+
8115
+ // src/utils.ts
8116
+ import * as path2 from "node:path";
8117
+ import { Request as MiniflareRequest } from "miniflare";
8118
+ import "vite";
8119
+ function getOutputDirectory(userConfig, environmentName) {
8120
+ const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
8121
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path2.join(rootOutputDirectory, environmentName);
8122
+ }
8123
+ function toMiniflareRequest(request) {
8124
+ return new MiniflareRequest(request.url, {
8125
+ method: request.method,
8126
+ headers: [["accept-encoding", "identity"], ...request.headers],
8127
+ body: request.body,
8128
+ duplex: "half"
8129
+ });
8130
+ }
8131
+ function nodeHeadersToWebHeaders(nodeHeaders) {
8132
+ const headers = new Headers();
8133
+ for (const [key, value] of Object.entries(nodeHeaders)) {
8134
+ if (typeof value === "string") {
8135
+ headers.append(key, value);
8136
+ } else if (Array.isArray(value)) {
8137
+ for (const item of value) {
8138
+ headers.append(key, item);
8461
8139
  }
8462
8140
  }
8463
8141
  }
8464
- throw importNotDefined(name2, packageJsonUrl, base);
8142
+ return headers;
8465
8143
  }
8466
- function parsePackageName(specifier, base) {
8467
- let separatorIndex = specifier.indexOf("/");
8468
- let validPackageName = true;
8469
- let isScoped = false;
8470
- if (specifier[0] === "@") {
8471
- isScoped = true;
8472
- if (separatorIndex === -1 || specifier.length === 0) {
8473
- validPackageName = false;
8474
- } else {
8475
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
8144
+
8145
+ // src/cloudflare-environment.ts
8146
+ var webSocketUndefinedError = "The WebSocket is undefined";
8147
+ function createHotChannel(webSocketContainer) {
8148
+ const listenersMap = /* @__PURE__ */ new Map();
8149
+ const client = {
8150
+ send(payload) {
8151
+ const webSocket = webSocketContainer.webSocket;
8152
+ assert3(webSocket, webSocketUndefinedError);
8153
+ webSocket.send(JSON.stringify(payload));
8154
+ }
8155
+ };
8156
+ function onMessage(event) {
8157
+ const payload = JSON.parse(event.data.toString());
8158
+ const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
8159
+ for (const listener of listeners) {
8160
+ listener(payload.data, client);
8161
+ }
8162
+ }
8163
+ return {
8164
+ send(payload) {
8165
+ const webSocket = webSocketContainer.webSocket;
8166
+ assert3(webSocket, webSocketUndefinedError);
8167
+ webSocket.send(JSON.stringify(payload));
8168
+ },
8169
+ on(event, listener) {
8170
+ const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
8171
+ listeners.add(listener);
8172
+ listenersMap.set(event, listeners);
8173
+ },
8174
+ off(event, listener) {
8175
+ listenersMap.get(event)?.delete(listener);
8176
+ },
8177
+ listen() {
8178
+ const webSocket = webSocketContainer.webSocket;
8179
+ assert3(webSocket, webSocketUndefinedError);
8180
+ webSocket.addEventListener("message", onMessage);
8181
+ },
8182
+ close() {
8183
+ const webSocket = webSocketContainer.webSocket;
8184
+ assert3(webSocket, webSocketUndefinedError);
8185
+ webSocket.removeEventListener("message", onMessage);
8476
8186
  }
8187
+ };
8188
+ }
8189
+ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
8190
+ #webSocketContainer;
8191
+ #worker;
8192
+ constructor(name2, config) {
8193
+ const webSocketContainer = {};
8194
+ super(name2, config, {
8195
+ hot: true,
8196
+ transport: createHotChannel(webSocketContainer)
8197
+ });
8198
+ this.#webSocketContainer = webSocketContainer;
8477
8199
  }
8478
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8479
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8480
- validPackageName = false;
8481
- }
8482
- if (!validPackageName) {
8483
- throw new ERR_INVALID_MODULE_SPECIFIER(
8484
- specifier,
8485
- "is not a valid package name",
8486
- fileURLToPath$1(base)
8200
+ async initRunner(worker, root, workerConfig) {
8201
+ this.#worker = worker;
8202
+ const response = await this.#worker.fetch(
8203
+ new URL(INIT_PATH, UNKNOWN_HOST),
8204
+ {
8205
+ headers: {
8206
+ [VITE_DEV_METADATA_HEADER]: JSON.stringify({
8207
+ root,
8208
+ entryPath: workerConfig.main
8209
+ }),
8210
+ upgrade: "websocket"
8211
+ }
8212
+ }
8213
+ );
8214
+ assert3(
8215
+ response.ok,
8216
+ `Failed to initialize module runner, error: ${await response.text()}`
8487
8217
  );
8218
+ const webSocket = response.webSocket;
8219
+ assert3(webSocket, "Failed to establish WebSocket");
8220
+ webSocket.accept();
8221
+ this.#webSocketContainer.webSocket = webSocket;
8488
8222
  }
8489
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8490
- return { packageName, packageSubpath, isScoped };
8223
+ };
8224
+ var cloudflareBuiltInModules = [
8225
+ "cloudflare:email",
8226
+ "cloudflare:sockets",
8227
+ "cloudflare:workers",
8228
+ "cloudflare:workflows"
8229
+ ];
8230
+ var defaultConditions = ["workerd", "module", "browser"];
8231
+ var target = "es2022";
8232
+ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
8233
+ return {
8234
+ resolve: {
8235
+ // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
8236
+ // dependencies as not external
8237
+ noExternal: true,
8238
+ // We want to use `workerd` package exports if available (e.g. for postgres).
8239
+ conditions: [...defaultConditions, "development|production"],
8240
+ // The Cloudflare ones are proper builtins in the environment
8241
+ builtins: [...cloudflareBuiltInModules]
8242
+ },
8243
+ dev: {
8244
+ createEnvironment(name2, config) {
8245
+ return new CloudflareDevEnvironment(name2, config);
8246
+ }
8247
+ },
8248
+ build: {
8249
+ createEnvironment(name2, config) {
8250
+ return new vite2.BuildEnvironment(name2, config);
8251
+ },
8252
+ target,
8253
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
8254
+ emitAssets: true,
8255
+ outDir: getOutputDirectory(userConfig, environmentName),
8256
+ copyPublicDir: false,
8257
+ ssr: true,
8258
+ rollupOptions: {
8259
+ // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
8260
+ // so the input value here serves both as the build input as well as the starting point for
8261
+ // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
8262
+ // optimizeDeps.entries in the dev config)
8263
+ input: workerConfig.main
8264
+ }
8265
+ },
8266
+ optimizeDeps: {
8267
+ // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
8268
+ noDiscovery: false,
8269
+ entries: workerConfig.main,
8270
+ exclude: [...cloudflareBuiltInModules],
8271
+ esbuildOptions: {
8272
+ platform: "neutral",
8273
+ target,
8274
+ conditions: [...defaultConditions, "development"],
8275
+ resolveExtensions: [
8276
+ ".mjs",
8277
+ ".js",
8278
+ ".mts",
8279
+ ".ts",
8280
+ ".jsx",
8281
+ ".tsx",
8282
+ ".json",
8283
+ ".cjs",
8284
+ ".cts",
8285
+ ".ctx"
8286
+ ]
8287
+ }
8288
+ },
8289
+ // if nodeCompat is enabled then let's keep the real process.env so that workerd can manipulate it
8290
+ keepProcessEnv: isNodeCompat(workerConfig)
8291
+ };
8491
8292
  }
8492
- function packageResolve(specifier, base, conditions) {
8493
- if (builtinModules2.includes(specifier)) {
8494
- return new URL$1("node:" + specifier);
8495
- }
8496
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8497
- specifier,
8498
- base
8499
- );
8500
- const packageConfig = getPackageScopeConfig(base);
8501
- if (packageConfig.exists) {
8502
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8503
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8504
- return packageExportsResolve(
8505
- packageJsonUrl2,
8506
- packageSubpath,
8507
- packageConfig,
8508
- base,
8509
- conditions
8510
- );
8511
- }
8293
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8294
+ if (resolvedPluginConfig.type === "assets-only") {
8295
+ return;
8512
8296
  }
8513
- let packageJsonUrl = new URL$1(
8514
- "./node_modules/" + packageName + "/package.json",
8515
- base
8297
+ return Promise.all(
8298
+ Object.entries(resolvedPluginConfig.workers).map(
8299
+ async ([environmentName, workerConfig]) => {
8300
+ const worker = await miniflare.getWorker(workerConfig.name);
8301
+ return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
8302
+ }
8303
+ )
8516
8304
  );
8517
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8518
- let lastPath;
8519
- do {
8520
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8521
- if (!stat || !stat.isDirectory()) {
8522
- lastPath = packageJsonPath;
8523
- packageJsonUrl = new URL$1(
8524
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8525
- packageJsonUrl
8526
- );
8527
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8528
- continue;
8529
- }
8530
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8531
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8532
- return packageExportsResolve(
8533
- packageJsonUrl,
8534
- packageSubpath,
8535
- packageConfig2,
8536
- base,
8537
- conditions
8538
- );
8539
- }
8540
- if (packageSubpath === ".") {
8541
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8542
- }
8543
- return new URL$1(packageSubpath, packageJsonUrl);
8544
- } while (packageJsonPath.length !== lastPath.length);
8545
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8546
8305
  }
8547
- function isRelativeSpecifier(specifier) {
8548
- if (specifier[0] === ".") {
8549
- if (specifier.length === 1 || specifier[1] === "/") return true;
8550
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8551
- return true;
8552
- }
8553
- }
8554
- return false;
8306
+
8307
+ // src/deploy-config.ts
8308
+ import assert4 from "node:assert";
8309
+ import * as fs2 from "node:fs";
8310
+ import * as path3 from "node:path";
8311
+ import "vite";
8312
+ function getDeployConfigPath(root) {
8313
+ return path3.resolve(root, ".wrangler", "deploy", "config.json");
8555
8314
  }
8556
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8557
- if (specifier === "") return false;
8558
- if (specifier[0] === "/") return true;
8559
- return isRelativeSpecifier(specifier);
8315
+ function getWorkerConfigPaths(root) {
8316
+ const deployConfigPath = getDeployConfigPath(root);
8317
+ const deployConfig = JSON.parse(
8318
+ fs2.readFileSync(deployConfigPath, "utf-8")
8319
+ );
8320
+ return [
8321
+ { configPath: deployConfig.configPath },
8322
+ ...deployConfig.auxiliaryWorkers
8323
+ ].map(
8324
+ ({ configPath }) => path3.resolve(path3.dirname(deployConfigPath), configPath)
8325
+ );
8560
8326
  }
8561
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8562
- const protocol = base.protocol;
8563
- const isData = protocol === "data:";
8564
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8565
- let resolved;
8566
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8567
- try {
8568
- resolved = new URL$1(specifier, base);
8569
- } catch (error_) {
8570
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8571
- error.cause = error_;
8572
- throw error;
8573
- }
8574
- } else if (protocol === "file:" && specifier[0] === "#") {
8575
- resolved = packageImportsResolve(specifier, base, conditions);
8327
+ function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
8328
+ return path3.relative(
8329
+ deployConfigDirectory,
8330
+ path3.resolve(root, outputDirectory, "wrangler.json")
8331
+ );
8332
+ }
8333
+ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
8334
+ const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
8335
+ const deployConfigDirectory = path3.dirname(deployConfigPath);
8336
+ fs2.mkdirSync(deployConfigDirectory, { recursive: true });
8337
+ if (resolvedPluginConfig.type === "assets-only") {
8338
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
8339
+ assert4(
8340
+ clientOutputDirectory,
8341
+ "Unexpected error: client environment output directory is undefined"
8342
+ );
8343
+ const deployConfig = {
8344
+ configPath: getRelativePathToWorkerConfig(
8345
+ deployConfigDirectory,
8346
+ resolvedViteConfig.root,
8347
+ clientOutputDirectory
8348
+ ),
8349
+ auxiliaryWorkers: []
8350
+ };
8351
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8576
8352
  } else {
8577
- try {
8578
- resolved = new URL$1(specifier);
8579
- } catch (error_) {
8580
- if (isRemote && !builtinModules2.includes(specifier)) {
8581
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8582
- error.cause = error_;
8583
- throw error;
8353
+ let entryWorkerConfigPath;
8354
+ const auxiliaryWorkers = [];
8355
+ for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
8356
+ const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
8357
+ assert4(
8358
+ outputDirectory,
8359
+ `Unexpected error: ${environmentName} environment output directory is undefined`
8360
+ );
8361
+ const configPath = getRelativePathToWorkerConfig(
8362
+ deployConfigDirectory,
8363
+ resolvedViteConfig.root,
8364
+ outputDirectory
8365
+ );
8366
+ if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
8367
+ entryWorkerConfigPath = configPath;
8368
+ } else {
8369
+ auxiliaryWorkers.push({ configPath });
8584
8370
  }
8585
- resolved = packageResolve(specifier, base, conditions);
8586
8371
  }
8372
+ assert4(
8373
+ entryWorkerConfigPath,
8374
+ `Unexpected error: entryWorkerConfigPath is undefined`
8375
+ );
8376
+ const deployConfig = {
8377
+ configPath: entryWorkerConfigPath,
8378
+ auxiliaryWorkers
8379
+ };
8380
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8587
8381
  }
8588
- assert5(resolved !== void 0, "expected to be defined");
8589
- if (resolved.protocol !== "file:") {
8590
- return resolved;
8591
- }
8592
- return finalizeResolution(resolved, base);
8593
8382
  }
8594
- function fileURLToPath2(id) {
8595
- if (typeof id === "string" && !id.startsWith("file://")) {
8596
- return normalizeSlash(id);
8383
+
8384
+ // src/dev.ts
8385
+ import assert5 from "node:assert";
8386
+ function getDevEntryWorker(resolvedPluginConfig, miniflare) {
8387
+ const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8388
+ assert5(entryWorkerConfig, "Unexpected error: No entry worker configuration");
8389
+ return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
8390
+ }
8391
+
8392
+ // src/miniflare-options.ts
8393
+ import assert6 from "node:assert";
8394
+ import * as fs3 from "node:fs";
8395
+ import * as fsp from "node:fs/promises";
8396
+ import * as path4 from "node:path";
8397
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
8398
+ import {
8399
+ kCurrentWorker,
8400
+ Log,
8401
+ LogLevel,
8402
+ Response as MiniflareResponse
8403
+ } from "miniflare";
8404
+ import { globSync } from "tinyglobby";
8405
+ import "vite";
8406
+ import {
8407
+ unstable_getMiniflareWorkerOptions,
8408
+ unstable_readConfig
8409
+ } from "wrangler";
8410
+ function getPersistence(root, persistState) {
8411
+ if (persistState === false) {
8412
+ return {};
8597
8413
  }
8598
- return normalizeSlash(fileURLToPath$1(id));
8414
+ const defaultPersistPath = ".wrangler/state";
8415
+ const persistPath = path4.resolve(
8416
+ root,
8417
+ typeof persistState === "object" ? persistState.path : defaultPersistPath,
8418
+ "v3"
8419
+ );
8420
+ return {
8421
+ cachePersist: path4.join(persistPath, "cache"),
8422
+ d1Persist: path4.join(persistPath, "d1"),
8423
+ durableObjectsPersist: path4.join(persistPath, "do"),
8424
+ kvPersist: path4.join(persistPath, "kv"),
8425
+ r2Persist: path4.join(persistPath, "r2"),
8426
+ workflowsPersist: path4.join(persistPath, "workflows")
8427
+ };
8599
8428
  }
8600
- function pathToFileURL(id) {
8601
- return pathToFileURL$1(fileURLToPath2(id)).toString();
8429
+ function missingWorkerErrorMessage(workerName) {
8430
+ return `${workerName} does not match a worker name.`;
8602
8431
  }
8603
- function normalizeid(id) {
8604
- if (typeof id !== "string") {
8605
- id = id.toString();
8606
- }
8607
- if (/(node|data|http|https|file):/.test(id)) {
8608
- return id;
8609
- }
8610
- if (BUILTIN_MODULES.has(id)) {
8611
- return "node:" + id;
8432
+ function getWorkerToWorkerEntrypointNamesMap(workers) {
8433
+ const workerToWorkerEntrypointNamesMap = new Map(
8434
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8435
+ );
8436
+ for (const worker of workers) {
8437
+ for (const value of Object.values(worker.serviceBindings ?? {})) {
8438
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
8439
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
8440
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
8441
+ assert6(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8442
+ entrypointNames.add(value.entrypoint);
8443
+ }
8444
+ }
8612
8445
  }
8613
- return "file://" + encodeURI(normalizeSlash(id));
8446
+ return workerToWorkerEntrypointNamesMap;
8614
8447
  }
8615
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8616
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8617
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8618
- "ERR_MODULE_NOT_FOUND",
8619
- "ERR_UNSUPPORTED_DIR_IMPORT",
8620
- "MODULE_NOT_FOUND",
8621
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8622
- ]);
8623
- function _tryModuleResolve(id, url, conditions) {
8624
- try {
8625
- return moduleResolve(id, url, conditions);
8626
- } catch (error) {
8627
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8628
- throw error;
8448
+ function getWorkerToDurableObjectClassNamesMap(workers) {
8449
+ const workerToDurableObjectClassNamesMap = new Map(
8450
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8451
+ );
8452
+ for (const worker of workers) {
8453
+ for (const value of Object.values(worker.durableObjects ?? {})) {
8454
+ if (typeof value === "string") {
8455
+ const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
8456
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8457
+ classNames.add(value);
8458
+ } else if (typeof value === "object") {
8459
+ if (value.scriptName) {
8460
+ const classNames = workerToDurableObjectClassNamesMap.get(
8461
+ value.scriptName
8462
+ );
8463
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8464
+ classNames.add(value.className);
8465
+ } else {
8466
+ const classNames = workerToDurableObjectClassNamesMap.get(
8467
+ worker.name
8468
+ );
8469
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8470
+ classNames.add(value.className);
8471
+ }
8472
+ }
8629
8473
  }
8630
8474
  }
8475
+ return workerToDurableObjectClassNamesMap;
8631
8476
  }
8632
- function _resolve(id, options = {}) {
8633
- if (typeof id !== "string") {
8634
- if (id instanceof URL) {
8635
- id = fileURLToPath2(id);
8636
- } else {
8637
- throw new TypeError("input must be a `string` or `URL`");
8477
+ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
8478
+ const workerToWorkflowEntrypointClassNamesMap = new Map(
8479
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8480
+ );
8481
+ for (const worker of workers) {
8482
+ for (const value of Object.values(worker.workflows ?? {})) {
8483
+ if (value.scriptName) {
8484
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8485
+ value.scriptName
8486
+ );
8487
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8488
+ classNames.add(value.className);
8489
+ } else {
8490
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8491
+ worker.name
8492
+ );
8493
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8494
+ classNames.add(value.className);
8495
+ }
8638
8496
  }
8639
8497
  }
8640
- if (/(node|data|http|https):/.test(id)) {
8641
- return id;
8642
- }
8643
- if (BUILTIN_MODULES.has(id)) {
8644
- return "node:" + id;
8645
- }
8646
- if (id.startsWith("file://")) {
8647
- id = fileURLToPath2(id);
8498
+ return workerToWorkflowEntrypointClassNamesMap;
8499
+ }
8500
+ var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
8501
+ var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
8502
+ var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
8503
+ var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
8504
+ var RUNNER_PATH = "./runner-worker/index.js";
8505
+ function getEntryWorkerConfig(resolvedPluginConfig) {
8506
+ if (resolvedPluginConfig.type === "assets-only") {
8507
+ return;
8648
8508
  }
8649
- if (isAbsolute(id)) {
8650
- try {
8651
- const stat = statSync2(id);
8652
- if (stat.isFile()) {
8653
- return pathToFileURL(id);
8509
+ return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8510
+ }
8511
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8512
+ const resolvedViteConfig = viteDevServer.config;
8513
+ const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
8514
+ const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
8515
+ const assetWorkers = [
8516
+ {
8517
+ name: ROUTER_WORKER_NAME,
8518
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8519
+ modulesRoot: miniflareModulesRoot,
8520
+ modules: [
8521
+ {
8522
+ type: "ESModule",
8523
+ path: path4.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
8524
+ contents: fs3.readFileSync(
8525
+ fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
8526
+ )
8527
+ }
8528
+ ],
8529
+ bindings: {
8530
+ CONFIG: {
8531
+ has_user_worker: resolvedPluginConfig.type === "workers"
8532
+ }
8533
+ },
8534
+ serviceBindings: {
8535
+ ASSET_WORKER: ASSET_WORKER_NAME,
8536
+ ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
8654
8537
  }
8655
- } catch (error) {
8656
- if (error?.code !== "ENOENT") {
8657
- throw error;
8538
+ },
8539
+ {
8540
+ name: ASSET_WORKER_NAME,
8541
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8542
+ modulesRoot: miniflareModulesRoot,
8543
+ modules: [
8544
+ {
8545
+ type: "ESModule",
8546
+ path: path4.join(miniflareModulesRoot, ASSET_WORKER_PATH),
8547
+ contents: fs3.readFileSync(
8548
+ fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
8549
+ )
8550
+ }
8551
+ ],
8552
+ bindings: {
8553
+ CONFIG: {
8554
+ ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
8555
+ ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
8556
+ }
8557
+ },
8558
+ serviceBindings: {
8559
+ __VITE_ASSET_EXISTS__: async (request) => {
8560
+ const { pathname } = new URL(request.url);
8561
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8562
+ let exists;
8563
+ try {
8564
+ exists = fs3.statSync(filePath).isFile();
8565
+ } catch (error) {
8566
+ exists = false;
8567
+ }
8568
+ return MiniflareResponse.json(exists);
8569
+ },
8570
+ __VITE_FETCH_ASSET__: async (request) => {
8571
+ const { pathname } = new URL(request.url);
8572
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8573
+ try {
8574
+ let html = await fsp.readFile(filePath, "utf-8");
8575
+ html = await viteDevServer.transformIndexHtml(pathname, html);
8576
+ return new MiniflareResponse(html, {
8577
+ headers: { "Content-Type": "text/html" }
8578
+ });
8579
+ } catch (error) {
8580
+ throw new Error(`Unexpected error. Failed to load ${pathname}`);
8581
+ }
8582
+ }
8658
8583
  }
8659
8584
  }
8660
- }
8661
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8662
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8663
- if (_urls.length === 0) {
8664
- _urls.push(new URL(pathToFileURL(process.cwd())));
8665
- }
8666
- const urls = [..._urls];
8667
- for (const url of _urls) {
8668
- if (url.protocol === "file:") {
8669
- urls.push(
8670
- new URL("./", url),
8671
- // If url is directory
8672
- new URL(joinURL(url.pathname, "_index.js"), url),
8673
- // TODO: Remove in next major version?
8674
- new URL("node_modules", url)
8585
+ ];
8586
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
8587
+ ([environmentName, workerConfig]) => {
8588
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
8589
+ {
8590
+ ...workerConfig,
8591
+ assets: void 0
8592
+ },
8593
+ resolvedPluginConfig.cloudflareEnv
8675
8594
  );
8595
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
8596
+ const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8597
+ return {
8598
+ externalWorkers: externalWorkers2,
8599
+ worker: {
8600
+ ...workerOptions,
8601
+ name: workerOptions.name ?? workerConfig.name,
8602
+ modulesRoot: miniflareModulesRoot,
8603
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
8604
+ serviceBindings: {
8605
+ ...workerOptions.serviceBindings,
8606
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
8607
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
8608
+ } : {},
8609
+ __VITE_INVOKE_MODULE__: async (request) => {
8610
+ const payload = await request.json();
8611
+ const invokePayloadData = payload.data;
8612
+ assert6(
8613
+ invokePayloadData.name === "fetchModule",
8614
+ `Invalid invoke event: ${invokePayloadData.name}`
8615
+ );
8616
+ const [moduleId] = invokePayloadData.data;
8617
+ const moduleRE = new RegExp(MODULE_PATTERN);
8618
+ const shouldExternalize = (
8619
+ // Worker modules (CompiledWasm, Text, Data)
8620
+ moduleRE.test(moduleId)
8621
+ );
8622
+ if (shouldExternalize) {
8623
+ const result2 = {
8624
+ externalize: moduleId,
8625
+ type: "module"
8626
+ };
8627
+ return MiniflareResponse.json({ result: result2 });
8628
+ }
8629
+ const devEnvironment = viteDevServer.environments[environmentName];
8630
+ const result = await devEnvironment.hot.handleInvoke(payload);
8631
+ return MiniflareResponse.json(result);
8632
+ }
8633
+ }
8634
+ }
8635
+ };
8676
8636
  }
8677
- }
8678
- let resolved;
8679
- for (const url of urls) {
8680
- resolved = _tryModuleResolve(id, url, conditionsSet);
8681
- if (resolved) {
8682
- break;
8683
- }
8684
- for (const prefix of ["", "/index"]) {
8685
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8686
- resolved = _tryModuleResolve(
8687
- joinURL(id, prefix) + extension,
8688
- url,
8689
- conditionsSet
8637
+ ) : [];
8638
+ const userWorkers = workersFromConfig.map((options) => options.worker);
8639
+ const externalWorkers = workersFromConfig.flatMap(
8640
+ (options) => options.externalWorkers
8641
+ );
8642
+ const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
8643
+ const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
8644
+ const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
8645
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8646
+ return {
8647
+ log: logger,
8648
+ handleRuntimeStdio(stdout, stderr) {
8649
+ const decoder = new TextDecoder();
8650
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8651
+ stderr.forEach(
8652
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8653
+ );
8654
+ },
8655
+ ...getPersistence(
8656
+ resolvedViteConfig.root,
8657
+ resolvedPluginConfig.persistState
8658
+ ),
8659
+ workers: [
8660
+ ...assetWorkers,
8661
+ ...externalWorkers,
8662
+ ...userWorkers.map((workerOptions) => {
8663
+ const wrappers = [
8664
+ `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
8665
+ `export default createWorkerEntrypointWrapper('default');`
8666
+ ];
8667
+ const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
8668
+ workerOptions.name
8690
8669
  );
8691
- if (resolved) {
8692
- break;
8670
+ assert6(
8671
+ workerEntrypointNames,
8672
+ `WorkerEntrypoint names not found for worker ${workerOptions.name}`
8673
+ );
8674
+ for (const entrypointName of [...workerEntrypointNames].sort()) {
8675
+ wrappers.push(
8676
+ `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
8677
+ );
8693
8678
  }
8679
+ const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8680
+ workerOptions.name
8681
+ );
8682
+ assert6(
8683
+ durableObjectClassNames,
8684
+ `DurableObject class names not found for worker ${workerOptions.name}`
8685
+ );
8686
+ for (const className of [...durableObjectClassNames].sort()) {
8687
+ wrappers.push(
8688
+ `export const ${className} = createDurableObjectWrapper('${className}');`
8689
+ );
8690
+ }
8691
+ const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
8692
+ assert6(
8693
+ workflowEntrypointClassNames,
8694
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
8695
+ );
8696
+ for (const className of [...workflowEntrypointClassNames].sort()) {
8697
+ wrappers.push(
8698
+ `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
8699
+ );
8700
+ }
8701
+ return {
8702
+ ...workerOptions,
8703
+ modules: [
8704
+ {
8705
+ type: "ESModule",
8706
+ path: path4.join(miniflareModulesRoot, WRAPPER_PATH),
8707
+ contents: wrappers.join("\n")
8708
+ },
8709
+ {
8710
+ type: "ESModule",
8711
+ path: path4.join(miniflareModulesRoot, RUNNER_PATH),
8712
+ contents: fs3.readFileSync(
8713
+ fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
8714
+ )
8715
+ }
8716
+ ],
8717
+ unsafeUseModuleFallbackService: true
8718
+ };
8719
+ })
8720
+ ],
8721
+ unsafeModuleFallbackService(request) {
8722
+ const url = new URL(request.url);
8723
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
8724
+ assert6(
8725
+ rawSpecifier,
8726
+ `Unexpected error: no specifier in request to module fallback service.`
8727
+ );
8728
+ const moduleRE = new RegExp(MODULE_PATTERN);
8729
+ const match = moduleRE.exec(rawSpecifier);
8730
+ assert6(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8731
+ const [full, moduleType, modulePath] = match;
8732
+ assert6(
8733
+ modulePath,
8734
+ `Unexpected error: module path not found in reference: ${full}.`
8735
+ );
8736
+ let source;
8737
+ try {
8738
+ source = fs3.readFileSync(modulePath);
8739
+ } catch (error) {
8740
+ throw new Error(
8741
+ `Import "${modulePath}" not found. Does the file exist?`
8742
+ );
8694
8743
  }
8695
- if (resolved) {
8696
- break;
8697
- }
8698
- }
8699
- if (resolved) {
8700
- break;
8744
+ return MiniflareResponse.json({
8745
+ // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
8746
+ wasm: Array.from(source)
8747
+ });
8701
8748
  }
8702
- }
8703
- if (!resolved) {
8704
- const error = new Error(
8705
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8706
- );
8707
- error.code = "ERR_MODULE_NOT_FOUND";
8708
- throw error;
8709
- }
8710
- return pathToFileURL(resolved);
8711
- }
8712
- function resolveSync(id, options) {
8713
- return _resolve(id, options);
8714
- }
8715
- function resolvePathSync(id, options) {
8716
- return fileURLToPath2(resolveSync(id, options));
8717
- }
8718
-
8719
- // src/node-js-compat.ts
8720
- import { defineEnv } from "unenv";
8721
- var { env } = defineEnv({
8722
- nodeCompat: true,
8723
- presets: [cloudflare]
8724
- });
8725
- var CLOUDFLARE_VIRTUAL_PREFIX = "\0__CLOUDFLARE_NODEJS_COMPAT__";
8726
- function isNodeCompat(workerConfig) {
8727
- if (workerConfig === void 0) {
8728
- return false;
8729
- }
8730
- const nodeCompatMode = getNodeCompat(
8731
- workerConfig.compatibility_date,
8732
- workerConfig.compatibility_flags ?? []
8733
- ).mode;
8734
- if (nodeCompatMode === "v2") {
8735
- return true;
8736
- }
8737
- if (nodeCompatMode === "legacy") {
8738
- throw new Error(
8739
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8740
- );
8741
- }
8742
- if (nodeCompatMode === "v1") {
8743
- throw new Error(
8744
- `Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
8745
- );
8746
- }
8747
- return false;
8749
+ };
8748
8750
  }
8749
- function injectGlobalCode(id, code) {
8750
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8751
- if (typeof globalInject === "string") {
8752
- const moduleSpecifier2 = globalInject;
8753
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier2}";
8754
- globalThis.${globalName} = var_${globalName};
8755
- `;
8756
- }
8757
- const [moduleSpecifier, exportName] = globalInject;
8758
- return `import var_${globalName} from "${CLOUDFLARE_VIRTUAL_PREFIX}${moduleSpecifier}";
8759
- globalThis.${globalName} = var_${globalName}.${exportName};
8760
- `;
8761
- }).join("\n");
8762
- const modified = new MagicString(code);
8763
- modified.prepend(injectedCode);
8751
+ function getPreviewModules(main, modulesRules) {
8752
+ assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8753
+ const rootPath = path4.dirname(main);
8754
+ const entryPath = path4.basename(main);
8764
8755
  return {
8765
- code: modified.toString(),
8766
- map: modified.generateMap({ hires: "boundary", source: id })
8756
+ rootPath,
8757
+ modules: [
8758
+ {
8759
+ type: "ESModule",
8760
+ path: entryPath
8761
+ },
8762
+ ...modulesRules.flatMap(
8763
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
8764
+ type,
8765
+ path: path8
8766
+ }))
8767
+ )
8768
+ ]
8767
8769
  };
8768
8770
  }
8769
- function getNodeCompatAliases() {
8770
- const aliases = {};
8771
- Object.keys(env.alias).forEach((key) => {
8772
- if (!env.external.includes(key)) {
8773
- aliases[key] = CLOUDFLARE_VIRTUAL_PREFIX + key;
8774
- }
8775
- });
8776
- return aliases;
8777
- }
8778
- function getNodeCompatExternals() {
8779
- return env.external;
8780
- }
8781
- function maybeStripNodeJsVirtualPrefix(source) {
8782
- return source.startsWith(CLOUDFLARE_VIRTUAL_PREFIX) ? source.slice(CLOUDFLARE_VIRTUAL_PREFIX.length) : void 0;
8783
- }
8784
- function resolveNodeJSImport(source) {
8785
- const alias = env.alias[source];
8786
- if (alias) {
8787
- assert6(
8788
- !env.external.includes(alias),
8789
- `Unexpected unenv alias to external module: ${source} -> ${alias}`
8790
- );
8791
- source = alias;
8792
- }
8793
- const resolved = resolvePathSync(source, {
8794
- url: import.meta.url
8771
+ function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
8772
+ const resolvedViteConfig = vitePreviewServer.config;
8773
+ const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
8774
+ const workerConfigs = configPaths.map(
8775
+ (configPath) => unstable_readConfig({ config: configPath })
8776
+ );
8777
+ const workers = workerConfigs.flatMap((config) => {
8778
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
8779
+ const { externalWorkers } = miniflareWorkerOptions;
8780
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8781
+ return [
8782
+ {
8783
+ ...workerOptions,
8784
+ name: workerOptions.name ?? config.name,
8785
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
8786
+ },
8787
+ ...externalWorkers
8788
+ ];
8795
8789
  });
8790
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8796
8791
  return {
8797
- unresolved: source,
8798
- resolved
8792
+ log: logger,
8793
+ handleRuntimeStdio(stdout, stderr) {
8794
+ const decoder = new TextDecoder();
8795
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8796
+ stderr.forEach(
8797
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8798
+ );
8799
+ },
8800
+ ...getPersistence(resolvedViteConfig.root, persistState),
8801
+ workers
8799
8802
  };
8800
8803
  }
8804
+ var ViteMiniflareLogger = class extends Log {
8805
+ logger;
8806
+ constructor(config) {
8807
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8808
+ this.logger = config.logger;
8809
+ }
8810
+ logWithLevel(level, message) {
8811
+ if (/^Ready on http/.test(message)) {
8812
+ level = LogLevel.DEBUG;
8813
+ }
8814
+ switch (level) {
8815
+ case LogLevel.ERROR:
8816
+ return this.logger.error(message);
8817
+ case LogLevel.WARN:
8818
+ return this.logger.warn(message);
8819
+ case LogLevel.INFO:
8820
+ return this.logger.info(message);
8821
+ }
8822
+ }
8823
+ };
8824
+ function miniflareLogLevelFromViteLogLevel(level = "info") {
8825
+ switch (level) {
8826
+ case "error":
8827
+ return LogLevel.ERROR;
8828
+ case "warn":
8829
+ return LogLevel.WARN;
8830
+ case "info":
8831
+ return LogLevel.INFO;
8832
+ case "silent":
8833
+ return LogLevel.NONE;
8834
+ }
8835
+ }
8801
8836
 
8802
8837
  // src/plugin-config.ts
8803
8838
  import assert8 from "node:assert";
@@ -8841,7 +8876,6 @@ var nonApplicableWorkerConfigs = {
8841
8876
  "build",
8842
8877
  "find_additional_modules",
8843
8878
  "no_bundle",
8844
- "node_compat",
8845
8879
  "preserve_file_names",
8846
8880
  "site",
8847
8881
  "tsconfig",
@@ -8858,7 +8892,6 @@ var nullableNonApplicable = [
8858
8892
  "find_additional_modules",
8859
8893
  "minify",
8860
8894
  "no_bundle",
8861
- "node_compat",
8862
8895
  "preserve_file_names",
8863
8896
  "site",
8864
8897
  "tsconfig",
@@ -9009,6 +9042,17 @@ function getWorkerConfig(configPath, env2, opts) {
9009
9042
  };
9010
9043
  }
9011
9044
  assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9045
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9046
+ if (!mainStat) {
9047
+ throw new Error(
9048
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9049
+ );
9050
+ }
9051
+ if (mainStat.isDirectory()) {
9052
+ throw new Error(
9053
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9054
+ );
9055
+ }
9012
9056
  return {
9013
9057
  type: "worker",
9014
9058
  raw,
@@ -9109,9 +9153,10 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9153
  }
9110
9154
 
9111
9155
  // src/websockets.ts
9112
- import ws from "ws";
9113
- function handleWebSocket(httpServer, fetcher, logger) {
9114
- const nodeWebSocket = new ws.Server({ noServer: true });
9156
+ import { coupleWebSocket } from "miniflare";
9157
+ import { WebSocketServer } from "ws";
9158
+ function handleWebSocket(httpServer, fetcher) {
9159
+ const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9160
  httpServer.on(
9116
9161
  "upgrade",
9117
9162
  async (request, socket, head) => {
@@ -9134,34 +9179,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9134
9179
  socket,
9135
9180
  head,
9136
9181
  async (clientWebSocket) => {
9137
- workerWebSocket.accept();
9138
- workerWebSocket.addEventListener("message", (event) => {
9139
- clientWebSocket.send(event.data);
9140
- });
9141
- workerWebSocket.addEventListener("error", (event) => {
9142
- logger.error(
9143
- `WebSocket error:
9144
- ${event.error?.stack || event.error?.message}`,
9145
- { error: event.error }
9146
- );
9147
- });
9148
- workerWebSocket.addEventListener("close", () => {
9149
- clientWebSocket.close();
9150
- });
9151
- clientWebSocket.on("message", (data2, isBinary) => {
9152
- workerWebSocket.send(
9153
- isBinary ? Array.isArray(data2) ? Buffer.concat(data2) : data2 : data2.toString()
9154
- );
9155
- });
9156
- clientWebSocket.on("error", (error) => {
9157
- logger.error(`WebSocket error:
9158
- ${error.stack || error.message}`, {
9159
- error
9160
- });
9161
- });
9162
- clientWebSocket.on("close", () => {
9163
- workerWebSocket.close();
9164
- });
9182
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9165
9183
  nodeWebSocket.emit("connection", clientWebSocket, request);
9166
9184
  }
9167
9185
  );
@@ -9220,7 +9238,7 @@ function cloudflare2(pluginConfig = {}) {
9220
9238
  }
9221
9239
  } : void 0,
9222
9240
  builder: {
9223
- async buildApp(builder) {
9241
+ buildApp: userConfig.builder?.buildApp ?? (async (builder) => {
9224
9242
  const clientEnvironment = builder.environments.client;
9225
9243
  const defaultHtmlPath = path7.resolve(
9226
9244
  builder.config.root,
@@ -9246,7 +9264,7 @@ function cloudflare2(pluginConfig = {}) {
9246
9264
  )
9247
9265
  );
9248
9266
  }
9249
- }
9267
+ })
9250
9268
  }
9251
9269
  };
9252
9270
  },
@@ -9307,7 +9325,7 @@ function cloudflare2(pluginConfig = {}) {
9307
9325
  return;
9308
9326
  }
9309
9327
  config.no_bundle = true;
9310
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9328
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9311
9329
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9312
9330
  config.unsafe = void 0;
9313
9331
  }
@@ -9354,11 +9372,7 @@ function cloudflare2(pluginConfig = {}) {
9354
9372
  },
9355
9373
  { alwaysCallNext: false }
9356
9374
  );
9357
- handleWebSocket(
9358
- viteDevServer.httpServer,
9359
- entryWorker.fetch,
9360
- viteDevServer.config.logger
9361
- );
9375
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9362
9376
  return () => {
9363
9377
  viteDevServer.middlewares.use((req, res, next) => {
9364
9378
  middleware(req, res, next);
@@ -9380,16 +9394,10 @@ function cloudflare2(pluginConfig = {}) {
9380
9394
  },
9381
9395
  { alwaysCallNext: false }
9382
9396
  );
9383
- handleWebSocket(
9384
- vitePreviewServer.httpServer,
9385
- miniflare2.dispatchFetch,
9386
- vitePreviewServer.config.logger
9387
- );
9388
- return () => {
9389
- vitePreviewServer.middlewares.use((req, res, next) => {
9390
- middleware(req, res, next);
9391
- });
9392
- };
9397
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9398
+ vitePreviewServer.middlewares.use((req, res, next) => {
9399
+ middleware(req, res, next);
9400
+ });
9393
9401
  }
9394
9402
  },
9395
9403
  // Plugin to support `CompiledWasm` modules
@@ -9465,49 +9473,61 @@ function cloudflare2(pluginConfig = {}) {
9465
9473
  apply(_config, env2) {
9466
9474
  return !env2.isPreview;
9467
9475
  },
9468
- config() {
9469
- return {
9470
- resolve: {
9471
- alias: getNodeCompatAliases()
9472
- }
9473
- };
9474
- },
9475
- configEnvironment(environmentName) {
9476
- const workerConfig = getWorkerConfig2(environmentName);
9477
- if (isNodeCompat(workerConfig)) {
9476
+ configEnvironment(name2) {
9477
+ if (isNodeCompat(getWorkerConfig2(name2))) {
9478
9478
  return {
9479
- build: {
9480
- rollupOptions: {
9481
- external: getNodeCompatExternals()
9482
- }
9479
+ resolve: {
9480
+ builtins: [...nodeCompatExternals]
9481
+ },
9482
+ optimizeDeps: {
9483
+ // This is a list of dependency entry-points that should be pre-bundled.
9484
+ // In this case we provide a list of all the possible polyfills so that they are pre-bundled,
9485
+ // ready ahead the first request to the dev server.
9486
+ // Without this the dependency optimizer will try to bundle them on-the-fly in the middle of the first request,
9487
+ // which can potentially cause problems if it leads to previous pre-bundling to become stale and needing to be reloaded.
9488
+ // TODO: work out how to re-enable pre-bundling of these
9489
+ // include: [...getNodeCompatEntries()],
9490
+ // This is a list of module specifiers that the dependency optimizer should not follow when doing import analysis.
9491
+ // 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.
9492
+ // Obviously we don't want/need the optimizer to try to process modules that are built-in;
9493
+ // But also we want to avoid following the ones that are polyfilled since the dependency-optimizer import analyzer does not
9494
+ // resolve these imports using our `resolveId()` hook causing the optimization step to fail.
9495
+ exclude: [
9496
+ ...builtinModules2,
9497
+ ...builtinModules2.map((m) => `node:${m}`)
9498
+ ]
9483
9499
  }
9484
9500
  };
9485
9501
  }
9486
9502
  },
9503
+ applyToEnvironment(environment) {
9504
+ return isNodeCompat(getWorkerConfig2(environment.name));
9505
+ },
9506
+ // We need the resolver from this plugin to run before built-in ones, otherwise Vite's built-in
9507
+ // resolver will try to externalize the Node.js module imports (e.g. `perf_hooks` and `node:tty`)
9508
+ // rather than allowing the resolve hook here to alias then to polyfills.
9509
+ enforce: "pre",
9487
9510
  async resolveId(source, importer, options) {
9488
- const strippedSource = maybeStripNodeJsVirtualPrefix(source);
9489
- if (!strippedSource) {
9490
- return;
9491
- }
9492
- const workerConfig = getWorkerConfig2(this.environment.name);
9493
- if (!isNodeCompat(workerConfig)) {
9494
- return this.resolve(strippedSource, importer, options);
9511
+ const result = resolveNodeJSImport(source);
9512
+ if (!result) {
9513
+ return this.resolve(source, importer, options);
9495
9514
  }
9496
- const { unresolved, resolved } = resolveNodeJSImport(strippedSource);
9497
- if (this.environment.mode === "dev" && this.environment.depsOptimizer) {
9498
- const optimized = this.environment.depsOptimizer.registerMissingImport(
9499
- unresolved,
9500
- resolved
9501
- ).id;
9502
- return this.resolve(optimized, importer, options);
9515
+ if (this.environment.mode === "dev") {
9516
+ assert9(
9517
+ this.environment.depsOptimizer,
9518
+ "depsOptimizer is required in dev mode"
9519
+ );
9520
+ const { id } = this.environment.depsOptimizer.registerMissingImport(
9521
+ result.unresolved,
9522
+ result.resolved
9523
+ );
9524
+ return this.resolve(id, importer, options);
9503
9525
  }
9504
- return this.resolve(resolved, importer, options);
9526
+ return this.resolve(result.resolved, importer, options);
9505
9527
  },
9506
9528
  async transform(code, id) {
9507
9529
  const workerConfig = getWorkerConfig2(this.environment.name);
9508
- if (!isNodeCompat(workerConfig)) {
9509
- return;
9510
- }
9530
+ assert9(workerConfig, "Expected a worker config");
9511
9531
  const resolvedId = await this.resolve(workerConfig.main);
9512
9532
  if (id === resolvedId?.id) {
9513
9533
  return injectGlobalCode(id, code);