@rangojs/router 0.0.0-experimental.102 → 0.0.0-experimental.103

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.
@@ -2040,7 +2040,7 @@ import { resolve } from "node:path";
2040
2040
  // package.json
2041
2041
  var package_default = {
2042
2042
  name: "@rangojs/router",
2043
- version: "0.0.0-experimental.102",
2043
+ version: "0.0.0-experimental.103",
2044
2044
  description: "Django-inspired RSC router with composable URL patterns",
2045
2045
  keywords: [
2046
2046
  "react",
@@ -4861,7 +4861,7 @@ function generateRoutesManifestModule(state) {
4861
4861
  }
4862
4862
  }
4863
4863
  const lines = [
4864
- `import { setCachedManifest, setPrecomputedEntries, setRouteTrie, setRouterManifest, registerRouterManifestLoader, clearAllRouterData } from "@rangojs/router/server";`,
4864
+ `import { setCachedManifest, setRouterManifest, registerRouterManifestLoader, clearAllRouterData } from "@rangojs/router/server";`,
4865
4865
  ...genFileImports,
4866
4866
  // Clear stale per-router cached data (manifest, trie, precomputed entries)
4867
4867
  // before re-populating. In Cloudflare dev mode, program reloads re-evaluate
@@ -4897,18 +4897,6 @@ function generateRoutesManifestModule(state) {
4897
4897
  );
4898
4898
  }
4899
4899
  }
