@tenphi/tasty 0.0.0-snapshot.05e04ff → 0.0.0-snapshot.06c8a41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/astro-CeYENy2x.js +301 -0
  2. package/dist/astro-CeYENy2x.js.map +1 -0
  3. package/dist/{babel-B_P8t-f0.d.ts → babel-DWCsafYw.d.ts} +2 -2
  4. package/dist/{collector-DCI2yzwx.js → collector-B3OsM252.js} +36 -13
  5. package/dist/collector-B3OsM252.js.map +1 -0
  6. package/dist/{collector-CQDeU7WS.d.ts → collector-BTVXj2hS.d.ts} +21 -3
  7. package/dist/{config-B97n_EIv.js → config-B3gPdCqd.js} +202 -393
  8. package/dist/config-B3gPdCqd.js.map +1 -0
  9. package/dist/{config-CwRr6-fG.d.ts → config-LfIDmVHx.d.ts} +93 -65
  10. package/dist/core/index.d.ts +5 -5
  11. package/dist/core/index.js +6 -6
  12. package/dist/{core-DWrUWxog.js → core-DGm0CFHP.js} +271 -184
  13. package/dist/core-DGm0CFHP.js.map +1 -0
  14. package/dist/css-resources-Cyl_axbI.js +149 -0
  15. package/dist/css-resources-Cyl_axbI.js.map +1 -0
  16. package/dist/{css-writer-Cq0fg5v8.js → css-writer-Bgowobbx.js} +3 -3
  17. package/dist/{css-writer-Cq0fg5v8.js.map → css-writer-Bgowobbx.js.map} +1 -1
  18. package/dist/{format-rules-Wb7dJOoL.js → format-rules-XRw9u7d4.js} +3 -29
  19. package/dist/format-rules-XRw9u7d4.js.map +1 -0
  20. package/dist/{hydrate-gFTLBDK9.js → hydrate-CNOmZprz.js} +2 -2
  21. package/dist/{hydrate-gFTLBDK9.js.map → hydrate-CNOmZprz.js.map} +1 -1
  22. package/dist/{index-C0W21Qcb.d.ts → index-Bm9ltvdH.d.ts} +28 -53
  23. package/dist/{index-DpykQKO8.d.ts → index-BmogEzTo.d.ts} +60 -38
  24. package/dist/index.d.ts +5 -5
  25. package/dist/index.js +41 -117
  26. package/dist/index.js.map +1 -1
  27. package/dist/{renderChunk-COXABoQz.js → keyframes-DE-OE76F.js} +248 -3
  28. package/dist/keyframes-DE-OE76F.js.map +1 -0
  29. package/dist/{merge-styles-Bpwfy1CS.d.ts → merge-styles-BcLl1u_d.d.ts} +2 -2
  30. package/dist/{merge-styles-CzVxdtav.js → merge-styles-DuoZEsm9.js} +2 -2
  31. package/dist/{merge-styles-CzVxdtav.js.map → merge-styles-DuoZEsm9.js.map} +1 -1
  32. package/dist/{resolve-recipes-BnrUEjWV.js → resolve-recipes-H9NqOQuP.js} +3 -3
  33. package/dist/{resolve-recipes-BnrUEjWV.js.map → resolve-recipes-H9NqOQuP.js.map} +1 -1
  34. package/dist/ssr/astro-client.js +1 -1
  35. package/dist/ssr/astro-middleware-extract-static.d.ts +11 -0
  36. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  37. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  38. package/dist/ssr/astro-middleware-extract.d.ts +11 -0
  39. package/dist/ssr/astro-middleware-extract.js +9 -0
  40. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  41. package/dist/ssr/astro-middleware-static.d.ts +3 -1
  42. package/dist/ssr/astro-middleware-static.js +1 -1
  43. package/dist/ssr/astro-middleware.d.ts +3 -1
  44. package/dist/ssr/astro-middleware.js +1 -1
  45. package/dist/ssr/astro.d.ts +45 -3
  46. package/dist/ssr/astro.js +1 -156
  47. package/dist/ssr/index.d.ts +2 -2
  48. package/dist/ssr/index.js +3 -3
  49. package/dist/ssr/index.js.map +1 -1
  50. package/dist/ssr/next-config.d.ts +66 -0
  51. package/dist/ssr/next-config.js +115 -0
  52. package/dist/ssr/next-config.js.map +1 -0
  53. package/dist/ssr/next.d.ts +9 -2
  54. package/dist/ssr/next.js +26 -9
  55. package/dist/ssr/next.js.map +1 -1
  56. package/dist/ssr-collector-ref-COs_ioWl.js +29 -0
  57. package/dist/ssr-collector-ref-COs_ioWl.js.map +1 -0
  58. package/dist/static/index.d.ts +2 -2
  59. package/dist/static/index.js +1 -1
  60. package/dist/zero/babel.d.ts +1 -1
  61. package/dist/zero/babel.js +4 -4
  62. package/dist/zero/babel.js.map +1 -1
  63. package/dist/zero/index.d.ts +1 -1
  64. package/dist/zero/index.js +1 -1
  65. package/dist/zero/next.d.ts +1 -1
  66. package/docs/debug.md +13 -0
  67. package/docs/injector.md +21 -7
  68. package/docs/runtime-benchmarks.md +192 -75
  69. package/docs/ssr.md +179 -20
  70. package/package.json +30 -9
  71. package/dist/collector-DCI2yzwx.js.map +0 -1
  72. package/dist/config-B97n_EIv.js.map +0 -1
  73. package/dist/core-DWrUWxog.js.map +0 -1
  74. package/dist/format-rules-Wb7dJOoL.js.map +0 -1
  75. package/dist/renderChunk-COXABoQz.js.map +0 -1
  76. package/dist/ssr/astro.js.map +0 -1
