@cloudflare/vite-plugin 0.0.0-36ef9c620 → 0.0.0-383dc0abd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1074,709 +1074,11 @@ import { Miniflare } from "miniflare";
1074
1074
  import * as vite6 from "vite";
1075
1075
 
1076
1076
  // src/cloudflare-environment.ts
1077
- import assert from "node:assert";
1078
- import * as vite2 from "vite";
1079
-
1080
- // src/constants.ts
1081
- var ROUTER_WORKER_NAME = "__router-worker__";
1082
- var ASSET_WORKER_NAME = "__asset-worker__";
1083
- var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
1084
- var MODULE_TYPES = ["CompiledWasm"];
1085
-
1086
- // src/shared.ts
1087
- var UNKNOWN_HOST = "http://localhost";
1088
- var INIT_PATH = "/__vite_plugin_cloudflare_init__";
1089
- var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
1090
-
1091
- // src/utils.ts
1092
- import * as path from "node:path";
1093
- import { Request as MiniflareRequest } from "miniflare";
1094
- import "vite";
1095
- function getOutputDirectory(userConfig, environmentName) {
1096
- const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
1097
- return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
1098
- }
1099
- function toMiniflareRequest(request) {
1100
- return new MiniflareRequest(request.url, {
1101
- method: request.method,
1102
- headers: [["accept-encoding", "identity"], ...request.headers],
1103
- body: request.body,
1104
- duplex: "half"
1105
- });
1106
- }
1107
- function nodeHeadersToWebHeaders(nodeHeaders) {
1108
- const headers = new Headers();
1109
- for (const [key, value] of Object.entries(nodeHeaders)) {
1110
- if (typeof value === "string") {
1111
- headers.append(key, value);
1112
- } else if (Array.isArray(value)) {
1113
- for (const item of value) {
1114
- headers.append(key, item);
1115
- }
1116
- }
1117
- }
1118
- return headers;
1119
- }
1120
-
1121
- // src/cloudflare-environment.ts
1122
- var webSocketUndefinedError = "The WebSocket is undefined";
1123
- function createHotChannel(webSocketContainer) {
1124
- const listenersMap = /* @__PURE__ */ new Map();
1125
- const client = {
1126
- send(payload) {
1127
- const webSocket = webSocketContainer.webSocket;
1128
- assert(webSocket, webSocketUndefinedError);
1129
- webSocket.send(JSON.stringify(payload));
1130
- }
1131
- };
1132
- function onMessage(event) {
1133
- const payload = JSON.parse(event.data.toString());
1134
- const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
1135
- for (const listener of listeners) {
1136
- listener(payload.data, client);
1137
- }
1138
- }
1139
- return {
1140
- send(payload) {
1141
- const webSocket = webSocketContainer.webSocket;
1142
- assert(webSocket, webSocketUndefinedError);
1143
- webSocket.send(JSON.stringify(payload));
1144
- },
1145
- on(event, listener) {
1146
- const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
1147
- listeners.add(listener);
1148
- listenersMap.set(event, listeners);
1149
- },
1150
- off(event, listener) {
1151
- listenersMap.get(event)?.delete(listener);
1152
- },
1153
- listen() {
1154
- const webSocket = webSocketContainer.webSocket;
1155
- assert(webSocket, webSocketUndefinedError);
1156
- webSocket.addEventListener("message", onMessage);
1157
- },
1158
- close() {
1159
- const webSocket = webSocketContainer.webSocket;
1160
- assert(webSocket, webSocketUndefinedError);
1161
- webSocket.removeEventListener("message", onMessage);
1162
- }
1163
- };
1164
- }
1165
- var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
1166
- #webSocketContainer;
1167
- #worker;
1168
- constructor(name2, config) {
1169
- const webSocketContainer = {};
1170
- super(name2, config, {
1171
- hot: true,
1172
- transport: createHotChannel(webSocketContainer)
1173
- });
1174
- this.#webSocketContainer = webSocketContainer;
1175
- }
1176
- async initRunner(worker) {
1177
- this.#worker = worker;
1178
- const response = await this.#worker.fetch(
1179
- new URL(INIT_PATH, UNKNOWN_HOST),
1180
- {
1181
- headers: {
1182
- upgrade: "websocket"
1183
- }
1184
- }
1185
- );
1186
- assert(
1187
- response.ok,
1188
- `Failed to initialize module runner, error: ${await response.text()}`
1189
- );
1190
- const webSocket = response.webSocket;
1191
- assert(webSocket, "Failed to establish WebSocket");
1192
- webSocket.accept();
1193
- this.#webSocketContainer.webSocket = webSocket;
1194
- }
1195
- };
1196
- var cloudflareBuiltInModules = [
1197
- "cloudflare:email",
1198
- "cloudflare:sockets",
1199
- "cloudflare:workers",
1200
- "cloudflare:workflows"
1201
- ];
1202
- var defaultConditions = ["workerd", "module", "browser"];
1203
- function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
1204
- return {
1205
- resolve: {
1206
- // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
1207
- // dependencies as not external
1208
- noExternal: true,
1209
- // We want to use `workerd` package exports if available (e.g. for postgres).
1210
- conditions: [...defaultConditions, "development|production"],
1211
- // The Cloudflare ones are proper builtins in the environment
1212
- builtins: [...cloudflareBuiltInModules]
1213
- },
1214
- dev: {
1215
- createEnvironment(name2, config) {
1216
- return new CloudflareDevEnvironment(name2, config);
1217
- }
1218
- },
1219
- build: {
1220
- createEnvironment(name2, config) {
1221
- return new vite2.BuildEnvironment(name2, config);
1222
- },
1223
- target: "es2022",
1224
- // We need to enable `emitAssets` in order to support additional modules defined by `rules`
1225
- emitAssets: true,
1226
- outDir: getOutputDirectory(userConfig, environmentName),
1227
- copyPublicDir: false,
1228
- ssr: true,
1229
- rollupOptions: {
1230
- // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
1231
- // so the input value here serves both as the build input as well as the starting point for
1232
- // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
1233
- // optimizeDeps.entries in the dev config)
1234
- input: workerConfig.main
1235
- }
1236
- },
1237
- optimizeDeps: {
1238
- // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
1239
- noDiscovery: false,
1240
- entries: workerConfig.main,
1241
- exclude: [...cloudflareBuiltInModules],
1242
- esbuildOptions: {
1243
- platform: "neutral",
1244
- conditions: [...defaultConditions, "development"],
1245
- resolveExtensions: [
1246
- ".mjs",
1247
- ".js",
1248
- ".mts",
1249
- ".ts",
1250
- ".jsx",
1251
- ".tsx",
1252
- ".json",
1253
- ".cjs",
1254
- ".cts",
1255
- ".ctx"
1256
- ]
1257
- }
1258
- },
1259
- keepProcessEnv: false
1260
- };
1261
- }
1262
- function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
1263
- if (resolvedPluginConfig.type === "assets-only") {
1264
- return;
1265
- }
1266
- return Promise.all(
1267
- Object.entries(resolvedPluginConfig.workers).map(
1268
- async ([environmentName, workerConfig]) => {
1269
- const worker = await miniflare.getWorker(workerConfig.name);
1270
- return viteDevServer.environments[environmentName].initRunner(worker);
1271
- }
1272
- )
1273
- );
1274
- }
1275
-
1276
- // src/deploy-config.ts
1277
- import assert2 from "node:assert";
1278
- import * as fs from "node:fs";
1279
- import * as path2 from "node:path";
1280
- import "vite";
1281
- function getDeployConfigPath(root) {
1282
- return path2.resolve(root, ".wrangler", "deploy", "config.json");
1283
- }
1284
- function getWorkerConfigPaths(root) {
1285
- const deployConfigPath = getDeployConfigPath(root);
1286
- const deployConfig = JSON.parse(
1287
- fs.readFileSync(deployConfigPath, "utf-8")
1288
- );
1289
- return [
1290
- { configPath: deployConfig.configPath },
1291
- ...deployConfig.auxiliaryWorkers
1292
- ].map(
1293
- ({ configPath }) => path2.resolve(path2.dirname(deployConfigPath), configPath)
1294
- );
1295
- }
1296
- function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
1297
- return path2.relative(
1298
- deployConfigDirectory,
1299
- path2.resolve(root, outputDirectory, "wrangler.json")
1300
- );
1301
- }
1302
- function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
1303
- const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
1304
- const deployConfigDirectory = path2.dirname(deployConfigPath);
1305
- fs.mkdirSync(deployConfigDirectory, { recursive: true });
1306
- if (resolvedPluginConfig.type === "assets-only") {
1307
- const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
1308
- assert2(
1309
- clientOutputDirectory,
1310
- "Unexpected error: client environment output directory is undefined"
1311
- );
1312
- const deployConfig = {
1313
- configPath: getRelativePathToWorkerConfig(
1314
- deployConfigDirectory,
1315
- resolvedViteConfig.root,
1316
- clientOutputDirectory
1317
- ),
1318
- auxiliaryWorkers: []
1319
- };
1320
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1321
- } else {
1322
- let entryWorkerConfigPath;
1323
- const auxiliaryWorkers = [];
1324
- for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
1325
- const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
1326
- assert2(
1327
- outputDirectory,
1328
- `Unexpected error: ${environmentName} environment output directory is undefined`
1329
- );
1330
- const configPath = getRelativePathToWorkerConfig(
1331
- deployConfigDirectory,
1332
- resolvedViteConfig.root,
1333
- outputDirectory
1334
- );
1335
- if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
1336
- entryWorkerConfigPath = configPath;
1337
- } else {
1338
- auxiliaryWorkers.push({ configPath });
1339
- }
1340
- }
1341
- assert2(
1342
- entryWorkerConfigPath,
1343
- `Unexpected error: entryWorkerConfigPath is undefined`
1344
- );
1345
- const deployConfig = {
1346
- configPath: entryWorkerConfigPath,
1347
- auxiliaryWorkers
1348
- };
1349
- fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
1350
- }
1351
- }
1352
-
1353
- // src/dev.ts
1354
- import assert3 from "node:assert";
1355
- function getDevEntryWorker(resolvedPluginConfig, miniflare) {
1356
- const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1357
- assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
1358
- return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
1359
- }
1360
-
1361
- // src/miniflare-options.ts
1362
- import assert4 from "node:assert";
1363
- import * as fs2 from "node:fs";
1364
- import * as fsp from "node:fs/promises";
1365
- import * as path3 from "node:path";
1366
- import { fileURLToPath } from "node:url";
1367
- import {
1368
- kCurrentWorker,
1369
- Log,
1370
- LogLevel,
1371
- Response as MiniflareResponse
1372
- } from "miniflare";
1373
- import "vite";
1374
- import {
1375
- unstable_getMiniflareWorkerOptions,
1376
- unstable_readConfig
1377
- } from "wrangler";
1378
- function getPersistence(root, persistState) {
1379
- if (persistState === false) {
1380
- return {};
1381
- }
1382
- const defaultPersistPath = ".wrangler/state";
1383
- const persistPath = path3.resolve(
1384
- root,
1385
- typeof persistState === "object" ? persistState.path : defaultPersistPath,
1386
- "v3"
1387
- );
1388
- return {
1389
- cachePersist: path3.join(persistPath, "cache"),
1390
- d1Persist: path3.join(persistPath, "d1"),
1391
- durableObjectsPersist: path3.join(persistPath, "do"),
1392
- kvPersist: path3.join(persistPath, "kv"),
1393
- r2Persist: path3.join(persistPath, "r2"),
1394
- workflowsPersist: path3.join(persistPath, "workflows")
1395
- };
1396
- }
1397
- function missingWorkerErrorMessage(workerName) {
1398
- return `${workerName} does not match a worker name.`;
1399
- }
1400
- function getWorkerToWorkerEntrypointNamesMap(workers) {
1401
- const workerToWorkerEntrypointNamesMap = new Map(
1402
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1403
- );
1404
- for (const worker of workers) {
1405
- for (const value of Object.values(worker.serviceBindings ?? {})) {
1406
- if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
1407
- const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
1408
- const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
1409
- assert4(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
1410
- entrypointNames.add(value.entrypoint);
1411
- }
1412
- }
1413
- }
1414
- return workerToWorkerEntrypointNamesMap;
1415
- }
1416
- function getWorkerToDurableObjectClassNamesMap(workers) {
1417
- const workerToDurableObjectClassNamesMap = new Map(
1418
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1419
- );
1420
- for (const worker of workers) {
1421
- for (const value of Object.values(worker.durableObjects ?? {})) {
1422
- if (typeof value === "string") {
1423
- const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
1424
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1425
- classNames.add(value);
1426
- } else if (typeof value === "object") {
1427
- if (value.scriptName) {
1428
- const classNames = workerToDurableObjectClassNamesMap.get(
1429
- value.scriptName
1430
- );
1431
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1432
- classNames.add(value.className);
1433
- } else {
1434
- const classNames = workerToDurableObjectClassNamesMap.get(
1435
- worker.name
1436
- );
1437
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1438
- classNames.add(value.className);
1439
- }
1440
- }
1441
- }
1442
- }
1443
- return workerToDurableObjectClassNamesMap;
1444
- }
1445
- function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
1446
- const workerToWorkflowEntrypointClassNamesMap = new Map(
1447
- workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
1448
- );
1449
- for (const worker of workers) {
1450
- for (const value of Object.values(worker.workflows ?? {})) {
1451
- if (value.scriptName) {
1452
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1453
- value.scriptName
1454
- );
1455
- assert4(classNames, missingWorkerErrorMessage(value.scriptName));
1456
- classNames.add(value.className);
1457
- } else {
1458
- const classNames = workerToWorkflowEntrypointClassNamesMap.get(
1459
- worker.name
1460
- );
1461
- assert4(classNames, missingWorkerErrorMessage(worker.name));
1462
- classNames.add(value.className);
1463
- }
1464
- }
1465
- }
1466
- return workerToWorkflowEntrypointClassNamesMap;
1467
- }
1468
- var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
1469
- var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
1470
- var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
1471
- var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
1472
- var RUNNER_PATH = "./runner-worker/index.js";
1473
- function getEntryWorkerConfig(resolvedPluginConfig) {
1474
- if (resolvedPluginConfig.type === "assets-only") {
1475
- return;
1476
- }
1477
- return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
1478
- }
1479
- function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
1480
- const resolvedViteConfig = viteDevServer.config;
1481
- const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
1482
- const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
1483
- const assetWorkers = [
1484
- {
1485
- name: ROUTER_WORKER_NAME,
1486
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1487
- modulesRoot: miniflareModulesRoot,
1488
- modules: [
1489
- {
1490
- type: "ESModule",
1491
- path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
1492
- contents: fs2.readFileSync(
1493
- fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
1494
- )
1495
- }
1496
- ],
1497
- bindings: {
1498
- CONFIG: {
1499
- has_user_worker: resolvedPluginConfig.type === "workers"
1500
- }
1501
- },
1502
- serviceBindings: {
1503
- ASSET_WORKER: ASSET_WORKER_NAME,
1504
- ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
1505
- }
1506
- },
1507
- {
1508
- name: ASSET_WORKER_NAME,
1509
- compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
1510
- modulesRoot: miniflareModulesRoot,
1511
- modules: [
1512
- {
1513
- type: "ESModule",
1514
- path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
1515
- contents: fs2.readFileSync(
1516
- fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
1517
- )
1518
- }
1519
- ],
1520
- bindings: {
1521
- CONFIG: {
1522
- ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
1523
- ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
1524
- }
1525
- },
1526
- serviceBindings: {
1527
- __VITE_ASSET_EXISTS__: async (request) => {
1528
- const { pathname } = new URL(request.url);
1529
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1530
- let exists;
1531
- try {
1532
- exists = fs2.statSync(filePath).isFile();
1533
- } catch (error) {
1534
- exists = false;
1535
- }
1536
- return MiniflareResponse.json(exists);
1537
- },
1538
- __VITE_FETCH_ASSET__: async (request) => {
1539
- const { pathname } = new URL(request.url);
1540
- const filePath = path3.join(resolvedViteConfig.root, pathname);
1541
- try {
1542
- let html = await fsp.readFile(filePath, "utf-8");
1543
- html = await viteDevServer.transformIndexHtml(pathname, html);
1544
- return new MiniflareResponse(html, {
1545
- headers: { "Content-Type": "text/html" }
1546
- });
1547
- } catch (error) {
1548
- throw new Error(`Unexpected error. Failed to load ${pathname}`);
1549
- }
1550
- }
1551
- }
1552
- }
1553
- ];
1554
- const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
1555
- ([environmentName, workerConfig]) => {
1556
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
1557
- {
1558
- ...workerConfig,
1559
- assets: void 0
1560
- },
1561
- resolvedPluginConfig.cloudflareEnv
1562
- );
1563
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1564
- return {
1565
- ...workerOptions,
1566
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1567
- name: workerConfig.name,
1568
- modulesRoot: miniflareModulesRoot,
1569
- unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
1570
- bindings: {
1571
- ...workerOptions.bindings,
1572
- __VITE_ROOT__: resolvedViteConfig.root,
1573
- __VITE_ENTRY_PATH__: workerConfig.main
1574
- },
1575
- serviceBindings: {
1576
- ...workerOptions.serviceBindings,
1577
- ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
1578
- [workerConfig.assets.binding]: ASSET_WORKER_NAME
1579
- } : {},
1580
- __VITE_INVOKE_MODULE__: async (request) => {
1581
- const payload = await request.json();
1582
- const invokePayloadData = payload.data;
1583
- assert4(
1584
- invokePayloadData.name === "fetchModule",
1585
- `Invalid invoke event: ${invokePayloadData.name}`
1586
- );
1587
- const [moduleId] = invokePayloadData.data;
1588
- const moduleRE = new RegExp(MODULE_PATTERN);
1589
- const shouldExternalize = (
1590
- // Worker modules (CompiledWasm, Text, Data)
1591
- moduleRE.test(moduleId)
1592
- );
1593
- if (shouldExternalize) {
1594
- const result2 = {
1595
- externalize: moduleId,
1596
- type: "module"
1597
- };
1598
- return MiniflareResponse.json({ result: result2 });
1599
- }
1600
- const devEnvironment = viteDevServer.environments[environmentName];
1601
- const result = await devEnvironment.hot.handleInvoke(payload);
1602
- return MiniflareResponse.json(result);
1603
- }
1604
- }
1605
- };
1606
- }
1607
- ) : [];
1608
- const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
1609
- const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
1610
- const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
1611
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1612
- return {
1613
- log: logger,
1614
- handleRuntimeStdio(stdout, stderr) {
1615
- const decoder = new TextDecoder();
1616
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1617
- stderr.forEach(
1618
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1619
- );
1620
- },
1621
- ...getPersistence(
1622
- resolvedViteConfig.root,
1623
- resolvedPluginConfig.persistState
1624
- ),
1625
- workers: [
1626
- ...assetWorkers,
1627
- ...userWorkers.map((workerOptions) => {
1628
- const wrappers = [
1629
- `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
1630
- `export default createWorkerEntrypointWrapper('default');`
1631
- ];
1632
- const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
1633
- workerOptions.name
1634
- );
1635
- assert4(
1636
- workerEntrypointNames,
1637
- `WorkerEntrypoint names not found for worker ${workerOptions.name}`
1638
- );
1639
- for (const entrypointName of [...workerEntrypointNames].sort()) {
1640
- wrappers.push(
1641
- `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
1642
- );
1643
- }
1644
- const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
1645
- workerOptions.name
1646
- );
1647
- assert4(
1648
- durableObjectClassNames,
1649
- `DurableObject class names not found for worker ${workerOptions.name}`
1650
- );
1651
- for (const className of [...durableObjectClassNames].sort()) {
1652
- wrappers.push(
1653
- `export const ${className} = createDurableObjectWrapper('${className}');`
1654
- );
1655
- }
1656
- const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
1657
- assert4(
1658
- workflowEntrypointClassNames,
1659
- `WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
1660
- );
1661
- for (const className of [...workflowEntrypointClassNames].sort()) {
1662
- wrappers.push(
1663
- `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
1664
- );
1665
- }
1666
- return {
1667
- ...workerOptions,
1668
- modules: [
1669
- {
1670
- type: "ESModule",
1671
- path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
1672
- contents: wrappers.join("\n")
1673
- },
1674
- {
1675
- type: "ESModule",
1676
- path: path3.join(miniflareModulesRoot, RUNNER_PATH),
1677
- contents: fs2.readFileSync(
1678
- fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
1679
- )
1680
- }
1681
- ],
1682
- unsafeUseModuleFallbackService: true
1683
- };
1684
- })
1685
- ],
1686
- unsafeModuleFallbackService(request) {
1687
- const url = new URL(request.url);
1688
- const rawSpecifier = url.searchParams.get("rawSpecifier");
1689
- assert4(
1690
- rawSpecifier,
1691
- `Unexpected error: no specifier in request to module fallback service.`
1692
- );
1693
- const moduleRE = new RegExp(MODULE_PATTERN);
1694
- const match = moduleRE.exec(rawSpecifier);
1695
- assert4(match, `Unexpected error: no match for module ${rawSpecifier}.`);
1696
- const [full, moduleType, modulePath] = match;
1697
- assert4(
1698
- modulePath,
1699
- `Unexpected error: module path not found in reference ${full}.`
1700
- );
1701
- let source;
1702
- try {
1703
- source = fs2.readFileSync(modulePath);
1704
- } catch (error) {
1705
- throw new Error(`Import ${modulePath} not found. Does the file exist?`);
1706
- }
1707
- return MiniflareResponse.json({
1708
- // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
1709
- wasm: Array.from(source)
1710
- });
1711
- }
1712
- };
1713
- }
1714
- function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
1715
- const resolvedViteConfig = vitePreviewServer.config;
1716
- const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
1717
- const workerConfigs = configPaths.map(
1718
- (configPath) => unstable_readConfig({ config: configPath })
1719
- );
1720
- const workers = workerConfigs.map((config) => {
1721
- const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
1722
- const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
1723
- return {
1724
- ...workerOptions,
1725
- // We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
1726
- name: config.name,
1727
- modules: true,
1728
- ...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
1729
- };
1730
- });
1731
- const logger = new ViteMiniflareLogger(resolvedViteConfig);
1732
- return {
1733
- log: logger,
1734
- handleRuntimeStdio(stdout, stderr) {
1735
- const decoder = new TextDecoder();
1736
- stdout.forEach((data2) => logger.info(decoder.decode(data2)));
1737
- stderr.forEach(
1738
- (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
1739
- );
1740
- },
1741
- ...getPersistence(resolvedViteConfig.root, persistState),
1742
- workers
1743
- };
1744
- }
1745
- var ViteMiniflareLogger = class extends Log {
1746
- logger;
1747
- constructor(config) {
1748
- super(miniflareLogLevelFromViteLogLevel(config.logLevel));
1749
- this.logger = config.logger;
1750
- }
1751
- logWithLevel(level, message) {
1752
- if (/^Ready on http/.test(message)) {
1753
- level = LogLevel.DEBUG;
1754
- }
1755
- switch (level) {
1756
- case LogLevel.ERROR:
1757
- return this.logger.error(message);
1758
- case LogLevel.WARN:
1759
- return this.logger.warn(message);
1760
- case LogLevel.INFO:
1761
- return this.logger.info(message);
1762
- }
1763
- }
1764
- };
1765
- function miniflareLogLevelFromViteLogLevel(level = "info") {
1766
- switch (level) {
1767
- case "error":
1768
- return LogLevel.ERROR;
1769
- case "warn":
1770
- return LogLevel.WARN;
1771
- case "info":
1772
- return LogLevel.INFO;
1773
- case "silent":
1774
- return LogLevel.NONE;
1775
- }
1776
- }
1077
+ import assert3 from "node:assert";
1078
+ import * as vite2 from "vite";
1777
1079
 
