@vite-hub/bundle 0.3.1 → 0.4.1

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 CHANGED
@@ -37,6 +37,8 @@ vitehub bundle --against .vitehub/bundle-before.json --json # the same as JSON
37
37
 
38
38
  The commands read `.vitehub/bundle/` and need no dev server. Development builds are not measured.
39
39
 
40
+ The Console and the ViteHub MCP read the same report through two read operations on the dev server: `bundle.report` returns what `vitehub bundle --json` prints, and `bundle.why` with `{ target }` returns what `vitehub bundle why <target> --json` prints. The dev server reads `.vitehub/bundle/` of its project, so run a production build first. A deployed server has no project files and answers `BUNDLE_DEV_SERVER_REQUIRED`. Without a report, the operations answer `BUNDLE_REPORT_MISSING`. Access to the `bundle` Console section allows both.
41
+
40
42
  The build also saves the report location in `.vitehub/bundle-root.json` at the build's working directory and beside the Vite config. This lets `vitehub bundle` find reports for a configured nested root without loading the project. Run a production build once to create this file for reports from an older version.
41
43
 
42
44
  ## What the report says
@@ -1,7 +1,8 @@
1
- import { a as explainBundleRoute, f as readBundleReportRoot, i as explainBundle, n as readSavedBundleReport, p as readEnvironmentReports, r as createBundleReport, t as compareBundleReports, u as formatBytes } from "./compare-B-xpyN4Y.js";
1
+ import { a as explainBundleRoute, f as readBundleReportRoot, i as explainBundle, n as readSavedBundleReport, p as readEnvironmentReports, r as createBundleReport, t as compareBundleReports, u as formatBytes } from "./compare-87VKOrA3.js";
2
2
  import { statSync } from "node:fs";
3
3
  import { basename, dirname, parse, resolve } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
+ import "node:url";
5
6
  //#region ../internal/src/build/vite.ts
