@vite-hub/runtime 0.0.4 → 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.
- package/README.md +278 -41
- package/dist/durability.d.ts +107 -0
- package/dist/durability.js +168 -0
- package/dist/error-diagnostics-BKICpwZp.js +85 -0
- package/dist/error-diagnostics-BsJr9VdW.d.ts +15 -0
- package/dist/errors-BEomN3fX.js +190 -0
- package/dist/execution-budget-BPXbISEt.d.ts +56 -0
- package/dist/index-Bcl-Hr-a.d.ts +678 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.js +5 -1159
- package/dist/internal/drain.d.ts +17 -0
- package/dist/internal/drain.js +75 -0
- package/dist/internal/execution-budget.d.ts +10 -0
- package/dist/internal/execution-budget.js +17 -0
- package/dist/internal/grant.d.ts +36 -0
- package/dist/internal/grant.js +44 -0
- package/dist/internal/h3.d.ts +42 -0
- package/dist/internal/h3.js +181 -0
- package/dist/internal/node.d.ts +33 -0
- package/dist/{node.js → internal/node.js} +12 -9
- package/dist/internal/public-url.d.ts +2 -0
- package/dist/internal/public-url.js +2 -0
- package/dist/internal/run-scope.d.ts +11 -0
- package/dist/internal/run-scope.js +30 -0
- package/dist/internal/runtime-type.d.ts +26 -0
- package/dist/internal/runtime-type.js +3 -0
- package/dist/internal/shutdown.d.ts +84 -0
- package/dist/internal/shutdown.js +202 -0
- package/dist/internal/test-mode-setup.d.ts +7 -0
- package/dist/internal/test-mode-setup.js +114 -0
- package/dist/internal/test-mode.d.ts +32 -0
- package/dist/internal/test-mode.js +9 -0
- package/dist/operations.d.ts +167 -0
- package/dist/operations.js +406 -0
- package/dist/public-url-1WeOw54Z.d.ts +34 -0
- package/dist/public-url-B6x0HMgY.js +140 -0
- package/dist/request-context-CP9NhgLL.js +2274 -0
- package/dist/runtime-type-BftydMAf.js +88 -0
- package/package.json +92 -17
- package/dist/drain.d.ts +0 -1
- package/dist/drain.js +0 -52
- package/dist/index-tBKyUP1T.d.ts +0 -314
- package/dist/node.d.ts +0 -35
- package/dist/runtime-type-ovvOd6m5.js +0 -37
|
@@ -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 };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { t as ExecutionBudget } from "../execution-budget-BPXbISEt.js";
|
|
2
|
+
//#region src/internal/execution-budget.d.ts
|
|
3
|
+
/** Internal context key used when a budget-owned tool is reused by another Invocation. */
|
|
4
|
+
export declare const executionBudgetOverride: unique symbol;
|
|
5
|
+
/** Internal context key used when a policy wrapper already charged a call. */
|
|
6
|
+
export declare const executionBudgetCharged: unique symbol;
|
|
7
|
+
export declare function markExecutionBudgetHandled(tool: object, budget: ExecutionBudget): void;
|
|
8
|
+
export declare function isExecutionBudgetHandled(tool: object, budget: ExecutionBudget): boolean;
|
|
9
|
+
export declare function executionBudgetHandledBy(tool: object): ExecutionBudget | undefined;
|
|
10
|
+
//#endregion
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//#region src/internal/execution-budget.ts
|
|
2
|
+
const budgetHandledTools = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
/** Internal context key used when a budget-owned tool is reused by another Invocation. */
|
|
4
|
+
const executionBudgetOverride = Symbol("vitehub.execution-budget-override");
|
|
5
|
+
/** Internal context key used when a policy wrapper already charged a call. */
|
|
6
|
+
const executionBudgetCharged = Symbol("vitehub.execution-budget-charged");
|
|
7
|
+
function markExecutionBudgetHandled(tool, budget) {
|
|
8
|
+
budgetHandledTools.set(tool, budget);
|
|
9
|
+
}
|
|
10
|
+
function isExecutionBudgetHandled(tool, budget) {
|
|
11
|
+
return budgetHandledTools.get(tool) === budget;
|
|
12
|
+
}
|
|
13
|
+
function executionBudgetHandledBy(tool) {
|
|
14
|
+
return budgetHandledTools.get(tool);
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { executionBudgetCharged, executionBudgetHandledBy, executionBudgetOverride, isExecutionBudgetHandled, markExecutionBudgetHandled };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/internal/grant.d.ts
|
|
2
|
+
declare const grantKind: unique symbol;
|
|
3
|
+
/**
|
|
4
|
+
* Proof that one check passed. Only the definition that issued it can verify it.
|
|
5
|
+
* The `Kind` brand is type-only. It keeps grants of different definitions apart at type level.
|
|
6
|
+
*/
|
|
7
|
+
export interface Grant<Kind extends string> {
|
|
8
|
+
readonly [grantKind]: Kind;
|
|
9
|
+
}
|
|
10
|
+
export interface GrantDefinition<Kind extends string, Input, Value> {
|
|
11
|
+
readonly kind: Kind;
|
|
12
|
+
/** Issue a frozen grant bound to `bind(input)`. `fields` become public read-only fields of the grant. */
|
|
13
|
+
issue: {
|
|
14
|
+
(input: Input): Grant<Kind>;
|
|
15
|
+
<Fields extends object>(input: Input, fields: Fields): Grant<Kind> & Readonly<Fields>;
|
|
16
|
+
};
|
|
17
|
+
/** Return the bound value, or `undefined` for a forged, consumed, or foreign value. Never throws. */
|
|
18
|
+
check: (candidate: unknown) => Value | undefined;
|
|
19
|
+
/** Return whether this definition issued the candidate and it has not been consumed. Never throws. */
|
|
20
|
+
isValid: (candidate: unknown) => boolean;
|
|
21
|
+
/** Return the bound value. Throws `GRANT_REQUIRED` when this definition did not issue the grant, or it was consumed. */
|
|
22
|
+
verify: (grant: Grant<Kind>) => Value;
|
|
23
|
+
/** Verify the grant and revoke it, so it works only once. */
|
|
24
|
+
consume: (grant: Grant<Kind>) => Value;
|
|
25
|
+
/** Attach a valid grant to an owner object, for example a request or a context. */
|
|
26
|
+
attach: (owner: WeakKey, grant: Grant<Kind>) => void;
|
|
27
|
+
/** Return the grant attached to `owner`, or `undefined` when there is none or it was consumed. */
|
|
28
|
+
attached: (owner: WeakKey) => Grant<Kind> | undefined;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Define one kind of grant. Keep the definition module-private: the module that owns the check issues grants,
|
|
32
|
+
* and the sensitive action verifies them. Each definition has its own registry, so a grant from another definition,
|
|
33
|
+
* another bundled copy, or a forged object fails closed. Grants are request-scoped. Never persist one.
|
|
34
|
+
*/
|
|
35
|
+
export declare function defineGrant<const Kind extends string, Input, Value>(kind: Kind, bind: (input: Input) => Value): GrantDefinition<Kind, Input, Value>;
|
|
36
|
+
//#endregion
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { r as isRuntimeObject } from "../runtime-type-BftydMAf.js";
|
|
2
|
+
import { t as ViteHubError } from "../errors-BEomN3fX.js";
|
|
3
|
+
//#region src/internal/grant.ts
|
|
4
|
+
/**
|
|
5
|
+
* Define one kind of grant. Keep the definition module-private: the module that owns the check issues grants,
|
|
6
|
+
* and the sensitive action verifies them. Each definition has its own registry, so a grant from another definition,
|
|
7
|
+
* another bundled copy, or a forged object fails closed. Grants are request-scoped. Never persist one.
|
|
8
|
+
*/
|
|
9
|
+
function defineGrant(kind, bind) {
|
|
10
|
+
const issued = /* @__PURE__ */ new WeakMap();
|
|
11
|
+
const owners = /* @__PURE__ */ new WeakMap();
|
|
12
|
+
function issue(input, fields) {
|
|
13
|
+
const grant = Object.freeze({ ...fields });
|
|
14
|
+
issued.set(grant, Object.freeze({ value: bind(input) }));
|
|
15
|
+
return grant;
|
|
16
|
+
}
|
|
17
|
+
function verify(grant) {
|
|
18
|
+
const entry = issued.get(grant);
|
|
19
|
+
if (!entry) throw new ViteHubError("GRANT_REQUIRED", `[vitehub] This action requires a valid "${kind}" grant.`, { details: { kind } });
|
|
20
|
+
return entry.value;
|
|
21
|
+
}
|
|
22
|
+
return Object.freeze({
|
|
23
|
+
kind,
|
|
24
|
+
issue,
|
|
25
|
+
check: (candidate) => isRuntimeObject(candidate) ? issued.get(candidate)?.value : void 0,
|
|
26
|
+
verify,
|
|
27
|
+
consume: (grant) => {
|
|
28
|
+
const value = verify(grant);
|
|
29
|
+
issued.delete(grant);
|
|
30
|
+
return value;
|
|
31
|
+
},
|
|
32
|
+
isValid: (candidate) => isRuntimeObject(candidate) && issued.has(candidate),
|
|
33
|
+
attach: (owner, grant) => {
|
|
34
|
+
verify(grant);
|
|
35
|
+
owners.set(owner, grant);
|
|
36
|
+
},
|
|
37
|
+
attached: (owner) => {
|
|
38
|
+
const grant = owners.get(owner);
|
|
39
|
+
return grant && issued.has(grant) ? grant : void 0;
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { defineGrant };
|
|
@@ -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 };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Bt as RuntimeResourceInspector } from "../index-Bcl-Hr-a.js";
|
|
2
|
+
//#region src/internal/node.d.ts
|
|
3
|
+
type ReadText = (path: string, options?: {
|
|
4
|
+
signal?: AbortSignal;
|
|
5
|
+
}) => Promise<string>;
|
|
6
|
+
export interface NodeRuntimeResourceInspectorOptions {
|
|
7
|
+
now?: () => Date;
|
|
8
|
+
readText?: ReadText;
|
|
9
|
+
}
|
|
10
|
+
export declare function resolveLinuxCgroupV2Path(mountinfo: string, membership: string): string | undefined;
|
|
11
|
+
export declare function nodeRuntimeResources(options?: NodeRuntimeResourceInspectorOptions): RuntimeResourceInspector;
|
|
12
|
+
export type ProcessReconcilerStatus = "accepting" | "drained" | "draining" | "failed";
|
|
13
|
+
export type ProcessReconcilerSignal = Exclude<NodeJS.Signals, "SIGKILL" | "SIGSTOP">;
|
|
14
|
+
export interface ProcessReconcilerRunContext {
|
|
15
|
+
track<T>(work: Promise<T>): Promise<T>;
|
|
16
|
+
}
|
|
17
|
+
export interface ProcessReconcilerOptions {
|
|
18
|
+
intervalMs: number;
|
|
19
|
+
onDrained?: () => Promise<void> | void;
|
|
20
|
+
onError?: (error: unknown, reason: string) => Promise<void> | void;
|
|
21
|
+
onQuiesce?: () => Promise<void> | void;
|
|
22
|
+
repairReason?: string;
|
|
23
|
+
run: (reason: string, context: ProcessReconcilerRunContext) => Promise<void> | void;
|
|
24
|
+
signal?: false | ProcessReconcilerSignal;
|
|
25
|
+
}
|
|
26
|
+
export interface ProcessReconciler extends ProcessReconcilerRunContext {
|
|
27
|
+
close: () => Promise<void>;
|
|
28
|
+
drain: () => Promise<void>;
|
|
29
|
+
status: () => ProcessReconcilerStatus;
|
|
30
|
+
wake: (reason: string) => void;
|
|
31
|
+
}
|
|
32
|
+
export declare function createProcessReconciler(options: ProcessReconcilerOptions): ProcessReconciler;
|
|
33
|
+
//#endregion
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { t as
|
|
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 ||
|
|
24
|
+
if (!error || typeof error !== "object") return;
|
|
25
25
|
try {
|
|
26
|
-
return
|
|
26
|
+
return typeof error.code === "string" ? error.code : void 0;
|
|
27
27
|
} catch {
|
|
28
28
|
return;
|
|
29
29
|
}
|
|
@@ -210,9 +210,9 @@ function nodeRuntimeResources(options = {}) {
|
|
|
210
210
|
} };
|
|
211
211
|
}
|
|
212
212
|
function createProcessReconciler(options) {
|
|
213
|
-
if (!Number.isFinite(options.intervalMs) || options.intervalMs < 1 || options.intervalMs > 2147483647) throw
|
|
213
|
+
if (!Number.isFinite(options.intervalMs) || options.intervalMs < 1 || options.intervalMs > 2147483647) throw runtimeErrorDiagnostics.RUNTIME_R0009({ message: "Process reconciler intervalMs must be between 1 and 2,147,483,647 milliseconds." });
|
|
214
214
|
const configuredSignal = options.signal;
|
|
215
|
-
if (configuredSignal === "SIGKILL" || configuredSignal === "SIGSTOP") throw
|
|
215
|
+
if (configuredSignal === "SIGKILL" || configuredSignal === "SIGSTOP") throw runtimeErrorDiagnostics.RUNTIME_R0010({ message: `Process reconciler signal ${configuredSignal} cannot be handled.` });
|
|
216
216
|
let closed = false;
|
|
217
217
|
let drainPromise;
|
|
218
218
|
let queued = false;
|
|
@@ -320,7 +320,7 @@ function createProcessReconciler(options) {
|
|
|
320
320
|
};
|
|
321
321
|
const drain = () => {
|
|
322
322
|
const caller = callbackContext.getStore();
|
|
323
|
-
if (caller && activeCallbacks.has(caller)) return Promise.reject(
|
|
323
|
+
if (caller && activeCallbacks.has(caller)) return Promise.reject(runtimeErrorDiagnostics.RUNTIME_R0011({ message: "Process reconciler callbacks cannot call drain() while active." }));
|
|
324
324
|
if (drainPromise) return drainPromise;
|
|
325
325
|
drainPromise = (async () => {
|
|
326
326
|
let failure;
|
|
@@ -383,8 +383,11 @@ function createProcessReconciler(options) {
|
|
|
383
383
|
scheduleRepair();
|
|
384
384
|
return {
|
|
385
385
|
async close() {
|
|
386
|
-
|
|
387
|
-
|
|
386
|
+
try {
|
|
387
|
+
await drain();
|
|
388
|
+
} finally {
|
|
389
|
+
if ((status === "drained" || status === "failed") && signal && listener) process.off(signal, listener);
|
|
390
|
+
}
|
|
388
391
|
},
|
|
389
392
|
drain,
|
|
390
393
|
status: () => status,
|
|
@@ -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 };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { t as runtimeErrorDiagnostics } from "../error-diagnostics-BsJr9VdW.js";
|
|
2
|
+
//#region src/internal/runtime-type.d.ts
|
|
3
|
+
type RuntimeTypeMap = {
|
|
4
|
+
bigint: bigint;
|
|
5
|
+
boolean: boolean;
|
|
6
|
+
function: CallableFunction;
|
|
7
|
+
number: number;
|
|
8
|
+
object: object | null;
|
|
9
|
+
string: string;
|
|
10
|
+
symbol: symbol;
|
|
11
|
+
undefined: undefined;
|
|
12
|
+
};
|
|
13
|
+
/** Narrows opaque inputs without reading their properties. Kept for `@vite-hub/presets`; other packages use `typeof`. */
|
|
14
|
+
export declare function hasRuntimeType<TType extends keyof RuntimeTypeMap>(value: unknown, expected: TType): value is RuntimeTypeMap[TType];
|
|
15
|
+
/** Marks an intentional structural boundary that TypeScript cannot express. */
|
|
16
|
+
export declare function asUnknownBoundary(value: unknown): unknown;
|
|
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;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { runtimeErrorDiagnostics };
|
|
@@ -0,0 +1,3 @@
|
|
|
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 };
|