@@ -1,19 +1,22 @@
1
1
  # Runtime Benchmarks
2
2
 
3
3
  Tasty keeps its performance claims in reproducible benchmarks rather than
4
- combining unlike measurements into one score. The repository measures four
4
+ combining unlike measurements into one score. The repository measures three
5
5
  different costs:
6
6
 
7
7
  1. Style parsing and generation in Node.
8
8
  2. The React overhead of an empty `tasty({})` wrapper.
9
9
  3. Cold browser generation and injection compared with equivalent CSS that is
10
10
  already on the page.
11
- 4. A representative React update that combines wrapper, cache, generation,
12
- injection, and style-resolution work.
11
+ 4. The steady-state interaction path — mod flips and styled subtrees opening
12
+ and closing after the page has loaded.
13
+ 5. Page-load cold start: network, module compilation, execution and first
14
+ paint, end to end in a throttled browser.
13
15
 
14
- These are focused microbenchmarks, not page-load or interaction scores. Run
15
- them several times on an otherwise idle machine and use a production profile
16
- to decide whether any cost matters in an application.
16
+ The first four are focused microbenchmarks, not page-level scores. The fifth is
17
+ a page-level measurement and is the only one that answers "what does a visitor
18
+ wait for". Run them several times on an otherwise idle machine and use a
19
+ production profile to decide whether any cost matters in an application.
17
20
 
18
21
  ## Reproducing the Results
19
22
 
@@ -21,12 +24,14 @@ to decide whether any cost matters in an application.
21
24
  pnpm bench
22
25
  pnpm bench:overhead
23
26
  pnpm bench:injection
