devflare 1.0.0-next.65 → 1.0.0-next.66

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.
Files changed (94) hide show
  1. package/README.md +2 -1
  2. package/dist/_chunks/{account-Cflj6rw3.js → account-BHY3fvrA.js} +6 -6
  3. package/dist/_chunks/{account-resources-CsmVowJp.js → account-resources-BdKj8q1h.js} +3 -3
  4. package/dist/_chunks/{ai-CBEuLdoP.js → ai-CN_SREim.js} +1 -1
  5. package/dist/_chunks/{build-BZ6lIG7n.js → build-DCgW1i8g.js} +2 -2
  6. package/dist/_chunks/{build-artifacts-CXLdD1PE.js → build-artifacts-Btqs5gPy.js} +12 -12
  7. package/dist/_chunks/{cli-z3FJ-9cO.js → cli-CWKMIIcG.js} +63 -20
  8. package/dist/_chunks/{cloudflare-BaloqI3H.js → cloudflare-Ic5ubQza.js} +6 -6
  9. package/dist/_chunks/{command-utils-CSnoFdxM.js → command-utils-DjaaMQX7.js} +2 -2
  10. package/dist/_chunks/{compiler-CgIFPfRA.js → compiler-UxXQgEPq.js} +3 -3
  11. package/dist/_chunks/{config-path-C3ac6r66.js → config-path-CYGlwKDs.js} +2 -2
  12. package/dist/_chunks/{config-BwRb2_vD.js → config-zQd4jmXU.js} +3 -3
  13. package/dist/_chunks/{deploy-CujD7j-R.js → deploy-DqYme109.js} +13 -13
  14. package/dist/_chunks/dev-DOoDj7SJ.js +757 -0
  15. package/dist/_chunks/{doctor-n_eqvv52.js → doctor-CAsJ-rSZ.js} +7 -7
  16. package/dist/_chunks/{env-_QKteEYJ.js → env-DyL6JOXI.js} +1 -1
  17. package/dist/_chunks/{family-D3SV6I0N.js → family-BTTpTwUk.js} +1 -1
  18. package/dist/_chunks/{init-DnkJOmpW.js → init-DJ5y3mu5.js} +3 -3
  19. package/dist/_chunks/{loader-E_UGyTrJ.js → loader-BC0skbnH.js} +5 -5
  20. package/dist/_chunks/{local-secrets-6sMstHXw.js → local-secrets-C0n5oRgI.js} +1 -1
  21. package/dist/_chunks/{login-D9-EwpSA.js → login-CgNcbpEq.js} +4 -4
  22. package/dist/_chunks/{preferences-BKp_7XJx.js → preferences-CbYERA_m.js} +1 -1
  23. package/dist/_chunks/{preview-registry-ClAbLTHH.js → preview-registry-CTXU4mBc.js} +2 -2
  24. package/dist/_chunks/{preview-resources-D_aFwtZR.js → preview-resources-CQIu2-NY.js} +5 -5
  25. package/dist/_chunks/{previews-D-GPVCeq.js → previews-BIaw6NVC.js} +10 -10
  26. package/dist/_chunks/{productions-me2YvmWK.js → productions-CF8oQcX7.js} +7 -7
  27. package/dist/_chunks/{r2-presign-runtime-zTOLS0Ea.js → r2-presign-runtime-C75FkLMd.js} +4 -4
  28. package/dist/_chunks/{remote-CZnP-HLJ.js → remote-8jEHLVGg.js} +2 -2
  29. package/dist/_chunks/{resolve-package-qizBfCIm.js → resolve-package-DeJUGxoE.js} +1 -1
  30. package/dist/_chunks/{routes-BMU7ga_l.js → routes-CRXB3-iw.js} +6 -6
  31. package/dist/_chunks/{runtime-Ckf-KKc7.js → runtime-CuMe2D6n.js} +1 -1
  32. package/dist/_chunks/{secrets-CxVCXmdh.js → secrets-BJuEa9Jz.js} +1 -1
  33. package/dist/_chunks/{tail-aMFzd-2K.js → tail-DjGRt8gw.js} +4 -4
  34. package/dist/_chunks/{token-Dmi0KXyX.js → token-wmeF8-IQ.js} +4 -4
  35. package/dist/_chunks/{tokens-iVcgNXi-.js → tokens-KaEr4B8e.js} +1 -1
  36. package/dist/_chunks/{types-ByjwxoVA.js → types-BLGfxIq-.js} +9 -9
  37. package/dist/_chunks/{ui-BUoZApvE.js → ui-BhCdDC2N.js} +1 -1
  38. package/dist/_chunks/{usage-BBTGzjon.js → usage-rRusKejc.js} +2 -2
  39. package/dist/_chunks/{vite-BBiqD3k7.js → vite-Dxuhm1BP.js} +11 -11
  40. package/dist/_chunks/{dev-C7Z23WNH.js → vite-process-BxZ8pb7i.js} +24 -765
  41. package/dist/_chunks/{worker-CtTVZeTH.js → worker-DgczaXVW.js} +6 -6
  42. package/dist/_chunks/workspace-CaTsTpDI.js +506 -0
  43. package/dist/_chunks/workspace-Ds3xMjOE.js +175 -0
  44. package/dist/browser.js +4 -4
  45. package/dist/cli/commands/workspace.d.ts +8 -0
  46. package/dist/cli/commands/workspace.d.ts.map +1 -0
  47. package/dist/cli/help-pages/pages/core.d.ts +1 -1
  48. package/dist/cli/help-pages/pages/core.d.ts.map +1 -1
  49. package/dist/cli/help-pages/shared.d.ts +1 -1
  50. package/dist/cli/help-pages/shared.d.ts.map +1 -1
  51. package/dist/cli/index.d.ts.map +1 -1
  52. package/dist/cli/index.js +1 -1
  53. package/dist/cloudflare/index.js +3 -3
  54. package/dist/config/index.d.ts +1 -0
  55. package/dist/config/index.d.ts.map +1 -1
  56. package/dist/config/workspace.d.ts +282 -0
  57. package/dist/config/workspace.d.ts.map +1 -0
  58. package/dist/config-entry.js +1 -1
  59. package/dist/decorators/index.js +1 -1
  60. package/dist/dev-server/miniflare-dev-config.d.ts +8 -0
  61. package/dist/dev-server/miniflare-dev-config.d.ts.map +1 -1
  62. package/dist/dev-server/workspace/merge-config.d.ts +81 -0
  63. package/dist/dev-server/workspace/merge-config.d.ts.map +1 -0
  64. package/dist/dev-server/workspace/prepare-app.d.ts +84 -0
  65. package/dist/dev-server/workspace/prepare-app.d.ts.map +1 -0
  66. package/dist/dev-server/workspace/server.d.ts +47 -0
  67. package/dist/dev-server/workspace/server.d.ts.map +1 -0
  68. package/dist/index.d.ts +1 -1
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +9 -8
  71. package/dist/runtime/index.js +3 -3
  72. package/dist/sveltekit/index.js +6 -6
  73. package/dist/test/index.js +17 -17
  74. package/dist/vite/index.js +1 -1
  75. package/package.json +1 -1
  76. package/dist/_chunks/{api-TzdliH-6.js → api-BKClUlUf.js} +0 -0
  77. package/dist/_chunks/{colors-DiK6wPJ5.js → colors-D0NVzAFN.js} +0 -0
  78. package/dist/_chunks/{context-CQkLyah9.js → context-ZQydom21.js} +0 -0
  79. package/dist/_chunks/{decorators-QmV57ixr.js → decorators-eXNZ1S0N.js} +0 -0
  80. package/dist/_chunks/{dependencies-C2oxFjU_.js → dependencies-wKqrxKV_.js} +0 -0
  81. package/dist/_chunks/{durable-object-DMtH0XYX.js → durable-object-DuMPM8re.js} +0 -0
  82. package/dist/_chunks/{generated-artifacts-dMJY4KAt.js → generated-artifacts-Bb13pGUG.js} +0 -0
  83. package/dist/_chunks/{glob-CmQOvunB.js → glob-DRw9sbfF.js} +0 -0
  84. package/dist/_chunks/{local-dev-vars-CTSa-wvF.js → local-dev-vars-BFLS-HoI.js} +1 -1
  85. package/dist/_chunks/{local-hyperdrive-CJ90j46O.js → local-hyperdrive-CcORzo76.js} +0 -0
  86. package/dist/_chunks/{local-media-bindings-DsAW4AMF.js → local-media-bindings-ZQe-epuw.js} +0 -0
  87. package/dist/_chunks/{package-metadata-DjHBLB-z.js → package-metadata-CLI488gB.js} +1 -1
  88. package/dist/_chunks/{preview-C3Cdr8an.js → preview-j9Kbx4-G.js} +1 -1
  89. /package/dist/_chunks/{remote-config-D39BY9ji.js → remote-config-Bw6qIVM4.js} +0 -0
  90. /package/dist/_chunks/{schema-normalization-Zgm4W6O6.js → schema-normalization-CTdiY17P.js} +0 -0
  91. /package/dist/_chunks/{vite-utils-OVLMV605.js → vite-utils-D8kPPxUy.js} +0 -0
  92. /package/dist/_chunks/{worker-bundler-dTTnYU3n.js → worker-bundler-Isj5jiW6.js} +0 -0
  93. /package/dist/_chunks/{worker-entrypoint-CQW77lG8.js → worker-entrypoint-C8j23t6d.js} +0 -0
  94. /package/dist/_chunks/{workerName-CFJsLZA-.js → workerName-kEXwmV2m.js} +0 -0
