@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.
- package/LICENSE +201 -0
- package/README.md +91 -2
- package/dist/cli-DdzHN8li.js +334 -0
- package/dist/cli-ubYJpAL_.d.ts +163 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +3 -0
- package/dist/compare-B-xpyN4Y.js +1796 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +16 -0
- package/dist/types-DBa_sXqC.d.ts +239 -0
- package/dist/vite.d.ts +84 -0
- package/dist/vite.js +294 -0
- package/package.json +75 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vite-hub/bundle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Bundle reports for ViteHub apps. After a production build, one command tells you, or your Agent, how big the client and the server are, how much code loads at startup, and why each package is in the output.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// vite.config.ts
|
|
7
|
+
import { defineConfig } from "vite"
|
|
8
|
+
import { vitehub } from "vite-hub"
|
|
9
|
+
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
plugins: [vitehub({ bundle: true })],
|
|
12
|
+
})
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
In Nuxt 5, set `vitehub: { bundle: true }` in `nuxt.config.ts`.
|
|
16
|
+
|
|
17
|
+
Read the [Bundle docs](https://vitehub.dev/docs/bundle) for a tutorial, the checks, and the full reference.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
vite build # or nuxt build
|
|
21
|
+
vitehub bundle # client and server size, startup size, largest groups
|
|
22
|
+
vitehub bundle --json # the full report
|
|
23
|
+
vitehub bundle why @libsql/client # the import chain from the entry to the package
|
|
24
|
+
vitehub bundle why /docs/kv # what a first visit to this page loads (Nuxt)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
To prove that a change makes the bundle smaller, or not bigger, save the report first and compare after the next build:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
vitehub bundle --json > .vitehub/bundle-before.json
|
|
31
|
+
# change the code, then build again
|
|
32
|
+
vitehub bundle --against .vitehub/bundle-before.json # side and startup deltas, groups that changed
|
|
33
|
+
vitehub bundle --against .vitehub/bundle-before.json --json # the same as JSON
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`--against` also takes a copy of `.vitehub/bundle/` or the root of another checkout with a build.
|
|
37
|
+
|
|
38
|
+
The commands read `.vitehub/bundle/` and need no dev server. Development builds are not measured.
|
|
39
|
+
|
|
40
|
+
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
|
+
|
|
42
|
+
## What the report says
|
|
43
|
+
|
|
44
|
+
- **Client and server.** Bytes and gzip bytes of the JavaScript that the build wrote, and the files that load at startup: the entries and every file that they import statically. On the server, startup code runs before the first request. Client startup combines all page entries, counting shared files once; a single page can load less.
|
|
45
|
+
- **Groups.** Each module counts toward one group: a ViteHub package (`@vite-hub/agent`, `vite-hub/console`), a framework package (`nitro`, `h3`, `vue`), a dependency, an app folder (`server/api`), or generated code (`.vitehub`, `#nitro/virtual`). A module gets its share of the bytes of the file it is in, so the groups add up to the file sizes.
|
|
46
|
+
- **Why.** The shortest import chain from an entry to a package, a file, or a group.
|
|
47
|
+
- **Routes.** In a Nuxt app, what the browser loads on a first visit to each page route: the startup files, and the files of the route's layout and pages with every file that they import statically, plus their CSS. Files that the page loads later with `import()` do not count. `why /docs/kv` finds the route that renders the path and lists its files and the largest modules that it adds.
|
|
48
|
+
- **Against.** The delta from a saved report: bytes, gzip, and startup bytes of each side, and the groups that grew, shrank, were added, or were removed.
|
|
49
|
+
|
|
50
|
+
The report joins the build environments. In Nuxt 5, Nitro bundles the SSR output, so the server part shows the SSR modules inside it instead of one large file.
|
|
51
|
+
|
|
52
|
+
## Checks
|
|
53
|
+
|
|
54
|
+
`vitehub bundle` ends with the problems that the report proves, and `--json` gives them in `findings`. Each finding has a `code`, a `severity`, a `why`, a `fix`, a `docs` link, and the import chain from the server entry.
|
|
55
|
+
|
|
56
|
+
- `BUNDLE_STARTUP_UNUSED` (warning): a package loads at server startup, and a feature of this build never runs it there. Features declare such packages from their resolved configuration in the Nitro hook `vitehub:bundle:rules`. The Database declares the libSQL client on a Cloudflare build where every Database is D1 or Postgres.
|
|
57
|
+
- `BUNDLE_HOST_SIZE_LIMIT` (error): the server JavaScript is over the host limit. Cloudflare accepts a Worker up to 64 MiB before compression.
|
|
58
|
+
|
|
59
|
+
An error makes the command exit with 1, so CI can run it after the build. A warning keeps exit code 0.
|
|
60
|
+
|
|
61
|
+
A startup rule applies only when its packages are imported by its `owner` or each other. Imports from app code or another package suppress the finding, because the feature cannot prove what those consumers need.
|
|
62
|
+
|
|
63
|
+
A feature adds a rule inside its Nitro module:
|
|
64
|
+
|
|
65
|
+
```ts fragment
|
|
66
|
+
nitro.hooks.hook("vitehub:bundle:rules", (rules) => {
|
|
67
|
+
rules.push({ owner: "@vite-hub/database", packages: ["@libsql/client"], why: "...", fix: "..." })
|
|
68
|
+
})
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## How it works
|
|
72
|
+
|
|
73
|
+
`hubBundle()` is a Vite plugin. In `writeBundle` it reads Rolldown's output chunks, `chunk.modules[id].renderedLength`, and `getModuleInfo()`, and writes `.vitehub/bundle/<environment>.json`. When Nitro bundles on its own, as in Nuxt 5, the plugin's Nitro module adds the same reader to Nitro's `build:config`. A new build removes the files of older builds.
|
|
74
|
+
|
|
75
|
+
Each Vite build command starts a fresh report. All environments of a Vite builder share a build ID, and `vite-hub/nuxt` starts one session for Nuxt's Vite and Nitro phases. Custom coordinators that run phases in separate processes must pass the same fresh `buildId` to `hubBundle({ buildId })` in every phase; independent commands do not join reports left on disk.
|
|
76
|
+
|
|
77
|
+
`vite-hub/nuxt` reads the pages and layouts that Nuxt resolves (`app.pages`, `app.layouts`) and passes them to `hubBundle().api.setRoutes()`. The client report stores each route with its component modules, the static imports of each output file, and the CSS files, so reading the report needs no Nuxt. A layout is known when `definePageMeta` sets a static `layout`; otherwise the route uses `default`. Layout files count only when the startup or page files also load Nuxt's `NuxtLayout` component. If Nuxt does not expose that component's file, layout files are omitted.
|
|
78
|
+
|
|
79
|
+
Static route aliases share the canonical route's files and bytes. Lookup uses Vue Router's matcher and Nuxt's `router.options.sensitive` and `strict` settings. Nuxt 5 defaults to case-sensitive matching. A custom `app/router.options.ts` file, including one from a layer or module, can replace routes or matching settings at runtime. In that case route estimates are unavailable: the CLI says why, and `client.routesUnavailable` stores the reason in JSON. This also applies to custom router options files that only change other settings. Bundle totals and module explanations remain available.
|
|
80
|
+
|
|
81
|
+
Page redirects also make route estimates unavailable, because the destination can change before a page renders. Runtime changes to layout selection or conditional rendering of `NuxtLayout` are not measured.
|
|
82
|
+
|
|
83
|
+
Read the report in code:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { compareBundleReports, explainBundleRouteTarget, explainBundleTarget, readBundleReport, readSavedBundleReport } from "@vite-hub/bundle"
|
|
87
|
+
|
|
88
|
+
const report = readBundleReport(process.cwd())
|
|
89
|
+
const why = explainBundleTarget(process.cwd(), "zod")
|
|
90
|
+
const page = explainBundleRouteTarget(process.cwd(), "/docs/kv")
|
|
91
|
+
const diff = compareBundleReports(readSavedBundleReport(".vitehub/bundle-before.json")!, report!)
|
|
92
|
+
```
|
|
@@ -0,0 +1,334 @@
|
|
|
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";
|
|
2
|
+
import { statSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, parse, resolve } from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
//#region ../internal/src/build/vite.ts
|
|
6
|
+
const projectRootDirectoryMarkers = [
|
|
7
|
+
["server", "agents"],
|
|
8
|
+
["server", "channels"],
|
|
9
|
+
["server", "connections"],
|
|
10
|
+
["server", "browsers"],
|
|
11
|
+
["server", "emails"],
|
|
12
|
+
["server", "schedules"],
|
|
13
|
+
["server", "workspaces"]
|
|
14
|
+
];
|
|
15
|
+
const projectRootFileMarkers = [
|
|
16
|
+
["package.json"],
|
|
17
|
+
["nuxt.config.ts"],
|
|
18
|
+
["nuxt.config.mts"],
|
|
19
|
+
["nuxt.config.js"],
|
|
20
|
+
["nuxt.config.mjs"]
|
|
21
|
+
];
|
|
22
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
23
|
+
const resolvedRoot = resolve(root);
|
|
24
|
+
const temporaryRoot = resolve(tmpdir());
|
|
25
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
26
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
27
|
+
if (basename(resolvedRoot) === "app") {
|
|
28
|
+
const parent = dirname(resolvedRoot);
|
|
29
|
+
if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
|
|
30
|
+
"nuxt.config.ts",
|
|
31
|
+
"nuxt.config.mts",
|
|
32
|
+
"nuxt.config.js",
|
|
33
|
+
"nuxt.config.mjs"
|
|
34
|
+
]))) return parent;
|
|
35
|
+
}
|
|
36
|
+
let current = resolvedRoot;
|
|
37
|
+
while (true) {
|
|
38
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
39
|
+
if (hasProjectRootMarker(current)) return current;
|
|
40
|
+
const parent = dirname(current);
|
|
41
|
+
if (parent === current) return resolvedRoot;
|
|
42
|
+
current = parent;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
46
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
47
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.code !== "ENOENT") throw error;
|
|
50
|
+
}
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
function hasProjectRootMarker(root) {
|
|
54
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
55
|
+
return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
|
|
56
|
+
}
|
|
57
|
+
function hasProjectRootFileMarker(root, markers) {
|
|
58
|
+
for (const marker of markers) {
|
|
59
|
+
const path = Array.isArray(marker) ? marker : [marker];
|
|
60
|
+
try {
|
|
61
|
+
if (statSync(resolve(root, ...path)).isFile()) return true;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error.code !== "ENOENT") throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/cli.ts
|
|
70
|
+
const reportUsage = "vitehub bundle [--against <report>] [--json]";
|
|
71
|
+
const whyUsage = "vitehub bundle why <package|file|/route> [--json]";
|
|
72
|
+
const missingReport = "No bundle report in .vitehub/bundle/. Set `bundle: true` in vitehub() (vite.config.ts) or in `vitehub` (nuxt.config.ts), then run a production build.\n";
|
|
73
|
+
/** A loaded project supplies its Vite root; runtime dispatch uses the last build's location. */
|
|
74
|
+
function projectRoot(context) {
|
|
75
|
+
const root = resolveViteHubProjectRoot(context.rootDir);
|
|
76
|
+
if (resolve(context.cwd) !== resolve(context.rootDir)) return root;
|
|
77
|
+
return readBundleReportRoot(context.cwd) ?? readBundleReportRoot(root) ?? root;
|
|
78
|
+
}
|
|
79
|
+
function parse$1(args) {
|
|
80
|
+
const result = {
|
|
81
|
+
help: false,
|
|
82
|
+
json: false,
|
|
83
|
+
positional: []
|
|
84
|
+
};
|
|
85
|
+
for (let index = 0; index < args.length; index++) {
|
|
86
|
+
const arg = args[index];
|
|
87
|
+
if (arg === "--json") result.json = true;
|
|
88
|
+
else if (arg === "--against" && args[index + 1] && !args[index + 1].startsWith("-")) result.against = args[++index];
|
|
89
|
+
else if (arg.startsWith("--against=") && arg.length > 10) result.against = arg.slice(10);
|
|
90
|
+
else if (arg === "--against" || arg === "--against=") result.missing ??= "--against <report>";
|
|
91
|
+
else if (arg === "-h" || arg === "--help") result.help = true;
|
|
92
|
+
else if (arg.startsWith("-")) result.unknown ??= arg;
|
|
93
|
+
else result.positional.push(arg);
|
|
94
|
+
}
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
function sideLines(label, side, startupMeaning) {
|
|
98
|
+
const lines = [
|
|
99
|
+
`${label}: ${formatBytes(side.bytes)} of JavaScript in ${side.chunks} files (gzip ${formatBytes(side.gzip)}). Environments: ${side.environments.join(", ")}.`,
|
|
100
|
+
` Startup: ${formatBytes(side.startup.bytes)} in ${side.startup.chunks} files (gzip ${formatBytes(side.startup.gzip)}). ${startupMeaning}`,
|
|
101
|
+
" Largest groups (total, startup):"
|
|
102
|
+
];
|
|
103
|
+
const width = Math.max(...side.groups.slice(0, 10).map((group) => formatBytes(group.bytes).length));
|
|
104
|
+
for (const group of side.groups.slice(0, 10)) lines.push(` ${formatBytes(group.bytes).padStart(width)} ${formatBytes(group.startupBytes).padStart(width)} ${group.name} (${group.kind})`);
|
|
105
|
+
if (side.groups.length > 10) lines.push(` ${side.groups.length - 10} more groups in --json`);
|
|
106
|
+
if (side.routesUnavailable) lines.push(` Routes unavailable: ${side.routesUnavailable}`);
|
|
107
|
+
if (side.routes?.length) {
|
|
108
|
+
const routes = side.routes.slice(0, 5);
|
|
109
|
+
const routeWidth = Math.max(...routes.map((route) => formatBytes(route.bytes).length));
|
|
110
|
+
lines.push(" Largest routes (first visit, page files only):");
|
|
111
|
+
for (const route of routes) lines.push(` ${formatBytes(route.bytes).padStart(routeWidth)} ${formatBytes(route.pageBytes).padStart(routeWidth)} ${route.path}`);
|
|
112
|
+
if (side.routes.length > 5) lines.push(` ${side.routes.length - 5} more routes in --json`);
|
|
113
|
+
}
|
|
114
|
+
return lines;
|
|
115
|
+
}
|
|
116
|
+
function fileCount(count) {
|
|
117
|
+
return `${count} ${count === 1 ? "file" : "files"}`;
|
|
118
|
+
}
|
|
119
|
+
function routeLines(explanation) {
|
|
120
|
+
const { route } = explanation;
|
|
121
|
+
const js = route.files.filter((file) => !file.file.endsWith(".css"));
|
|
122
|
+
const startup = js.filter((file) => file.startup);
|
|
123
|
+
const lines = [
|
|
124
|
+
`Route ${route.path}: ${formatBytes(route.bytes)} of JavaScript on a first visit (gzip ${formatBytes(route.gzip)}), ${formatBytes(route.cssBytes)} of CSS.`,
|
|
125
|
+
` Startup files: ${formatBytes(route.bytes - route.pageBytes)} in ${fileCount(startup.length)}. Page files: ${formatBytes(route.pageBytes)} in ${fileCount(js.length - startup.length)}.`,
|
|
126
|
+
` Components: ${route.components.join(", ") || "none"}`,
|
|
127
|
+
" Files (bytes, gzip):"
|
|
128
|
+
];
|
|
129
|
+
const width = Math.max(...route.files.map((file) => formatBytes(file.bytes).length));
|
|
130
|
+
for (const file of route.files) lines.push(` ${formatBytes(file.bytes).padStart(width)} ${formatBytes(file.gzip).padStart(width)} ${file.file}${file.startup ? " [startup]" : ""}`);
|
|
131
|
+
if (explanation.modules.length) {
|
|
132
|
+
lines.push(" Largest modules in the page files:");
|
|
133
|
+
const modules = explanation.modules.slice(0, 10);
|
|
134
|
+
const moduleWidth = Math.max(...modules.map((module) => formatBytes(module.bytes).length));
|
|
135
|
+
for (const module of modules) lines.push(` ${formatBytes(module.bytes).padStart(moduleWidth)} ${module.id}`);
|
|
136
|
+
}
|
|
137
|
+
lines.push("", "Run `vitehub bundle why <module>` on a module to see the import chain that loads it.", "");
|
|
138
|
+
return lines;
|
|
139
|
+
}
|
|
140
|
+
function findingLines(findings) {
|
|
141
|
+
if (!findings.length) return ["Checks: no findings.", ""];
|
|
142
|
+
const lines = [`Checks: ${findings.length} ${findings.length === 1 ? "finding" : "findings"}.`];
|
|
143
|
+
for (const finding of findings) {
|
|
144
|
+
lines.push(` ${finding.severity} ${finding.code} (${finding.side}): ${finding.why}`);
|
|
145
|
+
if (finding.chain.length) lines.push(` Chain: ${finding.chain.map((step) => step.id).join(" → ")}`);
|
|
146
|
+
lines.push(` Fix: ${finding.fix}`, ` Docs: ${finding.docs}`);
|
|
147
|
+
}
|
|
148
|
+
lines.push("");
|
|
149
|
+
return lines;
|
|
150
|
+
}
|
|
151
|
+
/** Like `vite-doctor`: an error finding fails the command, a warning does not. */
|
|
152
|
+
function exitCode(findings) {
|
|
153
|
+
return findings.some((finding) => finding.severity === "error") ? 1 : 0;
|
|
154
|
+
}
|
|
155
|
+
/** `+1.2 kB`, `-300 B`, or `0 B`. */
|
|
156
|
+
function formatDelta(bytes) {
|
|
157
|
+
return bytes > 0 ? `+${formatBytes(bytes)}` : bytes < 0 ? `-${formatBytes(-bytes)}` : "0 B";
|
|
158
|
+
}
|
|
159
|
+
function change(before, after) {
|
|
160
|
+
return `${formatBytes(before)} → ${formatBytes(after)} (${formatDelta(after - before)})`;
|
|
161
|
+
}
|
|
162
|
+
function comparisonLines(label, side) {
|
|
163
|
+
if (!side.groups.length && !side.delta.bytes && !side.delta.gzip && !side.delta.startupBytes && !side.delta.startupGzip) return [`${label}: no change, ${formatBytes(side.after.bytes)}. Startup: ${formatBytes(side.after.startupBytes)}.`];
|
|
164
|
+
const lines = [`${label}: ${change(side.before.bytes, side.after.bytes)}, gzip ${change(side.before.gzip, side.after.gzip)}.`, ` Startup: ${change(side.before.startupBytes, side.after.startupBytes)}, gzip ${change(side.before.startupGzip, side.after.startupGzip)}.`];
|
|
165
|
+
if (!side.groups.length) return lines;
|
|
166
|
+
lines.push(" Groups that changed (total, startup):");
|
|
167
|
+
const shown = side.groups.slice(0, 10);
|
|
168
|
+
const width = Math.max(...shown.flatMap((group) => [formatDelta(group.delta.bytes).length, formatDelta(group.delta.startupBytes).length]));
|
|
169
|
+
for (const group of shown) lines.push(` ${formatDelta(group.delta.bytes).padStart(width)} ${formatDelta(group.delta.startupBytes).padStart(width)} ${group.name} (${group.kind}), ${group.change}`);
|
|
170
|
+
if (side.groups.length > 10) lines.push(` ${side.groups.length - 10} more groups in --json`);
|
|
171
|
+
return lines;
|
|
172
|
+
}
|
|
173
|
+
function comparisonText(comparison) {
|
|
174
|
+
const lines = [`Bundle of the build from ${comparison.builds.after}, compared with the build from ${comparison.builds.before}`, ""];
|
|
175
|
+
if (comparison.builds.before === comparison.builds.after) lines.push("Both reports are from the same build. Run the production build again after the change, then compare.", "");
|
|
176
|
+
if (comparison.server) lines.push(...comparisonLines("Server", comparison.server), "");
|
|
177
|
+
if (comparison.client) lines.push(...comparisonLines("Client", comparison.client), "");
|
|
178
|
+
return lines.join("\n");
|
|
179
|
+
}
|
|
180
|
+
function runReport(args, context) {
|
|
181
|
+
const parsed = parse$1(args);
|
|
182
|
+
if (parsed.help) {
|
|
183
|
+
context.stdout.write([
|
|
184
|
+
`Usage: ${reportUsage}`,
|
|
185
|
+
"",
|
|
186
|
+
"Shows the size of the last production build: client and server, the code that loads at startup, and the largest",
|
|
187
|
+
"packages and folders. Needs a build with `bundle: true` in vitehub(). No dev server needed.",
|
|
188
|
+
"",
|
|
189
|
+
"Then it runs the bundle checks. It exits with 1 when a finding is an error, such as a server over the host size",
|
|
190
|
+
"limit. Warnings, such as a package that this build never runs at startup but loads there, keep exit code 0.",
|
|
191
|
+
"",
|
|
192
|
+
"With --against, it compares the last build with a saved report: the bytes of each side and of its startup",
|
|
193
|
+
"code, and the groups that grew, shrank, were added, or were removed. Save the report before the change:",
|
|
194
|
+
"",
|
|
195
|
+
" vitehub bundle --json > .vitehub/bundle-before.json",
|
|
196
|
+
" # change the code, then run the production build again",
|
|
197
|
+
" vitehub bundle --against .vitehub/bundle-before.json",
|
|
198
|
+
"",
|
|
199
|
+
"Options:",
|
|
200
|
+
" --against <report> Compare with a saved report: the output of --json, a copy of .vitehub/bundle/,",
|
|
201
|
+
" or a project root that has .vitehub/bundle/.",
|
|
202
|
+
" --json Print the full report, or the comparison with --against.",
|
|
203
|
+
" -h, --help Show this help.",
|
|
204
|
+
""
|
|
205
|
+
].join("\n"));
|
|
206
|
+
return 0;
|
|
207
|
+
}
|
|
208
|
+
if (parsed.missing) {
|
|
209
|
+
context.stderr.write(`${parsed.missing} needs a value.\nUsage: ${reportUsage}\n`);
|
|
210
|
+
return 1;
|
|
211
|
+
}
|
|
212
|
+
if (parsed.unknown || parsed.positional.length) {
|
|
213
|
+
context.stderr.write(`Unknown argument ${parsed.unknown ?? parsed.positional[0]}.\nUsage: ${reportUsage}\n`);
|
|
214
|
+
return 1;
|
|
215
|
+
}
|
|
216
|
+
const report = createBundleReport(readEnvironmentReports(projectRoot(context)));
|
|
217
|
+
if (!report) {
|
|
218
|
+
context.stderr.write(missingReport);
|
|
219
|
+
return 1;
|
|
220
|
+
}
|
|
221
|
+
if (parsed.against) {
|
|
222
|
+
const before = readSavedBundleReport(resolve(context.cwd, parsed.against));
|
|
223
|
+
if (!before) {
|
|
224
|
+
context.stderr.write(`No bundle report in ${parsed.against}. Save one before the change with \`vitehub bundle --json > .vitehub/bundle-before.json\`.\n`);
|
|
225
|
+
return 1;
|
|
226
|
+
}
|
|
227
|
+
const comparison = compareBundleReports(before, report);
|
|
228
|
+
context.stdout.write(parsed.json ? `${JSON.stringify({
|
|
229
|
+
...comparison,
|
|
230
|
+
findings: report.findings
|
|
231
|
+
}, null, 2)}\n` : `${comparisonText(comparison)}${findingLines(report.findings).join("\n")}`);
|
|
232
|
+
return exitCode(report.findings);
|
|
233
|
+
}
|
|
234
|
+
if (parsed.json) {
|
|
235
|
+
context.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
236
|
+
return exitCode(report.findings);
|
|
237
|
+
}
|
|
238
|
+
const lines = [`Bundle of the build from ${report.build}${report.host ? ` for ${report.host}` : ""}`, ""];
|
|
239
|
+
if (report.server) lines.push(...sideLines("Server", report.server, "This code loads before the server answers its first request."), "");
|
|
240
|
+
if (report.client) lines.push(...sideLines("Client", report.client, "Combined startup across all page entries; shared files count once."), "");
|
|
241
|
+
lines.push(...findingLines(report.findings));
|
|
242
|
+
lines.push("Run `vitehub bundle why <package|file>` to see why something is in the output.", "");
|
|
243
|
+
context.stdout.write(lines.join("\n"));
|
|
244
|
+
return exitCode(report.findings);
|
|
245
|
+
}
|
|
246
|
+
function runWhy(args, context) {
|
|
247
|
+
const parsed = parse$1(args);
|
|
248
|
+
if (parsed.help) {
|
|
249
|
+
context.stdout.write([
|
|
250
|
+
`Usage: ${whyUsage}`,
|
|
251
|
+
"",
|
|
252
|
+
"Shows why a package, a file, or a group is in the last production build: its size on the client and the server,",
|
|
253
|
+
"whether it loads at startup, and the shortest import chain from the entry to it.",
|
|
254
|
+
"",
|
|
255
|
+
"For a page route, such as /docs/kv, it shows what the browser loads on a first visit: the startup files, the",
|
|
256
|
+
"files of the route's layout and pages, and the largest modules that the route adds. Nuxt apps only.",
|
|
257
|
+
"",
|
|
258
|
+
"Examples:",
|
|
259
|
+
" vitehub bundle why @libsql/client",
|
|
260
|
+
" vitehub bundle why server/api/hello.get.ts",
|
|
261
|
+
" vitehub bundle why /docs/kv",
|
|
262
|
+
"",
|
|
263
|
+
"Options:",
|
|
264
|
+
" --json Print machine-readable JSON.",
|
|
265
|
+
" -h, --help Show this help.",
|
|
266
|
+
""
|
|
267
|
+
].join("\n"));
|
|
268
|
+
return 0;
|
|
269
|
+
}
|
|
270
|
+
const target = parsed.positional[0];
|
|
271
|
+
if (parsed.against || parsed.missing) parsed.unknown ??= "--against";
|
|
272
|
+
if (parsed.unknown || !target || parsed.positional.length > 1) {
|
|
273
|
+
context.stderr.write(`${parsed.unknown ? `Unknown argument ${parsed.unknown}.\n` : "Name one package, file, or group.\n"}Usage: ${whyUsage}\n`);
|
|
274
|
+
return 1;
|
|
275
|
+
}
|
|
276
|
+
const reports = readEnvironmentReports(projectRoot(context));
|
|
277
|
+
if (!reports.length) {
|
|
278
|
+
context.stderr.write(missingReport);
|
|
279
|
+
return 1;
|
|
280
|
+
}
|
|
281
|
+
const route = target.startsWith("/") ? explainBundleRoute(reports, target) : void 0;
|
|
282
|
+
if (route) {
|
|
283
|
+
context.stdout.write(parsed.json ? `${JSON.stringify(route, null, 2)}\n` : routeLines(route).join("\n"));
|
|
284
|
+
return 0;
|
|
285
|
+
}
|
|
286
|
+
const explanations = explainBundle(reports, target);
|
|
287
|
+
const unavailable = !explanations.length && target.startsWith("/") ? createBundleReport(reports)?.client?.routesUnavailable : void 0;
|
|
288
|
+
if (unavailable) {
|
|
289
|
+
context.stdout.write(parsed.json ? `${JSON.stringify({
|
|
290
|
+
target,
|
|
291
|
+
unavailable
|
|
292
|
+
}, null, 2)}\n` : `Routes unavailable: ${unavailable}\n`);
|
|
293
|
+
return 1;
|
|
294
|
+
}
|
|
295
|
+
if (parsed.json) {
|
|
296
|
+
context.stdout.write(`${JSON.stringify({
|
|
297
|
+
target,
|
|
298
|
+
explanations
|
|
299
|
+
}, null, 2)}\n`);
|
|
300
|
+
return 0;
|
|
301
|
+
}
|
|
302
|
+
if (!explanations.length) {
|
|
303
|
+
context.stdout.write(target.startsWith("/") ? `No page route of the last build renders ${target}. Routes need a Nuxt app with pages.\n` : `${target} is not in the last build.\n`);
|
|
304
|
+
return 0;
|
|
305
|
+
}
|
|
306
|
+
const lines = [];
|
|
307
|
+
for (const explanation of explanations) {
|
|
308
|
+
lines.push(`${explanation.side === "server" ? "Server" : "Client"}: ${formatBytes(explanation.bytes)} in ${explanation.group}${explanation.startup ? ", loads at startup" : ", loads on demand"}.`);
|
|
309
|
+
if (explanation.chain.length) for (const [index, step] of explanation.chain.entries()) lines.push(` ${index === 0 ? "" : "→ "}${step.id}${index === 0 || step.environment !== explanation.chain[index - 1].environment ? ` [${step.environment}]` : ""}`);
|
|
310
|
+
else lines.push(" No import chain from an entry. A plugin or the bundler added it.");
|
|
311
|
+
lines.push("");
|
|
312
|
+
}
|
|
313
|
+
context.stdout.write(lines.join("\n"));
|
|
314
|
+
return 0;
|
|
315
|
+
}
|
|
316
|
+
/** The `vitehub bundle` commands. They read `.vitehub/bundle/` and need no dev server. */
|
|
317
|
+
const bundleCliContributor = { namespaces: [{
|
|
318
|
+
defaultFeature: "report",
|
|
319
|
+
description: "Inspect the size of the last production build.",
|
|
320
|
+
features: [{
|
|
321
|
+
description: "Show client and server size, startup size, and the largest groups.",
|
|
322
|
+
name: "report",
|
|
323
|
+
run: runReport,
|
|
324
|
+
usage: reportUsage
|
|
325
|
+
}, {
|
|
326
|
+
description: "Show why a package or file is in the output, or what a page route loads.",
|
|
327
|
+
name: "why",
|
|
328
|
+
run: runWhy,
|
|
329
|
+
usage: whyUsage
|
|
330
|
+
}],
|
|
331
|
+
name: "bundle"
|
|
332
|
+
}] };
|
|
333
|
+
//#endregion
|
|
334
|
+
export { resolveViteHubProjectRoot as n, bundleCliContributor as t };
|