css-calipers 0.15.0 → 1.1.0-beta.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.
Files changed (207) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +70 -434
  3. package/dist/cjs/color/formats/display-p3/display-p3.js +25 -0
  4. package/dist/cjs/color/formats/escalate.js +41 -0
  5. package/dist/cjs/color/formats/hex/hex.js +28 -0
  6. package/dist/cjs/color/formats/hexAlpha/hexAlpha.js +25 -0
  7. package/dist/cjs/color/formats/hsl/hsl.js +23 -0
  8. package/dist/cjs/color/formats/hwb/hwb.js +24 -0
  9. package/dist/cjs/color/formats/index.js +36 -0
  10. package/dist/cjs/color/formats/internals.js +93 -0
  11. package/dist/cjs/color/formats/lab/lab.js +24 -0
  12. package/dist/cjs/color/formats/lch/lch.js +23 -0
  13. package/dist/cjs/color/formats/oklab/oklab.js +24 -0
  14. package/dist/cjs/color/formats/oklch/oklch.js +28 -0
  15. package/dist/cjs/color/formats/resolve.js +16 -0
  16. package/dist/cjs/color/formats/rgb/rgb.js +29 -0
  17. package/dist/cjs/color/formats/rgba/rgba.js +27 -0
  18. package/dist/cjs/color/formats/types.js +11 -0
  19. package/dist/cjs/color/index.js +619 -0
  20. package/dist/cjs/color/types.js +2 -0
  21. package/dist/cjs/core.js +11 -8
  22. package/dist/cjs/corpus.js +53 -0
  23. package/dist/cjs/css-values/cssValues.js +78 -0
  24. package/dist/cjs/css-values/index.js +36 -0
  25. package/dist/cjs/css-values/multi.js +290 -0
  26. package/dist/cjs/css-values/propertyMap.js +2 -0
  27. package/dist/cjs/css-values/spec.js +197 -0
  28. package/dist/cjs/default.js +17 -0
  29. package/dist/cjs/factory.js +1 -1
  30. package/dist/cjs/float.js +110 -0
  31. package/dist/cjs/index.js +29 -9
  32. package/dist/cjs/integer.js +114 -0
  33. package/dist/cjs/internal/createCoreApi.js +103 -38
  34. package/dist/cjs/internal/errors.js +13 -14
  35. package/dist/cjs/internal/toPlainDecimal.js +31 -0
  36. package/dist/cjs/measurements.js +41 -0
  37. package/dist/cjs/ratio.js +57 -22
  38. package/dist/cjs/scalar.js +9 -0
  39. package/dist/cjs/units/absolute.js +8 -8
  40. package/dist/cjs/units/angle.js +5 -5
  41. package/dist/cjs/units/container.js +7 -7
  42. package/dist/cjs/units/font-relative.js +13 -13
  43. package/dist/cjs/units/frequency.js +3 -3
  44. package/dist/cjs/units/grid.js +2 -2
  45. package/dist/cjs/units/index.js +9 -9
  46. package/dist/cjs/units/percent.js +4 -4
  47. package/dist/cjs/units/resolution.js +4 -4
  48. package/dist/cjs/units/time.js +3 -3
  49. package/dist/cjs/units/viewport-dynamic.js +7 -7
  50. package/dist/cjs/units/viewport-large.js +7 -7
  51. package/dist/cjs/units/viewport-small.js +7 -7
  52. package/dist/cjs/units/viewport.js +7 -7
  53. package/dist/esm/color/formats/display-p3/display-p3.d.ts +10 -0
  54. package/dist/esm/color/formats/display-p3/display-p3.d.ts.map +1 -0
  55. package/dist/esm/color/formats/display-p3/display-p3.js +22 -0
  56. package/dist/esm/color/formats/escalate.d.ts +10 -0
  57. package/dist/esm/color/formats/escalate.d.ts.map +1 -0
  58. package/dist/esm/color/formats/escalate.js +37 -0
  59. package/dist/esm/color/formats/hex/hex.d.ts +9 -0
  60. package/dist/esm/color/formats/hex/hex.d.ts.map +1 -0
  61. package/dist/esm/color/formats/hex/hex.js +25 -0
  62. package/dist/esm/color/formats/hexAlpha/hexAlpha.d.ts +9 -0
  63. package/dist/esm/color/formats/hexAlpha/hexAlpha.d.ts.map +1 -0
  64. package/dist/esm/color/formats/hexAlpha/hexAlpha.js +22 -0
  65. package/dist/esm/color/formats/hsl/hsl.d.ts +8 -0
  66. package/dist/esm/color/formats/hsl/hsl.d.ts.map +1 -0
  67. package/dist/esm/color/formats/hsl/hsl.js +20 -0
  68. package/dist/esm/color/formats/hwb/hwb.d.ts +9 -0
  69. package/dist/esm/color/formats/hwb/hwb.d.ts.map +1 -0
  70. package/dist/esm/color/formats/hwb/hwb.js +21 -0
  71. package/dist/esm/color/formats/index.d.ts +24 -0
  72. package/dist/esm/color/formats/index.d.ts.map +1 -0
  73. package/dist/esm/color/formats/index.js +32 -0
  74. package/dist/esm/color/formats/internals.d.ts +35 -0
  75. package/dist/esm/color/formats/internals.d.ts.map +1 -0
  76. package/dist/esm/color/formats/internals.js +78 -0
  77. package/dist/esm/color/formats/lab/lab.d.ts +9 -0
  78. package/dist/esm/color/formats/lab/lab.d.ts.map +1 -0
  79. package/dist/esm/color/formats/lab/lab.js +21 -0
  80. package/dist/esm/color/formats/lch/lch.d.ts +8 -0
  81. package/dist/esm/color/formats/lch/lch.d.ts.map +1 -0
  82. package/dist/esm/color/formats/lch/lch.js +20 -0
  83. package/dist/esm/color/formats/oklab/oklab.d.ts +9 -0
  84. package/dist/esm/color/formats/oklab/oklab.d.ts.map +1 -0
  85. package/dist/esm/color/formats/oklab/oklab.js +21 -0
  86. package/dist/esm/color/formats/oklch/oklch.d.ts +13 -0
  87. package/dist/esm/color/formats/oklch/oklch.d.ts.map +1 -0
  88. package/dist/esm/color/formats/oklch/oklch.js +25 -0
  89. package/dist/esm/color/formats/resolve.d.ts +15 -0
  90. package/dist/esm/color/formats/resolve.d.ts.map +1 -0
  91. package/dist/esm/color/formats/resolve.js +12 -0
  92. package/dist/esm/color/formats/rgb/rgb.d.ts +11 -0
  93. package/dist/esm/color/formats/rgb/rgb.d.ts.map +1 -0
  94. package/dist/esm/color/formats/rgb/rgb.js +26 -0
  95. package/dist/esm/color/formats/rgba/rgba.d.ts +9 -0
  96. package/dist/esm/color/formats/rgba/rgba.d.ts.map +1 -0
  97. package/dist/esm/color/formats/rgba/rgba.js +24 -0
  98. package/dist/esm/color/formats/types.d.ts +48 -0
  99. package/dist/esm/color/formats/types.d.ts.map +1 -0
  100. package/dist/esm/color/formats/types.js +7 -0
  101. package/dist/esm/color/index.d.ts +81 -0
  102. package/dist/esm/color/index.d.ts.map +1 -0
  103. package/dist/esm/color/index.js +609 -0
  104. package/dist/esm/color/types.d.ts +294 -0
  105. package/dist/esm/color/types.d.ts.map +1 -0
  106. package/dist/esm/color/types.js +1 -0
  107. package/dist/esm/core.d.ts +76 -270
  108. package/dist/esm/core.d.ts.map +1 -1
  109. package/dist/esm/core.js +5 -7
  110. package/dist/esm/corpus.d.ts +26 -0
  111. package/dist/esm/corpus.d.ts.map +1 -0
  112. package/dist/esm/corpus.js +37 -0
  113. package/dist/esm/css-values/cssValues.d.ts +60 -0
  114. package/dist/esm/css-values/cssValues.d.ts.map +1 -0
  115. package/dist/esm/css-values/cssValues.js +74 -0
  116. package/dist/esm/css-values/index.d.ts +6 -0
  117. package/dist/esm/css-values/index.d.ts.map +1 -0
  118. package/dist/esm/css-values/index.js +12 -0
  119. package/dist/esm/css-values/multi.d.ts +188 -0
  120. package/dist/esm/css-values/multi.d.ts.map +1 -0
  121. package/dist/esm/css-values/multi.js +281 -0
  122. package/dist/esm/css-values/propertyMap.d.ts +39 -0
  123. package/dist/esm/css-values/propertyMap.d.ts.map +1 -0
  124. package/dist/esm/css-values/propertyMap.js +1 -0
  125. package/dist/esm/css-values/spec.d.ts +36 -0
  126. package/dist/esm/css-values/spec.d.ts.map +1 -0
  127. package/dist/esm/css-values/spec.js +194 -0
  128. package/dist/esm/default.d.ts +267 -0
  129. package/dist/esm/default.d.ts.map +1 -0
  130. package/dist/esm/default.js +14 -0
  131. package/dist/esm/factory.d.ts +1 -1
  132. package/dist/esm/factory.d.ts.map +1 -1
  133. package/dist/esm/factory.js +3 -3
  134. package/dist/esm/float.d.ts +35 -0
  135. package/dist/esm/float.d.ts.map +1 -0
  136. package/dist/esm/float.js +104 -0
  137. package/dist/esm/index.d.ts +11 -9
  138. package/dist/esm/index.d.ts.map +1 -1
  139. package/dist/esm/index.js +19 -9
  140. package/dist/esm/integer.d.ts +36 -0
  141. package/dist/esm/integer.d.ts.map +1 -0
  142. package/dist/esm/integer.js +108 -0
  143. package/dist/esm/internal/buildMeasurementCreationError.tests.d.ts +1 -1
  144. package/dist/esm/internal/buildMeasurementCreationError.tests.d.ts.map +1 -1
  145. package/dist/esm/internal/createCoreApi.d.ts +9 -1
  146. package/dist/esm/internal/createCoreApi.d.ts.map +1 -1
  147. package/dist/esm/internal/createCoreApi.js +103 -38
  148. package/dist/esm/internal/createUnitsApi.d.ts +1 -1
  149. package/dist/esm/internal/createUnitsApi.d.ts.map +1 -1
  150. package/dist/esm/internal/errors.d.ts +3 -3
  151. package/dist/esm/internal/errors.d.ts.map +1 -1
  152. package/dist/esm/internal/errors.js +13 -14
  153. package/dist/esm/internal/toPlainDecimal.d.ts +2 -0
  154. package/dist/esm/internal/toPlainDecimal.d.ts.map +1 -0
  155. package/dist/esm/internal/toPlainDecimal.js +27 -0
  156. package/dist/esm/measurements.d.ts +16 -0
  157. package/dist/esm/measurements.d.ts.map +1 -0
  158. package/dist/esm/measurements.js +25 -0
  159. package/dist/esm/ratio.d.ts +14 -5
  160. package/dist/esm/ratio.d.ts.map +1 -1
  161. package/dist/esm/ratio.js +57 -22
  162. package/dist/esm/scalar.d.ts +14 -0
  163. package/dist/esm/scalar.d.ts.map +1 -0
  164. package/dist/esm/scalar.js +5 -0
  165. package/dist/esm/units/absolute.d.ts +1 -1
  166. package/dist/esm/units/absolute.d.ts.map +1 -1
  167. package/dist/esm/units/absolute.js +1 -1
  168. package/dist/esm/units/angle.d.ts +1 -1
  169. package/dist/esm/units/angle.d.ts.map +1 -1
  170. package/dist/esm/units/angle.js +1 -1
  171. package/dist/esm/units/container.d.ts +1 -1
  172. package/dist/esm/units/container.d.ts.map +1 -1
  173. package/dist/esm/units/container.js +1 -1
  174. package/dist/esm/units/font-relative.d.ts +1 -1
  175. package/dist/esm/units/font-relative.d.ts.map +1 -1
  176. package/dist/esm/units/font-relative.js +1 -1
  177. package/dist/esm/units/frequency.d.ts +1 -1
  178. package/dist/esm/units/frequency.d.ts.map +1 -1
  179. package/dist/esm/units/frequency.js +1 -1
  180. package/dist/esm/units/grid.d.ts +1 -1
  181. package/dist/esm/units/grid.d.ts.map +1 -1
  182. package/dist/esm/units/grid.js +1 -1
  183. package/dist/esm/units/index.d.ts +9 -9
  184. package/dist/esm/units/index.d.ts.map +1 -1
  185. package/dist/esm/units/index.js +9 -9
  186. package/dist/esm/units/percent.d.ts +1 -1
  187. package/dist/esm/units/percent.d.ts.map +1 -1
  188. package/dist/esm/units/percent.js +1 -1
  189. package/dist/esm/units/resolution.d.ts +1 -1
  190. package/dist/esm/units/resolution.d.ts.map +1 -1
  191. package/dist/esm/units/resolution.js +1 -1
  192. package/dist/esm/units/time.d.ts +1 -1
  193. package/dist/esm/units/time.d.ts.map +1 -1
  194. package/dist/esm/units/time.js +1 -1
  195. package/dist/esm/units/viewport-dynamic.d.ts +1 -1
  196. package/dist/esm/units/viewport-dynamic.d.ts.map +1 -1
  197. package/dist/esm/units/viewport-dynamic.js +1 -1
  198. package/dist/esm/units/viewport-large.d.ts +1 -1
  199. package/dist/esm/units/viewport-large.d.ts.map +1 -1
  200. package/dist/esm/units/viewport-large.js +1 -1
  201. package/dist/esm/units/viewport-small.d.ts +1 -1
  202. package/dist/esm/units/viewport-small.d.ts.map +1 -1
  203. package/dist/esm/units/viewport-small.js +1 -1
  204. package/dist/esm/units/viewport.d.ts +1 -1
  205. package/dist/esm/units/viewport.d.ts.map +1 -1
  206. package/dist/esm/units/viewport.js +1 -1
  207. package/package.json +55 -13