@@ -1,27 +1,21 @@
1
- import { c as getDevflareDotenvPaths, d as resolveConfigEnvVars, o as EnvVarResolutionError } from "./preview-C3Cdr8an.js";
2
- import { i as resolveConfigPath, r as loadConfig } from "./loader-E_UGyTrJ.js";
3
- import { g as normalizeR2Binding, n as getLocalKVNamespaceIdentifier, r as getSingleBrowserBindingName, t as getLocalD1DatabaseIdentifier } from "./schema-normalization-Zgm4W6O6.js";
4
- import { t as applyLocalDevVarsToConfig } from "./local-dev-vars-CTSa-wvF.js";
5
- import { a as cyanBold, f as logLine, g as yellow, o as dim, r as createCliTheme } from "./ui-BUoZApvE.js";
6
- import { clearLocalSendEmailBindings, setLocalSendEmailBindings } from "../utils/send-email.js";
7
- import { C as buildSendEmailConfig, D as buildVersionMetadataConfig, E as buildTailConsumersConfig, O as buildWorkerLoadersConfig, S as buildSecretsStoreConfig, T as buildStreamingTailConsumersConfig, _ as buildMtlsCertificatesConfig, b as buildQueueProducers, c as buildAiSearchInstancesConfig, d as buildArtifactsConfig, f as buildDispatchNamespacesConfig, g as buildMediaConfig, h as buildImagesConfig, k as buildWorkflowsConfig, l as buildAiSearchNamespacesConfig, m as buildHyperdrivesConfig, n as getRouteDirectoryCandidate, p as buildFlagshipConfig, s as resolveServiceBindings, t as discoverRoutes, u as buildAnalyticsEngineConfig, v as buildPipelinesConfig, w as buildStreamConfig, x as buildRateLimitsConfig, y as buildQueueConsumers } from "./routes-BMU7ga_l.js";
8
- import { r as transformDurableObject } from "./durable-object-DMtH0XYX.js";
9
- import { i as findFiles } from "./glob-CmQOvunB.js";
10
- import { d as DEFAULT_FETCH_ENTRY_FILES, f as DEFAULT_QUEUE_ENTRY_FILES, g as discoverDurableObjectFiles, h as resolveWorkerSurfacePaths, i as writeGeneratedViteConfig, l as prepareComposedWorkerEntrypoint, m as hasWorkerSurfacePaths, n as resolveEffectiveViteProject, p as DEFAULT_SCHEDULED_ENTRY_FILES, u as DEFAULT_EMAIL_ENTRY_FILES } from "./vite-BBiqD3k7.js";
11
- import { a as createWorkerdBundlerDefaults, i as writeWorkerCompatibleBundle, n as ensureDebugShim, r as resolveWorkerCompatibleRolldownConfig, t as bundleWorkerEntry } from "./worker-bundler-dTTnYU3n.js";
12
- import { n as bundleWorkflowEntrypointScript, t as R2_PRESIGN_RUNTIME_JS } from "./r2-presign-runtime-zTOLS0Ea.js";
13
- import { n as buildLocalSecretWrappedBindingConfig } from "./local-secrets-6sMstHXw.js";
14
- import { t as buildLocalBindingShimServiceConfig } from "./local-media-bindings-DsAW4AMF.js";
15
- import { i as waitForViteReady, n as resolveViteMode, r as stopSpawnedProcessTree, t as detectViteProject } from "./vite-utils-OVLMV605.js";
1
+ import { i as resolveConfigPath } from "./loader-BC0skbnH.js";
2
+ import { g as normalizeR2Binding, n as getLocalKVNamespaceIdentifier, r as getSingleBrowserBindingName, t as getLocalD1DatabaseIdentifier } from "./schema-normalization-CTdiY17P.js";
3
+ import { C as buildSendEmailConfig, D as buildVersionMetadataConfig, E as buildTailConsumersConfig, O as buildWorkerLoadersConfig, S as buildSecretsStoreConfig, T as buildStreamingTailConsumersConfig, _ as buildMtlsCertificatesConfig, b as buildQueueProducers, c as buildAiSearchInstancesConfig, d as buildArtifactsConfig, f as buildDispatchNamespacesConfig, g as buildMediaConfig, h as buildImagesConfig, k as buildWorkflowsConfig, l as buildAiSearchNamespacesConfig, m as buildHyperdrivesConfig, n as getRouteDirectoryCandidate, p as buildFlagshipConfig, u as buildAnalyticsEngineConfig, v as buildPipelinesConfig, w as buildStreamConfig, x as buildRateLimitsConfig, y as buildQueueConsumers } from "./routes-CRXB3-iw.js";
4
+ import { r as transformDurableObject } from "./durable-object-DuMPM8re.js";
5
+ import { i as findFiles } from "./glob-DRw9sbfF.js";
6
+ import { d as DEFAULT_FETCH_ENTRY_FILES, f as DEFAULT_QUEUE_ENTRY_FILES, g as discoverDurableObjectFiles, h as resolveWorkerSurfacePaths, i as writeGeneratedViteConfig, m as hasWorkerSurfacePaths, p as DEFAULT_SCHEDULED_ENTRY_FILES, u as DEFAULT_EMAIL_ENTRY_FILES } from "./vite-Dxuhm1BP.js";
7
+ import { a as createWorkerdBundlerDefaults, i as writeWorkerCompatibleBundle, n as ensureDebugShim, r as resolveWorkerCompatibleRolldownConfig } from "./worker-bundler-Isj5jiW6.js";
8
+ import { t as R2_PRESIGN_RUNTIME_JS } from "./r2-presign-runtime-C75FkLMd.js";
9
+ import { n as buildLocalSecretWrappedBindingConfig } from "./local-secrets-C0n5oRgI.js";
10
+ import { t as buildLocalBindingShimServiceConfig } from "./local-media-bindings-ZQe-epuw.js";
11
+ import { i as waitForViteReady, n as resolveViteMode } from "./vite-utils-D8kPPxUy.js";
16
12
  import { existsSync } from "node:fs";