1778
1080
  // src/node-js-compat.ts
1779
- import assert6 from "node:assert";
1081
+ import assert2 from "node:assert";
1780
1082
  import { cloudflare } from "@cloudflare/unenv-preset";
1781
1083
  import { getNodeCompat } from "miniflare";
1782
1084
 
@@ -7309,7 +6611,7 @@ Parser.acorn = {
7309
6611
 
7310
6612
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7311
6613
  import { builtinModules, createRequire } from "node:module";
7312
- import fs3, { realpathSync, statSync as statSync2, promises } from "node:fs";
6614
+ import fs, { realpathSync, statSync, promises } from "node:fs";
7313
6615
 
7314
6616
  // ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
7315
6617
  var r = String.fromCharCode;
@@ -7366,9 +6668,9 @@ var isAbsolute = function(p) {
7366
6668
 
7367
6669
  // ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
7368
6670
  import { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL as pathToFileURL$1 } from "node:url";
7369
- import assert5 from "node:assert";
6671
+ import assert from "node:assert";
7370
6672
  import process$1 from "node:process";
7371
- import path4, { dirname as dirname3 } from "node:path";
6673
+ import path, { dirname as dirname2 } from "node:path";
7372
6674
  import v8 from "node:v8";
7373
6675
  import { format as format2, inspect } from "node:util";
7374
6676
  var BUILTIN_MODULES = new Set(builtinModules);
@@ -7404,7 +6706,7 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7404
6706
  * @param {unknown} actual
7405
6707
  */
7406
6708
  (name2, expected, actual) => {
7407
- assert5(typeof name2 === "string", "'name' must be a string");
6709
+ assert(typeof name2 === "string", "'name' must be a string");
7408
6710
  if (!Array.isArray(expected)) {
7409
6711
  expected = [expected];
7410
6712
  }
@@ -7420,14 +6722,14 @@ codes.ERR_INVALID_ARG_TYPE = createError(
7420
6722
  const instances = [];
7421
6723
  const other = [];
7422
6724
  for (const value of expected) {
7423
- assert5(
6725
+ assert(
7424
6726
  typeof value === "string",
7425
6727
  "All expected entries have to be of type string"
7426
6728
  );
7427
6729
  if (kTypes.has(value)) {
7428
6730
  types2.push(value.toLowerCase());
7429
6731
  } else if (classRegExp.exec(value) === null) {
7430
- assert5(
6732
+ assert(
7431
6733
  value !== "object",
7432
6734
  'The value "object" should be written as "Object"'
7433
6735
  );
@@ -7500,14 +6802,14 @@ codes.ERR_INVALID_PACKAGE_TARGET = createError(
7500
6802
  * @param {boolean} [isImport=false]
7501
6803
  * @param {string} [base]
7502
6804
  */
7503
- (packagePath, key, target, isImport = false, base = void 0) => {
7504
- 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("./");
7505
6807
  if (key === ".") {
7506
- assert5(isImport === false);
7507
- 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 "./"' : ""}`;
7508
6810
  }
7509
6811
  return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
7510
- target
6812
+ target2
7511
6813
  )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
7512
6814
  },
7513
6815
  Error
@@ -7668,9 +6970,9 @@ var captureLargerStackTrace = hideStackFrames(
7668
6970
  );
7669
6971
  function getMessage(key, parameters, self) {
7670
6972
  const message = messages.get(key);
7671
- assert5(message !== void 0, "expected `message` to be found");
6973
+ assert(message !== void 0, "expected `message` to be found");
7672
6974
  if (typeof message === "function") {
7673
- assert5(
6975
+ assert(
7674
6976
  message.length <= parameters.length,
7675
6977
  // Default options do not count.
7676
6978
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
@@ -7680,7 +6982,7 @@ function getMessage(key, parameters, self) {
7680
6982
  const regex = /%[dfijoOs]/g;
7681
6983
  let expectedLength = 0;
7682
6984
  while (regex.exec(message) !== null) expectedLength++;
7683
- assert5(
6985
+ assert(
7684
6986
  expectedLength === parameters.length,
7685
6987
  `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
7686
6988
  );
@@ -7717,7 +7019,7 @@ function read(jsonPath, { base, specifier }) {
7717
7019
  }
7718
7020
  let string;
7719
7021
  try {
7720
- string = fs3.readFileSync(path4.toNamespacedPath(jsonPath), "utf8");
7022
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
7721
7023
  } catch (error) {
7722
7024
  const exception = (
7723
7025
  /** @type {ErrnoException} */
@@ -7903,14 +7205,14 @@ var patternRegEx = /\*/g;
7903
7205
  var encodedSeparatorRegEx = /%2f|%5c/i;
7904
7206
  var emittedPackageWarnings = /* @__PURE__ */ new Set();
7905
7207
  var doubleSlashRegEx = /[/\\]{2}/;
7906
- function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
7208
+ function emitInvalidSegmentDeprecation(target2, request, match, packageJsonUrl, internal, base, isTarget) {
7907
7209
  if (process$1.noDeprecation) {
7908
7210
  return;
7909
7211
  }
7910
7212
  const pjsonPath = fileURLToPath$1(packageJsonUrl);
7911
- const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
7213
+ const double = doubleSlashRegEx.exec(isTarget ? target2 : request) !== null;
7912
7214
  process$1.emitWarning(
7913
- `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7215
+ `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target2}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}.`,
7914
7216
  "DeprecationWarning",
7915
7217
  "DEP0166"
7916
7218
  );
@@ -7933,7 +7235,7 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7933
7235
  "DeprecationWarning",
7934
7236
  "DEP0151"
7935
7237
  );
7936
- } else if (path4.resolve(packagePath, main) !== urlPath) {
7238
+ } else if (path.resolve(packagePath, main) !== urlPath) {
7937
7239
  process$1.emitWarning(
7938
7240
  `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
7939
7241
  packagePath.length
@@ -7946,12 +7248,12 @@ Default "index" lookups for the main are deprecated for ES modules.`,
7946
7248
  }
7947
7249
  function tryStatSync(path8) {
7948
7250
  try {
7949
- return statSync2(path8);
7251
+ return statSync(path8);
7950
7252
  } catch {
7951
7253
  }
7952
7254
  }
7953
7255
  function fileExists(url) {
7954
- const stats = statSync2(url, { throwIfNoEntry: false });
7256
+ const stats = statSync(url, { throwIfNoEntry: false });
7955
7257
  const isFile = stats ? stats.isFile() : void 0;
7956
7258
  return isFile === null || isFile === void 0 ? false : isFile;
7957
7259
  }
@@ -8040,7 +7342,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
8040
7342
  {
8041
7343
  const real = realpathSync(filePath);
8042
7344
  const { search, hash } = resolved;
8043
- resolved = pathToFileURL$1(real + (filePath.endsWith(path4.sep) ? "/" : ""));
7345
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? "/" : ""));
8044
7346
  resolved.search = search;
8045
7347
  resolved.hash = hash;
8046
7348
  }
@@ -8068,47 +7370,47 @@ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
8068
7370
  base && fileURLToPath$1(base)
8069
7371
  );
8070
7372
  }
8071
- function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
8072
- target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
7373
+ function invalidPackageTarget(subpath, target2, packageJsonUrl, internal, base) {
7374
+ target2 = typeof target2 === "object" && target2 !== null ? JSON.stringify(target2, null, "") : `${target2}`;
8073
7375
  return new ERR_INVALID_PACKAGE_TARGET(
8074
7376
  fileURLToPath$1(new URL$1(".", packageJsonUrl)),
8075
7377
  subpath,
8076
- target,
7378
+ target2,
8077
7379
  internal,
8078
7380
  base && fileURLToPath$1(base)
8079
7381
  );
8080
7382
  }
8081
- function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
8082
- if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
8083
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8084
- if (!target.startsWith("./")) {
8085
- if (internal && !target.startsWith("../") && !target.startsWith("/")) {
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("/")) {
8086
7388
  let isURL = false;
8087
7389
  try {
8088
- new URL$1(target);
7390
+ new URL$1(target2);
8089
7391
  isURL = true;
8090
7392
  } catch {
8091
7393
  }
8092
7394
  if (!isURL) {
8093
7395
  const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8094
7396
  patternRegEx,
8095
- target,
7397
+ target2,
8096
7398
  () => subpath
8097
- ) : target + subpath;
7399
+ ) : target2 + subpath;
8098
7400
  return packageResolve(exportTarget, packageJsonUrl, conditions);
8099
7401
  }
8100
7402
  }
8101
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
7403
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
8102
7404
  }
8103
- if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
8104
- if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
7405
+ if (invalidSegmentRegEx.exec(target2.slice(2)) !== null) {
7406
+ if (deprecatedInvalidSegmentRegEx.exec(target2.slice(2)) === null) {
8105
7407
  if (!isPathMap) {
8106
7408
  const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8107
7409
  const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8108
7410
  patternRegEx,
8109
- target,
7411
+ target2,
8110
7412
  () => subpath
8111
- ) : target;
7413
+ ) : target2;
8112
7414
  emitInvalidSegmentDeprecation(
8113
7415
  resolvedTarget,
8114
7416
  request,
@@ -8119,684 +7421,1413 @@ function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base
8119
7421
  true
8120
7422
  );
8121
7423
  }
8122
- } else {
8123
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8124
- }
8125
- }
8126
- const resolved = new URL$1(target, packageJsonUrl);
8127
- const resolvedPath = resolved.pathname;
8128
- const packagePath = new URL$1(".", packageJsonUrl).pathname;
8129
- if (!resolvedPath.startsWith(packagePath))
8130
- throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
8131
- if (subpath === "") return resolved;
8132
- if (invalidSegmentRegEx.exec(subpath) !== null) {
8133
- const request = pattern ? match.replace("*", () => subpath) : match + subpath;
8134
- if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
8135
- if (!isPathMap) {
8136
- const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
8137
- patternRegEx,
8138
- target,
8139
- () => subpath
8140
- ) : target;
8141
- emitInvalidSegmentDeprecation(
8142
- resolvedTarget,
8143
- request,
8144
- match,
8145
- packageJsonUrl,
8146
- internal,
8147
- base,
8148
- false
7424
+ } else {
7425
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7426
+ }
7427
+ }
7428
+ const resolved = new URL$1(target2, packageJsonUrl);
7429
+ const resolvedPath = resolved.pathname;
7430
+ const packagePath = new URL$1(".", packageJsonUrl).pathname;
7431
+ if (!resolvedPath.startsWith(packagePath))
7432
+ throw invalidPackageTarget(match, target2, packageJsonUrl, internal, base);
7433
+ if (subpath === "") return resolved;
7434
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
7435
+ const request = pattern ? match.replace("*", () => subpath) : match + subpath;
7436
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
7437
+ if (!isPathMap) {
7438
+ const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
7439
+ patternRegEx,
7440
+ target2,
7441
+ () => subpath
7442
+ ) : target2;
7443
+ emitInvalidSegmentDeprecation(
7444
+ resolvedTarget,
7445
+ request,
7446
+ match,
7447
+ packageJsonUrl,
7448
+ internal,
7449
+ base,
7450
+ false
7451
+ );
7452
+ }
7453
+ } else {
7454
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
7455
+ }
7456
+ }
7457
+ if (pattern) {
7458
+ return new URL$1(
7459
+ RegExpPrototypeSymbolReplace.call(
7460
+ patternRegEx,
7461
+ resolved.href,
7462
+ () => subpath
7463
+ )
7464
+ );
7465
+ }
7466
+ return new URL$1(subpath, resolved);
7467
+ }
7468
+ function isArrayIndex(key) {
7469
+ const keyNumber = Number(key);
7470
+ if (`${keyNumber}` !== key) return false;
7471
+ return keyNumber >= 0 && keyNumber < 4294967295;
7472
+ }
7473
+ function resolvePackageTarget(packageJsonUrl, target2, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
7474
+ if (typeof target2 === "string") {
7475
+ return resolvePackageTargetString(
7476
+ target2,
7477
+ subpath,
7478
+ packageSubpath,
7479
+ packageJsonUrl,
7480
+ base,
7481
+ pattern,
7482
+ internal,
7483
+ isPathMap,
7484
+ conditions
7485
+ );
7486
+ }
7487
+ if (Array.isArray(target2)) {
7488
+ const targetList = target2;
7489
+ if (targetList.length === 0) return null;
7490
+ let lastException;
7491
+ let i = -1;
7492
+ while (++i < targetList.length) {
7493
+ const targetItem = targetList[i];
7494
+ let resolveResult;
7495
+ try {
7496
+ resolveResult = resolvePackageTarget(
7497
+ packageJsonUrl,
7498
+ targetItem,
7499
+ subpath,
7500
+ packageSubpath,
7501
+ base,
7502
+ pattern,
7503
+ internal,
7504
+ isPathMap,
7505
+ conditions
7506
+ );
7507
+ } catch (error) {
7508
+ const exception = (
7509
+ /** @type {ErrnoException} */
7510
+ error
7511
+ );
7512
+ lastException = exception;
7513
+ if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
7514
+ throw error;
7515
+ }
7516
+ if (resolveResult === void 0) continue;
7517
+ if (resolveResult === null) {
7518
+ lastException = null;
7519
+ continue;
7520
+ }
7521
+ return resolveResult;
7522
+ }
7523
+ if (lastException === void 0 || lastException === null) {
7524
+ return null;
7525
+ }
7526
+ throw lastException;
7527
+ }
7528
+ if (typeof target2 === "object" && target2 !== null) {
7529
+ const keys = Object.getOwnPropertyNames(target2);
7530
+ let i = -1;
7531
+ while (++i < keys.length) {
7532
+ const key = keys[i];
7533
+ if (isArrayIndex(key)) {
7534
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7535
+ fileURLToPath$1(packageJsonUrl),
7536
+ base,
7537
+ '"exports" cannot contain numeric property keys.'
7538
+ );
7539
+ }
7540
+ }
7541
+ i = -1;
7542
+ while (++i < keys.length) {
7543
+ const key = keys[i];
7544
+ if (key === "default" || conditions && conditions.has(key)) {
7545
+ const conditionalTarget = (
7546
+ /** @type {unknown} */
7547
+ target2[key]
7548
+ );
7549
+ const resolveResult = resolvePackageTarget(
7550
+ packageJsonUrl,
7551
+ conditionalTarget,
7552
+ subpath,
7553
+ packageSubpath,
7554
+ base,
7555
+ pattern,
7556
+ internal,
7557
+ isPathMap,
7558
+ conditions
7559
+ );
7560
+ if (resolveResult === void 0) continue;
7561
+ return resolveResult;
7562
+ }
7563
+ }
7564
+ return null;
7565
+ }
7566
+ if (target2 === null) {
7567
+ return null;
7568
+ }
7569
+ throw invalidPackageTarget(
7570
+ packageSubpath,
7571
+ target2,
7572
+ packageJsonUrl,
7573
+ internal,
7574
+ base
7575
+ );
7576
+ }
7577
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
7578
+ if (typeof exports === "string" || Array.isArray(exports)) return true;
7579
+ if (typeof exports !== "object" || exports === null) return false;
7580
+ const keys = Object.getOwnPropertyNames(exports);
7581
+ let isConditionalSugar = false;
7582
+ let i = 0;
7583
+ let keyIndex = -1;
7584
+ while (++keyIndex < keys.length) {
7585
+ const key = keys[keyIndex];
7586
+ const currentIsConditionalSugar = key === "" || key[0] !== ".";
7587
+ if (i++ === 0) {
7588
+ isConditionalSugar = currentIsConditionalSugar;
7589
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
7590
+ throw new ERR_INVALID_PACKAGE_CONFIG(
7591
+ fileURLToPath$1(packageJsonUrl),
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
+ }
7596
+ }
7597
+ return isConditionalSugar;
7598
+ }
7599
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
7600
+ if (process$1.noDeprecation) {
7601
+ return;
7602
+ }
7603
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
7604
+ if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
7605
+ emittedPackageWarnings.add(pjsonPath + "|" + match);
7606
+ process$1.emitWarning(
7607
+ `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath$1(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
7608
+ "DeprecationWarning",
7609
+ "DEP0155"
7610
+ );
7611
+ }
7612
+ function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
7613
+ let exports = packageConfig.exports;
7614
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
7615
+ exports = { ".": exports };
7616
+ }
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
7629
+ );
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
8149
7656
  );
8150
7657
  }
8151
- } else {
8152
- throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
8153
7658
  }
8154
7659
  }
8155
- if (pattern) {
8156
- return new URL$1(
8157
- RegExpPrototypeSymbolReplace.call(
8158
- patternRegEx,
8159
- resolved.href,
8160
- () => subpath
8161
- )
7660
+ if (bestMatch) {
7661
+ const target2 = (
7662
+ /** @type {unknown} */
7663
+ exports[bestMatch]
8162
7664
  );
8163
- }
8164
- return new URL$1(subpath, resolved);
8165
- }
8166
- function isArrayIndex(key) {
8167
- const keyNumber = Number(key);
8168
- if (`${keyNumber}` !== key) return false;
8169
- return keyNumber >= 0 && keyNumber < 4294967295;
8170
- }
8171
- function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
8172
- if (typeof target === "string") {
8173
- return resolvePackageTargetString(
8174
- target,
8175
- subpath,
8176
- packageSubpath,
7665
+ const resolveResult = resolvePackageTarget(
8177
7666
  packageJsonUrl,
7667
+ target2,
7668
+ bestMatchSubpath,
7669
+ bestMatch,
8178
7670
  base,
8179
- pattern,
8180
- internal,
8181
- isPathMap,
7671
+ true,
7672
+ false,
7673
+ packageSubpath.endsWith("/"),
8182
7674
  conditions
8183
7675
  );
7676
+ if (resolveResult === null || resolveResult === void 0) {
7677
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7678
+ }
7679
+ return resolveResult;
8184
7680
  }
8185
- if (Array.isArray(target)) {
8186
- const targetList = target;
8187
- if (targetList.length === 0) return null;
8188
- let lastException;
8189
- let i = -1;
8190
- while (++i < targetList.length) {
8191
- const targetItem = targetList[i];
8192
- let resolveResult;
8193
- try {
8194
- resolveResult = resolvePackageTarget(
7681
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base);
7682
+ }
7683
+ function patternKeyCompare(a, b) {
7684
+ const aPatternIndex = a.indexOf("*");
7685
+ const bPatternIndex = b.indexOf("*");
7686
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
7687
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
7688
+ if (baseLengthA > baseLengthB) return -1;
7689
+ if (baseLengthB > baseLengthA) return 1;
7690
+ if (aPatternIndex === -1) return 1;
7691
+ if (bPatternIndex === -1) return -1;
7692
+ if (a.length > b.length) return -1;
7693
+ if (b.length > a.length) return 1;
7694
+ return 0;
7695
+ }
7696
+ function packageImportsResolve(name2, base, conditions) {
7697
+ if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
7698
+ const reason = "is not a valid internal imports specifier name";
7699
+ throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
7700
+ }
7701
+ let packageJsonUrl;
7702
+ const packageConfig = getPackageScopeConfig(base);
7703
+ if (packageConfig.exists) {
7704
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
7705
+ const imports = packageConfig.imports;
7706
+ if (imports) {
7707
+ if (own.call(imports, name2) && !name2.includes("*")) {
7708
+ const resolveResult = resolvePackageTarget(
8195
7709
  packageJsonUrl,
8196
- targetItem,
8197
- subpath,
8198
- packageSubpath,
7710
+ imports[name2],
7711
+ "",
7712
+ name2,
8199
7713
  base,
8200
- pattern,
8201
- internal,
8202
- isPathMap,
7714
+ false,
7715
+ true,
7716
+ false,
8203
7717
  conditions
8204
7718
  );
8205
- } catch (error) {
8206
- const exception = (
8207
- /** @type {ErrnoException} */
8208
- error
8209
- );
8210
- lastException = exception;
8211
- if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
8212
- throw error;
8213
- }
8214
- if (resolveResult === void 0) continue;
8215
- if (resolveResult === null) {
8216
- lastException = null;
8217
- continue;
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
+ }
8218
7758
  }
8219
- return resolveResult;
8220
7759
  }
8221
- if (lastException === void 0 || lastException === null) {
8222
- return null;
7760
+ }
7761
+ throw importNotDefined(name2, packageJsonUrl, base);
7762
+ }
7763
+ function parsePackageName(specifier, base) {
7764
+ let separatorIndex = specifier.indexOf("/");
7765
+ let validPackageName = true;
7766
+ let isScoped = false;
7767
+ if (specifier[0] === "@") {
7768
+ isScoped = true;
7769
+ if (separatorIndex === -1 || specifier.length === 0) {
7770
+ validPackageName = false;
7771
+ } else {
7772
+ separatorIndex = specifier.indexOf("/", separatorIndex + 1);
7773
+ }
7774
+ }
7775
+ const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
7776
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
7777
+ validPackageName = false;
7778
+ }
7779
+ if (!validPackageName) {
7780
+ throw new ERR_INVALID_MODULE_SPECIFIER(
7781
+ specifier,
7782
+ "is not a valid package name",
7783
+ fileURLToPath$1(base)
7784
+ );
7785
+ }
7786
+ const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
7787
+ return { packageName, packageSubpath, isScoped };
7788
+ }
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(
7794
+ specifier,
7795
+ base
7796
+ );
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
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);
7843
+ }
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;
8223
7849
  }
8224
- throw lastException;
8225
7850
  }
8226
- if (typeof target === "object" && target !== null) {
8227
- const keys = Object.getOwnPropertyNames(target);
8228
- let i = -1;
8229
- while (++i < keys.length) {
8230
- const key = keys[i];
8231
- if (isArrayIndex(key)) {
8232
- throw new ERR_INVALID_PACKAGE_CONFIG(
8233
- fileURLToPath$1(packageJsonUrl),
8234
- base,
8235
- '"exports" cannot contain numeric property keys.'
8236
- );
8237
- }
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;
8238
7870
  }
8239
- i = -1;
8240
- while (++i < keys.length) {
8241
- const key = keys[i];
8242
- if (key === "default" || conditions && conditions.has(key)) {
8243
- const conditionalTarget = (
8244
- /** @type {unknown} */
8245
- target[key]
8246
- );
8247
- const resolveResult = resolvePackageTarget(
8248
- packageJsonUrl,
8249
- conditionalTarget,
8250
- subpath,
8251
- packageSubpath,
8252
- base,
8253
- pattern,
8254
- internal,
8255
- isPathMap,
8256
- conditions
8257
- );
8258
- if (resolveResult === void 0) continue;
8259
- return resolveResult;
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;
8260
7881
  }
7882
+ resolved = packageResolve(specifier, base, conditions);
8261
7883
  }
8262
- return null;
8263
7884
  }
8264
- if (target === null) {
8265
- return null;
7885
+ assert(resolved !== void 0, "expected to be defined");
7886
+ if (resolved.protocol !== "file:") {
7887
+ return resolved;
8266
7888
  }
8267
- throw invalidPackageTarget(
8268
- packageSubpath,
8269
- target,
8270
- packageJsonUrl,
8271
- internal,
8272
- base
8273
- );
7889
+ return finalizeResolution(resolved, base);
8274
7890
  }
8275
- function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
8276
- if (typeof exports === "string" || Array.isArray(exports)) return true;
8277
- if (typeof exports !== "object" || exports === null) return false;
8278
- const keys = Object.getOwnPropertyNames(exports);
8279
- let isConditionalSugar = false;
8280
- let i = 0;
8281
- let keyIndex = -1;
8282
- while (++keyIndex < keys.length) {
8283
- const key = keys[keyIndex];
8284
- const currentIsConditionalSugar = key === "" || key[0] !== ".";
8285
- if (i++ === 0) {
8286
- isConditionalSugar = currentIsConditionalSugar;
8287
- } else if (isConditionalSugar !== currentIsConditionalSugar) {
8288
- throw new ERR_INVALID_PACKAGE_CONFIG(
8289
- fileURLToPath$1(packageJsonUrl),
8290
- base,
8291
- `"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.`
8292
- );
8293
- }
7891
+ function fileURLToPath(id) {
7892
+ if (typeof id === "string" && !id.startsWith("file://")) {
7893
+ return normalizeSlash(id);
8294
7894
  }
8295
- return isConditionalSugar;
7895
+ return normalizeSlash(fileURLToPath$1(id));
8296
7896
  }