package/LICENSE.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 slafleche
3
+ Copyright (c) 2025-2026 Stéphane LaFlèche
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,493 +1,129 @@
1
- # CSS-Calipers
1
+ # css-calipers
2
2
 
3
- [![npm](https://img.shields.io/npm/v/css-calipers.svg)](https://www.npmjs.com/package/css-calipers)
4
- [![types](https://img.shields.io/npm/types/css-calipers.svg)](https://www.npmjs.com/package/css-calipers)
5
- [![license](https://img.shields.io/npm/l/css-calipers.svg)](./LICENSE.txt)
3
+ The missing pieces of typed CSS input, build-time-validated: colour, measurements, integers, floats, and ratios.
6
4
 
7
- **CSS is code. Treat it that way.**
8
- Compile-time unit safety for numeric, unit-bearing CSS values, with no surprises at runtime.
5
+ ## The problem
9
6
 
10
- ```ts
11
- // Before: pull the number AND the unit apart, do the math, glue them back
12
- const match = base.match(/^(-?\d*\.?\d+)([a-z%]+)$/i);
13
- if (!match) throw new Error(`Bad measurement: ${base}`);
14
- const [, numStr, unit] = match;
15
- const num = parseFloat(numStr);
16
- const pad = `${num + 4}${unit}`; // and nobody checked that `unit` matches what the caller expects
17
-
18
- // After: typed math, units enforced by the compiler
19
- const base = m(8); // or m(8, "rem"), m(1.5, "em"), etc.
20
- const pad = base.add(4).css(); // type error if units don't match
21
- ```
22
-
23
- A small TypeScript library for **type-safe CSS measurements**. Do arithmetic on real numbers with the unit attached, let the compiler catch `px`-vs-`rem` mistakes, and emit a CSS string only at the edge.
24
-
25
- At a glance:
26
-
27
- - Create measurements with `m` from a number and a unit; if you omit the unit, it defaults to `px` and is typed as the px measurement type.
28
- - Do unit-safe math with methods like `add` and `multiply`, then call `.css()`
29
- at the edge to get a CSS string (for example "10px").
30
-
31
- ## Install
32
-
33
- ```bash
34
- npm install css-calipers
35
- ```
7
+ CSS input values are untyped. A measurement is a string (`'8px'`), an opacity is a bare number, a colour is whatever string you typed. Nothing catches `opacity: 1.5`, a `px` value added to an `em`, or a `z-index` that is silently a float. The mistake surfaces in the browser, not the compiler.
36
8
 
37
- ---
9
+ ## Highlights
38
10
 
39
- ## Quick start
11
+ `.css()` on a colour emits the simplest format that holds it without losing information:
40
12
 
41
13
  ```ts
42
- import { m } from "css-calipers";
43
-
44
- // Declare vars
45
- const paddingBase = m(4); // defaults to px (and is typed as a px measurement) when no unit is specified
46
- const rotation = m(45, "deg"); // equivalent to a dedicated helper: mDeg(45)
47
-
48
- // Do safe arithmetic
49
- const margins = paddingBase.add(4);
50
- const offset = paddingBase.add(margins).multiply(2).subtract(1);
14
+ import { color } from 'css-calipers';
51
15
 
52
- // Emit only at the end in CSS (at runtime or in a build step)
53
- const style = {
54
- padding: paddingBase.css(),
55
- transform: `rotate(${rotation.double().css()})`, // 90deg
56
- };
16
+ color('#3366cc').css(); // '#3366cc' (opaque -> hex)
17
+ color('#3366cc').alpha(0.5).css(); // 'rgba(51, 102, 204, 0.5)' (translucent -> rgba)
18
+ color('oklch(0.7 0.37 150)').css(); // 'oklch(0.7 0.37 150 / 1)' (wide gamut -> oklch)
57
19
  ```
58
20
 
59
- If you prefer, you can also import unit helpers from dedicated subpaths. For example, `mPercent` is available from the root entrypoint and from `css-calipers/units/percent`, and all unit helpers are aggregated under `css-calipers/units`.
60
-
61
- ---
62
-
63
- ## Status & support
64
-
65
- > API surface and docs may change between `0.x` releases until the first stable version.
66
-
67
- - Status: early `0.x` release. Backwards compatibility is not guaranteed until `1.0.0`.
68
- - Questions or bugs: open an issue on GitHub (see the repository link at the top of this page or in `package.json`).
69
- - Tooling: tested primarily with TypeScript 5.6+ on Node 18+.
70
- - Support: this is a solo, early-stage project. If it saves you time, you can [buy me a coffee](https://buymeacoffee.com/slafleche) to support continued work.
71
-
72
- ---
73
-
74
- ## Media queries
21
+ That ladder is the default and is reconfigurable: set your own output format or priority list, per call or per instance.
75
22
 
76
- Media queries have moved out of CSS-Calipers. From `0.15` on, CSS-Calipers is
77
- purely the measurement layer.
78
-
79
- CSS-Calipers itself is part of
80
- [CSS-Bookends](https://github.com/slafleche/css-bookends): it is the measurement
81
- lexicon at the centre of the umbrella. The first CSS-Bookends beta gives you
82
- exactly what `css-calipers@0.14` does today, the same measurement layer and the
83
- same media query helper, just split into two installable pieces (`css-calipers`
84
- plus `@css-bookends/media-queries`). Nothing is lost.
85
-
86
- If you use the media query helper:
87
-
88
- - **Switch to CSS-Bookends** and add `@css-bookends/media-queries` alongside
89
- `css-calipers`. Same helper, now maintained in the umbrella.
90
- - **Or stay on `css-calipers@0.14`**, which still bundles the media query helper
91
- and remains the `latest` release for now.
92
-
93
- CSS-Bookends is the long-term home for everything beyond measurement (spacing,
94
- colours, borders, and more), so moving over is the recommended path.
95
-
96
- ---
97
-
98
- ## Features
99
-
100
- - **Compile-time unit validation.** Prevents mixing incompatible units.
101
- - **Arithmetic safety.** Operate only within matching units; explicit when
102
- converting.
103
- - **Explicit emission.** `.css()` outputs a typed string literal only when
104
- needed.
105
- - **Light runtime footprint.** Near-zero cost when emitted at build time.
106
- - **Framework-agnostic.** Works anywhere TypeScript does.
107
-
108
- Any numeric, unit-bearing CSS value is supported: `m` accepts any unit string you’d use in CSS
109
- (`'px'`, `'rem'`, `'%'`, `'vw'`, `'deg'`, `'ms'`, …), and you can model new
110
- measurements without waiting for a dedicated helper. For convenience and better
111
- types, every standard CSS unit also has a named helper (for example
112
- `mPx`, `mPercent`, `mVw`, `mEm`, `mMs`, `mFr`), which are equivalent to calling
113
- `m(value, 'unit')` directly.
114
-
115
- CSS-Calipers focuses exclusively on numeric, unit-bearing CSS values. Keywords
116
- like `auto`, `fit-content`, or `max-content`, full shorthand strings,
117
- `var(--token)`, or `calc(...)` expressions should remain explicit strings or
118
- dedicated keyword types in your app or styling layer. Everything else stays as
119
- plain CSS (see "Philosophy & Boundaries" below for more detail). For a concrete
120
- example of this separation in a mixed-input helper, see
121
- [examples/lineHeight-normalizer.example.ts](examples/lineHeight-normalizer.example.ts),
122
- which keeps keywords and CSS variables as plain strings while using measurements
123
- for numeric values.
124
-
125
- ---
126
-
127
- ## Should I use this?
128
-
129
- CSS-Calipers is a good fit if:
130
-
131
- - You already use TypeScript (or plan to) and want compile-time guarantees around CSS units.
132
- - You have a design system or token layer where layout math and unit conversions matter.
133
- - You care about catching unit mismatches and layout invariants early, in dev or tests.
134
- This library is opinionated about types and emitting valid CSS at the edges,
135
- but intentionally loose about how you structure or apply styles in between.
136
-
137
- It’s probably overkill if:
138
-
139
- - Your project has minimal custom layout math or relies mostly on utility classes/framework CSS.
140
- - You don’t use TypeScript and aren’t looking for stronger typing around CSS values.
141
- - You’re comfortable relying on manual discipline instead of typed measurements for units.
142
-
143
- ---
144
-
145
- ### Layout tokens example
23
+ Measurements are branded by unit, so a `px` cannot be added to an `em`, and arithmetic re-validates:
146
24
 
147
25
  ```ts
148
- import { m, mPercent, mVw, mVh, assertCondition } from "css-calipers";
149
-
150
- // Token-style measurements (px by default)
151
- const spacing = m(8); // Defaults to px and is typed as a PxMeasurement
152
- const cardPadding = spacing.multiply(2); // 16px
153
- const gutter = spacing.multiply(1.5); // 12px
154
-
155
- // Responsive bounds expressed in other units
156
- const minWidthPercent = mPercent(75); // 75%; same as m(75, "%")
157
- const maxWidthViewport = mVw(100); // 100vw; same as m(100, "vw")
158
-
159
- // Derived content width in px
160
- const contentBase = m(320);
161
- const minCardWidth = m(260);
162
- const maxCardWidth = m(360);
163
-
164
- // In real code, these bounds typically come from tokens or configuration,
165
- // so keeping the clamp in measurement space ensures units stay consistent.
166
- const cardWidth = contentBase.clamp(minCardWidth, maxCardWidth);
167
-
168
- // Unitless ratio you can reuse elsewhere
169
- const ratio = contentBase.getValue() / spacing.getValue(); // returns a number, no unit
170
-
171
- // Apply ratio to a different unit family
172
- const heroHeight = mVh(40).multiply(ratio);
173
-
174
- // Invalid arithmetic (different units) fails at compile time
175
- const exampleError = cardWidth.add(heroHeight); // ❌ Type error (px vs vh) see error handling below
176
-
177
- // Use plain numbers where they are just counts
178
- const columns = 3;
179
-
180
- // In development, enforce simple invariants so layout mistakes fail fast.
181
- // In production, you can either rely on earlier validation or add a separate
182
- // fallback path if this invariant is ever broken.
183
- if (process.env.NODE_ENV !== "production") {
184
- assertCondition(
185
- () => columns > 0,
186
- "cardGridStyles: columns must be greater than zero",
187
- );
188
- }
189
-
190
- // Compose a simple grid layout
191
- const cardGridStyles = {
192
- display: "grid",
193
- gap: gutter.css(),
194
- // Keep fraction units as plain CSS alongside measurement-derived values
195
- gridTemplateColumns: `repeat(${columns}, 1fr)`,
196
- // width driven by card width + gutters
197
- width: cardWidth
198
- .multiply(columns)
199
- .add(gutter.multiply(columns - 1))
200
- .css(),
201
- // container bounds in percent/viewport units
202
- minWidth: minWidthPercent.css(),
203
- maxWidth: maxWidthViewport.css(),
204
- // derived hero height based on px ratio, expressed in vh and used inside a calc() string
205
- // calc() stays plain CSS; CSS-Calipers only provides the numeric pieces
206
- minHeight: `calc(${heroHeight.css()} + 10vh)`,
207
- };
208
- ```
26
+ import { m } from 'css-calipers';
209
27
 
210
- ---
211
-
212
- ## Do custom checks your way
213
-
214
- CSS-Calipers will happily enforce units anywhere you choose, but it stays
215
- unopinionated about where those guards live. Drop assertions in a component, in
216
- a theme override, hardcode a debug routine, or wire a global invariant; the
217
- structure is up to you:
218
-
219
- ```ts
220
- import { assertMatchingUnits } from "css-calipers";
221
- import { formTokens } from "@/tokens/forms.tokens";
222
-
223
- if (process.env.NODE_ENV !== "production") {
224
- assertMatchingUnits(
225
- formTokens.field.paddingBlock,
226
- formTokens.field.paddingInline,
227
- "Form control padding mismatch",
228
- );
229
- }
230
- ```
231
-
232
- You can apply the same checks globally (e.g., during app bootstrap), only
233
- inside the components that need them, or in dedicated test helpers. For more
234
- complete patterns, see the examples folder: the validation unit-tests example
235
- ([examples/validation-unit-tests.example.ts](examples/validation-unit-tests.example.ts)) shows how to
236
- enforce spacing token invariants in a test suite, and the validation and runtime
237
- checks example ([examples/validation-and-runtime-checks.example.ts](examples/validation-and-runtime-checks.example.ts))
238
- shows how to apply dev-only guards around shared tokens in two different
239
- consumers (an HTML snippet and a style object) using the same line-height
240
- measurement.
241
-
242
- ---
243
-
244
- ## Error behavior
245
-
246
- - Operations are fail-fast: when you call helpers like `add`, `divide`, `clamp`,
247
- `measurementMin` / `measurementMax`, or the assertion helpers with invalid
248
- input (for example, mismatched units or non-finite values), CSS-Calipers
249
- throws a normal `Error`.
250
- - Error messages include the operation name (for example,
251
- `css-calipers.Measurement.divide` or `css-calipers.assertMatchingUnits`), the
252
- relevant values/units, and any context string you pass in.
253
- - The library does not catch these errors for you. You choose where to place
254
- assertions and where (if anywhere) to catch and handle exceptions.
255
- - In production, a common pattern is to wrap assertions in dev-only guards
256
- (such as `if (process.env.NODE_ENV !== 'production')`) or to enforce
257
- invariants in tests, so checks stay cheap and predictable at runtime.
258
-
259
- For concrete uses of these errors in tests and dev-only guards, see
260
- `TESTING.md` and the validation examples in
261
- [examples/validation-unit-tests.example.ts](examples/validation-unit-tests.example.ts) and
262
- [examples/validation-and-runtime-checks.example.ts](examples/validation-and-runtime-checks.example.ts).
263
-
264
- ---
265
-
266
- ## Common errors
267
-
268
- ### Non-finite measurement value
269
-
270
- Example
271
-
272
- ```
273
- css-calipers.m: Non-finite measurement value: undefined [code=CALIPERS_E_NONFINITE | helper=m | inputs=value=undefined, unit=px | stack=...]
28
+ m(8).add(m(4)).css(); // '12px' (m() defaults to px)
29
+ m(2, 'rem').multiply(2).css(); // '4rem'
274
30
  ```
275
31
 
276
- What it means
277
-
278
- - A measurement was constructed with undefined, NaN, or Infinity.
279
-
280
- How to fix
32
+ Ratios accept typed integers and floats on either side:
281
33
 
282
- - Provide a real numeric value and a unit (m(12), m(12, "px")).
283
- - Add a context label so the error points to the calling helper or token (m(12, { context: "tokens.cardWidth" })).
284
-
285
- ### Unit mismatch
286
-
287
- Example
34
+ ```ts
35
+ import { r, i, f } from 'css-calipers';
288
36
 
37
+ r(i(16), i(9)).css(); // '16/9'
38
+ r(f(1.5), i(2)).css(); // '1.5/2' (a float and an integer)
289
39
  ```
290
- css-calipers.assertMatchingUnits: measurement unit mismatch: px vs em [code=CALIPERS_E_UNIT_MISMATCH]
291
- ```
292
-
293
- What it means
294
40
 
295
- - You mixed units without an explicit conversion.
41
+ Refinements turn a runtime check into a compile-time guarantee: the checked value is branded, so a function that demands a non-negative measurement cannot be handed an unchecked one.
296
42
 
297
- How to fix
298
-
299
- - Normalize units at the source (convert em to px or vice versa).
300
- - Add an assertMatchingUnits call where the values enter your system.
43
+ ```ts
44
+ import { m, nonNegative, inRange } from 'css-calipers';
301
45
 
302
- ### Divide by zero
46
+ // `ensure` runs the check, then hands the value back with a HARDENED type. The brand
47
+ // proves it passed, so anything typed NonNegativeMeasurement is known to be checked.
48
+ const width = nonNegative.ensure(m(8)); // type: NonNegativeMeasurement<'px'> (throws if negative)
303
49
 
304
- Example
50
+ // `inRange` bakes its literal bounds into the type, so it is distinct from any other range.
51
+ const pct = inRange(0, 100).ensure(m(50, '%')); // type: InRangeMeasurement<'%', 0, 100>
305
52
 
306
- ```
307
- css-calipers.Measurement.divide: Cannot divide 10px by zero [code=CALIPERS_E_DIVIDE_BY_ZERO]
53
+ // `hardenWith` always returns a valid, hardened value: if the input fails the check it
54
+ // falls back to a known-good one instead of throwing.
55
+ nonNegative.hardenWith(m(-4, 'px')).css(); // '0px' (-4 fails the check, so it falls back to 0)
308
56
  ```
309
57
 
310
- What it means
58
+ Integers (`i`), floats (`f`), and custom colour formats round out the set.
311
59
 
312
- - You attempted to divide by zero in a measurement operation.
60
+ ## Why csstype does not cover this
313
61
 
314
- How to fix
62
+ `csstype` is excellent and ships here as a dependency. It types CSS property names and their keywords well. What it leaves loose is open INPUT values: where a property accepts an open number or string, csstype falls back to `(number & {})`, so a bare `1.5`, a `px` added to an `em`, or a float `z-index` all pass. You cannot construct a validated value from that. calipers fills exactly that gap, and `.css()` renders to a string that still satisfies csstype on output. It complements csstype; it never replaces it. csstype types the property and keyword side, calipers types the value side, and the aim is a complete typed surface for CSS input, built from both.
315
63
 
316
- - Guard inputs before dividing or replace zero with a safe fallback.
64
+ calipers is standalone and complete on its own. It is also Layer 1 of the larger CSS-Bookends project (helpers, then an opinionated framework, built on these primitives), and design-token (DTCG) documents convert to these primitives via the Bookends typesetter. Both are there if you want them, never required.
317
65
 
318
- ### Clamp bounds
66
+ A note on the names. The book metaphor (calipers, bookends, gilding, compendium) is deliberate, not just whimsy. Each name marks a ROLE, and intentionally hides the library currently filling it, because those internals are meant to be swappable. You import `color()`, not `culori`; the project's browser-compat finisher is `gilding`, not Lightning CSS. Swap the engine underneath and your call sites do not move.
319
67
 
320
- Example
68
+ ## Install
321
69
 
322
- ```
323
- css-calipers.Measurement.clamp: clamp: min (20px) must be <= max (12px) [code=CALIPERS_E_CLAMP_INVALID_RANGE]
70
+ ```sh
71
+ npm install css-calipers
324
72
  ```
325
73
 
326
- What it means
74
+ Dependencies: `csstype` and `culori` (the colour engine). ESM and CommonJS are both published; the colour surface is reachable from the root import.
327
75
 
328
- - The clamp minimum is greater than the clamp maximum.
76
+ ## Colour
329
77
 
330
- How to fix
78
+ `color(input, config?)` parses a CSS string, a structured `ColorObject` (one shape per colour space: `{ space: 'rgb', r, g, b, alpha? }`, hsl, hwb, lab, lch, oklab, oklch), a symbolic keyword (`currentColor`, a system colour, a cascade keyword), or an existing resolved colour. It normalizes to OKLCH internally and returns an immutable result.
331
79
 
332
- - Ensure min and max come from the same source or swap them before calling clamp.
80
+ Modifications return a new colour (the original is untouched) and thread the configured output format through: `darken`, `lighten`, `brighten`, `saturate`, `desaturate`, `setLightness`, `setChroma`, `setHue`, `hueShift`, `complement`, `mix`, `mixSolid`, `mixWithAlpha`, `alpha`, `solid`, `clone`, `contrast`. See `examples/color-modify.example.ts`.
333
81
 
334
- ### Stack hints and configuration
82
+ **Output.** `.css()` takes no argument and walks the default ladder `[hex, rgba, oklch]` (the order is backed by usage data, see `docs/color-format-popularity.md`). Force a format with a named selector (`.hex()`, `.rgb()`, `.rgba()`, `.hexAlpha()`, `.hsl()`, `.hwb()`, `.lab()`, `.lch()`, `.oklab()`, `.oklch()`, `.displayP3()`) or `.formatAs(...)`. `omitOpaqueAlpha` drops the alpha slot for an opaque colour where it is optional (lossless, off by default).
335
83
 
336
- For m and unit helpers, errors include a trimmed stack hint in non-production by default.
337
- You can disable or force stack hints globally:
84
+ **Strictness.** When a render cannot faithfully hold the colour (dropping a real alpha, out of sRGB gamut, modifying a symbolic colour), `strictness` decides: `auto` (default, throw in dev, warn in prod), `throw`, `warn`, or `silent`.
338
85
 
86
+ ```ts
87
+ color('#3366cc80').rgb().css(); // throws in dev (rgb carries no alpha)
88
+ color('#3366cc80', { strictness: 'silent' }).rgb().css(); // 'rgb(51, 102, 204)' (alpha dropped)
339
89
  ```
340
- import { setErrorConfig } from "css-calipers";
341
90
 
342
- // Disable stack hints everywhere (for production).
343
- setErrorConfig({ stackHints: "off" });
91
+ **Transparency.** A fully transparent colour renders as the `transparent` keyword by default; configurable with `{ transparent: 'keyword' | 'white' | 'black' | 'preserve' }` or per render with `.transparentAs(mode)`. See `examples/transparency.example.ts`.
344
92
 
345
- // Force stack hints everywhere (useful in dev or tests).
346
- setErrorConfig({ stackHints: "on" });
347
- ```
93
+ **Custom formats.** `createColor({ formats })` binds custom format plugins. A plugin bridges the input and output edges (storage stays canonical OKLCH) and gets a typed named selector; author one with `defineColorSpace`, and an optional `fallback` hook rewrites its output into browser-safe CSS. See `examples/custom-format.example.ts` (its "zoo" format is a deliberately silly extensibility demo, not a real format), `examples/plugin-fallback.example.ts`, and `docs/adding-a-color-format.md`.
348
94
 
349
- ---
95
+ ## Measurements
350
96
 
351
- ## Factory entrypoint (optional)
97
+ `m(value, unit?)` builds a measurement (unit defaults to `px`, lower-cased). Arithmetic, `round`, and `clamp` return new measurements in the same unit. Per-unit helpers bind the unit (`mPx`, `mEm`, `mRem`, `mPercent`, `mCqw`, ...) across every unit family: absolute, font-relative, viewport, container, angle, time, frequency, resolution, and grid.
352
98
 
353
- If you want instance-scoped configuration and a single re-export surface, use
354
- the factory entrypoint. The instance includes core helpers and unit helpers.
99
+ ## Integers and floats
355
100
 
356
- ```
357
- import { createCalipers } from "css-calipers/factory";
101
+ `i()` (a whole number) and `f()` (a real number) are constrained scalars for the unitless number space CSS leaves untyped. Both validate at construction and re-validate on every operation, so a constrained value stays valid (or throws) through arithmetic. `clamp(min, max)` snaps into range instead of throwing; `hardenInteger({ min, max })` / `hardenFloat({ min, max })` bind a constraint once into a reusable factory. See `examples/integers-floats.example.ts`.
358
102
 
359
- const calipers = createCalipers({
360
- errorConfig: { stackHints: "on" },
361
- });
103
+ ## Ratios
362
104
 
363
- export const { m, mPx, units } = calipers;
364
- ```
105
+ `r(numerator, denominator?)` (denominator `1` when omitted) accepts typed integers and floats on either side, with helpers `simplifyRatio`, `reduceRatio`, `normalizeRatio`, and `parseRatio`. See `examples/ratio.example.ts`.
365
106
 
366
- See [examples/factory-wrapper.example.ts](examples/factory-wrapper.example.ts)
367
- for a wrapper module you can re-export across your project.
107
+ ## Hardening and constraints
368
108
 
369
- ---
109
+ Refinements run a runtime check and return the same value branded with the constraint, so a function can demand "a non-negative measurement" and the compiler rejects anything unchecked (brands are keyed by a private symbol). The built-ins are `nonNegative`, `nonPositive`, and `inRange(min, max)`, each exposing `.is` / `.ensure` / `.check` / `.hardenWith`. `inRange` carries its literal bounds in the type. Build your own with `makeMeasurementRefinement`. The full model is in `docs/hardening.md`, with runnable examples in `examples/refinements.example.ts`.
370
110
 
371
- ## Co-existing with other systems
111
+ ## Per-property value helpers live in the books layer
372
112
 
373
- You don’t have to convert everything at once, or at all. If it fits your setup,
374
- you can write small adapters that accept existing CSS strings, CSS-Calipers
375
- measurements, or plain numbers and turn them into CSS values. CSS-Calipers can
376
- be dropped into an existing styling system or used from the ground up; it
377
- focuses narrowly on numeric, unit-bearing values and leaves the rest of your
378
- styling approach up to you. For a more realistic adapter pattern that
379
- normalizes mixed inputs (including CSS variables) into a single css-like value,
380
- see the line-height normalizer example referenced below.
113
+ calipers is the value-type primitives only (colour, measurements, integers, floats, ratios). The per-property value helpers (`opacity`, `zIndex`, `fontWeight`, ...) are NOT a calipers feature: they live one layer up, in the books layer. Each is a book that binds a calipers primitive to one CSS property, applies that property's bound and keyword companions, and types its `.css()` output against the matching csstype `Property.X`. The shared engine behind them is `@css-bookends/css-value-core`. For the full picture, the value-type side is mapped in `lexicons/calipers/surface.md` and the per-property side in `packages/css-value-core/surface.md`.
381
114
 
382
- ## Advanced
115
+ ## Factories
383
116
 
384
- ### String Literal Type Exclusion
117
+ The bare exports (`m`, `color`, the refinements, ...) are each a factory already called at its defaults, so the default instance and a custom instance share one construction path. The factory itself is the real configurable path and the override seam: `createCalipers({ errorConfig? })` returns a measurement instance and `createColor({ formats })` a colour instance with custom format plugins registered, and routing every consumer through a factory means you can rewrite or wrap any step (input, storage, output) with zero call-site changes. `corpus` is the lazy-defaults convenience entry: it default-exports a master factory, `createCalipersBundle({ measurements?, color? })`, that combines `createCalipers` + `createColor` under one keyed config and binds the whole calipers surface in one object (mirroring the compendium's `publishCompendium`), and it named-exports that same primitive set already bound at defaults, so you get everything wired without touching a factory yourself. (`corpus` and the bookends `@css-bookends/compendium/defaults` subpath are the only two lazy-defaults entries in the project.) Binding a factory once in one of your own modules and re-exporting the bound helper from there also keeps the blast radius of a library change small: your code imports that helper from a single seam, so a major restructuring of the library's internal paths lands in that one file, not across the hundreds or thousands of call sites that use it. And because each factory call returns its own independent instance, several configurations coexist side by side with no shared global state to collide: a `createColor` that emits hex and another that emits oklch, or a strict instance next to a clamping one, all live at once, with no cascade or global state to fight (each instance is just a value in scope, not a stylesheet competing in the cascade). See `examples/factory-wrapper.example.ts`.
385
118
 
386
- When helpers must _exclude_ CSS-Calipers–emitted numeric, unit-bearing CSS values from a keyword union,
387
- use the exported `MeasurementString` type together with your existing CSS
388
- property typings (for example, the `Property` types from the `csstype`
389
- package):
119
+ All of that power is opt-in. If you just want sensible defaults and none of the above, you never touch a factory: the bare `m` / `color` / refinement exports are ready as-is, and `corpus` hands you the whole primitive set bound at defaults in one import.
390
120
 
391
- ```ts
392
- import type { MeasurementString } from "css-calipers";
393
- import type { Property } from "csstype";
121
+ ## Documentation
394
122
 
395
- type SpacingKeyword = Exclude<
396
- Extract<Property.Margin, string>,
397
- MeasurementString
398
- >;
399
- ```
123
+ Deeper dives live in `docs/`:
400
124
 
401
- This lets helpers stay strict: `IMeasurement` for numeric, unit-bearing CSS values; targeted string
402
- keywords for symbolic CSS values, without reintroducing vague unions like
403
- `MeasurementLike`.
404
-
405
- ### Integration Patterns
406
-
407
- - **Typed helpers:** Accept either `IMeasurement` or a constrained keyword type,
408
- never a generic string.
409
- - **Pre-emission transforms:** Compose all math in CSS-Calipers, emit once at
410
- the style boundary.
411
- - **Build-time pipelines:** Run measurement math in Node or a build step
412
- (scripts, codegen, or bundler plugins) and emit plain CSS or tokens for your
413
- existing styling system so runtime only sees static values.
414
- - **Unit guards in debug:** Use `assertUnit()` in dev-only blocks to confirm
415
- consistency between related measurements.
416
- - **CSS variables:** Pass CSS-Calipers `.css()` output into style layers that
417
- interpolate them, but don’t try to store `var(--token)` inside the library.
418
-
419
- ---
420
-
421
- ## Philosophy & Boundaries
422
-
423
- - **Measurement math lives here; string composition lives elsewhere.**
424
- Use CSS-Calipers for unit-aware calculations, then hand results to
425
- helpers/adapters that emit CSS literals. Keep `calc()`/`linear-gradient()` logic outside
426
- the library so measurement objects remain pure.
427
-
428
- - **`.css()` at runtime is an edge, not a habit.**
429
- You can call `.css()` at runtime, but prefer emitting once to avoid hot-path
430
- string churn.
431
-
432
- - **Numbers are operands, not CSS-Calipers values.**
433
- You cannot create a CSS-Calipers value without a unit. Pass plain numbers as
434
- operands (`add`, `subtract`, `multiply`, `divide`) or combine with another
435
- `IMeasurement`, but never store bare numbers inside library state. If a value
436
- lacks both number and unit, CSS-Calipers won’t track it; you own whatever
437
- logic wraps it.
438
-
439
- - **Model keywords explicitly (not “escape hatches”).**
440
- If a helper needs symbolic CSS (e.g., `'auto'`, `'fit-content'`), define a
441
- precise keyword type and purposely exclude the emitted string type from
442
- CSS-Calipers so numeric, unit-bearing CSS values remain the default path.
443
-
444
- - **CSS custom properties coexist; they don’t mix.**
445
- Third-party primitives exposing `var(--token)` should keep those values as raw
446
- CSS strings. CSS-Calipers is intentionally narrow: it works with numeric
447
- measurements and unit-safe conversions, not tokens or CSS variables. You can
448
- still use `var(...)` and token strings anywhere in your styling system; they
449
- just sit outside the library. If you want those values to flow through
450
- CSS-Calipers, first extract the numeric value and unit in your own code and
451
- then pass that measurement into the library.
452
-
453
- ## Using CSS-Calipers in a larger styling system
454
-
455
- CSS is inherently flexible: the same property can accept numbers, unit-bearing
456
- strings, keywords, and CSS variables. CSS-Calipers is one focused piece of that
457
- ecosystem. It keeps the numeric, unit-bearing parts typed and predictable, and
458
- lets the rest of your styling system own tokens, variables, and higher-level
459
- APIs.
460
-
461
- For a worked example of this pattern, see
462
- [examples/lineHeight-normalizer.example.ts](examples/lineHeight-normalizer.example.ts). It shows a helper that accepts a
463
- `lineHeight` value from a CMS or configuration (numbers, numeric strings with
464
- units, keywords like `"normal"`, or CSS variables such as
465
- `"var(--body-line-height)"`) and normalizes them into a value with a `.css()`
466
- method. CSS-Calipers only participates when there is a concrete measurement
467
- (numbers and units); keywords and CSS variables remain plain CSS strings owned
468
- by your styling layer. That’s the intended scope: CSS will always be a mix of
469
- values, but the library gives you a tight, unit-safe boundary for the numeric
470
- parts inside a broader styling solution.
471
-
472
- ### Module guides
473
-
474
- Deeper guides live alongside this README:
475
-
476
- - Measurements core: [README_MEASUREMENT.md](README_MEASUREMENT.md)
477
- - Media queries: now in [`@css-bookends/media-queries`](https://github.com/slafleche/css-bookends)
478
-
479
- ### Further examples in this repo
480
-
481
- The `examples/` folder contains a few non-published usage sketches:
482
-
483
- - [examples/lineHeight-normalizer.example.ts](examples/lineHeight-normalizer.example.ts) &mdash;
484
- mixed input normalization for `lineHeight` (numbers, strings, CSS variables)
485
- into a single value with a `.css()` method.
486
- - [examples/validation-unit-tests.example.ts](examples/validation-unit-tests.example.ts) &mdash;
487
- simple unit tests that enforce spacing token invariants (shared units and
488
- small &le; large).
489
- - [examples/validation-and-runtime-checks.example.ts](examples/validation-and-runtime-checks.example.ts) &mdash;
490
- dev-only validation around shared tokens in two different consumers (HTML
491
- string and style object) using the same line-height measurement.
492
- - [examples/factory-wrapper.example.ts](examples/factory-wrapper.example.ts) &mdash;
493
- instance-scoped factory wrapper that re-exports the helpers.
125
+ - `docs/number-space.md` - which scalar CSS values are worth typing, and why.
126
+ - `docs/hardening.md` - the refinement model, branded types, and custom refinements.
127
+ - `docs/custom-format-registration.md` and `docs/adding-a-color-format.md` - registering custom colour formats end to end.
128
+ - `docs/color-format-popularity.md` - the usage data behind the default output ladder.
129
+ - `docs/integration.md` - using calipers with a styling pipeline.
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.displayP3 = void 0;
4
+ const internals_1 = require("../internals");
5
+ const types_1 = require("../types");
6
+ /**
7
+ * display-p3 — wider-than-sRGB device RGB (the P3 gamut), with alpha. This is the
8
+ * one gamut-DEPENDENT format: a fallback should also gate on
9
+ * `@media (color-gamut: p3)`, since the wider color only shows on a P3 display. Out
10
+ * of P3 is clamped (strictness-governed). Not a floor.
11
+ *
12
+ * See `display-p3.md`.
13
+ */
14
+ exports.displayP3 = (0, types_1.defineColorSpace)({
15
+ format: 'displayP3',
16
+ hasAlpha: true,
17
+ gamut: 'p3',
18
+ supportsProbe: '(color: color(display-p3 0 0 0))',
19
+ gamutDependent: true,
20
+ srgbFloor: false,
21
+ render: (color, cfg) => {
22
+ const c = (0, internals_1.toP3)((0, internals_1.fitGamut)(color, internals_1.inP3, 'p3', cfg.strictness));
23
+ return `color(display-p3 ${(0, internals_1.round)(c.r, 5)} ${(0, internals_1.round)(c.g, 5)} ${(0, internals_1.round)(c.b, 5)}${(0, internals_1.alphaSlot)(color, cfg)})`;
24
+ },
25
+ });
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.chooseFormat = void 0;
4
+ const index_1 = require("./index");
5
+ const internals_1 = require("./internals");
6
+ const resolve_1 = require("./resolve");
7
+ const descriptorFor = (format) => (0, resolve_1.asDescriptor)(format, index_1.colorFormats);
8
+ /**
9
+ * Whether a format can FAITHFULLY hold the color: its gamut contains the color, and
10
+ * it carries alpha if the color is non-opaque. 8-bit sRGB precision is accepted as
11
+ * faithful, so gamut + alpha are the only fit criteria.
12
+ */
13
+ const fits = (color, format) => {
14
+ const d = descriptorFor(format);
15
+ const gamutOk = d.gamut === 'unbounded'
16
+ ? true
17
+ : d.gamut === 'p3'
18
+ ? (0, internals_1.inP3)(color)
19
+ : (0, internals_1.inSrgb)(color);
20
+ const alphaOk = d.hasAlpha || !(0, internals_1.hasRealAlpha)(color);
21
+ return gamutOk && alphaOk;
22
+ };
23
+ /**
24
+ * Resolve an output config to a single format. A single format passes through
25
+ * unchanged (an explicit choice, no escalation). A priority list escalates to the
26
+ * first format that faithfully holds the color, or the last entry if none do (which
27
+ * then clamps via the render step's strictness).
28
+ */
29
+ const chooseFormat = (color, output) => {
30
+ if (!Array.isArray(output)) {
31
+ return output;
32
+ }
33
+ const list = output;
34
+ for (const format of list) {
35
+ if (fits(color, format)) {
36
+ return format;
37
+ }
38
+ }
39
+ return list[list.length - 1];
40
+ };
41
+ exports.chooseFormat = chooseFormat;