@tenphi/tasty 0.0.0-snapshot.27b6708 → 0.0.0-snapshot.28eb83c

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 (106) hide show
  1. package/README.md +38 -54
  2. package/dist/{babel-BUQGeOXA.d.ts → babel-D6lOuSwk.d.ts} +2 -2
  3. package/dist/chunks/async-storage-DKK-wTD4.js.map +1 -0
  4. package/dist/chunks/build-config-BBThSdlo.js +45 -0
  5. package/dist/chunks/build-config-BBThSdlo.js.map +1 -0
  6. package/dist/{collector-DTahQUiV.js → chunks/collector-DcViW2ZQ.js} +28 -14
  7. package/dist/chunks/collector-DcViW2ZQ.js.map +1 -0
  8. package/dist/chunks/config-engine-DQVQK4NU.js +403 -0
  9. package/dist/chunks/config-engine-DQVQK4NU.js.map +1 -0
  10. package/dist/chunks/css-definitions-BZ9vm0ci.js +1284 -0
  11. package/dist/chunks/css-definitions-BZ9vm0ci.js.map +1 -0
  12. package/dist/chunks/css-resources-Cyl_axbI.js +149 -0
  13. package/dist/chunks/css-resources-Cyl_axbI.js.map +1 -0
  14. package/dist/chunks/debug-Vyauml7U.js +583 -0
  15. package/dist/chunks/debug-Vyauml7U.js.map +1 -0
  16. package/dist/chunks/dsl-CXvoaLnj.js +2097 -0
  17. package/dist/chunks/dsl-CXvoaLnj.js.map +1 -0
  18. package/dist/chunks/hydration-CLdVKcH2.js +59 -0
  19. package/dist/chunks/hydration-CLdVKcH2.js.map +1 -0
  20. package/dist/chunks/react-runtime-so_X_yMo.js +1526 -0
  21. package/dist/chunks/react-runtime-so_X_yMo.js.map +1 -0
  22. package/dist/chunks/runtime-engine-DQ5laRou.js +3056 -0
  23. package/dist/chunks/runtime-engine-DQ5laRou.js.map +1 -0
  24. package/dist/{merge-styles-oklji0KB.js → chunks/shared-utils-OIg0N_dp.js} +42 -3
  25. package/dist/chunks/shared-utils-OIg0N_dp.js.map +1 -0
  26. package/dist/{config-B5kHzuNz.js → chunks/style-engine-CBuOt1e4.js} +2387 -7442
  27. package/dist/chunks/style-engine-CBuOt1e4.js.map +1 -0
  28. package/dist/{css-writer-B-J87ncv.js → chunks/zero-engine-BFh7gKbK.js} +3 -3
  29. package/dist/chunks/zero-engine-BFh7gKbK.js.map +1 -0
  30. package/dist/{collector-DUaHCcTS.d.ts → collector-CAmndLXe.d.ts} +23 -3
  31. package/dist/{config-YsxGv4tq.d.ts → config-BWYrv_Aa.d.ts} +141 -37
  32. package/dist/core/index.d.ts +5 -5
  33. package/dist/core/index.js +9 -6
  34. package/dist/{index-Cd45t5NM.d.ts → index-BzAC3p06.d.ts} +118 -23
  35. package/dist/{index-PqN-DIpn.d.ts → index-D4kRLj2o.d.ts} +128 -68
  36. package/dist/index.d.ts +5 -5
  37. package/dist/index.js +10 -922
  38. package/dist/{merge-styles-CU7JbEwg.d.ts → merge-styles-BFktNP8J.d.ts} +2 -2
  39. package/dist/ssr/astro-client.js +1 -1
  40. package/dist/ssr/astro-middleware-extract-static.d.ts +11 -0
  41. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  42. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  43. package/dist/ssr/astro-middleware-extract.d.ts +11 -0
  44. package/dist/ssr/astro-middleware-extract.js +9 -0
  45. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  46. package/dist/ssr/astro-middleware-static.d.ts +3 -1
  47. package/dist/ssr/astro-middleware.d.ts +3 -1
  48. package/dist/ssr/astro.d.ts +45 -3
  49. package/dist/ssr/astro.js +157 -14
  50. package/dist/ssr/astro.js.map +1 -1
  51. package/dist/ssr/index.d.ts +7 -7
  52. package/dist/ssr/index.js +4 -4
  53. package/dist/ssr/index.js.map +1 -1
  54. package/dist/ssr/next-config.d.ts +66 -0
  55. package/dist/ssr/next-config.js +135 -0
  56. package/dist/ssr/next-config.js.map +1 -0
  57. package/dist/ssr/next.d.ts +9 -2
  58. package/dist/ssr/next.js +26 -10
  59. package/dist/ssr/next.js.map +1 -1
  60. package/dist/static/index.d.ts +2 -2
  61. package/dist/static/index.js +1 -1
  62. package/dist/zero/babel.d.ts +1 -1
  63. package/dist/zero/babel.js +25 -24
  64. package/dist/zero/babel.js.map +1 -1
  65. package/dist/zero/index.d.ts +1 -1
  66. package/dist/zero/index.js +1 -1
  67. package/dist/zero/next.d.ts +1 -1
  68. package/docs/README.md +5 -3
  69. package/docs/adoption.md +3 -3
  70. package/docs/ai-agents.md +83 -78
  71. package/docs/comparison.md +12 -12
  72. package/docs/configuration.md +47 -47
  73. package/docs/debug.md +19 -7
  74. package/docs/dsl.md +3 -3
  75. package/docs/getting-started.md +10 -10
  76. package/docs/injector.md +62 -25
  77. package/docs/methodology.md +3 -3
  78. package/docs/migration-v3.md +49 -49
  79. package/docs/plugins.md +37 -33
  80. package/docs/react-api.md +2 -2
  81. package/docs/runtime-benchmarks.md +351 -0
  82. package/docs/ssr.md +219 -61
  83. package/docs/styles.md +43 -11
  84. package/docs/tasty-static.md +136 -103
  85. package/package.json +80 -11
  86. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  87. package/dist/collector-DTahQUiV.js.map +0 -1
  88. package/dist/config-B5kHzuNz.js.map +0 -1
  89. package/dist/context-CA8YKeMn.js +0 -24
  90. package/dist/context-CA8YKeMn.js.map +0 -1
  91. package/dist/core-Dr4u1NVD.js +0 -1566
  92. package/dist/core-Dr4u1NVD.js.map +0 -1
  93. package/dist/css-writer-B-J87ncv.js.map +0 -1
  94. package/dist/format-global-rules-DklyaXv-.js +0 -22
  95. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  96. package/dist/format-rules-DKOA-6qu.js +0 -130
  97. package/dist/format-rules-DKOA-6qu.js.map +0 -1
  98. package/dist/hydrate-OeMX99We.js +0 -37
  99. package/dist/hydrate-OeMX99We.js.map +0 -1
  100. package/dist/index.js.map +0 -1
  101. package/dist/keyframes-CV8azJf3.js +0 -493
  102. package/dist/keyframes-CV8azJf3.js.map +0 -1
  103. package/dist/merge-styles-oklji0KB.js.map +0 -1
  104. package/dist/resolve-recipes-DTG81rzl.js +0 -144
  105. package/dist/resolve-recipes-DTG81rzl.js.map +0 -1
  106. /package/dist/{async-storage-DKK-wTD4.js → chunks/async-storage-DKK-wTD4.js} +0 -0