4900
- if (state.isBuildMode) {
4901
- if (state.mergedPrecomputedEntries && state.mergedPrecomputedEntries.length > 0) {
4902
- lines.push(
4903
- `setPrecomputedEntries(${jsonParseExpression(state.mergedPrecomputedEntries)});`
4904
- );
4905
- }
4906
- if (state.mergedRouteTrie) {
4907
- lines.push(
4908
- `setRouteTrie(${jsonParseExpression(state.mergedRouteTrie)});`
4909
- );
4910
- }
4911
- }
4912
4900
  for (const routerId of state.perRouterManifestDataMap.keys()) {
4913
4901
  lines.push(
4914
4902
  `registerRouterManifestLoader(${JSON.stringify(routerId)}, () => import(${JSON.stringify(VIRTUAL_ROUTES_MANIFEST_ID + "/" + routerId)}));`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rangojs/router",
3
- "version": "0.0.0-experimental.102",
3
+ "version": "0.0.0-experimental.103",
4
4
  "description": "Django-inspired RSC router with composable URL patterns",
5
5
  "keywords": [
6
6
  "react",
@@ -0,0 +1,159 @@
1
+ ---
2
+ name: bundle-analysis
3
+ description: Audit a Rango app's production bundle for server-side code leaking into the client, dev/prod React duplication, oversized chunks, and inefficient client-reference grouping. Use when investigating bundle size growth, before a production deploy, or when the client/SSR/RSC output suddenly balloons.
4
+ argument-hint: "<app-dir>"
5
+ ---
6
+
7
+ # Bundle Analysis
8
+
9
+ Use this when you want **proof** that your Rango app is shipping the bundles you expect: small client, no server leaks, no doubled React, reasonable RSC worker size.
10
+
11
+ ## What this checks
12
+
13
+ Your app builds in three Vite environments — `client`, `ssr`, and `rsc` — and each ships its own bundle. The most common bundle bugs in a Rango app are:
14
+
15
+ 1. **Server code leaking into the client.** A file that imports `node:fs`, calls a database, or contains action logic ends up in the client bundle because a client component pulled it in transitively. Symptom: your client bundle is much larger than expected, sometimes with imports that fail at runtime.
16
+ 2. **Both dev and prod React in the SSR/RSC bundle.** When `process.env.NODE_ENV` isn't folded at build time, React's CJS files ship both `.development.js` _and_ `.production.js` variants — doubling React's footprint. The Cloudflare vite plugin folds NODE_ENV automatically; vanilla `vite build` does it for client but not always for SSR/RSC.
17
+ 3. **An oversized routes-manifest in your RSC worker.** The `virtual:rsc-router/routes-manifest/<routerId>` chunk holds your route trie and precomputed entries — large only in proportion to your route count. If it's surprisingly big, you may have unintentionally generated routes (e.g., parametrized fixtures) that bloated the trie.
18
+ 4. **Inefficient client-reference grouping.** Each `"use client"` boundary becomes a chunk. Too many small client components = many tiny chunks; one giant client component = one giant chunk that defeats code-splitting.
19
+
20
+ Tree-shaking does _not_ catch (1) generated data inlined as string literals or (2) data-dependent conditionals like React's. You need a visualizer.
21
+
22
+ ## Step 1: Install the visualizer
23
+
24
+ In your app's directory:
25
+
26
+ ```bash
27
+ pnpm add -D rollup-plugin-visualizer
28
+ # or: npm install --save-dev rollup-plugin-visualizer
29
+ # or: yarn add -D rollup-plugin-visualizer
30
+ ```
31
+
32
+ ## Step 2: Wire it into your `vite.config.ts`
33
+
34
+ Add a small helper that registers one visualizer instance **per Vite environment** (not just one global). The plugin caches its options after the first call, so a single instance can't handle multi-environment builds — you'll get a report for one environment and silence for the others.
35
+
36
+ ```ts
37
+ // vite.config.ts
38
+ import { defineConfig, type PluginOption, type Plugin } from "vite";
39
+ import { visualizer } from "rollup-plugin-visualizer";
40
+ import { join } from "node:path";
41
+ // ... your other imports ...
42
+
43
+ function analyze(): PluginOption[] {
44
+ if (!process.env.ANALYZE) return [];
45
+ return (["client", "ssr", "rsc"] as const).map((envName) => {
46
+ const inner = visualizer({
47
+ filename: join("bundle-stats", `${envName}.html`),
48
+ template: "treemap",
49
+ gzipSize: true,
50
+ brotliSize: true,
51
+ }) as Plugin;
52
+ return {
53
+ ...inner,
54
+ name: `analyze-${envName}`,
55
+ applyToEnvironment(env) {
56
+ return env.name === envName;
57
+ },
58
+ } as Plugin;
59
+ });
60
+ }
61
+
62
+ export default defineConfig(({ command }) => ({
63
+ plugins: [
64
+ // your existing plugins...
65
+ ...analyze(),
66
+ ],
67
+ // For non-Cloudflare apps, fold NODE_ENV explicitly so React's CJS files
68
+ // emit only the .production.js variants in SSR/RSC. Skip if your build
69
+ // setup already does this (the Cloudflare vite plugin does).
70
+ define:
71
+ command === "build"
72
+ ? { "process.env.NODE_ENV": JSON.stringify("production") }
73
+ : undefined,
74
+ }));
75
+ ```
76
+
77
+ Add `bundle-stats/` to your `.gitignore`.
78
+
79
+ ## Step 3: Build with the analyzer enabled
80
+
81
+ ```bash
82
+ ANALYZE=1 pnpm exec vite build
83
+ ```
84
+
85
+ You'll get three HTML reports in `bundle-stats/`:
86
+
87
+ - `bundle-stats/client.html` — what runs in the browser
88
+ - `bundle-stats/ssr.html` — what runs during HTML stream
89
+ - `bundle-stats/rsc.html` — what runs in your RSC server (Worker / Node)
90
+
91
+ Open them with a quick local server (file:// has CORS issues with the embedded scripts):
92
+
93
+ ```bash
94
+ pnpm dlx serve -l 5050 .
95
+ # then visit http://localhost:5050/bundle-stats/client.html
96
+ ```
97
+
98
+ ## Step 4: Triage the reports
99
+
100
+ ### Open `client.html` first
101
+
102
+ The treemap shows nested boxes; box area = uncompressed size. Hover for gzip/brotli numbers.
103
+
104
+ **Look for:**
105
+
106
+ - **Your server code.** Any of your own files that contain database queries, secret keys, server actions implementation (not the action _reference_), or `node:` imports. If they appear in the client treemap with non-zero bytes, they leaked. Common causes:
107
+ - A shared module that mixes client and server code without a `"use client"` or `"use server"` directive.
108
+ - A barrel file (`index.ts`) that re-exports both client and server symbols. Tree-shaking should help, but `JSON.parse('{...}')` data and side-effecting top-level statements survive.
109
+ - Client component imports a server-only utility through an indirect path (e.g., shared types file that pulls server modules).
110
+ - **Multiple copies of the same package.** Look for two boxes with the same package name but different version paths. Usually means a transitive dep pinned a different version.
111
+ - **The `@rangojs/router` chunk** should be roughly **50 KB gzip** (74 files). If significantly larger, you might be importing client-incompatible APIs from the wrong subpath.
112
+ - **Per-route client-reference chunks** (named like `chunk-<hash>.js`). Each `"use client"` boundary can become its own chunk. If you have hundreds of tiny chunks, you may have over-split (every leaf component as a client component); if you have one massive 200 KB chunk, you've under-split (a wide client tree behind one boundary).
113
+
114
+ ### Now check `ssr.html`
115
+
116
+ **Look for:**
117
+
118
+ - **`react-dom-server.edge.development-*.js`** (or any `*.development*.js` chunk). This is the dev/prod React doubling. Fix: add `define: { "process.env.NODE_ENV": '"production"' }` to your vite config (see Step 2).
119
+ - **Your client components** appearing in SSR. They're _expected_ here — SSR hydration needs to produce HTML for them. The same components show up in `client.html` too because the browser hydrates them. This is not a leak.
120
+ - **Total SSR size**: a reasonable Rango SSR is ~140 KB gzip plus your app code. If it's >300 KB, almost always (1) dev/prod React duplication or (2) a giant data structure being inlined.
121
+
122
+ ### Now check `rsc.html`
123
+
124
+ **Look for:**
125
+
126
+ - **`virtual:rsc-router/routes-manifest`** should be **tiny** (< 1 KB). If it's > 100 KB, you're on an old version of `@rangojs/router` that inlined the trie eagerly — upgrade to a release that includes commit `d10a2470`.
127
+ - **`virtual:rsc-router/routes-manifest/<hash>`** is the lazy per-router chunk. Its size is proportional to your route count. For a typical app: 5–50 KB gzip. For a stress-test app with thousands of routes: hundreds of KB. If yours is unexpectedly huge, check whether you're generating routes you don't need.
128
+ - **`<your-router>.named-routes.gen.ts`** — generated route map. Should match your route count.
129
+ - **Your action and loader implementations** — these run server-side. Expected to be here, not in client.
130
+ - **Worker-incompatible code** (Node-only imports like `node:fs` that Cloudflare doesn't support). The build will usually fail before the analyzer runs, but if you're seeing runtime errors at the edge, the RSC treemap shows what made it in.
131
+
132
+ ## Step 5: Fix what you find
133
+
134
+ | Finding | Fix |
135
+ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
136
+ | Your server code in `client.html` (non-zero bytes) | Audit the import chain. Add `"use server"` to server-only files. Move shared data out of barrel files. Use the `@rangojs/router/server` subpath for explicitly server APIs. |
137
+ | Your server code in `client.html` listed but 0 bytes | Tree-shaking already eliminated it. Cosmetic. Leave it. |
138
+ | `react-dom-server.edge.development-*.js` in SSR or RSC | Add the `define` block from Step 2 to your vite config. |
139
+ | Routes-manifest > 100 KB gzip in RSC eager chunk | Update `@rangojs/router` to a release that includes the lazy-only manifest fix. |
140
+ | Same package version present twice | Run `pnpm dedupe` (or `npm dedupe`). If the duplication persists, a transitive dep pins an incompatible version — open a PR upstream or pin the resolution. |
141
+ | Client chunk > 500 KB gzip with a single dominant module | That module is your largest client component. Consider lazy-loading via dynamic `import()` or moving non-interactive parts to server components. |
142
+ | Hundreds of tiny client chunks | You've sprinkled `"use client"` too liberally. Hoist directives to higher boundaries so React groups them. |
143
+
144
+ ## When to re-run
145
+
146
+ - Before every production deploy, especially after adding new dependencies.
147
+ - After upgrading `@rangojs/router`, React, or `@vitejs/plugin-rsc`.
148
+ - After adding routes that scale with data (e.g., one route per item from a content directory) — the manifest may have grown.
149
+ - When CI starts reporting larger artifact sizes.
150
+
151
+ ## Reporting Rango regressions
152
+
153
+ If a finding looks like a `@rangojs/router` regression (the framework is shipping more than it should, not your app), open an issue at the [@rangojs/router GitHub](https://github.com/ivogt/vite-rsc/issues) and include:
154
+
155
+ - The output of `client.html` / `rsc.html` (screenshots or the JSON `data = {...}` block from the HTML).
156
+ - The `@rangojs/router` version (`pnpm why @rangojs/router`).
157
+ - Your `vite.config.ts`.
158
+
159
+ The framework maintainers run a similar audit internally — the methodology in this skill mirrors what they use to validate every release.
@@ -34,6 +34,7 @@ Django-inspired RSC router with composable URL patterns, type-safe href, and ser
34
34
  | `/response-routes` | JSON/text/HTML/XML/stream endpoints with `path.json()`, `path.text()` |
35
35
  | `/mime-routes` | Content negotiation — same URL, different response types via Accept header |
36
36
  | `/fonts` | Load web fonts with preload hints |
37
+ | `/bundle-analysis` | Audit your app's production bundle for server leaks and oversized chunks |
37
38
  | `/migrate-nextjs` | Migrate a Next.js App Router project to Rango |
38
39
  | `/migrate-react-router` | Migrate a React Router / Remix project to Rango |
39
40
 
package/src/index.ts CHANGED
@@ -305,9 +305,14 @@ export {
305
305
  // Path-based response type lookup from RegisteredRoutes
306
306
  export type { PathResponse } from "./href-client.js";
307
307
 
308
- // Telemetry sink
309
- export { createConsoleSink } from "./router/telemetry.js";
310
- export { createOTelSink } from "./router/telemetry-otel.js";
308
+ // Telemetry types only — the createConsoleSink/createOTelSink values are
309
+ // server-only and live in index.rsc.ts (the `react-server` condition of the
310
+ // bare `@rangojs/router` import). Re-exporting them as values from this
311
+ // (default/client) entry would pull telemetry.ts and telemetry-otel.ts into
312
+ // the client module graph; both tree-shake to zero bytes but still appear in
313
+ // bundle analysis output and slow build-time module resolution. Consumers
314
+ // who need the values in non-RSC contexts can import from
315
+ // `@rangojs/router/server`.
311
316
  export type { OTelTracer, OTelSpan } from "./router/telemetry-otel.js";
312
317
  export type { TelemetrySink, TelemetryEvent } from "./router/telemetry.js";
313
318
 
@@ -58,7 +58,7 @@ export function generateRoutesManifestModule(state: DiscoveryState): string {
58
58
  }
59
59
 
60
60
  const lines = [
61
- `import { setCachedManifest, setPrecomputedEntries, setRouteTrie, setRouterManifest, registerRouterManifestLoader, clearAllRouterData } from "@rangojs/router/server";`,
61
+ `import { setCachedManifest, setRouterManifest, registerRouterManifestLoader, clearAllRouterData } from "@rangojs/router/server";`,
62
62
  ...genFileImports,
63
63
  // Clear stale per-router cached data (manifest, trie, precomputed entries)
64
64
  // before re-populating. In Cloudflare dev mode, program reloads re-evaluate
@@ -101,28 +101,18 @@ export function generateRoutesManifestModule(state: DiscoveryState): string {
101
101
  }
102
102
  }
103
103
 
104
- // In dev mode, skip trie and precomputed entries injection. These are
105
- // computed once during initial discovery and become stale after route
106
- // changes. A stale trie would incorrectly match removed routes. The
107
- // handler falls back to Phase 2 regex matching against the live
108
- // router.urlpatterns, which is always correct after a program reload.
109
- // In build mode, the trie is always fresh (built from the final route
110
- // tree) so it's safe to inject.
111
- if (state.isBuildMode) {
112
- if (
113
- state.mergedPrecomputedEntries &&
114
- state.mergedPrecomputedEntries.length > 0
115
- ) {
116
- lines.push(
117
- `setPrecomputedEntries(${jsonParseExpression(state.mergedPrecomputedEntries)});`,
118
- );
119
- }
120
- if (state.mergedRouteTrie) {
121
- lines.push(
122
- `setRouteTrie(${jsonParseExpression(state.mergedRouteTrie)});`,
123
- );
124
- }
125
- }
104
+ // Per-router trie and precomputedEntries are NOT inlined eagerly.
105
+ // They live in the per-router lazy chunks (generatePerRouterModule) and
106
+ // are loaded via ensureRouterManifest(routerId), which is awaited before
107
+ // every request in router.fetch() and before findMatch is reached.
108
+ // Inlining the merged versions here would duplicate the per-router data
109
+ // (the merged trie/precomputedEntries equal the per-router data for
110
+ // single-router apps; for multi-router, the merged trie is dead code
111
+ // because find-match.ts only consumes per-router tries).
112
+ //
113
+ // In dev mode, the handler also falls back to Phase 2 regex matching
114
+ // against live router.urlpatterns, which is always correct after a
115
+ // program reload.
126
116
 
127
117
  // Register lazy loaders for per-router manifest modules.
128
118
  // Each import() uses a static string literal so Rollup creates separate chunks.