24
- pnpm bench:tree
27
+ pnpm bench:interaction
28
+ pnpm bench:cold-start
25
29
  ```
26
30
 
27
- `pnpm bench` runs the core pipeline benchmarks in Node. The other three commands
28
- use production code paths in headless Chromium. The first checkout may require
29
- `pnpm test:setup` to download Chromium.
31
+ `pnpm bench` runs the core pipeline benchmarks in Node. The rest use production
32
+ code paths in headless Chromium. The first checkout may require
33
+ `pnpm test:setup` to download Chromium, and `pnpm bench:cold-start` needs a
34
+ current `dist/` — run `pnpm build` first.
30
35
 
31
36
  Run the Node and browser suites separately so they do not compete for CPU. The
32
37
  browser timer has 0.1 ms resolution, so both browser benchmarks perform many
@@ -106,21 +111,17 @@ snapshot experiment with controlled garbage collection.
106
111
  work when Tasty must generate and inject CSS that an otherwise equivalent page
107
112
  already has. It does not compare different stylesheet insertion techniques.
108
113
 
109
- The benchmark covers four group sizes with one style-resolution boundary per
110
- group:
114
+ The benchmark covers two useful workloads:
111
115
 
112
- - **One new rule:** add one rule, append its element, and immediately read its
113
- computed style. Each sample performs 50 independent groups for timer
114
- stability.
115
- - **10 new rules together:** generate and insert 10 rules, append their 10
116
- elements, then read every computed color without another write. Each sample
117
- performs 10 independent groups.
118
- - **100 or 1,000 new rules together:** perform the same sequence once per
119
- sample with 100 or 1,000 rules before the resolution boundary.
120
-
121
- Repeating the smaller groups inside one sample only raises the measurement
122
- above Chromium's timer resolution. Results are divided by that repetition
123
- count, so every row below describes one group with one resolution boundary.
116
+ - **One new rule:** add one rule to an existing stylesheet, append its one
117
+ element, and immediately read its computed style. Each timed sample performs
118
+ 50 independent one-rule transactions and reports their total; dividing the
119
+ raw/Tasty difference by 50 produces a stable per-rule result despite
120
+ Chromium's 0.1 ms timer resolution.
121
+ - **1,000 new rules together:** generate and insert all 1,000 rules into one
122
+ stylesheet, append all 1,000 elements, then read every computed color without
123
+ another write in between. This gives the browser one style-resolution
124
+ boundary for the group.
124
125
 
125
126
  For every transaction, the existing-CSS control has the equivalent stylesheet
126
127
  parsed, adopted, and attached before timing. The runtime root has a Tasty
@@ -137,20 +138,20 @@ the result. Pre-creating both stylesheets also excludes one-time sheet creation
137
138
  and adoption from the subtraction.
138
139
 
139
140
  On an Apple M3 Pro with Chromium 151, three consecutive runs produced these
140
- normalized ranges:
141
+ ranges:
141
142
 
142
- | New rules before one resolution | Groups per sample | Incremental cost per group | Incremental cost per rule |
143
- | ------------------------------: | ----------------: | -------------------------: | ------------------------: |
144
- | 1 | 50 | 0.111–0.114 ms | 111–114 us |
145
- | 10 | 10 | 0.142–0.159 ms | 14.2–15.9 us |
146
- | 100 | 1 | 0.90–0.94 ms | 9.0–9.4 us |
147
- | 1,000 | 1 | 7.58–8.10 ms | 7.6–8.1 us |
143
+ | Workload | CSS already present | Tasty runtime | Incremental Tasty cost |
144
+ | ---------------------------------------------------- | ------------------: | -------------: | ---------------------: |
145
+ | One new rule + immediate resolution, per transaction | 2.8–3.3 us | 110.3–113.8 us | 107.3–111.0 us |
146
+ | 1,000 new rules + one resolution | 1.86–2.06 ms | 9.01–9.98 ms | 7.13–7.92 ms |
147
+ | 1,000-rule workload, incremental cost per rule | — | — | 7.1–7.9 us |
148
148
 
149
- The curve makes the fixed work visible. Delivering 1,000 rules before one
150
- resolution boundary cost roughly 67–73 times as much in total as delivering
151
- one rule and resolving it, not 1,000 times as much. The average incremental
152
- cost per rule was roughly 14–15 times lower because the group amortized fixed
153
- transaction work and let the browser resolve all stylesheet writes together.
149
+ Directly compared, injecting 1,000 rules before one resolution boundary cost
150
+ about 66–71 times as much in total as injecting one rule and resolving it—not
151
+ 1,000 times as much. Its average incremental cost per rule was about 14–16
152
+ times lower. This is the same Tasty generation and injection path in both cases;
153
+ the group amortizes fixed transaction work and lets the browser resolve all the
154
+ stylesheet writes together.
154
155
 
155
156
  The subtraction is the meaningful result. It includes Tasty's cold style
156
157
  generation, cache and injector bookkeeping, rule insertion, and any additional
@@ -159,46 +160,156 @@ pretend to isolate `insertRule()` from the system that calls it.
159
160
 
160
161
  This is a deliberately cold workload. Reused styles resolve from cache and do
161
162
  not inject another rule. Different rule complexity, DOM shape, stylesheet size,
162
- browser, and hardware will change the number. Because the same group and
163
- resolution pattern is present in each workload's control, the difference
164
- answers the narrower delivery question: how much extra work did Tasty perform
165
- when the same CSS was not already there?
166
-
167
- ## Representative React Tree
168
-
169
- [`tasty-tree.bench.tsx`](../src/tasty-tree.bench.tsx) bridges the isolated
170
- measurements with one production React update. Every path updates 1,000 host
171
- elements sharing 20 combinations of `color` and `padding`, then reads computed
172
- styles after the commit:
173
-
174
- - **CSS already present:** raw elements switch between classes whose rules were
175
- attached before timing.
176
- - **Tasty, warm:** the elements switch between two sets of Tasty styles that
177
- were generated before timing.
178
- - **Tasty, cold:** every update introduces 20 new combinations shared across
179
- the 1,000 elements.
180
-
181
- The Tasty paths use the normal component API and `TastyBatchProvider`. On an
182
- Apple M3 Pro with production React 19.2.4 and Chromium 151, three consecutive
183
- runs produced these mean ranges:
184
-
185
- | Update path | Total time for 1,000 elements |
186
- | ----------------------------------- | ----------------------------: |
187
- | CSS already present | 1.64–1.70 ms |
188
- | Tasty, shared styles already cached | 4.17–4.43 ms |
189
- | Tasty, 20 new shared styles | 4.62–4.80 ms |
190
-
191
- In this workload, the warmed Tasty path added 2.52–2.73 ms over raw elements
192
- with existing CSS. Introducing 20 new shared combinations added another
193
- 0.38–0.55 ms over the warm Tasty update. This is a synthetic update, not an
194
- application score: it excludes effects, layout reads, paint, and concurrent
195
- scheduling, while deliberately making all 1,000 elements participate in every
196
- commit.
163
+ browser, and hardware will change the number. The single-rule and 1,000-rule
164
+ results are not interchangeable: the first crosses the injection-to-resolution
165
+ boundary once per rule, while the second lets the browser resolve 1,000 writes
166
+ together. Because the same resolution pattern is present in each workload's
167
+ control, the difference answers the narrower delivery question: how much extra
168
+ work did Tasty perform when the same CSS was not already there?
169
+
170
+ ## Steady-State Interaction
171
+
172
+ The benchmarks above measure mounting and whole-tree updates. A running
173
+ application spends most of its time on neither. It flips mods — hovered,
174
+ pressed, selected, expanded — on elements whose styles never change, one
175
+ element at a time, and it mounts and unmounts small styled subtrees as menus
176
+ and dialogs open. Both paths go through the state-map and ref-counting
177
+ machinery rather than the parser, so a regression in them is invisible to every
178
+ other benchmark here.
179
+
180
+ [`tasty-interaction.bench.tsx`](../src/tasty-interaction.bench.tsx) pairs each
181
+ case with a raw-DOM equivalent driven by a hand-written stylesheet that
182
+ produces the same computed color and background in both states. The benchmark
183
+ fails if either arm resolves to anything else, so an arm that quietly rendered
184
+ unstyled elements cannot report a flattering number.
185
+
186
+ Each leaf owns its own `useState`, which is what keeps a single-element
187
+ interaction single: re-rendering the root to flip one row would time the whole
188
+ tree. One toggle is far below Chromium's 0.1 ms timer resolution, so a sample
189
+ flips a 100-element tree three times over — 300 commits — and the churn case
190
+ performs 20 open/close cycles. Divide the raw/Tasty difference by those counts.
191
+
192
+ Two things had to be sized deliberately, and both are the difference between a
193
+ readable number and noise:
194
+
195
+ - **The tree is small (100 elements), not large.** React locates a leaf's
196
+ pending update by walking the sibling list, so in a 1,000-element tree a
197
+ single-element update costs ~68 us of traversal — identical in both arms and
198
+ an order of magnitude above anything the styling layer contributes.
199
+ - **The sample resolves style once, not once per flip.** Forcing a recalc
200
+ between flips costs ~70 us in both arms, which buries the delta the same way.
201
+ The browser's side of an interaction is real, but it is the browser's;
202
+ resolution boundaries are what the injection benchmark above measures.
203
+
204
+ On an Apple M1 Max with React 19.2.8 and Chromium 151, three consecutive runs
205
+ produced these ranges:
206
+
207
+ | Workload | Raw elements | Tasty mods | Extra per unit |
208
+ | --------------------------------------------------- | -----------: | ------------: | ------------------------: |
209
+ | 300 single-element mod toggles in a 100-element tree | 2.4–2.5 ms | 2.9–3.0 ms | 1.6–1.7 us / interaction |
210
+ | 20 mount + unmount cycles of a 200-element subtree | 7.6–7.7 ms | 12.6–12.7 ms | 1.22–1.27 us / element |
211
+
212
+ Two things are worth reading out of this.
213
+
214
+ A mod flip on an already-mounted element costs about 1.7 us. The CSS for both
215
+ states already exists — Tasty emits every state of a style map in one chunk on
216
+ first render — so both arms perform the same commit, and what is left is
217
+ Tasty's props and mod handling. That is the same order as the ~1 us empty
218
+ wrapper measured above, which is most of where it comes from.
219
+
220
+ Subtree churn is not about styling at all. Its ~1.25 us per element sits right
221
+ on the empty-wrapper mount cost, because the styles are already cached:
222
+ reopening a menu re-pays the React wrapper, not the style pipeline.
223
+
224
+ ## Page-Load Cold Start
225
+
226
+ Every benchmark above deliberately excludes the network, module compilation and
227
+ the first render. [`scripts/cold-start`](../scripts/cold-start) measures exactly
228
+ those: what a visitor waits for between requesting a page and seeing styled
229
+ content, in a real Chromium under CDP network and CPU throttling.
230
+
231
+ Three pages render the same 50 styled components and are verified, before any
232
+ timing, to produce the same 50 elements at the same computed color:
233
+
234
+ - **baseline** — the components server-rendered: identical markup, identical
235
+ class names, a linked stylesheet, and no Tasty on the page. Every other
236
+ column is a delta against this one.
237
+ - **runtime** — Tasty generates the CSS in the browser, as a client-rendered
238
+ application does. The run asserts it really did (69 rules generated).
239
+ - **prewarm** — the same, after one throwaway `computeStyles()` against a
240
+ detached root before the first component renders.
241
+
242
+ Each cell is the median of 5 uncached loads in a fresh browser context. The run
243
+ ends at the first contentful paint, observed through a `PerformanceObserver`
244
+ rather than counted in animation frames — `requestAnimationFrame` fires before
245
+ paint, so a page that commits fast can reach its second frame with nothing
246
+ painted yet.
247
+
248
+ The Tasty bundle is built from what the page imports (`tasty`, `configure`,
249
+ `computeStyles`, `tastyDebug`), so it is tree-shaken the way an application's
250
+ would be: 52.0 KB brotli, 186 KB raw. Re-exporting the whole library instead
251
+ adds ~4 KB brotli of code no page here calls, which would inflate the column
252
+ that dominates this result.
253
+
254
+ On an Apple M1 Max with React 19.2.8 and Chromium 151, first contentful paint:
255
+
256
+ | Link / CPU | baseline | runtime | prewarm | Tasty's cost |
257
+ | --------------------- | -------: | ------: | ------: | -----------: |
258
+ | No throttling, 1x | 44 ms | 56 ms | 56 ms | +12 ms |
259
+ | Fast 4G, 1x | 744 ms | 924 ms | 920 ms | +180 ms |
260
+ | Slow 4G, 1x | 2764 ms | 3708 ms | 3712 ms | +944 ms |
261
+ | No throttling, 4x CPU | 156 ms | 204 ms | 204 ms | +48 ms |
262
+ | Fast 4G, 4x CPU | 820 ms | 1052 ms | 1048 ms | +232 ms |
263
+ | Slow 4G, 4x CPU | 2824 ms | 3836 ms | 3844 ms | +1012 ms |
264
+
265
+ **The cost is the bundle, not the work.** On Slow 4G the extra transfer alone
266
+ accounts for 946 ms of the 944 ms FCP delta — the whole of it, within noise.
267
+ Everything Tasty then *does* is small by comparison:
268
+
269
+ | Phase (Slow 4G, 1x) | baseline | runtime | prewarm |
270
+ | ----------------------- | -------: | ------: | ------: |
271
+ | js+css transfer | 2150 ms | 3096 ms | 3096 ms |
272
+ | module compile (shared) | 1.7 ms | 1.6 ms | 1.5 ms |
273
+ | tasty top-level execute | — | 0.9 ms | 1.1 ms |
274
+ | `configure()` | — | 0.5 ms | 0.4 ms |
275
+ | prewarm | — | — | 4.7 ms |
276
+ | render 1st component | 2.0 ms | 6.7 ms | 2.5 ms |
277
+ | render 49 more | 1.0 ms | 6.0 ms | 5.7 ms |
278
+
279
+ Importing Tasty costs about 1 ms of top-level execution; `configure()` costs
280
+ half of one. The rest of the CPU delta — under 10 ms for 50 components — is
281
+ generation and injection, which is the cost the injection benchmark isolates.
282
+
283
+ One asymmetry is worth naming: the control links a render-blocking stylesheet
284
+ and the runtime modes have none, so the control's first paint waits for CSS the
285
+ runtime modes never request. That is the real difference between the two
286
+ delivery models, not a thumb on the scale, but it means the FCP delta is not
287
+ purely "what Tasty costs to execute".
288
+
289
+ **Prewarming moves the wake-up, it does not remove it.** The first styled render
290
+ is ~4.5 ms more expensive than the ones after it, because that is when the
291
+ engine's deferred payload is actually compiled. A throwaway `computeStyles()`
292
+ against a detached root pays it early: `render 1st` drops from 6.7 ms to
293
+ 2.5 ms. The prewarm itself costs 4.7 ms, so FCP does not move. It is worth
294
+ doing only when something else can overlap it, or when the first render is on a
295
+ latency-critical path and the page has idle time before it.
296
+
297
+ **Retained heap.** After a forced collection, the runtime page holds about
298
+ 1,013 KB more than the control (2,626 KB vs 1,613 KB) for 50 components — the
299
+ parser caches, the chunk cache, the injector's registry and the generated CSS.
300
+ The control is not zero either; most of its 1.6 MB is React and the DOM.
301
+
302
+ CPU throttling changes which line moves. At 4x, module compilation of the
303
+ larger graph becomes visible (7.4 ms → 26 ms) where at 1x it is free: V8
304
+ pre-parses at import and compiles lazily, so a slower CPU pays for code the
305
+ faster one never fully compiled. Transfer numbers from the unthrottled cells
306
+ are not worth reading — with no emulated link, resource timings are scheduling
307
+ jitter.
197
308
 
198
309
  ## Reading the Results Together
199
310
 
200
- Do not add all three benchmark numbers to estimate an application blindly.
201
- They describe different paths:
311
+ Do not add the microbenchmark numbers together to estimate an application
312
+ blindly. They describe different paths:
202
313
 
203
314
  - A stable `tasty()` factory can skip the style pipeline on later renders, but
204
315
  its React wrapper still participates in reconciliation.
@@ -206,11 +317,17 @@ They describe different paths:
206
317
  rule.
207
318
  - A genuinely new style pays generation and injection once, then becomes
208
319
  reusable.
209
- - A tree that shares a small style vocabulary pays the wrapper path per element
210
- but cold generation only per new combination.
320
+ - A mod flip on an already-styled element pays neither; it is a class-name
321
+ change.
211
322
  - Browser style resolution, layout, and paint depend on the actual document and
212
323
  need application-level profiling.
213
324
 
325
+ The cold-start measurement is the one that puts the rest in proportion. On a
326
+ slow connection, essentially all of Tasty's page-load cost is transferring the
327
+ library; the generation and injection the microbenchmarks obsess over is ~10 ms
328
+ for 50 components. Bundle size is therefore the lever with the largest effect
329
+ on first paint, and the runtime levers matter for what happens after it.
330
+
214
331
  The practical optimization target is therefore repeated work: keep style input
215
332
  stable when possible, reuse generated chunks, and generate CSS at build or
216
333
  server time when runtime flexibility is unnecessary.
package/docs/ssr.md CHANGED
@@ -86,6 +86,92 @@ export default function RootLayout({
86
86
 
87
87
  That's it. All `tasty()` components inside the tree automatically get SSR support. No per-component changes needed.
88
88
 
89
+ ### Optional shared globals stylesheet
90
+
91
+ By default, configured global CSS is included in the streamed Tasty style tag
92
+ for every route. `withTastyNext()` can move that stable CSS into one
93
+ content-hashed stylesheet shared by all routes while leaving component and hook
94
+ styles in the normal streaming path.
95
+
96
+ Keep the Tasty config in a side-effect-free module:
97
+
98
+ ```ts
99
+ // app/tasty.config.ts
100
+ import type { TastyConfig } from '@tenphi/tasty';
101
+
102
+ const config: TastyConfig = {
103
+ tokens: { $gap: '8px', '#brand': 'rebeccapurple' },
104
+ globalStyles: { body: { margin: '0', color: '#brand' } },
105
+ fontFaces: {
106
+ Brand: { src: 'url("/fonts/brand.woff2") format("woff2")' },
107
+ },
108
+ };
109
+
110
+ export default config;
111
+ ```
112
+
113
+ Use it from the Next config:
114
+
115
+ ```ts
116
+ // next.config.ts
117
+ import { withTastyNext } from '@tenphi/tasty/ssr/next-config';
118
+ import config from './app/tasty.config';
119
+
120
+ export default withTastyNext({
121
+ config,
122
+ })({
123
+ // your Next.js config
124
+ });
125
+ ```
126
+
127
+ The runtime must receive the same config. Import and configure it before the
128
+ registry renders:
129
+
130
+ ```tsx
131
+ // app/tasty-registry.tsx
132
+ 'use client';
133
+
134
+ import { configure } from '@tenphi/tasty';
135
+ import { TastyRegistry } from '@tenphi/tasty/ssr/next';
136
+ import config from './tasty.config';
137
+
138
+ configure(config);
139
+
140
+ export default function TastyStyleRegistry({ children }) {
141
+ return <TastyRegistry>{children}</TastyRegistry>;
142
+ }
143
+ ```
144
+
145
+ The generated file contains eager configuration artifacts: built-in and custom
146
+ `@property` rules, tokens and presets, `@font-face`, `@counter-style`, native
147
+ CSS `@function` definitions, and `globalStyles`. Route-dependent component
148
+ rules and calls to `useGlobalStyles`, `useRawCSS`, `useKeyframes`,
149
+ `useProperty`, `useFontFace`, `useCounterStyle`, and `useFunction` remain
150
+ route-specific. Configured keyframes also remain lazy and are streamed only
151
+ when a route references them.
152
+
153
+ The default output directory is `public/_tasty`. The wrapper adds the generated
154
+ URL to `TastyRegistry`, respects `basePath`, preserves existing `env` and
155
+ `headers` config, and serves the content-hashed file with an immutable one-year
156
+ cache header on Next server deployments. Static exports keep the content-hashed
157
+ URL and leave cache headers to the hosting provider. Older hashes are not
158
+ deleted automatically, so rolling deployments cannot break pages from the
159
+ previous build; clean the generated directory as part of a clean deployment if
160
+ needed. Page-relative CSS resources such as
161
+ `url(../fonts/brand.woff2)` are rejected because moving them would change their
162
+ meaning; use root-relative, absolute, or data URLs.
163
+
164
+ `withTastyNext()` options:
165
+
166
+ | Option | Type | Default | Description |
167
+ | ------------ | ------------- | ------------------------- | ---------------------------------------------------------------------- |
168
+ | `config` | `TastyConfig` | — | Config object; takes precedence over `configFile` |
169
+ | `configFile` | `string` | — | Project-relative config module path; requires the optional `jiti` peer |
170
+ | `rootDir` | `string` | current directory | Next app root when the build runs from a monorepo root |
171
+ | `outputDir` | `string` | `public/_tasty` | Filesystem output directory |
172
+ | `publicPath` | `string` | inferred from `outputDir` | Root-relative URL; required when output is outside `public` |
173
+ | `enabled` | `boolean` | `true` | Disable generation without changing wrapper composition |
174
+
89
175
  ### How it works
90
176
 
91
177
  - `TastyRegistry` is a `'use client'` component, but Next.js still server-renders it on initial page load. The `'use client'` boundary is required solely to access `useServerInsertedHTML` — **not** because `tasty()` components need the client.
@@ -128,13 +214,15 @@ The nonce is automatically applied to all `<style>` and `<script>` tags injected
128
214
 
129
215
  ## Astro
130
216
 
131
- Tasty offers three levels of Astro integration. Choose the one that matches your needs:
217
+ Tasty offers several levels of Astro integration. Choose the one that matches your needs:
132
218
 
133
- | Setup | Config needed | Deduplication | Hooks work | Client JS |
134
- | -------------------------------------- | ------------- | --------------- | ---------------------- | -------------- |
135
- | Zero setup | None | Per render tree | Yes (within each tree) | None |
136
- | `tastyIntegration({ islands: false })` | One line | Cross-tree | Yes | None |
137
- | `tastyIntegration()` | One line | Cross-tree | Yes | Auto-hydration |
219
+ | Setup | Config needed | Deduplication | Hooks work | Client JS |
220
+ | ---------------------------------------------------------------- | ------------- | ------------------------- | ---------------------- | -------------- |
221
+ | Zero setup | None | Per render tree | Yes (within each tree) | None |
222
+ | `tastyIntegration({ islands: false })` | One line | Cross-tree | Yes | None |
223
+ | `tastyIntegration()` | One line | Cross-tree | Yes | Auto-hydration |
224
+ | `tastyIntegration({ css: { mode: 'extract' } })` | One line | Cross-tree and cross-page | Yes | Auto-hydration |
225
+ | `tastyIntegration({ islands: false, css: { mode: 'extract' } })` | One line | Cross-tree and cross-page | Yes | None |
138
226
 
139
227
  ### Zero setup (static pages)
140
228
 
@@ -231,6 +319,63 @@ export default defineConfig({
231
319
 
232
320
  This gives the same middleware deduplication and hook support, but ships zero client-side JavaScript. No class-list `<script>` is emitted.
233
321
 
322
+ #### Build-wide CSS extraction
323
+
324
+ Static Astro builds can move Tasty CSS into content-hashed, browser-cacheable
325
+ shared and page assets:
326
+
327
+ ```ts
328
+ export default defineConfig({
329
+ integrations: [
330
+ react(),
331
+ tastyIntegration({
332
+ islands: false,
333
+ css: {
334
+ mode: 'extract',
335
+ },
336
+ }),
337
+ ],
338
+ });
339
+ ```
340
+
341
+ `css.mode` defaults to `'inline'`, so existing projects keep their current
342
+ output. Extraction requires Astro 5 or newer and only applies to prerendered
343
+ production pages. Development, preview-time SSR, and on-demand routes continue
344
+ to receive the normal inline `<style data-tasty-ssr>` output.
345
+
346
+ Extraction writes every artifact emitted by all styled pages to a shared
347
+ stylesheet. Each page's strict set difference is written to a separate page
348
+ stylesheet. The shared link comes first and the page link follows, so shared
349
+ styles form the base cascade and page-only styles can override them. A fully
350
+ shared page omits the empty page stylesheet. If generated pages have no common
351
+ artifacts, each page receives only its page stylesheet.
352
+
353
+ The shared-base/page-override order is the extraction-mode cascade contract.
354
+ It does not preserve an inline artifact order where a page-only rule originally
355
+ appeared before a shared rule. Use shared styles for defaults and page-only
356
+ styles for overrides.
357
+
358
+ Extracted CSS preserves resource URLs verbatim. Relative URLs in an inline
359
+ style resolve from the page, but in an extracted stylesheet they resolve from
360
+ the asset directory. Use absolute URLs or data URLs when extraction is enabled.
361
+ Root-relative URLs such as `url(/fonts/brand.woff2)` are also safe while the
362
+ stylesheet stays on the page's origin. The build fails with a clear error if an
363
+ artifact contains a page-relative or fragment-only URL, including URL strings
364
+ in `image-set()`, `image()`, `src()`, and `@import`.
365
+
366
+ Assets are written under Astro's configured `build.assets` directory (for
367
+ example, `/_astro/tasty.shared.a1b2c3.css` and
368
+ `/_astro/tasty.page.d4e5f6.css`). Links include the configured Astro `base`, so
369
+ nested routes do not need relative-path handling. Content hashes and output are
370
+ deterministic for identical builds. If `build.assetsPrefix` is configured,
371
+ Tasty uses its CSS-specific prefix (or `fallback`) just like Astro-generated
372
+ stylesheets. When that prefix points to a different origin, root-relative
373
+ resources would resolve against the asset origin rather than the page's origin,
374
+ so the build rejects them as well. Tasty compares the prefix with Astro's `site`
375
+ when it is configured; without `site`, an absolute or protocol-relative prefix
376
+ is treated conservatively as cross-origin. Use a fully absolute resource URL in
377
+ that configuration.
378
+
234
379
  ### Manual middleware (advanced)
235
380
 
236
381
  If you need to compose Tasty's middleware with other middleware (e.g., via `sequence()`), use `tastyMiddleware()` directly:
@@ -263,10 +408,15 @@ Astro's `@astrojs/react` renderer calls `renderToString()` for each React compon
263
408
  - **Static components** (no `client:*`): Styles are collected during `renderToString` and injected into `</head>` as a single `<style>` tag. No JavaScript is shipped.
264
409
  - **Islands** (`client:load`, `client:visible`, etc.): Styles are collected during SSR the same way. On the client, the hydration script (auto-injected by `tastyIntegration()` or manually via `@tenphi/tasty/ssr/astro-client`) reads the class list from `window.__TASTY__` and pre-populates the injector's rules map. The island's `computeStyles()` calls see the class names as already registered and skip the pipeline during hydration.
265
410
  - The middleware reads the full response body, then injects the collected CSS into `</head>` before sending the final HTML.
411
+ - In extraction mode, prerendered responses also carry temporary structured
412
+ artifact metadata. `astro:build:done` uses those collector-provided
413
+ boundaries to write shared and page assets and rewrite generated HTML, then
414
+ removes the metadata. Artifact boundaries are never inferred by splitting or
415
+ reparsing the generated CSS.
266
416
 
267
417
  ### CSP nonce
268
418
 
269
- Call `configure({ nonce: '...' })` before any rendering happens. The middleware reads the nonce and applies it to injected `<style>` and `<script>` tags.
419
+ Call `configure({ nonce: '...' })` before any rendering happens. The middleware reads the nonce and applies it to injected `<style>` and `<script>` tags. In extraction mode, the external stylesheet links retain the nonce.
270
420
 
271
421
  ---
272
422
 
@@ -349,13 +499,14 @@ const stream = await runWithCollector(collector, () =>
349
499
 
350
500
  ### Entry points
351
501
 
352
- | Import path | Description |
353
- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
354
- | `@tenphi/tasty/ssr` | Core SSR API: `ServerStyleCollector`, `createServerStyleCollector`, `runWithCollector`, `hydrateTastyClasses` |
355
- | `@tenphi/tasty/ssr/next` | Next.js App Router: `TastyRegistry` component |
356
- | `@tenphi/tasty/ssr/astro` | Astro: `tastyIntegration`, `tastyMiddleware` |
357
- | `@tenphi/tasty/ssr/astro-client` | Astro: client-side cache hydration (auto-injected by integration, or import manually) |
358
- | `@tenphi/tasty/ssr/astro-middleware`<br>`@tenphi/tasty/ssr/astro-middleware-static` | Astro: the middleware entrypoints `tastyIntegration()` registers via `addMiddleware()`. Exported so Astro can resolve them by specifier; you should not import them. For manual setups use `tastyMiddleware()`. |
502
+ | Import path | Description |
503
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
504
+ | `@tenphi/tasty/ssr` | Core SSR API: `ServerStyleCollector`, `createServerStyleCollector`, `runWithCollector`, `hydrateTastyClasses` |
505
+ | `@tenphi/tasty/ssr/next` | Next.js App Router: `TastyRegistry` component |
506
+ | `@tenphi/tasty/ssr/next-config` | Next.js config wrapper: shared, content-hashed global stylesheet |
507
+ | `@tenphi/tasty/ssr/astro` | Astro: `tastyIntegration`, `tastyMiddleware` |
508
+ | `@tenphi/tasty/ssr/astro-client` | Astro: client-side cache hydration (auto-injected by integration, or import manually) |
509
+ | `@tenphi/tasty/ssr/astro-middleware`<br>`@tenphi/tasty/ssr/astro-middleware-static`<br>`@tenphi/tasty/ssr/astro-middleware-extract`<br>`@tenphi/tasty/ssr/astro-middleware-extract-static` | Astro: the middleware entrypoints `tastyIntegration()` registers via `addMiddleware()`. Exported so Astro can resolve them by specifier; you should not import them. For manual setups use `tastyMiddleware()`. |
359
510
 
360
511
  ### `ServerStyleCollector`
361
512
 
@@ -375,7 +526,7 @@ Constructor: `new ServerStyleCollector(namePrefix?)`, or use the `createServerSt
375
526
  | `allocateCounterStyleName(providedName?)` | Allocate a counter-style name. Returns `providedName` if given, otherwise generates one using `${namePrefix}c${counter}` (e.g. `tc0`, `tc1`, ...). |
