@bamboocss/generator 1.55.7 → 1.56.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +44 -594
- package/dist/index.mjs +44 -594
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -51,7 +51,6 @@ function generateConditions(ctx) {
|
|
|
51
51
|
|
|
52
52
|
export type ConditionalValue<V> =
|
|
53
53
|
| V
|
|
54
|
-
| Array<V | null>
|
|
55
54
|
| {
|
|
56
55
|
[K in keyof Conditions]?: ConditionalValue<V>
|
|
57
56
|
}
|
|
@@ -211,190 +210,34 @@ function generateMergeCssFn(ctx) {
|
|
|
211
210
|
}
|
|
212
211
|
//#endregion
|
|
213
212
|
//#region src/artifacts/js/cva.ts
|
|
213
|
+
/**
|
|
214
|
+
* The runtime `cva` a compiled build keeps: a callable that throws, and `splitVariantProps`.
|
|
215
|
+
*
|
|
216
|
+
* The Vite compiler rewrites every call into the classes it selects and erases the recipe, so
|
|
217
|
+
* nothing else on the returned object is reachable. It used to carry a whole engine anyway —
|
|
218
|
+
* `resolve`, `raw`, `merge`/`composeRecipes`, `getCompoundVariantCss`, `variantMap`, `config` —
|
|
219
|
+
* and every read of those fails the build with `runtime-binding`, so none of it could run in a
|
|
220
|
+
* build that succeeded. It also kept `mergeCss` and the shorthand table alive in every bundle
|
|
221
|
+
* that imported `cva`.
|
|
222
|
+
*
|
|
223
|
+
* `splitVariantProps` stays because it is the one member the compiler lowers rather than
|
|
224
|
+
* rejects: `b.splitVariantProps(p)` becomes `splitProps(p, [...keys])`, and a call site it
|
|
225
|
+
* could not lower still has a working method behind it.
|
|
226
|
+
*/
|
|
214
227
|
function generateCvaFn(ctx) {
|
|
215
|
-
const { utility, hash, prefix } = ctx;
|
|
216
|
-
const withPrefix = prefix.className ? `(className) => className ? ${JSON.stringify(prefix.className)} + '-' + className : ${JSON.stringify(prefix.className)}` : `(className) => className`;
|
|
217
228
|
return {
|
|
218
229
|
js: outdent.outdent`
|
|
219
|
-
${ctx.file.import("
|
|
220
|
-
${ctx.file.import("mergeCss", "./merge-css")}
|
|
221
|
-
${ctx.file.import("cx", "./cx")}
|
|
222
|
-
|
|
223
|
-
// What \`createCss\` does to a class name, for the recipe path: prefix it, and hash it
|
|
224
|
-
// when \`hash.className\` is set. The build applies the same two steps to the rules it
|
|
225
|
-
// emits — see \`checkNamingAgreement\`, which compares the results.
|
|
226
|
-
const withPrefix = ${withPrefix}
|
|
227
|
-
export const formatRecipeClass = ${hash.className ? `(className) => withPrefix((${utility.toHash})([className], toHash))` : `withPrefix`}
|
|
228
|
-
|
|
229
|
-
const defaults = (conf) => ({
|
|
230
|
-
base: {},
|
|
231
|
-
variants: {},
|
|
232
|
-
defaultVariants: {},
|
|
233
|
-
compoundVariants: [],
|
|
234
|
-
...conf,
|
|
235
|
-
})
|
|
230
|
+
${ctx.file.import("splitProps, uncompiledStyle", "../helpers")}
|
|
236
231
|
|
|
237
232
|
export function cva(config) {
|
|
238
|
-
const
|
|
239
|
-
const getVariantProps = (variants) => ({ ...defaultVariants, ...compact(variants) })
|
|
240
|
-
|
|
241
|
-
// Derived from the config, because the build derives it from the same config while
|
|
242
|
-
// emitting the stylesheet and the two never meet. \`className\` when the author set
|
|
243
|
-
// one, a hash of the styles otherwise.
|
|
244
|
-
const name = getRecipeIdentity(config)
|
|
245
|
-
|
|
246
|
-
function resolve(props = {}) {
|
|
247
|
-
const computedVariants = getVariantProps(props)
|
|
248
|
-
let variantCss = { ...base }
|
|
249
|
-
for (const [key, value] of Object.entries(computedVariants)) {
|
|
250
|
-
if (variants[key]?.[value]) {
|
|
251
|
-
variantCss = mergeCss(variantCss, variants[key][value])
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
// A recipe with no compound variants has nothing left to merge, and the merge is
|
|
255
|
-
// not free just because its second operand is empty: \`mergeCss\` is memoized on its
|
|
256
|
-
// arguments, so the call hashes the whole accumulated style object before finding
|
|
257
|
-
// there is nothing to do. Most recipes declare no compound variants at all, so
|
|
258
|
-
// this is the common shape rather than a special case.
|
|
259
|
-
if (compoundVariants.length === 0) return variantCss
|
|
260
|
-
|
|
261
|
-
const compoundVariantCss = getCompoundVariantCss(compoundVariants, computedVariants)
|
|
262
|
-
return mergeCss(variantCss, compoundVariantCss)
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// \`raw\` runs per element per render — the JSX factory calls it to build the styles it
|
|
266
|
-
// merges with style props — and \`resolve\` is not cheap: a \`mergeCss\` per active variant
|
|
267
|
-
// plus a scan of every compound variant. Memoizing it keys that work on the variant
|
|
268
|
-
// props rather than repeating it for every element that shares them.
|
|
269
|
-
//
|
|
270
|
-
// \`raw\` still clones what it returns. The memoized object is shared, so handing it to a
|
|
271
|
-
// caller that mutated it would poison every later call.
|
|
272
|
-
//
|
|
273
|
-
// A recipe whose variants are all boolean could index an array instead of hashing, and
|
|
274
|
-
// that was built and measured: +25% to +35% on \`raw()\`. It is not here because the
|
|
275
|
-
// trade is bad. Correctness needs the selection read from own enumerable keys only, and
|
|
276
|
-
// every variant to carry a boolean default so the merge order is pinned — and once that
|
|
277
|
-
// gate is honest, no \`cva\`/\`sva\` call site in this repo passes it, because real recipes
|
|
278
|
-
// mix a string variant in. The cost is unconditional: +289 B gzipped on that module for
|
|
279
|
-
// every consumer, qualifying or not.
|
|
280
|
-
const resolveVariants = memo(resolve)
|
|
281
|
-
|
|
282
|
-
// The class names the build emitted rules for: the recipe's own class, plus one per
|
|
283
|
-
// selected variant. Not \`css(resolve(props))\` — that would name classes by property,
|
|
284
|
-
// and the stylesheet names this recipe's rules semantically, in the \`recipes\` layer.
|
|
285
|
-
//
|
|
286
|
-
// Compound variants are absent on purpose. Their rule selects on the variant classes
|
|
287
|
-
// already in this list — \`.btn--size_sm.btn--tone_a\` — so it applies without anything
|
|
288
|
-
// being added here, and adding a class for it would name a rule that does not exist.
|
|
289
|
-
function cvaFn(_props) {
|
|
290
|
-
return uncompiledStyle('cva')
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
const variantKeys = Object.keys(variants)
|
|
233
|
+
const variantKeys = Object.keys(config?.variants ?? {})
|
|
294
234
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
const variantMap = Object.fromEntries(Object.entries(variants).map(([key, value]) => [key, Object.keys(value)]))
|
|
300
|
-
|
|
301
|
-
const self = Object.assign(memo(cvaFn), {
|
|
302
|
-
__cva__: true,
|
|
303
|
-
variantMap,
|
|
304
|
-
raw: (...args) => cloneStyles(resolveVariants(...args)),
|
|
305
|
-
config,
|
|
306
|
-
// Composed against \`self\`, not against this closure, so \`a.merge(b).merge(c)\`
|
|
307
|
-
// composes the *result* with \`c\` rather than recomposing \`a\` with \`c\` and
|
|
308
|
-
// dropping \`b\`.
|
|
309
|
-
merge: (other) => composeRecipes(self, other),
|
|
310
|
-
splitVariantProps,
|
|
311
|
-
getVariantProps
|
|
312
|
-
})
|
|
313
|
-
|
|
314
|
-
return self
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* Compose two recipes into one.
|
|
319
|
-
*
|
|
320
|
-
* The class names come from both parents joined, not from a merged config. A recipe's
|
|
321
|
-
* classes are named from the config the *build* saw, and the build only ever sees the
|
|
322
|
-
* literal \`cva(...)\` call sites — a config synthesised here at runtime has no rules
|
|
323
|
-
* behind it, so naming classes off it returned classes that styled nothing. This is the
|
|
324
|
-
* shape \`mergeRecipes\` already uses for config recipes.
|
|
325
|
-
*
|
|
326
|
-
* The selection is resolved once and handed to both parents. Passing the raw props
|
|
327
|
-
* instead let each parent apply *its own* defaults, so \`m()\` and
|
|
328
|
-
* \`m(m.getVariantProps())\` disagreed and \`raw()\` contradicted the \`config\` the same
|
|
329
|
-
* object publishes.
|
|
330
|
-
*
|
|
331
|
-
* \`raw\` still deep-merges, so per-property override survives where it can be expressed:
|
|
332
|
-
* \`css(a.merge(b).raw(props))\` resolves before any class name exists. Through the class
|
|
333
|
-
* path both parents land in the \`recipes\` layer, so a collision there is decided by
|
|
334
|
-
* stylesheet order rather than by which parent came second.
|
|
335
|
-
*/
|
|
336
|
-
function composeRecipes(left, right) {
|
|
337
|
-
const leftConfig = defaults(left.config)
|
|
338
|
-
const rightConfig = defaults(right.config)
|
|
339
|
-
const variantKeys = uniq(Object.keys(left.variantMap), Object.keys(right.variantMap))
|
|
340
|
-
|
|
341
|
-
const config = {
|
|
342
|
-
base: mergeCss(leftConfig.base, rightConfig.base),
|
|
343
|
-
variants: Object.fromEntries(
|
|
344
|
-
variantKeys.map((key) => [key, mergeCss(leftConfig.variants[key], rightConfig.variants[key])]),
|
|
345
|
-
),
|
|
346
|
-
defaultVariants: mergeProps(leftConfig.defaultVariants, rightConfig.defaultVariants),
|
|
347
|
-
compoundVariants: [...leftConfig.compoundVariants, ...rightConfig.compoundVariants],
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
const select = (props) => ({ ...config.defaultVariants, ...compact(props) })
|
|
351
|
-
|
|
352
|
-
const composed = Object.assign(
|
|
353
|
-
memo((props) => {
|
|
354
|
-
const selection = select(props)
|
|
355
|
-
return cx(left(selection), right(selection))
|
|
356
|
-
}),
|
|
357
|
-
{
|
|
358
|
-
__cva__: true,
|
|
359
|
-
variantMap: Object.fromEntries(variantKeys.map((key) => [key, Object.keys(config.variants[key] ?? {})])),
|
|
360
|
-
raw: (props) => {
|
|
361
|
-
const selection = select(props)
|
|
362
|
-
return cloneStyles(mergeCss(left.raw(selection), right.raw(selection)))
|
|
363
|
-
},
|
|
364
|
-
config,
|
|
365
|
-
merge: (other) => composeRecipes(composed, other),
|
|
366
|
-
splitVariantProps: (props) => splitProps(props, variantKeys),
|
|
367
|
-
getVariantProps: select,
|
|
235
|
+
return Object.assign((_props) => uncompiledStyle('cva'), {
|
|
236
|
+
splitVariantProps(props) {
|
|
237
|
+
return splitProps(props, variantKeys)
|
|
368
238
|
},
|
|
369
|
-
)
|
|
370
|
-
|
|
371
|
-
return composed
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
export function getCompoundVariantCss(compoundVariants, variantMap) {
|
|
375
|
-
let result = {}
|
|
376
|
-
compoundVariants.forEach((compoundVariant) => {
|
|
377
|
-
const isMatching = Object.entries(compoundVariant).every(([key, value]) => {
|
|
378
|
-
if (key === 'css') return true
|
|
379
|
-
|
|
380
|
-
const values = Array.isArray(value) ? value : [value]
|
|
381
|
-
return values.some((value) => variantMap[key] === value)
|
|
382
|
-
})
|
|
383
|
-
|
|
384
|
-
if (isMatching) {
|
|
385
|
-
result = mergeCss(result, compoundVariant.css)
|
|
386
|
-
}
|
|
387
239
|
})
|
|
388
|
-
|
|
389
|
-
return result
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
export function assertCompoundVariant(name, compoundVariants, variants, prop) {
|
|
393
|
-
if (compoundVariants.length > 0 && typeof variants?.[prop] === 'object') {
|
|
394
|
-
throw new Error(\`[recipe:\${name}:\${prop}] Conditions are not supported when using compound variants.\`)
|
|
395
|
-
}
|
|
396
240
|
}
|
|
397
|
-
|
|
398
241
|
`,
|
|
399
242
|
dts: outdent.outdent`
|
|
400
243
|
${ctx.file.importType("RecipeCreatorFn", "../types/recipe")}
|
|
@@ -539,7 +382,7 @@ function generateCx(ctx) {
|
|
|
539
382
|
}
|
|
540
383
|
//#endregion
|
|
541
384
|
//#region src/artifacts/generated/helpers.mjs.json
|
|
542
|
-
var content$7 = "//#region src/assert.ts\nfunction isObject(value) {\n return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\nconst isObjectOrArray = (obj) => typeof obj === \"object\" && obj !== null;\n//#endregion\n//#region src/error.ts\nvar BambooError = class extends Error {\n code;\n hint;\n constructor(code, message, opts) {\n super(message, { cause: opts?.cause });\n this.code = `ERR_BAMBOO_${code}`;\n this.hint = opts?.hint;\n }\n};\n//#endregion\n//#region src/hash.ts\nfunction toChar(code) {\n return String.fromCharCode(code + (code > 25 ? 39 : 97));\n}\nfunction toName(code) {\n let name = \"\";\n let x;\n for (x = Math.abs(code); x > 52; x = x / 52 | 0) name = toChar(x % 52) + name;\n return toChar(x % 52) + name;\n}\nfunction toPhash(h, x) {\n let i = x.length;\n while (i) h = h * 33 ^ x.charCodeAt(--i);\n return h;\n}\nfunction toHash(value) {\n return toName(toPhash(5381, value) >>> 0);\n}\n//#endregion\n//#region src/memo.ts\n/**\n* Bounded argument memo used by the generated runtime (`css`, patterns, `cva`, recipes).\n*\n* Two regimes, picked per call:\n*\n* - Arguments that are flat (objects of primitives) take a cheap structural hash\n* and are confirmed with an exact comparison, so a hash collision can never\n* serve the wrong result. This is the shape `css({ ... })` has.\n* - Anything nested falls back to `JSON.stringify`, which V8 does faster than a\n* JS walk.\n*\n* The second point is the counter-intuitive one, and it has been measured rather\n* than assumed. Extending the structural hash to recurse — so nested styles could\n* take the fast path too — is *slower*, because it trades one native serialization\n* for two JS walks (hash, then the deep equality that confirms it). Over 10k\n* iterations per shape:\n*\n* shape stringify recursive hash + deep equal\n* flat 1.06ms 2.09ms\n* _hover 1.00ms 2.16ms\n* responsive 1.23ms 2.15ms\n* realistic 2.32ms 5.84ms\n* nested 3 deep 1.22ms 2.35ms\n*\n* So a nested `css()` call costing several times a flat one is not a defect here.\n* It is the floor for a value-keyed memo in JS, and the way to avoid it is to not\n* make the call — see the build-time fold in `@bamboocss/vite`.\n*\n* Both regimes key on *values*, never on object identity: mutating a style object\n* between calls changes its hash, so the next call misses and recomputes rather\n* than serving a stale class. Keying nested arguments on the identity of the inner\n* objects would skip serialization entirely, but it cannot detect a mutation, and\n* \"same object, different contents\" is exactly what a style object built per render\n* looks like.\n*\n* Both caches are bounded. An unbounded memo is a leak in any long-lived process\n* (SSR), where the set of distinct style objects grows without limit.\n*/\n/**\n* Distinct hashes held per memoized function before the cache rotates.\n*\n* This bounds *buckets*, not entries: a bucket keeps up to `MAX_BUCKET` colliding\n* argument lists, so the ceiling is `MAX_ENTRIES * MAX_BUCKET` live entries, and\n* twice that across both generations, since the previous one is retained until the\n* next rotation. Collisions are rare in practice, so the realistic figure is close\n* to `MAX_ENTRIES` — but the worst case is what matters when sizing a long-lived\n* process, so state it plainly.\n*\n* Rotation beats evicting the oldest key: single-key eviction is worst-case for a\n* working set that cycles, because it drops exactly the entry about to be needed.\n* Measured on a cycling set of 20k styles, one-at-a-time eviction cost ~719ns/op\n* against ~189ns unbounded, while rotation holds ~274ns. On realistic skewed\n* access rotation is at or below the unbounded cost.\n*/\nconst MAX_ENTRIES = 1e3;\n/** Entries kept per hash bucket, to bound the cost of a collision scan. */\nconst MAX_BUCKET = 8;\n/**\n* DJB2 over the arguments' own keys and primitive values.\n* Returns `null` for anything nested, which routes the call to the string key.\n*/\nconst flatHashOrNull = (args) => {\n let h = 5381;\n for (let a = 0; a < args.length; a++) {\n const obj = args[a];\n if (obj === null || typeof obj !== \"object\") {\n const t = typeof obj;\n if (t === \"string\") for (let i = 0; i < obj.length; i++) h = h * 33 ^ obj.charCodeAt(i);\n else if (t === \"number\") h = h * 33 ^ (obj | 0);\n else if (t === \"boolean\") h = h * 33 ^ (obj ? 991 : 997);\n else h = h * 33 ^ 3;\n continue;\n }\n if (Array.isArray(obj)) return null;\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) return null;\n for (const k in obj) {\n const v = obj[k];\n const tv = typeof v;\n if (v !== null && tv === \"object\") return null;\n for (let i = 0; i < k.length; i++) h = h * 33 ^ k.charCodeAt(i);\n if (tv === \"string\") for (let i = 0; i < v.length; i++) h = h * 33 ^ v.charCodeAt(i);\n else if (tv === \"number\") h = h * 33 ^ (v | 0);\n else if (tv === \"boolean\") h = h * 33 ^ (v ? 991 : 997);\n else h = h * 33 ^ 2;\n }\n }\n return h >>> 0;\n};\n/**\n* Value snapshot of the arguments, taken once at insert.\n*\n* The cache must not hold the caller's objects: a style object can capture a much\n* larger graph, and keeping it alive until the cache rotates changes GC behaviour\n* for code that never asked to be cached. Only the flat path reaches here, so a\n* shallow copy contains primitives only and retains nothing.\n*\n* Comparing against a copy also removes the last way a mutation could be missed.\n* Were the caller's own object stored, `oa === ob` would short-circuit the value\n* comparison, and a mutation that happened to preserve the hash would return the\n* stale entry. Against a copy that check can only ever be true for equal\n* primitives.\n*/\nconst snapshotArgs = (args) => {\n const values = [];\n const counts = [];\n for (let i = 0; i < args.length; i++) {\n const o = args[i];\n if (o !== null && typeof o === \"object\") {\n const copy = Array.isArray(o) ? [] : {};\n let n = 0;\n for (const k in o) {\n copy[k] = o[k];\n n++;\n }\n values.push(copy);\n counts.push(n);\n } else {\n values.push(o);\n counts.push(0);\n }\n }\n return {\n values,\n counts\n };\n};\n/**\n* Exact match, so a `flatHashOrNull` collision is resolved rather than trusted.\n* `bCounts` is the cached side's key count; comparing against it avoids the\n* `Object.keys()` allocation this would otherwise make on every cache hit.\n*/\nconst flatArgsEqual = (a, b, bCounts) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const oa = a[i];\n const ob = b[i];\n if (oa === ob) continue;\n if (oa === null || ob === null || typeof oa !== \"object\" || typeof ob !== \"object\") return false;\n if (Array.isArray(oa) !== Array.isArray(ob)) return false;\n let n = 0;\n for (const k in oa) {\n if (oa[k] !== ob[k]) return false;\n n++;\n }\n if (n !== bCounts[i]) return false;\n }\n return true;\n};\nconst memo = (fn) => {\n let buckets = /* @__PURE__ */ new Map();\n let priorBuckets = /* @__PURE__ */ new Map();\n let strings = /* @__PURE__ */ new Map();\n let priorStrings = /* @__PURE__ */ new Map();\n /**\n * One scalar argument, keyed directly.\n *\n * This is the shape of the hottest callers — `isCssProperty(prop)` runs per prop\n * per render — and a plain map lookup beats hashing, bucket scanning and\n * snapshotting for it. Distinct types stay distinct keys, so `1` and `'1'` do not\n * share an entry.\n */\n let scalars = /* @__PURE__ */ new Map();\n let priorScalars = /* @__PURE__ */ new Map();\n const scan = (bucket, args) => {\n if (bucket) for (let i = 0; i < bucket.length; i++) {\n const entry = bucket[i];\n if (flatArgsEqual(args, entry.values, entry.counts)) return entry;\n }\n };\n const get = (...args) => {\n if (args.length === 1) {\n const only = args[0];\n if (only === null || typeof only !== \"object\") {\n if (scalars.has(only)) return scalars.get(only);\n if (priorScalars.has(only)) {\n const promoted = priorScalars.get(only);\n scalars.set(only, promoted);\n return promoted;\n }\n const out = fn(only);\n scalars.set(only, out);\n if (scalars.size > MAX_ENTRIES) {\n priorScalars = scalars;\n scalars = /* @__PURE__ */ new Map();\n }\n return out;\n }\n }\n const hash = flatHashOrNull(args);\n if (hash !== null) {\n let bucket = buckets.get(hash);\n const hit = scan(bucket, args);\n if (hit) return hit.out;\n const priorHit = scan(priorBuckets.get(hash), args);\n if (priorHit) {\n if (!bucket) {\n bucket = [];\n buckets.set(hash, bucket);\n }\n bucket.push(priorHit);\n if (bucket.length > MAX_BUCKET) bucket.shift();\n return priorHit.out;\n }\n const snap = snapshotArgs(args);\n const out = fn(...args);\n if (!bucket) {\n bucket = [];\n buckets.set(hash, bucket);\n }\n bucket.push({\n values: snap.values,\n counts: snap.counts,\n out\n });\n if (bucket.length > MAX_BUCKET) bucket.shift();\n if (buckets.size > MAX_ENTRIES) {\n priorBuckets = buckets;\n buckets = /* @__PURE__ */ new Map();\n }\n return out;\n }\n const key = JSON.stringify(args);\n if (strings.has(key)) return strings.get(key);\n if (priorStrings.has(key)) {\n const promoted = priorStrings.get(key);\n strings.set(key, promoted);\n return promoted;\n }\n const out = fn(...args);\n strings.set(key, out);\n if (strings.size > MAX_ENTRIES) {\n priorStrings = strings;\n strings = /* @__PURE__ */ new Map();\n }\n return out;\n };\n return get;\n};\n//#endregion\n//#region src/merge-props.ts\nconst MERGE_OMIT = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\"\n]);\nfunction mergeProps(...sources) {\n return sources.reduce((prev, obj) => {\n if (!obj) return prev;\n Object.keys(obj).forEach((key) => {\n if (MERGE_OMIT.has(key)) return;\n const prevValue = prev[key];\n const value = obj[key];\n if (isObject(prevValue) && isObject(value)) prev[key] = mergeProps(prevValue, value);\n else prev[key] = value;\n });\n return prev;\n }, {});\n}\n//#endregion\n//#region src/walk-object.ts\nconst isNotNullish = (element) => element != null;\nfunction walkObject(target, predicate, options = {}) {\n const { stop, getKey } = options;\n function inner(value, path = []) {\n if (isObjectOrArray(value)) {\n const result = {};\n for (const [prop, child] of Object.entries(value)) {\n const key = getKey?.(prop, child) ?? prop;\n const childPath = [...path, key];\n if (stop?.(value, childPath)) return predicate(value, path);\n const next = inner(child, childPath);\n if (isNotNullish(next)) result[key] = next;\n }\n return result;\n }\n return predicate(value, path);\n }\n return inner(target);\n}\nfunction mapObject(obj, fn) {\n if (Array.isArray(obj)) return obj.map((value) => fn(value));\n if (!isObject(obj)) return fn(obj);\n return walkObject(obj, (value) => fn(value));\n}\n//#endregion\n//#region src/normalize-style-object.ts\n/**\n* Whether walking the object would only rebuild it.\n*\n* Normalizing does two things: it renames a shorthand to its longhand and drops nullish\n* leaves. A flat object of plain values written in longhand needs neither, and that is most\n* of what `css()` is handed — but it still paid for a full rebuild plus a path array per key.\n*\n* Every clause has to be exact, since a false positive returns an object the walk would have\n* changed. Nullish is one of them: a leaf the walk removes must not survive, or a later merge\n* would see it override the value beneath it. The array check is another, and it is on the\n* container as well as the values — `stop` is handed the container, so an array arriving at\n* the top level has to reach the walk to be rejected rather than being returned as it came.\n*\n* `for...in` reads inherited keys the walk ignores, which is safe in the only direction it can\n* be wrong — an extra key can send this to the slow path, never past it.\n*\n* It does read every value, as `compactStyles` and the argument memo already do, so an\n* accessor prop is read once more than before. Style props are values by the time they get\n* here and reading one has no effect, but it is the reason this cannot be reordered to read\n* lazily.\n*/\nfunction needsNoNormalizing(styles, resolveShorthand) {\n if (Array.isArray(styles)) return false;\n for (const key in styles) {\n const value = styles[key];\n if (value == null || typeof value === \"object\") return false;\n if (resolveShorthand !== void 0 && resolveShorthand(key) !== key) return false;\n }\n return true;\n}\n/**\n* The result may be the argument itself rather than a fresh object, so callers have to treat\n* it as read-only. Every one of them does today: merging accumulates into its own object and\n* the two `raw()` helpers clone at the boundary.\n*\n* An array is not a style value. It used to be read as one value per breakpoint, which meant\n* a font stack written the way CSS writes one — `['Inter', 'sans-serif']` — silently became\n* `Inter` at base and `sans-serif` at `sm`. The type no longer admits an array, so reaching\n* this throw takes a cast or untyped javascript; it says which property, since the walk knows\n* the path and the caller usually does not.\n*/\nfunction normalizeStyleObject(styles, context, shorthand = true) {\n const { utility } = context;\n const { hasShorthand, resolveShorthand } = utility;\n if (needsNoNormalizing(styles, shorthand && hasShorthand ? resolveShorthand : void 0)) return styles;\n return walkObject(styles, (value, path) => {\n if (Array.isArray(value)) throw new BambooError(\"INVALID_STYLE_VALUE\", `An array is not a style value${path.length ? `: \"${path.join(\".\")}\"` : \"\"}.`, { hint: \"Write a responsive value as a condition object, e.g. { base: \\\"medium\\\", lg: \\\"bold\\\" }.\" });\n return value;\n }, {\n stop: (value) => Array.isArray(value),\n getKey: shorthand ? (prop) => hasShorthand ? resolveShorthand(prop) : prop : void 0\n });\n}\n//#endregion\n//#region src/classname.ts\n/**\n* Whether a style object carries anything `compact` would have kept.\n*\n* The question `compactStyles` asks is only ever \"is this empty once undefined values are\n* dropped\", but it used to answer it by building the compacted object and then a key array\n* for it, then throwing both away. `Object.keys` enumerates exactly what `compact`'s\n* `Object.entries` did — own, enumerable, string-keyed — so this is the same predicate\n* without the two allocations, and it stops at the first value that settles it.\n*/\nfunction hasDefinedValue(style) {\n const keys = Object.keys(style);\n for (let i = 0; i < keys.length; i++) if (style[keys[i]] !== void 0) return true;\n return false;\n}\n/**\n* An array is not a style argument.\n*\n* `css([a, b])` used to mean `css(a, b)`, flattened here one level. Two spellings of one\n* call is the redundancy; the array one also cost a `flat()` allocation on every merge to\n* serve a shape almost nothing wrote, and read as a responsive array everywhere that had\n* not been taught to flatten it first.\n*\n* It throws rather than being filtered out as a non-object, which is what dropping the\n* `flat()` alone would have done — silently returning no class at all.\n*/\nfunction compactStyles(...styles) {\n return styles.filter((style) => {\n if (Array.isArray(style)) throw new BambooError(\"INVALID_STYLE_ARGUMENT\", \"An array is not a style argument.\", { hint: \"Spread it instead, e.g. css(...styles) rather than css(styles).\" });\n return isObject(style) && hasDefinedValue(style);\n });\n}\nfunction createMergeCss(context) {\n function resolve(styles) {\n const allStyles = compactStyles(...styles);\n if (allStyles.length === 1) return allStyles;\n return allStyles.map((style) => normalizeStyleObject(style, context));\n }\n function mergeCss(...styles) {\n return mergeProps(...resolve(styles));\n }\n return {\n mergeCss: memo(mergeCss),\n mergeCssUncached: mergeCss\n };\n}\n//#endregion\n//#region src/clone-styles.ts\nconst OMIT = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\"\n]);\n/**\n* Independent copy of a style object, nested condition blocks included.\n*\n* Merged style objects are cached, so anything handed to user code has to be\n* copied first: a caller mutating what it received would otherwise change what\n* every later caller reads back. `css.raw()` and `cva.raw()` are those boundaries.\n*\n* Kept separate from `mergeProps` deliberately. Merging is on the hot path — it\n* runs on every `css()` cache miss and on every render of a pattern component\n* under `jsxStyleProps: 'minimal'` — and copying there charges every caller for a\n* guarantee only the two `raw()` helpers need. Measured on a realistic style\n* object (5 base properties, 4 condition blocks) that was roughly twice the cost\n* of merging alone.\n*/\nfunction cloneStyles(styles) {\n if (Array.isArray(styles)) return styles.map((value) => cloneStyles(value));\n if (!isObject(styles)) return styles;\n const out = {};\n for (const key of Object.keys(styles)) {\n if (OMIT.has(key)) continue;\n out[key] = cloneStyles(styles[key]);\n }\n return out;\n}\n//#endregion\n//#region src/compact.ts\nfunction compact(value) {\n return Object.fromEntries(Object.entries(value ?? {}).filter(([_, value]) => value !== void 0));\n}\n//#endregion\n//#region src/recipe-identity.ts\n/**\n* The fields that decide what CSS a recipe produces. Anything else is metadata.\n*\n* `slots` and `scopeRoots` count. They do not change a declaration, but they change the\n* *shape* of what is emitted — which slots exist, and whether a slot's variants become\n* `@scope` rules or a class of its own. Two `sva`s differing only in `scopeRoots` hashed to\n* one name, and since an inline recipe is registered once, whichever was extracted first\n* decided the emission for both; the other's runtime then asked for classes no rule\n* existed under. \"Same styles, different DOM topology\" is exactly what `scopeRoots` is for,\n* so it is the collision most likely to happen.\n*/\nconst STYLE_FIELDS = [\n \"base\",\n \"variants\",\n \"compoundVariants\",\n \"defaultVariants\",\n \"slots\",\n \"scopeRoots\"\n];\n/**\n* A serialization that depends on the config's *content* and not on how it was written.\n*\n* Object keys are sorted, so reordering two variants in the source does not rename every\n* class the recipe emits. Arrays keep their order, because `compoundVariants` is precedence\n* ordered and two orderings are two different recipes.\n*\n* A function serializes to `null` rather than to its source. `JSON.stringify` already drops\n* them, and stringifying instead would key the name on whether the bundle was minified —\n* the same build-dependent divergence that `cx` was changed to avoid. Nothing that survives\n* static extraction is a function, so there is no real config this loses information about.\n*/\n/**\n* Runs of whitespace inside a declaration value, collapsed to one space.\n*\n* The build never sees the value as written. `maybe-box-node` reads every string literal\n* through `trimWhitespace`, so `'calc(100vh - 16px)'` is `'calc(100vh - 16px)'` by the time\n* a recipe config reaches the encoder — the two produce identical CSS, and the stylesheet\n* emits one rule for both.\n*\n* The browser holds the config as authored. Without this, the two sides hashed different\n* objects and derived different names, so the element asked for a class the stylesheet did\n* not carry and rendered with *none* of the recipe's styles. Silent, and invisible to a\n* dead-rule check: the extra name leaves no unused rule behind, because the collapsed config\n* is byte-identical to one that was already emitted.\n*\n* The regex is `trimWhitespace`'s, deliberately. A second spelling of \"the same value\" is a\n* second thing to keep in agreement, which is the defect this is fixing.\n*/\nconst collapseWhitespace = (value) => value.replaceAll(/\\s+/g, \" \");\nconst stable = (value) => {\n if (typeof value === \"string\") return JSON.stringify(collapseWhitespace(value));\n if (value === null || typeof value !== \"object\") return JSON.stringify(value) ?? \"null\";\n if (Array.isArray(value)) return `[${value.map(stable).join(\",\")}]`;\n const source = value;\n return `{${Object.keys(source).sort().filter((key) => source[key] !== void 0 && source[key] !== null).map((key) => `${JSON.stringify(key)}:${stable(source[key])}`).join(\",\")}}`;\n};\n/**\n* The name an inline `cva`/`sva` emits its classes under — `button--size_sm`, where this\n* returns the `button`.\n*\n* A config recipe gets its name from the key it is declared under. An inline one has no\n* such key, and the two places that need the name never meet: the build derives it while\n* emitting the stylesheet, the runtime derives it again in the browser. So it has to come\n* from something both of them see, which leaves the config object itself.\n*\n* Deriving it from the *binding* — `const button = cva(...)` — was the obvious alternative\n* and does not work. Only the build can see that binding; handing it to the runtime means\n* rewriting the call, and then a pipeline without that transform names classes differently\n* from one with it. An optional `className` gets the same readable output with none of\n* that, because it travels inside the config to both sides.\n*\n* `className` is the field a config recipe already names itself with, and it means the same\n* thing here — the prefix every class the recipe emits is built from. An inline recipe that\n* declares one is indistinguishable in the stylesheet from a recipe declared in config.\n*/\nconst getRecipeIdentity = (config, prefix = \"cva\") => {\n const declared = config?.className;\n if (typeof declared === \"string\" && declared) return declared;\n const styles = {};\n for (const field of STYLE_FIELDS) {\n const value = config?.[field];\n if (value !== void 0) styles[field] = value;\n }\n return `${prefix}_${toHash(stable(styles))}`;\n};\n//#endregion\n//#region src/is-css-function.ts\nconst fnRegExp = new RegExp(`^(${[\n \"min\",\n \"max\",\n \"clamp\",\n \"calc\"\n].join(\"|\")})\\\\(.*\\\\)`);\nconst isCssFunction = (v) => typeof v === \"string\" && fnRegExp.test(v);\n//#endregion\n//#region src/is-css-unit.ts\nconst lengthUnitsPattern = `(?:${\"cm,mm,Q,in,pc,pt,px,em,ex,ch,rem,lh,rlh,vw,vh,vmin,vmax,vb,vi,svw,svh,lvw,lvh,dvw,dvh,cqw,cqh,cqi,cqb,cqmin,cqmax,%\".split(\",\").join(\"|\")})`;\nconst lengthRegExp = new RegExp(`^[+-]?[0-9]*.?[0-9]+(?:[eE][+-]?[0-9]+)?${lengthUnitsPattern}$`);\nconst isCssUnit = (v) => typeof v === \"string\" && lengthRegExp.test(v);\n//#endregion\n//#region src/is-css-var.ts\nconst isCssVar = (v) => typeof v === \"string\" && /^var\\(--.+\\)$/.test(v);\n//#endregion\n//#region src/pattern-fns.ts\nconst createPatternFns = (token) => ({\n map: mapObject,\n isCssFunction,\n isCssVar,\n isCssUnit,\n token\n});\nconst getPatternStyles = (pattern, styles) => {\n if (!pattern?.defaultValues) return styles;\n const defaults = typeof pattern.defaultValues === \"function\" ? pattern.defaultValues(styles) : pattern.defaultValues;\n return Object.assign({}, defaults, compact(styles));\n};\n//#endregion\n//#region src/slot.ts\nconst getSlotRecipes = (recipe = {}) => {\n const init = (slot) => ({\n className: [recipe.className, slot].filter(Boolean).join(\"__\"),\n base: recipe.base?.[slot] ?? {},\n variants: {},\n defaultVariants: recipe.defaultVariants ?? {},\n compoundVariants: recipe.compoundVariants ? getSlotCompoundVariant(recipe.compoundVariants, slot) : []\n });\n const recipeParts = (recipe.slots ?? []).map((slot) => [slot, init(slot)]);\n for (const [variantsKey, variantsSpec] of Object.entries(recipe.variants ?? {})) for (const [variantKey, variantSpec] of Object.entries(variantsSpec)) recipeParts.forEach(([slot, slotRecipe]) => {\n slotRecipe.variants[variantsKey] ??= {};\n slotRecipe.variants[variantsKey][variantKey] = variantSpec[slot] ?? {};\n });\n return Object.fromEntries(recipeParts);\n};\nconst getSlotCompoundVariant = (compoundVariants, slotName) => compoundVariants.filter((compoundVariant) => compoundVariant?.css?.[slotName]).map((compoundVariant) => ({\n ...compoundVariant,\n css: compoundVariant.css[slotName]\n}));\n//#endregion\n//#region src/split-props.ts\n/**\n* Move one key into a bucket, keeping whatever about it is observable.\n*\n* Shared by both paths below so there is one implementation of the descriptor rules rather\n* than two to keep in step. The rules themselves are documented on `splitProps`.\n*/\nconst copyKey = (props, target, key) => {\n const descriptor = Object.getOwnPropertyDescriptor(props, key);\n if (!descriptor) return false;\n if (\"get\" in descriptor || \"set\" in descriptor || !descriptor.enumerable || key === \"__proto__\") Object.defineProperty(target, key, descriptor);\n else target[key] = descriptor.value;\n return true;\n};\n/**\n* One array group, which is what every call site in this project passes — a recipe's\n* `variantKeys`.\n*\n* The general path below is built for several groups that may be predicates, and pays for\n* that shape on every call: a closure per group, a `map` and a `concat` to assemble the\n* result, and a branch per group to tell an array from a predicate. None of it is reachable\n* with one array group.\n*\n* What it does *not* skip is the part that looks skippable. `own` stays, because membership\n* has to be answered from `ownKeys` rather than by asking the object: on a proxy — which is\n* what Solid's `mergeProps` hands over — every question is a trap, and a recipe naming eight\n* variants would otherwise fire eight traps to learn what one `ownKeys` already said. And\n* the two passes stay separate, because the group bucket is in *group* order while the rest\n* bucket is in *props* order, and that ordering reaches the emitted CSS.\n*/\nconst splitOneGroup = (props, allKeys, group) => {\n const own = new Set(allKeys);\n const taken = /* @__PURE__ */ new Set();\n const picked = {};\n for (let i = 0; i < group.length; i++) {\n const key = group[i];\n if (taken.has(key) || !own.has(key)) continue;\n if (copyKey(props, picked, key)) taken.add(key);\n }\n const rest = {};\n for (let i = 0; i < allKeys.length; i++) {\n const key = allKeys[i];\n if (taken.has(key)) continue;\n copyKey(props, rest, key);\n }\n return [picked, rest];\n};\n/**\n* Deal a props object into one bucket per key group, plus a final bucket for the rest.\n* A key goes to the first group that claims it.\n*\n* ## Why the descriptor is read per key rather than in bulk\n*\n* This used to call `Object.getOwnPropertyDescriptors` for the whole object and\n* `defineProperty` for every key it moved. Copying plain values instead is 2.4–2.9x faster\n* on the shapes that allow it, but it is only correct where props are data — and they are\n* not always. Solid compiles props to accessors, so reading one eagerly runs whatever it\n* wraps: splitting a component's props would construct its children before the surrounding\n* provider exists.\n*\n* So the descriptor is fetched per key, and the value path is taken only when it changes\n* nothing observable. An accessor keeps its laziness, a non-enumerable key keeps its\n* invisibility, and `__proto__` is defined rather than assigned so it stays an own\n* property instead of reaching the prototype setter.\n*\n* The one thing the value path drops is `writable`/`configurable`, so a bucket key taken\n* from frozen props is writable where it used to be frozen. Nothing here relies on that,\n* and preserving it would mean `defineProperty` on the common path — the cost this exists\n* to avoid. Keys that take the descriptor path keep theirs, so a bucket can be\n* inconsistent in that one respect.\n*\n* Key order within a bucket is preserved exactly. It is not cosmetic: `cva` merges\n* variant props in iteration order, and the parser reads the rest bucket as the style\n* props it encodes, so order reaches the emitted CSS.\n*/\nfunction splitProps(props, ...keys) {\n const allKeys = Object.getOwnPropertyNames(props);\n if (keys.length === 1 && Array.isArray(keys[0])) return splitOneGroup(props, allKeys, keys[0]);\n const own = new Set(allKeys);\n const taken = /* @__PURE__ */ new Set();\n const split = (group) => {\n const clone = {};\n for (let i = 0; i < group.length; i++) {\n const key = group[i];\n if (taken.has(key) || !own.has(key)) continue;\n if (copyKey(props, clone, key)) taken.add(key);\n }\n return clone;\n };\n /**\n * The predicate is called with the key alone.\n *\n * Handing it to `filter` passes `(key, index, allKeys)`. A one-parameter predicate cannot\n * see the extras, but a memoized one reads its whole argument list — and the predicates\n * that arrive here are memoized, `isCssProperty` among them. So the memo hashed the entire\n * key array once per prop, and keyed its cache on it: two elements with different prop sets\n * shared no entry even for the same prop name.\n *\n * Worth ~9.7x on that path, and nothing at all on a plain predicate — which is why the\n * bench below it needs a memoized case to see this at all.\n *\n * A loop rather than `filter((k) => key(k))` because the wrapper allocates a closure per\n * group. The two measure the same to within noise; the loop just does not need one.\n */\n const matching = (predicate) => {\n const group = [];\n for (let i = 0; i < allKeys.length; i++) {\n const key = allKeys[i];\n if (predicate(key)) group.push(key);\n }\n return group;\n };\n return keys.map((key) => split(Array.isArray(key) ? key : matching(key))).concat(split(allKeys));\n}\n//#endregion\n//#region src/uniq.ts\nconst uniq = (...items) => {\n const set = items.reduce((acc, currItems) => {\n if (currItems) currItems.forEach((item) => acc.add(item));\n return acc;\n }, /* @__PURE__ */ new Set([]));\n return Array.from(set);\n};\n//#endregion\nexport { cloneStyles, compact, createMergeCss, createPatternFns, getPatternStyles, getRecipeIdentity, getSlotCompoundVariant, getSlotRecipes, memo, mergeProps, splitProps, toHash, uniq };\n";
|
|
385
|
+
var content$7 = "//#region src/assert.ts\nfunction isObject(value) {\n return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\nconst isObjectOrArray = (obj) => typeof obj === \"object\" && obj !== null;\n//#endregion\n//#region src/error.ts\nvar BambooError = class extends Error {\n code;\n hint;\n constructor(code, message, opts) {\n super(message, { cause: opts?.cause });\n this.code = `ERR_BAMBOO_${code}`;\n this.hint = opts?.hint;\n }\n};\n//#endregion\n//#region src/memo.ts\n/**\n* Bounded argument memo used by the generated runtime (`css`, patterns, `cva`, recipes).\n*\n* Two regimes, picked per call:\n*\n* - Arguments that are flat (objects of primitives) take a cheap structural hash\n* and are confirmed with an exact comparison, so a hash collision can never\n* serve the wrong result. This is the shape `css({ ... })` has.\n* - Anything nested falls back to `JSON.stringify`, which V8 does faster than a\n* JS walk.\n*\n* The second point is the counter-intuitive one, and it has been measured rather\n* than assumed. Extending the structural hash to recurse — so nested styles could\n* take the fast path too — is *slower*, because it trades one native serialization\n* for two JS walks (hash, then the deep equality that confirms it). Over 10k\n* iterations per shape:\n*\n* shape stringify recursive hash + deep equal\n* flat 1.06ms 2.09ms\n* _hover 1.00ms 2.16ms\n* responsive 1.23ms 2.15ms\n* realistic 2.32ms 5.84ms\n* nested 3 deep 1.22ms 2.35ms\n*\n* So a nested `css()` call costing several times a flat one is not a defect here.\n* It is the floor for a value-keyed memo in JS, and the way to avoid it is to not\n* make the call — see the build-time fold in `@bamboocss/vite`.\n*\n* Both regimes key on *values*, never on object identity: mutating a style object\n* between calls changes its hash, so the next call misses and recomputes rather\n* than serving a stale class. Keying nested arguments on the identity of the inner\n* objects would skip serialization entirely, but it cannot detect a mutation, and\n* \"same object, different contents\" is exactly what a style object built per render\n* looks like.\n*\n* Both caches are bounded. An unbounded memo is a leak in any long-lived process\n* (SSR), where the set of distinct style objects grows without limit.\n*/\n/**\n* Distinct hashes held per memoized function before the cache rotates.\n*\n* This bounds *buckets*, not entries: a bucket keeps up to `MAX_BUCKET` colliding\n* argument lists, so the ceiling is `MAX_ENTRIES * MAX_BUCKET` live entries, and\n* twice that across both generations, since the previous one is retained until the\n* next rotation. Collisions are rare in practice, so the realistic figure is close\n* to `MAX_ENTRIES` — but the worst case is what matters when sizing a long-lived\n* process, so state it plainly.\n*\n* Rotation beats evicting the oldest key: single-key eviction is worst-case for a\n* working set that cycles, because it drops exactly the entry about to be needed.\n* Measured on a cycling set of 20k styles, one-at-a-time eviction cost ~719ns/op\n* against ~189ns unbounded, while rotation holds ~274ns. On realistic skewed\n* access rotation is at or below the unbounded cost.\n*/\nconst MAX_ENTRIES = 1e3;\n/** Entries kept per hash bucket, to bound the cost of a collision scan. */\nconst MAX_BUCKET = 8;\n/**\n* DJB2 over the arguments' own keys and primitive values.\n* Returns `null` for anything nested, which routes the call to the string key.\n*/\nconst flatHashOrNull = (args) => {\n let h = 5381;\n for (let a = 0; a < args.length; a++) {\n const obj = args[a];\n if (obj === null || typeof obj !== \"object\") {\n const t = typeof obj;\n if (t === \"string\") for (let i = 0; i < obj.length; i++) h = h * 33 ^ obj.charCodeAt(i);\n else if (t === \"number\") h = h * 33 ^ (obj | 0);\n else if (t === \"boolean\") h = h * 33 ^ (obj ? 991 : 997);\n else h = h * 33 ^ 3;\n continue;\n }\n if (Array.isArray(obj)) return null;\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) return null;\n for (const k in obj) {\n const v = obj[k];\n const tv = typeof v;\n if (v !== null && tv === \"object\") return null;\n for (let i = 0; i < k.length; i++) h = h * 33 ^ k.charCodeAt(i);\n if (tv === \"string\") for (let i = 0; i < v.length; i++) h = h * 33 ^ v.charCodeAt(i);\n else if (tv === \"number\") h = h * 33 ^ (v | 0);\n else if (tv === \"boolean\") h = h * 33 ^ (v ? 991 : 997);\n else h = h * 33 ^ 2;\n }\n }\n return h >>> 0;\n};\n/**\n* Value snapshot of the arguments, taken once at insert.\n*\n* The cache must not hold the caller's objects: a style object can capture a much\n* larger graph, and keeping it alive until the cache rotates changes GC behaviour\n* for code that never asked to be cached. Only the flat path reaches here, so a\n* shallow copy contains primitives only and retains nothing.\n*\n* Comparing against a copy also removes the last way a mutation could be missed.\n* Were the caller's own object stored, `oa === ob` would short-circuit the value\n* comparison, and a mutation that happened to preserve the hash would return the\n* stale entry. Against a copy that check can only ever be true for equal\n* primitives.\n*/\nconst snapshotArgs = (args) => {\n const values = [];\n const counts = [];\n for (let i = 0; i < args.length; i++) {\n const o = args[i];\n if (o !== null && typeof o === \"object\") {\n const copy = Array.isArray(o) ? [] : {};\n let n = 0;\n for (const k in o) {\n copy[k] = o[k];\n n++;\n }\n values.push(copy);\n counts.push(n);\n } else {\n values.push(o);\n counts.push(0);\n }\n }\n return {\n values,\n counts\n };\n};\n/**\n* Exact match, so a `flatHashOrNull` collision is resolved rather than trusted.\n* `bCounts` is the cached side's key count; comparing against it avoids the\n* `Object.keys()` allocation this would otherwise make on every cache hit.\n*/\nconst flatArgsEqual = (a, b, bCounts) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const oa = a[i];\n const ob = b[i];\n if (oa === ob) continue;\n if (oa === null || ob === null || typeof oa !== \"object\" || typeof ob !== \"object\") return false;\n if (Array.isArray(oa) !== Array.isArray(ob)) return false;\n let n = 0;\n for (const k in oa) {\n if (oa[k] !== ob[k]) return false;\n n++;\n }\n if (n !== bCounts[i]) return false;\n }\n return true;\n};\nconst memo = (fn) => {\n let buckets = /* @__PURE__ */ new Map();\n let priorBuckets = /* @__PURE__ */ new Map();\n let strings = /* @__PURE__ */ new Map();\n let priorStrings = /* @__PURE__ */ new Map();\n /**\n * One scalar argument, keyed directly.\n *\n * This is the shape of the hottest callers — `isCssProperty(prop)` runs per prop\n * per render — and a plain map lookup beats hashing, bucket scanning and\n * snapshotting for it. Distinct types stay distinct keys, so `1` and `'1'` do not\n * share an entry.\n */\n let scalars = /* @__PURE__ */ new Map();\n let priorScalars = /* @__PURE__ */ new Map();\n const scan = (bucket, args) => {\n if (bucket) for (let i = 0; i < bucket.length; i++) {\n const entry = bucket[i];\n if (flatArgsEqual(args, entry.values, entry.counts)) return entry;\n }\n };\n const get = (...args) => {\n if (args.length === 1) {\n const only = args[0];\n if (only === null || typeof only !== \"object\") {\n if (scalars.has(only)) return scalars.get(only);\n if (priorScalars.has(only)) {\n const promoted = priorScalars.get(only);\n scalars.set(only, promoted);\n return promoted;\n }\n const out = fn(only);\n scalars.set(only, out);\n if (scalars.size > MAX_ENTRIES) {\n priorScalars = scalars;\n scalars = /* @__PURE__ */ new Map();\n }\n return out;\n }\n }\n const hash = flatHashOrNull(args);\n if (hash !== null) {\n let bucket = buckets.get(hash);\n const hit = scan(bucket, args);\n if (hit) return hit.out;\n const priorHit = scan(priorBuckets.get(hash), args);\n if (priorHit) {\n if (!bucket) {\n bucket = [];\n buckets.set(hash, bucket);\n }\n bucket.push(priorHit);\n if (bucket.length > MAX_BUCKET) bucket.shift();\n return priorHit.out;\n }\n const snap = snapshotArgs(args);\n const out = fn(...args);\n if (!bucket) {\n bucket = [];\n buckets.set(hash, bucket);\n }\n bucket.push({\n values: snap.values,\n counts: snap.counts,\n out\n });\n if (bucket.length > MAX_BUCKET) bucket.shift();\n if (buckets.size > MAX_ENTRIES) {\n priorBuckets = buckets;\n buckets = /* @__PURE__ */ new Map();\n }\n return out;\n }\n const key = JSON.stringify(args);\n if (strings.has(key)) return strings.get(key);\n if (priorStrings.has(key)) {\n const promoted = priorStrings.get(key);\n strings.set(key, promoted);\n return promoted;\n }\n const out = fn(...args);\n strings.set(key, out);\n if (strings.size > MAX_ENTRIES) {\n priorStrings = strings;\n strings = /* @__PURE__ */ new Map();\n }\n return out;\n };\n return get;\n};\n//#endregion\n//#region src/merge-props.ts\nconst MERGE_OMIT = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\"\n]);\nfunction mergeProps(...sources) {\n return sources.reduce((prev, obj) => {\n if (!obj) return prev;\n Object.keys(obj).forEach((key) => {\n if (MERGE_OMIT.has(key)) return;\n const prevValue = prev[key];\n const value = obj[key];\n if (isObject(prevValue) && isObject(value)) prev[key] = mergeProps(prevValue, value);\n else prev[key] = value;\n });\n return prev;\n }, {});\n}\n//#endregion\n//#region src/walk-object.ts\nconst isNotNullish = (element) => element != null;\nfunction walkObject(target, predicate, options = {}) {\n const { stop, getKey } = options;\n function inner(value, path = []) {\n if (isObjectOrArray(value)) {\n const result = {};\n for (const [prop, child] of Object.entries(value)) {\n const key = getKey?.(prop, child) ?? prop;\n const childPath = [...path, key];\n if (stop?.(value, childPath)) return predicate(value, path);\n const next = inner(child, childPath);\n if (isNotNullish(next)) result[key] = next;\n }\n return result;\n }\n return predicate(value, path);\n }\n return inner(target);\n}\nfunction mapObject(obj, fn) {\n if (Array.isArray(obj)) return obj.map((value) => fn(value));\n if (!isObject(obj)) return fn(obj);\n return walkObject(obj, (value) => fn(value));\n}\n//#endregion\n//#region src/normalize-style-object.ts\n/**\n* Whether walking the object would only rebuild it.\n*\n* Normalizing does two things: it renames a shorthand to its longhand and drops nullish\n* leaves. A flat object of plain values written in longhand needs neither, and that is most\n* of what `css()` is handed — but it still paid for a full rebuild plus a path array per key.\n*\n* Every clause has to be exact, since a false positive returns an object the walk would have\n* changed. Nullish is one of them: a leaf the walk removes must not survive, or a later merge\n* would see it override the value beneath it. The array check is another, and it is on the\n* container as well as the values — `stop` is handed the container, so an array arriving at\n* the top level has to reach the walk to be rejected rather than being returned as it came.\n*\n* `for...in` reads inherited keys the walk ignores, which is safe in the only direction it can\n* be wrong — an extra key can send this to the slow path, never past it.\n*\n* It does read every value, as `compactStyles` and the argument memo already do, so an\n* accessor prop is read once more than before. Style props are values by the time they get\n* here and reading one has no effect, but it is the reason this cannot be reordered to read\n* lazily.\n*/\nfunction needsNoNormalizing(styles, resolveShorthand) {\n if (Array.isArray(styles)) return false;\n for (const key in styles) {\n const value = styles[key];\n if (value == null || typeof value === \"object\") return false;\n if (resolveShorthand !== void 0 && resolveShorthand(key) !== key) return false;\n }\n return true;\n}\n/**\n* The result may be the argument itself rather than a fresh object, so callers have to treat\n* it as read-only. Every one of them does today: merging accumulates into its own object and\n* the two `raw()` helpers clone at the boundary.\n*\n* An array is not a style value. It used to be read as one value per breakpoint, which meant\n* a font stack written the way CSS writes one — `['Inter', 'sans-serif']` — silently became\n* `Inter` at base and `sans-serif` at `sm`. The type no longer admits an array, so reaching\n* this throw takes a cast or untyped javascript; it says which property, since the walk knows\n* the path and the caller usually does not.\n*/\nfunction normalizeStyleObject(styles, context, shorthand = true) {\n const { utility } = context;\n const { hasShorthand, resolveShorthand } = utility;\n if (needsNoNormalizing(styles, shorthand && hasShorthand ? resolveShorthand : void 0)) return styles;\n return walkObject(styles, (value, path) => {\n if (Array.isArray(value)) throw new BambooError(\"INVALID_STYLE_VALUE\", `An array is not a style value${path.length ? `: \"${path.join(\".\")}\"` : \"\"}.`, { hint: \"Write a responsive value as a condition object, e.g. { base: \\\"medium\\\", lg: \\\"bold\\\" }.\" });\n return value;\n }, {\n stop: (value) => Array.isArray(value),\n getKey: shorthand ? (prop) => hasShorthand ? resolveShorthand(prop) : prop : void 0\n });\n}\n//#endregion\n//#region src/classname.ts\n/**\n* Whether a style object carries anything `compact` would have kept.\n*\n* The question `compactStyles` asks is only ever \"is this empty once undefined values are\n* dropped\", but it used to answer it by building the compacted object and then a key array\n* for it, then throwing both away. `Object.keys` enumerates exactly what `compact`'s\n* `Object.entries` did — own, enumerable, string-keyed — so this is the same predicate\n* without the two allocations, and it stops at the first value that settles it.\n*/\nfunction hasDefinedValue(style) {\n const keys = Object.keys(style);\n for (let i = 0; i < keys.length; i++) if (style[keys[i]] !== void 0) return true;\n return false;\n}\n/**\n* An array is not a style argument.\n*\n* `css([a, b])` used to mean `css(a, b)`, flattened here one level. Two spellings of one\n* call is the redundancy; the array one also cost a `flat()` allocation on every merge to\n* serve a shape almost nothing wrote, and read as a responsive array everywhere that had\n* not been taught to flatten it first.\n*\n* It throws rather than being filtered out as a non-object, which is what dropping the\n* `flat()` alone would have done — silently returning no class at all.\n*/\nfunction compactStyles(...styles) {\n return styles.filter((style) => {\n if (Array.isArray(style)) throw new BambooError(\"INVALID_STYLE_ARGUMENT\", \"An array is not a style argument.\", { hint: \"Spread it instead, e.g. css(...styles) rather than css(styles).\" });\n return isObject(style) && hasDefinedValue(style);\n });\n}\nfunction createMergeCss(context) {\n function resolve(styles) {\n const allStyles = compactStyles(...styles);\n if (allStyles.length === 1) return allStyles;\n return allStyles.map((style) => normalizeStyleObject(style, context));\n }\n function mergeCss(...styles) {\n return mergeProps(...resolve(styles));\n }\n return {\n mergeCss: memo(mergeCss),\n mergeCssUncached: mergeCss\n };\n}\n//#endregion\n//#region src/clone-styles.ts\nconst OMIT = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\"\n]);\n/**\n* Independent copy of a style object, nested condition blocks included.\n*\n* Merged style objects are cached, so anything handed to user code has to be\n* copied first: a caller mutating what it received would otherwise change what\n* every later caller reads back. `css.raw()` and `cva.raw()` are those boundaries.\n*\n* Kept separate from `mergeProps` deliberately. Merging is on the hot path — it\n* runs on every `css()` cache miss and on every render of a pattern component\n* under `jsxStyleProps: 'minimal'` — and copying there charges every caller for a\n* guarantee only the two `raw()` helpers need. Measured on a realistic style\n* object (5 base properties, 4 condition blocks) that was roughly twice the cost\n* of merging alone.\n*/\nfunction cloneStyles(styles) {\n if (Array.isArray(styles)) return styles.map((value) => cloneStyles(value));\n if (!isObject(styles)) return styles;\n const out = {};\n for (const key of Object.keys(styles)) {\n if (OMIT.has(key)) continue;\n out[key] = cloneStyles(styles[key]);\n }\n return out;\n}\n//#endregion\n//#region src/compact.ts\nfunction compact(value) {\n return Object.fromEntries(Object.entries(value ?? {}).filter(([_, value]) => value !== void 0));\n}\n//#endregion\n//#region src/is-css-function.ts\nconst fnRegExp = new RegExp(`^(${[\n \"min\",\n \"max\",\n \"clamp\",\n \"calc\"\n].join(\"|\")})\\\\(.*\\\\)`);\nconst isCssFunction = (v) => typeof v === \"string\" && fnRegExp.test(v);\n//#endregion\n//#region src/is-css-unit.ts\nconst lengthUnitsPattern = `(?:${\"cm,mm,Q,in,pc,pt,px,em,ex,ch,rem,lh,rlh,vw,vh,vmin,vmax,vb,vi,svw,svh,lvw,lvh,dvw,dvh,cqw,cqh,cqi,cqb,cqmin,cqmax,%\".split(\",\").join(\"|\")})`;\nconst lengthRegExp = new RegExp(`^[+-]?[0-9]*.?[0-9]+(?:[eE][+-]?[0-9]+)?${lengthUnitsPattern}$`);\nconst isCssUnit = (v) => typeof v === \"string\" && lengthRegExp.test(v);\n//#endregion\n//#region src/is-css-var.ts\nconst isCssVar = (v) => typeof v === \"string\" && /^var\\(--.+\\)$/.test(v);\n//#endregion\n//#region src/pattern-fns.ts\nconst createPatternFns = (token) => ({\n map: mapObject,\n isCssFunction,\n isCssVar,\n isCssUnit,\n token\n});\nconst getPatternStyles = (pattern, styles) => {\n if (!pattern?.defaultValues) return styles;\n const defaults = typeof pattern.defaultValues === \"function\" ? pattern.defaultValues(styles) : pattern.defaultValues;\n return Object.assign({}, defaults, compact(styles));\n};\n//#endregion\n//#region src/split-props.ts\n/**\n* Move one key into a bucket, keeping whatever about it is observable.\n*\n* Shared by both paths below so there is one implementation of the descriptor rules rather\n* than two to keep in step. The rules themselves are documented on `splitProps`.\n*/\nconst copyKey = (props, target, key) => {\n const descriptor = Object.getOwnPropertyDescriptor(props, key);\n if (!descriptor) return false;\n if (\"get\" in descriptor || \"set\" in descriptor || !descriptor.enumerable || key === \"__proto__\") Object.defineProperty(target, key, descriptor);\n else target[key] = descriptor.value;\n return true;\n};\n/**\n* One array group, which is what every call site in this project passes — a recipe's\n* `variantKeys`.\n*\n* The general path below is built for several groups that may be predicates, and pays for\n* that shape on every call: a closure per group, a `map` and a `concat` to assemble the\n* result, and a branch per group to tell an array from a predicate. None of it is reachable\n* with one array group.\n*\n* What it does *not* skip is the part that looks skippable. `own` stays, because membership\n* has to be answered from `ownKeys` rather than by asking the object: on a proxy — which is\n* what Solid's `mergeProps` hands over — every question is a trap, and a recipe naming eight\n* variants would otherwise fire eight traps to learn what one `ownKeys` already said. And\n* the two passes stay separate, because the group bucket is in *group* order while the rest\n* bucket is in *props* order, and that ordering reaches the emitted CSS.\n*/\nconst splitOneGroup = (props, allKeys, group) => {\n const own = new Set(allKeys);\n const taken = /* @__PURE__ */ new Set();\n const picked = {};\n for (let i = 0; i < group.length; i++) {\n const key = group[i];\n if (taken.has(key) || !own.has(key)) continue;\n if (copyKey(props, picked, key)) taken.add(key);\n }\n const rest = {};\n for (let i = 0; i < allKeys.length; i++) {\n const key = allKeys[i];\n if (taken.has(key)) continue;\n copyKey(props, rest, key);\n }\n return [picked, rest];\n};\n/**\n* Deal a props object into one bucket per key group, plus a final bucket for the rest.\n* A key goes to the first group that claims it.\n*\n* ## Why the descriptor is read per key rather than in bulk\n*\n* This used to call `Object.getOwnPropertyDescriptors` for the whole object and\n* `defineProperty` for every key it moved. Copying plain values instead is 2.4–2.9x faster\n* on the shapes that allow it, but it is only correct where props are data — and they are\n* not always. Solid compiles props to accessors, so reading one eagerly runs whatever it\n* wraps: splitting a component's props would construct its children before the surrounding\n* provider exists.\n*\n* So the descriptor is fetched per key, and the value path is taken only when it changes\n* nothing observable. An accessor keeps its laziness, a non-enumerable key keeps its\n* invisibility, and `__proto__` is defined rather than assigned so it stays an own\n* property instead of reaching the prototype setter.\n*\n* The one thing the value path drops is `writable`/`configurable`, so a bucket key taken\n* from frozen props is writable where it used to be frozen. Nothing here relies on that,\n* and preserving it would mean `defineProperty` on the common path — the cost this exists\n* to avoid. Keys that take the descriptor path keep theirs, so a bucket can be\n* inconsistent in that one respect.\n*\n* Key order within a bucket is preserved exactly. It is not cosmetic: `cva` merges\n* variant props in iteration order, and the parser reads the rest bucket as the style\n* props it encodes, so order reaches the emitted CSS.\n*/\nfunction splitProps(props, ...keys) {\n const allKeys = Object.getOwnPropertyNames(props);\n if (keys.length === 1 && Array.isArray(keys[0])) return splitOneGroup(props, allKeys, keys[0]);\n const own = new Set(allKeys);\n const taken = /* @__PURE__ */ new Set();\n const split = (group) => {\n const clone = {};\n for (let i = 0; i < group.length; i++) {\n const key = group[i];\n if (taken.has(key) || !own.has(key)) continue;\n if (copyKey(props, clone, key)) taken.add(key);\n }\n return clone;\n };\n /**\n * The predicate is called with the key alone.\n *\n * Handing it to `filter` passes `(key, index, allKeys)`. A one-parameter predicate cannot\n * see the extras, but a memoized one reads its whole argument list — and the predicates\n * that arrive here are memoized, `isCssProperty` among them. So the memo hashed the entire\n * key array once per prop, and keyed its cache on it: two elements with different prop sets\n * shared no entry even for the same prop name.\n *\n * Worth ~9.7x on that path, and nothing at all on a plain predicate — which is why the\n * bench below it needs a memoized case to see this at all.\n *\n * A loop rather than `filter((k) => key(k))` because the wrapper allocates a closure per\n * group. The two measure the same to within noise; the loop just does not need one.\n */\n const matching = (predicate) => {\n const group = [];\n for (let i = 0; i < allKeys.length; i++) {\n const key = allKeys[i];\n if (predicate(key)) group.push(key);\n }\n return group;\n };\n return keys.map((key) => split(Array.isArray(key) ? key : matching(key))).concat(split(allKeys));\n}\n//#endregion\nexport { cloneStyles, createMergeCss, createPatternFns, getPatternStyles, splitProps };\n";
|
|
543
386
|
//#endregion
|
|
544
387
|
//#region src/artifacts/js/helpers.ts
|
|
545
388
|
function generateHelpers() {
|
|
@@ -777,66 +620,10 @@ function generateMixinsSpec$1(theme) {
|
|
|
777
620
|
}
|
|
778
621
|
//#endregion
|
|
779
622
|
//#region src/artifacts/js/recipe.ts
|
|
780
|
-
const stringify$2 = (value) => JSON.stringify(value, null, 2);
|
|
781
623
|
const hasOwn = (obj, key) => {
|
|
782
624
|
if (!obj) return false;
|
|
783
625
|
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
784
626
|
};
|
|
785
|
-
function generateCreateRecipe(ctx) {
|
|
786
|
-
const { recipes, prefix, hash, utility } = ctx;
|
|
787
|
-
if (recipes.isEmpty()) return;
|
|
788
|
-
return {
|
|
789
|
-
name: "create-recipe",
|
|
790
|
-
dts: "",
|
|
791
|
-
js: outdent.outdent`
|
|
792
|
-
${ctx.file.import(hash.className ? "compact, splitProps, toHash, uniq, uncompiledStyle" : "compact, splitProps, uniq, uncompiledStyle", "../helpers")}
|
|
793
|
-
|
|
794
|
-
const withPrefix = ${prefix.className ? `(className) => className ? ${JSON.stringify(prefix.className)} + '-' + className : ${JSON.stringify(prefix.className)}` : `(className) => className`}
|
|
795
|
-
export const formatRecipeClass = ${hash.className ? `(className) => withPrefix((${utility.toHash})([className], toHash))` : `withPrefix`}
|
|
796
|
-
|
|
797
|
-
export const createRecipe = (name, defaultVariants, _compoundVariants, _variantMap) => {
|
|
798
|
-
const getVariantProps = (variants) => {
|
|
799
|
-
return {
|
|
800
|
-
[name]: '__ignore__',
|
|
801
|
-
...defaultVariants,
|
|
802
|
-
...compact(variants),
|
|
803
|
-
};
|
|
804
|
-
};
|
|
805
|
-
|
|
806
|
-
const recipeFn = (_variants) => uncompiledStyle(name)
|
|
807
|
-
|
|
808
|
-
return {
|
|
809
|
-
recipeFn,
|
|
810
|
-
getVariantProps,
|
|
811
|
-
__getCompoundVariantCss__: (_variants) => uncompiledStyle(name),
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
export const mergeRecipes = (recipeA, recipeB) => {
|
|
816
|
-
if (recipeA && !recipeB) return recipeA
|
|
817
|
-
if (!recipeA && recipeB) return recipeB
|
|
818
|
-
|
|
819
|
-
const recipeFn = (..._args) => uncompiledStyle(recipeA.__name__ || 'recipe')
|
|
820
|
-
const variantKeys = uniq(Object.keys(recipeA.variantMap), Object.keys(recipeB.variantMap))
|
|
821
|
-
const variantMap = variantKeys.reduce((acc, key) => {
|
|
822
|
-
acc[key] = uniq(recipeA.variantMap[key], recipeB.variantMap[key])
|
|
823
|
-
return acc
|
|
824
|
-
}, {})
|
|
825
|
-
|
|
826
|
-
return Object.assign(recipeFn, {
|
|
827
|
-
__recipe__: true,
|
|
828
|
-
__name__: \`$\{recipeA.__name__} \${recipeB.__name__}\`,
|
|
829
|
-
raw: (props) => props,
|
|
830
|
-
variantMap,
|
|
831
|
-
splitVariantProps(props) {
|
|
832
|
-
return splitProps(props, variantKeys)
|
|
833
|
-
},
|
|
834
|
-
})
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
`
|
|
838
|
-
};
|
|
839
|
-
}
|
|
840
627
|
function generateRecipes(ctx, filters) {
|
|
841
628
|
const { recipes } = ctx;
|
|
842
629
|
if (recipes.isEmpty()) return;
|
|
@@ -850,117 +637,19 @@ function generateRecipes(ctx, filters) {
|
|
|
850
637
|
else defaultValue = JSON.stringify(defaultValue);
|
|
851
638
|
return ctx.file.jsDocComment("", { default: defaultValue });
|
|
852
639
|
};
|
|
853
|
-
const slotNames = _bamboocss_core.Recipes.isSlotRecipeConfig(config) ? config.slots : [];
|
|
854
|
-
const anchorSlotNames = _bamboocss_core.Recipes.isSlotRecipeConfig(config) ? _bamboocss_core.Recipes.getScopeRoots(config) : [];
|
|
855
640
|
return {
|
|
856
641
|
name: dashName,
|
|
857
|
-
js:
|
|
858
|
-
|
|
859
|
-
/**
|
|
860
|
-
* Which slots each variant writes styles for.
|
|
861
|
-
*
|
|
862
|
-
* A scope reaches every slot inside an anchor's subtree. A slot under no anchor at
|
|
863
|
-
* all is not reached, and nothing here can detect that — reachability is a fact
|
|
864
|
-
* about the DOM. This is what says which slots a variant has to get to, so the
|
|
865
|
-
* component layer can thread the ones a scope cannot.
|
|
866
|
-
*/
|
|
867
|
-
const slotsAffectedBy = Object.fromEntries(Object.entries(config.variants ?? {}).map(([variant, values]) => [variant, Array.from(new Set(Object.values(values ?? {}).flatMap((slotStyles) => Object.keys(slotStyles ?? {}))))]));
|
|
868
|
-
return outdent.outdent`
|
|
869
|
-
${ctx.file.import("compact, getSlotCompoundVariant, memo, splitProps", "../helpers")}
|
|
870
|
-
${ctx.file.import("createRecipe, formatRecipeClass", "./create-recipe")}
|
|
871
|
-
|
|
872
|
-
const ${baseName}DefaultVariants = ${stringify$2(defaultVariants ?? {})}
|
|
873
|
-
const ${baseName}CompoundVariants = ${stringify$2(compoundVariants ?? [])}
|
|
874
|
-
|
|
875
|
-
// Formatted, not raw. A scoped slot's class is a constant that never passes through
|
|
876
|
-
// \`createCss\`, so \`hash.className\` and \`prefix\` have to be applied here to match
|
|
877
|
-
// the rule the stylesheet emits.
|
|
878
|
-
const ${baseName}SlotNames = ${stringify$2(config.slots.map((slot) => [slot, `${config.className}__${slot}`]))}.map(
|
|
879
|
-
([slotName, className]) => [slotName, formatRecipeClass(className)],
|
|
880
|
-
)
|
|
881
|
-
${anchors.length ? outdent.outdent`
|
|
882
|
-
/**
|
|
883
|
-
* Only the anchors take variants: ${anchors.map((slot) => `\`${baseName}.${slot}\``).join(", ")}.
|
|
884
|
-
* Every other slot's variant styles are emitted as rules scoped by a class an anchor
|
|
885
|
-
* carries, so that slot's class is a constant and nothing has to reach it at runtime.
|
|
886
|
-
*/
|
|
887
|
-
const ${baseName}Anchors = ${JSON.stringify(anchors)}
|
|
888
|
-
const ${baseName}AnchorFns = /* @__PURE__ */ ${baseName}Anchors.map((slotName) => [slotName, createRecipe(\`${config.className}__\${slotName}\`, ${baseName}DefaultVariants, getSlotCompoundVariant(${baseName}CompoundVariants, slotName), ${stringify$2(variantKeyMap)})])
|
|
889
|
-
const ${baseName}StaticSlots = /* @__PURE__ */ Object.fromEntries(
|
|
890
|
-
${baseName}SlotNames.filter(([slotName]) => !${baseName}Anchors.includes(slotName)),
|
|
891
|
-
)
|
|
892
|
-
|
|
893
|
-
const ${baseName}Fn = memo((props = {}) => ({
|
|
894
|
-
...${baseName}StaticSlots,
|
|
895
|
-
...Object.fromEntries(${baseName}AnchorFns.map(([slotName, anchorFn]) => [slotName, anchorFn.recipeFn(props)])),
|
|
896
|
-
}))` : outdent.outdent`
|
|
897
|
-
/**
|
|
898
|
-
* Raw, not the formatted name. \`createRecipe\` routes what it is given through
|
|
899
|
-
* \`createCss\`, which applies \`hash.className\` and \`prefix.className\` itself — so
|
|
900
|
-
* passing the already formatted \`slotKey\` applied both a second time. The runtime
|
|
901
|
-
* asked for \`toHash(toHash(name))\` while the stylesheet emitted \`toHash(name)\`, and
|
|
902
|
-
* every slot on such a recipe rendered unstyled.
|
|
903
|
-
*
|
|
904
|
-
* Invisible only when neither \`hash\` nor \`prefix\` is set, where both applications
|
|
905
|
-
* are identities. A prefixed build was equally broken — \`bam-bam-menu__trigger\`
|
|
906
|
-
* against a stylesheet emitting \`.bam-menu__trigger\` — which is easy to miss, since
|
|
907
|
-
* the obvious reading is that this is a hashing problem.
|
|
908
|
-
*/
|
|
909
|
-
const ${baseName}SlotFns = /* @__PURE__ */ ${baseName}SlotNames.map(([slotName]) => [slotName, createRecipe(\`${config.className}__\${slotName}\`, ${baseName}DefaultVariants, getSlotCompoundVariant(${baseName}CompoundVariants, slotName), ${stringify$2(variantKeyMap)})])
|
|
910
|
-
|
|
911
|
-
const ${baseName}Fn = memo((props = {}) => {
|
|
912
|
-
return Object.fromEntries(${baseName}SlotFns.map(([slotName, slotFn]) => [slotName, slotFn.recipeFn(props)]))
|
|
913
|
-
})`}
|
|
914
|
-
|
|
915
|
-
const ${baseName}VariantKeys = ${stringify$2(Object.keys(variantKeyMap))}
|
|
916
|
-
const getVariantProps = (variants) => ({ ...${baseName}DefaultVariants, ...compact(variants) })
|
|
917
|
-
|
|
918
|
-
export const ${baseName} = /* @__PURE__ */ Object.assign(${baseName}Fn, {
|
|
919
|
-
__recipe__: false,
|
|
920
|
-
__name__: '${baseName}',
|
|
921
|
-
raw: (props) => props,
|
|
922
|
-
/** Each slot's constant class, for targeting a slot in the DOM. */
|
|
923
|
-
classNameMap: /* @__PURE__ */ Object.fromEntries(${baseName}SlotNames),
|
|
924
|
-
/** The slots that enclose other slots, and so anchor their variant rules. */
|
|
925
|
-
scopeRoots: ${JSON.stringify(anchors)},
|
|
926
|
-
variantMap: ${stringify$2(variantKeyMap)},
|
|
927
|
-
/** Which slots each variant actually reaches, for a slot a scope cannot get to. */
|
|
928
|
-
slotsAffectedBy: ${stringify$2(slotsAffectedBy)},
|
|
929
|
-
splitVariantProps(props) {
|
|
930
|
-
return splitProps(props, ${baseName}VariantKeys)
|
|
931
|
-
},
|
|
932
|
-
getVariantProps,
|
|
933
|
-
${anchors.length ? outdent.outdent`
|
|
934
|
-
...Object.fromEntries(${baseName}AnchorFns.map(([slotName, anchorFn]) => [slotName, anchorFn.recipeFn])),
|
|
935
|
-
...${baseName}StaticSlots,
|
|
936
|
-
` : ""}
|
|
937
|
-
})
|
|
938
|
-
`;
|
|
939
|
-
}).otherwise((config) => outdent.outdent`
|
|
940
|
-
${ctx.file.import("memo, splitProps", "../helpers")}
|
|
941
|
-
${ctx.file.import("createRecipe, mergeRecipes", "./create-recipe")}
|
|
942
|
-
|
|
943
|
-
const ${baseName}VariantMap = ${stringify$2(variantKeyMap)}
|
|
944
|
-
|
|
945
|
-
const ${baseName}Fn = /* @__PURE__ */ createRecipe('${config.className}', ${stringify$2(defaultVariants ?? {})}, ${stringify$2(compoundVariants ?? [])}, ${baseName}VariantMap)
|
|
642
|
+
js: outdent.outdent`
|
|
643
|
+
${ctx.file.import("splitProps, uncompiledStyle", "../helpers")}
|
|
946
644
|
|
|
947
|
-
const ${baseName}VariantKeys = Object.keys(
|
|
645
|
+
const ${baseName}VariantKeys = ${JSON.stringify(Object.keys(variantKeyMap))}
|
|
948
646
|
|
|
949
|
-
export const ${baseName} = /* @__PURE__ */ Object.assign(
|
|
950
|
-
__recipe__: true,
|
|
951
|
-
__name__: '${baseName}',
|
|
952
|
-
__getCompoundVariantCss__: ${baseName}Fn.__getCompoundVariantCss__,
|
|
953
|
-
raw: (props) => props,
|
|
954
|
-
variantMap: ${baseName}VariantMap,
|
|
955
|
-
merge(recipe) {
|
|
956
|
-
return mergeRecipes(this, recipe)
|
|
957
|
-
},
|
|
647
|
+
export const ${baseName} = /* @__PURE__ */ Object.assign((_props) => uncompiledStyle(${JSON.stringify(config.className)}), {
|
|
958
648
|
splitVariantProps(props) {
|
|
959
649
|
return splitProps(props, ${baseName}VariantKeys)
|
|
960
650
|
},
|
|
961
|
-
getVariantProps: ${baseName}Fn.getVariantProps,
|
|
962
651
|
})
|
|
963
|
-
|
|
652
|
+
`,
|
|
964
653
|
dts: outdent.outdent`
|
|
965
654
|
${ctx.file.importType("ConditionalValue", "../types/index")}
|
|
966
655
|
${ctx.file.importType("DistributiveOmit, Pretty", "../types/system-types")}
|
|
@@ -973,10 +662,6 @@ function generateRecipes(ctx, filters) {
|
|
|
973
662
|
}).join("\n")}
|
|
974
663
|
}
|
|
975
664
|
|
|
976
|
-
type ${upperName}VariantMap = {
|
|
977
|
-
[key in keyof ${upperName}Variant]: Array<${upperName}Variant[key]>
|
|
978
|
-
}
|
|
979
|
-
|
|
980
665
|
${_bamboocss_core.Recipes.isSlotRecipeConfig(config) ? `type ${upperName}Slot = ${(0, _bamboocss_shared.unionType)(config.slots)}` : ""}
|
|
981
666
|
|
|
982
667
|
export type ${upperName}VariantProps = {
|
|
@@ -987,18 +672,7 @@ function generateRecipes(ctx, filters) {
|
|
|
987
672
|
${_bamboocss_core.Recipes.isSlotRecipeConfig(config) ? `__slot: ${upperName}Slot` : ""}
|
|
988
673
|
__type: ${upperName}VariantProps
|
|
989
674
|
(props?: ${upperName}VariantProps): ${_bamboocss_core.Recipes.isSlotRecipeConfig(config) ? `Pretty<Record<${upperName}Slot, string>>` : "string"}
|
|
990
|
-
raw: (props?: ${upperName}VariantProps) => ${upperName}VariantProps
|
|
991
|
-
/** Each variant and the values it accepts. \`Object.keys\` it for the variant names. */
|
|
992
|
-
variantMap: ${upperName}VariantMap
|
|
993
675
|
splitVariantProps<Props extends ${upperName}VariantProps>(props: Props): [${upperName}VariantProps, Pretty<DistributiveOmit<Props, keyof ${upperName}VariantProps>>]
|
|
994
|
-
getVariantProps: (props?: ${upperName}VariantProps) => ${upperName}VariantProps
|
|
995
|
-
${_bamboocss_core.Recipes.isSlotRecipeConfig(config) ? outdent.outdent`
|
|
996
|
-
/** Which slots each variant writes styles for. */
|
|
997
|
-
slotsAffectedBy: Record<keyof ${upperName}Variant, ${upperName}Slot[]>` : ""}
|
|
998
|
-
${anchorSlotNames.length ? outdent.outdent`
|
|
999
|
-
/** The slots that take variants — every other one is scoped by a class an anchor carries. */
|
|
1000
|
-
${anchorSlotNames.map((slot) => `${slot}: (props?: ${upperName}VariantProps) => string`).join("\n")}
|
|
1001
|
-
${slotNames.filter((slot) => !anchorSlotNames.includes(slot)).map((slot) => `${slot}: string`).join("\n")}` : ""}
|
|
1002
676
|
}
|
|
1003
677
|
|
|
1004
678
|
${ctx.file.jsDocComment(description, { deprecated })}
|
|
@@ -1009,241 +683,35 @@ function generateRecipes(ctx, filters) {
|
|
|
1009
683
|
}
|
|
1010
684
|
//#endregion
|
|
1011
685
|
//#region src/artifacts/js/sva.ts
|
|
686
|
+
/**
|
|
687
|
+
* The runtime `sva` a compiled build keeps: a callable that throws, and `splitVariantProps`.
|
|
688
|
+
*
|
|
689
|
+
* See `generateCvaFn`. The slot recipe carried the same unreachable engine, plus
|
|
690
|
+
* `classNameMap`, `slotsAffectedBy` and `scopeRoots` for `auditSlotScopes` — which took the
|
|
691
|
+
* recipe object as an argument, and passing it is itself a `runtime-binding`, so the audit
|
|
692
|
+
* could not be called from any build that compiled. It is removed with them. The Vite compiler
|
|
693
|
+
* returns complete atom strings for every slot and emits no `@scope` rules, so there is no
|
|
694
|
+
* unreachable-slot failure left for it to report.
|
|
695
|
+
*/
|
|
1012
696
|
function generateSvaFn(ctx) {
|
|
1013
697
|
return {
|
|
1014
698
|
js: outdent.outdent`
|
|
1015
|
-
${ctx.file.import("
|
|
1016
|
-
${ctx.file.import("cva, formatRecipeClass", "./cva")}
|
|
1017
|
-
${ctx.file.import("cx", "./cx")}
|
|
699
|
+
${ctx.file.import("splitProps, uncompiledStyle", "../helpers")}
|
|
1018
700
|
|
|
1019
701
|
export function sva(config) {
|
|
1020
|
-
|
|
1021
|
-
// \`getSlotRecipes\`, a config with no \`className\` gives every slot the bare slot name
|
|
1022
|
-
// — \`root\` — which every other anonymous recipe with a \`root\` slot would share. The
|
|
1023
|
-
// build injects the identity at the same point, for the same reason.
|
|
1024
|
-
const name = getRecipeIdentity(config, 'sva')
|
|
1025
|
-
const withName = { ...config, className: config.className ?? name }
|
|
1026
|
-
|
|
1027
|
-
const slots = Object.entries(getSlotRecipes(withName)).map(([slot, slotCva]) => [slot, cva(slotCva)])
|
|
1028
|
-
const defaultVariants = config.defaultVariants ?? {}
|
|
1029
|
-
|
|
1030
|
-
// Populated whether or not the author set a \`className\`. Every slot recipe is given
|
|
1031
|
-
// one before the split — the identity when the config declares none — so the guard
|
|
1032
|
-
// that used to sit here left an anonymous \`sva\` reporting no slot classes despite
|
|
1033
|
-
// emitting them.
|
|
1034
|
-
// Formatted, like the classes \`svaFn\` returns. Left raw, this reported the name the
|
|
1035
|
-
// element does *not* carry under \`hash\` or \`prefix\` — and \`auditSlotScopes\` builds
|
|
1036
|
-
// its selectors from this map, so the diagnostic went silent in exactly the configs
|
|
1037
|
-
// where a naming bug is likeliest.
|
|
1038
|
-
const classNameMap = slots.reduce((acc, [slot, cvaFn]) => {
|
|
1039
|
-
acc[slot] = formatRecipeClass(cvaFn.config.className)
|
|
1040
|
-
return acc
|
|
1041
|
-
}, {})
|
|
1042
|
-
|
|
1043
|
-
// The slots that enclose other slots, matching \`Recipes.getScopeRoots\`. Their variant
|
|
1044
|
-
// styles anchor \`@scope\` rules for every other slot, so only they take variants — a
|
|
1045
|
-
// variant class on any other slot would name a rule that was never emitted.
|
|
1046
|
-
//
|
|
1047
|
-
// A list, because a component can span a portal and so occupy more than one subtree.
|
|
1048
|
-
const declaredSlots = config.slots ?? []
|
|
1049
|
-
const anchors = config.scopeRoots
|
|
1050
|
-
? config.scopeRoots.filter((slot) => declaredSlots.includes(slot))
|
|
1051
|
-
: declaredSlots.includes('root') ? ['root'] : []
|
|
1052
|
-
|
|
1053
|
-
// \`classNameMap[slot]\` used to be joined on here, because the slot's classes were
|
|
1054
|
-
// atomic and nothing else carried the name to target it in the DOM. The slot's cva is
|
|
1055
|
-
// now named \`name__slot\` and returns that as its base class, so joining it again
|
|
1056
|
-
// would just repeat it.
|
|
1057
|
-
function svaFn(_props) {
|
|
1058
|
-
return uncompiledStyle('sva')
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
function raw(props) {
|
|
1062
|
-
const result = slots.map(([slot, cvaFn]) => [slot, cvaFn.raw(props)])
|
|
1063
|
-
return Object.fromEntries(result)
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
const variants = config.variants ?? {};
|
|
1067
|
-
const variantKeys = Object.keys(variants);
|
|
1068
|
-
|
|
1069
|
-
function splitVariantProps(props) {
|
|
1070
|
-
return splitProps(props, variantKeys);
|
|
1071
|
-
}
|
|
1072
|
-
const getVariantProps = (variants) => ({ ...defaultVariants, ...compact(variants) })
|
|
1073
|
-
|
|
1074
|
-
const variantMap = Object.fromEntries(
|
|
1075
|
-
Object.entries(variants).map(([key, value]) => [key, Object.keys(value)])
|
|
1076
|
-
);
|
|
1077
|
-
|
|
1078
|
-
// Which slots each variant writes styles for.
|
|
1079
|
-
//
|
|
1080
|
-
// A scope reaches every slot inside an anchor's subtree. A slot under no anchor is
|
|
1081
|
-
// not reached, and nothing at build time can detect that — reachability is a fact
|
|
1082
|
-
// about the DOM. This is what says which slots a variant has to get to, so the
|
|
1083
|
-
// component layer can thread the ones a scope cannot. Config slot recipes have always
|
|
1084
|
-
// exposed it; an inline \`sva\` had no way to answer the question at all.
|
|
1085
|
-
const slotsAffectedBy = Object.fromEntries(
|
|
1086
|
-
Object.entries(variants).map(([variant, values]) => [
|
|
1087
|
-
variant,
|
|
1088
|
-
[...new Set(Object.values(values ?? {}).flatMap((slotStyles) => Object.keys(slotStyles ?? {})))],
|
|
1089
|
-
])
|
|
1090
|
-
);
|
|
1091
|
-
|
|
1092
|
-
return Object.assign(memo(svaFn), {
|
|
1093
|
-
__cva__: false,
|
|
1094
|
-
raw,
|
|
1095
|
-
config,
|
|
1096
|
-
variantMap,
|
|
1097
|
-
classNameMap,
|
|
1098
|
-
/** The slots that enclose other slots, and so anchor their variant rules. */
|
|
1099
|
-
scopeRoots: anchors,
|
|
1100
|
-
slotsAffectedBy,
|
|
1101
|
-
splitVariantProps,
|
|
1102
|
-
getVariantProps,
|
|
1103
|
-
})
|
|
1104
|
-
}
|
|
1105
|
-
|
|
1106
|
-
/**
|
|
1107
|
-
* Report slots whose variant styles can never reach them.
|
|
1108
|
-
*
|
|
1109
|
-
* A scoped slot is styled through an \`@scope\` rule opened at an anchor, so it has to be
|
|
1110
|
-
* rendered inside one. A slot moved out of every anchor's subtree — through a portal,
|
|
1111
|
-
* with no second anchor named in \`scopeRoots\` — keeps its base styles and silently
|
|
1112
|
-
* loses its variant styles. That renders *nearly* right, which is harder to notice than
|
|
1113
|
-
* a total failure, and no build step can catch it: whether one element is inside another
|
|
1114
|
-
* is a fact about the DOM.
|
|
1115
|
-
*
|
|
1116
|
-
* Checks for the anchor's *base* class rather than its variant class. An anchor always
|
|
1117
|
-
* carries the base one; the variant class is absent whenever no variant is selected, and
|
|
1118
|
-
* matching on it would report a slot that is correctly placed and simply unstyled.
|
|
1119
|
-
*
|
|
1120
|
-
* Development only — call it behind \`process.env.NODE_ENV !== 'production'\` so bundlers
|
|
1121
|
-
* drop it, along with this function, from your production build.
|
|
1122
|
-
*
|
|
1123
|
-
* \`\`\`js
|
|
1124
|
-
* import { auditSlotScopes, select } from '../styled-system/css'
|
|
1125
|
-
*
|
|
1126
|
-
* if (process.env.NODE_ENV !== 'production') auditSlotScopes([select], { observe: true })
|
|
1127
|
-
* \`\`\`
|
|
1128
|
-
*/
|
|
1129
|
-
export function auditSlotScopes(recipes, options = {}) {
|
|
1130
|
-
const { root = typeof document === 'undefined' ? undefined : document, observe = false, onReport } = options
|
|
1131
|
-
if (!root) return () => {}
|
|
1132
|
-
|
|
1133
|
-
const escape = (value) =>
|
|
1134
|
-
typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : value.replace(/[^\\w-]/g, '\\\\$&')
|
|
1135
|
-
|
|
1136
|
-
const audit = () => {
|
|
1137
|
-
const found = []
|
|
702
|
+
const variantKeys = Object.keys(config?.variants ?? {})
|
|
1138
703
|
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
if (!anchors.length) continue
|
|
1144
|
-
|
|
1145
|
-
const classNameMap = recipe.classNameMap ?? {}
|
|
1146
|
-
const anchorSelector = anchors
|
|
1147
|
-
.map((slot) => classNameMap[slot])
|
|
1148
|
-
.filter(Boolean)
|
|
1149
|
-
.map((className) => '.' + escape(className))
|
|
1150
|
-
.join(', ')
|
|
1151
|
-
if (!anchorSelector) continue
|
|
1152
|
-
|
|
1153
|
-
const scoped = new Set(Object.values(recipe.slotsAffectedBy ?? {}).flat())
|
|
1154
|
-
|
|
1155
|
-
for (const slot of scoped) {
|
|
1156
|
-
if (anchors.includes(slot)) continue
|
|
1157
|
-
|
|
1158
|
-
const className = classNameMap[slot]
|
|
1159
|
-
if (!className) continue
|
|
1160
|
-
|
|
1161
|
-
for (const element of root.querySelectorAll('.' + escape(className))) {
|
|
1162
|
-
if (element.closest(anchorSelector)) continue
|
|
1163
|
-
found.push({ recipe: recipe.__name__, slot, className, element, anchors })
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
if (!found.length) return found
|
|
1169
|
-
|
|
1170
|
-
if (onReport) {
|
|
1171
|
-
onReport(found)
|
|
1172
|
-
} else {
|
|
1173
|
-
for (const problem of found) {
|
|
1174
|
-
console.warn(
|
|
1175
|
-
\`[bamboo] \${problem.recipe ?? 'slot recipe'}: the \\\`\${problem.slot}\\\` slot is rendered outside every \` +
|
|
1176
|
-
\`anchor (\${problem.anchors.join(', ')}), so its variant styles cannot reach it. \` +
|
|
1177
|
-
\`Add the enclosing slot to \\\`scopeRoots\\\`, or deliver the variant to this slot by hand.\`,
|
|
1178
|
-
problem.element,
|
|
1179
|
-
)
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
return found
|
|
1184
|
-
}
|
|
1185
|
-
|
|
1186
|
-
audit()
|
|
1187
|
-
|
|
1188
|
-
if (!observe || typeof MutationObserver === 'undefined') return () => {}
|
|
1189
|
-
|
|
1190
|
-
// Portaled content mounts after the first sweep, which is exactly the case this
|
|
1191
|
-
// exists to catch, so a one-shot pass would miss it.
|
|
1192
|
-
let queued = false
|
|
1193
|
-
const observer = new MutationObserver(() => {
|
|
1194
|
-
if (queued) return
|
|
1195
|
-
queued = true
|
|
1196
|
-
queueMicrotask(() => {
|
|
1197
|
-
queued = false
|
|
1198
|
-
audit()
|
|
1199
|
-
})
|
|
704
|
+
return Object.assign((_props) => uncompiledStyle('sva'), {
|
|
705
|
+
splitVariantProps(props) {
|
|
706
|
+
return splitProps(props, variantKeys)
|
|
707
|
+
},
|
|
1200
708
|
})
|
|
1201
|
-
observer.observe(root === document ? document.documentElement : root, { childList: true, subtree: true })
|
|
1202
|
-
|
|
1203
|
-
return () => observer.disconnect()
|
|
1204
709
|
}
|
|
1205
710
|
`,
|
|
1206
711
|
dts: outdent.outdent`
|
|
1207
712
|
${ctx.file.importType("SlotRecipeCreatorFn", "../types/recipe")}
|
|
1208
713
|
|
|
1209
714
|
export declare const sva: SlotRecipeCreatorFn
|
|
1210
|
-
|
|
1211
|
-
export interface SlotScopeProblem {
|
|
1212
|
-
/** The recipe the slot belongs to, when it has a name. */
|
|
1213
|
-
recipe?: string
|
|
1214
|
-
/** The slot whose variant styles cannot reach it. */
|
|
1215
|
-
slot: string
|
|
1216
|
-
/** The constant class that slot carries. */
|
|
1217
|
-
className: string
|
|
1218
|
-
/** The element found outside every anchor. */
|
|
1219
|
-
element: Element
|
|
1220
|
-
/** The anchors that were looked for. */
|
|
1221
|
-
anchors: string[]
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
export interface AuditSlotScopesOptions {
|
|
1225
|
-
/** Where to look. Defaults to \`document\`. */
|
|
1226
|
-
root?: ParentNode
|
|
1227
|
-
/** Re-check as the DOM changes, for content that mounts through a portal. */
|
|
1228
|
-
observe?: boolean
|
|
1229
|
-
/** Handle the findings yourself instead of warning to the console. */
|
|
1230
|
-
onReport?: (problems: SlotScopeProblem[]) => void
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
/**
|
|
1234
|
-
* Report slots whose variant styles can never reach them, in development.
|
|
1235
|
-
*
|
|
1236
|
-
* A scoped slot is styled through an \`@scope\` rule opened at an anchor, so it has to be
|
|
1237
|
-
* rendered inside one. A slot moved out of every anchor's subtree keeps its base styles
|
|
1238
|
-
* and silently loses its variant styles — which no build step can catch, because whether
|
|
1239
|
-
* one element is inside another is a fact about the DOM.
|
|
1240
|
-
*
|
|
1241
|
-
* Returns a function that stops observing.
|
|
1242
|
-
*/
|
|
1243
|
-
export declare function auditSlotScopes(
|
|
1244
|
-
recipes: ReadonlyArray<unknown>,
|
|
1245
|
-
options?: AuditSlotScopesOptions,
|
|
1246
|
-
): () => void
|
|
1247
715
|
`
|
|
1248
716
|
};
|
|
1249
717
|
}
|
|
@@ -2085,7 +1553,7 @@ var comments = {
|
|
|
2085
1553
|
var content$4 = "import type { CssProperty, SystemStyleObject } from './system-types'\nimport type { TokenCategory } from '../tokens'\n\ntype Primitive = string | number | boolean | null | undefined\ntype LiteralUnion<T, K extends Primitive = string> = T | (K & Record<never, never>)\n\nexport type PatternProperty =\n | { type: 'property'; value: CssProperty; description?: string }\n | { type: 'enum'; value: string[]; description?: string }\n | { type: 'token'; value: TokenCategory; property?: CssProperty; description?: string }\n | { type: 'string' | 'boolean' | 'number'; description?: string }\n\nexport interface PatternHelpers {\n map: (value: any, fn: (value: string) => string | undefined) => any\n /**\n * The css variable reference for a token path, or `fallback` when the path names no token.\n *\n * `token('spacing.4', '4')` is `var(--spacing-4)` where that token exists and `'4'` where it\n * does not — so a pattern can accept either a token name or a raw css value without knowing\n * the theme.\n */\n token: (path: string, fallback?: string) => string | undefined\n isCssUnit: (value: any) => boolean\n isCssVar: (value: any) => boolean\n isCssFunction: (value: any) => boolean\n}\n\nexport interface PatternProperties {\n [key: string]: PatternProperty\n}\n\ntype InferProps<T> = Record<LiteralUnion<keyof T>, any>\n\nexport type PatternDefaultValue<T> = Partial<InferProps<T>>\n\nexport type PatternDefaultValueFn<T> = (props: InferProps<T>) => PatternDefaultValue<T>\n\nexport interface PatternConfig<T extends PatternProperties = PatternProperties> {\n /**\n * The description of the pattern. This will be used in the JSDoc comment.\n */\n description?: string\n /**\n * The properties of the pattern.\n */\n properties?: T\n /**\n * The default values of the pattern.\n */\n defaultValues?: PatternDefaultValue<T> | PatternDefaultValueFn<T>\n /**\n * The css object this pattern will generate.\n */\n transform?: (props: InferProps<T>, helpers: PatternHelpers) => SystemStyleObject\n /**\n * Whether the pattern is deprecated.\n */\n deprecated?: boolean | string\n /**\n * Which css properties this pattern accepts alongside its own `properties`.\n *\n * - `all` accepts any css property.\n * - `none` accepts only the pattern's declared `properties`.\n * - `{ except }` accepts any css property but the ones listed.\n *\n * One option because these were two — `strict: true` for \"none\" and an `@experimental`\n * `blocklist` for \"all but these\" — and the pair had an unrepresentable combination that\n * silently did nothing: the blocklist is applied only to the type that lists css\n * properties, which `strict: true` does not emit, so setting both dropped the blocklist.\n *\n * Types only. Nothing strips a blocked property at runtime — one passed anyway reaches\n * `transform` and emits css.\n *\n * @default 'all'\n */\n cssProps?: 'all' | 'none' | { except: LiteralUnion<CssProperty>[] }\n}\n";
|
|
2086
1554
|
//#endregion
|
|
2087
1555
|
//#region src/artifacts/generated/recipe.d.ts.json
|
|
2088
|
-
var content$3 = "import type { RecipeRule } from './static-css'\nimport type { SystemStyleObject, DistributiveOmit, Pretty } from './system-types'\n\ntype StringToBoolean<T> = T extends 'true' | 'false' ? boolean : T\n\nexport type RecipeVariantRecord = Record<any, Record<any, SystemStyleObject>>\n\nexport type RecipeSelection<T extends RecipeVariantRecord> = keyof any extends keyof T\n ? {}\n : {\n [K in keyof T]?: StringToBoolean<keyof T[K]> | undefined\n }\n\nexport type RecipeVariantFn<T extends RecipeVariantRecord> = (props?: RecipeSelection<T>) => string\n\n/**\n * Extract the variant as optional props from a `cva` function.\n * Intended to be used with a JSX component, prefer `RecipeVariant` for a more strict type.\n */\nexport type RecipeVariantProps<\n T extends RecipeVariantFn<RecipeVariantRecord> | SlotRecipeVariantFn<string, SlotRecipeVariantRecord<string>>,\n> = Pretty<Parameters<T>[0]>\n\n/**\n * Extract the variants from a `cva` function.\n */\nexport type RecipeVariant<\n T extends RecipeVariantFn<RecipeVariantRecord> | SlotRecipeVariantFn<string, SlotRecipeVariantRecord<string>>,\n> = Exclude<Pretty<Required<RecipeVariantProps<T>>>, undefined>\n\
|
|
1556
|
+
var content$3 = "import type { RecipeRule } from './static-css'\nimport type { SystemStyleObject, DistributiveOmit, Pretty } from './system-types'\n\ntype StringToBoolean<T> = T extends 'true' | 'false' ? boolean : T\n\nexport type RecipeVariantRecord = Record<any, Record<any, SystemStyleObject>>\n\nexport type RecipeSelection<T extends RecipeVariantRecord> = keyof any extends keyof T\n ? {}\n : {\n [K in keyof T]?: StringToBoolean<keyof T[K]> | undefined\n }\n\nexport type RecipeVariantFn<T extends RecipeVariantRecord> = (props?: RecipeSelection<T>) => string\n\n/**\n * Extract the variant as optional props from a `cva` function.\n * Intended to be used with a JSX component, prefer `RecipeVariant` for a more strict type.\n */\nexport type RecipeVariantProps<\n T extends RecipeVariantFn<RecipeVariantRecord> | SlotRecipeVariantFn<string, SlotRecipeVariantRecord<string>>,\n> = Pretty<Parameters<T>[0]>\n\n/**\n * Extract the variants from a `cva` function.\n */\nexport type RecipeVariant<\n T extends RecipeVariantFn<RecipeVariantRecord> | SlotRecipeVariantFn<string, SlotRecipeVariantRecord<string>>,\n> = Exclude<Pretty<Required<RecipeVariantProps<T>>>, undefined>\n\n/* -----------------------------------------------------------------------------\n * Recipe / Standard\n * -----------------------------------------------------------------------------*/\n\n/**\n * What a compiled build lets you do with a recipe: call it, or split its variant props.\n *\n * Nothing else is declared, because nothing else compiles. The compiler rewrites a call into\n * the classes it selects and erases the recipe, so any other read of the binding — `raw`,\n * `variantMap`, `config`, `merge`, `getVariantProps` — would see a value that is no longer\n * there, and fails the build with `runtime-binding` or `raw-call`. Declaring them only let\n * that failure type-check.\n */\nexport interface RecipeRuntimeFn<T extends RecipeVariantRecord> extends RecipeVariantFn<T> {\n __type: RecipeSelection<T>\n splitVariantProps<Props extends RecipeSelection<T>>(\n props: Props,\n ): [RecipeSelection<T>, Pretty<DistributiveOmit<Props, keyof T>>]\n}\n\ntype OneOrMore<T> = T | Array<T>\n\nexport type RecipeCompoundSelection<T> = {\n [K in keyof T]?: OneOrMore<StringToBoolean<keyof T[K]>> | undefined\n}\n\nexport type RecipeCompoundVariant<T> = T & {\n css: SystemStyleObject\n}\n\nexport interface RecipeDefinition<T extends RecipeVariantRecord = RecipeVariantRecord> {\n /**\n * The base styles of the recipe.\n */\n base?: SystemStyleObject\n /**\n * Semantic recipe name used by extraction-only integrations.\n *\n * Required for a recipe declared in `theme.recipes`, where it is the key it is declared\n * under. Optional for an inline `cva`.\n *\n * The Vite compiler ignores this field when allocating declaration atoms: recipe identity\n * is not style identity, so identical declarations share one class across recipes.\n */\n className?: string\n /**\n * Whether the recipe is deprecated.\n */\n deprecated?: boolean | string\n /**\n * The multi-variant styles of the recipe.\n */\n variants?: T\n /**\n * The default variants of the recipe.\n */\n defaultVariants?: RecipeSelection<T>\n /**\n * The styles to apply when a combination of variants is selected.\n */\n compoundVariants?: Pretty<RecipeCompoundVariant<RecipeCompoundSelection<T>>>[]\n}\n\nexport type RecipeCreatorFn = <T extends RecipeVariantRecord>(config: RecipeDefinition<T>) => RecipeRuntimeFn<T>\n\ninterface RecipeConfigMeta {\n /**\n * The description of the recipe. This will be used in the JSDoc comment.\n */\n description?: string\n /**\n * The jsx elements to track for this recipe. Can be string or Regexp.\n *\n * @default capitalize(recipe.name)\n * @example ['Button', 'Link', /Button$/]\n */\n jsx?: Array<string | RegExp>\n /**\n * Variants to pre-generate, will be include in the final `config.staticCss`\n */\n staticCss?: RecipeRule[]\n}\n\nexport interface RecipeConfig<T extends RecipeVariantRecord = RecipeVariantRecord>\n extends RecipeDefinition<T>, RecipeConfigMeta {\n /**\n * Required extraction metadata for a configured recipe: the key under which it is\n * declared in `theme.recipes`. The Vite compiler does not use it as style identity.\n */\n className: string\n}\n\n/* -----------------------------------------------------------------------------\n * Recipe / Slot\n * -----------------------------------------------------------------------------*/\n\ntype SlotRecord<S extends string, T> = Partial<Record<S, T>>\n\nexport type SlotRecipeVariantRecord<S extends string> = Record<any, Record<any, SlotRecord<S, SystemStyleObject>>>\n\nexport type SlotRecipeVariantFn<S extends string, T extends RecipeVariantRecord> = (\n props?: RecipeSelection<T>,\n) => SlotRecord<S, string>\n\n/**\n * A slot recipe as a compiled build allows it: call it, or split its variant props. See\n * `RecipeRuntimeFn` for why nothing else is declared.\n */\nexport interface SlotRecipeRuntimeFn<\n S extends string,\n T extends SlotRecipeVariantRecord<S>,\n> extends SlotRecipeVariantFn<S, T> {\n splitVariantProps<Props extends RecipeSelection<T>>(\n props: Props,\n ): [RecipeSelection<T>, Pretty<DistributiveOmit<Props, keyof T>>]\n}\n\nexport type SlotRecipeCompoundVariant<S extends string, T> = T & {\n css: SlotRecord<S, SystemStyleObject>\n}\n\nexport interface SlotRecipeDefinition<\n S extends string = string,\n T extends SlotRecipeVariantRecord<S> = SlotRecipeVariantRecord<S>,\n> {\n /**\n * Semantic recipe name used by extraction-only integrations.\n *\n * Required for a recipe declared in `theme.slotRecipes`, where it is the key it is\n * declared under. Optional for an inline `sva`.\n *\n * The Vite compiler ignores this field when allocating declaration atoms: recipe and slot\n * identity do not enter generated class names.\n */\n className?: string\n /**\n * Whether the recipe is deprecated.\n */\n deprecated?: boolean | string\n /**\n * The parts/slots of the recipe.\n */\n slots: S[] | Readonly<S[]>\n /**\n * Accepted and ignored.\n *\n * Older extraction-only releases scoped a slot's variant styles with `@scope` rules anchored\n * at the slots named here. The Vite compiler returns complete atoms for every selected slot\n * and emits no `@scope`, so this has no effect on output; it is still accepted so existing\n * configs keep loading.\n *\n * @deprecated Has no effect on compiled output.\n */\n scopeRoots?: S[] | Readonly<S[]>\n /**\n * The base styles of the recipe.\n */\n base?: SlotRecord<S, SystemStyleObject>\n /**\n * The multi-variant styles of the recipe.\n */\n variants?: T\n /**\n * The default variants of the recipe.\n */\n defaultVariants?: RecipeSelection<T>\n /**\n * The styles to apply when a combination of variants is selected.\n */\n compoundVariants?: Pretty<SlotRecipeCompoundVariant<S, RecipeCompoundSelection<T>>>[]\n}\n\nexport type SlotRecipeCreatorFn = <S extends string, T extends SlotRecipeVariantRecord<S>>(\n config: SlotRecipeDefinition<S, T>,\n) => SlotRecipeRuntimeFn<S, T>\n\nexport type SlotRecipeConfig<\n S extends string = string,\n T extends SlotRecipeVariantRecord<S> = SlotRecipeVariantRecord<S>,\n> = SlotRecipeDefinition<S, T> &\n RecipeConfigMeta & {\n /**\n * Required extraction metadata for a configured recipe: the key under which it is\n * declared in `theme.slotRecipes`. The Vite compiler does not use it as style identity.\n */\n className: string\n }\n";
|
|
2089
1557
|
//#endregion
|
|
2090
1558
|
//#region src/artifacts/generated/selectors.d.ts.json
|
|
2091
1559
|
var content$2 = "import type { Pseudos } from './csstype'\n\ntype AriaAttributes =\n | '[aria-disabled]'\n | '[aria-hidden]'\n | '[aria-invalid]'\n | '[aria-readonly]'\n | '[aria-required]'\n | '[aria-selected]'\n | '[aria-checked]'\n | '[aria-expanded]'\n | '[aria-pressed]'\n | `[aria-current=${'page' | 'step' | 'location' | 'date' | 'time'}]`\n | '[aria-invalid]'\n | `[aria-sort=${'ascending' | 'descending'}]`\n\ntype DataAttributes =\n | '[data-selected]'\n | '[data-highlighted]'\n | '[data-hover]'\n | '[data-active]'\n | '[data-checked]'\n | '[data-disabled]'\n | '[data-readonly]'\n | '[data-focus]'\n | '[data-focus-visible]'\n | '[data-focus-visible-added]'\n | '[data-invalid]'\n | '[data-pressed]'\n | '[data-expanded]'\n | '[data-grabbed]'\n | '[data-dragged]'\n | '[data-orientation=horizontal]'\n | '[data-orientation=vertical]'\n | '[data-in-range]'\n | '[data-out-of-range]'\n | '[data-placeholder-shown]'\n | `[data-part=${string}]`\n | `[data-attr=${string}]`\n | `[data-placement=${string}]`\n | `[data-theme=${string}]`\n | `[data-size=${string}]`\n | `[data-state=${string}]`\n | '[data-empty]'\n | '[data-loading]'\n | '[data-loaded]'\n | '[data-enter]'\n | '[data-entering]'\n | '[data-exited]'\n | '[data-exiting]'\n\ntype AttributeSelector = `&${Pseudos | DataAttributes | AriaAttributes}`\ntype ParentSelector = `${DataAttributes | AriaAttributes} &`\n\ntype AtRuleType = 'media' | 'layer' | 'container' | 'supports' | 'page' | 'scope' | 'starting-style'\n\nexport type AnySelector = `${string}&` | `&${string}` | `@${AtRuleType}${string}`\nexport type Selectors = AttributeSelector | ParentSelector\n";
|
|
@@ -3115,22 +2583,6 @@ function setupCx(ctx) {
|
|
|
3115
2583
|
}]
|
|
3116
2584
|
};
|
|
3117
2585
|
}
|
|
3118
|
-
function setupCreateRecipe(ctx) {
|
|
3119
|
-
if (ctx.recipes.isEmpty()) return;
|
|
3120
|
-
const createRecipe = generateCreateRecipe(ctx);
|
|
3121
|
-
if (!createRecipe) return;
|
|
3122
|
-
return {
|
|
3123
|
-
id: "create-recipe",
|
|
3124
|
-
dir: ctx.paths.recipe,
|
|
3125
|
-
files: [{
|
|
3126
|
-
file: ctx.file.ext(createRecipe.name),
|
|
3127
|
-
code: createRecipe.js
|
|
3128
|
-
}, {
|
|
3129
|
-
file: ctx.file.extDts(createRecipe.name),
|
|
3130
|
-
code: createRecipe.dts
|
|
3131
|
-
}]
|
|
3132
|
-
};
|
|
3133
|
-
}
|
|
3134
2586
|
function setupRecipesIndex(ctx) {
|
|
3135
2587
|
if (ctx.recipes.isEmpty()) return;
|
|
3136
2588
|
const fileNames = ctx.recipes.details.map((recipe) => recipe.dashName);
|
|
@@ -3213,7 +2665,7 @@ function setupCssIndex(ctx) {
|
|
|
3213
2665
|
${ctx.file.reExport("css, fallback, viewTransition", "./css")}
|
|
3214
2666
|
${ctx.file.reExport("cx", "./cx")}
|
|
3215
2667
|
${ctx.file.reExport("cva", "./cva")}
|
|
3216
|
-
${ctx.file.reExport("sva
|
|
2668
|
+
${ctx.file.reExport("sva", "./sva")}
|
|
3217
2669
|
|
|
3218
2670
|
// Written by the source transform, never by hand. They are exported here because the
|
|
3219
2671
|
// transform adds them to whatever \`styled-system/css\` import the file already has, so
|
|
@@ -3230,8 +2682,7 @@ function setupCssIndex(ctx) {
|
|
|
3230
2682
|
${ctx.file.reExportDts("cx", "./cx")}
|
|
3231
2683
|
${ctx.file.reExportDts("cva", "./cva")}
|
|
3232
2684
|
${ctx.file.exportType("RecipeVariant, RecipeVariantProps", "./cva")}
|
|
3233
|
-
${ctx.file.reExportDts("sva
|
|
3234
|
-
${ctx.file.exportType("SlotScopeProblem, AuditSlotScopesOptions", "./sva")}
|
|
2685
|
+
${ctx.file.reExportDts("sva", "./sva")}
|
|
3235
2686
|
`
|
|
3236
2687
|
};
|
|
3237
2688
|
return {
|
|
@@ -3305,7 +2756,6 @@ const entries = [
|
|
|
3305
2756
|
["cva", setupCva],
|
|
3306
2757
|
["sva", setupSva],
|
|
3307
2758
|
["cx", setupCx],
|
|
3308
|
-
["create-recipe", setupCreateRecipe],
|
|
3309
2759
|
["recipes-index", setupRecipesIndex],
|
|
3310
2760
|
["recipes", setupRecipes],
|
|
3311
2761
|
["patterns-index", setupPatternsIndex],
|