@@ -1,1566 +0,0 @@
1
- import { Bt as getGlobalParseFunctions, G as StyleInjector, Gt as parseStyle, It as registerLocalFunctionPolyfills, J as hasLocalCounterStyle, K as extractLocalCounterStyle, Mt as formatFunctionRule, Nt as hasLocalFunctions, Pt as parseFunctionName, Q as hasLocalFontFace, Qt as isDevEnv, Ut as normalizeColorTokenValue, Vt as getGlobalParser, X as fontFaceContentHash, Y as extractLocalFontFace, Z as formatFontFaceRule, _ as isFunctionsPolyfillEnabled, _t as hashString, bt as hasLocalProperties, c as getGlobalInjector, en as Lru, et as STYLE_HANDLER_MAP, f as getNamePrefix, ft as makeClassName, ht as tastyClassRegex, it as PropertyTypeResolver, jt as extractLocalFunctions, l as getGlobalKeyframes, n as getConfig, p as hasGlobalKeyframes, q as formatCounterStyleRule, rt as createStyle, sn as normalizeDslName, tn as overrideColorAlpha, v as isTestEnvironment, vt as extractLocalProperties, wt as CHUNK_NAMES, xt as parsePropertyToken, y as markStylesGenerated, z as camelToKebab } from "./config-B5kHzuNz.js";
2
- import { a as mergeKeyframes, c as generateChunkCacheKey, i as hasLocalKeyframes, l as categorizeStyleKeys, n as extractLocalKeyframes, o as replaceAnimationNames, r as filterUsedKeyframes, s as renderStylesForChunk, t as extractAnimationNamesFromStyles } from "./keyframes-CV8azJf3.js";
3
- import { n as formatPropertyCSS, r as getRegisteredSSRCollector, t as formatRules } from "./format-rules-DKOA-6qu.js";
4
- import { t as resolveRecipes } from "./resolve-recipes-DTG81rzl.js";
5
- import { cache } from "react";
6
- //#region src/utils/function-color.ts
7
- const RE_FUNC_NAME = /^([a-z][a-z0-9-]*)\s*\(/i;
8
- const RE_COLOR_OUT = /^(?:rgb|hsl|hwb|lab|lch|oklab|oklch|color)\(|^#|^var\(--/i;
9
- /**
10
- * Resolve a `name(...)` value produced by a registered custom parse function
11
- * into its concrete color output.
12
- *
13
- * A color function is just a `functions` entry whose output is an already
14
- * supported color (`rgb`, `hsl`, `#…`, `oklch`, …). This helper delegates the
15
- * value to the global parser (which already runs the registered parse function)
16
- * and returns the result only when it looks like a color. Returns `null` when
17
- * `str` is not a registered custom function or its output is not a color.
18
- *
19
- * This is the generic replacement for the previously hardcoded okhsl/okhst
20
- * conversion branches scattered across `strToRgb`, `resolveToRgbaValues`, and
21
- * the `#token.alpha` injection path.
22
- */
23
- function resolveFunctionColor(str) {
24
- const m = RE_FUNC_NAME.exec(str);
25
- if (!m) return null;
26
- const name = m[1].toLowerCase();
27
- getGlobalParser();
28
- if (!(name in getGlobalParseFunctions())) return null;
29
- const out = getGlobalParser().process(str).output;
30
- if (!out || !RE_COLOR_OUT.test(out)) return null;
31
- return out;
32
- }
33
- //#endregion
34
- //#region src/injector/chunk-sheet-registry.ts
35
- /**
36
- * Global registry mapping CSS content hashes to shared constructable
37
- * CSSStyleSheet objects with reference counting.
38
- *
39
- * Multiple shadow roots adopting the same chunk share a single underlying
40
- * stylesheet object — parse once, adopt everywhere.
41
- */
42
- var ChunkSheetRegistry = class {
43
- sheets = /* @__PURE__ */ new Map();
44
- sheetToHash = /* @__PURE__ */ new WeakMap();
45
- /**
46
- * Get or create a CSSStyleSheet for the given CSS text.
47
- * Increments refCount. Uses content hash as the dedup key.
48
- */
49
- acquire(cssText) {
50
- const hash = hashString(cssText);
51
- const existing = this.sheets.get(hash);
52
- if (existing) {
53
- existing.refCount++;
54
- return existing.sheet;
55
- }
56
- const sheet = new CSSStyleSheet();
57
- sheet.replaceSync(cssText);
58
- const entry = {
59
- sheet,
60
- cssText,
61
- refCount: 1
62
- };
63
- this.sheets.set(hash, entry);
64
- this.sheetToHash.set(sheet, hash);
65
- return sheet;
66
- }
67
- /**
68
- * Decrement refCount for a sheet. When refCount reaches 0,
69
- * the sheet is removed from the registry.
70
- */
71
- release(sheet) {
72
- const hash = this.sheetToHash.get(sheet);
73
- if (!hash) return;
74
- const entry = this.sheets.get(hash);
75
- if (!entry) return;
76
- entry.refCount--;
77
- if (entry.refCount <= 0) {
78
- this.sheets.delete(hash);
79
- this.sheetToHash.delete(sheet);
80
- }
81
- }
82
- /**
83
- * Bulk acquire — returns an array of CSSStyleSheet in the same order.
84
- */
85
- acquireAll(cssTexts) {
86
- return cssTexts.map((text) => this.acquire(text));
87
- }
88
- /**
89
- * Bulk release — decrements refCount for each sheet.
90
- */
91
- releaseAll(sheets) {
92
- for (const sheet of sheets) this.release(sheet);
93
- }
94
- /** Number of unique sheets currently held. */
95
- get size() {
96
- return this.sheets.size;
97
- }
98
- };
99
- /** Module-level singleton shared across the entire application. */
100
- const chunkSheetRegistry = new ChunkSheetRegistry();
101
- //#endregion
102
- //#region src/injector/index.ts
103
- /**
104
- * Inject styles and return className with dispose function
105
- */
106
- function inject(rules, options) {
107
- const injector = getGlobalInjector();
108
- markStylesGenerated();
109
- return injector.inject(rules, options);
110
- }
111
- /**
112
- * Inject global rules that should not reserve tasty class names
113
- */
114
- function injectGlobal(rules, options) {
115
- return getGlobalInjector().injectGlobal(rules, options);
116
- }
117
- /**
118
- * Inject raw CSS text directly without parsing
119
- * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.
120
- * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.
121
- *
122
- * @example
123
- * ```tsx
124
- * // Inject raw CSS
125
- * const { dispose } = injectRawCSS(`
126
- * body { margin: 0; padding: 0; }
127
- * .my-class { color: red; }
128
- * `);
129
- *
130
- * // Later, remove the injected CSS
131
- * dispose();
132
- * ```
133
- */
134
- function injectRawCSS(css, options) {
135
- return getGlobalInjector().injectRawCSS(css, options);
136
- }
137
- /**
138
- * Get raw CSS text for SSR
139
- */
140
- function getRawCSSText(options) {
141
- return getGlobalInjector().getRawCSSText(options);
142
- }
143
- /**
144
- * Inject keyframes and return object with toString() and dispose()
145
- */
146
- function keyframes(steps, nameOrOptions) {
147
- return getGlobalInjector().keyframes(steps, nameOrOptions);
148
- }
149
- /**
150
- * Define a CSS @property custom property.
151
- * This enables advanced features like animating custom properties.
152
- *
153
- * Note: @property rules are global and persistent once defined.
154
- * Re-registering the same property name is a no-op.
155
- *
156
- * @param name - The custom property name (must start with --)
157
- * @param options - Property configuration
158
- *
159
- * @example
160
- * ```ts
161
- * // Define a color property that can be animated
162
- * property('--my-color', {
163
- * syntax: '<color>',
164
- * initialValue: 'red',
165
- * });
166
- *
167
- * // Define an angle property
168
- * property('--rotation', {
169
- * syntax: '<angle>',
170
- * inherits: false,
171
- * initialValue: '0deg',
172
- * });
173
- * ```
174
- */
175
- function property(name, options) {
176
- return getGlobalInjector().property(name, options);
177
- }
178
- /**
179
- * Check if a CSS @property has already been defined
180
- *
181
- * @param name - The custom property name to check
182
- * @param options - Options including root
183
- */
184
- function isPropertyDefined(name, options) {
185
- return getGlobalInjector().isPropertyDefined(name, options);
186
- }
187
- /**
188
- * Inject a CSS @font-face rule.
189
- *
190
- * Permanent and global — no dispose or ref-counting.
191
- * Deduplicates by content hash (family + descriptors).
192
- */
193
- function fontFace(family, descriptors, options) {
194
- return getGlobalInjector().fontFace(family, descriptors, options);
195
- }
196
- /**
197
- * Inject a CSS @counter-style rule.
198
- *
199
- * Permanent and global — no dispose or ref-counting. Deduplicates by name and
200
- * overrides an existing rule by default. Pass `weak: true` for global
201
- * `configure()` definitions, which never clobber an existing rule.
202
- */
203
- function counterStyle(name, descriptors, options) {
204
- return getGlobalInjector().counterStyle(name, descriptors, options);
205
- }
206
- /**
207
- * Inject a CSS @function rule (custom function).
208
- *
209
- * Permanent and global — no dispose or ref-counting. Deduplicates by function
210
- * name and overrides an existing rule by default. Pass `weak: true` for global
211
- * `configure()` definitions, which never clobber an existing rule.
212
- *
213
- * @param name - The function name (`$$name`, `$name`, or `--name`)
214
- * @param definition - Function definition (args, returns, result, local vars)
215
- *
216
- * @example
217
- * ```ts
218
- * func('$$negative', { args: ['$value'], result: '(-1 * $value)' });
219
- * ```
220
- */
221
- function func(name, definition, options) {
222
- return getGlobalInjector().func(name, definition, options);
223
- }
224
- /**
225
- * Get CSS text from all sheets (for SSR)
226
- */
227
- function getCSSText(options) {
228
- return getGlobalInjector().getCSSText(options);
229
- }
230
- /**
231
- * Collect only CSS used by a rendered subtree (like jest-styled-components).
232
- * Pass the container returned by render(...).
233
- */
234
- function getCSSTextForNode(node, options) {
235
- const classRegex = tastyClassRegex(getNamePrefix());
236
- const classSet = /* @__PURE__ */ new Set();
237
- const readClasses = (el) => {
238
- const cls = el.getAttribute("class");
239
- if (!cls) return;
240
- for (const token of cls.split(/\s+/)) if (classRegex.test(token)) classSet.add(token);
241
- };
242
- if (node.getAttribute) readClasses(node);
243
- const elements = node.querySelectorAll ? node.querySelectorAll("[class]") : [];
244
- if (elements) elements.forEach(readClasses);
245
- return getGlobalInjector().getCSSTextForClasses(classSet, options);
246
- }
247
- /**
248
- * Force cleanup of unused rules
249
- */
250
- function cleanup(root) {
251
- return getGlobalInjector().cleanup(root);
252
- }
253
- /**
254
- * Record a render-time usage hit for one or more classNames.
255
- * Used internally by computeStyles and tasty() to track usage for GC.
256
- * When the global touch counter reaches `touchInterval`, schedules GC.
257
- */
258
- function touch(className, options) {
259
- if (!getConfig().gc) return;
260
- getGlobalInjector().touch(className, options);
261
- }
262
- /**
263
- * Synchronous garbage collection of unused styles.
264
- * Evicts the oldest unused styles when usageMap exceeds capacity.
265
- * With `{ force: true }`, removes ALL unused styles regardless of capacity.
266
- *
267
- * @returns Number of styles evicted.
268
- */
269
- function gc(options) {
270
- return getGlobalInjector().gc(options);
271
- }
272
- /**
273
- * Get the global injector instance for debugging
274
- */
275
- const injector = { get instance() {
276
- return getGlobalInjector();
277
- } };
278
- /**
279
- * Destroy all resources and clean up
280
- */
281
- function destroy(root) {
282
- return getGlobalInjector().destroy(root);
283
- }
284
- /**
285
- * Create a new isolated injector instance
286
- */
287
- function createInjector(config = {}) {
288
- return new StyleInjector({
289
- ...getConfig(),
290
- forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),
291
- ...config
292
- });
293
- }
294
- //#endregion
295
- //#region src/rsc-cache.ts
296
- /**
297
- * Shared RSC (React Server Components) inline style cache.
298
- *
299
- * Uses React.cache for per-request memoization in Server Components.
300
- * Both computeStyles() and standalone style functions (useGlobalStyles,
301
- * useRawCSS, useKeyframes, useProperty, useFontFace, useCounterStyle)
302
- * share this cache so that CSS accumulated by standalone functions is
303
- * flushed into inline <style> tags by the next tasty() component.
304
- */
305
- /**
306
- * Per-request RSC style cache using React.cache.
307
- * React.cache provides per-request memoization in Server Components,
308
- * so each request gets its own isolated cache.
309
- */
310
- const getRSCCache = cache(() => ({
311
- cacheKeyToClassName: /* @__PURE__ */ new Map(),
312
- emittedKeys: /* @__PURE__ */ new Set(),
313
- internalsEmitted: false,
314
- pendingCSS: [],
315
- keyToIndex: /* @__PURE__ */ new Map(),
316
- generatedNames: /* @__PURE__ */ new Map()
317
- }));
318
- function rscAllocateClassName(rscCache, cacheKey) {
319
- const existing = rscCache.cacheKeyToClassName.get(cacheKey);
320
- if (existing) return {
321
- className: existing,
322
- isNew: false
323
- };
324
- const className = makeClassName(getNamePrefix(), hashString(cacheKey));
325
- rscCache.cacheKeyToClassName.set(cacheKey, className);
326
- return {
327
- className,
328
- isNew: true
329
- };
330
- }
331
- /**
332
- * Flush any pending CSS accumulated by standalone functions.
333
- * Returns the CSS string and clears the buffer.
334
- */
335
- function flushPendingCSS(rscCache) {
336
- if (rscCache.pendingCSS.length === 0) return "";
337
- const css = rscCache.pendingCSS.join("\n");
338
- rscCache.pendingCSS.length = 0;
339
- rscCache.keyToIndex.clear();
340
- return css;
341
- }
342
- /**
343
- * Push CSS into the RSC pending buffer with dedup via emittedKeys.
344
- * Returns true if the CSS was added, false if it was already emitted.
345
- *
346
- * Pass `replace` for slot-keyed entries (an explicit `id`), where the last write
347
- * must win to match the client's update-tracking behavior. If the slot has
348
- * already been flushed into a `<style>` tag the new CSS is appended instead,
349
- * which still wins by cascade order.
350
- */
351
- function pushRSCCSS(rscCache, key, css, replace) {
352
- if (replace) {
353
- const pendingIndex = rscCache.keyToIndex.get(key);
354
- if (pendingIndex !== void 0) {
355
- rscCache.pendingCSS[pendingIndex] = css;
356
- return true;
357
- }
358
- } else if (rscCache.emittedKeys.has(key)) return false;
359
- rscCache.emittedKeys.add(key);
360
- rscCache.keyToIndex.set(key, rscCache.pendingCSS.length);
361
- rscCache.pendingCSS.push(css);
362
- return true;
363
- }
364
- /**
365
- * Determine the current style injection target.
366
- * Centralizes the three-way detection (SSR collector / RSC cache / client DOM)
367
- * used by all style functions.
368
- */
369
- function getStyleTarget() {
370
- const collector = getRegisteredSSRCollector();
371
- if (collector) return {
372
- mode: "ssr",
373
- collector
374
- };
375
- if (typeof document === "undefined") return {
376
- mode: "rsc",
377
- cache: getRSCCache()
378
- };
379
- return { mode: "client" };
380
- }
381
- //#endregion
382
- //#region src/ssr/collect-auto-properties.ts
383
- /**
384
- * Scan rendered rules for auto-inferable custom properties and emit
385
- * @property CSS via the provided callback.
386
- */
387
- function scanAndEmitAutoProperties(rules, styles, emit) {
388
- const registered = /* @__PURE__ */ new Set();
389
- if (styles) {
390
- const localProps = styles["@property"];
391
- if (localProps && typeof localProps === "object") for (const token of Object.keys(localProps)) {
392
- const parsed = parsePropertyToken(token);
393
- if (parsed.isValid) registered.add(parsed.cssName);
394
- }
395
- }
396
- const resolver = new PropertyTypeResolver();
397
- for (const rule of rules) {
398
- if (!rule.declarations) continue;
399
- resolver.scanDeclarations(rule.declarations, (name) => registered.has(name), (name, syntax, initialValue) => {
400
- registered.add(name);
401
- const css = formatPropertyCSS(name, {
402
- syntax,
403
- inherits: true,
404
- initialValue
405
- });
406
- if (css) emit(name, css);
407
- });
408
- }
409
- }
410
- /**
411
- * Scan rendered rules for custom property declarations and collect
412
- * auto-inferred @property rules via the SSR collector.
413
- *
414
- * @param rules - Rendered style rules containing CSS declarations
415
- * @param collector - SSR collector to emit @property CSS into
416
- * @param styles - Original styles object (used to skip explicit @property)
417
- */
418
- function collectAutoInferredProperties(rules, collector, styles) {
419
- scanAndEmitAutoProperties(rules, styles, (name, css) => {
420
- collector.collectProperty(`__auto:${name}`, css);
421
- });
422
- }
423
- /**
424
- * RSC variant: scan rendered rules and push auto-inferred @property CSS
425
- * into the RSC pending buffer.
426
- */
427
- function collectAutoInferredPropertiesRSC(rules, rscCache, styles) {
428
- scanAndEmitAutoProperties(rules, styles, (name, css) => {
429
- pushRSCCSS(rscCache, `__auto:${name}`, css);
430
- });
431
- }
432
- //#endregion
433
- //#region src/ssr/format-keyframes.ts
434
- /**
435
- * Convert keyframes steps to a CSS string.
436
- * Replicates SheetManager.stepsToCSS() without the class instance.
437
- */
438
- function stepsToCSS(steps) {
439
- const rules = [];
440
- for (const [key, value] of Object.entries(steps)) {
441
- if (typeof value === "string") {
442
- rules.push(`${key} { ${value.trim()} }`);
443
- continue;
444
- }
445
- const styleMap = value || {};
446
- const styleNames = Object.keys(styleMap).sort();
447
- const handlerQueue = [];
448
- const seenHandlers = /* @__PURE__ */ new Set();
449
- styleNames.forEach((styleName) => {
450
- let handlers = STYLE_HANDLER_MAP[styleName];
451
- if (!handlers) handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];
452
- handlers.forEach((handler) => {
453
- if (!seenHandlers.has(handler)) {
454
- seenHandlers.add(handler);
455
- handlerQueue.push(handler);
456
- }
457
- });
458
- });
459
- const declarationPairs = [];
460
- handlerQueue.forEach((handler) => {
461
- const result = handler(handler.__lookupStyles.reduce((acc, name) => {
462
- const v = styleMap[name];
463
- if (v !== void 0) acc[name] = v;
464
- return acc;
465
- }, {}));
466
- if (!result) return;
467
- (Array.isArray(result) ? result : [result]).forEach((cssMap) => {
468
- if (!cssMap || typeof cssMap !== "object") return;
469
- const { $: _$, ...props } = cssMap;
470
- Object.entries(props).forEach(([prop, val]) => {
471
- if (val == null || val === "") return;
472
- if (Array.isArray(val)) val.forEach((v) => {
473
- if (v != null && v !== "") declarationPairs.push({
474
- prop,
475
- value: String(v)
476
- });
477
- });
478
- else declarationPairs.push({
479
- prop,
480
- value: String(val)
481
- });
482
- });
483
- });
484
- });
485
- const declarations = declarationPairs.map((d) => `${d.prop}: ${d.value}`).join("; ");
486
- rules.push(`${key} { ${declarations.trim()} }`);
487
- }
488
- return rules.join(" ");
489
- }
490
- /**
491
- * Format a @keyframes rule as a CSS string.
492
- */
493
- function formatKeyframesCSS(name, steps) {
494
- return `@keyframes ${name} { ${stepsToCSS(steps)} }`;
495
- }
496
- //#endregion
497
- //#region src/utils/has-keys.ts
498
- /**
499
- * Check if an object has any own enumerable keys.
500
- * Avoids the array allocation of Object.keys(obj).length > 0.
501
- */
502
- function hasKeys(obj) {
503
- for (const _ in obj) return true;
504
- return false;
505
- }
506
- //#endregion
507
- //#region src/compute-styles.ts
508
- /**
509
- * Hook-free, synchronous style computation.
510
- *
511
- * Extracts the core logic from useStyles() into a plain function that can
512
- * be called during React render without any hooks. Three code paths:
513
- *
514
- * 1. SSR collector — styles collected via ServerStyleCollector
515
- * 2. Client inject — styles injected synchronously into the DOM
516
- * 3. RSC inline — styles returned as CSS strings for inline <style> emission
517
- *
518
- * This enables tasty() components to work as React Server Components.
519
- */
520
- const EMPTY_RESULT = { className: "" };
521
- /**
522
- * Mark internals as emitted for this RSC request.
523
- *
524
- * Internals (tokens, @property, @font-face, @counter-style) are emitted
525
- * exclusively by the SSR collector via ServerStyleCollector.collectInternals().
526
- * The SSR path is reliable because TastyRegistry is always present as a
527
- * client component in the root layout, guaranteeing SSR runs for every page.
528
- *
529
- * Previously this function also emitted internals and coordinated with SSR
530
- * via a globalThis flag, but that flag leaked across requests in the same
531
- * Node.js process, causing pages without RSC-rendered tasty components
532
- * (e.g. the playground route) to lose all token CSS.
533
- */
534
- function collectInternalsRSC(rscCache) {
535
- if (rscCache.internalsEmitted) return "";
536
- rscCache.internalsEmitted = true;
537
- return "";
538
- }
539
- /**
540
- * Collect per-component ancillary CSS (keyframes, @property, font-face,
541
- * counter-style) for RSC mode.
542
- */
543
- function collectAncillaryRSC(rscCache, styles) {
544
- const parts = [];
545
- const usedKf = getUsedKeyframes(styles);
546
- if (usedKf) for (const [name, steps] of Object.entries(usedKf)) {
547
- const key = `__kf:${name}:${JSON.stringify(steps)}`;
548
- if (!rscCache.emittedKeys.has(key)) {
549
- rscCache.emittedKeys.add(key);
550
- parts.push(formatKeyframesCSS(name, steps));
551
- }
552
- }
553
- if (hasLocalProperties(styles)) {
554
- const localProperties = extractLocalProperties(styles);
555
- if (localProperties) for (const [token, definition] of Object.entries(localProperties)) {
556
- const key = `__prop:${token}`;
557
- if (!rscCache.emittedKeys.has(key)) {
558
- rscCache.emittedKeys.add(key);
559
- const css = formatPropertyCSS(token, definition);
560
- if (css) parts.push(css);
561
- }
562
- }
563
- }
564
- if (hasLocalFontFace(styles)) {
565
- const localFontFace = extractLocalFontFace(styles);
566
- if (localFontFace) for (const [family, input] of Object.entries(localFontFace)) {
567
- const descriptors = Array.isArray(input) ? input : [input];
568
- for (const desc of descriptors) {
569
- const key = `__ff:${fontFaceContentHash(family, desc)}`;
570
- if (!rscCache.emittedKeys.has(key)) {
571
- rscCache.emittedKeys.add(key);
572
- parts.push(formatFontFaceRule(family, desc));
573
- }
574
- }
575
- }
576
- }
577
- if (hasLocalCounterStyle(styles)) {
578
- const localCounterStyle = extractLocalCounterStyle(styles);
579
- if (localCounterStyle) for (const [name, descriptors] of Object.entries(localCounterStyle)) {
580
- const key = `__cs:${name}:${JSON.stringify(descriptors)}`;
581
- if (!rscCache.emittedKeys.has(key)) {
582
- rscCache.emittedKeys.add(key);
583
- parts.push(formatCounterStyleRule(name, descriptors));
584
- }
585
- }
586
- }
587
- if (!isFunctionsPolyfillEnabled() && hasLocalFunctions(styles)) {
588
- const localFunctions = extractLocalFunctions(styles);
589
- if (localFunctions) for (const [name, definition] of Object.entries(localFunctions)) {
590
- const key = `__func:${parseFunctionName(name)}`;
591
- if (!rscCache.emittedKeys.has(key)) {
592
- rscCache.emittedKeys.add(key);
593
- parts.push(formatFunctionRule(name, definition));
594
- }
595
- }
596
- }
597
- return parts.join("\n");
598
- }
599
- /**
600
- * Process all chunks in RSC mode: render CSS to strings, allocate classNames,
601
- * and return combined { className, css }.
602
- */
603
- function computeStylesRSC(styles, chunkMap, stableStyles) {
604
- const rscCache = getRSCCache();
605
- const cssParts = [];
606
- const classNames = [];
607
- const pendingCSS = flushPendingCSS(rscCache);
608
- if (pendingCSS) cssParts.push(pendingCSS);
609
- const internalsCSS = collectInternalsRSC(rscCache);
610
- if (internalsCSS) cssParts.push(internalsCSS);
611
- for (const [chunkName, chunkStyleKeys] of chunkMap) {
612
- if (chunkStyleKeys.length === 0) continue;
613
- const { className, isNew } = rscAllocateClassName(rscCache, generateChunkCacheKey(styles, chunkName, chunkStyleKeys, stableStyles));
614
- classNames.push(className);
615
- if (isNew) {
616
- const renderResult = renderStylesForChunk(styles, chunkName, chunkStyleKeys);
617
- if (renderResult.rules.length > 0) {
618
- const css = formatRules(renderResult.rules, className);
619
- if (css) cssParts.push(css);
620
- }
621
- }
622
- }
623
- const ancillaryCSS = collectAncillaryRSC(rscCache, styles);
624
- if (ancillaryCSS) cssParts.push(ancillaryCSS);
625
- if (classNames.length === 0) return EMPTY_RESULT;
626
- const css = cssParts.join("\n");
627
- return {
628
- className: classNames.join(" "),
629
- css: css || void 0
630
- };
631
- }
632
- /**
633
- * Get keyframes that are actually used in styles.
634
- * Returns null if no keyframes are used (fast path for zero overhead).
635
- */
636
- function getUsedKeyframes(styles) {
637
- const hasLocal = hasLocalKeyframes(styles);
638
- const hasGlobal = hasGlobalKeyframes();
639
- if (!hasLocal && !hasGlobal) return null;
640
- const usedNames = extractAnimationNamesFromStyles(styles);
641
- if (usedNames.size === 0) return null;
642
- return filterUsedKeyframes(mergeKeyframes(hasLocal ? extractLocalKeyframes(styles) : null, hasGlobal ? getGlobalKeyframes() : null), usedNames);
643
- }
644
- /**
645
- * Process a chunk on the SSR path: allocate via collector, render, collect CSS.
646
- */
647
- function processChunkSSR(collector, styles, chunkName, styleKeys, stableStyles) {
648
- if (styleKeys.length === 0) return null;
649
- const cacheKey = generateChunkCacheKey(styles, chunkName, styleKeys, stableStyles);
650
- const { className, isNewAllocation } = collector.allocateClassName(cacheKey);
651
- if (isNewAllocation) {
652
- const renderResult = renderStylesForChunk(styles, chunkName, styleKeys);
653
- if (renderResult.rules.length > 0) {
654
- collector.collectChunk(cacheKey, className, renderResult.rules);
655
- return {
656
- name: chunkName,
657
- styleKeys,
658
- cacheKey,
659
- renderResult,
660
- className
661
- };
662
- }
663
- return null;
664
- }
665
- return {
666
- name: chunkName,
667
- styleKeys,
668
- cacheKey,
669
- renderResult: { rules: [] },
670
- className
671
- };
672
- }
673
- /**
674
- * Process a chunk on the client: render, allocate className, and inject
675
- * CSS synchronously. The injector's cache makes this idempotent.
676
- */
677
- function processChunkSync(styles, chunkName, styleKeys, stableStyles, root) {
678
- if (styleKeys.length === 0) return null;
679
- const cacheKey = generateChunkCacheKey(styles, chunkName, styleKeys, stableStyles);
680
- const renderResult = renderStylesForChunk(styles, chunkName, styleKeys, cacheKey);
681
- if (renderResult.rules.length === 0) return null;
682
- const { className } = inject(renderResult.rules, {
683
- cacheKey,
684
- root
685
- });
686
- return {
687
- name: chunkName,
688
- styleKeys,
689
- cacheKey,
690
- renderResult,
691
- className
692
- };
693
- }
694
- /**
695
- * Inject keyframes synchronously and return a name replacement map.
696
- * On the client, keyframes are injected into the DOM.
697
- */
698
- function injectKeyframesSync(usedKeyframes, root) {
699
- let nameMap = null;
700
- for (const [name, steps] of Object.entries(usedKeyframes)) {
701
- const injectedName = keyframes(steps, {
702
- name,
703
- root
704
- }).toString();
705
- if (injectedName !== name) {
706
- if (!nameMap) nameMap = /* @__PURE__ */ new Map();
707
- nameMap.set(name, injectedName);
708
- }
709
- }
710
- return nameMap;
711
- }
712
- /**
713
- * Inject chunk rules synchronously, replacing animation names if needed.
714
- */
715
- function injectChunkRulesSync(chunks, nameMap, root) {
716
- for (const chunk of chunks) if (chunk.renderResult.rules.length > 0) inject(nameMap ? chunk.renderResult.rules.map((rule) => ({
717
- ...rule,
718
- declarations: replaceAnimationNames(rule.declarations, nameMap)
719
- })) : chunk.renderResult.rules, {
720
- cacheKey: chunk.cacheKey,
721
- root
722
- });
723
- }
724
- /**
725
- * Inject all ancillary rules (properties, font-faces, counter-styles) synchronously.
726
- */
727
- function injectAncillarySync(styles, root) {
728
- if (hasLocalProperties(styles)) {
729
- const localProperties = extractLocalProperties(styles);
730
- if (localProperties) for (const [token, definition] of Object.entries(localProperties)) property(token, {
731
- ...definition,
732
- root
733
- });
734
- }
735
- if (hasLocalFontFace(styles)) {
736
- const localFontFace = extractLocalFontFace(styles);
737
- if (localFontFace) for (const [family, input] of Object.entries(localFontFace)) {
738
- const descriptors = Array.isArray(input) ? input : [input];
739
- for (const desc of descriptors) fontFace(family, desc, { root });
740
- }
741
- }
742
- if (hasLocalCounterStyle(styles)) {
743
- const localCounterStyle = extractLocalCounterStyle(styles);
744
- if (localCounterStyle) for (const [name, descriptors] of Object.entries(localCounterStyle)) counterStyle(name, descriptors, { root });
745
- }
746
- if (!isFunctionsPolyfillEnabled() && hasLocalFunctions(styles)) {
747
- const localFunctions = extractLocalFunctions(styles);
748
- if (localFunctions) for (const [name, definition] of Object.entries(localFunctions)) func(name, definition, { root });
749
- }
750
- }
751
- /**
752
- * Collect all ancillary rules into the SSR collector.
753
- */
754
- function collectAncillarySSR(collector, styles, chunks) {
755
- const usedKf = getUsedKeyframes(styles);
756
- if (usedKf) for (const [name, steps] of Object.entries(usedKf)) {
757
- const css = formatKeyframesCSS(name, steps);
758
- collector.collectKeyframes(name, css);
759
- }
760
- if (hasLocalProperties(styles)) {
761
- const localProperties = extractLocalProperties(styles);
762
- if (localProperties) for (const [token, definition] of Object.entries(localProperties)) {
763
- const css = formatPropertyCSS(token, definition);
764
- if (css) collector.collectProperty(token, css);
765
- }
766
- }
767
- if (hasLocalFontFace(styles)) {
768
- const localFontFace = extractLocalFontFace(styles);
769
- if (localFontFace) for (const [family, input] of Object.entries(localFontFace)) {
770
- const descriptors = Array.isArray(input) ? input : [input];
771
- for (const desc of descriptors) {
772
- const hash = fontFaceContentHash(family, desc);
773
- const css = formatFontFaceRule(family, desc);
774
- collector.collectFontFace(hash, css);
775
- }
776
- }
777
- }
778
- if (hasLocalCounterStyle(styles)) {
779
- const localCounterStyle = extractLocalCounterStyle(styles);
780
- if (localCounterStyle) for (const [name, descriptors] of Object.entries(localCounterStyle)) {
781
- const css = formatCounterStyleRule(name, descriptors);
782
- collector.collectCounterStyle(name, css);
783
- }
784
- }
785
- if (!isFunctionsPolyfillEnabled() && hasLocalFunctions(styles)) {
786
- const localFunctions = extractLocalFunctions(styles);
787
- if (localFunctions) for (const [name, definition] of Object.entries(localFunctions)) {
788
- const css = formatFunctionRule(name, definition);
789
- collector.collectFunction(parseFunctionName(name), css);
790
- }
791
- }
792
- if (getConfig().autoPropertyTypes !== false) {
793
- const allRules = chunks.flatMap((c) => c.renderResult.rules);
794
- if (allRules.length > 0) collectAutoInferredProperties(allRules, collector, styles);
795
- }
796
- }
797
- /**
798
- * Synchronous, hook-free style computation.
799
- *
800
- * Resolves recipes, categorizes style keys into chunks, renders CSS rules,
801
- * allocates class names, and injects / collects / returns the CSS.
802
- *
803
- * Three code paths:
804
- * 1. SSR collector — discovered via ALS or passed explicitly; CSS collected
805
- * 2. RSC inline — no collector and no `document`; CSS returned as `result.css`
806
- * for the caller to emit as an inline `<style>` tag
807
- * 3. Client inject — CSS injected synchronously into the DOM (idempotent)
808
- *
809
- * @param styles - Tasty styles object (or undefined for no styles)
810
- * @param options - Optional SSR collector override
811
- */
812
- function computeStyles(styles, options) {
813
- if (!styles || !hasKeys(styles)) return EMPTY_RESULT;
814
- const resolved = resolveRecipes(styles);
815
- const stableStyles = options?.stableStyles === true && resolved === styles;
816
- if (isFunctionsPolyfillEnabled() && hasLocalFunctions(resolved)) registerLocalFunctionPolyfills(resolved);
817
- const chunkMap = categorizeStyleKeys(resolved);
818
- const collector = options?.ssrCollector !== void 0 ? options.ssrCollector : getRegisteredSSRCollector();
819
- const chunks = [];
820
- if (collector) {
821
- collector.collectInternals();
822
- for (const [chunkName, chunkStyleKeys] of chunkMap) {
823
- const chunk = processChunkSSR(collector, resolved, chunkName, chunkStyleKeys, stableStyles);
824
- if (chunk) chunks.push(chunk);
825
- }
826
- collectAncillarySSR(collector, resolved, chunks);
827
- } else if (typeof document === "undefined") return computeStylesRSC(resolved, chunkMap, stableStyles);
828
- else {
829
- const root = options?.root;
830
- injectAncillarySync(resolved, root);
831
- const usedKf = getUsedKeyframes(resolved);
832
- const nameMap = usedKf ? injectKeyframesSync(usedKf, root) : null;
833
- for (const [chunkName, chunkStyleKeys] of chunkMap) {
834
- const chunk = processChunkSync(resolved, chunkName, chunkStyleKeys, stableStyles, root);
835
- if (chunk) chunks.push(chunk);
836
- }
837
- if (nameMap) injectChunkRulesSync(chunks, nameMap, root);
838
- for (const chunk of chunks) touch(chunk.className, { root });
839
- }
840
- if (chunks.length === 0) return EMPTY_RESULT;
841
- if (chunks.length === 1) return { className: chunks[0].className };
842
- return { className: chunks.map((c) => c.className).join(" ") };
843
- }
844
- //#endregion
845
- //#region src/utils/filter-base-props.ts
846
- const DOMPropNames = new Set(["id"]);
847
- const BasePropNames = new Set([
848
- "role",
849
- "as",
850
- "element",
851
- "css",
852
- "qa",
853
- "mods",
854
- "qaVal",
855
- "hidden",
856
- "isHidden",
857
- "disabled",
858
- "isDisabled",
859
- "children",
860
- "style",
861
- "className",
862
- "href",
863
- "target",
864
- "tabIndex"
865
- ]);
866
- const ignoreEventPropsNames = new Set([
867
- "onPress",
868
- "onHoverStart",
869
- "onHoverEnd",
870
- "onPressStart",
871
- "onPressEnd"
872
- ]);
873
- const propRe = /^((data-).*)$/;
874
- const eventRe = /^on[A-Z].+$/;
875
- /**
876
- * Filters out all props that aren't valid DOM props or defined via override prop obj.
877
- * @param props - The component props to be filtered.
878
- * @param opts - Props to override.
879
- */
880
- function filterBaseProps(props, opts = {}) {
881
- const { propNames, eventProps } = opts;
882
- const filteredProps = {};
883
- for (const prop in props) if (Object.prototype.hasOwnProperty.call(props, prop) && (DOMPropNames.has(prop) || BasePropNames.has(prop) || prop.startsWith("aria-") || eventProps && eventRe.test(prop) && !ignoreEventPropsNames.has(prop) || propNames?.has(prop) || propRe.test(prop))) filteredProps[prop] = props[prop];
884
- return filteredProps;
885
- }
886
- //#endregion
887
- //#region src/utils/colors.ts
888
- function color(name, opacity = 1) {
889
- if (opacity !== 1) return overrideColorAlpha(`var(--${name}-color)`, String(opacity));
890
- return `var(--${name}-color)`;
891
- }
892
- //#endregion
893
- //#region src/utils/cache-wrapper.ts
894
- /**
895
- * Create a function that caches the result with LRU eviction.
896
- */
897
- function cacheWrapper(handler, limit = 1e3) {
898
- const cache = new Lru(limit);
899
- return (firstArg, secondArg) => {
900
- const key = typeof firstArg === "string" && secondArg == null ? firstArg : JSON.stringify([firstArg, secondArg]);
901
- let result = cache.get(key);
902
- if (result === void 0) {
903
- result = secondArg == null ? handler(firstArg) : handler(firstArg, secondArg);
904
- cache.set(key, result);
905
- }
906
- return result;
907
- };
908
- }
909
- //#endregion
910
- //#region src/utils/mod-attrs.ts
911
- function modAttrs(map) {
912
- return map ? Object.keys(map).reduce((attrs, key) => {
913
- const value = map[key];
914
- if (value == null || value === false) return attrs;
915
- const attrName = `data-${camelToKebab(key)}`;
916
- if (value === true) attrs[attrName] = "";
917
- else if (typeof value === "string") attrs[attrName] = value;
918
- else if (typeof value === "number") attrs[attrName] = String(value);
919
- else console.warn(`[Tasty] Invalid mod value for "${key}". Expected boolean, string, or number, got ${typeof value}`);
920
- return attrs;
921
- }, {}) : null;
922
- }
923
- const _modAttrs = cacheWrapper(modAttrs);
924
- //#endregion
925
- //#region src/utils/dotize.ts
926
- const dotize = {
927
- valTypes: {
928
- none: "NONE",
929
- primitive: "PRIM",
930
- object: "OBJECT",
931
- array: "ARRAY"
932
- },
933
- getValType: function(val) {
934
- if (!val || typeof val != "object" || Array.isArray(val)) return dotize.valTypes.primitive;
935
- if (typeof val == "object") return dotize.valTypes.object;
936
- },
937
- getPathType: function(arrPath) {
938
- const arrPathTypes = [];
939
- for (const path in arrPath) {
940
- const pathVal = arrPath[path];
941
- if (!pathVal) arrPathTypes.push(dotize.valTypes.none);
942
- else if (dotize.isNumber(pathVal)) arrPathTypes.push(dotize.valTypes.array);
943
- else arrPathTypes.push(dotize.valTypes.object);
944
- }
945
- return arrPathTypes;
946
- },
947
- isUndefined: function(obj) {
948
- return typeof obj == "undefined";
949
- },
950
- isNumber: function(f) {
951
- return !isNaN(parseInt(f));
952
- },
953
- isEmptyObj: function(obj) {
954
- for (const prop in obj) if (Object.hasOwnProperty.call(obj, prop)) return false;
955
- return JSON.stringify(obj) === JSON.stringify({});
956
- },
957
- isPlainObject: function(obj) {
958
- if (typeof obj !== "object" || obj === null) return false;
959
- return Object.getPrototypeOf(obj) === Object.prototype;
960
- },
961
- isNotObject: function(obj) {
962
- return !obj || !this.isPlainObject(obj);
963
- },
964
- isEmptyArray: function(arr) {
965
- return Array.isArray(arr) && arr.length == 0;
966
- },
967
- isNotArray: function(arr) {
968
- return Array.isArray(arr) == false;
969
- },
970
- removeEmptyArrayItem: function(arr) {
971
- return arr.filter(function(el) {
972
- return el != null && el != "";
973
- });
974
- },
975
- getFieldName: function(field, prefix, isRoot, isArrayItem, isArray) {
976
- if (isArray) return (prefix ? prefix : "") + (dotize.isNumber(field) ? "[" + field + "]" : (isRoot && !prefix ? "" : ".") + field);
977
- else if (isArrayItem) return (prefix ? prefix : "") + "[" + field + "]";
978
- else return (prefix ? prefix + "." : "") + field;
979
- },
980
- startsWith: function(val, valToSearch) {
981
- return val.indexOf(valToSearch) == 0;
982
- },
983
- convert: function(obj, prefix = "") {
984
- let newObj = {};
985
- if (dotize.isNotObject(obj)) if (prefix) {
986
- newObj[prefix] = obj;
987
- return newObj;
988
- } else return obj;
989
- return (function recurse(o, p, isRoot) {
990
- const isArrayItem = Array.isArray(o);
991
- for (const f in o) {
992
- const currentProp = o[f];
993
- if (currentProp && typeof currentProp === "object" && !Array.isArray(currentProp) && dotize.isPlainObject(currentProp)) {
994
- if (isArrayItem && dotize.isEmptyObj(currentProp) == false) newObj = recurse(currentProp, dotize.getFieldName(f, p, isRoot, true));
995
- else if (dotize.isEmptyObj(currentProp) == false) newObj = recurse(currentProp, dotize.getFieldName(f, p, isRoot));
996
- else if (dotize.isEmptyObj(currentProp)) newObj[dotize.getFieldName(f, p, isRoot, isArrayItem)] = currentProp;
997
- } else if (isArrayItem || dotize.isNumber(f)) newObj[dotize.getFieldName(f, p, isRoot, true)] = currentProp;
998
- else newObj[dotize.getFieldName(f, p, isRoot)] = currentProp;
999
- }
1000
- return newObj;
1001
- })(obj, prefix, true);
1002
- },
1003
- backward: function(obj, prefix) {
1004
- let newObj = {};
1005
- const arStartRegex = /\[(\d+)\]/g;
1006
- if (dotize.isNotObject(obj) && dotize.isNotArray(obj)) if (prefix) return obj[prefix];
1007
- else return obj;
1008
- for (let tProp in obj) {
1009
- const tPropVal = obj[tProp];
1010
- if (prefix) {
1011
- const prefixRegex = new RegExp("^" + prefix);
1012
- tProp = tProp.replace(prefixRegex, "");
1013
- }
1014
- tProp = tProp.replace(arStartRegex, ".$1");
1015
- if (dotize.startsWith(tProp, ".")) tProp = tProp.replace(/^\./, "");
1016
- const arrPath = tProp.split(".");
1017
- const arrPathTypes = dotize.getPathType(arrPath);
1018
- if (!dotize.isUndefined(arrPathTypes) && arrPathTypes[0] == dotize.valTypes.array && Array.isArray(newObj) == false) newObj = [];
1019
- (function recurse(rPropVal, rObj, rPropValPrev, rObjPrev) {
1020
- let currentPath = arrPath.shift();
1021
- const currentPathType = arrPathTypes.shift();
1022
- if (typeof currentPath == "undefined" || currentPath == "") {
1023
- newObj = rPropVal;
1024
- return;
1025
- }
1026
- const isArray = currentPathType == dotize.valTypes.array;
1027
- if (dotize.isNumber(currentPath)) currentPath = parseInt(currentPath);
1028
- if (arrPath.length > 0) {
1029
- if (typeof rObj[currentPath] == "undefined") if (isArray) rObj[currentPath] = [];
1030
- else rObj[currentPath] = {};
1031
- recurse(rPropVal, rObj[currentPath], currentPath, rObj);
1032
- return;
1033
- }
1034
- if (currentPathType == dotize.valTypes.array && rPropValPrev && rObjPrev) {
1035
- if (Array.isArray(rObjPrev[rPropValPrev]) == false) rObjPrev[rPropValPrev] = [];
1036
- rObjPrev[rPropValPrev].push(rPropVal);
1037
- } else rObj[currentPath] = rPropVal;
1038
- })(tPropVal, newObj);
1039
- }
1040
- return newObj;
1041
- }
1042
- };
1043
- //#endregion
1044
- //#region src/utils/process-tokens.ts
1045
- /**
1046
- * Check if a value is a valid token value (string, number, or boolean - not object).
1047
- * Returns false for `false` values (they mean "skip this token").
1048
- */
1049
- function isValidTokenValue(value) {
1050
- if (value === void 0 || value === null || value === false) return false;
1051
- if (typeof value === "object") {
1052
- console.warn("[Tasty] Object values are not allowed in tokens prop. Tokens do not support state-based styling. Use a primitive value instead.");
1053
- return false;
1054
- }
1055
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1056
- }
1057
- /**
1058
- * Process a single token value through the tasty parser.
1059
- * Numbers are converted to strings; 0 stays as "0".
1060
- */
1061
- function processTokenValue(value) {
1062
- if (typeof value === "number") {
1063
- if (value === 0) return "0";
1064
- return parseStyle(String(value)).output;
1065
- }
1066
- return parseStyle(value).output;
1067
- }
1068
- /**
1069
- * Resolve one `$name` / `#name` entry to the custom property it declares and
1070
- * the value to declare, or `null` when the entry declares nothing.
1071
- *
1072
- * The two sigils differ only in the property name they build and in how `true`
1073
- * is read: for a custom property it is the empty value, for a color it is
1074
- * `transparent`.
1075
- */
1076
- function resolveTokenEntry(key, value) {
1077
- const name = `--${normalizeDslName(key.slice(1))}`;
1078
- if (key[0] === "$") return [name, processTokenValue(value === true ? "" : value)];
1079
- const colorValue = normalizeColorTokenValue(value);
1080
- if (colorValue === null) return null;
1081
- return [`${name}-color`, processTokenValue(colorValue)];
1082
- }
1083
- /**
1084
- * Process tokens object into inline style properties.
1085
- * - `$name` -> `--name` with the parsed value
1086
- * - `#name` -> `--name-color` with the parsed value
1087
- *
1088
- * @param tokens - The tokens object to process
1089
- * @returns CSSProperties object or undefined if no tokens to process
1090
- */
1091
- function processTokens(tokens) {
1092
- if (!tokens) return;
1093
- const keys = Object.keys(tokens);
1094
- if (keys.length === 0) return;
1095
- let result;
1096
- for (const key of keys) {
1097
- const value = tokens[key];
1098
- if (!isValidTokenValue(value)) continue;
1099
- if (key[0] !== "$" && key[0] !== "#") continue;
1100
- const entry = resolveTokenEntry(key, value);
1101
- if (!entry) continue;
1102
- if (!result) result = {};
1103
- result[entry[0]] = entry[1];
1104
- }
1105
- return result;
1106
- }
1107
- //#endregion
1108
- //#region src/debug.ts
1109
- function fmtSize(bytes) {
1110
- return bytes > 1024 ? `${(bytes / 1024).toFixed(1)}KB` : `${bytes}B`;
1111
- }
1112
- function countRules(css) {
1113
- return (css.match(/\{[^}]*\}/g) || []).length;
1114
- }
1115
- function sortTastyClasses(classes) {
1116
- return Array.from(classes).sort((a, b) => a.localeCompare(b));
1117
- }
1118
- function getRegistry(root = document) {
1119
- return injector.instance._sheetManager?.getRegistry(root);
1120
- }
1121
- function getUnusedClasses(root = document) {
1122
- const registry = getRegistry(root);
1123
- if (!registry) return [];
1124
- const result = [];
1125
- for (const [cls, rc] of registry.refCounts) if (rc === 0) result.push(cls);
1126
- return sortTastyClasses(result);
1127
- }
1128
- function findDomTastyClasses(root = document) {
1129
- const classes = /* @__PURE__ */ new Set();
1130
- const elements = root.querySelectorAll?.("[class]") || [];
1131
- const classRegex = tastyClassRegex(getNamePrefix());
1132
- elements.forEach((el) => {
1133
- const attr = el.getAttribute("class");
1134
- if (attr) {
1135
- for (const cls of attr.split(/\s+/)) if (classRegex.test(cls)) classes.add(cls);
1136
- }
1137
- });
1138
- return sortTastyClasses(classes);
1139
- }
1140
- function prettifyCSS(css) {
1141
- if (!css || !css.trim()) return "";
1142
- const out = [];
1143
- let depth = 0;
1144
- const indent = () => " ".repeat(depth);
1145
- let normalized = css.replace(/\s+/g, " ").trim();
1146
- normalized = normalized.replace(/\s*\{\s*/g, " { ");
1147
- normalized = normalized.replace(/\s*\}\s*/g, " } ");
1148
- normalized = normalized.replace(/;\s*/g, "; ");
1149
- const tokens = normalized.split(/\s+/);
1150
- let buf = "";
1151
- for (const t of tokens) if (t === "{") {
1152
- const header = buf.trim();
1153
- if (header) {
1154
- const parts = splitOutsideParens(header, ",");
1155
- if (parts.length > 1) out.push(parts.map((p, idx) => idx === 0 ? `${indent()}${p.trim()},` : `${indent()}${p.trim()}${idx < parts.length - 1 ? "," : ""}`).join("\n") + " {");
1156
- else out.push(`${indent()}${header} {`);
1157
- } else out.push(`${indent()}{`);
1158
- depth++;
1159
- buf = "";
1160
- } else if (t === "}") {
1161
- if (buf.trim()) {
1162
- for (const decl of buf.split(";").filter((s) => s.trim())) out.push(`${indent()}${decl.trim()};`);
1163
- buf = "";
1164
- }
1165
- depth = Math.max(0, depth - 1);
1166
- out.push(`${indent()}}`);
1167
- } else if (t.endsWith(";")) {
1168
- buf += ` ${t}`;
1169
- const full = buf.trim();
1170
- if (full) out.push(`${indent()}${full}`);
1171
- buf = "";
1172
- } else buf += ` ${t}`;
1173
- if (buf.trim()) out.push(buf.trim());
1174
- return out.filter((l) => l.trim()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
1175
- }
1176
- /** Split `str` by `sep` only when not inside parentheses */
1177
- function splitOutsideParens(str, sep) {
1178
- const parts = [];
1179
- let depth = 0;
1180
- let start = 0;
1181
- for (let i = 0; i < str.length; i++) {
1182
- const ch = str[i];
1183
- if (ch === "(") depth++;
1184
- else if (ch === ")") depth--;
1185
- else if (depth === 0 && str.startsWith(sep, i)) {
1186
- parts.push(str.slice(start, i));
1187
- start = i + sep.length;
1188
- }
1189
- }
1190
- parts.push(str.slice(start));
1191
- return parts;
1192
- }
1193
- function extractChunkName(cacheKey) {
1194
- for (const part of cacheKey.split("\0")) {
1195
- if (part.startsWith("[states:")) continue;
1196
- if (!part.includes(":") && part.length > 0) return part;
1197
- }
1198
- return null;
1199
- }
1200
- function getChunkForClass(className, root = document) {
1201
- const registry = getRegistry(root);
1202
- if (!registry) return null;
1203
- for (const [key, cn] of registry.cacheKeyToClassName) if (cn === className) return extractChunkName(key);
1204
- return null;
1205
- }
1206
- function buildChunkBreakdown(root = document) {
1207
- const registry = getRegistry(root);
1208
- if (!registry) return {
1209
- byChunk: {},
1210
- totalChunkTypes: 0,
1211
- totalClasses: 0
1212
- };
1213
- const byChunk = {};
1214
- for (const [cacheKey, className] of registry.cacheKeyToClassName) {
1215
- const chunk = extractChunkName(cacheKey) || "unknown";
1216
- if (!byChunk[chunk]) byChunk[chunk] = {
1217
- classes: [],
1218
- cssSize: 0,
1219
- ruleCount: 0
1220
- };
1221
- byChunk[chunk].classes.push(className);
1222
- const css = injector.instance.getCSSTextForClasses([className], { root });
1223
- byChunk[chunk].cssSize += css.length;
1224
- byChunk[chunk].ruleCount += countRules(css);
1225
- }
1226
- for (const entry of Object.values(byChunk)) entry.classes = sortTastyClasses(entry.classes);
1227
- const totalClasses = Object.values(byChunk).reduce((s, e) => s + e.classes.length, 0);
1228
- return {
1229
- byChunk,
1230
- totalChunkTypes: Object.keys(byChunk).length,
1231
- totalClasses
1232
- };
1233
- }
1234
- function getGlobalTypeCSS(type, root = document) {
1235
- const registry = getRegistry(root);
1236
- if (!registry) return {
1237
- css: "",
1238
- ruleCount: 0,
1239
- size: 0
1240
- };
1241
- const chunks = [];
1242
- let rc = 0;
1243
- if (type === "keyframes") for (const [, entry] of registry.keyframesCache) {
1244
- const info = entry.info;
1245
- const sheetInfo = registry.sheets[info.sheetIndex];
1246
- const sm = injector.instance._sheetManager;
1247
- const ss = sheetInfo && sm ? sm.getCSSSheet(sheetInfo) : null;
1248
- if (ss && info.ruleIndex < ss.cssRules.length) {
1249
- const rule = ss.cssRules[info.ruleIndex];
1250
- if (rule) {
1251
- chunks.push(rule.cssText);
1252
- rc++;
1253
- }
1254
- } else if (info.cssText) {
1255
- chunks.push(info.cssText);
1256
- rc++;
1257
- }
1258
- }
1259
- else {
1260
- const prefix = type === "global" ? "global:" : type === "raw" ? "raw:" : "property:";
1261
- for (const [key, ri] of registry.globalRules) {
1262
- if (!key.startsWith(prefix)) continue;
1263
- const sheetInfo = registry.sheets[ri.sheetIndex];
1264
- const sm = injector.instance._sheetManager;
1265
- const ss = sheetInfo && sm ? sm.getCSSSheet(sheetInfo) : null;
1266
- if (ss) {
1267
- const start = Math.max(0, ri.ruleIndex);
1268
- const end = Math.min(ss.cssRules.length - 1, ri.endRuleIndex ?? ri.ruleIndex);
1269
- if (start >= 0 && end >= start && start < ss.cssRules.length) for (let i = start; i <= end; i++) {
1270
- const rule = ss.cssRules[i];
1271
- if (rule) {
1272
- chunks.push(rule.cssText);
1273
- rc++;
1274
- }
1275
- }
1276
- } else if (ri.cssText?.length) {
1277
- chunks.push(...ri.cssText);
1278
- rc += ri.cssText.length;
1279
- }
1280
- }
1281
- }
1282
- const raw = chunks.join("\n");
1283
- return {
1284
- css: prettifyCSS(raw),
1285
- ruleCount: rc,
1286
- size: raw.length
1287
- };
1288
- }
1289
- function getSourceCssForClasses(classNames, root = document) {
1290
- const registry = getRegistry(root);
1291
- if (!registry) return null;
1292
- const chunks = [];
1293
- let found = false;
1294
- for (const cls of classNames) {
1295
- const info = registry.rules.get(cls);
1296
- if (info?.cssText?.length) {
1297
- chunks.push(...info.cssText);
1298
- found = true;
1299
- }
1300
- }
1301
- return found ? chunks.join("\n") : null;
1302
- }
1303
- function getDefs(root = document) {
1304
- const registry = getRegistry(root);
1305
- let properties = [];
1306
- if (registry?.injectedProperties) properties = Array.from(registry.injectedProperties.keys()).sort();
1307
- const keyframes = [];
1308
- if (registry) {
1309
- for (const entry of registry.keyframesCache.values()) keyframes.push({
1310
- name: entry.name,
1311
- refCount: entry.refCount
1312
- });
1313
- keyframes.sort((a, b) => a.name.localeCompare(b.name));
1314
- }
1315
- return {
1316
- properties,
1317
- keyframes
1318
- };
1319
- }
1320
- const CHUNK_ORDER = [
1321
- CHUNK_NAMES.COMBINED,
1322
- CHUNK_NAMES.APPEARANCE,
1323
- CHUNK_NAMES.FONT,
1324
- CHUNK_NAMES.DIMENSION,
1325
- CHUNK_NAMES.DISPLAY,
1326
- CHUNK_NAMES.LAYOUT,
1327
- CHUNK_NAMES.POSITION,
1328
- CHUNK_NAMES.MISC,
1329
- CHUNK_NAMES.SUBCOMPONENTS
1330
- ];
1331
- const tastyDebug = {
1332
- css(target, opts) {
1333
- const { root = document, prettify = true, raw = false, source = false } = opts || {};
1334
- let css = "";
1335
- const classRegex = tastyClassRegex(getNamePrefix());
1336
- if (source && typeof target === "string" && classRegex.test(target)) {
1337
- const src = getSourceCssForClasses([target], root);
1338
- if (src) css = src;
1339
- else {
1340
- if (!raw) console.warn("[Tasty] source CSS not available (requires dev mode or TASTY_DEBUG=true). Falling back to live CSSOM.");
1341
- css = injector.instance.getCSSTextForClasses([target], { root });
1342
- }
1343
- } else if (source && Array.isArray(target)) {
1344
- const src = getSourceCssForClasses(target, root);
1345
- if (src) css = src;
1346
- else {
1347
- if (!raw) console.warn("[Tasty] source CSS not available. Falling back to live CSSOM.");
1348
- css = injector.instance.getCSSTextForClasses(target, { root });
1349
- }
1350
- } else if (typeof target === "string") if (target === "all") css = injector.instance.getCSSText({ root });
1351
- else if (target === "global") {
1352
- css = getGlobalTypeCSS("global", root).css;
1353
- return css;
1354
- } else if (target === "active") {
1355
- const active = findDomTastyClasses(root);
1356
- css = injector.instance.getCSSTextForClasses(active, { root });
1357
- } else if (target === "unused") {
1358
- const unused = getUnusedClasses(root);
1359
- css = injector.instance.getCSSTextForClasses(unused, { root });
1360
- } else if (target === "page") css = getPageCSS(root);
1361
- else if (classRegex.test(target)) css = injector.instance.getCSSTextForClasses([target], { root });
1362
- else {
1363
- const el = root.querySelector?.(target);
1364
- if (el) css = getCSSTextForNode(el, { root });
1365
- }
1366
- else if (Array.isArray(target)) css = injector.instance.getCSSTextForClasses(target, { root });
1367
- else if (target instanceof Element) css = getCSSTextForNode(target, { root });
1368
- const result = prettify ? prettifyCSS(css) : css;
1369
- if (!raw) {
1370
- const label = Array.isArray(target) ? `[${target.join(", ")}]` : target;
1371
- const rc = countRules(css);
1372
- console.group(`CSS for ${label} (${rc} rules, ${fmtSize(css.length)})`);
1373
- console.log(result || "(empty)");
1374
- console.groupEnd();
1375
- }
1376
- return result;
1377
- },
1378
- inspect(target, opts) {
1379
- const { root = document, raw = false } = opts || {};
1380
- const element = typeof target === "string" ? root.querySelector?.(target) : target;
1381
- if (!element) {
1382
- const empty = {
1383
- element: null,
1384
- classes: [],
1385
- chunks: [],
1386
- css: "",
1387
- size: 0,
1388
- rules: 0
1389
- };
1390
- if (!raw) console.warn("[Tasty] debug.inspect: element not found");
1391
- return empty;
1392
- }
1393
- const classList = element.getAttribute("class") || "";
1394
- const classRegex = tastyClassRegex(getNamePrefix());
1395
- const tastyClasses = classList.split(/\s+/).filter((cls) => classRegex.test(cls));
1396
- const chunks = tastyClasses.map((className) => ({
1397
- className,
1398
- chunkName: getChunkForClass(className, root)
1399
- }));
1400
- const css = getCSSTextForNode(element, { root });
1401
- const rules = countRules(css);
1402
- const result = {
1403
- element,
1404
- classes: tastyClasses,
1405
- chunks,
1406
- css: prettifyCSS(css),
1407
- size: css.length,
1408
- rules
1409
- };
1410
- if (!raw) {
1411
- const tag = element.tagName.toLowerCase();
1412
- const id = element.id ? `#${element.id}` : "";
1413
- console.group(`inspect ${tag}${id} — ${tastyClasses.length} classes, ${rules} rules, ${fmtSize(css.length)}`);
1414
- if (chunks.length) console.log("Chunks:", chunks.map((c) => `${c.className}→${c.chunkName || "?"}`).join(", "));
1415
- console.groupCollapsed("CSS");
1416
- console.log(result.css || "(empty)");
1417
- console.groupEnd();
1418
- console.groupEnd();
1419
- }
1420
- return result;
1421
- },
1422
- summary(opts) {
1423
- const { root = document, raw = false } = opts || {};
1424
- const activeClasses = findDomTastyClasses(root);
1425
- const unusedClasses = getUnusedClasses(root);
1426
- const totalStyledClasses = [...activeClasses, ...unusedClasses];
1427
- const activeCSS = injector.instance.getCSSTextForClasses(activeClasses, { root });
1428
- const unusedCSS = injector.instance.getCSSTextForClasses(unusedClasses, { root });
1429
- const allCSS = injector.instance.getCSSText({ root });
1430
- const activeRuleCount = countRules(activeCSS);
1431
- const unusedRuleCount = countRules(unusedCSS);
1432
- const globalData = getGlobalTypeCSS("global", root);
1433
- const rawData = getGlobalTypeCSS("raw", root);
1434
- const kfData = getGlobalTypeCSS("keyframes", root);
1435
- const propData = getGlobalTypeCSS("property", root);
1436
- const totalRuleCount = activeRuleCount + unusedRuleCount + globalData.ruleCount + rawData.ruleCount + kfData.ruleCount + propData.ruleCount;
1437
- const metrics = injector.instance.getMetrics({ root });
1438
- const defs = getDefs(root);
1439
- const chunkBreakdown = buildChunkBreakdown(root);
1440
- const summary = {
1441
- activeClasses,
1442
- unusedClasses,
1443
- totalStyledClasses,
1444
- activeCSSSize: activeCSS.length,
1445
- unusedCSSSize: unusedCSS.length,
1446
- globalCSSSize: globalData.size,
1447
- rawCSSSize: rawData.size,
1448
- keyframesCSSSize: kfData.size,
1449
- propertyCSSSize: propData.size,
1450
- totalCSSSize: allCSS.length,
1451
- activeRuleCount,
1452
- unusedRuleCount,
1453
- globalRuleCount: globalData.ruleCount,
1454
- rawRuleCount: rawData.ruleCount,
1455
- keyframesRuleCount: kfData.ruleCount,
1456
- propertyRuleCount: propData.ruleCount,
1457
- totalRuleCount,
1458
- metrics,
1459
- definedProperties: defs.properties,
1460
- definedKeyframes: defs.keyframes,
1461
- chunkBreakdown
1462
- };
1463
- if (!raw) {
1464
- console.group("Tasty Summary");
1465
- console.log(`Active: ${activeClasses.length} classes, ${activeRuleCount} rules, ${fmtSize(activeCSS.length)}`);
1466
- console.log(`Unused: ${unusedClasses.length} classes, ${unusedRuleCount} rules, ${fmtSize(unusedCSS.length)}`);
1467
- console.log(`Global: ${globalData.ruleCount} rules, ${fmtSize(globalData.size)}`);
1468
- if (rawData.ruleCount) console.log(`Raw: ${rawData.ruleCount} rules, ${fmtSize(rawData.size)}`);
1469
- if (kfData.ruleCount) console.log(`Keyframes: ${kfData.ruleCount} rules, ${fmtSize(kfData.size)}`);
1470
- if (propData.ruleCount) console.log(`@property: ${propData.ruleCount} rules, ${fmtSize(propData.size)}`);
1471
- console.log(`Total: ${totalStyledClasses.length} classes, ${totalRuleCount} rules, ${fmtSize(allCSS.length)}`);
1472
- if (metrics) {
1473
- const total = metrics.hits + metrics.misses;
1474
- const rate = total > 0 ? (metrics.hits / total * 100).toFixed(1) : 0;
1475
- console.log(`Cache: ${rate}% hit rate (${total} lookups)`);
1476
- }
1477
- if (chunkBreakdown.totalChunkTypes > 0) {
1478
- console.groupCollapsed(`Chunks (${chunkBreakdown.totalChunkTypes} types, ${chunkBreakdown.totalClasses} classes)`);
1479
- for (const name of CHUNK_ORDER) {
1480
- const d = chunkBreakdown.byChunk[name];
1481
- if (d) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1482
- }
1483
- for (const [name, d] of Object.entries(chunkBreakdown.byChunk)) if (!CHUNK_ORDER.includes(name)) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1484
- console.groupEnd();
1485
- }
1486
- if (defs.properties.length || defs.keyframes.length) console.log(`Defs: ${defs.properties.length} @property, ${defs.keyframes.length} @keyframes`);
1487
- console.groupEnd();
1488
- }
1489
- return summary;
1490
- },
1491
- chunks(opts) {
1492
- const { root = document, raw = false } = opts || {};
1493
- const breakdown = buildChunkBreakdown(root);
1494
- if (!raw) {
1495
- console.group(`Chunks (${breakdown.totalChunkTypes} types, ${breakdown.totalClasses} classes)`);
1496
- for (const name of CHUNK_ORDER) {
1497
- const d = breakdown.byChunk[name];
1498
- if (d) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1499
- }
1500
- for (const [name, d] of Object.entries(breakdown.byChunk)) if (!CHUNK_ORDER.includes(name)) console.log(` ${name}: ${d.classes.length} cls, ${d.ruleCount} rules, ${fmtSize(d.cssSize)}`);
1501
- console.groupEnd();
1502
- }
1503
- return breakdown;
1504
- },
1505
- cache(opts) {
1506
- const { root = document, raw = false } = opts || {};
1507
- const active = findDomTastyClasses(root);
1508
- const unused = getUnusedClasses(root);
1509
- const metrics = injector.instance.getMetrics({ root });
1510
- const status = {
1511
- classes: {
1512
- active,
1513
- unused,
1514
- all: [...active, ...unused]
1515
- },
1516
- metrics
1517
- };
1518
- if (!raw) {
1519
- console.group("Cache");
1520
- console.log(`Active: ${active.length}, Unused: ${unused.length}`);
1521
- if (metrics) {
1522
- const total = metrics.hits + metrics.misses;
1523
- const rate = total > 0 ? (metrics.hits / total * 100).toFixed(1) : 0;
1524
- console.log(`Hits: ${metrics.hits}, Misses: ${metrics.misses}, Rate: ${rate}%`);
1525
- }
1526
- console.groupEnd();
1527
- }
1528
- return status;
1529
- },
1530
- cleanup(opts) {
1531
- injector.instance.cleanup(opts?.root);
1532
- },
1533
- help() {
1534
- console.log(`tastyDebug API:
1535
- .summary() — overview (classes, rules, sizes)
1536
- .css("active") — CSS for classes in DOM
1537
- .css("t42") — CSS for a specific class
1538
- .css("t42",{source:1})— original CSS before browser parsing (dev only)
1539
- .css(".selector") — CSS for a DOM element
1540
- .inspect(".selector") — element details (classes, chunks, rules)
1541
- .chunks() — style chunk breakdown
1542
- .cache() — cache status and metrics
1543
- .cleanup() — force unused style cleanup
1544
- Options: { raw: true } suppresses logging, { root: shadowRoot } targets Shadow DOM`);
1545
- },
1546
- install() {
1547
- if (typeof window !== "undefined" && window.tastyDebug !== tastyDebug) {
1548
- window.tastyDebug = tastyDebug;
1549
- console.log("tastyDebug installed. Run tastyDebug.help() for commands.");
1550
- }
1551
- }
1552
- };
1553
- function getPageCSS(root = document) {
1554
- const chunks = [];
1555
- try {
1556
- if ("styleSheets" in root) for (const sheet of Array.from(root.styleSheets)) try {
1557
- if (sheet.cssRules) chunks.push(Array.from(sheet.cssRules).map((r) => r.cssText).join("\n"));
1558
- } catch {}
1559
- } catch {}
1560
- return chunks.join("\n");
1561
- }
1562
- if (typeof window !== "undefined" && isDevEnv()) tastyDebug.install();
1563
- //#endregion
1564
- export { property as A, getRawCSSText as C, injector as D, injectRawCSS as E, ChunkSheetRegistry as M, chunkSheetRegistry as N, isPropertyDefined as O, resolveFunctionColor as P, getCSSTextForNode as S, injectGlobal as T, destroy as _, color as a, gc as b, hasKeys as c, collectAutoInferredPropertiesRSC as d, getStyleTarget as f, createInjector as g, counterStyle as h, _modAttrs as i, touch as j, keyframes as k, formatKeyframesCSS as l, cleanup as m, processTokens as n, filterBaseProps as o, pushRSCCSS as p, dotize as r, computeStyles as s, tastyDebug as t, collectAutoInferredProperties as u, fontFace as v, inject as w, getCSSText as x, func as y };
1565
-
1566
- //# sourceMappingURL=core-Dr4u1NVD.js.map