8297
- function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
8298
- if (process$1.noDeprecation) {
8299
- return;
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();
8300
7903
  }
8301
- const pjsonPath = fileURLToPath$1(pjsonUrl);
8302
- if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
8303
- emittedPackageWarnings.add(pjsonPath + "|" + match);
8304
- process$1.emitWarning(
8305
- `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.`,
8306
- "DeprecationWarning",
8307
- "DEP0155"
8308
- );
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));
8309
7911
  }
8310
- function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
8311
- let exports = packageConfig.exports;
8312
- if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
8313
- exports = { ".": exports };
7912
+ var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
7913
+ var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
7914
+ var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
7915
+ "ERR_MODULE_NOT_FOUND",
7916
+ "ERR_UNSUPPORTED_DIR_IMPORT",
7917
+ "MODULE_NOT_FOUND",
7918
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
7919
+ ]);
7920
+ function _tryModuleResolve(id, url, conditions) {
7921
+ try {
7922
+ return moduleResolve(id, url, conditions);
7923
+ } catch (error) {
7924
+ if (!NOT_FOUND_ERRORS.has(error?.code)) {
7925
+ throw error;
7926
+ }
8314
7927
  }
8315
- if (own.call(exports, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
8316
- const target = exports[packageSubpath];
8317
- const resolveResult = resolvePackageTarget(
8318
- packageJsonUrl,
8319
- target,
8320
- "",
8321
- packageSubpath,
8322
- base,
8323
- false,
8324
- false,
8325
- false,
8326
- conditions
8327
- );
8328
- if (resolveResult === null || resolveResult === void 0) {
8329
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
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`");
8330
7935
  }
8331
- return resolveResult;
8332
7936
  }
8333
- let bestMatch = "";
8334
- let bestMatchSubpath = "";
8335
- const keys = Object.getOwnPropertyNames(exports);
8336
- let i = -1;
8337
- while (++i < keys.length) {
8338
- const key = keys[i];
8339
- const patternIndex = key.indexOf("*");
8340
- if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
8341
- if (packageSubpath.endsWith("/")) {
8342
- emitTrailingSlashPatternDeprecation(
8343
- packageSubpath,
8344
- packageJsonUrl,
8345
- base
8346
- );
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);
8347
7951
  }
8348
- const patternTrailer = key.slice(patternIndex + 1);
8349
- if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8350
- bestMatch = key;
8351
- bestMatchSubpath = packageSubpath.slice(
8352
- patternIndex,
8353
- packageSubpath.length - patternTrailer.length
7952
+ } catch (error) {
7953
+ if (error?.code !== "ENOENT") {
7954
+ throw error;
7955
+ }
7956
+ }
7957
+ }
7958
+ const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
7959
+ const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
7960
+ if (_urls.length === 0) {
7961
+ _urls.push(new URL(pathToFileURL(process.cwd())));
7962
+ }
7963
+ const urls = [..._urls];
7964
+ for (const url of _urls) {
7965
+ if (url.protocol === "file:") {
7966
+ urls.push(
7967
+ new URL("./", url),
7968
+ // If url is directory
7969
+ new URL(joinURL(url.pathname, "_index.js"), url),
7970
+ // TODO: Remove in next major version?
7971
+ new URL("node_modules", url)
7972
+ );
7973
+ }
7974
+ }
7975
+ let resolved;
7976
+ for (const url of urls) {
7977
+ resolved = _tryModuleResolve(id, url, conditionsSet);
7978
+ if (resolved) {
7979
+ break;
7980
+ }
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
8354
7987
  );
7988
+ if (resolved) {
7989
+ break;
7990
+ }
8355
7991
  }
7992
+ if (resolved) {
7993
+ break;
7994
+ }
7995
+ }
7996
+ if (resolved) {
7997
+ break;
8356
7998
  }
8357
7999
  }
8358
- if (bestMatch) {
8359
- const target = (
8360
- /** @type {unknown} */
8361
- exports[bestMatch]
8000
+ if (!resolved) {
8001
+ const error = new Error(
8002
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
8003
+ );
8004
+ error.code = "ERR_MODULE_NOT_FOUND";
8005
+ throw error;
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`
8362
8038
  );
8363
- const resolveResult = resolvePackageTarget(
8364
- packageJsonUrl,
8365
- target,
8366
- bestMatchSubpath,
8367
- bestMatch,
8368
- base,
8369
- true,
8370
- false,
8371
- packageSubpath.endsWith("/"),
8372
- conditions
8039
+ }
8040
+ return false;
8041
+ }
8042
+ function injectGlobalCode(id, code) {
8043
+ const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8044
+ if (typeof globalInject === "string") {
8045
+ const moduleSpecifier2 = globalInject;
8046
+ return `import var_${globalName} from "${moduleSpecifier2}";
8047
+ globalThis.${globalName} = var_${globalName};
8048
+ `;
8049
+ }
8050
+ const [moduleSpecifier, exportName] = globalInject;
8051
+ assert2(
8052
+ moduleSpecifier !== void 0,
8053
+ "Expected moduleSpecifier to be defined"
8373
8054
  );
8374
- if (resolveResult === null || resolveResult === void 0) {
8375
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8055
+ assert2(exportName !== void 0, "Expected exportName to be defined");
8056
+ return `import var_${globalName} from "${moduleSpecifier}";
8057
+ globalThis.${globalName} = var_${globalName}.${exportName};
8058
+ `;
8059
+ }).join("\n");
8060
+ const modified = new MagicString(code);
8061
+ modified.prepend(injectedCode);
8062
+ return {
8063
+ code: modified.toString(),
8064
+ map: modified.generateMap({ hires: "boundary", source: id })
8065
+ };
8066
+ }
8067
+ function resolveNodeJSImport(source) {
8068
+ const alias = env.alias[source];
8069
+ if (alias) {
8070
+ return {
8071
+ unresolved: alias,
8072
+ resolved: resolvePathSync(alias, { url: import.meta.url })
8073
+ };
8074
+ }
8075
+ if (nodeCompatEntries.has(source)) {
8076
+ return {
8077
+ unresolved: source,
8078
+ resolved: resolvePathSync(source, { url: import.meta.url })
8079
+ };
8080
+ }
8081
+ }
8082
+ function getNodeCompatEntries() {
8083
+ const entries = new Set(Object.values(env.alias));
8084
+ for (const globalInject of Object.values(env.inject)) {
8085
+ if (typeof globalInject === "string") {
8086
+ entries.add(globalInject);
8087
+ } else {
8088
+ assert2(
8089
+ globalInject[0] !== void 0,
8090
+ "Expected first element of globalInject to be defined"
8091
+ );
8092
+ entries.add(globalInject[0]);
8376
8093
  }
8377
- return resolveResult;
8378
8094
  }
8379
- throw exportsNotFound(packageSubpath, packageJsonUrl, base);
8095
+ nodeCompatExternals.forEach((external) => entries.delete(external));
8096
+ return entries;
8380
8097
  }
8381
- function patternKeyCompare(a, b) {
8382
- const aPatternIndex = a.indexOf("*");
8383
- const bPatternIndex = b.indexOf("*");
8384
- const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
8385
- const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
8386
- if (baseLengthA > baseLengthB) return -1;
8387
- if (baseLengthB > baseLengthA) return 1;
8388
- if (aPatternIndex === -1) return 1;
8389
- if (bPatternIndex === -1) return -1;
8390
- if (a.length > b.length) return -1;
8391
- if (b.length > a.length) return 1;
8392
- return 0;
8098
+
8099
+ // src/constants.ts
8100
+ var ROUTER_WORKER_NAME = "__router-worker__";
8101
+ var ASSET_WORKER_NAME = "__asset-worker__";
8102
+ var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
8103
+ var MODULE_TYPES = ["CompiledWasm"];
8104
+
8105
+ // src/shared.ts
8106
+ var UNKNOWN_HOST = "http://localhost";
8107
+ var INIT_PATH = "/__vite_plugin_cloudflare_init__";
8108
+ var MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_TYPES.join("|")})__(.*?)__`;
8109
+ var VITE_DEV_METADATA_HEADER = "__VITE_DEV_METADATA__";
8110
+
8111
+ // src/utils.ts
8112
+ import * as path2 from "node:path";
8113
+ import { Request as MiniflareRequest } from "miniflare";
8114
+ import "vite";
8115
+ function getOutputDirectory(userConfig, environmentName) {
8116
+ const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
8117
+ return userConfig.environments?.[environmentName]?.build?.outDir ?? path2.join(rootOutputDirectory, environmentName);
8393
8118
  }
8394
- function packageImportsResolve(name2, base, conditions) {
8395
- if (name2 === "#" || name2.startsWith("#/") || name2.endsWith("/")) {
8396
- const reason = "is not a valid internal imports specifier name";
8397
- throw new ERR_INVALID_MODULE_SPECIFIER(name2, reason, fileURLToPath$1(base));
8398
- }
8399
- let packageJsonUrl;
8400
- const packageConfig = getPackageScopeConfig(base);
8401
- if (packageConfig.exists) {
8402
- packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
8403
- const imports = packageConfig.imports;
8404
- if (imports) {
8405
- if (own.call(imports, name2) && !name2.includes("*")) {
8406
- const resolveResult = resolvePackageTarget(
8407
- packageJsonUrl,
8408
- imports[name2],
8409
- "",
8410
- name2,
8411
- base,
8412
- false,
8413
- true,
8414
- false,
8415
- conditions
8416
- );
8417
- if (resolveResult !== null && resolveResult !== void 0) {
8418
- return resolveResult;
8419
- }
8420
- } else {
8421
- let bestMatch = "";
8422
- let bestMatchSubpath = "";
8423
- const keys = Object.getOwnPropertyNames(imports);
8424
- let i = -1;
8425
- while (++i < keys.length) {
8426
- const key = keys[i];
8427
- const patternIndex = key.indexOf("*");
8428
- if (patternIndex !== -1 && name2.startsWith(key.slice(0, -1))) {
8429
- const patternTrailer = key.slice(patternIndex + 1);
8430
- if (name2.length >= key.length && name2.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
8431
- bestMatch = key;
8432
- bestMatchSubpath = name2.slice(
8433
- patternIndex,
8434
- name2.length - patternTrailer.length
8435
- );
8436
- }
8437
- }
8438
- }
8439
- if (bestMatch) {
8440
- const target = imports[bestMatch];
8441
- const resolveResult = resolvePackageTarget(
8442
- packageJsonUrl,
8443
- target,
8444
- bestMatchSubpath,
8445
- bestMatch,
8446
- base,
8447
- true,
8448
- true,
8449
- false,
8450
- conditions
8451
- );
8452
- if (resolveResult !== null && resolveResult !== void 0) {
8453
- return resolveResult;
8454
- }
8455
- }
8119
+ function toMiniflareRequest(request) {
8120
+ return new MiniflareRequest(request.url, {
8121
+ method: request.method,
8122
+ headers: [["accept-encoding", "identity"], ...request.headers],
8123
+ body: request.body,
8124
+ duplex: "half"
8125
+ });
8126
+ }
8127
+ function nodeHeadersToWebHeaders(nodeHeaders) {
8128
+ const headers = new Headers();
8129
+ for (const [key, value] of Object.entries(nodeHeaders)) {
8130
+ if (typeof value === "string") {
8131
+ headers.append(key, value);
8132
+ } else if (Array.isArray(value)) {
8133
+ for (const item of value) {
8134
+ headers.append(key, item);
8456
8135
  }
8457
8136
  }
8458
8137
  }
8459
- throw importNotDefined(name2, packageJsonUrl, base);
8138
+ return headers;
8460
8139
  }
8461
- function parsePackageName(specifier, base) {
8462
- let separatorIndex = specifier.indexOf("/");
8463
- let validPackageName = true;
8464
- let isScoped = false;
8465
- if (specifier[0] === "@") {
8466
- isScoped = true;
8467
- if (separatorIndex === -1 || specifier.length === 0) {
8468
- validPackageName = false;
8469
- } else {
8470
- separatorIndex = specifier.indexOf("/", separatorIndex + 1);
8140
+
8141
+ // src/cloudflare-environment.ts
8142
+ var webSocketUndefinedError = "The WebSocket is undefined";
8143
+ function createHotChannel(webSocketContainer) {
8144
+ const listenersMap = /* @__PURE__ */ new Map();
8145
+ const client = {
8146
+ send(payload) {
8147
+ const webSocket = webSocketContainer.webSocket;
8148
+ assert3(webSocket, webSocketUndefinedError);
8149
+ webSocket.send(JSON.stringify(payload));
8150
+ }
8151
+ };
8152
+ function onMessage(event) {
8153
+ const payload = JSON.parse(event.data.toString());
8154
+ const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
8155
+ for (const listener of listeners) {
8156
+ listener(payload.data, client);
8471
8157
  }
8472
8158
  }
8473
- const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
8474
- if (invalidPackageNameRegEx.exec(packageName) !== null) {
8475
- validPackageName = false;
8159
+ return {
8160
+ send(payload) {
8161
+ const webSocket = webSocketContainer.webSocket;
8162
+ assert3(webSocket, webSocketUndefinedError);
8163
+ webSocket.send(JSON.stringify(payload));
8164
+ },
8165
+ on(event, listener) {
8166
+ const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
8167
+ listeners.add(listener);
8168
+ listenersMap.set(event, listeners);
8169
+ },
8170
+ off(event, listener) {
8171
+ listenersMap.get(event)?.delete(listener);
8172
+ },
8173
+ listen() {
8174
+ const webSocket = webSocketContainer.webSocket;
8175
+ assert3(webSocket, webSocketUndefinedError);
8176
+ webSocket.addEventListener("message", onMessage);
8177
+ },
8178
+ close() {
8179
+ const webSocket = webSocketContainer.webSocket;
8180
+ assert3(webSocket, webSocketUndefinedError);
8181
+ webSocket.removeEventListener("message", onMessage);
8182
+ }
8183
+ };
8184
+ }
8185
+ var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
8186
+ #webSocketContainer;
8187
+ #worker;
8188
+ constructor(name2, config) {
8189
+ const webSocketContainer = {};
8190
+ super(name2, config, {
8191
+ hot: true,
8192
+ transport: createHotChannel(webSocketContainer)
8193
+ });
8194
+ this.#webSocketContainer = webSocketContainer;
8476
8195
  }
8477
- if (!validPackageName) {
8478
- throw new ERR_INVALID_MODULE_SPECIFIER(
8479
- specifier,
8480
- "is not a valid package name",
8481
- fileURLToPath$1(base)
8196
+ async initRunner(worker, root, workerConfig) {
8197
+ this.#worker = worker;
8198
+ const response = await this.#worker.fetch(
8199
+ new URL(INIT_PATH, UNKNOWN_HOST),
8200
+ {
8201
+ headers: {
8202
+ [VITE_DEV_METADATA_HEADER]: JSON.stringify({
8203
+ root,
8204
+ entryPath: workerConfig.main
8205
+ }),
8206
+ upgrade: "websocket"
8207
+ }
8208
+ }
8209
+ );
8210
+ assert3(
8211
+ response.ok,
8212
+ `Failed to initialize module runner, error: ${await response.text()}`
8482
8213
  );
8214
+ const webSocket = response.webSocket;
8215
+ assert3(webSocket, "Failed to establish WebSocket");
8216
+ webSocket.accept();
8217
+ this.#webSocketContainer.webSocket = webSocket;
8483
8218
  }
8484
- const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
8485
- return { packageName, packageSubpath, isScoped };
8219
+ };
8220
+ var cloudflareBuiltInModules = [
8221
+ "cloudflare:email",
8222
+ "cloudflare:sockets",
8223
+ "cloudflare:workers",
8224
+ "cloudflare:workflows"
8225
+ ];
8226
+ var defaultConditions = ["workerd", "module", "browser"];
8227
+ var target = "es2022";
8228
+ function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
8229
+ return {
8230
+ resolve: {
8231
+ // Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
8232
+ // dependencies as not external
8233
+ noExternal: true,
8234
+ // We want to use `workerd` package exports if available (e.g. for postgres).
8235
+ conditions: [...defaultConditions, "development|production"],
8236
+ // The Cloudflare ones are proper builtins in the environment
8237
+ builtins: [...cloudflareBuiltInModules]
8238
+ },
8239
+ dev: {
8240
+ createEnvironment(name2, config) {
8241
+ return new CloudflareDevEnvironment(name2, config);
8242
+ }
8243
+ },
8244
+ build: {
8245
+ createEnvironment(name2, config) {
8246
+ return new vite2.BuildEnvironment(name2, config);
8247
+ },
8248
+ target,
8249
+ // We need to enable `emitAssets` in order to support additional modules defined by `rules`
8250
+ emitAssets: true,
8251
+ outDir: getOutputDirectory(userConfig, environmentName),
8252
+ copyPublicDir: false,
8253
+ ssr: true,
8254
+ rollupOptions: {
8255
+ // Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
8256
+ // so the input value here serves both as the build input as well as the starting point for
8257
+ // dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
8258
+ // optimizeDeps.entries in the dev config)
8259
+ input: workerConfig.main
8260
+ }
8261
+ },
8262
+ optimizeDeps: {
8263
+ // Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
8264
+ noDiscovery: false,
8265
+ entries: workerConfig.main,
8266
+ exclude: [...cloudflareBuiltInModules],
8267
+ esbuildOptions: {
8268
+ platform: "neutral",
8269
+ target,
8270
+ conditions: [...defaultConditions, "development"],
8271
+ resolveExtensions: [
8272
+ ".mjs",
8273
+ ".js",
8274
+ ".mts",
8275
+ ".ts",
8276
+ ".jsx",
8277
+ ".tsx",
8278
+ ".json",
8279
+ ".cjs",
8280
+ ".cts",
8281
+ ".ctx"
8282
+ ]
8283
+ }
8284
+ },
8285
+ // if nodeCompat is enabled then let's keep the real process.env so that workerd can manipulate it
8286
+ keepProcessEnv: isNodeCompat(workerConfig)
8287
+ };
8486
8288
  }
8487
- function packageResolve(specifier, base, conditions) {
8488
- if (builtinModules.includes(specifier)) {
8489
- return new URL$1("node:" + specifier);
8490
- }
8491
- const { packageName, packageSubpath, isScoped } = parsePackageName(
8492
- specifier,
8493
- base
8494
- );
8495
- const packageConfig = getPackageScopeConfig(base);
8496
- if (packageConfig.exists) {
8497
- const packageJsonUrl2 = pathToFileURL$1(packageConfig.pjsonPath);
8498
- if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
8499
- return packageExportsResolve(
8500
- packageJsonUrl2,
8501
- packageSubpath,
8502
- packageConfig,
8503
- base,
8504
- conditions
8505
- );
8506
- }
8289
+ function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
8290
+ if (resolvedPluginConfig.type === "assets-only") {
8291
+ return;
8507
8292
  }
8508
- let packageJsonUrl = new URL$1(
8509
- "./node_modules/" + packageName + "/package.json",
8510
- base
8293
+ return Promise.all(
8294
+ Object.entries(resolvedPluginConfig.workers).map(
8295
+ async ([environmentName, workerConfig]) => {
8296
+ const worker = await miniflare.getWorker(workerConfig.name);
8297
+ return viteDevServer.environments[environmentName].initRunner(worker, viteDevServer.config.root, workerConfig);
8298
+ }
8299
+ )
8511
8300
  );
8512
- let packageJsonPath = fileURLToPath$1(packageJsonUrl);
8513
- let lastPath;
8514
- do {
8515
- const stat = tryStatSync(packageJsonPath.slice(0, -13));
8516
- if (!stat || !stat.isDirectory()) {
8517
- lastPath = packageJsonPath;
8518
- packageJsonUrl = new URL$1(
8519
- (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
8520
- packageJsonUrl
8521
- );
8522
- packageJsonPath = fileURLToPath$1(packageJsonUrl);
8523
- continue;
8524
- }
8525
- const packageConfig2 = read(packageJsonPath, { base, specifier });
8526
- if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
8527
- return packageExportsResolve(
8528
- packageJsonUrl,
8529
- packageSubpath,
8530
- packageConfig2,
8531
- base,
8532
- conditions
8533
- );
8534
- }
8535
- if (packageSubpath === ".") {
8536
- return legacyMainResolve(packageJsonUrl, packageConfig2, base);
8537
- }
8538
- return new URL$1(packageSubpath, packageJsonUrl);
8539
- } while (packageJsonPath.length !== lastPath.length);
8540
- throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false);
8541
8301
  }
8542
- function isRelativeSpecifier(specifier) {
8543
- if (specifier[0] === ".") {
8544
- if (specifier.length === 1 || specifier[1] === "/") return true;
8545
- if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
8546
- return true;
8547
- }
8548
- }
8549
- return false;
8302
+
8303
+ // src/deploy-config.ts
8304
+ import assert4 from "node:assert";
8305
+ import * as fs2 from "node:fs";
8306
+ import * as path3 from "node:path";
8307
+ import "vite";
8308
+ function getDeployConfigPath(root) {
8309
+ return path3.resolve(root, ".wrangler", "deploy", "config.json");
8550
8310
  }
8551
- function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
8552
- if (specifier === "") return false;
8553
- if (specifier[0] === "/") return true;
8554
- return isRelativeSpecifier(specifier);
8311
+ function getWorkerConfigPaths(root) {
8312
+ const deployConfigPath = getDeployConfigPath(root);
8313
+ const deployConfig = JSON.parse(
8314
+ fs2.readFileSync(deployConfigPath, "utf-8")
8315
+ );
8316
+ return [
8317
+ { configPath: deployConfig.configPath },
8318
+ ...deployConfig.auxiliaryWorkers
8319
+ ].map(
8320
+ ({ configPath }) => path3.resolve(path3.dirname(deployConfigPath), configPath)
8321
+ );
8555
8322
  }
8556
- function moduleResolve(specifier, base, conditions, preserveSymlinks) {
8557
- const protocol = base.protocol;
8558
- const isData = protocol === "data:";
8559
- const isRemote = isData || protocol === "http:" || protocol === "https:";
8560
- let resolved;
8561
- if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
8562
- try {
8563
- resolved = new URL$1(specifier, base);
8564
- } catch (error_) {
8565
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8566
- error.cause = error_;
8567
- throw error;
8568
- }
8569
- } else if (protocol === "file:" && specifier[0] === "#") {
8570
- resolved = packageImportsResolve(specifier, base, conditions);
8323
+ function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
8324
+ return path3.relative(
8325
+ deployConfigDirectory,
8326
+ path3.resolve(root, outputDirectory, "wrangler.json")
8327
+ );
8328
+ }
8329
+ function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
8330
+ const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
8331
+ const deployConfigDirectory = path3.dirname(deployConfigPath);
8332
+ fs2.mkdirSync(deployConfigDirectory, { recursive: true });
8333
+ if (resolvedPluginConfig.type === "assets-only") {
8334
+ const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
8335
+ assert4(
8336
+ clientOutputDirectory,
8337
+ "Unexpected error: client environment output directory is undefined"
8338
+ );
8339
+ const deployConfig = {
8340
+ configPath: getRelativePathToWorkerConfig(
8341
+ deployConfigDirectory,
8342
+ resolvedViteConfig.root,
8343
+ clientOutputDirectory
8344
+ ),
8345
+ auxiliaryWorkers: []
8346
+ };
8347
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8571
8348
  } else {
8572
- try {
8573
- resolved = new URL$1(specifier);
8574
- } catch (error_) {
8575
- if (isRemote && !builtinModules.includes(specifier)) {
8576
- const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
8577
- error.cause = error_;
8578
- throw error;
8349
+ let entryWorkerConfigPath;
8350
+ const auxiliaryWorkers = [];
8351
+ for (const environmentName of Object.keys(resolvedPluginConfig.workers)) {
8352
+ const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
8353
+ assert4(
8354
+ outputDirectory,
8355
+ `Unexpected error: ${environmentName} environment output directory is undefined`
8356
+ );
8357
+ const configPath = getRelativePathToWorkerConfig(
8358
+ deployConfigDirectory,
8359
+ resolvedViteConfig.root,
8360
+ outputDirectory
8361
+ );
8362
+ if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) {
8363
+ entryWorkerConfigPath = configPath;
8364
+ } else {
8365
+ auxiliaryWorkers.push({ configPath });
8579
8366
  }
8580
- resolved = packageResolve(specifier, base, conditions);
8581
8367
  }
8368
+ assert4(
8369
+ entryWorkerConfigPath,
8370
+ `Unexpected error: entryWorkerConfigPath is undefined`
8371
+ );
8372
+ const deployConfig = {
8373
+ configPath: entryWorkerConfigPath,
8374
+ auxiliaryWorkers
8375
+ };
8376
+ fs2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
8582
8377
  }
8583
- assert5(resolved !== void 0, "expected to be defined");
8584
- if (resolved.protocol !== "file:") {
8585
- return resolved;
8586
- }
8587
- return finalizeResolution(resolved, base);
8588
8378
  }
8589
- function fileURLToPath2(id) {
8590
- if (typeof id === "string" && !id.startsWith("file://")) {
8591
- return normalizeSlash(id);
8379
+
8380
+ // src/dev.ts
8381
+ import assert5 from "node:assert";
8382
+ function getDevEntryWorker(resolvedPluginConfig, miniflare) {
8383
+ const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8384
+ assert5(entryWorkerConfig, "Unexpected error: No entry worker configuration");
8385
+ return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
8386
+ }
8387
+
8388
+ // src/miniflare-options.ts
8389
+ import assert6 from "node:assert";
8390
+ import * as fs3 from "node:fs";
8391
+ import * as fsp from "node:fs/promises";
8392
+ import * as path4 from "node:path";
8393
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
8394
+ import {
8395
+ kCurrentWorker,
8396
+ Log,
8397
+ LogLevel,
8398
+ Response as MiniflareResponse
8399
+ } from "miniflare";
8400
+ import { globSync } from "tinyglobby";
8401
+ import "vite";
8402
+ import {
8403
+ unstable_getMiniflareWorkerOptions,
8404
+ unstable_readConfig
8405
+ } from "wrangler";
8406
+ function getPersistence(root, persistState) {
8407
+ if (persistState === false) {
8408
+ return {};
8592
8409
  }
8593
- return normalizeSlash(fileURLToPath$1(id));
8410
+ const defaultPersistPath = ".wrangler/state";
8411
+ const persistPath = path4.resolve(
8412
+ root,
8413
+ typeof persistState === "object" ? persistState.path : defaultPersistPath,
8414
+ "v3"
8415
+ );
8416
+ return {
8417
+ cachePersist: path4.join(persistPath, "cache"),
8418
+ d1Persist: path4.join(persistPath, "d1"),
8419
+ durableObjectsPersist: path4.join(persistPath, "do"),
8420
+ kvPersist: path4.join(persistPath, "kv"),
8421
+ r2Persist: path4.join(persistPath, "r2"),
8422
+ workflowsPersist: path4.join(persistPath, "workflows")
8423
+ };
8594
8424
  }
8595
- function pathToFileURL(id) {
8596
- return pathToFileURL$1(fileURLToPath2(id)).toString();
8425
+ function missingWorkerErrorMessage(workerName) {
8426
+ return `${workerName} does not match a worker name.`;
8597
8427
  }
8598
- function normalizeid(id) {
8599
- if (typeof id !== "string") {
8600
- id = id.toString();
8601
- }
8602
- if (/(node|data|http|https|file):/.test(id)) {
8603
- return id;
8604
- }
8605
- if (BUILTIN_MODULES.has(id)) {
8606
- return "node:" + id;
8428
+ function getWorkerToWorkerEntrypointNamesMap(workers) {
8429
+ const workerToWorkerEntrypointNamesMap = new Map(
8430
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8431
+ );
8432
+ for (const worker of workers) {
8433
+ for (const value of Object.values(worker.serviceBindings ?? {})) {
8434
+ if (typeof value === "object" && "name" in value && value.entrypoint !== void 0 && value.entrypoint !== "default") {
8435
+ const targetWorkerName = value.name === kCurrentWorker ? worker.name : value.name;
8436
+ const entrypointNames = workerToWorkerEntrypointNamesMap.get(targetWorkerName);
8437
+ assert6(entrypointNames, missingWorkerErrorMessage(targetWorkerName));
8438
+ entrypointNames.add(value.entrypoint);
8439
+ }
8440
+ }
8607
8441
  }
8608
- return "file://" + encodeURI(normalizeSlash(id));
8442
+ return workerToWorkerEntrypointNamesMap;
8609
8443
  }
8610
- var DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
8611
- var DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
8612
- var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
8613
- "ERR_MODULE_NOT_FOUND",
8614
- "ERR_UNSUPPORTED_DIR_IMPORT",
8615
- "MODULE_NOT_FOUND",
8616
- "ERR_PACKAGE_PATH_NOT_EXPORTED"
8617
- ]);
8618
- function _tryModuleResolve(id, url, conditions) {
8619
- try {
8620
- return moduleResolve(id, url, conditions);
8621
- } catch (error) {
8622
- if (!NOT_FOUND_ERRORS.has(error?.code)) {
8623
- throw error;
8444
+ function getWorkerToDurableObjectClassNamesMap(workers) {
8445
+ const workerToDurableObjectClassNamesMap = new Map(
8446
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8447
+ );
8448
+ for (const worker of workers) {
8449
+ for (const value of Object.values(worker.durableObjects ?? {})) {
8450
+ if (typeof value === "string") {
8451
+ const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
8452
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8453
+ classNames.add(value);
8454
+ } else if (typeof value === "object") {
8455
+ if (value.scriptName) {
8456
+ const classNames = workerToDurableObjectClassNamesMap.get(
8457
+ value.scriptName
8458
+ );
8459
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8460
+ classNames.add(value.className);
8461
+ } else {
8462
+ const classNames = workerToDurableObjectClassNamesMap.get(
8463
+ worker.name
8464
+ );
8465
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8466
+ classNames.add(value.className);
8467
+ }
8468
+ }
8624
8469
  }
8625
8470
  }
8471
+ return workerToDurableObjectClassNamesMap;
8626
8472
  }
8627
- function _resolve(id, options = {}) {
8628
- if (typeof id !== "string") {
8629
- if (id instanceof URL) {
8630
- id = fileURLToPath2(id);
8631
- } else {
8632
- throw new TypeError("input must be a `string` or `URL`");
8473
+ function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
8474
+ const workerToWorkflowEntrypointClassNamesMap = new Map(
8475
+ workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
8476
+ );
8477
+ for (const worker of workers) {
8478
+ for (const value of Object.values(worker.workflows ?? {})) {
8479
+ if (value.scriptName) {
8480
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8481
+ value.scriptName
8482
+ );
8483
+ assert6(classNames, missingWorkerErrorMessage(value.scriptName));
8484
+ classNames.add(value.className);
8485
+ } else {
8486
+ const classNames = workerToWorkflowEntrypointClassNamesMap.get(
8487
+ worker.name
8488
+ );
8489
+ assert6(classNames, missingWorkerErrorMessage(worker.name));
8490
+ classNames.add(value.className);
8491
+ }
8633
8492
  }
8634
8493
  }
8635
- if (/(node|data|http|https):/.test(id)) {
8636
- return id;
8637
- }
8638
- if (BUILTIN_MODULES.has(id)) {
8639
- return "node:" + id;
8640
- }
8641
- if (id.startsWith("file://")) {
8642
- id = fileURLToPath2(id);
8494
+ return workerToWorkflowEntrypointClassNamesMap;
8495
+ }
8496
+ var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
8497
+ var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
8498
+ var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
8499
+ var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
8500
+ var RUNNER_PATH = "./runner-worker/index.js";
8501
+ function getEntryWorkerConfig(resolvedPluginConfig) {
8502
+ if (resolvedPluginConfig.type === "assets-only") {
8503
+ return;
8643
8504
  }
8644
- if (isAbsolute(id)) {
8645
- try {
8646
- const stat = statSync2(id);
8647
- if (stat.isFile()) {
8648
- return pathToFileURL(id);
8505
+ return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
8506
+ }
8507
+ function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
8508
+ const resolvedViteConfig = viteDevServer.config;
8509
+ const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
8510
+ const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
8511
+ const assetWorkers = [
8512
+ {
8513
+ name: ROUTER_WORKER_NAME,
8514
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8515
+ modulesRoot: miniflareModulesRoot,
8516
+ modules: [
8517
+ {
8518
+ type: "ESModule",
8519
+ path: path4.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
8520
+ contents: fs3.readFileSync(
8521
+ fileURLToPath2(new URL(ROUTER_WORKER_PATH, import.meta.url))
8522
+ )
8523
+ }
8524
+ ],
8525
+ bindings: {
8526
+ CONFIG: {
8527
+ has_user_worker: resolvedPluginConfig.type === "workers"
8528
+ }
8529
+ },
8530
+ serviceBindings: {
8531
+ ASSET_WORKER: ASSET_WORKER_NAME,
8532
+ ...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
8649
8533
  }
8650
- } catch (error) {
8651
- if (error?.code !== "ENOENT") {
8652
- throw error;
8534
+ },
8535
+ {
8536
+ name: ASSET_WORKER_NAME,
8537
+ compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
8538
+ modulesRoot: miniflareModulesRoot,
8539
+ modules: [
8540
+ {
8541
+ type: "ESModule",
8542
+ path: path4.join(miniflareModulesRoot, ASSET_WORKER_PATH),
8543
+ contents: fs3.readFileSync(
8544
+ fileURLToPath2(new URL(ASSET_WORKER_PATH, import.meta.url))
8545
+ )
8546
+ }
8547
+ ],
8548
+ bindings: {
8549
+ CONFIG: {
8550
+ ...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
8551
+ ...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
8552
+ }
8553
+ },
8554
+ serviceBindings: {
8555
+ __VITE_ASSET_EXISTS__: async (request) => {
8556
+ const { pathname } = new URL(request.url);
8557
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8558
+ let exists;
8559
+ try {
8560
+ exists = fs3.statSync(filePath).isFile();
8561
+ } catch (error) {
8562
+ exists = false;
8563
+ }
8564
+ return MiniflareResponse.json(exists);
8565
+ },
8566
+ __VITE_FETCH_ASSET__: async (request) => {
8567
+ const { pathname } = new URL(request.url);
8568
+ const filePath = path4.join(resolvedViteConfig.root, pathname);
8569
+ try {
8570
+ let html = await fsp.readFile(filePath, "utf-8");
8571
+ html = await viteDevServer.transformIndexHtml(pathname, html);
8572
+ return new MiniflareResponse(html, {
8573
+ headers: { "Content-Type": "text/html" }
8574
+ });
8575
+ } catch (error) {
8576
+ throw new Error(`Unexpected error. Failed to load ${pathname}`);
8577
+ }
8578
+ }
8653
8579
  }
8654
8580
  }
8655
- }
8656
- const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
8657
- const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
8658
- if (_urls.length === 0) {
8659
- _urls.push(new URL(pathToFileURL(process.cwd())));
8660
- }
8661
- const urls = [..._urls];
8662
- for (const url of _urls) {
8663
- if (url.protocol === "file:") {
8664
- urls.push(
8665
- new URL("./", url),
8666
- // If url is directory
8667
- new URL(joinURL(url.pathname, "_index.js"), url),
8668
- // TODO: Remove in next major version?
8669
- new URL("node_modules", url)
8581
+ ];
8582
+ const workersFromConfig = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
8583
+ ([environmentName, workerConfig]) => {
8584
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(
8585
+ {
8586
+ ...workerConfig,
8587
+ assets: void 0
8588
+ },
8589
+ resolvedPluginConfig.cloudflareEnv
8670
8590
  );
8591
+ const { externalWorkers: externalWorkers2 } = miniflareWorkerOptions;
8592
+ const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8593
+ return {
8594
+ externalWorkers: externalWorkers2,
8595
+ worker: {
8596
+ ...workerOptions,
8597
+ name: workerOptions.name ?? workerConfig.name,
8598
+ modulesRoot: miniflareModulesRoot,
8599
+ unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
8600
+ serviceBindings: {
8601
+ ...workerOptions.serviceBindings,
8602
+ ...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
8603
+ [workerConfig.assets.binding]: ASSET_WORKER_NAME
8604
+ } : {},
8605
+ __VITE_INVOKE_MODULE__: async (request) => {
8606
+ const payload = await request.json();
8607
+ const invokePayloadData = payload.data;
8608
+ assert6(
8609
+ invokePayloadData.name === "fetchModule",
8610
+ `Invalid invoke event: ${invokePayloadData.name}`
8611
+ );
8612
+ const [moduleId] = invokePayloadData.data;
8613
+ const moduleRE = new RegExp(MODULE_PATTERN);
8614
+ const shouldExternalize = (
8615
+ // Worker modules (CompiledWasm, Text, Data)
8616
+ moduleRE.test(moduleId)
8617
+ );
8618
+ if (shouldExternalize) {
8619
+ const result2 = {
8620
+ externalize: moduleId,
8621
+ type: "module"
8622
+ };
8623
+ return MiniflareResponse.json({ result: result2 });
8624
+ }
8625
+ const devEnvironment = viteDevServer.environments[environmentName];
8626
+ const result = await devEnvironment.hot.handleInvoke(payload);
8627
+ return MiniflareResponse.json(result);
8628
+ }
8629
+ }
8630
+ }
8631
+ };
8671
8632
  }
8672
- }
8673
- let resolved;
8674
- for (const url of urls) {
8675
- resolved = _tryModuleResolve(id, url, conditionsSet);
8676
- if (resolved) {
8677
- break;
8678
- }
8679
- for (const prefix of ["", "/index"]) {
8680
- for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
8681
- resolved = _tryModuleResolve(
8682
- joinURL(id, prefix) + extension,
8683
- url,
8684
- conditionsSet
8633
+ ) : [];
8634
+ const userWorkers = workersFromConfig.map((options) => options.worker);
8635
+ const externalWorkers = workersFromConfig.flatMap(
8636
+ (options) => options.externalWorkers
8637
+ );
8638
+ const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
8639
+ const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
8640
+ const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
8641
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8642
+ return {
8643
+ log: logger,
8644
+ handleRuntimeStdio(stdout, stderr) {
8645
+ const decoder = new TextDecoder();
8646
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8647
+ stderr.forEach(
8648
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8649
+ );
8650
+ },
8651
+ ...getPersistence(
8652
+ resolvedViteConfig.root,
8653
+ resolvedPluginConfig.persistState
8654
+ ),
8655
+ workers: [
8656
+ ...assetWorkers,
8657
+ ...externalWorkers,
8658
+ ...userWorkers.map((workerOptions) => {
8659
+ const wrappers = [
8660
+ `import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
8661
+ `export default createWorkerEntrypointWrapper('default');`
8662
+ ];
8663
+ const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
8664
+ workerOptions.name
8685
8665
  );
