@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
@@ -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 };
@@ -0,0 +1,406 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ import { toJsonSchema } from "@valibot/to-json-schema";
3
+ //#region ../internal/dist/error-diagnostics-NFLF9k-4.js
4
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
5
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
6
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
7
+ codes: {
8
+ INTERNAL_R0012: {
9
+ ...dynamicError,
10
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
11
+ },
12
+ INTERNAL_R0013: {
13
+ ...dynamicError,
14
+ fix: "Check that the provider token can manage the resource in the path that the message names. `error.kind` and `error.codes` hold the provider failure."
15
+ },
16
+ INTERNAL_R0014: {
17
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
18
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
19
+ },
20
+ INTERNAL_R0020: {
21
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
22
+ why: ({ message }) => message === void 0 ? "" : String(message)
23
+ },
24
+ INTERNAL_R0021: {
25
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
26
+ why: ({ message }) => message === void 0 ? "" : String(message)
27
+ },
28
+ INTERNAL_R0022: {
29
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
30
+ why: ({ message }) => message === void 0 ? "" : String(message)
31
+ },
32
+ INTERNAL_R0024: {
33
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
34
+ why: ({ message }) => message === void 0 ? "" : String(message)
35
+ },
36
+ INTERNAL_R0023: {
37
+ fix: "Ask for access to the section of this operation.",
38
+ why: ({ message }) => message === void 0 ? "" : String(message)
39
+ },
40
+ INTERNAL_B0001: {
41
+ ...dynamicError,
42
+ fix: "Give the resource that the message names another name or binding in the `vitehub()` options of its feature, so that two different Cloudflare resources do not share one name."
43
+ },
44
+ INTERNAL_B0015: {
45
+ ...dynamicError,
46
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
47
+ },
48
+ INTERNAL_B0016: {
49
+ ...dynamicError,
50
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
51
+ },
52
+ INTERNAL_B0017: {
53
+ ...dynamicError,
54
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
55
+ },
56
+ INTERNAL_B0018: {
57
+ ...dynamicError,
58
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
59
+ },
60
+ INTERNAL_B0019: {
61
+ ...dynamicError,
62
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
63
+ },
64
+ INTERNAL_B0020: {
65
+ ...dynamicError,
66
+ fix: "Correct the field that the message names in the `package.json` of a runtime dependency of the app, such as a workspace package, or run `pnpm install` again to restore an installed package."
67
+ },
68
+ INTERNAL_B0021: {
69
+ ...dynamicError,
70
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
71
+ },
72
+ INTERNAL_B0022: {
73
+ ...dynamicError,
74
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
75
+ },
76
+ INTERNAL_B0025: {
77
+ ...dynamicError,
78
+ fix: "Replace the `new URL(\"./...\", import.meta.url)` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` of that file."
79
+ },
80
+ INTERNAL_B0026: {
81
+ ...dynamicError,
82
+ fix: "Replace the computed `import()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import` or with `import(\"<literal path>\")`."
83
+ },
84
+ INTERNAL_B0027: {
85
+ ...dynamicError,
86
+ fix: "Replace the computed `require()` in the project-root `main.ts`, or in a Schedule file of `server/schedules/` and the files it imports, with a static `import`."
87
+ },
88
+ INTERNAL_B0028: {
89
+ ...dynamicError,
90
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
91
+ },
92
+ INTERNAL_B0029: {
93
+ ...dynamicError,
94
+ fix: "Stop the other builds that write the same Deno output folder, delete the `.vitehub-lock` folder next to that output folder, such as `.output.vitehub-lock`, then build again."
95
+ },
96
+ INTERNAL_B0031: {
97
+ ...dynamicError,
98
+ fix: "Import `./schedule/deno-cron.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./schedule/deno-cron.mjs\", import.meta.url).href)` outside any condition."
99
+ },
100
+ INTERNAL_B0032: {
101
+ ...dynamicError,
102
+ fix: "Import `./server/index.mjs` at the top level of the project-root `main.ts`, for example with `await import(new URL(\"./server/index.mjs\", import.meta.url).href)` outside any condition."
103
+ },
104
+ INTERNAL_B0035: {
105
+ ...dynamicError,
106
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
107
+ },
108
+ INTERNAL_B0039: {
109
+ ...dynamicError,
110
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
111
+ },
112
+ INTERNAL_B0040: {
113
+ ...dynamicError,
114
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
115
+ },
116
+ INTERNAL_B0043: {
117
+ ...dynamicError,
118
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
119
+ },
120
+ INTERNAL_B0046: {
121
+ ...dynamicError,
122
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
123
+ },
124
+ INTERNAL_B0047: {
125
+ ...dynamicError,
126
+ fix: "Correct the `package.json` file that the message names so that it holds one JSON object, or run `pnpm install` again to restore an installed package."
127
+ },
128
+ INTERNAL_B0048: {
129
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
130
+ why: ({ message }) => message === void 0 ? "" : String(message)
131
+ },
132
+ INTERNAL_B0049: {
133
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
134
+ why: ({ message }) => message === void 0 ? "" : String(message)
135
+ },
136
+ INTERNAL_B0050: {
137
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
138
+ why: ({ message }) => message === void 0 ? "" : String(message)
139
+ },
140
+ INTERNAL_B0051: {
141
+ why: ({ field, generated, name, path, project, scope }) => `The Cloudflare ${path} entry "${name}"${scope} is written by ViteHub and by the project's Wrangler config with a different ${field}: ${generated} and ${project}.`,
142
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
143
+ },
144
+ INTERNAL_B0052: {
145
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
146
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
147
+ },
148
+ INTERNAL_R0025: {
149
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
150
+ why: ({ message }) => message === void 0 ? "" : String(message)
151
+ },
152
+ INTERNAL_R0026: {
153
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
154
+ fix: "Review the operation, then run it again with --yes to confirm the change."
155
+ },
156
+ INTERNAL_C0001: {
157
+ ...dynamicError,
158
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
159
+ },
160
+ INTERNAL_C0002: {
161
+ ...dynamicError,
162
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
163
+ },
164
+ INTERNAL_R0001: {
165
+ ...dynamicError,
166
+ fix: "Set `host` in `vitehub()`, or in the `vitehub` options of `nuxt.config.ts`, to `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. Or remove `host` so that ViteHub finds the host from the environment."
167
+ },
168
+ INTERNAL_R0002: {
169
+ ...dynamicError,
170
+ fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
171
+ },
172
+ INTERNAL_R0004: {
173
+ ...dynamicError,
174
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
175
+ },
176
+ INTERNAL_R0005: {
177
+ ...dynamicError,
178
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
179
+ },
180
+ INTERNAL_R0006: {
181
+ ...dynamicError,
182
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
183
+ },
184
+ INTERNAL_R0007: {
185
+ ...dynamicError,
186
+ fix: "Set `maxResponseBytes` of the HTTP request to a positive integer no greater than the limit that the message names, or remove it to use the default."
187
+ },
188
+ INTERNAL_R0008: {
189
+ ...dynamicError,
190
+ fix: "Make the value that the message names match its schema: the input, query, or body that you send, or the response schema that you declare for the request."
191
+ },
192
+ INTERNAL_R0009: {
193
+ ...dynamicError,
194
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
195
+ },
196
+ INTERNAL_R0010: {
197
+ ...dynamicError,
198
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
199
+ },
200
+ INTERNAL_R0011: {
201
+ ...dynamicError,
202
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
203
+ },
204
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
205
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
206
+ fix: "Name the Console key with 1 to 64 characters from A-Z, 0-9, and _, such as `CI`. The app reads its public key from `VITEHUB_CONSOLE_KEY_<NAME>`."
207
+ },
208
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
209
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
210
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
211
+ },
212
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
213
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
214
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
215
+ },
216
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
217
+ why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
218
+ fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
219
+ },
220
+ INTERNAL_FORGE_NOT_INSTALLED: {
221
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
222
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
223
+ },
224
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
225
+ why: ({ detail }) => detail,
226
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
227
+ },
228
+ INTERNAL_MCP_METHOD_FAILED: {
229
+ why: ({ name }) => `${name} failed on the server.`,
230
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
231
+ },
232
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
233
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
234
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
235
+ },
236
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
237
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
238
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
239
+ },
240
+ INTERNAL_PRESET_TUPLE_INVALID: {
241
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
242
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
243
+ },
244
+ INTERNAL_SECRET_PURPOSE_MISSING: {
245
+ why: "[vitehub] A derived secret requires a purpose.",
246
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
247
+ },
248
+ INTERNAL_SECRET_TOO_SHORT: {
249
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
250
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
251
+ },
252
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
253
+ why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
254
+ fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
255
+ },
256
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
257
+ why: "Received integer which cannot be safely represented as a JavaScript number",
258
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
259
+ },
260
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
261
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
262
+ fix: "Ask for the `draft-07`, `draft-2020-12`, or `openapi-3.0` JSON Schema target, or pass one of them as `withValibotJsonSchema(schema, { target })`."
263
+ }
264
+ }
265
+ });
266
+ //#endregion
267
+ //#region ../internal/dist/object.js
268
+ /** A non-null object or a function that is not an array. */
269
+ function isRecordOrFunction(value) {
270
+ return Object(value) === value && !Array.isArray(value);
271
+ }
272
+ //#endregion
273
+ //#region ../internal/dist/standard-schema.js
274
+ function readOwn(value, key) {
275
+ if (value === null || Object(value) !== value) return;
276
+ try {
277
+ return Reflect.get(Object(value), key);
278
+ } catch {
279
+ return;
280
+ }
281
+ }
282
+ /**
283
+ * Read a Standard JSON Schema projection without throwing.
284
+ *
285
+ * Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
286
+ * (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
287
+ */
288
+ function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
289
+ const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
290
+ const project = readOwn(jsonSchema, direction);
291
+ if (typeof project !== "function") return;
292
+ try {
293
+ const result = project.call(jsonSchema, libraryOptions ? {
294
+ target,
295
+ libraryOptions
296
+ } : { target });
297
+ return isRecordOrFunction(result) ? result : void 0;
298
+ } catch {
299
+ return;
300
+ }
301
+ }
302
+ //#endregion
303
+ //#region ../internal/dist/valibot.js
304
+ const valibotTargets = /* @__PURE__ */ new Set([
305
+ "draft-07",
306
+ "draft-2020-12",
307
+ "openapi-3.0"
308
+ ]);
309
+ function isValibotTarget(value) {
310
+ return valibotTargets.has(String(value));
311
+ }
312
+ /**
313
+ * Add Standard JSON Schema conversion to a plain Valibot schema. Valibot schemas validate as Standard Schema but carry
314
+ * no JSON Schema, so forms, tools, and model providers would get no shape for them. Other schemas, Valibot schemas that
315
+ * already convert, and async Valibot schemas return unchanged. The copy keeps every Valibot property, so validation
316
+ * does not change.
317
+ *
318
+ * `target` fixes the JSON Schema dialect. Without it, each conversion uses the dialect that the caller asks for.
319
+ */
320
+ function withValibotJsonSchema(schema, options = {}) {
321
+ const standard = schema["~standard"];
322
+ if (standard.vendor !== "valibot" || Reflect.get(schema, "async") === true) return schema;
323
+ if (Object.hasOwn(standard, "jsonSchema") && standard.jsonSchema) return schema;
324
+ const convert = (typeMode) => (request) => {
325
+ const target = options.target ?? request.target;
326
+ if (!isValibotTarget(target)) throw internalErrorDiagnostics.INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED({ target: String(target) });
327
+ return toJsonSchema(schema, {
328
+ target,
329
+ typeMode,
330
+ errorMode: "ignore"
331
+ });
332
+ };
333
+ return {
334
+ ...schema,
335
+ "~standard": {
336
+ ...standard,
337
+ jsonSchema: {
338
+ input: convert("input"),
339
+ output: convert("output")
340
+ }
341
+ }
342
+ };
343
+ }
344
+ //#endregion
345
+ //#region ../internal/dist/operation-definition.js
346
+ const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
347
+ const kinds = /* @__PURE__ */ new Set([
348
+ "read",
349
+ "write",
350
+ "destructive"
351
+ ]);
352
+ function invalidDefinition(name, reason) {
353
+ return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
354
+ }
355
+ function checkDefinition(definition) {
356
+ if (!isRecordOrFunction(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
357
+ const { name } = definition;
358
+ if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
359
+ if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
360
+ const { section } = definition;
361
+ if (section !== false && !(section instanceof Function) && !isSectionId(section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false; section ids cannot contain ':'.");
362
+ if (definition.scope !== void 0 && (!(definition.scope instanceof Function) || String(section) !== section)) throw invalidDefinition(name, "scope must be a function, and it needs a section id.");
363
+ if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
364
+ const input = definition.input;
365
+ if (!isRecordOrFunction(input) || !isRecordOrFunction(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
366
+ if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
367
+ const { maxRequestBytes } = definition;
368
+ if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
369
+ if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
370
+ const { mcp } = definition;
371
+ if (mcp !== void 0 && mcp !== false && (!isRecordOrFunction(mcp) || mcp.title !== void 0 && (String(mcp.title) !== mcp.title || !mcp.title) || mcp.format !== void 0 && !(mcp.format instanceof Function))) throw invalidDefinition(name, "mcp must be false, or an object with a title string and a format function.");
372
+ }
373
+ /** The default limit of a call, in bytes. */
374
+ const defaultRequestBytes = 65536;
375
+ /** Input keys that the generated CLI commands read themselves. */
376
+ const reservedOperationFlags = [
377
+ "input",
378
+ "json",
379
+ "timeout",
380
+ "url",
381
+ "yes"
382
+ ];
383
+ /**
384
+ * Define one operation. The Console, the CLI, MCP, and agent tools call the same definition. Contribute it with
385
+ * `vitehub: { operations: [{ module, export }] }` on a Vite plugin.
386
+ */
387
+ function defineOperation(definition) {
388
+ checkDefinition(definition);
389
+ const defined = {
390
+ ...definition,
391
+ input: withValibotJsonSchema(definition.input)
392
+ };
393
+ const properties = operationInputJsonSchema(defined).properties;
394
+ const clashes = isRecordOrFunction(properties) ? Object.keys(properties).filter((key) => reservedOperationFlags.includes(key)) : [];
395
+ if (clashes.length) throw invalidDefinition(definition.name, `the input key ${clashes.map((key) => JSON.stringify(key)).join(", ")} is a CLI flag of every command (${reservedOperationFlags.join(", ")}). Rename it.`);
396
+ return defined;
397
+ }
398
+ function isSectionId(section) {
399
+ return typeof section === "string" && section !== "" && !section.includes(":");
400
+ }
401
+ /** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
402
+ function operationInputJsonSchema(operation) {
403
+ return standardJsonSchema(operation.input, "input") ?? { type: "object" };
404
+ }
405
+ //#endregion
406
+ export { defineOperation };
@@ -0,0 +1,34 @@
1
+ //#region src/public-url.d.ts
2
+ /** Public origins resolved from `vitehub({ publicUrl })` at build time. */
3
+ interface PublicUrlConfig {
4
+ /** One origin for the whole deployment. */
5
+ url?: string;
6
+ /** One origin per discovered Agent, from the function form. */
7
+ agents?: Record<string, string>;
8
+ }
9
+ /** Replace aliases when a generated Agent registry is installed. */
10
+ declare function resetPublicUrlAgentNames(): void;
11
+ /** Associate an evaluated Agent name with the identity used by build-time URL configuration. */
12
+ declare function registerPublicUrlAgentName(name: string, discoveredName: string): void;
13
+ /**
14
+ * Resolve the public origin of this deployment.
15
+ *
16
+ * A configured origin always wins over the request: the single `vitehub({ publicUrl })` origin, then the origin of
17
+ * the Agent, then, for a request, the configured origin with the same host as the request or the only configured origin. When
18
+ * `publicUrl` configures several origins and none of them fits, the result is `undefined`: the request Host cannot
19
+ * name a new origin. Only when nothing is configured, such as in `vite dev`, the request origin is the result.
20
+ * Set `configuredOnly` when the request must not supply it in that case either.
21
+ */
22
+ declare function resolvePublicUrl(options?: {
23
+ agentName?: string;
24
+ request?: Pick<Request, "url">;
25
+ configuredOnly?: boolean;
26
+ }): string | undefined;
27
+ /**
28
+ * Build the hosted Console URL that opens one Agent invocation, such as
29
+ * `https://console.vitehub.dev/open?project=https%3A%2F%2Fapp.example.com&path=%2Fagents%2Fbot%2Finvocations%2Fid`.
30
+ * `origin` must not include the application base path. The hosted Console checks the project URL when it opens the link.
31
+ */
32
+ declare function consoleInvocationUrl(origin: string, agentName: string, invocationId: string): string;
33
+ //#endregion
34
+ export { resolvePublicUrl as a, resetPublicUrlAgentNames as i, consoleInvocationUrl as n, registerPublicUrlAgentName as r, PublicUrlConfig as t };