6
7
  const projectRootDirectoryMarkers = [
7
8
  ["server", "agents"],
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
- import { u as formatBytes } from "./compare-B-xpyN4Y.js";
2
- import { t as bundleCliContributor } from "./cli-DdzHN8li.js";
1
+ import { u as formatBytes } from "./compare-87VKOrA3.js";
2
+ import { t as bundleCliContributor } from "./cli-CJOjJmEo.js";
3
3
  export { bundleCliContributor, formatBytes };
@@ -1,3 +1,4 @@
1
+ import { t as isRecord } from "./object-Da1zyPCR.js";
1
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
3
  import { dirname, join, posix, relative, resolve } from "node:path";
3
4
  import { createConsoleReporter, defineDiagnostics } from "nostics";
@@ -78,7 +79,7 @@ function formatBytes(bytes) {
78
79
  /** The largest Worker that Cloudflare accepts, before compression. */
79
80
  const cloudflareWorkerSizeLimit = 67108864;
80
81
  const bundleDiagnostics = /*#__PURE__*/ defineDiagnostics({
81
- docsBase: "https://vitehub.dev/docs/development/diagnostics",
82
+ docsBase: "https://vitehub.dev/docs/bundle/diagnostics",
82
83
  codes: {
83
84
  BUNDLE_STARTUP_UNUSED: {
84
85
  why: ({ packages, reason }) => `${packages.map((item) => `\`${item.name}\` (${formatBytes(item.bytes)})`).join(", ")} ${packages.length === 1 ? "loads" : "load"} at server startup. ${reason}`,
@@ -1680,12 +1681,6 @@ function explainBundleRoute(reports, target) {
1680
1681
  }
1681
1682
  }
1682
1683
  //#endregion
1683
- //#region ../internal/src/object.ts
1684
- /** A non-null object that is not an array. Functions do not pass. */
1685
- function isRecord(value) {
1686
- return typeof value === "object" && value !== null && !Array.isArray(value);
1687
- }
1688
- //#endregion
1689
1684
  //#region src/compare.ts
1690
1685
  function totals(side) {
1691
1686
  return side ? {
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as explainBundleRoute, d as bundleReportDir, i as explainBundle, n as readSavedBundleReport, p as readEnvironmentReports, r as createBundleReport, s as moduleGroup, t as compareBundleReports } from "./compare-B-xpyN4Y.js";
1
+ import { a as explainBundleRoute, d as bundleReportDir, i as explainBundle, n as readSavedBundleReport, p as readEnvironmentReports, r as createBundleReport, s as moduleGroup, t as compareBundleReports } from "./compare-87VKOrA3.js";
2
2
  //#region src/index.ts
3
3
  /** The report of the last build with `bundle` on, or `undefined` when there is none. */
4
4
  function readBundleReport(root) {
@@ -0,0 +1,11 @@
1
+ //#region ../internal/src/object.ts
2
+ /** A non-null object that is not an array. Functions do not pass. */
3
+ function isRecord(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ /** A non-null object or a function that is not an array. */
7
+ function isRecordOrFunction(value) {
8
+ return Object(value) === value && !Array.isArray(value);
9
+ }
10
+ //#endregion
11
+ export { isRecordOrFunction as n, isRecord as t };
@@ -0,0 +1,239 @@
1
+ //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
2
+ /** The Standard Typed interface. This is a base type extended by other specs. */
3
+ interface StandardTypedV1<Input = unknown, Output = Input> {
4
+ /** The Standard properties. */
5
+ readonly "~standard": StandardTypedV1.Props<Input, Output>;
6
+ }
7
+ declare namespace StandardTypedV1 {
8
+ /** The Standard Typed properties interface. */
9
+ interface Props<Input = unknown, Output = Input> {
10
+ /** The version number of the standard. */
11
+ readonly version: 1;
12
+ /** The vendor name of the schema library. */
13
+ readonly vendor: string;
14
+ /** Inferred types associated with the schema. */
15
+ readonly types?: Types<Input, Output> | undefined;
16
+ }
17
+ /** The Standard Typed types interface. */
18
+ interface Types<Input = unknown, Output = Input> {
19
+ /** The input type of the schema. */
20
+ readonly input: Input;
21
+ /** The output type of the schema. */
22
+ readonly output: Output;
23
+ }
24
+ /** Infers the input type of a Standard Typed. */
25
+ type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
26
+ /** Infers the output type of a Standard Typed. */
27
+ type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
28
+ }
29
+ /** The Standard Schema interface. */
30
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
31
+ /** The Standard Schema properties. */
32
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
33
+ }
34
+ declare namespace StandardSchemaV1 {
35
+ /** The Standard Schema properties interface. */
36
+ interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
37
+ /** Validates unknown input values. */
38
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
39
+ }
40
+ /** The result interface of the validate function. */
41
+ type Result<Output> = SuccessResult<Output> | FailureResult;
42
+ /** The result interface if validation succeeds. */
43
+ interface SuccessResult<Output> {
44
+ /** The typed output value. */
45
+ readonly value: Output;
46
+ /** A falsy value for `issues` indicates success. */
47
+ readonly issues?: undefined;
48
+ }
49
+ interface Options {
50
+ /** Explicit support for additional vendor-specific parameters, if needed. */
51
+ readonly libraryOptions?: Record<string, unknown> | undefined;
52
+ }
53
+ /** The result interface if validation fails. */
54
+ interface FailureResult {
55
+ /** The issues of failed validation. */
56
+ readonly issues: ReadonlyArray<Issue>;
57
+ }
58
+ /** The issue interface of the failure output. */
59
+ interface Issue {
60
+ /** The error message of the issue. */
61
+ readonly message: string;
62
+ /** The path of the issue, if any. */
63
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
64
+ }
65
+ /** The path segment interface of the issue. */
66
+ interface PathSegment {
67
+ /** The key representing a path segment. */
68
+ readonly key: PropertyKey;
69
+ }
70
+ /** The Standard types interface. */
71
+ interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
72
+ /** Infers the input type of a Standard. */
73
+ type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
74
+ /** Infers the output type of a Standard. */
75
+ type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
+ }
77
+ //#endregion
78
+ //#region ../internal/src/operation-definition.d.ts
79
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
+ type OperationKind = "read" | "write" | "destructive";
81
+ /** The signed-in user of a call. */
82
+ interface OperationUser {
83
+ id: string;
84
+ name?: string;
85
+ email?: string;
86
+ image?: string;
87
+ [key: string]: unknown;
88
+ }
89
+ /** The Agent Actor when an agent calls through a capability or MCP on behalf of a user. */
90
+ interface OperationActor {
91
+ id: string;
92
+ kind?: string;
93
+ label?: string;
94
+ meta?: object;
95
+ }
96
+ /** The checked Console access of a call. `vite-hub` issues it. `ConsoleAccess` has this shape. */
97
+ interface OperationAccess {
98
+ readonly mode: string;
99
+ /**
100
+ * The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
101
+ * operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
102
+ * calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
103
+ * allows only the reads of that scope.
104
+ */
105
+ readonly sections: "all" | readonly string[];
106
+ readonly user?: OperationUser;
107
+ }
108
+ interface OperationContext {
109
+ /** The checked Console access of the call. */
110
+ access: OperationAccess;
111
+ /** The signed-in user, or null. */
112
+ user: OperationUser | null;
113
+ /** The Agent Actor when an agent calls on behalf of `user`. */
114
+ actor?: OperationActor;
115
+ surface: "console" | "cli" | "mcp" | "agent";
116
+ /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
117
+ development?: boolean;
118
+ /**
119
+ * The project root of a development server, for operations that read build files, such as `bundle.report`. Hosts set
120
+ * it only with `development`, so a deployed server never reads project files through it.
121
+ */
122
+ projectRoot?: string;
123
+ env?: Record<string, unknown>;
124
+ waitUntil?: (task: Promise<unknown>) => void;
125
+ request?: Request;
126
+ /**
127
+ * The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
128
+ * with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
129
+ * of Comments.
130
+ */
131
+ event?: unknown;
132
+ /** Operations set a success status here, such as 202 for an accepted call. */
133
+ response?: {
134
+ status?: number;
135
+ };
136
+ /**
137
+ * An agent or an MCP client may pass `lease: "override"` to `content.save`, `content.remove`, and `content.restore`
138
+ * only when the developer allowed it. Defaults to false, so a model cannot take over a document that a person is editing.
139
+ */
140
+ overrideLeases?: boolean;
141
+ /**
142
+ * What an Agent may read of the Channel conversations, set by `operations({ conversations })`. `participant`: only the
143
+ * threads that the Actor takes part in. `all`: every thread. Unset: none.
144
+ */
145
+ conversations?: "all" | "participant";
146
+ }
147
+ interface OperationDefinition<Input, Output> {
148
+ /** `<section>.<verb>`, such as `content.publish`. Unique per app. */
149
+ name: string;
150
+ /** One sentence. Becomes the CLI help line and the MCP tool description. */
151
+ description: string;
152
+ /**
153
+ * Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
154
+ * from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
155
+ * scope and read-only grants. A function that returns an invalid id denies the call.
156
+ */
157
+ section: string | false | ((input: Input) => string | undefined);
158
+ /**
159
+ * The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
160
+ * the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
161
+ * `:` needs the whole section.
162
+ */
163
+ scope?: (input: Input) => string | undefined;
164
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
165
+ kind: OperationKind;
166
+ /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
167
+ input: StandardSchemaV1<unknown, Input>;
168
+ output?: StandardSchemaV1<unknown, Output>;
169
+ cli?: {
170
+ /** Defaults: namespace = section, command = verb. */
171
+ namespace?: string;
172
+ /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
173
+ command?: string;
174
+ /** Input keys read from positional arguments, in order. */
175
+ positional?: string[];
176
+ /** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
177
+ format?: (output: Output) => string;
178
+ /** `vitehub <namespace>` runs this command when no command is named. */
179
+ default?: boolean;
180
+ };
181
+ /** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
182
+ maxRequestBytes?: number;
183
+ /**
184
+ * Returns true when this call only reads, such as a dry run of a `destructive` operation. The CLI then skips the
185
+ * confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
186
+ */
187
+ readOnlyWhen?: (input: Input) => boolean;
188
+ /**
189
+ * How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
190
+ * Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
191
+ * result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
192
+ * is the result as JSON.
193
+ */
194
+ mcp?: false | {
195
+ title?: string;
196
+ format?: (output: NoInfer<Output>) => string;
197
+ };
198
+ /** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
199
+ user?: false;
200
+ /**
201
+ * The operation runs code of the app, such as a workflow, a job, a task, or a schedule. The Console registers it only
202
+ * when `console.invoke` is on, which is the default in development and off in a production build.
203
+ */
204
+ invoke?: true;
205
+ run: (input: Input, context: OperationContext) => Output | Promise<Output>;
206
+ }
207
+ /** An operation of any input and output, as a registry holds it. */
208
+ interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
209
+ readOnlyWhen?: (input: never) => boolean;
210
+ cli?: {
211
+ namespace?: string;
212
+ command?: string;
213
+ default?: boolean;
214
+ positional?: string[];
215
+ format?: (output: never) => string;
216
+ };
217
+ mcp?: false | {
218
+ title?: string;
219
+ format?: (output: never) => string;
220
+ };
221
+ input: StandardSchemaV1;
222
+ output?: StandardSchemaV1;
223
+ run: (input: never, context: OperationContext) => unknown;
224
+ scope?: (input: never) => string | undefined;
225
+ section: string | false | ((input: never) => string | undefined);
226
+ }
227
+ /** The contribution of one plugin: operations, or a module that exports them. */
228
+ interface OperationContributionEntry {
229
+ /** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
230
+ module: string;
231
+ /** Named export that holds an operation or an array of operations. Defaults to `default`. */
232
+ export?: string;
233
+ /** Loads the export in the tool process, for a module that the tool cannot resolve by name. */
234
+ load?: () => Promise<unknown>;
235
+ /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
236
+ runtime?: false;
237
+ }
238
+ //#endregion
239
+ export { OperationContributionEntry as n, AnyOperation as t };
@@ -0,0 +1,14 @@
1
+ import { a as BundleExplanation, g as BundleRouteExplanation } from "./types-DBa_sXqC.js";
2
+ import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
3
+ //#region src/operations.d.ts
4
+ /** What `bundle.why` returns. `vitehub bundle why --json` prints the same object. */
5
+ export type BundleWhyResult = BundleRouteExplanation | {
6
+ target: string;
7
+ unavailable: string;
8
+ } | {
9
+ target: string;
10
+ explanations: BundleExplanation[];
11
+ };
12
+ /** The `bundle.*` operations. The Console and the ViteHub MCP call them on a dev server. `vitehub bundle` reads the same files. */
13
+ export declare const bundleOperations: readonly AnyOperation[];
14
+ //#endregion
@@ -0,0 +1,476 @@
1
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { defineDiagnostics } from "nostics";
3
+ import { toJsonSchema } from "@valibot/to-json-schema";
4
+ import * as v from "valibot";
5
+ //#region ../internal/src/error-diagnostics.ts
6
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
7
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
8
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
9
+ codes: {
10
+ INTERNAL_R0012: {
11
+ ...dynamicError,
12
+ fix: "Check the URL, the headers, and the credentials of the HTTP request. `error.status` holds the status that the server sent."
13
+ },
14
+ INTERNAL_R0013: {
15
+ ...dynamicError,
16
+ 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."
17
+ },
18
+ INTERNAL_R0014: {
19
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
20
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
21
+ },
22
+ INTERNAL_R0020: {
23
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
24
+ why: ({ message }) => message === void 0 ? "" : String(message)
25
+ },
26
+ INTERNAL_R0021: {
27
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
28
+ why: ({ message }) => message === void 0 ? "" : String(message)
29
+ },
30
+ INTERNAL_R0022: {
31
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
32
+ why: ({ message }) => message === void 0 ? "" : String(message)
33
+ },
34
+ INTERNAL_R0024: {
35
+ 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>.",
36
+ why: ({ message }) => message === void 0 ? "" : String(message)
37
+ },
38
+ INTERNAL_R0023: {
39
+ fix: "Ask for access to the section of this operation.",
40
+ why: ({ message }) => message === void 0 ? "" : String(message)
41
+ },
42
+ INTERNAL_B0001: {
43
+ ...dynamicError,
44
+ 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."
45
+ },
46
+ INTERNAL_B0015: {
47
+ ...dynamicError,
48
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
49
+ },
50
+ INTERNAL_B0016: {
51
+ ...dynamicError,
52
+ 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."
53
+ },
54
+ INTERNAL_B0017: {
55
+ ...dynamicError,
56
+ 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."
57
+ },
58
+ INTERNAL_B0018: {
59
+ ...dynamicError,
60
+ 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."
61
+ },
62
+ INTERNAL_B0019: {
63
+ ...dynamicError,
64
+ 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."
65
+ },
66
+ INTERNAL_B0020: {
67
+ ...dynamicError,
68
+ 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."
69
+ },
70
+ INTERNAL_B0021: {
71
+ ...dynamicError,
72
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
73
+ },
74
+ INTERNAL_B0022: {
75
+ ...dynamicError,
76
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`."
77
+ },
78
+ INTERNAL_B0025: {
79
+ ...dynamicError,
80
+ 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."
81
+ },
82
+ INTERNAL_B0026: {
83
+ ...dynamicError,
84
+ 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>\")`."
85
+ },
86
+ INTERNAL_B0027: {
87
+ ...dynamicError,
88
+ 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`."
89
+ },
90
+ INTERNAL_B0028: {
91
+ ...dynamicError,
92
+ fix: "Wait for the other build of this app to finish, or stop the process that the message names, then build again."
93
+ },
94
+ INTERNAL_B0029: {
95
+ ...dynamicError,
96
+ 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."
97
+ },
98
+ INTERNAL_B0031: {
99
+ ...dynamicError,
100
+ 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."
101
+ },
102
+ INTERNAL_B0032: {
103
+ ...dynamicError,
104
+ 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."
105
+ },
106
+ INTERNAL_B0035: {
107
+ ...dynamicError,
108
+ fix: "Delete the provider output folder that holds the file that the message names, such as `dist/<app>` for Cloudflare, and build again."
109
+ },
110
+ INTERNAL_B0039: {
111
+ ...dynamicError,
112
+ fix: "Fix the build error that ViteHub showed before this one. ViteHub stops writing the provider output when another part of the build fails."
113
+ },
114
+ INTERNAL_B0040: {
115
+ ...dynamicError,
116
+ fix: "Remove the custom Nitro `output.serverDir`, so that the Nitro preset of the host writes the server entry that the message names."
117
+ },
118
+ INTERNAL_B0043: {
119
+ ...dynamicError,
120
+ fix: "Delete the build output folder, such as `.output` or `.vercel/output`, and build again."
121
+ },
122
+ INTERNAL_B0046: {
123
+ ...dynamicError,
124
+ fix: "Install the package that the message names in the app, for example with `pnpm add <name>`, then build again."
125
+ },
126
+ INTERNAL_B0047: {
127
+ ...dynamicError,
128
+ 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."
129
+ },
130
+ INTERNAL_B0048: {
131
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
132
+ why: ({ message }) => message === void 0 ? "" : String(message)
133
+ },
134
+ INTERNAL_B0049: {
135
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
136
+ why: ({ message }) => message === void 0 ? "" : String(message)
137
+ },
138
+ INTERNAL_B0050: {
139
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
140
+ why: ({ message }) => message === void 0 ? "" : String(message)
141
+ },
142
+ INTERNAL_B0051: {
143
+ 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}.`,
144
+ fix: "Remove the entry from the project's Wrangler config, since ViteHub writes it, or give one of them another name."
145
+ },
146
+ INTERNAL_B0052: {
147
+ why: ({ column, section }) => `The column "${column}" of the Console section "${section}" needs both \`format: "switch"\` and a \`switch\` operation name such as "skills.set".`,
148
+ fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
149
+ },
150
+ INTERNAL_R0025: {
151
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
152
+ why: ({ message }) => message === void 0 ? "" : String(message)
153
+ },
154
+ INTERNAL_R0026: {
155
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
156
+ fix: "Review the operation, then run it again with --yes to confirm the change."
157
+ },
158
+ INTERNAL_C0001: {
159
+ ...dynamicError,
160
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
161
+ },
162
+ INTERNAL_C0002: {
163
+ ...dynamicError,
164
+ fix: "Rename or remove one of the two files that the message lists. ViteHub takes the Definition name from the file path."
165
+ },
166
+ INTERNAL_R0001: {
167
+ ...dynamicError,
168
+ 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."
169
+ },
170
+ INTERNAL_R0002: {
171
+ ...dynamicError,
172
+ 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."
173
+ },
174
+ INTERNAL_R0004: {
175
+ ...dynamicError,
176
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
177
+ },
178
+ INTERNAL_R0005: {
179
+ ...dynamicError,
180
+ fix: "Set `method` of the HTTP request to `GET`, `HEAD`, or `POST`."
181
+ },
182
+ INTERNAL_R0006: {
183
+ ...dynamicError,
184
+ fix: "Set `timeout` of the HTTP request to a number of milliseconds from 1 to 2147483647, or remove it to use the default."
185
+ },
186
+ INTERNAL_R0007: {
187
+ ...dynamicError,
188
+ 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."
189
+ },
190
+ INTERNAL_R0008: {
191
+ ...dynamicError,
192
+ 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."
193
+ },
194
+ INTERNAL_R0009: {
195
+ ...dynamicError,
196
+ fix: "Use a Standard Schema whose `validate()` returns `{ value }` or `{ issues }` for the value that the message names."
197
+ },
198
+ INTERNAL_R0010: {
199
+ ...dynamicError,
200
+ fix: "Run the command again. If the error stays, check the Cloudflare API status, because Cloudflare sent a response that ViteHub cannot read."
201
+ },
202
+ INTERNAL_R0011: {
203
+ ...dynamicError,
204
+ fix: "Pass an h3 app, an object with a `fetch(request)` method, or a fetch function as `app`."
205
+ },
206
+ INTERNAL_CONSOLE_KEY_NAME_INVALID: {
207
+ why: ({ name }) => `[vitehub] The Console key name ${JSON.stringify(name)} must be 1 to 64 of A-Z, 0-9, and _.`,
208
+ 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>`."
209
+ },
210
+ INTERNAL_CONSOLE_PRIVATE_KEY_INVALID: {
211
+ why: "[vitehub] A Console private key is the 32-byte Ed25519 seed as base64url (43 characters). `vitehub secret console-key` makes one.",
212
+ fix: "Run `vitehub secret console-key` and use the 43-character private key that it prints, without spaces or quotes."
213
+ },
214
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLES_MULTIPLE: {
215
+ why: ({ prefix, variables }) => `[vitehub] Set one ${prefix}<NAME> variable. This environment has ${variables}.`,
216
+ fix: "Keep one `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` variable in the environment of the command, and unset the others that the message names."
217
+ },
218
+ INTERNAL_CONSOLE_PRIVATE_KEY_VARIABLE_INVALID: {
219
+ 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 _.`,
220
+ 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>`."
221
+ },
222
+ INTERNAL_DEV_SERVER_NOT_FOUND: {
223
+ why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
224
+ fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
225
+ },
226
+ INTERNAL_FORGE_NOT_INSTALLED: {
227
+ why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
228
+ fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
229
+ },
230
+ INTERNAL_MCP_ARGUMENTS_INVALID: {
231
+ why: ({ detail }) => detail,
232
+ fix: "Pass the prompt or resource the arguments that `prompts/list` or `resources/templates/list` describes for it."
233
+ },
234
+ INTERNAL_MCP_METHOD_FAILED: {
235
+ why: ({ name }) => `${name} failed on the server.`,
236
+ fix: "Read the server log for the error of the MCP prompt or resource that the message names, and fix its handler."
237
+ },
238
+ INTERNAL_MCP_RESOURCE_NOT_FOUND: {
239
+ why: ({ uri }) => `Resource not found: ${uri}. Call resources/list or resources/templates/list for the resources of this server.`,
240
+ fix: "Call `resources/list` or `resources/templates/list`, and read a URI that one of them returns."
241
+ },
242
+ INTERNAL_PRESET_OPTION_UNKNOWN: {
243
+ why: ({ key, label }) => `[vitehub] Unknown ${label} option "${key}".`,
244
+ fix: "Remove the option that the message names from the preset options, or correct its spelling to an option that the preset declares."
245
+ },
246
+ INTERNAL_PRESET_TUPLE_INVALID: {
247
+ why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
248
+ fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
249
+ },
250
+ INTERNAL_SECRET_PURPOSE_MISSING: {
251
+ why: "[vitehub] A derived secret requires a purpose.",
252
+ fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
253
+ },
254
+ INTERNAL_SECRET_TOO_SHORT: {
255
+ why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
256
+ fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
257
+ },
258
+ INTERNAL_SQLITE_ARGUMENT_INVALID: {
259
+ 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",
260
+ 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."
261
+ },
262
+ INTERNAL_SQLITE_INTEGER_UNSAFE: {
263
+ why: "Received integer which cannot be safely represented as a JavaScript number",
264
+ fix: "Create the client with `intMode: \"bigint\"` or `intMode: \"string\"`, or read the column with `CAST(column AS TEXT)` in the query."
265
+ },
266
+ INTERNAL_VALIBOT_JSON_SCHEMA_TARGET_UNSUPPORTED: {
267
+ why: ({ target }) => `[vitehub] Valibot cannot convert a schema to the ${target} JSON Schema target.`,
268
+ 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 })`."
269
+ }
270
+ }
271
+ });
272
+ //#endregion
273
+ //#region ../internal/src/standard-schema.ts
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/src/valibot.ts
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/src/operation-definition.ts
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
+ //#region src/operations.ts
407
+ /** Why `bundle.report` and `bundle.why` cannot answer. The checks of a report are in `bundleDiagnostics`. */
408
+ const bundleOperationDiagnostics = /*#__PURE__*/ defineDiagnostics({
409
+ docsBase: "https://vitehub.dev/docs/bundle/diagnostics",
410
+ codes: {
411
+ BUNDLE_DEV_SERVER_REQUIRED: {
412
+ why: "The bundle report is a file of the build in `.vitehub/bundle/`. Only the dev server of the project can read it. A deployed server has no project files.",
413
+ fix: "Call the operation on the dev server of the project (`vite dev` or `nuxt dev`), or run `vitehub bundle` in the project."
414
+ },
415
+ BUNDLE_REPORT_MISSING: {
416
+ why: "There is no bundle report in `.vitehub/bundle/`. No production build with `bundle: true` ran in this project.",
417
+ fix: "Set `bundle: true` in `vitehub()` (vite.config.ts) or in `vitehub` (nuxt.config.ts), then run `vite build` or `nuxt build`."
418
+ }
419
+ }
420
+ });
421
+ const reader = () => import("./index.js");
422
+ /** The environment reports of the project that the dev server runs. A deployed server has no project files. */
423
+ async function reportsOf(context) {
424
+ if (context.development !== true || !context.projectRoot) throw Object.assign(bundleOperationDiagnostics.BUNDLE_DEV_SERVER_REQUIRED(), { status: 409 });
425
+ const reports = (await reader()).readEnvironmentReports(context.projectRoot);
426
+ if (!reports.length) throw Object.assign(bundleOperationDiagnostics.BUNDLE_REPORT_MISSING(), { status: 404 });
427
+ return reports;
428
+ }
429
+ function defineBundleOperation(definition) {
430
+ return defineOperation({
431
+ ...definition,
432
+ kind: "read",
433
+ section: "bundle",
434
+ user: false
435
+ });
436
+ }
437
+ /** The `bundle.*` operations. The Console and the ViteHub MCP call them on a dev server. `vitehub bundle` reads the same files. */
438
+ const bundleOperations = [defineBundleOperation({
439
+ cli: {
440
+ command: "report",
441
+ default: true,
442
+ namespace: "bundle"
443
+ },
444
+ description: "Read the bundle report of the last production build: client and server bytes, startup bytes, the largest groups, and the checks.",
445
+ input: v.strictObject({}),
446
+ mcp: { title: "Bundle report" },
447
+ name: "bundle.report",
448
+ run: async (_input, context) => (await reader()).createBundleReport(await reportsOf(context))
449
+ }), defineBundleOperation({
450
+ cli: {
451
+ command: "why",
452
+ namespace: "bundle",
453
+ positional: ["target"]
454
+ },
455
+ description: "Explain why a package, a file, or a group is in the last production build, with its bytes, whether it loads at startup, and the import chain from the entry. A page route such as /docs/kv shows what a first visit loads.",
456
+ input: v.strictObject({ target: v.pipe(v.string(), v.trim(), v.minLength(1, "Name a package, a file, a group, or a page route.")) }),
457
+ mcp: { title: "Why is it in the bundle" },
458
+ name: "bundle.why",
459
+ run: async ({ target }, context) => {
460
+ const reports = await reportsOf(context);
461
+ const { createBundleReport, explainBundle, explainBundleRoute } = await reader();
462
+ const route = target.startsWith("/") ? explainBundleRoute(reports, target) : void 0;
463
+ if (route) return route;
464
+ const explanations = explainBundle(reports, target);
465
+ const unavailable = !explanations.length && target.startsWith("/") ? createBundleReport(reports)?.client?.routesUnavailable : void 0;
466
+ return unavailable ? {
467
+ target,
468
+ unavailable
469
+ } : {
470
+ target,
471
+ explanations
472
+ };
473
+ }
474
+ })];
475
+ //#endregion
476
+ export { bundleOperations };
package/dist/vite.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { n as ViteHubCliPluginMetadata } from "./cli-ubYJpAL_.js";
2
2
  import { C as BundleStartupRule, y as BundleRouteOptions } from "./types-DBa_sXqC.js";
3
+ import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
3
4
  import { Plugin } from "vite";
4
5
  //#region src/routes.d.ts
5
6
  /** A page route with the absolute files of the components that render it, outermost first. */
@@ -69,7 +70,9 @@ export type BundleVitePlugin = Plugin & {
69
70
  startBuild: () => string;
70
71
  };
71
72
  nitro: BundleNitroModule;
72
- vitehub: ViteHubCliPluginMetadata;
73
+ vitehub: ViteHubCliPluginMetadata & {
74
+ operations: readonly OperationContributionEntry[];
75
+ };
73
76
  };
74
77
  export interface BundleViteOptions {
75
78
  /** A coordinator can pass the same fresh ID to phases running in separate processes. */
package/dist/vite.js CHANGED
@@ -1,8 +1,144 @@
1
- import { c as moduleId, h as writeEnvironmentReport, l as allocateBytes, m as writeBundleReportRoot, o as nuxtPageRoutes } from "./compare-B-xpyN4Y.js";
2
- import { n as resolveViteHubProjectRoot, t as bundleCliContributor } from "./cli-DdzHN8li.js";
1
+ import { c as moduleId, h as writeEnvironmentReport, l as allocateBytes, m as writeBundleReportRoot, o as nuxtPageRoutes } from "./compare-87VKOrA3.js";
2
+ import { n as resolveViteHubProjectRoot, t as bundleCliContributor } from "./cli-CJOjJmEo.js";
3
+ import { existsSync } from "node:fs";
3
4
  import { dirname, resolve } from "node:path";
5
+ import { defineDiagnostics } from "nostics";
6
+ import { fileURLToPath } from "node:url";
4
7
  import { randomUUID } from "node:crypto";
5
8
  import { gzipSync } from "node:zlib";
9
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
10
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
11
+ function normalizeWindowsPath(input = "") {
12
+ if (!input) return input;
13
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
14
+ }
15
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
16
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
17
+ function cwd() {
18
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
19
+ return "/";
20
+ }
21
+ const resolve$1 = function(...arguments_) {
22
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
23
+ let resolvedPath = "";
24
+ let resolvedAbsolute = false;
25
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
26
+ const path = index >= 0 ? arguments_[index] : cwd();
27
+ if (!path || path.length === 0) continue;
28
+ resolvedPath = `${path}/${resolvedPath}`;
29
+ resolvedAbsolute = isAbsolute(path);
30
+ }
31
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
32
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
33
+ return resolvedPath.length > 0 ? resolvedPath : ".";
34
+ };
35
+ function normalizeString(path, allowAboveRoot) {
36
+ let res = "";
37
+ let lastSegmentLength = 0;
38
+ let lastSlash = -1;
39
+ let dots = 0;
40
+ let char = null;
41
+ for (let index = 0; index <= path.length; ++index) {
42
+ if (index < path.length) char = path[index];
43
+ else if (char === "/") break;
44
+ else char = "/";
45
+ if (char === "/") {
46
+ if (lastSlash === index - 1 || dots === 1);
47
+ else if (dots === 2) {
48
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
49
+ if (res.length > 2) {
50
+ const lastSlashIndex = res.lastIndexOf("/");
51
+ if (lastSlashIndex === -1) {
52
+ res = "";
53
+ lastSegmentLength = 0;
54
+ } else {
55
+ res = res.slice(0, lastSlashIndex);
56
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
57
+ }
58
+ lastSlash = index;
59
+ dots = 0;
60
+ continue;
61
+ } else if (res.length > 0) {
62
+ res = "";
63
+ lastSegmentLength = 0;
64
+ lastSlash = index;
65
+ dots = 0;
66
+ continue;
67
+ }
68
+ }
69
+ if (allowAboveRoot) {
70
+ res += res.length > 0 ? "/.." : "..";
71
+ lastSegmentLength = 2;
72
+ }
73
+ } else {
74
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
75
+ else res = path.slice(lastSlash + 1, index);
76
+ lastSegmentLength = index - lastSlash - 1;
77
+ }
78
+ lastSlash = index;
79
+ dots = 0;
80
+ } else if (char === "." && dots !== -1) ++dots;
81
+ else dots = -1;
82
+ }
83
+ return res;
84
+ }
85
+ const isAbsolute = function(p) {
86
+ return _IS_ABSOLUTE_RE.test(p);
87
+ };
88
+ const dirname$1 = function(p) {
89
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
90
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
91
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
92
+ };
93
+ //#endregion
94
+ //#region ../internal/src/invariant.ts
95
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
96
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
97
+ codes: { INTERNAL_INVARIANT_FAILED: {
98
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
99
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
100
+ } }
101
+ });
102
+ /**
103
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
104
+ * Use a code from the package catalog when a developer can cause the error or fix it.
105
+ */
106
+ function invariantError(what) {
107
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
108
+ }
109
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
110
+ function invariant(condition, what) {
111
+ if (!condition) throw invariantError(what);
112
+ }
113
+ //#endregion
114
+ //#region ../internal/src/build/paths.ts
115
+ function resolveRuntimeModule(packageDir, modulePath) {
116
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
117
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
118
+ }
119
+ const packageDirs = /* @__PURE__ */ new Map();
120
+ function findPackageDir(file) {
121
+ const start = dirname$1(file);
122
+ const cached = packageDirs.get(start);
123
+ if (cached) return cached;
124
+ let dir = start;
125
+ while (!existsSync(resolve$1(dir, "package.json"))) {
126
+ const parent = dirname$1(dir);
127
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
128
+ dir = parent;
129
+ }
130
+ packageDirs.set(start, dir);
131
+ return dir;
132
+ }
133
+ /**
134
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
135
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
136
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
137
+ */
138
+ function ownModule(importMetaUrl, modulePath) {
139
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
140
+ }
141
+ //#endregion
6
142
  //#region src/collect.ts
7
143
  function isChunk(output) {
8
144
  return typeof output === "object" && output !== null && Reflect.get(output, "type") === "chunk";
@@ -287,7 +423,14 @@ function hubBundle(options = {}) {
287
423
  nitro: bundleNitroModule(() => coordinatedBuild, (instance) => {
288
424
  nitro = instance;
289
425
  }),
290
- vitehub: { cli: bundleCliContributor }
426
+ vitehub: {
427
+ cli: bundleCliContributor,
428
+ operations: [{
429
+ export: "bundleOperations",
430
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).bundleOperations,
431
+ module: ownModule(import.meta.url, "operations")
432
+ }]
433
+ }
291
434
  };
292
435
  }
293
436
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/bundle",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "Bundle reports for ViteHub apps: client and server size, startup cost, and why each package is in the output.",
5
5
  "keywords": [
6
6
  "bundle",
@@ -46,7 +46,9 @@
46
46
  "./package.json": "./package.json"
47
47
  },
48
48
  "dependencies": {
49
+ "@valibot/to-json-schema": "^1.8.0",
49
50
  "nostics": "1.4.0",
51
+ "valibot": "^1.5.0",
50
52
  "vue-router": "^5.4.0"
51
53
  },
52
54
  "devDependencies": {
@@ -67,7 +69,7 @@
67
69
  }
68
70
  },
69
71
  "engines": {
70
- "node": ">=22.18.0"
72
+ "node": ">=24.15.0"
71
73
  },
72
74
  "scripts": {
73
75
  "build": "vp pack",