@vite-hub/runtime 0.1.0 → 0.3.0

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 (44) hide show
  1. package/README.md +151 -117
  2. package/dist/durability.d.ts +107 -0
  3. package/dist/durability.js +168 -0
  4. package/dist/error-diagnostics-BKICpwZp.js +85 -0
  5. package/dist/error-diagnostics-BsJr9VdW.d.ts +15 -0
  6. package/dist/{errors-CbqHQTvn.js → errors-BEomN3fX.js} +1 -1
  7. package/dist/{execution-budget-D8SwJE8_.d.ts → execution-budget-BPXbISEt.d.ts} +9 -6
  8. package/dist/index-Bcl-Hr-a.d.ts +678 -0
  9. package/dist/index.d.ts +5 -4
  10. package/dist/index.js +5 -4
  11. package/dist/internal/drain.d.ts +17 -0
  12. package/dist/internal/drain.js +75 -0
  13. package/dist/internal/execution-budget.d.ts +1 -1
  14. package/dist/internal/grant.js +2 -2
  15. package/dist/internal/h3.d.ts +42 -0
  16. package/dist/internal/h3.js +181 -0
  17. package/dist/{node.d.ts → internal/node.d.ts} +2 -2
  18. package/dist/{node.js → internal/node.js} +4 -4
  19. package/dist/internal/public-url.d.ts +2 -0
  20. package/dist/internal/public-url.js +2 -0
  21. package/dist/internal/run-scope.d.ts +11 -0
  22. package/dist/internal/run-scope.js +30 -0
  23. package/dist/internal/runtime-type.d.ts +9 -2
  24. package/dist/internal/runtime-type.js +3 -2
  25. package/dist/{shutdown.d.ts → internal/shutdown.d.ts} +1 -1
  26. package/dist/{shutdown.js → internal/shutdown.js} +1 -1
  27. package/dist/internal/test-mode-setup.d.ts +7 -0
  28. package/dist/internal/test-mode-setup.js +114 -0
  29. package/dist/internal/test-mode.d.ts +32 -0
  30. package/dist/internal/test-mode.js +9 -0
  31. package/dist/operations.d.ts +167 -0
  32. package/dist/operations.js +406 -0
  33. package/dist/public-url-1WeOw54Z.d.ts +34 -0
  34. package/dist/public-url-B6x0HMgY.js +140 -0
  35. package/dist/{src-jy-gyPPu.js → request-context-CP9NhgLL.js} +635 -551
  36. package/dist/runtime-type-BftydMAf.js +88 -0
  37. package/package.json +61 -26
  38. package/dist/drain.d.ts +0 -1
  39. package/dist/drain.js +0 -69
  40. package/dist/error-diagnostics-Bkym4e6y.d.ts +0 -12
  41. package/dist/h3.d.ts +0 -49
  42. package/dist/h3.js +0 -404
  43. package/dist/index-Rl4DbP8B.d.ts +0 -574
  44. package/dist/runtime-type-CgfU6SWl.js +0 -52
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { t as runtimeErrorDiagnostics } from "./error-diagnostics-Bkym4e6y.js";
2
- import { $ as emitTraceEvent, $t as decodeRouteSegment, A as RuntimeWaitUntil, At as RuntimeDiagnosticEvent, B as TraceEventLogOptions, Bt as isRuntimeDiagnostic, C as PolicyDecision, Ct as ViteHubErrorDetails, D as RuntimeCapabilityHandle, Dt as isViteHubError, E as RuntimeCapabilities, Et as getViteHubErrorShape, F as TraceContext, Ft as RuntimeResourceScope, G as TraceStepStatus, Gt as ResultError, H as TracePayloadVisibility, Ht as DefineErrorsOptions, I as TraceEvent, It as RuntimeResourceSnapshot, J as createRuntimeContext, Jt as PublicUrlConfig, K as TraceStepView, Kt as defineErrors, L as TraceEventContentPolicy, Lt as RuntimeResourceSupport, M as TraceActivityContext, Mt as RuntimeDiagnosticReporter, N as TraceActivityOwner, Nt as RuntimeResourceInspector, O as RuntimeContextInput, Ot as RuntimeDiagnosticError, P as TraceActivityPhase, Pt as RuntimeResourceObservation, Q as deriveTraceRuns, Qt as resolvePublicUrl, R as TraceEventLog, Rt as RuntimeResourceUnit, S as PolicyContext, St as ViteHubErrorDetail, T as RunLifecycleHooks, Tt as ViteHubErrorShape, U as TraceRunStatus, Ut as ErrorCatalog, V as TraceEventPayload, Vt as normalizeRuntimeDiagnosticError, W as TraceRunView, Wt as Result, X as createTraceEventLog, Xt as registerPublicUrlAgentName, Y as createRuntimeWaitUntilController, Yt as consoleInvocationUrl, Z as defineCapability, Zt as resetPublicUrlAgentNames, _ as MaybeResolvable, _t as WorkCheckpointStore, a as ApprovalDecision, an as RuntimePreflightCheckSummary, at as normalizeExecutionAuthority, b as OpenTelemetrySpanView, bt as createWorkTracker, c as CapabilityDefinition, cn as RuntimePreflightHandle, ct as traceEventsToOpenTelemetryLogRecords, d as CreatedRuntimeContext, dn as RuntimePreflightManifest, dt as SerializedResponse, en as encodeRouteSegment, et as getCapability, f as ExecutionAuthority, fn as RuntimePreflightOptions, ft as deserializeResponse, g as MaybePromise, gn as startRuntimePreflight, gt as WorkCheckpoint, h as LeaseStore, hn as runRuntimePreflight, ht as toResponse, i as AccessAuthorizeResult, in as RuntimePreflightCheckResult, it as noExecutionAuthority, j as RuntimeWaitUntilController, jt as RuntimeDiagnosticLevel, k as RuntimeHostContext, kt as RuntimeDiagnosticErrorOptions, l as CapabilityHandle, ln as RuntimePreflightIssue, lt as traceEventsToOpenTelemetrySpans, m as Lease, mn as RuntimePreflightValue, mt as serializeResponse, n as AccessAuthorize, nn as RuntimePreflightCheck, nt as isExecutionAuthority, o as ApprovalRequest, on as RuntimePreflightDetails, ot as resolveCapabilityPolicy, p as ExecutionContext, pn as RuntimePreflightState, pt as isSerializedResponse, q as createExecutionContext, qt as toResultError, r as AccessAuthorizeOption, rn as RuntimePreflightCheckContext, rt as isResolvable, s as ApprovalState, sn as RuntimePreflightDiagnosticData, st as resolveRuntimeValue, t as AccessAuthorizationContext, tn as isTraceContentAttributeKey, tt as hasCapability, u as CapabilityPolicy, un as RuntimePreflightKind, ut as unknownExecutionAuthority, v as OpenTelemetryLogRecordView, vt as WorkOutcome, w as Resolvable, wt as ViteHubErrorOptions, x as OpenTelemetrySpanViewOptions, xt as ViteHubError, y as OpenTelemetrySpanEventView, yt as WorkTracker, z as TraceEventLogEntry, zt as formatRuntimeDiagnosticError } from "./index-Rl4DbP8B.js";
3
- import { a as ExecutionBudgetOptions, c as createExecutionBudget, i as ExecutionBudgetLimits, n as ExecutionBudgetCounter, o as ExecutionBudgetSnapshot, r as ExecutionBudgetExceededError, s as ExecutionBudgetUsage, t as ExecutionBudget } from "./execution-budget-D8SwJE8_.js";
4
- export { AccessAuthorizationContext, AccessAuthorize, AccessAuthorizeOption, AccessAuthorizeResult, ApprovalDecision, ApprovalRequest, ApprovalState, CapabilityDefinition, CapabilityHandle, CapabilityPolicy, CreatedRuntimeContext, type DefineErrorsOptions, type ErrorCatalog, ExecutionAuthority, type ExecutionBudget, type ExecutionBudgetCounter, ExecutionBudgetExceededError, type ExecutionBudgetLimits, type ExecutionBudgetOptions, type ExecutionBudgetSnapshot, type ExecutionBudgetUsage, ExecutionContext, Lease, LeaseStore, MaybePromise, MaybeResolvable, OpenTelemetryLogRecordView, OpenTelemetrySpanEventView, OpenTelemetrySpanView, OpenTelemetrySpanViewOptions, PolicyContext, PolicyDecision, type PublicUrlConfig, Resolvable, type Result, type ResultError, RunLifecycleHooks, RuntimeCapabilities, RuntimeCapabilityHandle, RuntimeContextInput, type RuntimeDiagnosticError, type RuntimeDiagnosticErrorOptions, type RuntimeDiagnosticEvent, type RuntimeDiagnosticLevel, type RuntimeDiagnosticReporter, RuntimeHostContext, type RuntimePreflightCheck, type RuntimePreflightCheckContext, type RuntimePreflightCheckResult, type RuntimePreflightCheckSummary, type RuntimePreflightDetails, type RuntimePreflightDiagnosticData, type RuntimePreflightHandle, type RuntimePreflightIssue, type RuntimePreflightKind, type RuntimePreflightManifest, type RuntimePreflightOptions, type RuntimePreflightState, type RuntimePreflightValue, type RuntimeResourceInspector, type RuntimeResourceObservation, type RuntimeResourceScope, type RuntimeResourceSnapshot, type RuntimeResourceSupport, type RuntimeResourceUnit, RuntimeWaitUntil, RuntimeWaitUntilController, type SerializedResponse, TraceActivityContext, TraceActivityOwner, TraceActivityPhase, TraceContext, TraceEvent, TraceEventContentPolicy, TraceEventLog, TraceEventLogEntry, TraceEventLogOptions, TraceEventPayload, TracePayloadVisibility, TraceRunStatus, TraceRunView, TraceStepStatus, TraceStepView, ViteHubError, type ViteHubErrorDetail, type ViteHubErrorDetails, type ViteHubErrorOptions, type ViteHubErrorShape, type WorkCheckpoint, type WorkCheckpointStore, type WorkOutcome, type WorkTracker, consoleInvocationUrl, createExecutionBudget, createExecutionContext, createRuntimeContext, createRuntimeWaitUntilController, createTraceEventLog, createWorkTracker, decodeRouteSegment, defineCapability, defineErrors, deriveTraceRuns, deserializeResponse, emitTraceEvent, encodeRouteSegment, formatRuntimeDiagnosticError, getCapability, getViteHubErrorShape, hasCapability, isExecutionAuthority, isResolvable, isRuntimeDiagnostic, isSerializedResponse, isTraceContentAttributeKey, isViteHubError, noExecutionAuthority, normalizeExecutionAuthority, normalizeRuntimeDiagnosticError, registerPublicUrlAgentName, resetPublicUrlAgentNames, resolveCapabilityPolicy, resolvePublicUrl, resolveRuntimeValue, runRuntimePreflight, runtimeErrorDiagnostics, serializeResponse, startRuntimePreflight, toResponse, toResultError, traceEventsToOpenTelemetryLogRecords, traceEventsToOpenTelemetrySpans, unknownExecutionAuthority };
1
+ import { t as runtimeErrorDiagnostics } from "./error-diagnostics-BsJr9VdW.js";
2
+ import { $ as emitTraceEvent, $t as decodeRouteSegment, A as RuntimeWaitUntil, At as ViteHubErrorDetails, B as TraceEventLogOptions, Bt as RuntimeResourceInspector, C as PolicyDecision, Cn as ViteHubStandardProps, Ct as RuntimeName, D as RuntimeCapabilityHandle, E as RuntimeCapabilities, F as TraceContext, Ft as RuntimeDiagnosticError, G as TraceStepStatus, Gt as RuntimeResourceUnit, H as TracePayloadVisibility, Ht as RuntimeResourceScope, I as TraceEvent, It as RuntimeDiagnosticErrorOptions, J as createRuntimeContext, Jt as normalizeRuntimeDiagnosticError, K as TraceStepView, Kt as formatRuntimeDiagnosticError, L as TraceEventContentPolicy, Lt as RuntimeDiagnosticEvent, M as TraceActivityContext, Mt as ViteHubErrorShape, N as TraceActivityOwner, Nt as getViteHubErrorShape, O as RuntimeContextInput, Ot as ViteHubError, P as TraceActivityPhase, Pt as isViteHubError, Q as deriveTraceRuns, Qt as normalizeConsoleProjectUrl, R as TraceEventLog, Rt as RuntimeDiagnosticLevel, S as PolicyContext, Sn as ViteHubRuntime, St as RuntimeContextOptions, T as RunLifecycleHooks, Tt as getStandardContext, U as TraceRunStatus, Ut as RuntimeResourceSnapshot, V as TraceEventPayload, Vt as RuntimeResourceObservation, W as TraceRunView, Wt as RuntimeResourceSupport, X as createTraceEventLog, Xt as hostedConsoleUrl, Y as createRuntimeWaitUntilController, Yt as hostedConsoleOrigin, Z as defineCapability, Zt as normalizeConsolePath, _ as MaybeResolvable, _n as ResultError, _t as isResponse, a as AnonymousAccessAuthorizationContext, an as LeaseRecord, at as normalizeExecutionAuthority, b as OpenTelemetrySpanView, bn as isTraceContentAttributeKey, bt as toResponse, c as ApprovalRequest, cn as LeaseStore, ct as traceEventsToOpenTelemetryLogRecords, d as CapabilityHandle, dn as leaseTable, dt as HostBindingErrorCode, en as encodeRouteSegment, et as getCapability, f as CapabilityPolicy, fn as DefineErrorsOptions, ft as detectHost, g as MaybePromise, gn as Result, gt as deserializeResponse, h as ExecutionContext, hn as ErrorHandle, ht as SerializedResponse, i as AccessAuthorizeResult, in as LeaseOperation, it as noExecutionAuthority, j as RuntimeWaitUntilController, jt as ViteHubErrorOptions, k as RuntimeHostContext, kt as ViteHubErrorDetail, l as ApprovalState, ln as createMemoryLeaseStore, lt as traceEventsToOpenTelemetrySpans, m as ExecutionAuthority, mn as ErrorCodes, mt as ViteHubHost, n as AccessAuthorize, nn as LeaseAcquireOptions, nt as isExecutionAuthority, o as AnonymousAccessAuthorize, on as LeaseSqlClient, ot as resolveCapabilityPolicy, p as CreatedRuntimeContext, pn as ErrorCatalog, pt as getHostBinding, q as createExecutionContext, qt as isRuntimeDiagnostic, r as AccessAuthorizeOption, rn as LeaseErrorCode, rt as isResolvable, s as ApprovalDecision, sn as LeaseSqlParam, st as resolveRuntimeValue, t as AccessAuthorizationContext, tn as Lease, tt as hasCapability, u as CapabilityDefinition, un as createSqlLeaseStore, ut as unknownExecutionAuthority, v as OpenTelemetryLogRecordView, vn as defineErrors, vt as isSerializedResponse, w as Resolvable, wt as getRuntimeContext, x as OpenTelemetrySpanViewOptions, xn as ViteHubContext, xt as RequestRuntimeContext, y as OpenTelemetrySpanEventView, yn as toResultError, yt as serializeResponse, z as TraceEventLogEntry, zt as RuntimeDiagnosticReporter } from "./index-Bcl-Hr-a.js";
3
+ import { a as ExecutionBudgetOptions, c as createExecutionBudget, i as ExecutionBudgetLimits, l as isExecutionBudgetExceededError, n as ExecutionBudgetCounter, o as ExecutionBudgetSnapshot, r as ExecutionBudgetExceededError, s as ExecutionBudgetUsage, t as ExecutionBudget } from "./execution-budget-BPXbISEt.js";
4
+ import { a as resolvePublicUrl, n as consoleInvocationUrl, t as PublicUrlConfig } from "./public-url-1WeOw54Z.js";
5
+ export { AccessAuthorizationContext, AccessAuthorize, AccessAuthorizeOption, AccessAuthorizeResult, AnonymousAccessAuthorizationContext, AnonymousAccessAuthorize, ApprovalDecision, ApprovalRequest, ApprovalState, CapabilityDefinition, CapabilityHandle, CapabilityPolicy, CreatedRuntimeContext, type DefineErrorsOptions, type ErrorCatalog, type ErrorCodes, type ErrorHandle, ExecutionAuthority, type ExecutionBudget, type ExecutionBudgetCounter, type ExecutionBudgetExceededError, type ExecutionBudgetLimits, type ExecutionBudgetOptions, type ExecutionBudgetSnapshot, type ExecutionBudgetUsage, ExecutionContext, type HostBindingErrorCode, type Lease, type LeaseAcquireOptions, type LeaseErrorCode, type LeaseOperation, type LeaseRecord, type LeaseSqlClient, type LeaseSqlParam, type LeaseStore, MaybePromise, MaybeResolvable, OpenTelemetryLogRecordView, OpenTelemetrySpanEventView, OpenTelemetrySpanView, OpenTelemetrySpanViewOptions, PolicyContext, PolicyDecision, type PublicUrlConfig, type RequestRuntimeContext, Resolvable, type Result, type ResultError, RunLifecycleHooks, RuntimeCapabilities, RuntimeCapabilityHandle, RuntimeContextInput, type RuntimeContextOptions, type RuntimeDiagnosticError, type RuntimeDiagnosticErrorOptions, type RuntimeDiagnosticEvent, type RuntimeDiagnosticLevel, type RuntimeDiagnosticReporter, RuntimeHostContext, type RuntimeName, type RuntimeResourceInspector, type RuntimeResourceObservation, type RuntimeResourceScope, type RuntimeResourceSnapshot, type RuntimeResourceSupport, type RuntimeResourceUnit, RuntimeWaitUntil, RuntimeWaitUntilController, type SerializedResponse, TraceActivityContext, TraceActivityOwner, TraceActivityPhase, TraceContext, TraceEvent, TraceEventContentPolicy, TraceEventLog, TraceEventLogEntry, TraceEventLogOptions, TraceEventPayload, TracePayloadVisibility, TraceRunStatus, TraceRunView, TraceStepStatus, TraceStepView, type ViteHubContext, ViteHubError, type ViteHubErrorDetail, type ViteHubErrorDetails, type ViteHubErrorOptions, type ViteHubErrorShape, type ViteHubHost, type ViteHubRuntime, type ViteHubStandardProps, consoleInvocationUrl, createExecutionBudget, createExecutionContext, createMemoryLeaseStore, createRuntimeContext, createRuntimeWaitUntilController, createSqlLeaseStore, createTraceEventLog, decodeRouteSegment, defineCapability, defineErrors, deriveTraceRuns, deserializeResponse, detectHost, emitTraceEvent, encodeRouteSegment, formatRuntimeDiagnosticError, getCapability, getHostBinding, getRuntimeContext, getStandardContext, getViteHubErrorShape, hasCapability, hostedConsoleOrigin, hostedConsoleUrl, isExecutionAuthority, isExecutionBudgetExceededError, isResolvable, isResponse, isRuntimeDiagnostic, isSerializedResponse, isTraceContentAttributeKey, isViteHubError, leaseTable, noExecutionAuthority, normalizeConsolePath, normalizeConsoleProjectUrl, normalizeExecutionAuthority, normalizeRuntimeDiagnosticError, resolveCapabilityPolicy, resolvePublicUrl, resolveRuntimeValue, runtimeErrorDiagnostics, serializeResponse, toResponse, toResultError, traceEventsToOpenTelemetryLogRecords, traceEventsToOpenTelemetrySpans, unknownExecutionAuthority };
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { i as runtimeErrorDiagnostics } from "./runtime-type-CgfU6SWl.js";
2
- import { n as getViteHubErrorShape, r as isViteHubError, t as ViteHubError } from "./errors-CbqHQTvn.js";
3
- import { A as registerPublicUrlAgentName, C as createWorkTracker, D as isRuntimeDiagnostic, E as formatRuntimeDiagnosticError, F as ExecutionBudgetExceededError, I as createExecutionBudget, L as runRuntimePreflight, M as resolvePublicUrl, N as decodeRouteSegment, O as normalizeRuntimeDiagnosticError, P as encodeRouteSegment, R as startRuntimePreflight, S as toResponse, T as toResultError, _ as traceEventsToOpenTelemetrySpans, a as defineCapability, b as isSerializedResponse, c as getCapability, d as isResolvable, f as noExecutionAuthority, g as traceEventsToOpenTelemetryLogRecords, h as resolveRuntimeValue, i as createTraceEventLog, j as resetPublicUrlAgentNames, k as consoleInvocationUrl, l as hasCapability, m as resolveCapabilityPolicy, n as createRuntimeContext, o as deriveTraceRuns, p as normalizeExecutionAuthority, r as createRuntimeWaitUntilController, s as emitTraceEvent, t as createExecutionContext, u as isExecutionAuthority, v as unknownExecutionAuthority, w as defineErrors, x as serializeResponse, y as deserializeResponse, z as isTraceContentAttributeKey } from "./src-jy-gyPPu.js";
4
- export { ExecutionBudgetExceededError, ViteHubError, consoleInvocationUrl, createExecutionBudget, createExecutionContext, createRuntimeContext, createRuntimeWaitUntilController, createTraceEventLog, createWorkTracker, decodeRouteSegment, defineCapability, defineErrors, deriveTraceRuns, deserializeResponse, emitTraceEvent, encodeRouteSegment, formatRuntimeDiagnosticError, getCapability, getViteHubErrorShape, hasCapability, isExecutionAuthority, isResolvable, isRuntimeDiagnostic, isSerializedResponse, isTraceContentAttributeKey, isViteHubError, noExecutionAuthority, normalizeExecutionAuthority, normalizeRuntimeDiagnosticError, registerPublicUrlAgentName, resetPublicUrlAgentNames, resolveCapabilityPolicy, resolvePublicUrl, resolveRuntimeValue, runRuntimePreflight, runtimeErrorDiagnostics, serializeResponse, startRuntimePreflight, toResponse, toResultError, traceEventsToOpenTelemetryLogRecords, traceEventsToOpenTelemetrySpans, unknownExecutionAuthority };
1
+ import { A as isResponse, B as isRuntimeDiagnostic, C as resolveRuntimeValue, D as detectHost, E as unknownExecutionAuthority, F as createSqlLeaseStore, H as createExecutionBudget, I as leaseTable, L as defineErrors, M as serializeResponse, N as toResponse, O as getHostBinding, P as createMemoryLeaseStore, R as toResultError, S as resolveCapabilityPolicy, T as traceEventsToOpenTelemetrySpans, U as isExecutionBudgetExceededError, V as normalizeRuntimeDiagnosticError, W as isTraceContentAttributeKey, _ as hasCapability, b as noExecutionAuthority, d as createRuntimeWaitUntilController, f as createTraceEventLog, g as getCapability, h as emitTraceEvent, i as getStandardContext, j as isSerializedResponse, k as deserializeResponse, l as createExecutionContext, m as deriveTraceRuns, p as defineCapability, r as getRuntimeContext, u as createRuntimeContext, v as isExecutionAuthority, w as traceEventsToOpenTelemetryLogRecords, x as normalizeExecutionAuthority, y as isResolvable, z as formatRuntimeDiagnosticError } from "./request-context-CP9NhgLL.js";
2
+ import { t as runtimeErrorDiagnostics } from "./error-diagnostics-BKICpwZp.js";
3
+ import { n as getViteHubErrorShape, r as isViteHubError, t as ViteHubError } from "./errors-BEomN3fX.js";
4
+ import { a as hostedConsoleOrigin, c as normalizeConsoleProjectUrl, i as resolvePublicUrl, l as decodeRouteSegment, o as hostedConsoleUrl, s as normalizeConsolePath, t as consoleInvocationUrl, u as encodeRouteSegment } from "./public-url-B6x0HMgY.js";
5
+ export { ViteHubError, consoleInvocationUrl, createExecutionBudget, createExecutionContext, createMemoryLeaseStore, createRuntimeContext, createRuntimeWaitUntilController, createSqlLeaseStore, createTraceEventLog, decodeRouteSegment, defineCapability, defineErrors, deriveTraceRuns, deserializeResponse, detectHost, emitTraceEvent, encodeRouteSegment, formatRuntimeDiagnosticError, getCapability, getHostBinding, getRuntimeContext, getStandardContext, getViteHubErrorShape, hasCapability, hostedConsoleOrigin, hostedConsoleUrl, isExecutionAuthority, isExecutionBudgetExceededError, isResolvable, isResponse, isRuntimeDiagnostic, isSerializedResponse, isTraceContentAttributeKey, isViteHubError, leaseTable, noExecutionAuthority, normalizeConsolePath, normalizeConsoleProjectUrl, normalizeExecutionAuthority, normalizeRuntimeDiagnosticError, resolveCapabilityPolicy, resolvePublicUrl, resolveRuntimeValue, runtimeErrorDiagnostics, serializeResponse, toResponse, toResultError, traceEventsToOpenTelemetryLogRecords, traceEventsToOpenTelemetrySpans, unknownExecutionAuthority };
@@ -0,0 +1,17 @@
1
+ //#region src/internal/drain.d.ts
2
+ /** The streams that `vitehub drain` writes to. */
3
+ export interface DrainOutput {
4
+ stderr: {
5
+ write: (chunk: string) => unknown;
6
+ };
7
+ stdout: {
8
+ write: (chunk: string) => unknown;
9
+ };
10
+ }
11
+ export declare const drainUsage = "vitehub drain MAINPID [STATUS_URL]";
12
+ /**
13
+ * `vitehub drain MAINPID [STATUS_URL]`: sends the drain signal to a running server and waits until its status endpoint
14
+ * reports `drained`. Returns 0 when it drained, 1 when it failed, and 2 for a usage error.
15
+ */
16
+ export declare function runDrain(args: readonly string[], output: DrainOutput): Promise<number>;
17
+ //#endregion
@@ -0,0 +1,75 @@
1
+ import { t as runtimeErrorDiagnostics } from "../error-diagnostics-BKICpwZp.js";
2
+ //#region src/internal/drain-process.ts
3
+ /** Check whether a process still exists without confusing access denial for exit. */
4
+ function isProcessRunning(pid) {
5
+ try {
6
+ process.kill(pid, 0);
7
+ return true;
8
+ } catch (error) {
9
+ try {
10
+ return typeof error === "object" && error !== null && "code" in error && error.code === "EPERM";
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+ }
16
+ /** Request a drain signal, allowing status polling when signal permission is denied. */
17
+ function signalProcess(pid) {
18
+ try {
19
+ process.kill(pid, "SIGUSR2");
20
+ return "signaled";
21
+ } catch (error) {
22
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EPERM") return "permission-denied";
23
+ throw error;
24
+ }
25
+ }
26
+ //#endregion
27
+ //#region src/internal/drain.ts
28
+ const drainUsage = "vitehub drain MAINPID [STATUS_URL]";
29
+ async function readStatus(statusUrl) {
30
+ try {
31
+ const response = await fetch(statusUrl, { signal: AbortSignal.timeout(5e3) });
32
+ if (!response.ok) {
33
+ await response.body?.cancel();
34
+ return "unavailable";
35
+ }
36
+ const body = await response.json();
37
+ const status = body && typeof body === "object" ? body.status : void 0;
38
+ return status === "accepting" || status === "drained" || status === "draining" || status === "failed" ? status : "invalid";
39
+ } catch {
40
+ return "unavailable";
41
+ }
42
+ }
43
+ /**
44
+ * `vitehub drain MAINPID [STATUS_URL]`: sends the drain signal to a running server and waits until its status endpoint
45
+ * reports `drained`. Returns 0 when it drained, 1 when it failed, and 2 for a usage error.
46
+ */
47
+ async function runDrain(args, output) {
48
+ const [pidInput, statusInput] = args;
49
+ if (pidInput === "-h" || pidInput === "--help") {
50
+ output.stdout.write(`Usage: ${drainUsage}\n`);
51
+ return 0;
52
+ }
53
+ const pid = Number(pidInput);
54
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
55
+ output.stderr.write(`usage: ${drainUsage}\n`);
56
+ return 2;
57
+ }
58
+ const statusUrl = statusInput || "http://127.0.0.1:3000/api/drain";
59
+ try {
60
+ let signalAttempted = false;
61
+ while (isProcessRunning(pid)) {
62
+ const status = await readStatus(statusUrl);
63
+ if (status === "failed" || status === "invalid") throw runtimeErrorDiagnostics.RUNTIME_R0004({ message: `Process drain reported ${status}.` });
64
+ if (status === "drained") return 0;
65
+ if (status === "accepting" && !signalAttempted) signalAttempted = signalProcess(pid) === "signaled";
66
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
67
+ }
68
+ throw runtimeErrorDiagnostics.RUNTIME_R0005({ message: `Process ${pid} exited before drain completed.` });
69
+ } catch (error) {
70
+ output.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
71
+ return 1;
72
+ }
73
+ }
74
+ //#endregion
75
+ export { drainUsage, runDrain };
@@ -1,4 +1,4 @@
1
- import { t as ExecutionBudget } from "../execution-budget-D8SwJE8_.js";
1
+ import { t as ExecutionBudget } from "../execution-budget-BPXbISEt.js";
2
2
  //#region src/internal/execution-budget.d.ts
3
3
  /** Internal context key used when a budget-owned tool is reused by another Invocation. */
4
4
  export declare const executionBudgetOverride: unique symbol;
@@ -1,5 +1,5 @@
1
- import { r as isRuntimeObject } from "../runtime-type-CgfU6SWl.js";
2
- import { t as ViteHubError } from "../errors-CbqHQTvn.js";
1
+ import { r as isRuntimeObject } from "../runtime-type-BftydMAf.js";
2
+ import { t as ViteHubError } from "../errors-BEomN3fX.js";
3
3
  //#region src/internal/grant.ts
4
4
  /**
5
5
  * Define one kind of grant. Keep the definition module-private: the module that owns the check issues grants,
@@ -0,0 +1,42 @@
1
+ import { Cn as ViteHubStandardProps, Dt as sendPreparedResponse, Et as installRequestStandardContext, Sn as ViteHubRuntime, St as RuntimeContextOptions, xn as ViteHubContext, xt as RequestRuntimeContext } from "../index-Bcl-Hr-a.js";
2
+ import { EventHandlerRequest } from "h3";
3
+ //#region src/internal/h3.d.ts
4
+ declare module "h3" {
5
+ interface H3Event<_RequestT extends EventHandlerRequest = EventHandlerRequest> {
6
+ /** Set by ViteHub for each request until H3 implements Standard Context. */
7
+ readonly "~standard": ViteHubStandardProps;
8
+ }
9
+ }
10
+ export type H3RuntimeContextOptions = RuntimeContextOptions;
11
+ /**
12
+ * A request event without Standard Context types, such as the event of a `nuxt/server` handler: a web Request and the
13
+ * response that the host prepares. `installStandardContext()` sets `~standard` on it.
14
+ */
15
+ export interface HostRequestEvent {
16
+ readonly req: Request;
17
+ readonly res: {
18
+ status?: number;
19
+ readonly headers: Headers;
20
+ };
21
+ }
22
+ export type H3RuntimeContext<TOptions extends H3RuntimeContextOptions = {}> = RequestRuntimeContext<TOptions>;
23
+ /**
24
+ * Set `event["~standard"]` on an H3 2 event. A value that the host set stays. ViteHub also sets the same value on
25
+ * `event.req`, so a Fetchable handler that receives only the Request reads the same Standard
26
+ * Context, and H3 adds the headers that primitives set to the Response that the handler returns.
27
+ * ViteHub calls this for each request in a Nitro `request` hook. Call it yourself only for an event that
28
+ * Nitro did not create, such as in a test. Throws `RUNTIME_R0015` when the event has no request.
29
+ * H3 does not set `~standard` itself yet (https://github.com/h3js/h3/issues/1658).
30
+ */
31
+ export declare function installStandardContext<T extends object>(event: T): asserts event is T & ViteHubContext;
32
+ /**
33
+ * Return the Standard Context of an H3 event or a web Request. ViteHub primitives read request events through this
34
+ * function. It sets Standard Context first when Nitro did not, such as for an H3 app without the ViteHub Vite plugin
35
+ * or an event in a test. Throws `RUNTIME_R0015` when the event has no request.
36
+ */
37
+ export declare function getStandardContext(value: Request | ViteHubContext): ViteHubStandardProps;
38
+ /** Adapt one request. Pass an H3 event or a web Request. Await flushWaitUntil when the host has no lifetime API. */
39
+ export declare function getRuntimeContext(value: Request | ViteHubContext): H3RuntimeContext;
40
+ export declare function getRuntimeContext<const TOptions extends H3RuntimeContextOptions>(value: Request | ViteHubContext, options: TOptions): H3RuntimeContext<TOptions>;
41
+ //#endregion
42
+ export { type ViteHubContext, type ViteHubRuntime, type ViteHubStandardProps, installRequestStandardContext, sendPreparedResponse };
@@ -0,0 +1,181 @@
1
+ import { G as activeEnvStorageKey, J as ownObject, K as cloudflareOwners, Y as ownValue, a as installRequestStandardContext, c as sendPreparedResponse, i as getStandardContext$1, n as firstAddress, o as isHostRequest, q as getCloudflareEnv, s as requestAddressPaths, t as createStandardRuntimeContext } from "../request-context-CP9NhgLL.js";
2
+ import { t as runtimeErrorDiagnostics } from "../error-diagnostics-BKICpwZp.js";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ //#region ../internal/dist/runtime/cloudflare-env.js
5
+ const runtimeGlobal = globalThis;
6
+ runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
7
+ /** Return the Cloudflare Worker execution context of a request event, if the host provides one. */
8
+ function getCloudflareExecutionContext(event) {
9
+ for (const owner of cloudflareOwners(ownObject(event))) {
10
+ const context = ownObject(ownValue(owner, "context"));
11
+ if (context) return context;
12
+ }
13
+ }
14
+ function resolveWaitUntil(event, options = {}) {
15
+ const target = ownObject(event);
16
+ const context = ownObject(ownValue(target, "context"));
17
+ const cloudflare = ownObject(ownValue(context, "cloudflare"));
18
+ const cloudflareContext = ownObject(ownValue(cloudflare, "context"));
19
+ const platform = ownObject(ownValue(context, "_platform"));
20
+ const platformCloudflare = ownObject(ownValue(platform, "cloudflare"));
21
+ const platformCloudflareContext = ownObject(ownValue(platformCloudflare, "context"));
22
+ const req = ownObject(ownValue(target, "req"));
23
+ const reqRuntime = ownObject(ownValue(req, "runtime"));
24
+ const reqCloudflare = ownObject(ownValue(reqRuntime, "cloudflare"));
25
+ const hosts = [
26
+ context,
27
+ cloudflare,
28
+ cloudflareContext,
29
+ platformCloudflare,
30
+ platformCloudflareContext,
31
+ req,
32
+ reqCloudflare,
33
+ ownObject(ownValue(reqCloudflare, "context"))
34
+ ];
35
+ const owners = options.preferHost ? [...hosts, target] : [target, ...hosts];
36
+ for (const owner of owners) {
37
+ const waitUntil = ownValue(owner, "waitUntil");
38
+ if (typeof waitUntil === "function") return waitUntil.bind(owner);
39
+ }
40
+ }
41
+ //#endregion
42
+ //#region src/internal/h3.ts
43
+ /** H3 2 uses separate headers for returned error Responses. Mirror only Standard Context writes to both. */
44
+ function responseHeaders(target) {
45
+ const { headers, errHeaders } = target;
46
+ if (!errHeaders) return headers;
47
+ const view = new Headers();
48
+ const methods = {
49
+ append(name, value) {
50
+ headers.append(name, value);
51
+ errHeaders.append(name, value);
52
+ },
53
+ delete(name) {
54
+ headers.delete(name);
55
+ errHeaders.delete(name);
56
+ },
57
+ entries: headers.entries.bind(headers),
58
+ forEach(callback, thisArg) {
59
+ headers.forEach((value, key) => callback.call(thisArg, value, key, view));
60
+ },
61
+ get: headers.get.bind(headers),
62
+ getSetCookie: headers.getSetCookie.bind(headers),
63
+ has: headers.has.bind(headers),
64
+ keys: headers.keys.bind(headers),
65
+ set(name, value) {
66
+ headers.set(name, value);
67
+ errHeaders.set(name, value);
68
+ },
69
+ values: headers.values.bind(headers),
70
+ [Symbol.iterator]: headers[Symbol.iterator].bind(headers)
71
+ };
72
+ return Object.assign(view, methods);
73
+ }
74
+ /** Map Standard Context response fields to the response that H3 sends. H3 sends the value the handler returns as the body. */
75
+ function preparedResponse(target) {
76
+ const headers = responseHeaders(target);
77
+ return {
78
+ get body() {},
79
+ set body(_value) {
80
+ throw runtimeErrorDiagnostics.RUNTIME_R0016({ message: "[vitehub] H3 does not read `~standard.res.body`. Return the body or a Response from the handler." });
81
+ },
82
+ get headers() {
83
+ return headers;
84
+ },
85
+ set headers(value) {
86
+ for (const name of Array.from(headers.keys())) headers.delete(name);
87
+ for (const [name, item] of value ?? []) headers.append(name, item);
88
+ },
89
+ get status() {
90
+ return target.status;
91
+ },
92
+ set status(value) {
93
+ target.status = value;
94
+ }
95
+ };
96
+ }
97
+ /**
98
+ * The `~standard` properties of one H3 event. Each property reads the event on first access and keeps the value,
99
+ * because most requests never read Standard Context and ViteHub sets it on every request.
100
+ */
101
+ var H3StandardProps = class {
102
+ vendor = "h3";
103
+ #event;
104
+ #request;
105
+ #res;
106
+ #runtime;
107
+ #waitUntil;
108
+ constructor(event, request) {
109
+ this.#event = event;
110
+ this.#request = request;
111
+ }
112
+ get req() {
113
+ return this.#request;
114
+ }
115
+ get res() {
116
+ return this.#res ??= preparedResponse(Reflect.get(this.#event, "res"));
117
+ }
118
+ get runtime() {
119
+ if (this.#runtime) return this.#runtime;
120
+ const env = getCloudflareEnv(this.#event, { fallback: false });
121
+ const context = getCloudflareExecutionContext(this.#event);
122
+ const clientAddress = firstAddress(this.#request, requestAddressPaths);
123
+ return this.#runtime = {
124
+ ...env || context ? { cloudflare: {
125
+ ...env ? { env } : {},
126
+ ...context ? { context } : {}
127
+ } } : {},
128
+ ...clientAddress ? { clientAddress } : {}
129
+ };
130
+ }
131
+ get waitUntil() {
132
+ if (this.#waitUntil === void 0) this.#waitUntil = resolveWaitUntil(this.#event, { preferHost: true }) ?? null;
133
+ return this.#waitUntil ?? void 0;
134
+ }
135
+ };
136
+ function createH3StandardProps(event) {
137
+ const req = Object.hasOwn(event, "req") ? Reflect.get(event, "req") : void 0;
138
+ return isHostRequest(req) && "res" in event ? new H3StandardProps(event, req) : void 0;
139
+ }
140
+ /**
141
+ * Set `event["~standard"]` on an H3 2 event. A value that the host set stays. ViteHub also sets the same value on
142
+ * `event.req`, so a Fetchable handler that receives only the Request reads the same Standard
143
+ * Context, and H3 adds the headers that primitives set to the Response that the handler returns.
144
+ * ViteHub calls this for each request in a Nitro `request` hook. Call it yourself only for an event that
145
+ * Nitro did not create, such as in a test. Throws `RUNTIME_R0015` when the event has no request.
146
+ * H3 does not set `~standard` itself yet (https://github.com/h3js/h3/issues/1658).
147
+ */
148
+ function installStandardContext(event) {
149
+ if (!("~standard" in event)) {
150
+ const props = createH3StandardProps(event);
151
+ if (!props) throw runtimeErrorDiagnostics.RUNTIME_R0015({ message: "[vitehub] The event has no request, so ViteHub cannot set `~standard`. Pass the event of an H3 or Nitro route." });
152
+ Object.defineProperty(event, "~standard", {
153
+ configurable: true,
154
+ enumerable: false,
155
+ value: props
156
+ });
157
+ }
158
+ const req = Object.hasOwn(event, "req") ? Reflect.get(event, "req") : void 0;
159
+ if (isHostRequest(req)) installRequestStandardContext(req, Reflect.get(event, "~standard"));
160
+ }
161
+ /**
162
+ * Return the Standard Context of an H3 event or a web Request. ViteHub primitives read request events through this
163
+ * function. It sets Standard Context first when Nitro did not, such as for an H3 app without the ViteHub Vite plugin
164
+ * or an event in a test. Throws `RUNTIME_R0015` when the event has no request.
165
+ */
166
+ function getStandardContext(value) {
167
+ if (isHostRequest(value)) return getStandardContext$1(value);
168
+ installStandardContext(value);
169
+ return value["~standard"];
170
+ }
171
+ function getRuntimeContext(value, options = {}) {
172
+ if (isHostRequest(value)) return createStandardRuntimeContext(value, getStandardContext$1(value), options);
173
+ if (!value["~standard"]) try {
174
+ installStandardContext(value);
175
+ } catch (error) {
176
+ if (options.request === void 0 || error?.name !== "RUNTIME_R0015") throw error;
177
+ }
178
+ return createStandardRuntimeContext(value, value["~standard"], options);
179
+ }
180
+ //#endregion
181
+ export { getRuntimeContext, getStandardContext, installRequestStandardContext, installStandardContext, sendPreparedResponse };
@@ -1,5 +1,5 @@
1
- import { Nt as RuntimeResourceInspector } from "./index-Rl4DbP8B.js";
2
- //#region src/node.d.ts
1
+ import { Bt as RuntimeResourceInspector } from "../index-Bcl-Hr-a.js";
2
+ //#region src/internal/node.d.ts
3
3
  type ReadText = (path: string, options?: {
4
4
  signal?: AbortSignal;
5
5
  }) => Promise<string>;
@@ -1,9 +1,9 @@
1
- import { i as runtimeErrorDiagnostics, n as hasRuntimeType } from "./runtime-type-CgfU6SWl.js";
1
+ import { t as runtimeErrorDiagnostics } from "../error-diagnostics-BKICpwZp.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { availableMemory, memoryUsage, resourceUsage } from "node:process";
6
- //#region src/node.ts
6
+ //#region src/internal/node.ts
7
7
  function observation(name, value, scope, source, unit) {
8
8
  return value === void 0 || !Number.isFinite(value) ? [] : [{
9
9
  name,
@@ -21,9 +21,9 @@ async function readResult(readText, path, signal) {
21
21
  }
22
22
  }
23
23
  function readErrorCode(error) {
24
- if (!error || !hasRuntimeType(error, "object")) return;
24
+ if (!error || typeof error !== "object") return;
25
25
  try {
26
- return hasRuntimeType(error.code, "string") ? error.code : void 0;
26
+ return typeof error.code === "string" ? error.code : void 0;
27
27
  } catch {
28
28
  return;
29
29
  }
@@ -0,0 +1,2 @@
1
+ import { i as resetPublicUrlAgentNames, r as registerPublicUrlAgentName } from "../public-url-1WeOw54Z.js";
2
+ export { registerPublicUrlAgentName, resetPublicUrlAgentNames };
@@ -0,0 +1,2 @@
1
+ import { n as registerPublicUrlAgentName, r as resetPublicUrlAgentNames } from "../public-url-B6x0HMgY.js";
2
+ export { registerPublicUrlAgentName, resetPublicUrlAgentNames };
@@ -0,0 +1,11 @@
1
+ //#region src/internal/run-scope.d.ts
2
+ /** Wraps one unit of work, such as a Schedule run or a Queue job. It calls `run` once and passes on its error. */
3
+ export type RunScope = (run: () => Promise<void>) => Promise<unknown>;
4
+ /**
5
+ * Adds a scope that wraps each Schedule run and Queue job. Workspace adds one, so a run that throws drops the writes it
6
+ * staged in a cached Store. Adding the same scope again does nothing.
7
+ */
8
+ export declare function registerRunScope(scope: RunScope): void;
9
+ /** Runs one Schedule run or Queue job inside every registered scope. A Nitro request gets its scopes from middleware. */
10
+ export declare function runInRunScopes<T>(run: () => T | Promise<T>): Promise<T>;
11
+ //#endregion
@@ -0,0 +1,30 @@
1
+ //#region src/internal/run-scope.ts
2
+ const scopesKey = Symbol.for("vitehub.runtime.runScopes");
3
+ function scopes() {
4
+ const runtimeGlobal = globalThis;
5
+ return runtimeGlobal[scopesKey] ??= /* @__PURE__ */ new Set();
6
+ }
7
+ /**
8
+ * Adds a scope that wraps each Schedule run and Queue job. Workspace adds one, so a run that throws drops the writes it
9
+ * staged in a cached Store. Adding the same scope again does nothing.
10
+ */
11
+ function registerRunScope(scope) {
12
+ scopes().add(scope);
13
+ }
14
+ /** Runs one Schedule run or Queue job inside every registered scope. A Nitro request gets its scopes from middleware. */
15
+ async function runInRunScopes(run) {
16
+ let result;
17
+ let next = async () => {
18
+ result = await run();
19
+ };
20
+ for (const scope of scopes()) {
21
+ const inner = next;
22
+ next = async () => {
23
+ await scope(inner);
24
+ };
25
+ }
26
+ await next();
27
+ return result;
28
+ }
29
+ //#endregion
30
+ export { registerRunScope, runInRunScopes };
@@ -1,4 +1,4 @@
1
- import { t as runtimeErrorDiagnostics } from "../error-diagnostics-Bkym4e6y.js";
1
+ import { t as runtimeErrorDiagnostics } from "../error-diagnostics-BsJr9VdW.js";
2
2
  //#region src/internal/runtime-type.d.ts
3
3
  type RuntimeTypeMap = {
4
4
  bigint: bigint;
@@ -10,10 +10,17 @@ type RuntimeTypeMap = {
10
10
  symbol: symbol;
11
11
  undefined: undefined;
12
12
  };
13
- /** Narrows opaque inputs without reading their properties. */
13
+ /** Narrows opaque inputs without reading their properties. Kept for `@vite-hub/presets`; other packages use `typeof`. */
14
14
  export declare function hasRuntimeType<TType extends keyof RuntimeTypeMap>(value: unknown, expected: TType): value is RuntimeTypeMap[TType];
15
15
  /** Marks an intentional structural boundary that TypeScript cannot express. */
16
16
  export declare function asUnknownBoundary(value: unknown): unknown;
17
17
  export declare function isRuntimeObject(value: unknown): value is object;
18
+ /**
19
+ * Return whether `value` is a Response of this runtime: of the native class, or of the class that the server installed
20
+ * as the global `Response`.
21
+ * The `status` getter checks the internal Response slot, so a copied prototype, an object tagged `Response`,
22
+ * and a Response from another Fetch implementation all fail. A proxy fails too. The check reads no property of `value`.
23
+ */
24
+ export declare function isRuntimeResponse(value: unknown): value is Response;
18
25
  //#endregion
19
26
  export { runtimeErrorDiagnostics };
@@ -1,2 +1,3 @@
1
- import { i as runtimeErrorDiagnostics, n as hasRuntimeType, r as isRuntimeObject, t as asUnknownBoundary } from "../runtime-type-CgfU6SWl.js";
2
- export { asUnknownBoundary, hasRuntimeType, isRuntimeObject, runtimeErrorDiagnostics };
1
+ import { t as runtimeErrorDiagnostics } from "../error-diagnostics-BKICpwZp.js";
2
+ import { i as isRuntimeResponse, n as hasRuntimeType, r as isRuntimeObject, t as asUnknownBoundary } from "../runtime-type-BftydMAf.js";
3
+ export { asUnknownBoundary, hasRuntimeType, isRuntimeObject, isRuntimeResponse, runtimeErrorDiagnostics };
@@ -1,4 +1,4 @@
1
- //#region src/shutdown.d.ts
1
+ //#region src/internal/shutdown.d.ts
2
2
  /**
3
3
  * Graceful shutdown that ViteHub owns.
4
4
  *
@@ -1,4 +1,4 @@
1
- //#region src/shutdown.ts
1
+ //#region src/internal/shutdown.ts
2
2
  /** Name of the variable that sets the shared drain budget in milliseconds. The default is 0. */
3
3
  const shutdownDrainEnv = "VITEHUB_SHUTDOWN_DRAIN_MS";
4
4
  /** Time that a drain gets after the budget ends to finish its abort, such as a restart notice. */
@@ -0,0 +1,7 @@
1
+ import { ViteHubTestMode } from "./test-mode.js";
2
+ //#region src/internal/test-mode-setup.d.ts
3
+ /** Turns test mode on for this process, or returns the active one. */
4
+ export declare function enableViteHubTestMode(options?: {
5
+ root?: string;
6
+ }): ViteHubTestMode;
7
+ //#endregion
@@ -0,0 +1,114 @@
1
+ import { viteHubTestModeKey } from "./test-mode.js";
2
+ //#region src/internal/test-mode-setup.ts
3
+ const processRoots = /* @__PURE__ */ new Map();
4
+ function isRunning(pid) {
5
+ try {
6
+ process.kill(pid, 0);
7
+ return true;
8
+ } catch (error) {
9
+ return error.code === "EPERM";
10
+ }
11
+ }
12
+ /**
13
+ * One folder per test process under `<root>/.vitehub/test`. A test runner can stop its workers without an exit event,
14
+ * so each process also deletes the folders of processes that no longer run.
15
+ */
16
+ function processTemporaryRoot(root) {
17
+ const existing = processRoots.get(root);
18
+ if (existing) return existing;
19
+ const processRoot = (async () => {
20
+ const [{ rmSync }, { mkdir, mkdtemp, readdir, rm }, { join }] = await Promise.all([
21
+ import("node:fs"),
22
+ import("node:fs/promises"),
23
+ import("node:path")
24
+ ]);
25
+ const parent = join(root, ".vitehub", "test");
26
+ await mkdir(parent, { recursive: true });
27
+ for (const name of await readdir(parent)) {
28
+ const pid = Number(name.split("-")[0]);
29
+ if (Number.isInteger(pid) && pid !== process.pid && !isRunning(pid)) await rm(join(parent, name), {
30
+ force: true,
31
+ recursive: true
32
+ });
33
+ }
34
+ const directory = await mkdtemp(join(parent, `${process.pid}-`));
35
+ process.once("exit", () => rmSync(directory, {
36
+ force: true,
37
+ recursive: true
38
+ }));
39
+ return directory;
40
+ })();
41
+ processRoots.set(root, processRoot);
42
+ return processRoot;
43
+ }
44
+ function createViteHubTestMode(root) {
45
+ const env = {};
46
+ let backends = /* @__PURE__ */ new Map();
47
+ let temporaryRoot;
48
+ function backend(key, create, dispose) {
49
+ const existing = backends.get(key);
50
+ if (existing) return existing.value;
51
+ const value = create();
52
+ backends.set(key, {
53
+ dispose,
54
+ value
55
+ });
56
+ return value;
57
+ }
58
+ function peek(key) {
59
+ return backends.get(key)?.value;
60
+ }
61
+ return {
62
+ env,
63
+ root,
64
+ backend,
65
+ peek,
66
+ async directory(key) {
67
+ temporaryRoot ??= (async () => {
68
+ const [{ mkdtemp }, { join }] = await Promise.all([import("node:fs/promises"), import("node:path")]);
69
+ return await mkdtemp(join(await processTemporaryRoot(root), "test-"));
70
+ })();
71
+ const [{ createHash }, { mkdir }, { join }] = await Promise.all([
72
+ import("node:crypto"),
73
+ import("node:fs/promises"),
74
+ import("node:path")
75
+ ]);
76
+ const directory = join(await temporaryRoot, createHash("sha256").update(key).digest("hex"));
77
+ await mkdir(directory, { recursive: true });
78
+ return directory;
79
+ },
80
+ async reset() {
81
+ const previous = backends;
82
+ const previousRoot = temporaryRoot;
83
+ backends = /* @__PURE__ */ new Map();
84
+ temporaryRoot = void 0;
85
+ for (const name of Object.keys(env)) delete env[name];
86
+ const failures = [];
87
+ for (const { dispose, value } of previous.values()) try {
88
+ await dispose?.(await value);
89
+ } catch (error) {
90
+ failures.push(error);
91
+ }
92
+ if (previousRoot) {
93
+ const { rm } = await import("node:fs/promises");
94
+ await rm(await previousRoot, {
95
+ force: true,
96
+ recursive: true
97
+ });
98
+ }
99
+ if (failures.length) throw new AggregateError(failures, "[vitehub] A test backend failed to close.");
100
+ }
101
+ };
102
+ }
103
+ /** Turns test mode on for this process, or returns the active one. */
104
+ function enableViteHubTestMode(options = {}) {
105
+ const target = globalThis;
106
+ const root = options.root ?? (typeof process === "object" ? process.cwd() : "/");
107
+ const existing = target[viteHubTestModeKey];
108
+ if (existing && existing.root === root) return existing;
109
+ const mode = createViteHubTestMode(root);
110
+ target[viteHubTestModeKey] = mode;
111
+ return mode;
112
+ }
113
+ //#endregion
114
+ export { enableViteHubTestMode };