@vite-hub/bundle 0.0.0-stage → 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.
@@ -0,0 +1,46 @@
1
+ import { C as BundleStartupRule, S as BundleSideComparison, _ as BundleRouteFile, a as BundleExplanation, b as BundleRouteSource, c as BundleFindingCode, d as BundleGroupKind, f as BundleGroupSize, g as BundleRouteExplanation, h as BundleRoute, i as BundleEnvironmentReport, l as BundleGroup, m as BundleReport, n as BundleChunk, o as BundleFile, p as BundleModule, r as BundleComparison, s as BundleFinding, t as BundleChainStep, u as BundleGroupChange, v as BundleRouteModule, w as BundleTotals, x as BundleSide, y as BundleRouteOptions } from "./types-DBa_sXqC.js";
2
+ //#region src/compare.d.ts
3
+ /** What changed from `before` to `after`: the bytes of each side and of its startup code, and each group that changed. */
4
+ export declare function compareBundleReports(before: BundleReport, after: BundleReport): BundleComparison;
5
+ /**
6
+ * Reads a report to compare with. `path` is the output of `vitehub bundle --json`, a copy of `.vitehub/bundle/`, or a
7
+ * project root that has `.vitehub/bundle/`. Returns `undefined` when `path` holds no report.
8
+ */
9
+ export declare function readSavedBundleReport(path: string): BundleReport | undefined;
10
+ //#endregion
11
+ //#region src/files.d.ts
12
+ /** Folder of the environment reports, relative to the project root. */
13
+ export declare const bundleReportDir = ".vitehub/bundle";
14
+ /** Reads every environment report in `.vitehub/bundle/`. A file that is not a report is skipped. */
15
+ export declare function readEnvironmentReports(root: string): BundleEnvironmentReport[];
16
+ //#endregion
17
+ //#region src/groups.d.ts
18
+ /** Names the group of a root-relative module id. */
19
+ export declare function moduleGroup(id: string): {
20
+ name: string;
21
+ kind: BundleGroupKind;
22
+ };
23
+ //#endregion
24
+ //#region src/report.d.ts
25
+ /** Joins the environment reports of one build into the report of the app. */
26
+ export declare function createBundleReport(reports: readonly BundleEnvironmentReport[]): BundleReport | undefined;
27
+ /**
28
+ * Says why a package, a file, or a group is in the output: its bytes on each side, whether it loads at startup, and
29
+ * the shortest import chain from the entry. A chain through Nuxt's SSR output continues inside the SSR build.
30
+ */
31
+ export declare function explainBundle(reports: readonly BundleEnvironmentReport[], target: string): BundleExplanation[];
32
+ /**
33
+ * Says what the browser loads on a first visit to a page route, such as `/docs/kv`: the startup files, the files of the
34
+ * route's layout and pages, and the modules that the route adds. `undefined` when no route of the last build matches.
35
+ */
36
+ export declare function explainBundleRoute(reports: readonly BundleEnvironmentReport[], target: string): BundleRouteExplanation | undefined;
37
+ //#endregion
38
+ //#region src/index.d.ts
39
+ /** The report of the last build with `bundle` on, or `undefined` when there is none. */
40
+ export declare function readBundleReport(root: string): BundleReport | undefined;
41
+ /** Why `target` (a package, a file, or a group) is in the last build. Empty when the build does not contain it. */
42
+ export declare function explainBundleTarget(root: string, target: string): BundleExplanation[];
43
+ /** What the browser loads on a first visit to the page route that renders `path`, such as `/docs/kv`. */
44
+ export declare function explainBundleRouteTarget(root: string, path: string): BundleRouteExplanation | undefined;
45
+ //#endregion
46
+ export type { BundleChainStep, BundleChunk, BundleComparison, BundleEnvironmentReport, BundleExplanation, BundleFile, BundleFinding, BundleFindingCode, BundleGroup, BundleGroupChange, BundleGroupKind, BundleGroupSize, BundleModule, BundleReport, BundleRoute, BundleRouteExplanation, BundleRouteFile, BundleRouteModule, BundleRouteOptions, BundleRouteSource, BundleSide, BundleSideComparison, BundleStartupRule, BundleTotals };
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
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";
2
+ //#region src/index.ts
3
+ /** The report of the last build with `bundle` on, or `undefined` when there is none. */
4
+ function readBundleReport(root) {
5
+ return createBundleReport(readEnvironmentReports(root));
6
+ }
7
+ /** Why `target` (a package, a file, or a group) is in the last build. Empty when the build does not contain it. */
8
+ function explainBundleTarget(root, target) {
9
+ return explainBundle(readEnvironmentReports(root), target);
10
+ }
11
+ /** What the browser loads on a first visit to the page route that renders `path`, such as `/docs/kv`. */
12
+ function explainBundleRouteTarget(root, path) {
13
+ return explainBundleRoute(readEnvironmentReports(root), path);
14
+ }
15
+ //#endregion
16
+ export { bundleReportDir, compareBundleReports, createBundleReport, explainBundle, explainBundleRoute, explainBundleRouteTarget, explainBundleTarget, moduleGroup, readBundleReport, readEnvironmentReports, readSavedBundleReport };
@@ -0,0 +1,239 @@
1
+ //#region src/types.d.ts
2
+ /** What put a module in the output. */
3
+ type BundleGroupKind = "app" | "dependency" | "framework" | "generated" | "vitehub";
4
+ /** One source module in one output chunk. */
5
+ interface BundleModule {
6
+ /** Path relative to the project root, or `node_modules/<package>/<file>` for a dependency. */
7
+ id: string;
8
+ /** The module's share of the chunk's output bytes. */
9
+ bytes: number;
10
+ /** Modules that this module imports statically, by `id`. Only modules in the same build. */
11
+ imports: string[];
12
+ /** Modules that this module imports with `import()`, by `id`. */
13
+ dynamicImports: string[];
14
+ /** The module is an entry of the build. */
15
+ entry: boolean;
16
+ }
17
+ /** One JavaScript file that a build wrote. */
18
+ interface BundleChunk {
19
+ /** Path relative to the build's output folder. */
20
+ file: string;
21
+ bytes: number;
22
+ gzip: number;
23
+ entry: boolean;
24
+ /** The file loads when the entry loads: the entry, and every file it imports statically. */
25
+ startup: boolean;
26
+ /** Files that this file imports statically. The browser loads them with it. */
27
+ imports?: string[];
28
+ /** CSS files that load with this file. Client only. */
29
+ css?: string[];
30
+ modules: BundleModule[];
31
+ }
32
+ /** What one Vite environment or one Nitro build wrote. ViteHub writes one file for each to `.vitehub/bundle/`. */
33
+ interface BundleEnvironmentReport {
34
+ schemaVersion: 1;
35
+ /** Same for every environment of one build command. */
36
+ build: string;
37
+ /** Vite environment name, such as `client` or `ssr`, or `nitro` for the server build. */
38
+ environment: string;
39
+ side: "client" | "server";
40
+ /** The output folder, relative to the project root. */
41
+ outDir: string;
42
+ /** The Nitro preset of the server build, such as `cloudflare-module` or `node-server`. */
43
+ host?: string;
44
+ /** What the features of this build declare about the server output. Only on the server side. */
45
+ rules?: BundleStartupRule[];
46
+ chunks: BundleChunk[];
47
+ /** CSS files that the build wrote. Client only. */
48
+ css?: BundleFile[];
49
+ /** The page routes of the app and the components that render them. Client of a Nuxt app only. */
50
+ routes?: BundleRouteSource[];
51
+ routeOptions?: BundleRouteOptions;
52
+ }
53
+ /** Matching options captured by the framework, without loading the app when reading a report. */
54
+ interface BundleRouteOptions {
55
+ sensitive?: boolean;
56
+ strict?: boolean;
57
+ /** Why static route reporting is unavailable for this build. */
58
+ unavailable?: string;
59
+ }
60
+ /**
61
+ * Packages that a feature knows this build never runs at server startup. The feature derives it from its resolved
62
+ * configuration, for example the Database when every Database uses a D1 binding. It adds the rule in the Nitro hook
63
+ * `vitehub:bundle:rules`.
64
+ */
65
+ interface BundleStartupRule {
66
+ /** The package that declares the rule. Independent consumers of `packages` suppress the finding. */
67
+ owner: string;
68
+ /** Package names, as `vitehub bundle` groups them. Put the package that code imports first: findings explain it. */
69
+ packages: string[];
70
+ /** Why this build does not need the packages at startup. */
71
+ why: string;
72
+ /** What to change when one of them loads at startup. */
73
+ fix: string;
74
+ }
75
+ type BundleFindingCode = "BUNDLE_STARTUP_UNUSED" | "BUNDLE_HOST_SIZE_LIMIT";
76
+ /**
77
+ * A problem that the report proves. `error` means that the host rejects the deployment, and `vitehub bundle` exits
78
+ * with 1. `warning` means that the app works but loads code that it does not need.
79
+ */
80
+ interface BundleFinding {
81
+ code: BundleFindingCode;
82
+ severity: "error" | "warning";
83
+ side: "client" | "server";
84
+ why: string;
85
+ fix: string;
86
+ docs: string;
87
+ /** The bytes that the finding is about, before compression. */
88
+ bytes: number;
89
+ /** The import chain from the entry to the module that the finding is about, as `vitehub bundle why` gives it. */
90
+ chain: BundleChainStep[];
91
+ }
92
+ interface BundleGroup {
93
+ /** `@vite-hub/agent`, `vite-hub/console`, `h3`, `server/api`, `.nuxt`, ... */
94
+ name: string;
95
+ kind: BundleGroupKind;
96
+ bytes: number;
97
+ /** Bytes of the group in files that load at startup. */
98
+ startupBytes: number;
99
+ modules: number;
100
+ }
101
+ interface BundleSide {
102
+ /** The environments that this side joins, such as `["nitro", "ssr"]`. */
103
+ environments: string[];
104
+ bytes: number;
105
+ gzip: number;
106
+ chunks: number;
107
+ startup: {
108
+ bytes: number;
109
+ gzip: number;
110
+ chunks: number;
111
+ };
112
+ /** Largest first. */
113
+ groups: BundleGroup[];
114
+ /** What a first visit to each page route loads, largest first. Client of a Nuxt app only. */
115
+ routes?: BundleRoute[];
116
+ /** Why the build cannot provide static route estimates. */
117
+ routesUnavailable?: string;
118
+ }
119
+ /** The output of one build, for the whole app. `vitehub bundle --json` prints it. */
120
+ interface BundleReport {
121
+ schemaVersion: 1;
122
+ build: string;
123
+ /** The Nitro preset of the server build. */
124
+ host?: string;
125
+ client?: BundleSide;
126
+ server?: BundleSide;
127
+ /** Problems that the report proves. Empty when there are none. */
128
+ findings: BundleFinding[];
129
+ }
130
+ /** One step of an import chain. */
131
+ interface BundleChainStep {
132
+ environment: string;
133
+ id: string;
134
+ }
135
+ interface BundleExplanation {
136
+ /** The module that matched, by `id`. */
137
+ target: string;
138
+ group: string;
139
+ side: "client" | "server";
140
+ bytes: number;
141
+ startup: boolean;
142
+ /** From the build entry to the target. */
143
+ chain: BundleChainStep[];
144
+ }
145
+ /** One file that a build wrote, with its size. */
146
+ interface BundleFile {
147
+ /** Path relative to the build's output folder. */
148
+ file: string;
149
+ bytes: number;
150
+ gzip: number;
151
+ }
152
+ /** A page route and the components that render it, as the framework resolves them. */
153
+ interface BundleRouteSource {
154
+ /** The route path, such as `/docs/:slug()`. */
155
+ path: string;
156
+ /** The layout and the page components of the route, outermost first, by module `id`. */
157
+ components: string[];
158
+ }
159
+ /** One file that a first visit to a route loads. */
160
+ interface BundleRouteFile extends BundleFile {
161
+ /** The file loads on every page because the entry imports it. */
162
+ startup: boolean;
163
+ }
164
+ /**
165
+ * What the browser loads on a first visit to a page route: the startup files, and the files of the route's layout and
166
+ * page components with every file that they import statically. Files that the page loads later with `import()` do not
167
+ * count.
168
+ */
169
+ interface BundleRoute extends BundleRouteSource {
170
+ /** JavaScript bytes of a first visit. */
171
+ bytes: number;
172
+ gzip: number;
173
+ /** The part of `bytes` that only some routes load: the files that are not startup files. */
174
+ pageBytes: number;
175
+ /** CSS bytes of a first visit. Nuxt can inline some of this CSS in the HTML. */
176
+ cssBytes: number;
177
+ /** JavaScript and CSS files, largest first. */
178
+ files: BundleRouteFile[];
179
+ }
180
+ /** A module in a file that only some routes load. */
181
+ interface BundleRouteModule {
182
+ id: string;
183
+ /** The output file that holds the module. */
184
+ file: string;
185
+ bytes: number;
186
+ }
187
+ interface BundleRouteExplanation {
188
+ /** The path that was asked for, such as `/docs/kv`. */
189
+ target: string;
190
+ route: BundleRoute;
191
+ /** Modules of the files that are not startup files, largest first. They are what the route adds. */
192
+ modules: BundleRouteModule[];
193
+ }
194
+ /** Bytes of a side, as `vitehub bundle --against` compares them. */
195
+ interface BundleTotals {
196
+ bytes: number;
197
+ gzip: number;
198
+ startupBytes: number;
199
+ startupGzip: number;
200
+ }
201
+ /** Bytes of a group, as `vitehub bundle --against` compares them. */
202
+ interface BundleGroupSize {
203
+ bytes: number;
204
+ startupBytes: number;
205
+ }
206
+ /**
207
+ * A group that changed between two builds. `added` and `removed` mean that the group is in one build only. Otherwise
208
+ * the total bytes decide between `grew` and `shrank`, and the startup bytes decide when the total did not change.
209
+ */
210
+ interface BundleGroupChange {
211
+ name: string;
212
+ kind: BundleGroupKind;
213
+ change: "added" | "removed" | "grew" | "shrank";
214
+ before: BundleGroupSize;
215
+ after: BundleGroupSize;
216
+ /** `after` minus `before`. */
217
+ delta: BundleGroupSize;
218
+ }
219
+ /** One side of two builds. A side that a build does not have counts as 0 bytes. */
220
+ interface BundleSideComparison {
221
+ before: BundleTotals;
222
+ after: BundleTotals;
223
+ /** `after` minus `before`. */
224
+ delta: BundleTotals;
225
+ /** Only the groups that changed, the largest change first. */
226
+ groups: BundleGroupChange[];
227
+ }
228
+ /** What changed from one build to the next. `vitehub bundle --against <saved report> --json` prints it. */
229
+ interface BundleComparison {
230
+ schemaVersion: 1;
231
+ builds: {
232
+ before: string;
233
+ after: string;
234
+ };
235
+ client?: BundleSideComparison;
236
+ server?: BundleSideComparison;
237
+ }
238
+ //#endregion
239
+ export { BundleStartupRule as C, BundleSideComparison as S, BundleRouteFile as _, BundleExplanation as a, BundleRouteSource as b, BundleFindingCode as c, BundleGroupKind as d, BundleGroupSize as f, BundleRouteExplanation as g, BundleRoute as h, BundleEnvironmentReport as i, BundleGroup as l, BundleReport as m, BundleChunk as n, BundleFile as o, BundleModule as p, BundleComparison as r, BundleFinding as s, BundleChainStep as t, BundleGroupChange as u, BundleRouteModule as v, BundleTotals as w, BundleSide as x, BundleRouteOptions as y };
package/dist/vite.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { n as ViteHubCliPluginMetadata } from "./cli-ubYJpAL_.js";
2
+ import { C as BundleStartupRule, y as BundleRouteOptions } from "./types-DBa_sXqC.js";
3
+ import { Plugin } from "vite";
4
+ //#region src/routes.d.ts
5
+ /** A page route with the absolute files of the components that render it, outermost first. */
6
+ interface PageRoute {
7
+ path: string;
8
+ files: string[];
9
+ /** Include this layout only when the route also loads its renderer. */
10
+ layout?: {
11
+ file: string;
12
+ component: string;
13
+ };
14
+ /** Suppress route estimates for this build when a route cannot be measured safely. */
15
+ unavailable?: string;
16
+ }
17
+ /** The parts of a Nuxt page that the report reads. */
18
+ interface NuxtPageLike {
19
+ path: string;
20
+ alias?: string | string[];
21
+ file?: string;
22
+ /** Named views, including `default`. */
23
+ components?: Record<string, string>;
24
+ redirect?: unknown;
25
+ meta?: {
26
+ layout?: unknown;
27
+ redirect?: unknown;
28
+ };
29
+ children?: NuxtPageLike[];
30
+ }
31
+ /**
32
+ * The routes of a Nuxt app, from the pages that Nuxt resolves and the layouts that it finds. A nested route renders
33
+ * every parent page. The layout is the last static `layout` in the page meta of the route, or `default`. A layout
34
+ * that the app sets at runtime is not known at build time.
35
+ */
36
+ export declare function nuxtPageRoutes(pages: readonly NuxtPageLike[], layouts?: Readonly<Record<string, {
37
+ file: string;
38
+ }>>, layoutComponent?: string): PageRoute[];
39
+ //#endregion
40
+ //#region src/vite.d.ts
41
+ interface BundlerConfig {
42
+ plugins?: unknown;
43
+ }
44
+ /** The parts of a Nitro 3 instance that the server report reads. */
45
+ interface NitroLike {
46
+ hooks: {
47
+ hook: (name: "build:config", callback: (nitro: unknown, config: {
48
+ rolldown?: BundlerConfig;
49
+ rollup?: BundlerConfig;
50
+ }) => void) => void;
51
+ callHook: (name: "vitehub:bundle:rules", rules: BundleStartupRule[]) => Promise<unknown> | unknown;
52
+ };
53
+ options: {
54
+ builder?: string;
55
+ dev: boolean;
56
+ preset?: string;
57
+ rootDir: string;
58
+ };
59
+ }
60
+ interface BundleNitroModule {
61
+ name: string;
62
+ setup: (nitro: NitroLike) => void;
63
+ }
64
+ export type BundleVitePlugin = Plugin & {
65
+ api: {
66
+ /** The page routes of the app. The client report keeps them, so `vitehub bundle` can say what each route loads. */
67
+ setRoutes: (routes: PageRoute[], options?: BundleRouteOptions) => void;
68
+ /** Frameworks such as Nuxt start one session before running their Vite and Nitro phases. */
69
+ startBuild: () => string;
70
+ };
71
+ nitro: BundleNitroModule;
72
+ vitehub: ViteHubCliPluginMetadata;
73
+ };
74
+ export interface BundleViteOptions {
75
+ /** A coordinator can pass the same fresh ID to phases running in separate processes. */
76
+ buildId?: string;
77
+ }
78
+ /**
79
+ * Writes a bundle report for each build environment to `.vitehub/bundle/`. `vitehub bundle` joins them into one
80
+ * report for the app. Builds without the plugin write nothing.
81
+ */
82
+ export declare function hubBundle(options?: BundleViteOptions): BundleVitePlugin;
83
+ //#endregion
84
+ export type { NuxtPageLike, PageRoute };
package/dist/vite.js ADDED
@@ -0,0 +1,294 @@
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";
3
+ import { dirname, resolve } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { gzipSync } from "node:zlib";
6
+ //#region src/collect.ts
7
+ function isChunk(output) {
8
+ return typeof output === "object" && output !== null && Reflect.get(output, "type") === "chunk";
9
+ }
10
+ function isCssAsset(output) {
11
+ return typeof output === "object" && output !== null && Reflect.get(output, "type") === "asset" && String(Reflect.get(output, "fileName")).endsWith(".css");
12
+ }
13
+ function cssFiles(bundle) {
14
+ return Object.values(bundle).filter(isCssAsset).map((asset) => {
15
+ const source = typeof asset.source === "string" ? Buffer.from(asset.source) : asset.source;
16
+ return {
17
+ file: asset.fileName,
18
+ bytes: source.byteLength,
19
+ gzip: gzipSync(source).length
20
+ };
21
+ }).sort((left, right) => right.bytes - left.bytes || left.file.localeCompare(right.file));
22
+ }
23
+ function relativeTo(root, path) {
24
+ const base = root.replace(/\\/g, "/").replace(/\/$/, "");
25
+ const normalized = path.replace(/\\/g, "/");
26
+ return normalized === base ? "." : normalized.startsWith(`${base}/`) ? normalized.slice(base.length + 1) : normalized;
27
+ }
28
+ /**
29
+ * Reads the imports of a module as report ids. The bundler drops modules that leave no code, such as a package index
30
+ * that only re-exports, so an import of such a module continues to the modules that it imports. An edge is dynamic
31
+ * when one step on the way is `import()`.
32
+ */
33
+ function createEdgeReader(ids, getModuleInfo) {
34
+ const through = /* @__PURE__ */ new Map();
35
+ const visit = (raw, visiting) => {
36
+ const cached = through.get(raw);
37
+ if (cached) return cached;
38
+ const result = {
39
+ imports: /* @__PURE__ */ new Set(),
40
+ dynamicImports: /* @__PURE__ */ new Set(),
41
+ complete: !visiting.has(raw)
42
+ };
43
+ if (!result.complete) return result;
44
+ visiting.add(raw);
45
+ const info = getModuleInfo(raw);
46
+ const add = (next, dynamic) => {
47
+ const id = ids.get(next);
48
+ if (id) {
49
+ (dynamic ? result.dynamicImports : result.imports).add(id);
50
+ return;
51
+ }
52
+ const nested = visit(next, visiting);
53
+ result.complete &&= nested.complete;
54
+ for (const found of nested.imports) (dynamic ? result.dynamicImports : result.imports).add(found);
55
+ for (const found of nested.dynamicImports) result.dynamicImports.add(found);
56
+ };
57
+ for (const next of info?.importedIds ?? []) add(next, false);
58
+ for (const next of info?.dynamicallyImportedIds ?? []) add(next, true);
59
+ visiting.delete(raw);
60
+ if (result.complete) through.set(raw, result);
61
+ return result;
62
+ };
63
+ return (raw) => visit(raw, /* @__PURE__ */ new Set());
64
+ }
65
+ /** Reads one build's output: the bytes of each chunk, the share of each module, and the startup files. */
66
+ function collectEnvironmentReport(bundle, options) {
67
+ const chunks = Object.values(bundle).filter(isChunk);
68
+ const byFile = new Map(chunks.map((chunk) => [chunk.fileName, chunk]));
69
+ const startup = /* @__PURE__ */ new Set();
70
+ const pending = chunks.filter((chunk) => chunk.isEntry).map((chunk) => chunk.fileName);
71
+ while (pending.length) {
72
+ const file = pending.pop();
73
+ if (startup.has(file)) continue;
74
+ startup.add(file);
75
+ pending.push(...byFile.get(file)?.imports ?? []);
76
+ }
77
+ const ids = /* @__PURE__ */ new Map();
78
+ const packages = /* @__PURE__ */ new Map();
79
+ const isEntry = (id, chunk) => options.getModuleInfo(id)?.isEntry ?? chunk.facadeModuleId === id;
80
+ for (const chunk of chunks) for (const [id, module] of Object.entries(chunk.modules)) if (module.renderedLength > 0 || isEntry(id, chunk)) ids.set(id, moduleId(id, options.root, packages));
81
+ const edges = createEdgeReader(ids, options.getModuleInfo);
82
+ const client = options.side === "client";
83
+ const rows = chunks.map((chunk) => {
84
+ const bytes = Buffer.byteLength(chunk.code);
85
+ const entries = Object.entries(chunk.modules).filter(([id]) => ids.has(id));
86
+ const merged = /* @__PURE__ */ new Map();
87
+ for (const [raw, module] of entries) {
88
+ const id = ids.get(raw);
89
+ const row = merged.get(id) ?? {
90
+ rendered: 0,
91
+ imports: /* @__PURE__ */ new Set(),
92
+ dynamicImports: /* @__PURE__ */ new Set(),
93
+ entry: false
94
+ };
95
+ const out = edges(raw);
96
+ row.rendered += module.renderedLength;
97
+ for (const next of out.imports) row.imports.add(next);
98
+ for (const next of out.dynamicImports) row.dynamicImports.add(next);
99
+ row.entry ||= isEntry(raw, chunk);
100
+ merged.set(id, row);
101
+ }
102
+ const shares = allocateBytes([...merged.values()].map((row) => row.rendered), bytes);
103
+ const modules = [...merged].map(([id, row], index) => ({
104
+ id,
105
+ bytes: shares[index],
106
+ imports: [...row.imports].filter((next) => next !== id).sort(),
107
+ dynamicImports: [...row.dynamicImports].filter((next) => next !== id && !row.imports.has(next)).sort(),
108
+ entry: row.entry
109
+ })).sort((left, right) => right.bytes - left.bytes || left.id.localeCompare(right.id));
110
+ const css = client ? [...chunk.viteMetadata?.importedCss ?? []].sort() : [];
111
+ return {
112
+ file: chunk.fileName,
113
+ bytes,
114
+ gzip: gzipSync(chunk.code).length,
115
+ entry: chunk.isEntry,
116
+ startup: startup.has(chunk.fileName),
117
+ imports: [...chunk.imports].sort(),
118
+ ...css.length ? { css } : {},
119
+ modules
120
+ };
121
+ }).sort((left, right) => right.bytes - left.bytes || left.file.localeCompare(right.file));
122
+ const css = client ? cssFiles(bundle) : [];
123
+ const unavailable = options.routeOptions?.unavailable ?? options.routes?.find((route) => route.unavailable)?.unavailable;
124
+ const routeOptions = unavailable ? {
125
+ ...options.routeOptions,
126
+ unavailable
127
+ } : options.routeOptions;
128
+ const routes = client && !unavailable ? options.routes?.map((route) => {
129
+ let files = route.files;
130
+ const layout = route.layout;
131
+ if (layout) {
132
+ const pages = new Set(files.filter((file) => file !== layout.file).map((file) => moduleId(file, options.root, packages)));
133
+ const loaded = /* @__PURE__ */ new Set();
134
+ const pending = rows.filter((chunk) => chunk.startup || chunk.modules.some((module) => pages.has(module.id)));
135
+ while (pending.length) {
136
+ const chunk = pending.pop();
137
+ if (loaded.has(chunk.file)) continue;
138
+ loaded.add(chunk.file);
139
+ pending.push(...rows.filter((candidate) => chunk.imports?.includes(candidate.file)));
140
+ }
141
+ const renderer = moduleId(layout.component, options.root, packages);
142
+ if (!rows.some((chunk) => loaded.has(chunk.file) && chunk.modules.some((module) => module.id === renderer))) files = files.filter((file) => file !== layout.file);
143
+ }
144
+ return {
145
+ path: route.path,
146
+ components: files.map((file) => moduleId(file, options.root, packages))
147
+ };
148
+ }) : void 0;
149
+ return {
150
+ schemaVersion: 1,
151
+ build: options.build,
152
+ environment: options.environment,
153
+ side: options.side,
154
+ outDir: relativeTo(options.root, options.outDir),
155
+ chunks: rows,
156
+ ...css.length ? { css } : {},
157
+ ...routes?.length ? { routes } : {},
158
+ ...client && routeOptions ? { routeOptions } : {}
159
+ };
160
+ }
161
+ //#endregion
162
+ //#region src/vite.ts
163
+ const outputsKey = Symbol.for("vitehub.bundle.outputs");
164
+ /** Vite and Nitro can observe the same output; only that output object is deduplicated. */
165
+ function writtenOutputs() {
166
+ const outputs = Reflect.get(globalThis, outputsKey) ?? /* @__PURE__ */ new WeakMap();
167
+ Reflect.set(globalThis, outputsKey, outputs);
168
+ return outputs;
169
+ }
170
+ function newBuildId() {
171
+ return `${(/* @__PURE__ */ new Date()).toISOString()}-${randomUUID()}`;
172
+ }
173
+ /** Asks the features of the build for their rules. Each feature adds them to `rules` in its `vitehub:bundle:rules` hook. */
174
+ async function serverFacts(nitro) {
175
+ const rules = [];
176
+ if (!nitro) return { rules };
177
+ await nitro.hooks.callHook("vitehub:bundle:rules", rules);
178
+ return {
179
+ ...nitro.options.preset ? { host: nitro.options.preset } : {},
180
+ rules
181
+ };
182
+ }
183
+ function writeReport(context, bundle, options, facts) {
184
+ const root = resolve(options.root);
185
+ const outDir = resolve(options.outDir);
186
+ const outputs = writtenOutputs();
187
+ const written = outputs.get(bundle) ?? /* @__PURE__ */ new Set();
188
+ const key = `${root}\0${options.build}\0${options.environment}\0${outDir}`;
189
+ if (written.has(key)) return;
190
+ const { chunks, ...report } = collectEnvironmentReport(bundle, {
191
+ ...options,
192
+ getModuleInfo: (id) => context.getModuleInfo(id),
193
+ outDir,
194
+ root
195
+ });
196
+ writeEnvironmentReport(root, {
197
+ ...report,
198
+ ...facts?.host ? { host: facts.host } : {},
199
+ ...facts?.rules.length ? { rules: facts.rules } : {},
200
+ chunks
201
+ });
202
+ for (const cliRoot of /* @__PURE__ */ new Set([
203
+ root,
204
+ process.cwd(),
205
+ ...options.configRoot ? [options.configRoot] : []
206
+ ])) writeBundleReportRoot(cliRoot, root);
207
+ written.add(key);
208
+ outputs.set(bundle, written);
209
+ }
210
+ /** Adds a Rolldown plugin to a Nitro build that bundles on its own, such as the server build of Nuxt 5. */
211
+ function bundleNitroModule(buildId, onSetup) {
212
+ return {
213
+ name: "@vite-hub/bundle/nitro",
214
+ setup(nitro) {
215
+ if (!nitro.options.dev) onSetup(nitro);
216
+ if (nitro.options.dev || nitro.options.builder === "vite") return;
217
+ const root = nitro.options.rootDir;
218
+ nitro.hooks.hook("build:config", (_nitro, config) => {
219
+ const bundler = config.rolldown ?? config.rollup;
220
+ if (!bundler) return;
221
+ const build = newBuildId();
222
+ bundler.plugins = [...Array.isArray(bundler.plugins) ? bundler.plugins : bundler.plugins ? [bundler.plugins] : [], {
223
+ name: "@vite-hub/bundle/nitro-report",
224
+ async writeBundle(output, bundle) {
225
+ writeReport(this, bundle, {
226
+ build: buildId() ?? build,
227
+ environment: "nitro",
228
+ outDir: output.dir ?? root,
229
+ root,
230
+ side: "server"
231
+ }, await serverFacts(nitro));
232
+ }
233
+ }];
234
+ });
235
+ }
236
+ };
237
+ }
238
+ /**
239
+ * Writes a bundle report for each build environment to `.vitehub/bundle/`. `vitehub bundle` joins them into one
240
+ * report for the app. Builds without the plugin write nothing.
241
+ */
242
+ function hubBundle(options = {}) {
243
+ let coordinatedBuild = options.buildId;
244
+ const builds = /* @__PURE__ */ new WeakMap();
245
+ let routes = [];
246
+ let routeOptions;
247
+ let nitro;
248
+ return {
249
+ name: "@vite-hub/bundle/vite",
250
+ enforce: "post",
251
+ sharedDuringBuild: true,
252
+ buildApp: {
253
+ order: "pre",
254
+ async handler(builder) {
255
+ const build = coordinatedBuild ?? newBuildId();
256
+ for (const environment of Object.values(builder.environments)) builds.set(environment, build);
257
+ }
258
+ },
259
+ buildStart() {
260
+ if (!builds.has(this.environment)) builds.set(this.environment, coordinatedBuild ?? newBuildId());
261
+ },
262
+ async writeBundle(output, bundle) {
263
+ const environment = this.environment;
264
+ const config = environment.config;
265
+ const side = config.consumer === "server" ? "server" : "client";
266
+ writeReport(this, bundle, {
267
+ build: coordinatedBuild ?? builds.get(environment),
268
+ ...config.configFile ? { configRoot: dirname(config.configFile) } : {},
269
+ environment: environment.name,
270
+ routes,
271
+ routeOptions,
272
+ outDir: output.dir ?? resolve(config.root, config.build.outDir),
273
+ root: resolveViteHubProjectRoot(config.root),
274
+ side
275
+ }, side === "server" ? await serverFacts(nitro) : void 0);
276
+ },
277
+ api: {
278
+ setRoutes(next, options) {
279
+ routes = next;
280
+ routeOptions = options;
281
+ },
282
+ startBuild() {
283
+ coordinatedBuild = newBuildId();
284
+ return coordinatedBuild;
285
+ }
286
+ },
287
+ nitro: bundleNitroModule(() => coordinatedBuild, (instance) => {
288
+ nitro = instance;
289
+ }),
290
+ vitehub: { cli: bundleCliContributor }
291
+ };
292
+ }
293
+ //#endregion
294
+ export { hubBundle, nuxtPageRoutes };