@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,84 @@
|
|
|
1
|
+
//#region src/internal/shutdown.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Graceful shutdown that ViteHub owns.
|
|
4
|
+
*
|
|
5
|
+
* Each package registers its drain once with `onShutdown()`. On a stop signal, ViteHub runs
|
|
6
|
+
* every drain in parallel with one shared budget, then lets the server close HTTP, waits for
|
|
7
|
+
* Nitro `close` hooks, and exits the process once.
|
|
8
|
+
*/
|
|
9
|
+
export type ShutdownSignal = "SIGINT" | "SIGTERM";
|
|
10
|
+
export interface ShutdownDrainContext {
|
|
11
|
+
/** Aborts when the shared drain budget ends. */
|
|
12
|
+
signal: AbortSignal;
|
|
13
|
+
/** The shared drain budget in milliseconds. */
|
|
14
|
+
timeoutMs: number;
|
|
15
|
+
}
|
|
16
|
+
/** Stops new work and waits for active work. It gets the shared budget and an abort signal. */
|
|
17
|
+
export type ShutdownDrain = (context: ShutdownDrainContext) => unknown;
|
|
18
|
+
export interface ShutdownDrainResult {
|
|
19
|
+
durationMs: number;
|
|
20
|
+
error?: string;
|
|
21
|
+
name: string;
|
|
22
|
+
status: "drained" | "failed" | "timeout";
|
|
23
|
+
}
|
|
24
|
+
export interface ShutdownDrainEntry {
|
|
25
|
+
app: ShutdownApp;
|
|
26
|
+
drain: ShutdownDrain;
|
|
27
|
+
name: string;
|
|
28
|
+
result?: Promise<ShutdownDrainResult>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Process-wide shutdown state, kept on `process.__vitehubShutdown`. Read it to see the
|
|
32
|
+
* registered drains, the stop signal, and the drain results.
|
|
33
|
+
*/
|
|
34
|
+
export interface ShutdownState {
|
|
35
|
+
/** Nitro apps that already run their drains from a `close` hook. */
|
|
36
|
+
apps: WeakSet<ShutdownApp>;
|
|
37
|
+
entries: Set<ShutdownDrainEntry>;
|
|
38
|
+
results: ShutdownDrainResult[];
|
|
39
|
+
signal?: ShutdownSignal;
|
|
40
|
+
/** `true` when ViteHub handles SIGTERM and SIGINT for this process. */
|
|
41
|
+
signals: boolean;
|
|
42
|
+
status: "running" | "draining" | "exited";
|
|
43
|
+
/** Set once the stop signal handler is installed or skipped. */
|
|
44
|
+
trap?: "pending" | "installed" | "skipped";
|
|
45
|
+
}
|
|
46
|
+
/** The part of a Nitro app that the shutdown helper uses. */
|
|
47
|
+
export interface ShutdownApp {
|
|
48
|
+
hooks: {
|
|
49
|
+
hook(name: "close", callback: () => unknown): unknown;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** The part of `process` that the shutdown helper uses. Tests pass a replacement. */
|
|
53
|
+
export interface ShutdownRuntime {
|
|
54
|
+
__vitehubShutdown?: ShutdownState;
|
|
55
|
+
env: Record<string, string | undefined>;
|
|
56
|
+
exit(code: number): void;
|
|
57
|
+
kill?: (pid: number, signal: ShutdownSignal) => unknown;
|
|
58
|
+
listeners(signal: ShutdownSignal): unknown[];
|
|
59
|
+
off(signal: ShutdownSignal, listener: (signal: ShutdownSignal) => void): unknown;
|
|
60
|
+
on(signal: ShutdownSignal, listener: (signal: ShutdownSignal) => void): unknown;
|
|
61
|
+
release?: {
|
|
62
|
+
name?: string;
|
|
63
|
+
};
|
|
64
|
+
stdout?: {
|
|
65
|
+
write(chunk: string, callback: (error?: Error | null) => void): unknown;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Name of the variable that sets the shared drain budget in milliseconds. The default is 0. */
|
|
69
|
+
export declare const shutdownDrainEnv = "VITEHUB_SHUTDOWN_DRAIN_MS";
|
|
70
|
+
/** Returns the shutdown state of this process. */
|
|
71
|
+
export declare function shutdownState(runtime?: ShutdownRuntime | undefined): ShutdownState;
|
|
72
|
+
/**
|
|
73
|
+
* Runs the drains that did not start yet, in parallel, with one shared budget. Pass an app to
|
|
74
|
+
* run only the drains of that app. Each drain runs once, and a later call returns its result.
|
|
75
|
+
*/
|
|
76
|
+
export declare function runShutdownDrains(app?: ShutdownApp, runtime?: ShutdownRuntime | undefined): Promise<ShutdownDrainResult[]>;
|
|
77
|
+
/**
|
|
78
|
+
* Registers a drain that ViteHub runs once when the host stops.
|
|
79
|
+
*
|
|
80
|
+
* The drain runs when a server that owns stop signals gets SIGTERM or SIGINT, or when the
|
|
81
|
+
* Nitro app closes. All drains share the budget in `VITEHUB_SHUTDOWN_DRAIN_MS`.
|
|
82
|
+
*/
|
|
83
|
+
export declare function onShutdown(app: ShutdownApp, name: string, drain: ShutdownDrain, runtime?: ShutdownRuntime | undefined): void;
|
|
84
|
+
//#endregion
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
//#region src/internal/shutdown.ts
|
|
2
|
+
/** Name of the variable that sets the shared drain budget in milliseconds. The default is 0. */
|
|
3
|
+
const shutdownDrainEnv = "VITEHUB_SHUTDOWN_DRAIN_MS";
|
|
4
|
+
/** Time that a drain gets after the budget ends to finish its abort, such as a restart notice. */
|
|
5
|
+
const settleMs = 15e3;
|
|
6
|
+
/** Time that the server gets to close HTTP and run Nitro `close` hooks after the drains. */
|
|
7
|
+
const closeMs = 1e4;
|
|
8
|
+
const signals = ["SIGTERM", "SIGINT"];
|
|
9
|
+
function currentProcess() {
|
|
10
|
+
const candidate = globalThis.process;
|
|
11
|
+
if (!candidate || typeof candidate.on !== "function" || typeof candidate.listeners !== "function") return void 0;
|
|
12
|
+
return candidate;
|
|
13
|
+
}
|
|
14
|
+
/** State for a host without `process`, such as a Cloudflare Worker without Node compatibility. */
|
|
15
|
+
let isolateState;
|
|
16
|
+
/** Returns the shutdown state of this process. */
|
|
17
|
+
function shutdownState(runtime = currentProcess()) {
|
|
18
|
+
const create = () => ({
|
|
19
|
+
apps: /* @__PURE__ */ new WeakSet(),
|
|
20
|
+
entries: /* @__PURE__ */ new Set(),
|
|
21
|
+
results: [],
|
|
22
|
+
signals: false,
|
|
23
|
+
status: "running"
|
|
24
|
+
});
|
|
25
|
+
if (!runtime) return isolateState ??= create();
|
|
26
|
+
return runtime.__vitehubShutdown ??= create();
|
|
27
|
+
}
|
|
28
|
+
function drainBudget(runtime) {
|
|
29
|
+
const configured = Number(runtime?.env[shutdownDrainEnv]);
|
|
30
|
+
return Number.isFinite(configured) && configured > 0 ? configured : 0;
|
|
31
|
+
}
|
|
32
|
+
function drainErrorMessage(error) {
|
|
33
|
+
try {
|
|
34
|
+
return error instanceof Error ? String(error.message) : String(error);
|
|
35
|
+
} catch {
|
|
36
|
+
return "Unknown shutdown drain error.";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function runEntry(entry, timeoutMs, state) {
|
|
40
|
+
const startedAt = Date.now();
|
|
41
|
+
const controller = new AbortController();
|
|
42
|
+
const timers = [];
|
|
43
|
+
const later = (ms) => new Promise((resolve) => {
|
|
44
|
+
const timer = setTimeout(() => resolve("timeout"), ms);
|
|
45
|
+
timer.unref?.();
|
|
46
|
+
timers.push(timer);
|
|
47
|
+
});
|
|
48
|
+
later(timeoutMs).then(() => controller.abort(/* @__PURE__ */ new Error("Shutdown drain budget ended.")));
|
|
49
|
+
let result;
|
|
50
|
+
try {
|
|
51
|
+
const outcome = await Promise.race([Promise.resolve().then(() => entry.drain({
|
|
52
|
+
signal: controller.signal,
|
|
53
|
+
timeoutMs
|
|
54
|
+
})).then(() => "drained"), later(timeoutMs + settleMs)]);
|
|
55
|
+
result = {
|
|
56
|
+
durationMs: Date.now() - startedAt,
|
|
57
|
+
name: entry.name,
|
|
58
|
+
status: outcome
|
|
59
|
+
};
|
|
60
|
+
} catch (error) {
|
|
61
|
+
result = {
|
|
62
|
+
durationMs: Date.now() - startedAt,
|
|
63
|
+
error: drainErrorMessage(error),
|
|
64
|
+
name: entry.name,
|
|
65
|
+
status: "failed"
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
for (const timer of timers) clearTimeout(timer);
|
|
69
|
+
controller.abort();
|
|
70
|
+
state.results.push(result);
|
|
71
|
+
return result;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Runs the drains that did not start yet, in parallel, with one shared budget. Pass an app to
|
|
75
|
+
* run only the drains of that app. Each drain runs once, and a later call returns its result.
|
|
76
|
+
*/
|
|
77
|
+
function runShutdownDrains(app, runtime = currentProcess()) {
|
|
78
|
+
const state = shutdownState(runtime);
|
|
79
|
+
const timeoutMs = drainBudget(runtime);
|
|
80
|
+
const entries = [...state.entries].filter((entry) => !app || entry.app === app);
|
|
81
|
+
return Promise.all(entries.map((entry) => entry.result ??= runEntry(entry, timeoutMs, state).finally(() => {
|
|
82
|
+
if (state.status === "running") state.entries.delete(entry);
|
|
83
|
+
})));
|
|
84
|
+
}
|
|
85
|
+
function installSignalTrap(app, runtime, state) {
|
|
86
|
+
state.trap = "pending";
|
|
87
|
+
const existing = new Map(signals.map((signal) => [signal, new Set(runtime.listeners(signal))]));
|
|
88
|
+
const serverListeners = [];
|
|
89
|
+
let resolveSetup;
|
|
90
|
+
const setup = new Promise((resolve) => {
|
|
91
|
+
resolveSetup = resolve;
|
|
92
|
+
});
|
|
93
|
+
const stop = (signal) => {
|
|
94
|
+
if (state.status !== "running") return;
|
|
95
|
+
state.status = "draining";
|
|
96
|
+
state.signal = signal;
|
|
97
|
+
const startedAt = Date.now();
|
|
98
|
+
const names = [...state.entries].map((entry) => entry.name);
|
|
99
|
+
console.info("[vitehub]", JSON.stringify({
|
|
100
|
+
drainMs: drainBudget(runtime),
|
|
101
|
+
drains: names,
|
|
102
|
+
event: "shutdown.draining",
|
|
103
|
+
signal,
|
|
104
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
105
|
+
}));
|
|
106
|
+
(async () => {
|
|
107
|
+
await setup;
|
|
108
|
+
if (!serverListeners.length) {
|
|
109
|
+
state.status = "running";
|
|
110
|
+
if (runtime.kill && typeof process !== "undefined" && typeof process.pid === "number") runtime.kill(process.pid, signal);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const results = await runShutdownDrains(void 0, runtime);
|
|
114
|
+
console.info("[vitehub]", JSON.stringify({
|
|
115
|
+
durationMs: Date.now() - startedAt,
|
|
116
|
+
event: "shutdown.drained",
|
|
117
|
+
results,
|
|
118
|
+
signal,
|
|
119
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
120
|
+
}));
|
|
121
|
+
const listeners = serverListeners.filter(([name]) => name === signal);
|
|
122
|
+
const closeServer = Promise.all(listeners.map(([, listener]) => Promise.resolve().then(() => listener(signal)))).then(() => void 0, (error) => console.error("[vitehub] Server shutdown failed.", error));
|
|
123
|
+
await Promise.race([closeServer, new Promise((resolve) => {
|
|
124
|
+
setTimeout(resolve, closeMs).unref?.();
|
|
125
|
+
})]);
|
|
126
|
+
state.status = "exited";
|
|
127
|
+
const exited = JSON.stringify({
|
|
128
|
+
durationMs: Date.now() - startedAt,
|
|
129
|
+
event: "shutdown.exited",
|
|
130
|
+
signal,
|
|
131
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
132
|
+
});
|
|
133
|
+
if (runtime.stdout) {
|
|
134
|
+
await new Promise((resolve) => {
|
|
135
|
+
let settled = false;
|
|
136
|
+
const finish = (error) => {
|
|
137
|
+
if (settled) return;
|
|
138
|
+
settled = true;
|
|
139
|
+
if (error) console.error("[vitehub] Failed to flush shutdown output.", error);
|
|
140
|
+
resolve();
|
|
141
|
+
};
|
|
142
|
+
const timer = setTimeout(finish, 1e3);
|
|
143
|
+
timer.unref?.();
|
|
144
|
+
runtime.stdout.write(`[vitehub] ${exited}\n`, (error) => {
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
finish(error);
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
150
|
+
} else console.info("[vitehub]", exited);
|
|
151
|
+
runtime.exit(0);
|
|
152
|
+
})().catch((error) => {
|
|
153
|
+
console.error("[vitehub] Shutdown failed.", error);
|
|
154
|
+
state.status = "exited";
|
|
155
|
+
runtime.exit(1);
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
for (const signal of signals) runtime.on(signal, stop);
|
|
159
|
+
setTimeout(() => {
|
|
160
|
+
for (const signal of signals) {
|
|
161
|
+
const server = runtime.listeners(signal).filter((listener) => typeof listener === "function" && listener !== stop && !existing.get(signal)?.has(listener)).find((listener) => listener.name === "shutdown" || listener.name === "stop");
|
|
162
|
+
if (server) {
|
|
163
|
+
const handler = server;
|
|
164
|
+
runtime.off(signal, handler);
|
|
165
|
+
serverListeners.push([signal, handler]);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (serverListeners.length) {
|
|
169
|
+
state.trap = "installed";
|
|
170
|
+
state.signals = true;
|
|
171
|
+
resolveSetup();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
for (const signal of signals) runtime.off(signal, stop);
|
|
175
|
+
state.trap = "skipped";
|
|
176
|
+
resolveSetup();
|
|
177
|
+
}, 0);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Registers a drain that ViteHub runs once when the host stops.
|
|
181
|
+
*
|
|
182
|
+
* The drain runs when a server that owns stop signals gets SIGTERM or SIGINT, or when the
|
|
183
|
+
* Nitro app closes. All drains share the budget in `VITEHUB_SHUTDOWN_DRAIN_MS`.
|
|
184
|
+
*/
|
|
185
|
+
function onShutdown(app, name, drain, runtime = currentProcess()) {
|
|
186
|
+
const state = shutdownState(runtime);
|
|
187
|
+
state.entries.add({
|
|
188
|
+
app,
|
|
189
|
+
drain,
|
|
190
|
+
name
|
|
191
|
+
});
|
|
192
|
+
if (!state.apps.has(app)) {
|
|
193
|
+
state.apps.add(app);
|
|
194
|
+
app.hooks.hook("close", () => runShutdownDrains(app, runtime));
|
|
195
|
+
}
|
|
196
|
+
if (runtime && !state.trap) {
|
|
197
|
+
if ((runtime.release?.name === "node" || runtime.release?.name === "bun") && globalThis.navigator?.userAgent !== "Cloudflare-Workers") installSignalTrap(app, runtime, state);
|
|
198
|
+
else state.trap = "skipped";
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
202
|
+
export { onShutdown, runShutdownDrains, shutdownDrainEnv, shutdownState };
|
|
@@ -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 };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
//#region src/internal/test-mode.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Test mode for app tests. `vite-hub/test` turns it on, and each Server Primitive then uses a local backend that lives
|
|
4
|
+
* until the next reset, instead of its configured driver. The state is on `globalThis`, so every package copy in the
|
|
5
|
+
* process sees the same test mode. This module imports nothing, so every host bundle can include it;
|
|
6
|
+
* `./test-mode-setup.ts` creates the mode with Node APIs.
|
|
7
|
+
*/
|
|
8
|
+
export interface ViteHubTestMode {
|
|
9
|
+
/** Server Env values that the test set. Server Env reads them before `process.env`. */
|
|
10
|
+
readonly env: Record<string, string>;
|
|
11
|
+
/** The app folder that has `server/`. Database reads its migrations from there. */
|
|
12
|
+
readonly root: string;
|
|
13
|
+
/**
|
|
14
|
+
* Returns the backend with this key, and creates it on the first call after a reset. `dispose` runs on the next
|
|
15
|
+
* reset. A Primitive keeps no backend of its own in test mode, so a reset gives every test empty storage.
|
|
16
|
+
*/
|
|
17
|
+
backend: <T>(key: string, create: () => T, dispose?: (value: Awaited<T>) => unknown) => T;
|
|
18
|
+
/** Returns the backend with this key when the current test created it. */
|
|
19
|
+
peek: <T>(key: string) => T | undefined;
|
|
20
|
+
/** Returns an empty folder for this key under `<root>/.vitehub/test`. The next reset deletes it. */
|
|
21
|
+
directory: (key: string) => Promise<string>;
|
|
22
|
+
/** Disposes every backend, deletes the temporary folders, and clears the Server Env values. */
|
|
23
|
+
reset: () => Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
/** The `globalThis` key of the active test mode. */
|
|
26
|
+
export declare const viteHubTestModeKey: unique symbol;
|
|
27
|
+
export type ViteHubTestModeGlobal = typeof globalThis & {
|
|
28
|
+
[viteHubTestModeKey]?: ViteHubTestMode;
|
|
29
|
+
};
|
|
30
|
+
/** The active test mode, or `undefined` outside tests. */
|
|
31
|
+
export declare function getViteHubTestMode(): ViteHubTestMode | undefined;
|
|
32
|
+
//#endregion
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
//#region src/internal/test-mode.ts
|
|
2
|
+
/** The `globalThis` key of the active test mode. */
|
|
3
|
+
const viteHubTestModeKey = Symbol.for("vitehub.test");
|
|
4
|
+
/** The active test mode, or `undefined` outside tests. */
|
|
5
|
+
function getViteHubTestMode() {
|
|
6
|
+
return globalThis[viteHubTestModeKey];
|
|
7
|
+
}
|
|
8
|
+
//#endregion
|
|
9
|
+
export { getViteHubTestMode, viteHubTestModeKey };
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
//#region ../internal/dist/operation-definition-CnqtvP1y.d.ts
|
|
3
|
+
//#region src/operation-definition.d.ts
|
|
4
|
+
/** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
|
|
5
|
+
type OperationKind = "read" | "write" | "destructive";
|
|
6
|
+
/** The signed-in user of a call. */
|
|
7
|
+
interface OperationUser {
|
|
8
|
+
id: string;
|
|
9
|
+
name?: string;
|
|
10
|
+
email?: string;
|
|
11
|
+
image?: string;
|
|
12
|
+
[key: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
/** The Agent Actor when an agent calls through a capability or MCP on behalf of a user. */
|
|
15
|
+
interface OperationActor {
|
|
16
|
+
id: string;
|
|
17
|
+
kind?: string;
|
|
18
|
+
label?: string;
|
|
19
|
+
meta?: object;
|
|
20
|
+
}
|
|
21
|
+
/** The checked Console access of a call. `vite-hub` issues it. `ConsoleAccess` has this shape. */
|
|
22
|
+
interface OperationAccess {
|
|
23
|
+
readonly mode: string;
|
|
24
|
+
/**
|
|
25
|
+
* The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
|
|
26
|
+
* operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
|
|
27
|
+
* calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
|
|
28
|
+
* allows only the reads of that scope.
|
|
29
|
+
*/
|
|
30
|
+
readonly sections: "all" | readonly string[];
|
|
31
|
+
readonly user?: OperationUser;
|
|
32
|
+
}
|
|
33
|
+
interface OperationContext {
|
|
34
|
+
/** The checked Console access of the call. */
|
|
35
|
+
access: OperationAccess;
|
|
36
|
+
/** The signed-in user, or null. */
|
|
37
|
+
user: OperationUser | null;
|
|
38
|
+
/** The Agent Actor when an agent calls on behalf of `user`. */
|
|
39
|
+
actor?: OperationActor;
|
|
40
|
+
surface: "console" | "cli" | "mcp" | "agent";
|
|
41
|
+
/** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
|
|
42
|
+
development?: boolean;
|
|
43
|
+
env?: Record<string, unknown>;
|
|
44
|
+
waitUntil?: (task: Promise<unknown>) => void;
|
|
45
|
+
request?: Request;
|
|
46
|
+
/**
|
|
47
|
+
* The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
|
|
48
|
+
* with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
|
|
49
|
+
* of Comments.
|
|
50
|
+
*/
|
|
51
|
+
event?: unknown;
|
|
52
|
+
/** Operations set a success status here, such as 202 for an accepted call. */
|
|
53
|
+
response?: {
|
|
54
|
+
status?: number;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* An agent or an MCP client may pass `lease: "override"` to `content.save`, `content.remove`, and `content.restore`
|
|
58
|
+
* only when the developer allowed it. Defaults to false, so a model cannot take over a document that a person is editing.
|
|
59
|
+
*/
|
|
60
|
+
overrideLeases?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* What an Agent may read of the Channel conversations, set by `operations({ conversations })`. `participant`: only the
|
|
63
|
+
* threads that the Actor takes part in. `all`: every thread. Unset: none.
|
|
64
|
+
*/
|
|
65
|
+
conversations?: "all" | "participant";
|
|
66
|
+
}
|
|
67
|
+
interface OperationDefinition<Input, Output> {
|
|
68
|
+
/** `<section>.<verb>`, such as `content.publish`. Unique per app. */
|
|
69
|
+
name: string;
|
|
70
|
+
/** One sentence. Becomes the CLI help line and the MCP tool description. */
|
|
71
|
+
description: string;
|
|
72
|
+
/**
|
|
73
|
+
* Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
|
|
74
|
+
* from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
|
|
75
|
+
* scope and read-only grants. A function that returns an invalid id denies the call.
|
|
76
|
+
*/
|
|
77
|
+
section: string | false | ((input: Input) => string | undefined);
|
|
78
|
+
/**
|
|
79
|
+
* The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
|
|
80
|
+
* the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
|
|
81
|
+
* `:` needs the whole section.
|
|
82
|
+
*/
|
|
83
|
+
scope?: (input: Input) => string | undefined;
|
|
84
|
+
/** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
|
|
85
|
+
kind: OperationKind;
|
|
86
|
+
/** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
|
|
87
|
+
input: StandardSchemaV1<unknown, Input>;
|
|
88
|
+
output?: StandardSchemaV1<unknown, Output>;
|
|
89
|
+
cli?: {
|
|
90
|
+
/** Defaults: namespace = section, command = verb. */
|
|
91
|
+
namespace?: string;
|
|
92
|
+
/** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
|
|
93
|
+
command?: string;
|
|
94
|
+
/** Input keys read from positional arguments, in order. */
|
|
95
|
+
positional?: string[];
|
|
96
|
+
/** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
|
|
97
|
+
format?: (output: Output) => string;
|
|
98
|
+
/** `vitehub <namespace>` runs this command when no command is named. */
|
|
99
|
+
default?: boolean;
|
|
100
|
+
};
|
|
101
|
+
/** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
|
|
102
|
+
maxRequestBytes?: number;
|
|
103
|
+
/**
|
|
104
|
+
* Returns true when this call only reads, such as a dry run of a `destructive` operation. The CLI then skips the
|
|
105
|
+
* confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
|
|
106
|
+
*/
|
|
107
|
+
readOnlyWhen?: (input: Input) => boolean;
|
|
108
|
+
/**
|
|
109
|
+
* How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
|
|
110
|
+
* Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
|
|
111
|
+
* result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
|
|
112
|
+
* is the result as JSON.
|
|
113
|
+
*/
|
|
114
|
+
mcp?: false | {
|
|
115
|
+
title?: string;
|
|
116
|
+
format?: (output: NoInfer<Output>) => string;
|
|
117
|
+
};
|
|
118
|
+
/** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
|
|
119
|
+
user?: false;
|
|
120
|
+
/**
|
|
121
|
+
* The operation runs code of the app, such as a workflow, a job, a task, or a schedule. The Console registers it only
|
|
122
|
+
* when `console.invoke` is on, which is the default in development and off in a production build.
|
|
123
|
+
*/
|
|
124
|
+
invoke?: true;
|
|
125
|
+
run: (input: Input, context: OperationContext) => Output | Promise<Output>;
|
|
126
|
+
}
|
|
127
|
+
/** The fields every surface reports for a failed call. */
|
|
128
|
+
interface OperationFailure {
|
|
129
|
+
code: string;
|
|
130
|
+
message: string;
|
|
131
|
+
fix?: string;
|
|
132
|
+
docs?: string;
|
|
133
|
+
details?: Record<string, unknown>;
|
|
134
|
+
status: number;
|
|
135
|
+
}
|
|
136
|
+
type OperationResult<Output = unknown> = {
|
|
137
|
+
ok: true;
|
|
138
|
+
value: Output;
|
|
139
|
+
} | ({
|
|
140
|
+
ok: false;
|
|
141
|
+
} & OperationFailure);
|
|
142
|
+
/**
|
|
143
|
+
* Define one operation. The Console, the CLI, MCP, and agent tools call the same definition. Contribute it with
|
|
144
|
+
* `vitehub: { operations: [{ module, export }] }` on a Vite plugin.
|
|
145
|
+
*/
|
|
146
|
+
declare function defineOperation<Input, Output>(definition: OperationDefinition<Input, Output>): OperationDefinition<Input, Output>;
|
|
147
|
+
/** The contribution of one plugin: operations, or a module that exports them. */
|
|
148
|
+
interface OperationContributionEntry {
|
|
149
|
+
/** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
|
|
150
|
+
module: string;
|
|
151
|
+
/** Named export that holds an operation or an array of operations. Defaults to `default`. */
|
|
152
|
+
export?: string;
|
|
153
|
+
/** Loads the export in the tool process, for a module that the tool cannot resolve by name. */
|
|
154
|
+
load?: () => Promise<unknown>;
|
|
155
|
+
/** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
|
|
156
|
+
runtime?: false;
|
|
157
|
+
}
|
|
158
|
+
/** The contribution of a plugin: a list, or a function that returns it, for a plugin that reads the project first. */
|
|
159
|
+
type OperationContributions = readonly OperationContributionEntry[] | (() => readonly OperationContributionEntry[] | Promise<readonly OperationContributionEntry[]>);
|
|
160
|
+
interface OperationContributingPlugin {
|
|
161
|
+
name?: string;
|
|
162
|
+
vitehub?: {
|
|
163
|
+
operations?: OperationContributions;
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
//#endregion
|
|
167
|
+
export { type OperationAccess, type OperationActor, type OperationContext, type OperationContributingPlugin, type OperationContributionEntry, type OperationContributions, type OperationDefinition, type OperationFailure, type OperationKind, type OperationResult, type OperationUser, defineOperation };
|