17
13
  import { dirname, relative, resolve } from "pathe";
18
- import { exec, spawn } from "node:child_process";
14
+ import { spawn } from "node:child_process";
19
15
  import { homedir } from "node:os";
20
16
  import { join as join$1 } from "node:path";
21
- import { createConsola } from "consola";
22
17
  import picomatch from "picomatch";
23
18
  import { createHash } from "node:crypto";
24
- import { promisify } from "node:util";
25
19
  import { createInterface } from "node:readline";
26
20
  import { createServer } from "node:http";
27
21
  import { Browser, detectBrowserPlatform, install, resolveBuildId } from "@puppeteer/browsers";
@@ -1082,85 +1076,6 @@ async function handleHttpTransfer(request, env, url) {
1082
1076
  }
1083
1077
  `;
1084
1078
  //#endregion
1085
- //#region src/bridge/miniflare.ts
1086
- function isIgnorableMiniflareDisposeError(error) {
1087
- if (!(error instanceof Error)) return false;
1088
- const details = error;
1089
- return details.code === "EBADF" && details.syscall === "kill";
1090
- }
1091
- //#endregion
1092
- //#region src/cli/wrangler-auth.ts
1093
- const execAsync = promisify(exec);
1094
- /**
1095
- * Check if the config contains any bindings that require remote access
1096
- */
1097
- function detectRemoteBindings(config) {
1098
- const remoteBindings = [];
1099
- const bindings = config.bindings;
1100
- if (!bindings) return remoteBindings;
1101
- if (bindings.ai) remoteBindings.push(`AI (binding: ${bindings.ai.binding})`);
1102
- if (bindings.vectorize) for (const [name] of Object.entries(bindings.vectorize)) remoteBindings.push(`Vectorize (binding: ${name})`);
1103
- return remoteBindings;
1104
- }
1105
- /**
1106
- * Check if wrangler is logged in by running `wrangler whoami`
1107
- *
1108
- * Returns:
1109
- * - loggedIn: true if user is authenticated
1110
- * - accountId: the account ID if available
1111
- * - email: the email if available
1112
- * - error: error message if check failed
1113
- */
1114
- async function checkWranglerAuth() {
1115
- try {
1116
- const { stdout, stderr } = await execAsync("bunx wrangler whoami", { timeout: 15e3 });
1117
- const output = stdout + stderr;
1118
- if (output.includes("not authenticated") || output.includes("Not logged in") || output.includes("wrangler login")) return {
1119
- loggedIn: false,
1120
- error: "Not logged in to Wrangler"
1121
- };
1122
- const emailMatch = output.match(/email[:\s]+([^\s!]+)/i);
1123
- const accountMatch = output.match(/Account\s+ID[:\s]+([a-f0-9]+)/i);
1124
- return {
1125
- loggedIn: true,
1126
- email: emailMatch?.[1],
1127
- accountId: accountMatch?.[1]
1128
- };
1129
- } catch (error) {
1130
- const msg = error instanceof Error ? error.message : String(error);
1131
- if (msg.includes("ENOENT") || msg.includes("not found")) return {
1132
- loggedIn: false,
1133
- error: "Wrangler not installed. Run: npm install -g wrangler"
1134
- };
1135
- return {
1136
- loggedIn: false,
1137
- error: msg
1138
- };
1139
- }
1140
- }
1141
- /**
1142
- * Check if remote bindings are properly configured
1143
- *
1144
- * Returns warnings if:
1145
- * - Config has remote-only bindings but no accountId
1146
- * - Config has remote-only bindings but user is not logged in to wrangler
1147
- */
1148
- async function checkRemoteBindingRequirements(config) {
1149
- const remoteBindings = detectRemoteBindings(config);
1150
- if (remoteBindings.length === 0) return {
1151
- hasRemoteBindings: false,
1152
- remoteBindings: [],
1153
- missingAccountId: false,
1154
- notLoggedIn: false
1155
- };
1156
- return {
1157
- hasRemoteBindings: true,
1158
- remoteBindings,
1159
- missingAccountId: !config.accountId,
1160
- notLoggedIn: !(await checkWranglerAuth()).loggedIn
1161
- };
1162
- }
1163
- //#endregion
1164
1079
  //#region src/dev-server/d1-migrations.ts
1165
1080
  const MIGRATION_RETRY_DELAYS_MS = [
1166
1081
  500,
@@ -1310,81 +1225,6 @@ async function runD1Migrations(options) {
1310
1225
  }
1311
1226
  }
1312
1227
  //#endregion
1313
- //#region src/dev-server/dev-server-state.ts
1314
- /**
1315
- * Build a fresh `DevServerState` with all handles in their not-yet-started
1316
- * positions. `enableVite` is the user's request — `start()` may downgrade it
1317
- * later via `resolveViteIntegration`.
1318
- */
1319
- function createDevServerState(initial) {
1320
- return {
1321
- enableVite: initial.enableVite,
1322
- miniflare: null,
1323
- doBundler: null,
1324
- workerSourceWatcher: null,
1325
- workerWatchTargets: [],
1326
- viteProcess: null,
1327
- config: null,
1328
- serviceBindingResolution: null,
1329
- browserShim: null,
1330
- browserShimPort: initial.browserShimPort ?? 8788,
1331
- mainWorkerSurfacePaths: {
1332
- fetch: null,
1333
- queue: null,
1334
- scheduled: null,
1335
- email: null,
1336
- tail: null
1337
- },
1338
- resolvedWorkerConfigPath: null,
1339
- mainWorkerScriptPath: null,
1340
- bundledMainWorkerScriptPath: null,
1341
- workflowEntrypointScript: "",
1342
- currentDoResult: null,
1343
- mainWorkerRoutes: null,
1344
- generatedViteConfigPath: null
1345
- };
1346
- }
1347
- /**
1348
- * Tear down everything in `state` in the same order the legacy `stop()`
1349
- * function used. After this returns, every handle on `state` is `null` again
1350
- * and the local sendEmail bindings have been cleared.
1351
- *
1352
- * Order is important and intentionally mirrors the production sequence:
1353
- * 1. DO bundler (stop rebuilds before Miniflare goes away)
1354
- * 2. Worker source watcher (stop FS callbacks before Miniflare disposal)
1355
- * 3. Miniflare itself
1356
- * 4. Vite child process (after Miniflare so requests cannot race shutdown)
1357
- * 5. Browser shim
1358
- * 6. Local sendEmail registry reset
1359
- */
1360
- async function disposeDevServerState(state) {
1361
- if (state.doBundler) {
1362
- await state.doBundler.close();
1363
- state.doBundler = null;
1364
- }
1365
- if (state.workerSourceWatcher) {
1366
- await state.workerSourceWatcher.close();
1367
- state.workerSourceWatcher = null;
1368
- }
1369
- if (state.miniflare) {
1370
- try {
1371
- await state.miniflare.dispose();
1372
- } catch (error) {
1373
- if (!isIgnorableMiniflareDisposeError(error)) throw error;
1374
- }
1375
- state.miniflare = null;
1376
- }
1377
- if (state.viteProcess) {
1378
- await stopSpawnedProcessTree(state.viteProcess);
1379
- state.viteProcess = null;
1380
- }
1381
- if (state.browserShim) {
1382
- await state.browserShim.stop();
1383
- state.browserShim = null;
1384
- }
1385
- clearLocalSendEmailBindings();
1386
- }
1387
- //#endregion
1388
1228
  //#region src/browser-shim/binding-worker.ts
1389
1229
  const MAX_CHUNK_SIZE = 1048575;
1390
1230
  /**
@@ -2170,7 +2010,7 @@ function resolveR2PresignOrigin(serverConfig, miniflareHost, miniflarePort) {
2170
2010
  * workers array is present.
2171
2011
  */
2172
2012
  function buildMiniflareDevConfig(input) {
2173
- const { config: loadedConfig, cwd, miniflarePort, miniflareHost = "127.0.0.1", persist, enableVite, debug, mainWorkerSurfacePaths, mainWorkerRoutes, mainWorkerScriptPath, bundledMainWorkerScriptPath, workflowEntrypointScript, browserShimPort, doResult, serviceBindingResolution, r2PresignSecret, logger } = input;
2013
+ const { config: loadedConfig, cwd, miniflarePort, miniflareHost = "127.0.0.1", persist, enableVite, debug, mainWorkerSurfacePaths, mainWorkerRoutes, mainWorkerScriptPath, bundledMainWorkerScriptPath, workflowEntrypointScript, browserShimPort, doResult, serviceBindingResolution, r2PresignSecret, additionalInjectedVars, logger } = input;
2174
2014
  const bindings = loadedConfig.bindings ?? {};
2175
2015
  const persistPath = process.env.DEVFLARE_PERSIST_DIR ? resolve(cwd, process.env.DEVFLARE_PERSIST_DIR) : resolve(cwd, ".devflare/data");
2176
2016
  const appWorkerName = loadedConfig.name;
@@ -2228,6 +2068,12 @@ function buildMiniflareDevConfig(input) {
2228
2068
  const aiSearchInstancesConfig = buildAiSearchInstancesConfig(bindings);
2229
2069
  const localSecretWrappedBindingConfig = buildLocalSecretWrappedBindingConfig(loadedConfig, cwd);
2230
2070
  const localSecretBindingNames = new Set(localSecretWrappedBindingConfig.localBindingNames);
2071
+ const secretsStoreConfig = buildSecretsStoreConfig(bindings, loadedConfig.secretsStoreId, localSecretBindingNames);
2072
+ const presignVars = bindings.r2 && r2PresignSecret ? {
2073
+ DEVFLARE_R2_PRESIGN_SECRET: r2PresignSecret,
2074
+ DEVFLARE_R2_PRESIGN_ORIGIN: resolveR2PresignOrigin(serverConfig, miniflareHost, miniflarePort)
2075
+ } : void 0;
2076
+ const hasAdditional = additionalInjectedVars !== void 0 && Object.keys(additionalInjectedVars).length > 0;
2231
2077
  const workerContext = {
2232
2078
  cwd,
2233
2079
  loadedConfig,
@@ -2251,12 +2097,12 @@ function buildMiniflareDevConfig(input) {
2251
2097
  artifactsConfig,
2252
2098
  aiSearchNamespacesConfig,
2253
2099
  aiSearchInstancesConfig,
2254
- secretsStoreConfig: buildSecretsStoreConfig(bindings, loadedConfig.secretsStoreId, localSecretBindingNames),
2100
+ secretsStoreConfig,
2255
2101
  localSecretWrappedBindingConfig,
2256
2102
  queueProducers,
2257
- injectedVars: bindings.r2 && r2PresignSecret ? {
2258
- DEVFLARE_R2_PRESIGN_SECRET: r2PresignSecret,
2259
- DEVFLARE_R2_PRESIGN_ORIGIN: resolveR2PresignOrigin(serverConfig, miniflareHost, miniflarePort)
2103
+ injectedVars: presignVars || hasAdditional ? {
2104
+ ...presignVars ?? {},
2105
+ ...hasAdditional ? additionalInjectedVars : {}
2260
2106
  } : void 0
2261
2107
  };
2262
2108
  const createWorkerConfig = (options) => makeMiniflareWorker(workerContext, options);
@@ -2329,43 +2175,6 @@ function buildMiniflareDevConfig(input) {
2329
2175
  };
2330
2176
  }
2331
2177
  //#endregion
2332
- //#region src/dev-server/reload-queue.ts
2333
- function createReloadQueue({ reload, logger }) {
2334
- let running = null;
2335
- let pending = null;
2336
- async function runOnce() {
2337
- try {
2338
- await reload();
2339
- } catch (error) {
2340
- logger?.error("[devflare dev] reload failed:", error);
2341
- }
2342
- }
2343
- function schedule() {
2344
- if (!running) {
2345
- running = runOnce().finally(() => {
2346
- running = null;
2347
- });
2348
- return running;
2349
- }
2350
- if (!pending) pending = running.then(() => {
2351
- pending = null;
2352
- running = runOnce().finally(() => {
2353
- running = null;
2354
- });
2355
- return running;
2356
- });
2357
- return pending;
2358
- }
2359
- async function drain() {
2360
- while (running || pending) if (pending) await pending;
2361
- else if (running) await running;
2362
- }
2363
- return {
2364
- schedule,
2365
- drain
2366
- };
2367
- }
2368
- //#endregion
2369
2178
  //#region src/dev-server/runtime-stdio.ts
2370
2179
  function writeStdout(logger, message) {
2371
2180
  if (typeof logger?.log === "function") {
@@ -3117,554 +2926,4 @@ async function startViteProcess(options) {
3117
2926
  return viteProcess;
3118
2927
  }
3119
2928
  //#endregion
3120
- //#region src/dev-server/worker-source-watcher.ts
3121
- async function startWorkerSourceWatcher(options) {
3122
- const { watchTargets, resolvedWorkerConfigPath, logger, onConfigChange, onWorkerChange } = options;
3123
- if (watchTargets.length === 0) return null;
3124
- const chokidar = await import("chokidar");
3125
- const isWindows = process.platform === "win32";
3126
- const ignoredSegments = [
3127
- "/node_modules/",
3128
- "/.git/",
3129
- "/.devflare/",
3130
- "/dist/"
3131
- ];
3132
- const normalizePath = (filePath) => filePath.replace(/\\/g, "/");
3133
- const isIgnoredPath = (filePath) => {
3134
- const normalizedPath = normalizePath(filePath);
3135
- return ignoredSegments.some((segment) => normalizedPath.includes(segment));
3136
- };
3137
- let reloadTimeout = null;
3138
- let reloadInProgress = false;
3139
- let pendingReloadPath = null;
3140
- const flushPendingReload = async () => {
3141
- if (!pendingReloadPath) return;
3142
- const nextPath = pendingReloadPath;
3143
- pendingReloadPath = null;
3144
- await triggerReload(nextPath);
3145
- };
3146
- const triggerReload = async (filePath) => {
3147
- if (reloadInProgress) {
3148
- pendingReloadPath = filePath;
3149
- return;
3150
- }
3151
- reloadInProgress = true;
3152
- try {
3153
- const normalizedConfigPath = resolvedWorkerConfigPath ? normalizePath(resolvedWorkerConfigPath) : null;
3154
- if (normalizedConfigPath && normalizePath(filePath) === normalizedConfigPath) {
3155
- logger?.info(`Devflare config changed: ${filePath}`);
3156
- await onConfigChange();
3157
- return;
3158
- }
3159
- logger?.info(`Worker source changed: ${filePath}`);
3160
- await onWorkerChange();
3161
- } catch (error) {
3162
- logger?.error("Worker source reload failed:", error);
3163
- } finally {
3164
- reloadInProgress = false;
3165
- await flushPendingReload();
3166
- }
3167
- };
3168
- const scheduleReload = (filePath) => {
3169
- if (reloadTimeout) clearTimeout(reloadTimeout);
3170
- reloadTimeout = setTimeout(() => {
3171
- reloadTimeout = null;
3172
- triggerReload(filePath);
3173
- }, 150);
3174
- };
3175
- const watcher = chokidar.watch(watchTargets, {
3176
- ignoreInitial: true,
3177
- usePolling: isWindows,
3178
- interval: isWindows ? 300 : void 0,
3179
- awaitWriteFinish: {
3180
- stabilityThreshold: 100,
3181
- pollInterval: 50
3182
- },
3183
- ignored: (filePath) => isIgnoredPath(filePath)
3184
- });
3185
- const onFileEvent = (filePath) => {
3186
- if (isIgnoredPath(filePath)) return;
3187
- scheduleReload(filePath);
3188
- };
3189
- watcher.on("change", onFileEvent);
3190
- watcher.on("add", onFileEvent);
3191
- watcher.on("unlink", onFileEvent);
3192
- watcher.on("error", (error) => {
3193
- logger?.error("Worker source watcher error:", error);
3194
- });
3195
- await new Promise((resolvePromise, rejectPromise) => {
3196
- const handleReady = () => {
3197
- watcher.off("error", handleInitialError);
3198
- logger?.info(`Worker source watcher ready (${watchTargets.length} target(s))`);
3199
- resolvePromise();
3200
- };
3201
- const handleInitialError = (error) => {
3202
- watcher.off("ready", handleReady);
3203
- rejectPromise(error instanceof Error ? error : new Error(String(error)));
3204
- };
3205
- watcher.once("ready", handleReady);
3206
- watcher.once("error", handleInitialError);
3207
- });
3208
- return watcher;
3209
- }
3210
- /**
3211
- * Compute the diff between current and next watch-target lists and apply it
3212
- * to the given watcher. Returns the deduped next-targets array which the
3213
- * caller should store as the new "current" state.
3214
- */
3215
- async function applyWatcherTargetDiff(watcher, currentTargets, nextTargets) {
3216
- const nextSet = new Set(nextTargets);
3217
- const targetsToRemove = currentTargets.filter((t) => !nextSet.has(t));
3218
- const targetsToAdd = nextTargets.filter((t) => !currentTargets.includes(t));
3219
- if (targetsToRemove.length > 0) await watcher.unwatch(targetsToRemove);
3220
- if (targetsToAdd.length > 0) watcher.add(targetsToAdd);
3221
- return nextTargets;
3222
- }
3223
- //#endregion
3224
- //#region src/dev-server/server.ts
3225
- function createDevServer(options) {
3226
- const { cwd, configPath, vitePort = 5173, miniflarePort = 8787, miniflareHost = "127.0.0.1", enableVite: enableViteRequested = true, persist = true, logger, verbose = false, debug = process.env.DEVFLARE_DEBUG === "true" } = options;
3227
- const state = createDevServerState({ enableVite: enableViteRequested });
3228
- const r2PresignSecret = `${crypto.randomUUID()}${crypto.randomUUID()}`;
3229
- const reloadQueue = createReloadQueue({
3230
- reload: async () => {
3231
- if (!state.miniflare) return;
3232
- const { Log, LogLevel } = await import("miniflare");
3233
- const mfConfig = buildMiniflareConfig(state.currentDoResult);
3234
- const log = createMiniflareLog(Log, LogLevel, "DEBUG", logger);
3235
- if (log) mfConfig.log = log;
3236
- mfConfig.handleRuntimeStdio = createRuntimeStdioForwarder(logger);
3237
- logger?.info("Reloading Miniflare...");
3238
- await state.miniflare.setOptions(mfConfig);
3239
- logger?.success("Miniflare reloaded");
3240
- },
3241
- logger
3242
- });
3243
- async function bundleMainWorker() {
3244
- if (!state.mainWorkerScriptPath || !state.config) {
3245
- state.bundledMainWorkerScriptPath = null;
3246
- return;
3247
- }
3248
- state.bundledMainWorkerScriptPath = await bundleWorkerEntry({
3249
- cwd,
3250
- inputFile: state.mainWorkerScriptPath,
3251
- outFile: resolve(cwd, ".devflare", "worker-entrypoints", "main.js"),
3252
- rolldownOptions: state.config.rolldown?.options,
3253
- sourcemap: state.config.rolldown?.sourcemap,
3254
- minify: state.config.rolldown?.minify,
3255
- logger
3256
- });
3257
- logger?.debug(`Bundled main worker → ${state.bundledMainWorkerScriptPath}`);
3258
- }
3259
- function buildMiniflareConfig(doResult) {
3260
- if (!state.config) throw new Error("Config not loaded");
3261
- return buildMiniflareDevConfig({
3262
- config: state.config,
3263
- cwd,
3264
- miniflarePort,
3265
- miniflareHost,
3266
- persist,
3267
- enableVite: state.enableVite,
3268
- debug,
3269
- mainWorkerSurfacePaths: state.mainWorkerSurfacePaths,
3270
- mainWorkerRoutes: state.mainWorkerRoutes,
3271
- mainWorkerScriptPath: state.mainWorkerScriptPath,
3272
- bundledMainWorkerScriptPath: state.bundledMainWorkerScriptPath,
3273
- workflowEntrypointScript: state.workflowEntrypointScript,
3274
- browserShimPort: state.browserShimPort,
3275
- doResult,
3276
- serviceBindingResolution: state.serviceBindingResolution,
3277
- r2PresignSecret,
3278
- logger
3279
- });
3280
- }
3281
- async function bundleWorkflowEntrypoints() {
3282
- if (!state.config) {
3283
- state.workflowEntrypointScript = "";
3284
- return;
3285
- }
3286
- state.workflowEntrypointScript = await bundleWorkflowEntrypointScript(state.config, cwd, { logger });
3287
- }
3288
- /**
3289
- * Start Miniflare with current config
3290
- */
3291
- async function startMiniflare(doResult) {
3292
- const { Miniflare, Log, LogLevel } = await import("miniflare");
3293
- const mfConfig = buildMiniflareConfig(doResult);
3294
- const log = createMiniflareLog(Log, LogLevel, "DEBUG", logger);
3295
- if (log) mfConfig.log = log;
3296
- mfConfig.handleRuntimeStdio = createRuntimeStdioForwarder(logger);
3297
- const shouldLogMiniflareDiagnostics = verbose || debug;
3298
- if (shouldLogMiniflareDiagnostics) logMiniflareConfigDiagnostics(logger, mfConfig);
3299
- state.miniflare = new Miniflare(mfConfig);
3300
- await state.miniflare.ready;
3301
- const displayHost = miniflareHost === "0.0.0.0" || miniflareHost === "::" ? "localhost" : miniflareHost;
3302
- logger?.success(`Miniflare ready on http://${displayHost}:${miniflarePort}`);
3303
- if (shouldLogMiniflareDiagnostics) await logMiniflareBindingDiagnostics(logger, state.miniflare, mfConfig);
3304
- }
3305
- /**
3306
- * Reload Miniflare with updated DO bundles
3307
- */
3308
- async function reloadMiniflare(doResult) {
3309
- state.currentDoResult = doResult;
3310
- await reloadQueue.schedule();
3311
- }
3312
- async function refreshWorkerOnlySurfaceState() {
3313
- if (!state.config) return;
3314
- state.mainWorkerSurfacePaths = await resolveMainWorkerSurfacePaths(cwd, state.config);
3315
- state.mainWorkerRoutes = await discoverRoutes(cwd, state.config);
3316
- const composedMainEntry = await prepareComposedWorkerEntrypoint(cwd, state.config, void 0, { devInternalEmail: true });
3317
- state.mainWorkerScriptPath = composedMainEntry ? composedMainEntry : null;
3318
- if (state.mainWorkerScriptPath) await bundleMainWorker();
3319
- else state.bundledMainWorkerScriptPath = null;
3320
- await syncWorkerWatchTargets();
3321
- }
3322
- function getWorkerWatchTargets() {
3323
- if (state.enableVite || !state.config) return [];
3324
- const targets = collectWorkerWatchRoots(cwd, state.config, state.mainWorkerSurfacePaths);
3325
- if (state.resolvedWorkerConfigPath) targets.push(state.resolvedWorkerConfigPath);
3326
- return [...new Set(targets)];
3327
- }
3328
- async function syncWorkerWatchTargets() {
3329
- if (!state.workerSourceWatcher) return;
3330
- state.workerWatchTargets = await applyWatcherTargetDiff(state.workerSourceWatcher, state.workerWatchTargets, getWorkerWatchTargets());
3331
- }
3332
- async function reloadWorkerOnlyConfig() {
3333
- await loadRuntimeConfigWhenEnvReady();
3334
- if (!state.config) return;
3335
- setLocalSendEmailBindings(state.config.bindings?.sendEmail ?? {});
3336
- await bundleWorkflowEntrypoints();
3337
- await refreshWorkerOnlySurfaceState();
3338
- await reloadMiniflare(state.currentDoResult);
3339
- }
3340
- async function loadRuntimeConfig() {
3341
- state.resolvedWorkerConfigPath = await resolveWorkerConfigWatchPath(cwd, configPath);
3342
- state.config = await applyLocalDevVarsToConfig(await resolveConfigEnvVars(await loadConfig({
3343
- cwd,
3344
- configFile: configPath
3345
- }), {
3346
- cwd,
3347
- configPath: state.resolvedWorkerConfigPath ?? configPath,
3348
- mode: "dev"
3349
- }), {
3350
- cwd,
3351
- configPath: state.resolvedWorkerConfigPath ?? void 0
3352
- });
3353
- state.serviceBindingResolution = state.config.bindings?.services ? await resolveServiceBindings(state.config, state.resolvedWorkerConfigPath ? dirname(state.resolvedWorkerConfigPath) : cwd) : null;
3354
- }
3355
- async function waitForDotenvChange() {
3356
- const configWatchPath = state.resolvedWorkerConfigPath ?? await resolveWorkerConfigWatchPath(cwd, configPath);
3357
- const watchPaths = getDevflareDotenvPaths(configWatchPath ? dirname(configWatchPath) : cwd);
3358
- const { watch } = await import("chokidar");
3359
- await new Promise((resolveWait, rejectWait) => {
3360
- const watcher = watch(watchPaths, {
3361
- ignoreInitial: true,
3362
- awaitWriteFinish: {
3363
- stabilityThreshold: 100,
3364
- pollInterval: 25
3365
- }
3366
- });
3367
- const finish = () => {
3368
- watcher.close().then(resolveWait, rejectWait);
3369
- };
3370
- watcher.on("add", finish);
3371
- watcher.on("change", finish);
3372
- watcher.on("unlink", finish);
3373
- watcher.on("error", rejectWait);
3374
- });
3375
- }
3376
- async function loadRuntimeConfigWhenEnvReady() {
3377
- while (true) try {
3378
- await loadRuntimeConfig();
3379
- return;
3380
- } catch (error) {
3381
- if (!(error instanceof EnvVarResolutionError)) throw error;
3382
- logger?.warn(error.message);
3383
- logger?.info("Devflare dev is waiting for .env or .env.dev to change before starting.");
3384
- await waitForDotenvChange();
3385
- }
3386
- }
3387
- async function startWorkerSourceWatcher$1() {
3388
- if (state.enableVite || !state.config) return;
3389
- const watchTargets = getWorkerWatchTargets();
3390
- if (watchTargets.length === 0) return;
3391
- state.workerWatchTargets = watchTargets;
3392
- state.workerSourceWatcher = await startWorkerSourceWatcher({
3393
- watchTargets,
3394
- resolvedWorkerConfigPath: state.resolvedWorkerConfigPath,
3395
- logger,
3396
- onConfigChange: reloadWorkerOnlyConfig,
3397
- onWorkerChange: async () => {
3398
- await refreshWorkerOnlySurfaceState();
3399
- await reloadMiniflare(state.currentDoResult);
3400
- }
3401
- });
3402
- }
3403
- /**
3404
- * Start the complete dev server
3405
- */
3406
- async function start() {
3407
- logger?.info("Starting unified dev server...");
3408
- await loadRuntimeConfigWhenEnvReady();
3409
- if (!state.config) throw new Error("Config not loaded");
3410
- setLocalSendEmailBindings(state.config.bindings?.sendEmail ?? {});
3411
- logger?.debug("Loaded config:", state.config.name);
3412
- await bundleWorkflowEntrypoints();
3413
- const viteIntegration = await resolveViteIntegration({
3414
- cwd,
3415
- configPath,
3416
- miniflarePort,
3417
- enableViteRequested: state.enableVite,
3418
- logger
3419
- });
3420
- state.enableVite = viteIntegration.enableVite;
3421
- state.generatedViteConfigPath = viteIntegration.generatedViteConfigPath;
3422
- await refreshWorkerOnlySurfaceState();
3423
- if (!state.enableVite && (hasWorkerSurfacePaths(state.mainWorkerSurfacePaths) || Boolean(state.mainWorkerRoutes?.routes.length))) logWorkerHandlerDetection(logger, state.enableVite, true, state.mainWorkerSurfacePaths, state.mainWorkerRoutes);
3424
- else if (!state.enableVite) logWorkerHandlerDetection(logger, state.enableVite, false, state.mainWorkerSurfacePaths, state.mainWorkerRoutes);
3425
- logRemoteBindingRequirements(logger, await checkRemoteBindingRequirements(state.config));
3426
- state.browserShim = await maybeStartBrowserShim(state.config, {
3427
- browserShimPort: state.browserShimPort,
3428
- logger,
3429
- verbose
3430
- });
3431
- const doInit = await maybeStartDOBundler(state.config, {
3432
- cwd,
3433
- logger,
3434
- onRebuild: async (result) => {
3435
- await reloadMiniflare(result);
3436
- }
3437
- });
3438
- state.doBundler = doInit.bundler;
3439
- const doResult = doInit.result;
3440
- state.currentDoResult = doResult;
3441
- await startMiniflare(doResult);
3442
- await startWorkerSourceWatcher$1();
3443
- if (state.enableVite) state.viteProcess = await startViteProcess({
3444
- cwd,
3445
- configPath,
3446
- vitePort,
3447
- miniflarePort,
3448
- generatedViteConfigPath: state.generatedViteConfigPath,
3449
- r2Presign: state.config.bindings?.r2 ? {
3450
- secret: r2PresignSecret,
3451
- origin: resolveR2PresignOrigin(state.config.server, miniflareHost, miniflarePort)
3452
- } : null,
3453
- logger
3454
- });
3455
- else logger?.info("Vite startup skipped (no effective Vite config found for this package)");
3456
- await new Promise((r) => setTimeout(r, 1e3));
3457
- await runD1Migrations({
3458
- cwd,
3459
- config: state.config,
3460
- miniflarePort,
3461
- logger
3462
- });
3463
- }
3464
- /**
3465
- * Stop the dev server
3466
- */
3467
- async function stop() {
3468
- await disposeDevServerState(state);
3469
- }
3470
- /**
3471
- * Get Miniflare instance
3472
- */
3473
- function getMiniflare() {
3474
- return state.miniflare;
3475
- }
3476
- return {
3477
- start,
3478
- stop,
3479
- getMiniflare
3480
- };
3481
- }
3482
- //#endregion
3483
- //#region src/cli/commands/dev.ts
3484
- function readStringOption(value) {
3485
- return typeof value === "string" ? value : void 0;
3486
- }
3487
- function parsePort(value, source) {
3488
- const port = Number(value);
3489
- if (!Number.isInteger(port) || port <= 0 || port > 65535) throw new Error(`${source} must be an integer between 1 and 65535`);
3490
- return port;
3491
- }
3492
- function resolveSinglePort(runtimePort, bridgePort, source) {
3493
- if (runtimePort && bridgePort && runtimePort !== bridgePort) throw new Error(`Conflicting Devflare runtime ports: ${source} runtime port is ${runtimePort}, but bridge port is ${bridgePort}. Use one value for both.`);
3494
- const value = runtimePort ?? bridgePort;
3495
- return value ? parsePort(value, source) : void 0;
3496
- }
3497
- function resolveDevRuntimePort(options, env = process.env, configPort) {
3498
- return resolveSinglePort(readStringOption(options["runtime-port"]), readStringOption(options["bridge-port"]), "CLI") ?? resolveSinglePort(env.DEVFLARE_RUNTIME_PORT, env.DEVFLARE_BRIDGE_PORT, "environment") ?? configPort ?? 8787;
3499
- }
3500
- /**
3501
- * Resolve the host the local Miniflare runtime instance binds to.
3502
- *
3503
- * Precedence: `--runtime-host` CLI flag > `DEVFLARE_RUNTIME_HOST` env var >
3504
- * `server.host` config value > `127.0.0.1`.
3505
- */
3506
- function resolveDevRuntimeHost(options, env = process.env, configHost) {
3507
- const envHost = env.DEVFLARE_RUNTIME_HOST?.trim();
3508
- return readStringOption(options["runtime-host"]) ?? (envHost ? envHost : void 0) ?? configHost ?? "127.0.0.1";
3509
- }
3510
- /**
3511
- * Create a log writer that writes to both terminal and file
3512
- */
3513
- async function createLogWriter(cwd, options) {
3514
- if (!options.log && !options.logTemp) return null;
3515
- const fs = await import("node:fs");
3516
- let logPath;
3517
- if (options.logTemp) logPath = resolve(cwd, ".log");
3518
- else logPath = resolve(cwd, `.log-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19)}`);
3519
- const fileStream = fs.createWriteStream(logPath, { flags: "w" });
3520
- const ansiRegex = /\x1b\[[0-9;]*m/g;
3521
- return {
3522
- path: logPath,
3523
- write(data, source) {
3524
- const str = typeof data === "string" ? data : data.toString();
3525
- if (!str.trim()) return;
3526
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().slice(11, 23);
3527
- const prefix = source ? `[${timestamp}][${source.toUpperCase()}] ` : `[${timestamp}] `;
3528
- const cleanStr = str.replace(ansiRegex, "");
3529
- fileStream.write(prefix + cleanStr + (cleanStr.endsWith("\n") ? "" : "\n"));
3530
- },
3531
- close() {
3532
- fileStream.end();
3533
- }
3534
- };
3535
- }
3536
- async function runDevCommand(parsed, logger, options) {
3537
- const cwd = options.cwd || parsed.options.cwd || process.cwd();
3538
- const configPath = parsed.options.config;
3539
- const port = parsed.options.port;
3540
- const logEnabled = parsed.options.log === true;
3541
- const logTempEnabled = parsed.options["log-temp"] === true;
3542
- const persistEnabled = parsed.options.persist === true;
3543
- const debugEnabled = parsed.options.debug === true || process.env.DEVFLARE_DEBUG === "true";
3544
- const verbose = parsed.options.verbose === true || debugEnabled;
3545
- const theme = createCliTheme(parsed.options);
3546
- const config = await loadConfig({
3547
- cwd,
3548
- configFile: configPath
3549
- });
3550
- let miniflarePort;
3551
- let miniflareHost;
3552
- try {
3553
- miniflarePort = resolveDevRuntimePort(parsed.options, process.env, config.server?.port);
3554
- miniflareHost = resolveDevRuntimeHost(parsed.options, process.env, config.server?.host);
3555
- } catch (error) {
3556
- logger.error(error instanceof Error ? error.message : String(error));
3557
- return { exitCode: 1 };
3558
- }
3559
- const viteProject = resolveEffectiveViteProject(await detectViteProject(cwd), config);
3560
- const logWriter = await createLogWriter(cwd, {
3561
- log: logEnabled,
3562
- logTemp: logTempEnabled
3563
- });
3564
- if (logWriter) {
3565
- const logFile = relative(cwd, logWriter.path) || ".log";
3566
- logLine(logger, `${dim("logging", theme)} ${logFile}`);
3567
- }
3568
- const devLogger = createConsola({ level: verbose ? 4 : 3 });
3569
- if (logWriter) {
3570
- const wrapLog = (original, prefix = "") => {
3571
- return (message, ...args) => {
3572
- original(message, ...args);
3573
- const formatted = prefix ? `${prefix} ${[message, ...args].join(" ")}` : [message, ...args].join(" ");
3574
- logWriter.write(formatted);
3575
- };
3576
- };
3577
- Object.assign(devLogger.log, wrapLog(devLogger.log.bind(devLogger)));
3578
- Object.assign(devLogger.info, wrapLog(devLogger.info.bind(devLogger)));
3579
- Object.assign(devLogger.error, wrapLog(devLogger.error.bind(devLogger), "[ERROR]"));
3580
- Object.assign(devLogger.warn, wrapLog(devLogger.warn.bind(devLogger), "[WARN]"));
3581
- Object.assign(devLogger.success, wrapLog(devLogger.success.bind(devLogger), "[OK]"));
3582
- Object.assign(devLogger.debug, wrapLog(devLogger.debug.bind(devLogger), "[DEBUG]"));
3583
- }
3584
- try {
3585
- logLine(logger);
3586
- if (viteProject.shouldStartVite) {
3587
- logLine(logger, `${cyanBold("dev", theme)} ${dim("Unified Dev Server", theme)}`);
3588
- logLine(logger, " ├─ Vite: Full HMR for frontend");
3589
- logLine(logger, " ├─ Miniflare: All Cloudflare bindings");
3590
- logLine(logger, " ├─ Rolldown: Worker + DO bundling with watch");
3591
- logLine(logger, " └─ Bridge: WebSocket RPC connection");
3592
- } else {
3593
- logLine(logger, `${cyanBold("dev", theme)} ${dim("Worker Dev Server", theme)}`);
3594
- logLine(logger, " ├─ Miniflare: All Cloudflare bindings");
3595
- logLine(logger, " ├─ Rolldown: Worker + DO bundling with watch");
3596
- logLine(logger, " └─ Vite: Disabled (no effective Vite config found)");
3597
- if (viteProject.wantsViteIntegration) {
3598
- logger.warn("Vite-related settings were detected, but no effective Vite config was available");
3599
- logger.warn("Skipping Vite startup and running in worker-only mode");
3600
- }
3601
- }
3602
- logLine(logger);
3603
- const devServer = createDevServer({
3604
- cwd,
3605
- configPath,
3606
- vitePort: port ? Number.parseInt(port, 10) : 5173,
3607
- miniflarePort,
3608
- miniflareHost,
3609
- enableVite: viteProject.shouldStartVite,
3610
- persist: persistEnabled,
3611
- logger: devLogger,
3612
- verbose,
3613
- debug: debugEnabled
3614
- });
3615
- let isCleaningUp = false;
3616
- const cleanupHandlers = /* @__PURE__ */ new Map();
3617
- const removeCleanupHandlers = () => {
3618
- for (const [event, handler] of cleanupHandlers) process.off(event, handler);
3619
- cleanupHandlers.clear();
3620
- };
3621
- const cleanup = async (exitCode, reason) => {
3622
- if (isCleaningUp) return;
3623
- isCleaningUp = true;
3624
- removeCleanupHandlers();
3625
- if (reason) {
3626
- const message = reason instanceof Error ? reason.stack ?? reason.message : String(reason);
3627
- logger.error(message);
3628
- }
3629
- logLine(logger);
3630
- logLine(logger, `${yellow("dev", theme)} ${dim("Shutting down…", theme)}`);
3631
- try {
3632
- await devServer.stop();
3633
- } finally {
3634
- logWriter?.close();
3635
- process.exit(exitCode);
3636
- }
3637
- };
3638
- const registerCleanupHandler = (event, handler) => {
3639
- cleanupHandlers.set(event, handler);
3640
- process.on(event, handler);
3641
- };
3642
- registerCleanupHandler("SIGINT", () => {
3643
- cleanup(0);
3644
- });
3645
- registerCleanupHandler("SIGTERM", () => {
3646
- cleanup(0);
3647
- });
3648
- registerCleanupHandler("SIGHUP", () => {
3649
- cleanup(0);
3650
- });
3651
- registerCleanupHandler("uncaughtException", (error) => {
3652
- cleanup(1, error);
3653
- });
3654
- registerCleanupHandler("unhandledRejection", (reason) => {
3655
- cleanup(1, reason);
3656
- });
3657
- await devServer.start();
3658
- await new Promise(() => {});
3659
- return { exitCode: 0 };
3660
- } catch (error) {
3661
- logWriter?.close();
3662
- if (error instanceof Error) {
3663
- logger.error("Dev server failed:", error.message);
3664
- if (verbose) logger.error(error.stack);
3665
- }
3666
- return { exitCode: 1 };
3667
- }
3668
- }
3669
- //#endregion
3670
- export { runDevCommand };
2929
+ export { createMiniflareLog as _, logWorkerHandlerDetection as a, resolveViteIntegration as c, createRuntimeStdioForwarder as d, buildMiniflareDevConfig as f, runD1Migrations as g, resolveMainWorkerSurfacePaths as h, logRemoteBindingRequirements as i, resolveWorkerConfigWatchPath as l, collectWorkerWatchRoots as m, logMiniflareBindingDiagnostics as n, maybeStartBrowserShim as o, resolveR2PresignOrigin as p, logMiniflareConfigDiagnostics as r, maybeStartDOBundler as s, startViteProcess as t, createBrowserShim as u, createDOBundler as v };