376
527
  | `collectGlobalStyles(key, css)` | Record global styles (from `useGlobalStyles`). Deduplicated by key. |
377
528
  | `collectRawCSS(key, css)` | Record raw CSS text (from `useRawCSS`). Deduplicated by key. |
378
- | `collectInternals()` | Collect internal `@property` rules, `:root` token defaults, `@font-face`, and `@counter-style` rules from the global config. Called automatically on first chunk collection; idempotent. |
529
+ | `collectInternals()` | Collect eager configured globals: `@property`, `:root` tokens and presets, `@font-face`, `@counter-style`, `@function`, and `globalStyles`. Called automatically on first chunk collection; idempotent. |
379
530
  | `getCSS()` | Get all collected CSS as a single string. For non-streaming SSR. |
380
531
  | `flushCSS()` | Get only CSS collected since the last flush. For streaming SSR. |
381
532
  | `getRenderedClassNames()` | Get the list of class names rendered so far. Serialized to `window.__TASTY__` for client hydration via `hydrateTastyClasses()`. |
@@ -384,10 +535,18 @@ Constructor: `new ServerStyleCollector(namePrefix?)`, or use the `createServerSt
384
535
 
385
536
  Next.js App Router component. Props:
386
537
 
387
- | Prop | Type | Default | Description |
388
- | --------------- | ----------- | -------- | ------------------------------------------------ |
389
- | `children` | `ReactNode` | required | Application tree |
390
- | `transferCache` | `boolean` | `true` | Embed cache state script for zero-cost hydration |
538
+ | Prop | Type | Default | Description |
539
+ | ------------------ | ----------------- | --------- | ------------------------------------------------------------------------- |
540
+ | `children` | `ReactNode` | required | Application tree |
541
+ | `transferCache` | `boolean` | `true` | Embed cache state script for zero-cost hydration |
542
+ | `sharedStylesheet` | `string \| false` | generated | Override the shared URL, or disable generated shared CSS for the registry |
543
+
544
+ ### `withTastyNext(options)`
545
+
546
+ Next.js configuration wrapper exported from
547
+ `@tenphi/tasty/ssr/next-config`. It generates a shared stylesheet from eager
548
+ Tasty configuration artifacts and wires its URL and immutable cache header
549
+ into the Next config. Route-specific CSS continues through `TastyRegistry`.
391
550
 
392
551
  ### `tastyIntegration(options?)`
393
552
 
@@ -429,7 +588,7 @@ Class names are also derived from the _resolved_ styles, so the server and the c
429
588
 
430
589
  ### Styles duplicated after hydration
431
590
 
432
- **Global CSS** (`:root` tokens, `@property`, `globalStyles`, `@font-face`, `@counter-style`) configured via `configure()` is automatically deduplicated. When Tasty detects `<style data-tasty-ssr>` in the document, it skips client-side injection of globals that were already rendered by the SSR collector. This means `configure()` can be called with the full config on both server and client — no `typeof window === 'undefined'` guard is needed.
591
+ **Global CSS** (`:root` tokens, `@property`, `globalStyles`, `@font-face`, `@counter-style`, `@function`) configured via `configure()` is automatically deduplicated. When Tasty detects an inline or extracted `[data-tasty-ssr]` stylesheet in the document, it skips client-side injection of globals that were already rendered by the SSR collector. This means `configure()` can be called with the full config on both server and client — no `typeof window === 'undefined'` guard is needed.
433
592
 
434
593
  **Component CSS**: SSR `<style data-tasty-ssr>` tags remain in the DOM. The client injector creates separate `<style>` elements for any new styles. SSR styles are never modified or removed by the client. If this is a concern for very large apps, you can remove the SSR style tags and hydration scripts manually after hydration:
435
594