8686
- if (resolved) {
8687
- break;
8666
+ assert6(
8667
+ workerEntrypointNames,
8668
+ `WorkerEntrypoint names not found for worker ${workerOptions.name}`
8669
+ );
8670
+ for (const entrypointName of [...workerEntrypointNames].sort()) {
8671
+ wrappers.push(
8672
+ `export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
8673
+ );
8688
8674
  }
8675
+ const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
8676
+ workerOptions.name
8677
+ );
8678
+ assert6(
8679
+ durableObjectClassNames,
8680
+ `DurableObject class names not found for worker ${workerOptions.name}`
8681
+ );
8682
+ for (const className of [...durableObjectClassNames].sort()) {
8683
+ wrappers.push(
8684
+ `export const ${className} = createDurableObjectWrapper('${className}');`
8685
+ );
8686
+ }
8687
+ const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
8688
+ assert6(
8689
+ workflowEntrypointClassNames,
8690
+ `WorkflowEntrypoint class names not found for worker: ${workerOptions.name}`
8691
+ );
8692
+ for (const className of [...workflowEntrypointClassNames].sort()) {
8693
+ wrappers.push(
8694
+ `export const ${className} = createWorkflowEntrypointWrapper('${className}');`
8695
+ );
8696
+ }
8697
+ return {
8698
+ ...workerOptions,
8699
+ modules: [
8700
+ {
8701
+ type: "ESModule",
8702
+ path: path4.join(miniflareModulesRoot, WRAPPER_PATH),
8703
+ contents: wrappers.join("\n")
8704
+ },
8705
+ {
8706
+ type: "ESModule",
8707
+ path: path4.join(miniflareModulesRoot, RUNNER_PATH),
8708
+ contents: fs3.readFileSync(
8709
+ fileURLToPath2(new URL(RUNNER_PATH, import.meta.url))
8710
+ )
8711
+ }
8712
+ ],
8713
+ unsafeUseModuleFallbackService: true
8714
+ };
8715
+ })
8716
+ ],
8717
+ unsafeModuleFallbackService(request) {
8718
+ const url = new URL(request.url);
8719
+ const rawSpecifier = url.searchParams.get("rawSpecifier");
8720
+ assert6(
8721
+ rawSpecifier,
8722
+ `Unexpected error: no specifier in request to module fallback service.`
8723
+ );
8724
+ const moduleRE = new RegExp(MODULE_PATTERN);
8725
+ const match = moduleRE.exec(rawSpecifier);
8726
+ assert6(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
8727
+ const [full, moduleType, modulePath] = match;
8728
+ assert6(
8729
+ modulePath,
8730
+ `Unexpected error: module path not found in reference: ${full}.`
8731
+ );
8732
+ let source;
8733
+ try {
8734
+ source = fs3.readFileSync(modulePath);
8735
+ } catch (error) {
8736
+ throw new Error(
8737
+ `Import "${modulePath}" not found. Does the file exist?`
8738
+ );
8689
8739
  }
8690
- if (resolved) {
8691
- break;
8692
- }
8693
- }
8694
- if (resolved) {
8695
- break;
8740
+ return MiniflareResponse.json({
8741
+ // Cap'n Proto expects byte arrays for `:Data` typed fields from JSON
8742
+ wasm: Array.from(source)
8743
+ });
8696
8744
  }
8697
- }
8698
- if (!resolved) {
8699
- const error = new Error(
8700
- `Cannot find module ${id} imported from ${urls.join(", ")}`
8701
- );
8702
- error.code = "ERR_MODULE_NOT_FOUND";
8703
- throw error;
8704
- }
8705
- return pathToFileURL(resolved);
8706
- }
8707
- function resolveSync(id, options) {
8708
- return _resolve(id, options);
8709
- }
8710
- function resolvePathSync(id, options) {
8711
- return fileURLToPath2(resolveSync(id, options));
8745
+ };
8712
8746
  }
8713
-
8714
- // src/node-js-compat.ts
8715
- import { defineEnv } from "unenv";
8716
- var { env } = defineEnv({
8717
- nodeCompat: true,
8718
- presets: [cloudflare]
8719
- });
8720
- var nodeCompatExternals = new Set(env.external);
8721
- var nodeCompatEntries = getNodeCompatEntries();
8722
- function isNodeCompat(workerConfig) {
8723
- if (workerConfig === void 0) {
8724
- return false;
8725
- }
8726
- const nodeCompatMode = getNodeCompat(
8727
- workerConfig.compatibility_date,
8728
- workerConfig.compatibility_flags ?? []
8729
- ).mode;
8730
- if (nodeCompatMode === "v2") {
8731
- return true;
8732
- }
8733
- if (nodeCompatMode === "legacy") {
8734
- throw new Error(
8735
- "Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
8736
- );
8737
- }
8738
- if (nodeCompatMode === "v1") {
8739
- throw new Error(
8740
- `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`
8741
- );
8742
- }
8743
- return false;
8747
+ function getPreviewModules(main, modulesRules) {
8748
+ assert6(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
8749
+ const rootPath = path4.dirname(main);
8750
+ const entryPath = path4.basename(main);
8751
+ return {
8752
+ rootPath,
8753
+ modules: [
8754
+ {
8755
+ type: "ESModule",
8756
+ path: entryPath
8757
+ },
8758
+ ...modulesRules.flatMap(
8759
+ ({ type, include }) => globSync(include, { cwd: rootPath, ignore: entryPath }).map((path8) => ({
8760
+ type,
8761
+ path: path8
8762
+ }))
8763
+ )
8764
+ ]
8765
+ };
8744
8766
  }
8745
- function injectGlobalCode(id, code) {
8746
- const injectedCode = Object.entries(env.inject).map(([globalName, globalInject]) => {
8747
- if (typeof globalInject === "string") {
8748
- const moduleSpecifier2 = globalInject;
8749
- return `import var_${globalName} from "${moduleSpecifier2}";
8750
- globalThis.${globalName} = var_${globalName};
8751
- `;
8752
- }
8753
- const [moduleSpecifier, exportName] = globalInject;
8754
- assert6(
8755
- moduleSpecifier !== void 0,
8756
- "Expected moduleSpecifier to be defined"
8757
- );
8758
- assert6(exportName !== void 0, "Expected exportName to be defined");
8759
- return `import var_${globalName} from "${moduleSpecifier}";
8760
- globalThis.${globalName} = var_${globalName}.${exportName};
8761
- `;
8762
- }).join("\n");
8763
- const modified = new MagicString(code);
8764
- modified.prepend(injectedCode);
8767
+ function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
8768
+ const resolvedViteConfig = vitePreviewServer.config;
8769
+ const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
8770
+ const workerConfigs = configPaths.map(
8771
+ (configPath) => unstable_readConfig({ config: configPath })
8772
+ );
8773
+ const workers = workerConfigs.flatMap((config) => {
8774
+ const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
8775
+ const { externalWorkers } = miniflareWorkerOptions;
8776
+ const { ratelimits, modulesRules, ...workerOptions } = miniflareWorkerOptions.workerOptions;
8777
+ return [
8778
+ {
8779
+ ...workerOptions,
8780
+ name: workerOptions.name ?? config.name,
8781
+ ...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : { modules: true, script: "" }
8782
+ },
8783
+ ...externalWorkers
8784
+ ];
8785
+ });
8786
+ const logger = new ViteMiniflareLogger(resolvedViteConfig);
8765
8787
  return {
8766
- code: modified.toString(),
8767
- map: modified.generateMap({ hires: "boundary", source: id })
8788
+ log: logger,
8789
+ handleRuntimeStdio(stdout, stderr) {
8790
+ const decoder = new TextDecoder();
8791
+ stdout.forEach((data2) => logger.info(decoder.decode(data2)));
8792
+ stderr.forEach(
8793
+ (error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
8794
+ );
8795
+ },
8796
+ ...getPersistence(resolvedViteConfig.root, persistState),
8797
+ workers
8768
8798
  };
8769
8799
  }
8770
- function resolveNodeJSImport(source) {
8771
- const alias = env.alias[source];
8772
- if (alias) {
8773
- return {
8774
- unresolved: alias,
8775
- resolved: resolvePathSync(alias, { url: import.meta.url })
8776
- };
8777
- }
8778
- if (nodeCompatEntries.has(source)) {
8779
- return {
8780
- unresolved: source,
8781
- resolved: resolvePathSync(source, { url: import.meta.url })
8782
- };
8800
+ var ViteMiniflareLogger = class extends Log {
8801
+ logger;
8802
+ constructor(config) {
8803
+ super(miniflareLogLevelFromViteLogLevel(config.logLevel));
8804
+ this.logger = config.logger;
8783
8805
  }
8784
- }
8785
- function getNodeCompatEntries() {
8786
- const entries = new Set(Object.values(env.alias));
8787
- for (const globalInject of Object.values(env.inject)) {
8788
- if (typeof globalInject === "string") {
8789
- entries.add(globalInject);
8790
- } else {
8791
- assert6(
8792
- globalInject[0] !== void 0,
8793
- "Expected first element of globalInject to be defined"
8794
- );
8795
- entries.add(globalInject[0]);
8806
+ logWithLevel(level, message) {
8807
+ if (/^Ready on http/.test(message)) {
8808
+ level = LogLevel.DEBUG;
8809
+ }
8810
+ switch (level) {
8811
+ case LogLevel.ERROR:
8812
+ return this.logger.error(message);
8813
+ case LogLevel.WARN:
8814
+ return this.logger.warn(message);
8815
+ case LogLevel.INFO:
8816
+ return this.logger.info(message);
8796
8817
  }
8797
8818
  }
8798
- nodeCompatExternals.forEach((external) => entries.delete(external));
8799
- return entries;
8819
+ };
8820
+ function miniflareLogLevelFromViteLogLevel(level = "info") {
8821
+ switch (level) {
8822
+ case "error":
8823
+ return LogLevel.ERROR;
8824
+ case "warn":
8825
+ return LogLevel.WARN;
8826
+ case "info":
8827
+ return LogLevel.INFO;
8828
+ case "silent":
8829
+ return LogLevel.NONE;
8830
+ }
8800
8831
  }
8801
8832
 
8802
8833
  // src/plugin-config.ts
@@ -8841,7 +8872,6 @@ var nonApplicableWorkerConfigs = {
8841
8872
  "build",
8842
8873
  "find_additional_modules",
8843
8874
  "no_bundle",
8844
- "node_compat",
8845
8875
  "preserve_file_names",
8846
8876
  "site",
8847
8877
  "tsconfig",
@@ -8858,7 +8888,6 @@ var nullableNonApplicable = [
8858
8888
  "find_additional_modules",
8859
8889
  "minify",
8860
8890
  "no_bundle",
8861
- "node_compat",
8862
8891
  "preserve_file_names",
8863
8892
  "site",
8864
8893
  "tsconfig",
@@ -9009,6 +9038,17 @@ function getWorkerConfig(configPath, env2, opts) {
9009
9038
  };
9010
9039
  }
9011
9040
  assert7(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
9041
+ const mainStat = fs4.statSync(config.main, { throwIfNoEntry: false });
9042
+ if (!mainStat) {
9043
+ throw new Error(
9044
+ `The provided Wrangler config main field (${config.main}) doesn't point to an existing file`
9045
+ );
9046
+ }
9047
+ if (mainStat.isDirectory()) {
9048
+ throw new Error(
9049
+ `The provided Wrangler config main field (${config.main}) points to a directory, it needs to point to a file instead`
9050
+ );
9051
+ }
9012
9052
  return {
9013
9053
  type: "worker",
9014
9054
  raw,
@@ -9109,8 +9149,9 @@ function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
9109
9149
  }
9110
9150
 
9111
9151
  // src/websockets.ts
9152
+ import { coupleWebSocket } from "miniflare";
9112
9153
  import { WebSocketServer } from "ws";
9113
- function handleWebSocket(httpServer, fetcher, logger) {
9154
+ function handleWebSocket(httpServer, fetcher) {
9114
9155
  const nodeWebSocket = new WebSocketServer({ noServer: true });
9115
9156
  httpServer.on(
9116
9157
  "upgrade",
@@ -9134,34 +9175,7 @@ function handleWebSocket(httpServer, fetcher, logger) {
9134
9175
  socket,
9135
9176
  head,
9136
9177
  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
- });
9178
+ coupleWebSocket(clientWebSocket, workerWebSocket);
9165
9179
  nodeWebSocket.emit("connection", clientWebSocket, request);
9166
9180
  }
9167
9181
  );
@@ -9307,7 +9321,7 @@ function cloudflare2(pluginConfig = {}) {
9307
9321
  return;
9308
9322
  }
9309
9323
  config.no_bundle = true;
9310
- config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
9324
+ config.rules = [{ type: "ESModule", globs: ["**/*.js", "**/*.mjs"] }];
9311
9325
  if (config.unsafe && Object.keys(config.unsafe).length === 0) {
9312
9326
  config.unsafe = void 0;
9313
9327
  }
@@ -9354,11 +9368,7 @@ function cloudflare2(pluginConfig = {}) {
9354
9368
  },
9355
9369
  { alwaysCallNext: false }
9356
9370
  );
9357
- handleWebSocket(
9358
- viteDevServer.httpServer,
9359
- entryWorker.fetch,
9360
- viteDevServer.config.logger
9361
- );
9371
+ handleWebSocket(viteDevServer.httpServer, entryWorker.fetch);
9362
9372
  return () => {
9363
9373
  viteDevServer.middlewares.use((req, res, next) => {
9364
9374
  middleware(req, res, next);
@@ -9380,16 +9390,10 @@ function cloudflare2(pluginConfig = {}) {
9380
9390
  },
9381
9391
  { alwaysCallNext: false }
9382
9392
  );
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
- };
9393
+ handleWebSocket(vitePreviewServer.httpServer, miniflare2.dispatchFetch);
9394
+ vitePreviewServer.middlewares.use((req, res, next) => {
9395
+ middleware(req, res, next);
9396
+ });
9393
9397
  }
9394
9398
  },
9395
9399
  // Plugin to support `CompiledWasm` modules