@tenphi/glaze 0.0.0-snapshot.875bb2f → 0.0.0-snapshot.8827a91

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 CHANGED
@@ -370,8 +370,30 @@ const sRGBGammaToLinear = (val) => {
370
370
  const abs = Math.abs(val);
371
371
  return abs <= .04045 ? val / 12.92 : sign * Math.pow((abs + .055) / 1.055, 2.4);
372
372
  };
373
+ /** Gamma-encoded sRGB clamped to the display gamut — what a browser paints. */
374
+ function toDisplayGamma(linearRgb) {
375
+ return [
376
+ Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[0]))),
377
+ Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[1]))),
378
+ Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[2])))
379
+ ];
380
+ }
381
+ /**
382
+ * Browser alpha compositing: `source-over` interpolates the gamma-encoded
383
+ * channels, not linear light (50% black over white paints `#808080`).
384
+ * Takes display-gamma inputs and returns the composite as linear sRGB for
385
+ * the luminance pipeline.
386
+ */
387
+ function compositeOverGamma(baseGamma, overlayGamma, alpha) {
388
+ return [
389
+ sRGBGammaToLinear(baseGamma[0] + (overlayGamma[0] - baseGamma[0]) * alpha),
390
+ sRGBGammaToLinear(baseGamma[1] + (overlayGamma[1] - baseGamma[1]) * alpha),
391
+ sRGBGammaToLinear(baseGamma[2] + (overlayGamma[2] - baseGamma[2]) * alpha)
392
+ ];
393
+ }
373
394
  /**
374
395
  * Convert OKHSL to gamma-encoded sRGB (clamped to 0–1).
396
+ * h: 0–360, s: 0–1, l: 0–1. Returns [r, g, b] with each channel 0–1.
375
397
  */
376
398
  function okhslToSrgb(h, s, l, pastel = false) {
377
399
  const lin = okhslToLinearSrgb(h, s, l, pastel);
@@ -581,47 +603,72 @@ function fmt$1(value, decimals) {
581
603
  return parseFloat(value.toFixed(decimals)).toString();
582
604
  }
583
605
  /**
606
+ * Every `format*` writer takes `s` / `l` / `t` on the **0–1 factor scale** —
607
+ * the same scale every producer in the library hands back (`resolve()`,
608
+ * `variantToOkhsl`, `srgbToOkhsl`, `oklabToOkhsl`, `okhslToOklab`,
609
+ * `okhslToSrgb`). The percentages are an output detail: the writers multiply
610
+ * by 100 themselves when the CSS syntax asks for a percentage.
611
+ *
612
+ * Before 2.0 the writers took 0–100 while everything producing those values
613
+ * returned 0–1, so the obvious composition was off by 100x and failed
614
+ * silently — `0.7` is a legal percentage, so the result was a valid CSS string
615
+ * naming a near-black color. A value above 1 can only be that old
616
+ * percentage-scale input, so warn about it loudly rather than emit a wrong
617
+ * color quietly.
618
+ */
619
+ const scaleWarnCache = /* @__PURE__ */ new Set();
620
+ function warnPercentScale(fn, ...values) {
621
+ if (!values.some((v) => v > 1.000001)) return;
622
+ if (!scaleWarnCache.has(fn)) {
623
+ scaleWarnCache.add(fn);
624
+ console.warn(`glaze: ${fn}() got a value above 1 — it takes the 0-1 factors every Glaze producer returns (resolve(), variantToOkhsl, srgbToOkhsl), not 0-100 percentages. Divide by 100, or drop the "* 100" left over from the pre-2.0 signature.`);
625
+ }
626
+ }
627
+ /**
584
628
  * Format OKHSL values as a CSS `okhsl(H S% L%)` string.
585
- * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
629
+ * h: 0–360, s: 0–1, l: 0–1 (factor scale, as returned by every converter).
586
630
  */
587
631
  function formatOkhsl(h, s, l, pastel = false) {
632
+ warnPercentScale("formatOkhsl", s, l);
588
633
  let outS = s;
589
- if (pastel) outS = oklabToOkhsl(okhslToOklab(h, s / 100, l / 100, true), false)[1] * 100;
590
- return `okhsl(${fmt$1(h, 2)} ${fmt$1(outS, 2)}% ${fmt$1(l, 2)}%)`;
634
+ if (pastel) outS = oklabToOkhsl(okhslToOklab(h, s, l, true), false)[1];
635
+ return `okhsl(${fmt$1(h, 2)} ${fmt$1(outS * 100, 2)}% ${fmt$1(l * 100, 2)}%)`;
591
636
  }
592
637
  /**
593
638
  * Format OKHST values as a CSS `okhst(H S% T%)` string.
594
- * h: 0–360, s: 0–100, t: 0–100 (percentage scale for s and t).
639
+ * h: 0–360, s: 0–1, t: 0–1 (factor scale, matching `ResolvedColorVariant`).
595
640
  *
596
641
  * Pastel recompute matches `formatOkhsl`: convert via OKLab so external
597
642
  * parsers that only understand non-pastel OKHST render identically.
598
643
  */
599
644
  function formatOkhst(h, s, t, pastel = false) {
645
+ warnPercentScale("formatOkhst", s, t);
600
646
  let outS = s;
601
647
  if (pastel) {
602
648
  const REF_EPS = .05;
603
649
  const den = Math.log(1 + REF_EPS) - Math.log(REF_EPS);
604
- const y = Math.exp(t / 100 * den + Math.log(REF_EPS)) - REF_EPS;
605
- const l = toe(Math.cbrt(Math.max(0, y)));
606
- outS = oklabToOkhsl(okhslToOklab(h, s / 100, l, true), false)[1] * 100;
650
+ const y = Math.exp(t * den + Math.log(REF_EPS)) - REF_EPS;
651
+ outS = oklabToOkhsl(okhslToOklab(h, s, toe(Math.cbrt(Math.max(0, y))), true), false)[1];
607
652
  }
608
- return `okhst(${fmt$1(h, 2)} ${fmt$1(outS, 2)}% ${fmt$1(t, 2)}%)`;
653
+ return `okhst(${fmt$1(h, 2)} ${fmt$1(outS * 100, 2)}% ${fmt$1(t * 100, 2)}%)`;
609
654
  }
610
655
  /**
611
656
  * Format OKHSL values as a CSS `rgb(R G B)` string.
612
657
  * Uses 2 decimal places to avoid 8-bit quantization contrast loss.
613
- * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
658
+ * h: 0–360, s: 0–1, l: 0–1 (factor scale, as returned by every converter).
614
659
  */
615
660
  function formatRgb(h, s, l, pastel = false) {
616
- const [r, g, b] = okhslToSrgb(h, s / 100, l / 100, pastel);
661
+ warnPercentScale("formatRgb", s, l);
662
+ const [r, g, b] = okhslToSrgb(h, s, l, pastel);
617
663
  return `rgb(${parseFloat((r * 255).toFixed(2))} ${parseFloat((g * 255).toFixed(2))} ${parseFloat((b * 255).toFixed(2))})`;
618
664
  }
619
665
  /**
620
666
  * Format OKHSL values as a CSS `hsl(H S% L%)` string.
621
- * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
667
+ * h: 0–360, s: 0–1, l: 0–1 (factor scale, as returned by every converter).
622
668
  */
623
669
  function formatHsl(h, s, l, pastel = false) {
624
- const [r, g, b] = okhslToSrgb(h, s / 100, l / 100, pastel);
670
+ warnPercentScale("formatHsl", s, l);
671
+ const [r, g, b] = okhslToSrgb(h, s, l, pastel);
625
672
  const max = Math.max(r, g, b);
626
673
  const min = Math.min(r, g, b);
627
674
  const delta = max - min;
@@ -638,10 +685,11 @@ function formatHsl(h, s, l, pastel = false) {
638
685
  }
639
686
  /**
640
687
  * Format OKHSL values as a CSS `oklch(L C H)` string.
641
- * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
688
+ * h: 0–360, s: 0–1, l: 0–1 (factor scale, as returned by every converter).
642
689
  */
643
690
  function formatOklch(h, s, l, pastel = false) {
644
- const [L, C, hh] = okhslToOklch(h, s / 100, l / 100, pastel);
691
+ warnPercentScale("formatOklch", s, l);
692
+ const [L, C, hh] = okhslToOklch(h, s, l, pastel);
645
693
  return `oklch(${fmt$1(L, 4)} ${fmt$1(C, 4)} ${fmt$1(hh, 2)})`;
646
694
  }
647
695
  /**
@@ -675,6 +723,8 @@ function okhslToOklch(h, s, l, pastel = false) {
675
723
  /**
676
724
  * Build a fresh defaults object. Called from module init and from
677
725
  * `resetConfig()` so the two paths can't drift.
726
+ *
727
+ * `pastel: false` is a fixed instance default — not globally configurable.
678
728
  */
679
729
  function defaultConfig() {
680
730
  return {
@@ -699,9 +749,21 @@ function defaultConfig() {
699
749
  },
700
750
  autoFlip: true,
701
751
  pastel: false,
702
- inferRole: true
752
+ inferRole: true,
753
+ contrastLevel: "auto"
703
754
  };
704
755
  }
756
+ /**
757
+ * Validate an authored `contrastLevel`. Numbers clamp to 0–100 so a slider
758
+ * can't produce an out-of-range level; a non-finite number throws rather than
759
+ * silently reading as `'auto'`, which would turn a `NaN` slider value into an
760
+ * invisible no-op.
761
+ */
762
+ function normalizeContrastLevel(value) {
763
+ if (value === void 0 || value === "auto") return "auto";
764
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`glaze: contrastLevel must be a finite number 0–100 or 'auto' (got ${String(value)}).`);
765
+ return Math.max(0, Math.min(100, value));
766
+ }
705
767
  let globalConfig = defaultConfig();
706
768
  /**
707
769
  * Monotonic counter incremented on every `configure()` / `resetConfig()`
@@ -738,9 +800,11 @@ function configure(config) {
738
800
  highContrast: config.modes?.highContrast ?? globalConfig.modes.highContrast
739
801
  },
740
802
  shadowTuning: config.shadowTuning ?? globalConfig.shadowTuning,
803
+ glowTuning: config.glowTuning ?? globalConfig.glowTuning,
741
804
  autoFlip: config.autoFlip ?? globalConfig.autoFlip,
742
- pastel: config.pastel ?? globalConfig.pastel,
743
- inferRole: config.inferRole ?? globalConfig.inferRole
805
+ pastel: false,
806
+ inferRole: config.inferRole ?? globalConfig.inferRole,
807
+ contrastLevel: normalizeContrastLevel(config.contrastLevel ?? globalConfig.contrastLevel)
744
808
  };
745
809
  }
746
810
  function resetConfig() {
@@ -752,9 +816,15 @@ function resetConfig() {
752
816
  * Only fields present in `override` are replaced; others fall through
753
817
  * from `base`. `false` for tone windows passes through as-is
754
818
  * (treated as the full range by `activeWindow()` in okhst.ts).
819
+ *
820
+ * `pastel` is instance-only: `override.pastel ?? false`, never inherited
821
+ * from the global base.
755
822
  */
756
823
  function mergeConfig(base, override) {
757
- if (!override) return base;
824
+ if (!override) return base.pastel === false ? base : {
825
+ ...base,
826
+ pastel: false
827
+ };
758
828
  return {
759
829
  lightTone: override.lightTone !== void 0 ? override.lightTone : base.lightTone,
760
830
  darkTone: override.darkTone !== void 0 ? override.darkTone : base.darkTone,
@@ -762,18 +832,25 @@ function mergeConfig(base, override) {
762
832
  states: base.states,
763
833
  modes: base.modes,
764
834
  shadowTuning: override.shadowTuning ?? base.shadowTuning,
835
+ glowTuning: override.glowTuning ?? base.glowTuning,
765
836
  autoFlip: override.autoFlip ?? base.autoFlip,
766
- pastel: override.pastel ?? base.pastel,
767
- inferRole: override.inferRole ?? base.inferRole
837
+ pastel: override.pastel ?? false,
838
+ inferRole: override.inferRole ?? base.inferRole,
839
+ contrastLevel: normalizeContrastLevel(override.contrastLevel ?? base.contrastLevel)
768
840
  };
769
841
  }
770
842
  /**
771
- * Freeze the resolve-relevant effective config as a plain override.
772
- * Used by `theme.export()` and standalone color-token creation so
773
- * restored snapshots ignore later `configure()` calls for these fields.
843
+ * Freeze `getConfig() ∪ instanceLocal ∪ exportArg` as a plain, resolve-relevant
844
+ * override for authoring export, so restored snapshots pin these fields. Later
845
+ * wins; nested objects (`shadowTuning` / `glowTuning`) replace wholesale. The
846
+ * final `structuredClone` detaches tone-window / tuning objects that `mergeConfig`
847
+ * may still share with the live global config.
774
848
  */
775
- function buildEffectiveConfigOverride(userOverride) {
776
- const effective = mergeConfig(getConfig(), userOverride);
849
+ function freezeConfigForExport(instanceLocal, exportArg) {
850
+ const effective = mergeConfig(getConfig(), {
851
+ ...instanceLocal,
852
+ ...exportArg
853
+ });
777
854
  const out = {
778
855
  lightTone: effective.lightTone,
779
856
  darkTone: effective.darkTone,
@@ -782,8 +859,11 @@ function buildEffectiveConfigOverride(userOverride) {
782
859
  pastel: effective.pastel,
783
860
  inferRole: effective.inferRole
784
861
  };
785
- if (effective.shadowTuning !== void 0) out.shadowTuning = { ...effective.shadowTuning };
786
- return out;
862
+ if (effective.shadowTuning !== void 0) out.shadowTuning = effective.shadowTuning;
863
+ if (effective.glowTuning !== void 0) out.glowTuning = effective.glowTuning;
864
+ const authoredLevel = exportArg?.contrastLevel ?? instanceLocal?.contrastLevel;
865
+ if (authoredLevel !== void 0) out.contrastLevel = normalizeContrastLevel(authoredLevel);
866
+ return structuredClone(out);
787
867
  }
788
868
 
789
869
  //#endregion
@@ -791,8 +871,13 @@ function buildEffectiveConfigOverride(userOverride) {
791
871
  /**
792
872
  * Current authoring-export schema version. Bump when the export shape
793
873
  * changes in a non-compatible way. Written on every `.export()` snapshot.
874
+ *
875
+ * - `1` — Glaze 2.x.
876
+ * - `2` — Glaze 3: `shadow` `intensity` / `fg` / `tuning` changed meaning and
877
+ * `glow` was added. Version-1 theme snapshots that carry shadow defs or a
878
+ * `shadowTuning` are rejected on restore.
794
879
  */
795
- const GLAZE_EXPORT_VERSION = 1;
880
+ const GLAZE_EXPORT_VERSION = 2;
796
881
 
797
882
  //#endregion
798
883
  //#region src/serialize.ts
@@ -804,15 +889,32 @@ function isPlainObject(data) {
804
889
  return typeof data === "object" && data !== null && !Array.isArray(data);
805
890
  }
806
891
  /**
807
- * Reject unknown future schema versions. Missing `version` is allowed
808
- * (legacy snapshots). Older versions than current are accepted.
892
+ * Reject unknown / invalid schema versions. Missing `version` is allowed
893
+ * (legacy snapshots). Present versions must be an integer in
894
+ * `1..=GLAZE_EXPORT_VERSION`.
809
895
  */
810
896
  function assertExportVersion(data, factory) {
811
897
  if (data.version === void 0) return;
812
- if (typeof data.version !== "number" || !Number.isFinite(data.version)) throw new Error(`${factory}: invalid "version" field — expected a number (got ${JSON.stringify(data.version)}).`);
898
+ if (typeof data.version !== "number" || !Number.isInteger(data.version) || data.version < 1) throw new Error(`${factory}: invalid "version" field — expected an integer >= 1 (got ${JSON.stringify(data.version)}).`);
813
899
  if (data.version > GLAZE_EXPORT_VERSION) throw new Error(`${factory}: unsupported export version ${data.version} (this library supports version ${GLAZE_EXPORT_VERSION}). Upgrade @tenphi/glaze to load this snapshot.`);
814
900
  }
815
901
  /**
902
+ * Reject a version-1 (Glaze 2) theme snapshot that carries shadow colors or a
903
+ * `shadowTuning`. Glaze 3 changed what shadow `intensity`, `fg` and tuning
904
+ * mean, so restoring one would silently re-render every shadow differently.
905
+ * Version-1 snapshots without shadows load as before. `fallbackVersion` is the
906
+ * enclosing palette's version, for a theme entry that carries none of its own.
907
+ */
908
+ function assertNoLegacyShadows(data, factory, fallbackVersion) {
909
+ if ((data.version ?? fallbackVersion) !== 1) return;
910
+ const colors = isPlainObject(data.colors) ? data.colors : {};
911
+ const shadows = Object.keys(colors).filter((name) => isPlainObject(colors[name]) && colors[name].type === "shadow");
912
+ const hasTuning = isPlainObject(data.config) && data.config.shadowTuning !== void 0;
913
+ if (shadows.length === 0 && !hasTuning) return;
914
+ const what = shadows.length > 0 ? `shadow colors (${shadows.map((n) => JSON.stringify(n)).join(", ")})` : "a \"shadowTuning\" config";
915
+ throw new Error(`${factory}: this snapshot is export version 1 (Glaze 2) and contains ${what}. Glaze 3 changed what shadow "intensity", "fg" and tuning mean, so it would restore with different shadows. Re-author them as described in docs/migration.md ("3.0 — shadows and glows") and export again.`);
916
+ }
917
+ /**
816
918
  * When `kind` is present, it must match the factory. Missing `kind` is
817
919
  * allowed for legacy snapshots.
818
920
  */
@@ -851,52 +953,6 @@ function isPaletteExport(data) {
851
953
  return hasPaletteShape(data);
852
954
  }
853
955
 
854
- //#endregion
855
- //#region src/format-guard.ts
856
- const NON_NATIVE_FORMATS = new Set(["okhsl", "okhst"]);
857
- /**
858
- * Throw when a non-native Glaze color space is requested for an export that
859
- * emits raw CSS or non-Tasty token maps.
860
- */
861
- function assertNativeFormat(format, method) {
862
- if (format !== void 0 && NON_NATIVE_FORMATS.has(format)) throw new Error(`glaze: ${format} output is only supported by tasty() (not a native CSS color space). Use tasty({ format: '${format}' }) or pick a native format (oklch|hsl|rgb) for ${method}().`);
863
- }
864
- const SCHEME_FIELDS = [
865
- {
866
- field: "light",
867
- modes: () => true
868
- },
869
- {
870
- field: "dark",
871
- modes: (m) => m.dark
872
- },
873
- {
874
- field: "lightContrast",
875
- modes: (m) => m.highContrast
876
- },
877
- {
878
- field: "darkContrast",
879
- modes: (m) => m.dark && m.highContrast
880
- }
881
- ];
882
- /**
883
- * Throw when `splitHue` is enabled but any exported color is not pastel.
884
- * Hue rotation is only clip-free when chroma is bounded by the hue-independent
885
- * safe chroma (`computeSafeChromaOKLCH`).
886
- */
887
- function assertAllPastel(resolved, modes) {
888
- const nonPastel = [];
889
- for (const [name, color] of resolved) for (const { field, modes: active } of SCHEME_FIELDS) {
890
- if (!active(modes)) continue;
891
- if (color[field].pastel !== true) {
892
- if (!nonPastel.includes(name)) nonPastel.push(name);
893
- break;
894
- }
895
- }
896
- if (nonPastel.length === 0) return;
897
- throw new Error(`glaze: splitHue requires every color to be pastel (hue rotation is only clip-free when chroma is bounded by the hue-independent safe chroma). Non-pastel: ${nonPastel.join(", ")}. Set pastel: true (global or per-color) or drop splitHue.`);
898
- }
899
-
900
956
  //#endregion
901
957
  //#region src/hc-pair.ts
902
958
  function pairNormal(p) {
@@ -908,6 +964,61 @@ function pairHC(p) {
908
964
  function clamp(v, min, max) {
909
965
  return Math.max(min, Math.min(max, v));
910
966
  }
967
+ function lerp(a, b, f) {
968
+ return a + (b - a) * f;
969
+ }
970
+ /**
971
+ * Blend fraction at/above which an un-interpolable HC pair switches from its
972
+ * normal entry to its high-contrast one (level 50).
973
+ */
974
+ const PAIR_SWITCH = .5;
975
+ /** Blend fraction (0–1) for an authored 0–100 contrast level. */
976
+ function levelFraction(level) {
977
+ return clamp(level, 0, 100) / 100;
978
+ }
979
+ /**
980
+ * Manual-contrast blend fraction (0–1) for a resolved config, or `undefined`
981
+ * in `'auto'` mode, where the normal variants take the authored normal entries
982
+ * as-is.
983
+ *
984
+ * Note `contrastLevel: 0` yields `0`, not `undefined`. The two select different
985
+ * branches, and an authored `0` is a slider position that `.export()` freezes
986
+ * where an absent level is not — but they are not an *output* distinction: at
987
+ * fraction 0 every interpolation returns its normal entry verbatim, so level 0
988
+ * reproduces `'auto'` bit for bit.
989
+ */
990
+ function contrastFraction(config) {
991
+ const level = config.contrastLevel;
992
+ if (typeof level !== "number" || !Number.isFinite(level)) return void 0;
993
+ return levelFraction(level);
994
+ }
995
+ /**
996
+ * Whether the high-contrast variants are exact duplicates of the normal ones —
997
+ * true only at `contrastLevel: 100`, where the normal passes already resolve at
998
+ * full contrast.
999
+ *
1000
+ * The level otherwise says nothing about high contrast: it positions the normal
1001
+ * variants, while `lightContrast` / `darkContrast` stay the true high-contrast
1002
+ * resolution at every level. This predicate marks the one level where that tier
1003
+ * carries no new information, so callers can skip the two high-contrast passes,
1004
+ * their drift checks, and the redundant output tier.
1005
+ */
1006
+ function hcMirrorsNormal(config) {
1007
+ return contrastFraction(config) === 1;
1008
+ }
1009
+ /**
1010
+ * A numeric HC pair at a blend fraction (shadow / glow `intensity`, mix `value`).
1011
+ *
1012
+ * The endpoints return the authored entry *by identity* rather than through
1013
+ * float arithmetic — `a + (b - a) * 1` is not bit-exactly `b` in IEEE 754, and
1014
+ * levels 0 / 100 must reproduce the classic output exactly.
1015
+ */
1016
+ function numberAt(p, f) {
1017
+ if (!Array.isArray(p)) return p;
1018
+ if (f <= 0) return p[0];
1019
+ if (f >= 1) return p[1];
1020
+ return lerp(p[0], p[1], f);
1021
+ }
911
1022
  /** Whether a tone value is an extreme keyword (`'max'` / `'min'`). */
912
1023
  function isExtremeTone(value) {
913
1024
  return value === "max" || value === "min";
@@ -952,6 +1063,34 @@ function parseToneValue(value) {
952
1063
  };
953
1064
  }
954
1065
  /**
1066
+ * Parse an authored tone pair at a manual-contrast blend fraction, returning
1067
+ * the same normalized shape as {@link parseToneValue}.
1068
+ *
1069
+ * Same-kind numeric pairs interpolate their magnitude — absolute tones
1070
+ * (`[30, 20]` → 25 at level 50) and relative deltas (`['+10', '+20']` → +15).
1071
+ * Everything else is un-interpolable and switches at {@link PAIR_SWITCH}:
1072
+ * extremes carry no magnitude, and a mixed-kind pair would change *which*
1073
+ * resolver branch runs mid-ramp (absolute remap vs. extreme-against-base vs.
1074
+ * base-anchored delta), putting a discontinuity at level 100 — exactly where
1075
+ * the output must stay bit-exact.
1076
+ *
1077
+ * Returns a parsed struct rather than a `ToneValue` so a blended relative
1078
+ * delta never round-trips through a `'+15.5'` string, and so `kind` — which
1079
+ * selects the resolver branch — cannot drift.
1080
+ */
1081
+ function parseToneValueAt(p, f) {
1082
+ if (!Array.isArray(p)) return parseToneValue(p);
1083
+ if (f <= 0) return parseToneValue(p[0]);
1084
+ if (f >= 1) return parseToneValue(p[1]);
1085
+ const normal = parseToneValue(p[0]);
1086
+ const hc = parseToneValue(p[1]);
1087
+ if (normal.kind === hc.kind && normal.kind !== "extreme") return {
1088
+ kind: normal.kind,
1089
+ value: lerp(normal.value, hc.value, f)
1090
+ };
1091
+ return f < PAIR_SWITCH ? normal : hc;
1092
+ }
1093
+ /**
955
1094
  * Compute the effective hue for a color, given the theme seed hue
956
1095
  * and an optional per-color hue override.
957
1096
  */
@@ -987,7 +1126,9 @@ function isAbsoluteTone(tone) {
987
1126
  * - the resolved-variant edge adapter (`variantToOkhsl`),
988
1127
  * - the per-scheme tone mapping that replaced the Möbius dark curve
989
1128
  * (`mapToneForScheme`), the dark desaturation reducer, and the solver's scheme
990
- * tone range.
1129
+ * tone range,
1130
+ * - the scheme tone window, including the high-contrast bypass and its
1131
+ * continuous generalization under a manual contrast level.
991
1132
  *
992
1133
  * See `docs/okhst.md` for the full specification and the calibrated
993
1134
  * default constants.
@@ -1050,7 +1191,11 @@ function okhslToOkhst(c) {
1050
1191
  }
1051
1192
  /**
1052
1193
  * Edge adapter: a resolved variant stores canonical tone `t` (0–1). Convert
1053
- * it to the OKHSL `{ h, s, l }` the formatters and luminance pipeline expect.
1194
+ * it to the OKHSL `{ h, s, l }` the formatters and luminance pipeline expect —
1195
+ * `s` and `l` on the same 0–1 factor scale, so `const { h, s, l } =
1196
+ * variantToOkhsl(v)` destructures straight into `formatOkhsl` / `formatRgb` /
1197
+ * `okhslToLinearSrgb` with no rescaling. `alpha` stays on the variant; use
1198
+ * `glaze.format(v, format)` for a string that carries it.
1054
1199
  */
1055
1200
  function variantToOkhsl(v) {
1056
1201
  return {
@@ -1086,7 +1231,12 @@ function normalizeToneWindow(win) {
1086
1231
  /**
1087
1232
  * Resolve the active tone window for a scheme as OKHSL-lightness endpoints.
1088
1233
  * - HC variants always return the full range `[0, 100]` with the mode eps.
1089
- * - `false` (= "no clamping") is treated as `[0, 100]` with the reference eps.
1234
+ * - Under a manual `contrastLevel`, each endpoint is interpolated toward that
1235
+ * full range: light `10 → 0` / `100 → 100`, dark `15 → 0` / `95 → 100`. The
1236
+ * endpoints are exact — level 0 returns the configured window and level 100
1237
+ * the same literal the HC branch returns.
1238
+ * - `false` (= "no clamping") is treated as `[0, 100]` with the reference eps,
1239
+ * and is therefore level-invariant.
1090
1240
  */
1091
1241
  function activeWindow(isHighContrast, kind, config) {
1092
1242
  const win = normalizeToneWindow(kind === "dark" ? config.darkTone : config.lightTone);
@@ -1095,7 +1245,18 @@ function activeWindow(isHighContrast, kind, config) {
1095
1245
  hi: 100,
1096
1246
  eps: win.eps
1097
1247
  };
1098
- return win;
1248
+ const f = contrastFraction(config);
1249
+ if (f === void 0 || f <= 0) return win;
1250
+ if (f >= 1) return {
1251
+ lo: 0,
1252
+ hi: 100,
1253
+ eps: win.eps
1254
+ };
1255
+ return {
1256
+ lo: lerp(win.lo, 0, f),
1257
+ hi: lerp(win.hi, 100, f),
1258
+ eps: win.eps
1259
+ };
1099
1260
  }
1100
1261
  /**
1101
1262
  * Remap an authored tone (0–100) into a scheme window and return the final
@@ -1119,6 +1280,9 @@ function remapToneToLightness(authorTone, win) {
1119
1280
  * The window remap uses the mode's render eps to land a final OKHSL
1120
1281
  * lightness; that lightness is then re-expressed as canonical tone so
1121
1282
  * relative offsets and contrast stay comparable across schemes.
1283
+ *
1284
+ * A manual `contrastLevel` widens the window continuously (see
1285
+ * `activeWindow`); inversion is unaffected.
1122
1286
  */
1123
1287
  function mapToneForScheme(authorTone, mode, isDark, isHighContrast, config) {
1124
1288
  if (mode === "static") return clamp(authorTone, 0, 100);
@@ -1133,7 +1297,8 @@ function mapSaturationDark(s, mode, config) {
1133
1297
  /**
1134
1298
  * Tone search range (0–1) for the contrast solver in a given scheme.
1135
1299
  * `static` searches the full range; otherwise the scheme window's tone
1136
- * endpoints (HC bypasses to full range).
1300
+ * endpoints (HC bypasses to full range, a manual `contrastLevel` widens
1301
+ * toward it — see `activeWindow`).
1137
1302
  */
1138
1303
  function schemeToneRange(isDark, mode, isHighContrast, config) {
1139
1304
  if (mode === "static") return [0, 1];
@@ -1142,149 +1307,444 @@ function schemeToneRange(isDark, mode, isHighContrast, config) {
1142
1307
  }
1143
1308
 
1144
1309
  //#endregion
1145
- //#region src/contrast-solver.ts
1310
+ //#region src/color-value.ts
1146
1311
  /**
1147
- * Contrast solver — operates in OKHST tone.
1148
- *
1149
- * Finds the tone closest to a preferred tone that satisfies a contrast
1150
- * floor (WCAG 2 ratio or APCA Lc) against a base color. Because tone is
1151
- * contrast-uniform, the WCAG branch gets a closed-form seed and the search
1152
- * converges quickly.
1312
+ * Parsing and validation for `GlazeColorValue` — the literal color forms.
1153
1313
  *
1154
- * Public API: `findToneForContrast`, `findValueForMixContrast`,
1155
- * `resolveMinContrast`, `resolveContrastForMode`, `apcaContrast`.
1156
- */
1157
- /**
1158
- * Luminance of a linear-sRGB color in the basis the metric expects: WCAG
1159
- * relative luminance for `wcag`, APCA screen luminance (`Ys`) for `apca`.
1160
- */
1161
- function metricLuminance(metric, linearRgb) {
1162
- return metric === "apca" ? apcaLuminanceFromLinearRgb(linearRgb) : gamutClampedLuminance(linearRgb);
1163
- }
1164
- const APCA_PRESETS = {
1165
- preferred: 90,
1166
- body: 75,
1167
- content: 60,
1168
- large: 45,
1169
- "non-text": 30,
1170
- min: 15
1171
- };
1172
- /**
1173
- * APCA-W3 "Enhanced Level" delta added to a bare APCA target in high-contrast
1174
- * mode when no explicit HC value is provided (analogous to WCAG AAA over AA).
1175
- * Only applied when neither the outer `contrast` pair nor the inner `apca`
1176
- * pair carries an explicit HC entry.
1177
- */
1178
- const APCA_HC_ENHANCEMENT = 15;
1179
- /** Upper bound for an APCA Lc target after HC enhancement. */
1180
- const APCA_MAX_LC = 106;
1181
- /**
1182
- * Resolve an APCA target — a raw Lc number (kept as-is) or an `ApcaPreset`
1183
- * keyword mapped to its Lc value. The magnitude is forced non-negative.
1184
- */
1185
- function resolveApcaTarget(value) {
1186
- if (typeof value === "number") return Math.abs(value);
1187
- return APCA_PRESETS[value];
1188
- }
1189
- const CONTRAST_PRESETS = {
1190
- AA: 4.5,
1191
- AAA: 7,
1192
- "AA-large": 3,
1193
- "AAA-large": 4.5
1194
- };
1195
- /**
1196
- * WCAG high-contrast auto-promotion (analog of APCA's Enhanced Level). A bare
1197
- * AA / AA-large preset is promoted to its spec-defined "Enhanced" successor
1198
- * (SC 1.4.3 → SC 1.4.6) in high-contrast mode. AAA / AAA-large are already
1199
- * the top WCAG tier and are left unchanged. Bare numeric targets have no
1200
- * defined successor tier and are also left unchanged. An explicit HC value
1201
- * (outer or inner pair) always overrides.
1314
+ * Hex, the CSS color functions Glaze emits, and the four value-object shapes all
1315
+ * land here and come out as OKHSL. Split out of `color-token.ts` so both
1316
+ * consumers can reach it without an import cycle: standalone `glaze.color()`
1317
+ * tokens build on it, and the resolver needs it for a theme color's `from`. It
1318
+ * depends on nothing but the color math, which is what keeps that true.
1202
1319
  */
1203
- const WCAG_HC_PROMOTION = {
1204
- AA: "AAA",
1205
- "AA-large": "AAA-large"
1206
- };
1207
- function resolveMinContrast(value) {
1208
- if (typeof value === "number") return Math.max(1, value);
1209
- return CONTRAST_PRESETS[value];
1210
- }
1211
1320
  /**
1212
- * Resolve a WCAG target (number or preset) for a mode, applying the
1213
- * high-contrast auto-promotion when `explicitHC` is false and the value is an
1214
- * AA-family preset. Bare numbers and AAA-family presets pass through.
1321
+ * Matches the CSS color functions Glaze itself emits (`rgb()`, `hsl()`,
1322
+ * `okhsl()`, `oklch()`) plus their legacy alpha aliases (`rgba()`, `hsla()`).
1323
+ *
1324
+ * Only bare numeric components are supported. Named colors (`red`),
1325
+ * relative-color syntax (`from <color> ...`), and angle units other
1326
+ * than bare degrees (`deg` is the only suffix tolerated by `parseFloat`)
1327
+ * are out of scope.
1215
1328
  */
1216
- function resolveWcagTarget(value, isHighContrast, explicitHC) {
1217
- if (typeof value === "number") return resolveMinContrast(value);
1218
- if (isHighContrast && !explicitHC) {
1219
- const promoted = WCAG_HC_PROMOTION[value];
1220
- if (promoted !== void 0) return resolveMinContrast(promoted);
1221
- }
1222
- return resolveMinContrast(value);
1223
- }
1224
- function pickPair(p, isHighContrast) {
1225
- return Array.isArray(p) ? isHighContrast ? p[1] : p[0] : p;
1329
+ const COLOR_FN_RE = /^(rgba?|hsla?|okhsl|okhst|oklch)\(\s*([^)]*)\s*\)$/i;
1330
+ function parseNumberOrPercent(raw, percentScale) {
1331
+ if (raw.endsWith("%")) return parseFloat(raw) / 100 * percentScale;
1332
+ return parseFloat(raw);
1226
1333
  }
1227
1334
  /**
1228
- * Resolve a `ContrastSpec` (already selected from any outer HC pair) for a
1229
- * given mode into `{ metric, target }`. Handles the inner metric HC pair and
1230
- * preset resolution. `polarity` is passed through to the result for the APCA
1231
- * branch (it controls argument order in the solver); WCAG ignores it.
1335
+ * Split the body of a CSS color function into its components and detect
1336
+ * whether an alpha channel was present.
1232
1337
  *
1233
- * `outerExplicitHC` indicates whether the caller selected this `spec` from an
1234
- * explicit high-contrast entry of the outer `contrast` pair. Together with the
1235
- * inner metric pair, it decides whether the HC auto-enhancement fires:
1236
- * - APCA: +15 Lc "Enhanced Level" boost when neither level is explicit.
1237
- * - WCAG: AA → AAA / AA-large → AAA-large promotion (SC 1.4.3 → 1.4.6) when
1238
- * neither level is explicit. AAA-family presets and bare numbers are left
1239
- * unchanged (AAA is the top WCAG tier).
1240
- * Defaults to `false` (correct for direct callers, which pass a single
1241
- * selected spec rather than an outer pair).
1338
+ * Handles both modern slash syntax (`R G B / A` or `R, G, B / A`) and
1339
+ * legacy comma syntax (`R, G, B, A`). The alpha value itself is discarded
1340
+ * by the caller — standalone Glaze colors have no opacity field.
1242
1341
  */
1243
- function resolveContrastForMode(spec, isHighContrast, polarity, outerExplicitHC) {
1244
- if (typeof spec === "number" || typeof spec === "string") return {
1245
- metric: "wcag",
1246
- target: resolveWcagTarget(spec, isHighContrast, !!outerExplicitHC)
1342
+ function splitColorBody(body) {
1343
+ const slashIdx = body.indexOf("/");
1344
+ if (slashIdx !== -1) return {
1345
+ components: body.slice(0, slashIdx).trim().split(/[\s,]+/).filter(Boolean),
1346
+ hadAlpha: body.slice(slashIdx + 1).trim().length > 0
1247
1347
  };
1248
- if ("apca" in spec) {
1249
- const baseTarget = resolveApcaTarget(pickPair(spec.apca, isHighContrast));
1250
- const innerExplicitHC = Array.isArray(spec.apca);
1348
+ const components = body.split(/[\s,]+/).filter(Boolean);
1349
+ if (components.length === 4) {
1350
+ components.pop();
1251
1351
  return {
1252
- metric: "apca",
1253
- target: isHighContrast && !outerExplicitHC && !innerExplicitHC ? Math.min(baseTarget + APCA_HC_ENHANCEMENT, APCA_MAX_LC) : baseTarget,
1254
- polarity: polarity ?? "fg"
1352
+ components,
1353
+ hadAlpha: true
1255
1354
  };
1256
1355
  }
1257
- const innerExplicitHC = Array.isArray(spec.wcag);
1258
1356
  return {
1259
- metric: "wcag",
1260
- target: resolveWcagTarget(pickPair(spec.wcag, isHighContrast), isHighContrast, !!outerExplicitHC || innerExplicitHC)
1357
+ components,
1358
+ hadAlpha: false
1261
1359
  };
1262
1360
  }
1263
- const APCA_EXPONENTS = {
1264
- mainTRC: 2.4,
1265
- normBG: .56,
1266
- normTXT: .57,
1267
- revTXT: .62,
1268
- revBG: .65
1269
- };
1270
- const APCA_BLACK_THRESH = .022;
1271
- const APCA_BLACK_CLIP = 1.414;
1272
- const APCA_DELTA_Y_MIN = 5e-4;
1273
- const APCA_SCALE = 1.14;
1274
- const APCA_LO_OFFSET = .027;
1275
- function apcaSoftClamp(y) {
1276
- const yc = Math.max(0, y);
1277
- if (yc >= APCA_BLACK_THRESH) return yc;
1278
- return yc + Math.pow(APCA_BLACK_THRESH - yc, APCA_BLACK_CLIP);
1361
+ function warnDroppedAlpha(input) {
1362
+ console.warn(`glaze: alpha component dropped from "${input}" (standalone color has no opacity field).`);
1279
1363
  }
1280
- /**
1281
- * APCA lightness contrast (Lc), signed: positive for dark text on light bg,
1282
- * negative for light text on dark bg. Inputs are screen luminances (0–1).
1283
- */
1284
- function apcaContrast(yText, yBg) {
1285
- const txt = apcaSoftClamp(yText);
1286
- const bg = apcaSoftClamp(yBg);
1287
- if (Math.abs(bg - txt) < APCA_DELTA_Y_MIN) return 0;
1364
+ function parseColorString(input) {
1365
+ if (input.startsWith("#")) {
1366
+ const parsed = parseHexAlpha(input);
1367
+ if (!parsed) throw new Error(`glaze: invalid hex color "${input}".`);
1368
+ if (parsed.alpha !== void 0) warnDroppedAlpha(input);
1369
+ const [h, s, l] = srgbToOkhsl(parsed.rgb);
1370
+ return {
1371
+ h,
1372
+ s,
1373
+ l
1374
+ };
1375
+ }
1376
+ const m = input.match(COLOR_FN_RE);
1377
+ if (!m) throw new Error(`glaze: unsupported color string "${input}".`);
1378
+ const fn = m[1].toLowerCase();
1379
+ const { components, hadAlpha } = splitColorBody(m[2].trim());
1380
+ if (hadAlpha) warnDroppedAlpha(input);
1381
+ if (components.length !== 3) throw new Error(`glaze: expected 3 components in "${input}".`);
1382
+ switch (fn) {
1383
+ case "rgb":
1384
+ case "rgba": {
1385
+ const [h, s, l] = srgbToOkhsl([
1386
+ parseNumberOrPercent(components[0], 255) / 255,
1387
+ parseNumberOrPercent(components[1], 255) / 255,
1388
+ parseNumberOrPercent(components[2], 255) / 255
1389
+ ]);
1390
+ return {
1391
+ h,
1392
+ s,
1393
+ l
1394
+ };
1395
+ }
1396
+ case "hsl":
1397
+ case "hsla": {
1398
+ const [oh, os, ol] = srgbToOkhsl(hslToSrgb(parseFloat(components[0]), parseNumberOrPercent(components[1], 1), parseNumberOrPercent(components[2], 1)));
1399
+ return {
1400
+ h: oh,
1401
+ s: os,
1402
+ l: ol
1403
+ };
1404
+ }
1405
+ case "okhsl": return {
1406
+ h: parseFloat(components[0]),
1407
+ s: parseNumberOrPercent(components[1], 1),
1408
+ l: parseNumberOrPercent(components[2], 1)
1409
+ };
1410
+ case "okhst": return okhstToOkhsl({
1411
+ h: parseFloat(components[0]),
1412
+ s: parseNumberOrPercent(components[1], 1),
1413
+ t: parseNumberOrPercent(components[2], 1)
1414
+ });
1415
+ case "oklch": {
1416
+ const L = parseNumberOrPercent(components[0], 1);
1417
+ const C = parseNumberOrPercent(components[1], .4);
1418
+ const hRad = parseFloat(components[2]) * Math.PI / 180;
1419
+ const [h, s, l] = oklabToOkhsl([
1420
+ L,
1421
+ C * Math.cos(hRad),
1422
+ C * Math.sin(hRad)
1423
+ ]);
1424
+ return {
1425
+ h,
1426
+ s,
1427
+ l
1428
+ };
1429
+ }
1430
+ }
1431
+ throw new Error(`glaze: unsupported color function "${fn}".`);
1432
+ }
1433
+ /**
1434
+ * Validate a user-supplied `OkhslColor`. Catches the common 0-100 vs 0-1
1435
+ * confusion (the structured form uses 0-100, OKHSL objects use 0-1).
1436
+ */
1437
+ function validateOkhslColor(value) {
1438
+ const { h, s, l } = value;
1439
+ if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l)) throw new Error("glaze.color: OkhslColor h/s/l must be finite numbers.");
1440
+ if (s > 1.5 || l > 1.5) throw new Error("glaze.color: OkhslColor s/l must be in 0–1 range. Did you mean the structured form { hue, saturation, tone } (which uses 0–100)?");
1441
+ }
1442
+ /** Validate a user-supplied `{ r, g, b }` object in 0–255. */
1443
+ function validateRgbColor(value) {
1444
+ for (const key of [
1445
+ "r",
1446
+ "g",
1447
+ "b"
1448
+ ]) {
1449
+ const n = value[key];
1450
+ if (!Number.isFinite(n) || n < 0 || n > 255) throw new Error(`glaze.color: RgbColor ${key} must be a finite number in 0–255 (got ${n}).`);
1451
+ }
1452
+ }
1453
+ /** Validate a user-supplied `{ l, c, h }` OKLCh object. */
1454
+ function validateOklchColor(value) {
1455
+ const { l, c, h } = value;
1456
+ if (!Number.isFinite(l) || !Number.isFinite(c) || !Number.isFinite(h)) throw new Error("glaze.color: OklchColor l/c/h must be finite numbers.");
1457
+ if (l > 1.5 || c > 1.5) throw new Error("glaze.color: OklchColor l/c must be in 0–1 range (matching oklch() strings).");
1458
+ }
1459
+ function oklchComponentsToOkhsl(l, c, hDeg) {
1460
+ const hRad = hDeg * Math.PI / 180;
1461
+ const [h, s, outL] = oklabToOkhsl([
1462
+ l,
1463
+ c * Math.cos(hRad),
1464
+ c * Math.sin(hRad)
1465
+ ]);
1466
+ return {
1467
+ h,
1468
+ s,
1469
+ l: outL
1470
+ };
1471
+ }
1472
+ function isRgbColorObject(value) {
1473
+ return "r" in value && "g" in value && "b" in value;
1474
+ }
1475
+ function isOklchColorObject(value) {
1476
+ return "c" in value && "l" in value && "h" in value;
1477
+ }
1478
+ function isOkhstColorObject(value) {
1479
+ return "t" in value && "h" in value && "s" in value;
1480
+ }
1481
+ /** Validate a user-supplied `{ h, s, t }` OKHST object (s/t in 0–1). */
1482
+ function validateOkhstColor(value) {
1483
+ const { h, s, t } = value;
1484
+ if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(t)) throw new Error("glaze.color: OkhstColor h/s/t must be finite numbers.");
1485
+ if (s > 1.5 || t > 1.5) throw new Error("glaze.color: OkhstColor s/t must be in 0–1 range. Did you mean the structured form { hue, saturation, tone } (which uses 0–100)?");
1486
+ }
1487
+ /**
1488
+ * Extract an OKHSL color from any `GlazeColorValue` form. Also used by
1489
+ * `glaze.shadow()` / `glaze.glow()` so all their inputs (hex, color
1490
+ * functions, OKHSL, literal objects) go through one parser.
1491
+ */
1492
+ function extractOkhslFromValue(value) {
1493
+ if (typeof value === "string") return parseColorString(value);
1494
+ if (Array.isArray(value)) throw new Error("glaze.color: RGB tuple [r, g, b] is no longer supported — use { r, g, b } instead.");
1495
+ if (isRgbColorObject(value)) {
1496
+ validateRgbColor(value);
1497
+ const [h, s, l] = srgbToOkhsl([
1498
+ value.r / 255,
1499
+ value.g / 255,
1500
+ value.b / 255
1501
+ ]);
1502
+ return {
1503
+ h,
1504
+ s,
1505
+ l
1506
+ };
1507
+ }
1508
+ if (isOklchColorObject(value)) {
1509
+ validateOklchColor(value);
1510
+ return oklchComponentsToOkhsl(value.l, value.c, value.h);
1511
+ }
1512
+ if (isOkhstColorObject(value)) {
1513
+ validateOkhstColor(value);
1514
+ return okhstToOkhsl(value);
1515
+ }
1516
+ validateOkhslColor(value);
1517
+ return value;
1518
+ }
1519
+
1520
+ //#endregion
1521
+ //#region src/format-guard.ts
1522
+ const NON_NATIVE_FORMATS = new Set(["okhsl", "okhst"]);
1523
+ /**
1524
+ * Throw when a non-native Glaze color space is requested for an export that
1525
+ * emits raw CSS or non-Tasty token maps.
1526
+ */
1527
+ function assertNativeFormat(format, method) {
1528
+ if (format !== void 0 && NON_NATIVE_FORMATS.has(format)) throw new Error(`glaze: ${format} output is only supported by tasty() (not a native CSS color space). Use tasty({ format: '${format}' }) or pick a native format (oklch|hsl|rgb) for ${method}().`);
1529
+ }
1530
+ const SCHEME_FIELDS = [
1531
+ {
1532
+ field: "light",
1533
+ modes: () => true
1534
+ },
1535
+ {
1536
+ field: "dark",
1537
+ modes: (m) => m.dark
1538
+ },
1539
+ {
1540
+ field: "lightContrast",
1541
+ modes: (m) => m.highContrast
1542
+ },
1543
+ {
1544
+ field: "darkContrast",
1545
+ modes: (m) => m.dark && m.highContrast
1546
+ }
1547
+ ];
1548
+ /**
1549
+ * Throw when `splitHue` is enabled but any exported color is not pastel.
1550
+ * Hue rotation is only clip-free when chroma is bounded by the hue-independent
1551
+ * safe chroma (`computeSafeChromaOKLCH`).
1552
+ */
1553
+ function assertAllPastel(resolved, modes) {
1554
+ const nonPastel = [];
1555
+ for (const [name, color] of resolved) for (const { field, modes: active } of SCHEME_FIELDS) {
1556
+ if (!active(modes)) continue;
1557
+ if (color[field].pastel !== true) {
1558
+ if (!nonPastel.includes(name)) nonPastel.push(name);
1559
+ break;
1560
+ }
1561
+ }
1562
+ if (nonPastel.length === 0) return;
1563
+ throw new Error(`glaze: splitHue requires every color to be pastel (hue rotation is only clip-free when chroma is bounded by the hue-independent safe chroma). Non-pastel: ${nonPastel.join(", ")}. Set pastel: true (per-theme, per-token, or per-color) or drop splitHue.`);
1564
+ }
1565
+
1566
+ //#endregion
1567
+ //#region src/contrast-solver.ts
1568
+ /**
1569
+ * Contrast solver — operates in OKHST tone.
1570
+ *
1571
+ * Finds the tone closest to a preferred tone that satisfies a contrast
1572
+ * floor (WCAG 2 ratio or APCA Lc) against a base color. Because tone is
1573
+ * contrast-uniform, the WCAG branch gets a closed-form seed and the search
1574
+ * converges quickly.
1575
+ *
1576
+ * Public API: `findToneForContrast`, `findValueForMixContrast`,
1577
+ * `resolveMinContrast`, `resolveContrastForMode`, `resolveContrastForLevel`,
1578
+ * `apcaContrast`.
1579
+ */
1580
+ /**
1581
+ * Luminance of a linear-sRGB color in the basis the metric expects: WCAG
1582
+ * relative luminance for `wcag`, APCA screen luminance (`Ys`) for `apca`.
1583
+ */
1584
+ function metricLuminance(metric, linearRgb) {
1585
+ return metric === "apca" ? apcaLuminanceFromLinearRgb(linearRgb) : gamutClampedLuminance(linearRgb);
1586
+ }
1587
+ const APCA_PRESETS = {
1588
+ preferred: 90,
1589
+ body: 75,
1590
+ content: 60,
1591
+ large: 45,
1592
+ "non-text": 30,
1593
+ min: 15
1594
+ };
1595
+ /**
1596
+ * APCA-W3 "Enhanced Level" delta added to a bare APCA target in high-contrast
1597
+ * mode when no explicit HC value is provided (analogous to WCAG AAA over AA).
1598
+ * Only applied when neither the outer `contrast` pair nor the inner `apca`
1599
+ * pair carries an explicit HC entry.
1600
+ */
1601
+ const APCA_HC_ENHANCEMENT = 15;
1602
+ /** Upper bound for an APCA Lc target after HC enhancement. */
1603
+ const APCA_MAX_LC = 106;
1604
+ /**
1605
+ * Resolve an APCA target — a raw Lc number (kept as-is) or an `ApcaPreset`
1606
+ * keyword mapped to its Lc value. The magnitude is forced non-negative.
1607
+ */
1608
+ function resolveApcaTarget(value) {
1609
+ if (typeof value === "number") return Math.abs(value);
1610
+ return APCA_PRESETS[value];
1611
+ }
1612
+ const CONTRAST_PRESETS = {
1613
+ AA: 4.5,
1614
+ AAA: 7,
1615
+ "AA-large": 3,
1616
+ "AAA-large": 4.5
1617
+ };
1618
+ /**
1619
+ * WCAG high-contrast auto-promotion (analog of APCA's Enhanced Level). A bare
1620
+ * AA / AA-large preset is promoted to its spec-defined "Enhanced" successor
1621
+ * (SC 1.4.3 → SC 1.4.6) in high-contrast mode. AAA / AAA-large are already
1622
+ * the top WCAG tier and are left unchanged. Bare numeric targets have no
1623
+ * defined successor tier and are also left unchanged. An explicit HC value
1624
+ * (outer or inner pair) always overrides.
1625
+ */
1626
+ const WCAG_HC_PROMOTION = {
1627
+ AA: "AAA",
1628
+ "AA-large": "AAA-large"
1629
+ };
1630
+ function resolveMinContrast(value) {
1631
+ if (typeof value === "number") return Math.max(1, value);
1632
+ return CONTRAST_PRESETS[value];
1633
+ }
1634
+ /**
1635
+ * Resolve a WCAG target (number or preset) for a mode, applying the
1636
+ * high-contrast auto-promotion when `explicitHC` is false and the value is an
1637
+ * AA-family preset. Bare numbers and AAA-family presets pass through.
1638
+ */
1639
+ function resolveWcagTarget(value, isHighContrast, explicitHC) {
1640
+ if (typeof value === "number") return resolveMinContrast(value);
1641
+ if (isHighContrast && !explicitHC) {
1642
+ const promoted = WCAG_HC_PROMOTION[value];
1643
+ if (promoted !== void 0) return resolveMinContrast(promoted);
1644
+ }
1645
+ return resolveMinContrast(value);
1646
+ }
1647
+ function pickPair(p, isHighContrast) {
1648
+ return Array.isArray(p) ? isHighContrast ? p[1] : p[0] : p;
1649
+ }
1650
+ /**
1651
+ * The metric a single `ContrastSpec` measures in. Bare numbers and WCAG
1652
+ * presets are `'wcag'`; only an `{ apca }` object is `'apca'`.
1653
+ */
1654
+ function contrastMetricOf(spec) {
1655
+ return typeof spec === "object" && "apca" in spec ? "apca" : "wcag";
1656
+ }
1657
+ /**
1658
+ * Resolve a `ContrastSpec` (already selected from any outer HC pair) for a
1659
+ * given mode into `{ metric, target }`. Handles the inner metric HC pair and
1660
+ * preset resolution. `polarity` is passed through to the result for the APCA
1661
+ * branch (it controls argument order in the solver); WCAG ignores it.
1662
+ *
1663
+ * `outerExplicitHC` indicates whether the caller selected this `spec` from an
1664
+ * explicit high-contrast entry of the outer `contrast` pair. Together with the
1665
+ * inner metric pair, it decides whether the HC auto-enhancement fires:
1666
+ * - APCA: +15 Lc "Enhanced Level" boost when neither level is explicit.
1667
+ * - WCAG: AA → AAA / AA-large → AAA-large promotion (SC 1.4.3 → 1.4.6) when
1668
+ * neither level is explicit. AAA-family presets and bare numbers are left
1669
+ * unchanged (AAA is the top WCAG tier).
1670
+ * Defaults to `false` (correct for direct callers, which pass a single
1671
+ * selected spec rather than an outer pair).
1672
+ */
1673
+ function resolveContrastForMode(spec, isHighContrast, polarity, outerExplicitHC) {
1674
+ if (typeof spec === "number" || typeof spec === "string") return {
1675
+ metric: "wcag",
1676
+ target: resolveWcagTarget(spec, isHighContrast, !!outerExplicitHC)
1677
+ };
1678
+ if ("apca" in spec) {
1679
+ const baseTarget = resolveApcaTarget(pickPair(spec.apca, isHighContrast));
1680
+ const innerExplicitHC = Array.isArray(spec.apca);
1681
+ return {
1682
+ metric: "apca",
1683
+ target: isHighContrast && !outerExplicitHC && !innerExplicitHC ? Math.min(baseTarget + APCA_HC_ENHANCEMENT, APCA_MAX_LC) : baseTarget,
1684
+ polarity: polarity ?? "fg"
1685
+ };
1686
+ }
1687
+ const innerExplicitHC = Array.isArray(spec.wcag);
1688
+ return {
1689
+ metric: "wcag",
1690
+ target: resolveWcagTarget(pickPair(spec.wcag, isHighContrast), isHighContrast, !!outerExplicitHC || innerExplicitHC)
1691
+ };
1692
+ }
1693
+ /**
1694
+ * Resolve a `contrast` spec — including its outer `[normal, highContrast]`
1695
+ * pair — at a manual contrast `level` (0–100), by resolving both ends and
1696
+ * interpolating the numeric target.
1697
+ *
1698
+ * Level 0 / 100 delegate verbatim to {@link resolveContrastForMode}, so the
1699
+ * endpoints are bit-identical to classic normal / high-contrast resolution.
1700
+ * Resolving each end fully first also means every rule that governs the
1701
+ * escalation still applies at both ends for free: preset mapping, the
1702
+ * `APCA_MAX_LC` clamp, and the explicit-HC suppression that cancels the
1703
+ * `AA → AAA` promotion and the `+15 Lc` enhancement.
1704
+ *
1705
+ * Throws when the two ends measure in different metrics — a WCAG ratio and an
1706
+ * APCA Lc live on different scales, so there is no target between them. Such a
1707
+ * pair is rejected at authoring time by `validateColorDefs`; this is the guard
1708
+ * for direct callers.
1709
+ */
1710
+ function resolveContrastForLevel(spec, level, polarity) {
1711
+ const outerExplicitHC = Array.isArray(spec);
1712
+ const f = levelFraction(level);
1713
+ const normal = resolveContrastForMode(pairNormal(spec), false, polarity, outerExplicitHC);
1714
+ if (f <= 0) return normal;
1715
+ const hc = resolveContrastForMode(pairHC(spec), true, polarity, outerExplicitHC);
1716
+ if (f >= 1) return hc;
1717
+ if (normal.metric !== hc.metric) throw new Error(`glaze: a "contrast" pair cannot switch metric between its normal (${normal.metric}) and high-contrast (${hc.metric}) entry — the two targets are on different scales. Use one metric for both entries.`);
1718
+ return {
1719
+ ...normal,
1720
+ target: lerp(normal.target, hc.target, f)
1721
+ };
1722
+ }
1723
+ const APCA_EXPONENTS = {
1724
+ mainTRC: 2.4,
1725
+ normBG: .56,
1726
+ normTXT: .57,
1727
+ revTXT: .62,
1728
+ revBG: .65
1729
+ };
1730
+ const APCA_BLACK_THRESH = .022;
1731
+ const APCA_BLACK_CLIP = 1.414;
1732
+ const APCA_DELTA_Y_MIN = 5e-4;
1733
+ const APCA_SCALE = 1.14;
1734
+ const APCA_LO_OFFSET = .027;
1735
+ function apcaSoftClamp(y) {
1736
+ const yc = Math.max(0, y);
1737
+ if (yc >= APCA_BLACK_THRESH) return yc;
1738
+ return yc + Math.pow(APCA_BLACK_THRESH - yc, APCA_BLACK_CLIP);
1739
+ }
1740
+ /**
1741
+ * APCA lightness contrast (Lc), signed: positive for dark text on light bg,
1742
+ * negative for light text on dark bg. Inputs are screen luminances (0–1).
1743
+ */
1744
+ function apcaContrast(yText, yBg) {
1745
+ const txt = apcaSoftClamp(yText);
1746
+ const bg = apcaSoftClamp(yBg);
1747
+ if (Math.abs(bg - txt) < APCA_DELTA_Y_MIN) return 0;
1288
1748
  let sapc;
1289
1749
  if (bg > txt) {
1290
1750
  sapc = (Math.pow(bg, APCA_EXPONENTS.normBG) - Math.pow(txt, APCA_EXPONENTS.normTXT)) * APCA_SCALE;
@@ -1400,7 +1860,7 @@ function wcagToneSeed(yBase, target, darker) {
1400
1860
  return Math.max(0, Math.min(1, toneFromY(yClamped, REF_EPS) / 100));
1401
1861
  }
1402
1862
  function solveNearestContrast(opts) {
1403
- const { lum, yBase, metric, target, searchTarget, lo, hi, searchAnchor, distanceAnchor, epsilon, maxIterations, flip, initialIsLower, polarity } = opts;
1863
+ const { lum, yBase, metric, target, searchTarget, lo, hi, searchAnchor, distanceAnchor, epsilon, maxIterations, flip, preferInitial, initialIsLower, polarity } = opts;
1404
1864
  const runBranch = (lower) => lower ? searchBranch(lum, lo, searchAnchor, yBase, metric, searchTarget, epsilon, maxIterations, searchAnchor, polarity) : searchBranch(lum, searchAnchor, hi, yBase, metric, searchTarget, epsilon, maxIterations, searchAnchor, polarity);
1405
1865
  const initialResult = runBranch(initialIsLower);
1406
1866
  initialResult.met = initialResult.contrast >= target;
@@ -1411,14 +1871,20 @@ function solveNearestContrast(opts) {
1411
1871
  if (flip) {
1412
1872
  const oppositeResult = (initialIsLower ? distanceAnchor < hi : distanceAnchor > lo) ? runBranch(!initialIsLower) : null;
1413
1873
  if (oppositeResult) oppositeResult.met = oppositeResult.contrast >= target;
1414
- if (initialResult.met && oppositeResult?.met) return Math.abs(initialResult.pos - distanceAnchor) <= Math.abs(oppositeResult.pos - distanceAnchor) ? {
1415
- ...initialResult,
1416
- lower: initialIsLower
1417
- } : {
1418
- ...oppositeResult,
1419
- lower: !initialIsLower,
1420
- flipped: true
1421
- };
1874
+ if (initialResult.met && oppositeResult?.met) {
1875
+ if (preferInitial) return {
1876
+ ...initialResult,
1877
+ lower: initialIsLower
1878
+ };
1879
+ return Math.abs(initialResult.pos - distanceAnchor) <= Math.abs(oppositeResult.pos - distanceAnchor) ? {
1880
+ ...initialResult,
1881
+ lower: initialIsLower
1882
+ } : {
1883
+ ...oppositeResult,
1884
+ lower: !initialIsLower,
1885
+ flipped: true
1886
+ };
1887
+ }
1422
1888
  if (initialResult.met) return {
1423
1889
  ...initialResult,
1424
1890
  lower: initialIsLower
@@ -1481,6 +1947,7 @@ function findToneForContrast(options) {
1481
1947
  epsilon,
1482
1948
  maxIterations,
1483
1949
  flip: options.flip ?? false,
1950
+ preferInitial: options.preferInitial ?? false,
1484
1951
  initialIsLower: initialIsDarker,
1485
1952
  polarity
1486
1953
  });
@@ -1531,6 +1998,7 @@ function findValueForMixContrast(options) {
1531
1998
  epsilon,
1532
1999
  maxIterations,
1533
2000
  flip: options.flip ?? false,
2001
+ preferInitial: false,
1534
2002
  initialIsLower,
1535
2003
  polarity
1536
2004
  });
@@ -1651,36 +2119,46 @@ function oppositeRole(role) {
1651
2119
  }
1652
2120
 
1653
2121
  //#endregion
1654
- //#region src/shadow.ts
2122
+ //#region src/lighting.ts
1655
2123
  /**
1656
- * Shadow color computation.
2124
+ * Shadow and glow color computation.
1657
2125
  *
1658
- * Owns the shadow / mix def predicates, default tuning constants, the
1659
- * tuning merge, and the actual `computeShadow` math (hue blend,
1660
- * saturation cap, lightness clamp, alpha curve). The resolver consumes
1661
- * this module per scheme variant.
2126
+ * Owns the shadow / glow / mix def predicates, the default lighting tuning
2127
+ * and its merge, and the exact lighting solver (`computeLighting`). Both
2128
+ * types emit a translucent pigment over a known surface (`bg`) whose opacity
2129
+ * is solved so the composite lands an exact tone step away from it: darker
2130
+ * for `shadow`, lighter for `glow`, in every scheme. Compositing is modeled
2131
+ * the way browsers paint it — `source-over` on gamma-encoded sRGB — and the
2132
+ * step is measured in the WCAG-shaped tone of the composite's luminance, so
2133
+ * it holds on chromatic surfaces too. An optional object (`fg`) scales the
2134
+ * step the way bounce light does. The resolver consumes this module per
2135
+ * scheme variant; `glaze.shadow()` / `glaze.glow()` call it directly.
1662
2136
  */
1663
2137
  function isShadowDef(def) {
1664
2138
  return def.type === "shadow";
1665
2139
  }
2140
+ function isGlowDef(def) {
2141
+ return def.type === "glow";
2142
+ }
2143
+ /** A `shadow` or `glow` def — the translucent overlay types. */
2144
+ function isLightingDef(def) {
2145
+ return isShadowDef(def) || isGlowDef(def);
2146
+ }
1666
2147
  function isMixDef(def) {
1667
2148
  return def.type === "mix";
1668
2149
  }
1669
- const DEFAULT_SHADOW_TUNING = {
1670
- saturationFactor: .18,
1671
- maxSaturation: .25,
1672
- lightnessFactor: .25,
1673
- lightnessBounds: [.05, .2],
1674
- minGapTarget: .05,
1675
- alphaMax: 1,
1676
- bgHueBlend: .2
2150
+ const DEFAULT_LIGHTING_TUNING = {
2151
+ objectInfluence: .5,
2152
+ tint: 0,
2153
+ reach: 1,
2154
+ hueBleed: 0
1677
2155
  };
1678
- function resolveShadowTuning(perColor, globalTuning) {
2156
+ /** Defaults ← global (`shadowTuning` / `glowTuning`) ← per-color, field by field. */
2157
+ function resolveLightingTuning(perColor, globalTuning) {
1679
2158
  return {
1680
- ...DEFAULT_SHADOW_TUNING,
2159
+ ...DEFAULT_LIGHTING_TUNING,
1681
2160
  ...globalTuning,
1682
- ...perColor,
1683
- lightnessBounds: perColor?.lightnessBounds ?? globalTuning?.lightnessBounds ?? DEFAULT_SHADOW_TUNING.lightnessBounds
2161
+ ...perColor
1684
2162
  };
1685
2163
  }
1686
2164
  function circularLerp(a, b, t) {
@@ -1689,75 +2167,197 @@ function circularLerp(a, b, t) {
1689
2167
  else if (diff < -180) diff += 360;
1690
2168
  return ((a + diff * t) % 360 + 360) % 360;
1691
2169
  }
2170
+ const SAT_EPSILON = 1e-6;
2171
+ const BISECT_ITERATIONS = 40;
2172
+ const GOLDEN = (Math.sqrt(5) - 1) / 2;
2173
+ /**
2174
+ * Object factor `k = max(0, 1 + β · d · (t_bg − t_fg) / 100)`, with `d = +1`
2175
+ * for a shadow and `−1` for a glow. Calibrated so an object at the surface's
2176
+ * own tone — or no object at all — gives exactly the authored step: a darker
2177
+ * object deepens its shadow, a lighter one strengthens its glow.
2178
+ */
2179
+ function objectFactor(kind, bgTone, fgTone, objectInfluence) {
2180
+ if (fgTone === void 0) return 1;
2181
+ const d = kind === "shadow" ? 1 : -1;
2182
+ return Math.max(0, 1 + objectInfluence * d * (bgTone - fgTone) / 100);
2183
+ }
1692
2184
  /**
1693
- * Compute the canonical max-contrast reference t value for normalization.
1694
- * Uses bg.l=1, fg.l=0, intensity=100 — the theoretical maximum.
1695
- * This is a fixed constant per tuning configuration, ensuring uniform
1696
- * scaling across all bg/fg pairs at low intensities.
1697
- */
1698
- function computeRefT(tuning) {
1699
- const EPSILON = 1e-6;
1700
- let lShRef = clamp(tuning.lightnessFactor, tuning.lightnessBounds[0], tuning.lightnessBounds[1]);
1701
- lShRef = Math.max(Math.min(lShRef, 1 - tuning.minGapTarget), 0);
1702
- return 1 / Math.max(1 - lShRef, EPSILON);
1703
- }
1704
- function computeShadow(bg, fg, intensity, tuning) {
1705
- const EPSILON = 1e-6;
1706
- const clampedIntensity = clamp(intensity, 0, 100);
1707
- const contrastWeight = fg ? Math.abs(bg.l - fg.l) : 1;
1708
- const deltaL = clampedIntensity / 100 * contrastWeight;
1709
- const h = fg ? circularLerp(fg.h, bg.h, tuning.bgHueBlend) : bg.h;
1710
- const s = fg ? Math.min(fg.s * tuning.saturationFactor, tuning.maxSaturation) : 0;
1711
- let lSh = clamp(bg.l * tuning.lightnessFactor, tuning.lightnessBounds[0], tuning.lightnessBounds[1]);
1712
- lSh = Math.max(Math.min(lSh, bg.l - tuning.minGapTarget), 0);
1713
- const t = deltaL / Math.max(bg.l - lSh, EPSILON);
1714
- const tRef = computeRefT(tuning);
1715
- const norm = Math.tanh(tRef / tuning.alphaMax);
1716
- const alpha = Math.min(tuning.alphaMax * Math.tanh(t / tuning.alphaMax) / norm, tuning.alphaMax);
2185
+ * The pigment: pure black (shadow) / pure white (glow) by default. `reach`
2186
+ * below 1 parks it part of the way from the surface's tone to that extreme so
2187
+ * a `tint` — saturation in the surface's hue, optionally pulled toward the
2188
+ * object's hue by `hueBleed` — can show.
2189
+ */
2190
+ function pigmentFor(kind, bg, fg, bgTone, tuning) {
2191
+ const reach = clamp(tuning.reach, 0, 1);
2192
+ const tone = kind === "shadow" ? bgTone * (1 - reach) : bgTone + (100 - bgTone) * reach;
2193
+ const bleed = clamp(tuning.hueBleed, 0, 1);
1717
2194
  return {
1718
- h,
1719
- s,
1720
- l: lSh,
1721
- alpha
2195
+ h: fg !== void 0 && fg.s > SAT_EPSILON && bleed > 0 ? circularLerp(bg.h, fg.h, bleed) : bg.h,
2196
+ s: clamp(tuning.tint, 0, 1),
2197
+ l: clamp(fromTone(tone), 0, 1)
2198
+ };
2199
+ }
2200
+ /**
2201
+ * Solve the pigment opacity that moves `bg` exactly `intensity × k` tones
2202
+ * darker (shadow) or lighter (glow) once the browser composites it.
2203
+ *
2204
+ * The composite's luminance is convex in alpha (each gamma channel moves
2205
+ * linearly and the sRGB decode is convex), so the "has reached the step"
2206
+ * predicate is monotone whenever full opacity reaches it and a bisection
2207
+ * lands it exactly. When it doesn't, the step is out of reach — a glow on
2208
+ * white, a deep shadow on near-black — and the result pins to the pigment's
2209
+ * strongest composite, reporting what it reached in `reached`.
2210
+ */
2211
+ function computeLighting(kind, bg, fg, intensity, tuning, pastel) {
2212
+ const bgTone = toTone(bg.l);
2213
+ const k = objectFactor(kind, bgTone, fg === void 0 ? void 0 : toTone(fg.l), tuning.objectInfluence);
2214
+ const step = clamp(intensity, 0, 100) * k;
2215
+ const pigment = pigmentFor(kind, bg, fg, bgTone, tuning);
2216
+ const bgGamma = toDisplayGamma(okhslToLinearSrgb(bg.h, bg.s, bg.l, bg.pastel ?? pastel));
2217
+ const pigmentGamma = toDisplayGamma(okhslToLinearSrgb(pigment.h, pigment.s, pigment.l, pastel));
2218
+ const toneAt = (alpha) => toneFromY(relativeLuminanceFromLinearRgb(compositeOverGamma(bgGamma, pigmentGamma, alpha)));
2219
+ const surfaceTone = toneAt(0);
2220
+ const d = kind === "shadow" ? 1 : -1;
2221
+ const gain = (alpha) => d * (surfaceTone - toneAt(alpha));
2222
+ if (step <= 0) return {
2223
+ ...pigment,
2224
+ alpha: 0,
2225
+ step,
2226
+ reached: 0
2227
+ };
2228
+ let hi = 1;
2229
+ if (gain(1) < step) {
2230
+ hi = kind === "shadow" ? strongestShadowAlpha(gain) : 1;
2231
+ const reached = gain(hi);
2232
+ if (reached < step) return reached > 0 ? {
2233
+ ...pigment,
2234
+ alpha: hi,
2235
+ step,
2236
+ reached
2237
+ } : {
2238
+ ...pigment,
2239
+ alpha: 0,
2240
+ step,
2241
+ reached: 0
2242
+ };
2243
+ }
2244
+ let lo = 0;
2245
+ for (let i = 0; i < BISECT_ITERATIONS; i++) {
2246
+ const mid = (lo + hi) / 2;
2247
+ if (gain(mid) < step) lo = mid;
2248
+ else hi = mid;
2249
+ }
2250
+ return {
2251
+ ...pigment,
2252
+ alpha: hi,
2253
+ step,
2254
+ reached: gain(hi)
1722
2255
  };
1723
2256
  }
2257
+ /**
2258
+ * Opacity of a shadow pigment's darkest composite. Full opacity for pure
2259
+ * black; a tinted pigment whose channels pull in different directions can
2260
+ * bottom out earlier, so a golden-section search over the unimodal gain finds
2261
+ * it and the better of that and full opacity wins. (A glow needs no search:
2262
+ * convex luminance peaks at an endpoint, and full opacity is the one that
2263
+ * lightens.)
2264
+ */
2265
+ function strongestShadowAlpha(gain) {
2266
+ let a = 0;
2267
+ let b = 1;
2268
+ for (let i = 0; i < BISECT_ITERATIONS; i++) {
2269
+ const c = b - GOLDEN * (b - a);
2270
+ const e = a + GOLDEN * (b - a);
2271
+ if (gain(c) < gain(e)) a = c;
2272
+ else b = e;
2273
+ }
2274
+ const peak = (a + b) / 2;
2275
+ return gain(peak) > gain(1) ? peak : 1;
2276
+ }
1724
2277
 
1725
2278
  //#endregion
1726
2279
  //#region src/validation.ts
1727
2280
  /**
1728
2281
  * Color graph validation and topological sort.
1729
2282
  *
1730
- * `validateColorDefs` rejects bad references (missing / shadow-referencing /
1731
- * base/contrast/tone mismatches) and detects cycles before the
1732
- * resolver runs. `topoSort` orders defs so each color is processed after
2283
+ * `validateColorDefs` rejects bad references (missing / shadow- or
2284
+ * glow-referencing / base/contrast/tone mismatches) and detects cycles before
2285
+ * the resolver runs. `topoSort` orders defs so each color is processed after
1733
2286
  * its base / bg / fg / target dependencies.
1734
2287
  */
2288
+ /**
2289
+ * Does this color sit at an absolute tone — either authored, or carried by a
2290
+ * `from` value? That is the test for "root" (placed on its own) as opposed to
2291
+ * "dependent" (placed relative to a base), and it is what lets a bare
2292
+ * `{ from: '#2F5BFF' }` stand as a complete color definition.
2293
+ */
2294
+ function hasAbsoluteTone(def) {
2295
+ if (def.tone === void 0) return def.from !== void 0;
2296
+ return isAbsoluteTone(def.tone);
2297
+ }
2298
+ /**
2299
+ * Reject a `contrast` pair whose two entries measure in different metrics.
2300
+ *
2301
+ * A WCAG ratio and an APCA Lc are different scales, so `[4.5, { apca: 75 }]`
2302
+ * asks one color to be judged two incompatible ways. There is no target between
2303
+ * them for a manual `contrastLevel` to resolve, and even in `'auto'` mode the
2304
+ * two variants become incomparable. Pick one metric and pair its values
2305
+ * instead: `{ wcag: [4.5, 7] }` or `{ apca: [60, 90] }`.
2306
+ */
2307
+ function assertConsistentContrastMetric(name, contrast) {
2308
+ if (contrast === void 0 || !Array.isArray(contrast)) return;
2309
+ const normal = contrastMetricOf(pairNormal(contrast));
2310
+ const hc = contrastMetricOf(pairHC(contrast));
2311
+ if (normal === hc) return;
2312
+ throw new Error(`glaze: color "${name}" has a "contrast" pair that switches metric (${normal} → ${hc}). A WCAG ratio and an APCA Lc are different scales; use one metric for both entries, e.g. { ${normal}: [normal, highContrast] }.`);
2313
+ }
2314
+ /**
2315
+ * `'shadow'` / `'glow'` when `ref` names a local translucent overlay — which
2316
+ * nothing may build on — else `undefined`.
2317
+ */
2318
+ function overlayKindOf(defs, ref) {
2319
+ const def = Object.hasOwn(defs, ref) ? defs[ref] : void 0;
2320
+ return def !== void 0 && isLightingDef(def) ? def.type : void 0;
2321
+ }
1735
2322
  function validateColorDefs(defs, externalBases) {
1736
2323
  const localNames = new Set(Object.keys(defs));
1737
2324
  const allNames = new Set([...localNames, ...externalBases ? externalBases.keys() : []]);
1738
2325
  for (const [name, def] of Object.entries(defs)) {
1739
- if (isShadowDef(def)) {
1740
- if (!allNames.has(def.bg)) throw new Error(`glaze: shadow "${name}" references non-existent bg "${def.bg}".`);
1741
- if (localNames.has(def.bg) && isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
1742
- if (def.fg !== void 0) {
1743
- if (!allNames.has(def.fg)) throw new Error(`glaze: shadow "${name}" references non-existent fg "${def.fg}".`);
1744
- if (localNames.has(def.fg) && isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
2326
+ if (isLightingDef(def)) {
2327
+ const kind = def.type;
2328
+ for (const field of ["bg", "fg"]) {
2329
+ const ref = def[field];
2330
+ if (ref === void 0) continue;
2331
+ if (!allNames.has(ref)) throw new Error(`glaze: ${kind} "${name}" references non-existent ${field} "${ref}".`);
2332
+ const refKind = overlayKindOf(defs, ref);
2333
+ if (refKind !== void 0) throw new Error(`glaze: ${kind} "${name}" ${field} "${ref}" references a ${refKind} color.`);
1745
2334
  }
1746
2335
  continue;
1747
2336
  }
1748
2337
  if (isMixDef(def)) {
1749
2338
  if (!allNames.has(def.base)) throw new Error(`glaze: mix "${name}" references non-existent base "${def.base}".`);
1750
2339
  if (!allNames.has(def.target)) throw new Error(`glaze: mix "${name}" references non-existent target "${def.target}".`);
1751
- if (localNames.has(def.base) && isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
1752
- if (localNames.has(def.target) && isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
2340
+ for (const field of ["base", "target"]) {
2341
+ const ref = def[field];
2342
+ const refKind = overlayKindOf(defs, ref);
2343
+ if (refKind !== void 0) throw new Error(`glaze: mix "${name}" ${field} "${ref}" references a ${refKind} color.`);
2344
+ }
2345
+ assertConsistentContrastMetric(name, def.contrast);
1753
2346
  continue;
1754
2347
  }
1755
2348
  const regDef = def;
2349
+ assertConsistentContrastMetric(name, regDef.contrast);
2350
+ if (regDef.from !== void 0) try {
2351
+ extractOkhslFromValue(regDef.from);
2352
+ } catch (error) {
2353
+ throw new Error(`glaze: color "${name}" has an invalid "from" value. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2354
+ }
1756
2355
  if (regDef.contrast !== void 0 && !regDef.base) throw new Error(`glaze: color "${name}" has "contrast" without "base".`);
1757
2356
  if (regDef.tone !== void 0 && !isAbsoluteTone(regDef.tone) && !regDef.base) throw new Error(`glaze: color "${name}" has relative "tone" without "base".`);
1758
2357
  if (regDef.base && !allNames.has(regDef.base)) throw new Error(`glaze: color "${name}" references non-existent base "${regDef.base}".`);
1759
- if (regDef.base && localNames.has(regDef.base) && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
1760
- if (!isAbsoluteTone(regDef.tone) && regDef.base === void 0) throw new Error(`glaze: color "${name}" must have either absolute "tone" (root) or "base" (dependent).`);
2358
+ const baseKind = regDef.base && overlayKindOf(defs, regDef.base);
2359
+ if (baseKind) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a ${baseKind} color.`);
2360
+ if (!hasAbsoluteTone(regDef) && regDef.base === void 0) throw new Error(`glaze: color "${name}" must have either absolute "tone" (root), "from" (a literal color), or "base" (dependent).`);
1761
2361
  if (regDef.contrast !== void 0 && regDef.opacity !== void 0) console.warn(`glaze: color "${name}" has both "contrast" and "opacity". Opacity makes perceived tone unpredictable.`);
1762
2362
  }
1763
2363
  const visited = /* @__PURE__ */ new Set();
@@ -1768,7 +2368,7 @@ function validateColorDefs(defs, externalBases) {
1768
2368
  if (visited.has(name)) return;
1769
2369
  inStack.add(name);
1770
2370
  const def = defs[name];
1771
- if (isShadowDef(def)) {
2371
+ if (isLightingDef(def)) {
1772
2372
  dfs(def.bg);
1773
2373
  if (def.fg) dfs(def.fg);
1774
2374
  } else if (isMixDef(def)) {
@@ -1791,7 +2391,7 @@ function topoSort(defs) {
1791
2391
  visited.add(name);
1792
2392
  const def = defs[name];
1793
2393
  if (def === void 0) return;
1794
- if (isShadowDef(def)) {
2394
+ if (isLightingDef(def)) {
1795
2395
  visit(def.bg);
1796
2396
  if (def.fg) visit(def.fg);
1797
2397
  } else if (isMixDef(def)) {
@@ -1810,7 +2410,8 @@ function topoSort(defs) {
1810
2410
  //#endregion
1811
2411
  //#region src/warnings.ts
1812
2412
  /**
1813
- * Contrast-warning dispatcher.
2413
+ * Resolve-time warning dispatcher: unmet contrast floors, chromatic contrast
2414
+ * drift, and out-of-reach shadow / glow steps.
1814
2415
  *
1815
2416
  * Tokens memoize their resolution, but a long-lived process (e.g. a dev
1816
2417
  * server with HMR) can re-resolve the same theme many times. The cache
@@ -1862,6 +2463,23 @@ function warnContrastDrift(name, isDark, isHighContrast, contrast, yColor, yBase
1862
2463
  if (dedupe(`drift|${name}|${scheme}|${contrast.metric}|${contrast.target.toFixed(2)}|${actual.toFixed(2)}`)) return;
1863
2464
  console.warn(`glaze: color "${name}" drifts below ${metricLabel(contrast)} in ${scheme} scheme (measured ${actual.toFixed(2)}). Chromatic luminance differs from the gray tone; nudge the tone or saturation if the floor matters.`);
1864
2465
  }
2466
+ /** Tone slack before an out-of-reach shadow / glow step is worth a warning. */
2467
+ const LIGHTING_WARN_SLACK = .05;
2468
+ /**
2469
+ * Warn when a `shadow` / `glow` step is out of reach of its pigment — a glow
2470
+ * on white, a deep shadow on near-black — so the composite pins to the
2471
+ * pigment's strongest and lands short. `name` is omitted for the standalone
2472
+ * `glaze.shadow()` / `glaze.glow()` factories, which have no scheme either.
2473
+ */
2474
+ function warnLightingUnreachable(kind, name, scheme, step, reached) {
2475
+ if (reached >= step - LIGHTING_WARN_SLACK) return;
2476
+ const label = scheme ? schemeLabel(scheme.isDark, scheme.isHighContrast) : void 0;
2477
+ if (dedupe(`lighting|${kind}|${name ?? ""}|${label ?? ""}|${step.toFixed(2)}|${reached.toFixed(2)}`)) return;
2478
+ const subject = name === void 0 ? `glaze.${kind}()` : `${kind} "${name}"`;
2479
+ const where = label === void 0 ? "" : ` in ${label} scheme`;
2480
+ const extreme = kind === "shadow" ? "black" : "white";
2481
+ console.warn(`glaze: ${subject} cannot reach a ${step.toFixed(1)}-tone step${where} (reached ${reached.toFixed(1)} at full strength). Lower the intensity, move the surface away from ${extreme}, or raise a tuned-down \`reach\`.`);
2482
+ }
1865
2483
 
1866
2484
  //#endregion
1867
2485
  //#region src/resolver.ts
@@ -1869,14 +2487,19 @@ function warnContrastDrift(name, isDark, isHighContrast, contrast, yColor, yBase
1869
2487
  * Color resolution engine.
1870
2488
  *
1871
2489
  * Runs the four-pass solver (light → light-HC → dark → dark-HC) that
1872
- * turns a `ColorMap` into a fully resolved `ResolvedColor` per name.
1873
- * Owns the per-scheme resolve helpers for regular, shadow, and mix
1874
- * color defs.
2490
+ * turns a `ColorMap` into a fully resolved `ResolvedColor` per name. A manual
2491
+ * `contrastLevel` interpolates the authored HC pairs, tone window, and contrast
2492
+ * targets at that level for the two *normal* passes only; the high-contrast
2493
+ * passes bypass the level entirely, so the high-contrast slots are the same
2494
+ * values `'auto'` resolves. At level 100 the normal passes already are the
2495
+ * high-contrast ones, so the solver drops to two passes (light → dark) and
2496
+ * mirrors the slots. Owns the per-scheme resolve helpers for regular, shadow /
2497
+ * glow, and mix color defs.
1875
2498
  *
1876
2499
  * Variants are stored in OKHST: `h` / `s` are OKHSL hue/saturation and
1877
2500
  * `t` is the canonical contrast-uniform tone (0–1, reference eps). The
1878
2501
  * resolver works in tone for regular colors and converts to/from OKHSL
1879
- * lightness only at the mix/shadow and luminance edges.
2502
+ * lightness only at the mix / shadow / glow and luminance edges.
1880
2503
  *
1881
2504
  * Every function receives a single `GlazeConfigResolved` so the full
1882
2505
  * per-instance config (including overrides) is available without
@@ -1935,7 +2558,7 @@ function resolveRoleInMap(name, def, defs, inferRole, roles) {
1935
2558
  const cached = roles.get(name);
1936
2559
  if (cached) return cached;
1937
2560
  let role;
1938
- if (isShadowDef(def)) role = "surface";
2561
+ if (isLightingDef(def)) role = "surface";
1939
2562
  else if (isMixDef(def)) role = normalizeRole(def.role) ?? (inferRole ? inferRoleFromName(name) : void 0) ?? resolveBaseRoleInMap(def.base, defs, inferRole, roles) ?? "text";
1940
2563
  else {
1941
2564
  const regDef = def;
@@ -1953,128 +2576,248 @@ function resolveRoleInMap(name, def, defs, inferRole, roles) {
1953
2576
  * 4. `'text'` (foreground) default
1954
2577
  *
1955
2578
  * Memoized on `ctx.roles` so the four scheme passes share one resolution.
1956
- * Shadows have no contrast participation and default to `'surface'`.
2579
+ * Shadows and glows have no contrast participation and default to `'surface'`.
1957
2580
  */
1958
2581
  function resolveRole(name, def, ctx) {
1959
2582
  return resolveRoleInMap(name, def, ctx.defs, ctx.config.inferRole, ctx.roles);
1960
2583
  }
1961
- function resolveContrastSpec(spec, isHighContrast, polarity) {
2584
+ function resolveContrastSpec(spec, isHighContrast, config, polarity) {
2585
+ if (!isHighContrast && contrastFraction(config) !== void 0) return resolveContrastForLevel(spec, config.contrastLevel, polarity);
1962
2586
  const outerExplicitHC = Array.isArray(spec);
1963
2587
  return resolveContrastForMode(isHighContrast ? pairHC(spec) : pairNormal(spec), isHighContrast, polarity, outerExplicitHC);
1964
2588
  }
1965
2589
  /**
2590
+ * The authored tone for this pass: the pair's own entry in `'auto'` mode, or
2591
+ * the manual-level interpolation. Returns the parsed struct so the `kind` —
2592
+ * which selects the branch in `resolveDependentColor` — is fixed here once.
2593
+ */
2594
+ function passTone(tone, isHighContrast, config) {
2595
+ const f = contrastFraction(config);
2596
+ return f === void 0 || isHighContrast ? parseToneValue(isHighContrast ? pairHC(tone) : pairNormal(tone)) : parseToneValueAt(tone, f);
2597
+ }
2598
+ /** The authored numeric pair for this pass (shadow / glow `intensity`, mix `value`). */
2599
+ function passNumber(p, isHighContrast, config) {
2600
+ const f = contrastFraction(config);
2601
+ if (f === void 0 || isHighContrast) return isHighContrast ? pairHC(p) : pairNormal(p);
2602
+ return numberAt(p, f);
2603
+ }
2604
+ /**
1966
2605
  * Apply the relative-tone delta against a base, honoring `flip`.
1967
2606
  *
1968
- * When `flip` is on and `base + delta` falls outside `[0, 100]`, mirror the
1969
- * delta to the other side of the base (so an offset that would clamp instead
1970
- * reflects back into range). When off, the caller clamps as usual.
2607
+ * When `flip` is on and `base + delta` falls outside `[0, 100]`, try mirroring
2608
+ * the delta to the other side of the base. If the mirrored target is also out
2609
+ * of range, keep the original delta so the caller clamps on the authored side.
2610
+ * When off, the caller clamps as usual.
1971
2611
  */
1972
2612
  function applyToneFlip(delta, baseTone, flip) {
1973
2613
  if (!flip) return delta;
1974
2614
  const target = baseTone + delta;
1975
2615
  if (target >= 0 && target <= 100) return delta;
1976
- return -delta;
2616
+ const mirrored = baseTone - delta;
2617
+ if (mirrored >= 0 && mirrored <= 100) return -delta;
2618
+ return delta;
2619
+ }
2620
+ /**
2621
+ * Dark position for an extreme tone (`'max'` / `'min'`) anchored to a base.
2622
+ *
2623
+ * A windowed dark remap compresses the base→extreme span, so the pair loses
2624
+ * contrast in dark. Instead, measure the tone shift the light scheme applied
2625
+ * between the base and the extreme, then replay it against the base's dark
2626
+ * tone: `auto` mirrors the sign (both ends invert), `fixed` keeps it. The
2627
+ * result is clamped to `[0, 100]` only — crossing the dark tone window is
2628
+ * intended, since the author asked for the extreme.
2629
+ */
2630
+ function extremeDarkTone(authorTone, mode, isHighContrast, baseResolved, config) {
2631
+ const extremeLightTone = mapToneForScheme(authorTone, mode, false, isHighContrast, config);
2632
+ const lightBase = getSchemeVariant(baseResolved, false, isHighContrast);
2633
+ const darkBase = getSchemeVariant(baseResolved, true, isHighContrast);
2634
+ const shift = extremeLightTone - lightBase.t * 100;
2635
+ return clamp(darkBase.t * 100 + (mode === "auto" ? -shift : shift), 0, 100);
2636
+ }
2637
+ /**
2638
+ * Hue, absolute saturation (0–1) and tone (0–100) read off a color def's `from`.
2639
+ *
2640
+ * Deliberately not memoized. Keying a cache on the def object looks free — a
2641
+ * resolve reads this a handful of times per color — but defs are stored by
2642
+ * reference, so mutating one in place and re-setting it would invalidate the
2643
+ * theme's own cache while a def-keyed cache quietly served the old color. The
2644
+ * parse is a few microseconds against a resolve that is already cached; that is
2645
+ * not a trade worth a staleness bug.
2646
+ */
2647
+ function fromSeed(def) {
2648
+ if (def.from === void 0) return void 0;
2649
+ const { h, s, l } = extractOkhslFromValue(def.from);
2650
+ return {
2651
+ hue: h,
2652
+ saturation: s,
2653
+ tone: toTone(l)
2654
+ };
2655
+ }
2656
+ /**
2657
+ * The config this color resolves against.
2658
+ *
2659
+ * A `from` color carries a literal value, so its light variant has to survive
2660
+ * the light tone window intact — hence a local `lightTone: false`, the same
2661
+ * default the value-shorthand form of `glaze.color()` applies. Only the light
2662
+ * window is dropped: dark and high contrast keep theirs, because that is where
2663
+ * the color is expected to adapt.
2664
+ */
2665
+ function configForColor(def, config) {
2666
+ if (def.from === void 0) return config;
2667
+ return {
2668
+ ...config,
2669
+ lightTone: false
2670
+ };
2671
+ }
2672
+ function resolveRootColor(def, isHighContrast, config) {
2673
+ if (def.tone === void 0) return clamp(fromSeed(def).tone, 0, 100);
2674
+ return clamp(passTone(def.tone, isHighContrast, config).value, 0, 100);
1977
2675
  }
1978
- function resolveRootColor(def, isHighContrast) {
1979
- const rawT = def.tone;
2676
+ /**
2677
+ * Effective hue and saturation for one color in one scheme.
2678
+ *
2679
+ * Dark schemes read the dark seed pair and the color's `darkHue` /
2680
+ * `darkSaturation`, each falling back to its light counterpart. An explicit
2681
+ * dark saturation — on the seed or the def — is taken literally; the global
2682
+ * `darkDesaturation` reduction applies only when neither is authored.
2683
+ * `mode: 'static'` pins one value across every scheme, so it skips all of it.
2684
+ *
2685
+ * Shared by `resolveColorForScheme` (the emitted variant) and
2686
+ * `resolveDependentColor` (the contrast solver's inputs) so the solver always
2687
+ * measures the color it is actually going to produce.
2688
+ */
2689
+ function resolveChannels(def, ctx, isDark) {
2690
+ const mode = def.mode ?? "auto";
2691
+ const satFactor = clamp(def.saturation ?? 1, 0, 1);
2692
+ const seed = fromSeed(def);
2693
+ const fromHue = seed !== void 0 && def.hue === void 0 ? seed.hue : void 0;
2694
+ const fromSaturation = seed !== void 0 && def.saturation === void 0 ? seed.saturation : void 0;
2695
+ if (!isDark || mode === "static") return {
2696
+ hue: fromHue ?? resolveEffectiveHue(ctx.hue, def.hue),
2697
+ saturation: fromSaturation ?? clamp(satFactor * ctx.saturation / 100, 0, 1)
2698
+ };
2699
+ const darkSeedSaturation = ctx.darkSaturation ?? ctx.saturation;
2700
+ const darkFactor = clamp(def.darkSaturation ?? satFactor, 0, 1);
2701
+ const fromDark = fromSaturation !== void 0 && def.darkSaturation === void 0;
2702
+ const raw = fromDark ? fromSaturation : darkFactor * darkSeedSaturation / 100;
2703
+ const explicitDark = fromDark ? false : def.darkSaturation !== void 0 || ctx.darkSaturation !== void 0;
1980
2704
  return {
1981
- authorTone: clamp(parseToneValue(isHighContrast ? pairHC(rawT) : pairNormal(rawT)).value, 0, 100),
1982
- satFactor: clamp(def.saturation ?? 1, 0, 1)
2705
+ hue: fromHue !== void 0 && def.darkHue === void 0 ? fromHue : resolveEffectiveHue(ctx.darkHue ?? ctx.hue, def.darkHue ?? def.hue),
2706
+ saturation: clamp(explicitDark ? raw : mapSaturationDark(raw, mode, ctx.config), 0, 1)
1983
2707
  };
1984
2708
  }
1985
- function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effectiveHue, polarity, effectivePastel) {
2709
+ function resolveDependentColor(name, def, ctx, isHighContrast, isDark, channels, polarity, effectivePastel) {
1986
2710
  const baseName = def.base;
1987
2711
  const baseResolved = ctx.resolved.get(baseName);
1988
2712
  if (!baseResolved) throw new Error(`glaze: base "${baseName}" not yet resolved for "${name}".`);
1989
2713
  const mode = def.mode ?? "auto";
1990
- const satFactor = clamp(def.saturation ?? 1, 0, 1);
1991
2714
  const flip = def.autoFlip ?? ctx.config.autoFlip;
1992
2715
  const pastel = effectivePastel;
2716
+ const config = configForColor(def, ctx.config);
1993
2717
  const baseVariant = getSchemeVariant(baseResolved, isDark, isHighContrast);
1994
2718
  const baseTone = baseVariant.t * 100;
1995
2719
  let preferredTone;
1996
- const rawTone = def.tone;
2720
+ let isExtreme = false;
2721
+ const seed = fromSeed(def);
2722
+ const rawTone = def.tone ?? (seed !== void 0 ? seed.tone : void 0);
1997
2723
  if (rawTone === void 0) preferredTone = baseTone;
1998
2724
  else {
1999
- const parsed = parseToneValue(isHighContrast ? pairHC(rawTone) : pairNormal(rawTone));
2725
+ const parsed = passTone(rawTone, isHighContrast, config);
2000
2726
  if (parsed.kind === "relative") if (isDark && mode === "auto") {
2001
2727
  const baseLightTone = getSchemeVariant(baseResolved, false, isHighContrast).t * 100;
2002
- preferredTone = mapToneForScheme(clamp(baseLightTone + applyToneFlip(parsed.value, baseLightTone, flip), 0, 100), "auto", true, isHighContrast, ctx.config);
2728
+ preferredTone = mapToneForScheme(clamp(baseLightTone + applyToneFlip(parsed.value, baseLightTone, flip), 0, 100), "auto", true, isHighContrast, config);
2003
2729
  } else preferredTone = clamp(baseTone + applyToneFlip(parsed.value, baseTone, flip), 0, 100);
2004
- else preferredTone = mapToneForScheme(parsed.value, mode, isDark, isHighContrast, ctx.config);
2730
+ else {
2731
+ isExtreme = parsed.kind === "extreme";
2732
+ if (isExtreme && isDark && mode !== "static") preferredTone = extremeDarkTone(parsed.value, mode, isHighContrast, baseResolved, config);
2733
+ else preferredTone = mapToneForScheme(parsed.value, mode, isDark, isHighContrast, config);
2734
+ }
2005
2735
  }
2006
2736
  const rawContrast = def.contrast;
2007
2737
  if (rawContrast !== void 0) {
2008
- const resolvedContrast = resolveContrastSpec(rawContrast, isHighContrast, polarity);
2009
- const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode, ctx.config) : satFactor * ctx.saturation / 100;
2738
+ const resolvedContrast = resolveContrastSpec(rawContrast, isHighContrast, config, polarity);
2010
2739
  const baseOkhsl = toOkhslVariant(baseVariant);
2011
2740
  const baseLinearRgb = okhslToLinearSrgb(baseOkhsl.h, baseOkhsl.s, baseOkhsl.l, baseVariant.pastel ?? ctx.config.pastel);
2012
- const toneRange = schemeToneRange(isDark, mode, isHighContrast, ctx.config);
2741
+ const preferredRange = isExtreme ? [0, 1] : schemeToneRange(isDark, mode, isHighContrast, config);
2013
2742
  let initialDirection;
2014
2743
  if (preferredTone < baseTone) initialDirection = "darker";
2015
2744
  else if (preferredTone > baseTone) initialDirection = "lighter";
2016
- const result = findToneForContrast({
2017
- hue: effectiveHue,
2018
- saturation: effectiveSat,
2019
- preferredTone: clamp(preferredTone / 100, toneRange[0], toneRange[1]),
2745
+ const solve = {
2746
+ hue: channels.hue,
2747
+ saturation: channels.saturation,
2748
+ preferredTone: clamp(preferredTone / 100, preferredRange[0], preferredRange[1]),
2020
2749
  baseLinearRgb,
2021
- contrast: resolvedContrast,
2022
2750
  toneRange: [0, 1],
2023
- initialDirection,
2024
2751
  flip,
2025
2752
  pastel
2753
+ };
2754
+ const level = isHighContrast ? void 0 : contrastFraction(config);
2755
+ let preferInitial = false;
2756
+ if (level !== void 0 && level > 0 && level < 1) {
2757
+ initialDirection = findToneForContrast({
2758
+ ...solve,
2759
+ contrast: resolveContrastForLevel(rawContrast, level < PAIR_SWITCH ? 0 : 100, polarity),
2760
+ initialDirection
2761
+ }).tone * 100 < baseTone ? "darker" : "lighter";
2762
+ preferInitial = true;
2763
+ }
2764
+ const result = findToneForContrast({
2765
+ ...solve,
2766
+ contrast: resolvedContrast,
2767
+ initialDirection,
2768
+ preferInitial
2026
2769
  });
2027
2770
  if (!result.met) warnContrastUnmet(name, isDark, isHighContrast, resolvedContrast, result.contrast);
2028
- return {
2029
- tone: result.tone * 100,
2030
- satFactor
2031
- };
2771
+ return result.tone * 100;
2032
2772
  }
2033
- return {
2034
- tone: clamp(preferredTone, 0, 100),
2035
- satFactor
2036
- };
2773
+ return clamp(preferredTone, 0, 100);
2037
2774
  }
2038
2775
  function resolveColorForScheme(name, def, ctx, isDark, isHighContrast) {
2039
- if (isShadowDef(def)) return resolveShadowForScheme(def, ctx, isDark, isHighContrast);
2776
+ if (isLightingDef(def)) return resolveLightingForScheme(name, def, ctx, isDark, isHighContrast);
2040
2777
  if (isMixDef(def)) return resolveMixForScheme(name, def, ctx, isDark, isHighContrast);
2041
2778
  const regDef = def;
2042
2779
  const mode = regDef.mode ?? "auto";
2043
- const isRoot = isAbsoluteTone(regDef.tone) && !regDef.base;
2044
- const effectiveHue = resolveEffectiveHue(ctx.hue, regDef.hue);
2780
+ const isRoot = hasAbsoluteTone(regDef) && !regDef.base;
2781
+ const channels = resolveChannels(regDef, ctx, isDark);
2045
2782
  const polarity = roleToPolarity(resolveRole(name, def, ctx));
2046
2783
  const pastel = regDef.pastel ?? ctx.config.pastel;
2047
- let finalTone;
2048
- let satFactor;
2049
- if (isRoot) {
2050
- const root = resolveRootColor(regDef, isHighContrast);
2051
- finalTone = mapToneForScheme(root.authorTone, mode, isDark, isHighContrast, ctx.config);
2052
- satFactor = root.satFactor;
2053
- } else {
2054
- const dep = resolveDependentColor(name, regDef, ctx, isHighContrast, isDark, effectiveHue, polarity, pastel);
2055
- finalTone = dep.tone;
2056
- satFactor = dep.satFactor;
2057
- }
2058
- const baseSat = satFactor * ctx.saturation / 100;
2059
- const finalSat = isDark ? mapSaturationDark(baseSat, mode, ctx.config) : baseSat;
2060
- const toneFraction = clamp(finalTone / 100, 0, 1);
2784
+ const config = configForColor(regDef, ctx.config);
2785
+ const finalTone = isRoot ? mapToneForScheme(resolveRootColor(regDef, isHighContrast, config), mode, isDark, isHighContrast, config) : resolveDependentColor(name, regDef, ctx, isHighContrast, isDark, channels, polarity, pastel);
2061
2786
  return {
2062
- h: effectiveHue,
2063
- s: clamp(finalSat, 0, 1),
2064
- t: toneFraction,
2787
+ h: channels.hue,
2788
+ s: channels.saturation,
2789
+ t: clamp(finalTone / 100, 0, 1),
2065
2790
  alpha: regDef.opacity ?? 1,
2066
2791
  pastel
2067
2792
  };
2068
2793
  }
2069
- function resolveShadowForScheme(def, ctx, isDark, isHighContrast) {
2794
+ /**
2795
+ * Shadow / glow: solve the pigment opacity that lands this scheme's `bg`
2796
+ * exactly `intensity × k` tones darker / lighter. `bg` and `fg` are read per
2797
+ * scheme, so the object factor `k` adapts on its own in dark and high contrast.
2798
+ */
2799
+ function resolveLightingForScheme(name, def, ctx, isDark, isHighContrast) {
2070
2800
  const bgVariant = toOkhslVariant(getSchemeVariant(ctx.resolved.get(def.bg), isDark, isHighContrast));
2071
- let fgVariant;
2072
- if (def.fg) fgVariant = toOkhslVariant(getSchemeVariant(ctx.resolved.get(def.fg), isDark, isHighContrast));
2073
- const intensity = isHighContrast ? pairHC(def.intensity) : pairNormal(def.intensity);
2074
- const tuning = resolveShadowTuning(def.tuning, ctx.config.shadowTuning);
2801
+ const fgVariant = def.fg ? toOkhslVariant(getSchemeVariant(ctx.resolved.get(def.fg), isDark, isHighContrast)) : void 0;
2802
+ const intensity = passNumber(def.intensity, isHighContrast, ctx.config);
2803
+ const tuning = resolveLightingTuning(def.tuning, def.type === "shadow" ? ctx.config.shadowTuning : ctx.config.glowTuning);
2804
+ const pastel = def.pastel ?? ctx.config.pastel;
2805
+ const result = computeLighting(def.type, {
2806
+ ...bgVariant,
2807
+ pastel: bgVariant.pastel ?? ctx.config.pastel
2808
+ }, fgVariant, intensity, tuning, pastel);
2809
+ warnLightingUnreachable(def.type, name, {
2810
+ isDark,
2811
+ isHighContrast
2812
+ }, result.step, result.reached);
2075
2813
  return {
2076
- ...toToneVariant(computeShadow(bgVariant, fgVariant, intensity, tuning)),
2077
- pastel: def.pastel ?? ctx.config.pastel
2814
+ ...toToneVariant({
2815
+ h: result.h,
2816
+ s: result.s,
2817
+ l: result.l,
2818
+ alpha: result.alpha
2819
+ }),
2820
+ pastel
2078
2821
  };
2079
2822
  }
2080
2823
  function okhslVariantToLinearRgb(v, pastel) {
@@ -2119,7 +2862,7 @@ function resolveMixForScheme(name, def, ctx, isDark, isHighContrast) {
2119
2862
  const targetResolved = ctx.resolved.get(def.target);
2120
2863
  const baseVariant = toOkhslVariant(getSchemeVariant(baseResolved, isDark, isHighContrast));
2121
2864
  const targetVariant = toOkhslVariant(getSchemeVariant(targetResolved, isDark, isHighContrast));
2122
- let t = clamp(isHighContrast ? pairHC(def.value) : pairNormal(def.value), 0, 100) / 100;
2865
+ let t = clamp(passNumber(def.value, isHighContrast, ctx.config), 0, 100) / 100;
2123
2866
  const blend = def.blend ?? "opaque";
2124
2867
  const space = def.space ?? "okhsl";
2125
2868
  const polarity = roleToPolarity(resolveRole(name, def, ctx));
@@ -2127,10 +2870,14 @@ function resolveMixForScheme(name, def, ctx, isDark, isHighContrast) {
2127
2870
  const baseLinear = okhslVariantToLinearRgb(baseVariant, baseVariant.pastel ?? ctx.config.pastel);
2128
2871
  const targetLinear = okhslVariantToLinearRgb(targetVariant, targetVariant.pastel ?? ctx.config.pastel);
2129
2872
  if (def.contrast !== void 0) {
2130
- const resolvedContrast = resolveContrastSpec(def.contrast, isHighContrast, polarity);
2873
+ const resolvedContrast = resolveContrastSpec(def.contrast, isHighContrast, ctx.config, polarity);
2131
2874
  const metric = resolvedContrast.metric;
2132
2875
  let luminanceAt;
2133
- if (blend === "transparent" || space === "srgb") luminanceAt = (v) => metricLuminance(metric, linearSrgbLerp(baseLinear, targetLinear, v));
2876
+ if (blend === "transparent") {
2877
+ const baseGamma = toDisplayGamma(baseLinear);
2878
+ const targetGamma = toDisplayGamma(targetLinear);
2879
+ luminanceAt = (v) => metricLuminance(metric, compositeOverGamma(baseGamma, targetGamma, v));
2880
+ } else if (space === "srgb") luminanceAt = (v) => metricLuminance(metric, linearSrgbLerp(baseLinear, targetLinear, v));
2134
2881
  else luminanceAt = (v) => {
2135
2882
  return metricLuminance(metric, okhslToLinearSrgb(mixHue(baseVariant, targetVariant, v), baseVariant.s + (targetVariant.s - baseVariant.s) * v, baseVariant.l + (targetVariant.l - baseVariant.l) * v, pastel));
2136
2883
  };
@@ -2167,7 +2914,7 @@ function resolveMixForScheme(name, def, ctx, isDark, isHighContrast) {
2167
2914
  };
2168
2915
  }
2169
2916
  function defMode(def) {
2170
- if (isShadowDef(def) || isMixDef(def)) return void 0;
2917
+ if (isLightingDef(def) || isMixDef(def)) return void 0;
2171
2918
  return def.mode ?? "auto";
2172
2919
  }
2173
2920
  /**
@@ -2211,22 +2958,28 @@ function seedField(order, ctx, field, source) {
2211
2958
  }
2212
2959
  }
2213
2960
  /**
2214
- * After the four passes, surface chromatic contrast drift (§10): a color
2961
+ * After the passes, surface chromatic contrast drift (§10): a color
2215
2962
  * resolved with a `base` + `contrast` may land slightly under the contrast
2216
2963
  * its tone implies because chromatic luminance drifts from the gray tone.
2964
+ *
2965
+ * Under a manual `contrastLevel` the spec is resolved at the level, so the check
2966
+ * measures each normal variant against the target it was actually solved for. At
2967
+ * level 100 the high-contrast slots are mirrors and are skipped: the normal
2968
+ * schemes already carry that check, and repeating it would emit a byte-identical
2969
+ * advisory under a different scheme label, which dedupes as a separate key.
2217
2970
  */
2218
2971
  function verifyContrastDrift(order, defs, result, config) {
2219
2972
  const roles = /* @__PURE__ */ new Map();
2220
2973
  for (const name of order) {
2221
2974
  const def = defs[name];
2222
- if (isShadowDef(def) || isMixDef(def)) continue;
2975
+ if (isLightingDef(def) || isMixDef(def)) continue;
2223
2976
  const regDef = def;
2224
2977
  if (regDef.contrast === void 0 || !regDef.base) continue;
2225
2978
  const color = result.get(name);
2226
2979
  const base = result.get(regDef.base);
2227
2980
  if (!color || !base) continue;
2228
2981
  const polarity = roleToPolarity(resolveRoleInMap(name, def, defs, config.inferRole, roles));
2229
- for (const s of [
2982
+ const schemes = [
2230
2983
  {
2231
2984
  isDark: false,
2232
2985
  isHighContrast: false,
@@ -2247,8 +3000,11 @@ function verifyContrastDrift(order, defs, result, config) {
2247
3000
  isHighContrast: true,
2248
3001
  field: "darkContrast"
2249
3002
  }
2250
- ]) {
2251
- const spec = resolveContrastSpec(regDef.contrast, s.isHighContrast, polarity);
3003
+ ];
3004
+ const mirrored = hcMirrorsNormal(config);
3005
+ for (const s of schemes) {
3006
+ if (mirrored && s.isHighContrast) continue;
3007
+ const spec = resolveContrastSpec(regDef.contrast, s.isHighContrast, config, polarity);
2252
3008
  const cVariant = color[s.field];
2253
3009
  const bVariant = base[s.field];
2254
3010
  const cOkhsl = toOkhslVariant(cVariant);
@@ -2261,26 +3017,32 @@ function verifyContrastDrift(order, defs, result, config) {
2261
3017
  }
2262
3018
  }
2263
3019
  }
2264
- function resolveAllColors(hue, saturation, defs, config, externalBases) {
3020
+ function resolveAllColors(seed, defs, config, externalBases) {
2265
3021
  validateColorDefs(defs, externalBases);
2266
3022
  const order = topoSort(defs);
2267
3023
  const ctx = {
2268
- hue,
2269
- saturation,
3024
+ ...seed,
2270
3025
  defs,
2271
3026
  resolved: /* @__PURE__ */ new Map(),
2272
3027
  config,
2273
3028
  roles: /* @__PURE__ */ new Map()
2274
3029
  };
2275
3030
  if (externalBases) for (const [name, color] of externalBases) ctx.resolved.set(name, color);
3031
+ const mirrored = hcMirrorsNormal(config);
2276
3032
  const lightMap = runPass(order, defs, ctx, false, false, "light");
2277
- seedField(order, ctx, "lightContrast", lightMap);
2278
- const lightHCMap = runPass(order, defs, ctx, false, true, "lightContrast");
3033
+ let lightHCMap = lightMap;
3034
+ if (!mirrored) {
3035
+ seedField(order, ctx, "lightContrast", lightMap);
3036
+ lightHCMap = runPass(order, defs, ctx, false, true, "lightContrast");
3037
+ }
2279
3038
  seedField(order, ctx, "dark", lightMap);
2280
3039
  seedField(order, ctx, "darkContrast", lightHCMap);
2281
3040
  const darkMap = runPass(order, defs, ctx, true, false, "dark");
2282
- seedField(order, ctx, "darkContrast", darkMap);
2283
- const darkHCMap = runPass(order, defs, ctx, true, true, "darkContrast");
3041
+ let darkHCMap = darkMap;
3042
+ if (!mirrored) {
3043
+ seedField(order, ctx, "darkContrast", darkMap);
3044
+ darkHCMap = runPass(order, defs, ctx, true, true, "darkContrast");
3045
+ }
2284
3046
  const result = /* @__PURE__ */ new Map();
2285
3047
  for (const name of order) result.set(name, {
2286
3048
  name,
@@ -2299,8 +3061,14 @@ function resolveAllColors(hue, saturation, defs, config, externalBases) {
2299
3061
  /**
2300
3062
  * Hue channel planning for `splitHue` exports.
2301
3063
  *
2302
- * Builds per-color hue var references and scheme-independent `--*-hue`
2303
- * declarations for oklch CSS / Tasty output when every color is pastel.
3064
+ * Builds per-color hue var references and the `--*-hue` declarations backing
3065
+ * them for oklch CSS / Tasty output when every color is pastel.
3066
+ *
3067
+ * Hue is scheme-independent unless the theme or a color authors a dark hue,
3068
+ * so declarations are collected per scheme (`'light'` / `'dark'`) and the dark
3069
+ * set is emitted only when it actually differs — see `buildHueDeclarations`.
3070
+ * A color that authors a hue in *either* scheme gets its own var in both, so
3071
+ * the shared `var()` reference stays valid.
2304
3072
  */
2305
3073
  const ACHROMATIC_EPSILON = 1e-6;
2306
3074
  function cssProp(prefix, name, suffix) {
@@ -2309,21 +3077,52 @@ function cssProp(prefix, name, suffix) {
2309
3077
  function isAchromatic(v) {
2310
3078
  return v.s <= ACHROMATIC_EPSILON;
2311
3079
  }
2312
- function themeHuePlan(name, def, variant, ctx) {
2313
- if (def === void 0 || isShadowDef(def) || isMixDef(def) || isAchromatic(variant)) return {
3080
+ /** Seed hue backing `--{baseName}-hue` in a given scheme. */
3081
+ function schemeSeedHue(ctx, scheme) {
3082
+ return scheme === "dark" ? ctx.darkSeedHue ?? ctx.seedHue : ctx.seedHue;
3083
+ }
3084
+ function themeHuePlan(name, def, variant, ctx, scheme) {
3085
+ if (def === void 0 || isLightingDef(def) || isMixDef(def) || isAchromatic(variant)) return {
2314
3086
  hueVar: "",
2315
3087
  inline: true,
2316
3088
  declarations: []
2317
3089
  };
2318
3090
  const regDef = def;
2319
3091
  const baseHueVar = `var(--${ctx.baseName}-hue)`;
2320
- if (regDef.hue === void 0) return {
3092
+ const prop = cssProp(ctx.prefix, name, "-hue");
3093
+ if ((regDef.mode ?? "auto") === "static" && schemeSeedHue(ctx, "dark") !== ctx.seedHue) return {
3094
+ hueVar: `var(${prop})`,
3095
+ inline: false,
3096
+ declarations: [{
3097
+ prop,
3098
+ value: String(variant.h)
3099
+ }]
3100
+ };
3101
+ if (regDef.hue === void 0 && regDef.darkHue === void 0 && regDef.from === void 0) return {
2321
3102
  hueVar: baseHueVar,
2322
3103
  inline: false,
2323
3104
  declarations: []
2324
3105
  };
2325
- const parsed = parseRelativeOrAbsolute(regDef.hue);
2326
- const prop = cssProp(ctx.prefix, name, "-hue");
3106
+ const authored = scheme === "dark" ? regDef.darkHue ?? regDef.hue : regDef.hue;
3107
+ if (authored === void 0) {
3108
+ if (regDef.from !== void 0) return {
3109
+ hueVar: `var(${prop})`,
3110
+ inline: false,
3111
+ declarations: [{
3112
+ prop,
3113
+ value: String(variant.h)
3114
+ }]
3115
+ };
3116
+ return {
3117
+ hueVar: `var(${prop})`,
3118
+ inline: false,
3119
+ declarations: [{
3120
+ prop,
3121
+ value: baseHueVar
3122
+ }]
3123
+ };
3124
+ }
3125
+ const parsed = parseRelativeOrAbsolute(authored);
2327
3126
  if (parsed.relative) {
2328
3127
  const sign = parsed.value >= 0 ? "+" : "-";
2329
3128
  const magnitude = Math.abs(parsed.value);
@@ -2347,13 +3146,13 @@ function themeHuePlan(name, def, variant, ctx) {
2347
3146
  }]
2348
3147
  };
2349
3148
  }
2350
- function standaloneHuePlan(name, variant, ctx) {
3149
+ function standaloneHuePlan(name, variant, ctx, scheme) {
2351
3150
  if (isAchromatic(variant)) return {
2352
3151
  hueVar: "",
2353
3152
  inline: true,
2354
3153
  declarations: []
2355
3154
  };
2356
- const hue = ctx.resolvedHue ?? variant.h;
3155
+ const hue = scheme === "dark" ? variant.h : ctx.resolvedHue ?? variant.h;
2357
3156
  const prop = cssProp(ctx.prefix, name, "-hue");
2358
3157
  return {
2359
3158
  hueVar: `var(${prop})`,
@@ -2364,12 +3163,12 @@ function standaloneHuePlan(name, variant, ctx) {
2364
3163
  }]
2365
3164
  };
2366
3165
  }
2367
- function buildHuePlan(name, def, variant, ctx) {
2368
- if (ctx.mode === "standalone") return standaloneHuePlan(name, variant, ctx);
2369
- return themeHuePlan(name, def, variant, ctx);
3166
+ function buildHuePlan(name, def, variant, ctx, scheme = "light") {
3167
+ if (ctx.mode === "standalone") return standaloneHuePlan(name, variant, ctx, scheme);
3168
+ return themeHuePlan(name, def, variant, ctx, scheme);
2370
3169
  }
2371
3170
  /** Collect unique hue declarations across all colors (theme + per-color). */
2372
- function collectHueDeclarations(resolved, ctx) {
3171
+ function collectHueDeclarations(resolved, ctx, scheme) {
2373
3172
  if (ctx.emitDeclarations === false) return [];
2374
3173
  const seen = /* @__PURE__ */ new Set();
2375
3174
  const out = [];
@@ -2380,15 +3179,35 @@ function collectHueDeclarations(resolved, ctx) {
2380
3179
  };
2381
3180
  if (ctx.mode === "theme") push({
2382
3181
  prop: `--${ctx.baseName}-hue`,
2383
- value: String(ctx.seedHue)
3182
+ value: String(schemeSeedHue(ctx, scheme))
2384
3183
  });
2385
3184
  for (const [name, color] of resolved) {
2386
3185
  const def = ctx.defs[name];
2387
- const plan = buildHuePlan(name, def, color.light, ctx);
3186
+ const plan = buildHuePlan(name, def, scheme === "dark" ? color.dark : color.light, ctx, scheme);
2388
3187
  for (const decl of plan.declarations) push(decl);
2389
3188
  }
2390
3189
  return out;
2391
3190
  }
3191
+ /**
3192
+ * Hue declarations for both schemes. `dark` is empty when it resolves to the
3193
+ * same hues as light — the common case, with no `darkHue` anywhere.
3194
+ *
3195
+ * When they differ, the **whole** dark set is returned rather than only the
3196
+ * entries whose text changed. A relative declaration reads
3197
+ * `calc(var(--theme-hue) + N)` in both schemes even though its resolved value
3198
+ * moves with the seed, and custom properties substitute `var()` at
3199
+ * computed-value time on the declaring element — so re-declaring
3200
+ * `--{baseName}-hue` alone would leave inherited per-color vars still holding
3201
+ * the light-substituted value.
3202
+ */
3203
+ function buildHueDeclarations(resolved, ctx) {
3204
+ const light = collectHueDeclarations(resolved, ctx, "light");
3205
+ const dark = collectHueDeclarations(resolved, ctx, "dark");
3206
+ return {
3207
+ light,
3208
+ dark: dark.length === light.length && dark.every((decl, i) => decl.prop === light[i].prop && decl.value === light[i].value) ? [] : dark
3209
+ };
3210
+ }
2392
3211
  function buildHuePlans(resolved, ctx) {
2393
3212
  const plans = /* @__PURE__ */ new Map();
2394
3213
  for (const [name, color] of resolved) plans.set(name, buildHuePlan(name, ctx.defs[name], color.light, ctx));
@@ -2422,10 +3241,10 @@ function fmt(value, decimals) {
2422
3241
  function formatVariant(v, format = "oklch", pastel = false) {
2423
3242
  const effectivePastel = v.pastel ?? pastel;
2424
3243
  let base;
2425
- if (format === "okhst") base = formatOkhst(v.h, v.s * 100, v.t * 100, effectivePastel);
3244
+ if (format === "okhst") base = formatOkhst(v.h, v.s, v.t, effectivePastel);
2426
3245
  else {
2427
3246
  const { l } = variantToOkhsl(v);
2428
- base = formatters[format](v.h, v.s * 100, l * 100, effectivePastel);
3247
+ base = formatters[format](v.h, v.s, l, effectivePastel);
2429
3248
  }
2430
3249
  if (v.alpha >= 1) return base;
2431
3250
  const closing = base.lastIndexOf(")");
@@ -2441,7 +3260,7 @@ function formatVariantHue(v, plan, pastel = false) {
2441
3260
  const [L, C] = okhslToOklch(v.h, v.s, l, effectivePastel);
2442
3261
  let base;
2443
3262
  if (plan.inline) if (v.s <= 1e-6) base = `oklch(${fmt(L, 4)} 0 0)`;
2444
- else base = formatOklch(v.h, v.s * 100, l * 100, effectivePastel);
3263
+ else base = formatOklch(v.h, v.s, l, effectivePastel);
2445
3264
  else base = `oklch(${fmt(L, 4)} ${fmt(C, 4)} ${plan.hueVar})`;
2446
3265
  if (v.alpha >= 1) return base;
2447
3266
  const closing = base.lastIndexOf(")");
@@ -2451,28 +3270,47 @@ function formatColorValue(v, format, pastel, huePlan) {
2451
3270
  if (format === "oklch" && huePlan !== void 0) return formatVariantHue(v, huePlan, pastel);
2452
3271
  return formatVariant(v, format, pastel);
2453
3272
  }
3273
+ /**
3274
+ * Resolve the effective output modes for an export.
3275
+ *
3276
+ * `modes.highContrast` and `contrastLevel` are independent: the level positions
3277
+ * the normal variants, the high-contrast tier stays the true high-contrast
3278
+ * resolution, and the two compose — a slider raises the baseline while a
3279
+ * `prefers-contrast: more` block still escalates on top of it.
3280
+ *
3281
+ * The one exception is a **global** level of 100, where the normal variants
3282
+ * already *are* the high-contrast ones. The tier would be an exact duplicate, so
3283
+ * it is dropped and a single light/dark set is emitted — including against an
3284
+ * explicit `highContrast: true` override, which has nothing different left to
3285
+ * ask for.
3286
+ *
3287
+ * A level set on a single theme or token does not change which modes are
3288
+ * emitted: `modes` is global-only, and a palette must not have one sibling
3289
+ * collapse the shared token structure. A per-instance level of 100 therefore
3290
+ * still reports into the tier, with values equal to its own normal ones.
3291
+ */
2454
3292
  function resolveModes(override) {
2455
3293
  const cfg = getConfig();
3294
+ const highContrast = override?.highContrast ?? cfg.modes.highContrast;
2456
3295
  return {
2457
3296
  dark: override?.dark ?? cfg.modes.dark,
2458
- highContrast: override?.highContrast ?? cfg.modes.highContrast
3297
+ highContrast: highContrast && !hcMirrorsNormal(cfg)
2459
3298
  };
2460
3299
  }
2461
3300
  function buildTokenMap(resolved, prefix, states, modes, format = "oklch", pastel = false, channelCtx) {
2462
3301
  const tokens = {};
2463
3302
  const huePlans = channelCtx !== void 0 && format === "oklch" ? buildHuePlans(resolved, channelCtx) : void 0;
2464
3303
  if (huePlans !== void 0 && channelCtx !== void 0) {
2465
- const emitDecls = channelCtx.emitDeclarations !== false;
2466
- if (emitDecls && channelCtx.mode === "theme") tokens[`$${channelCtx.baseName}-hue`] = { "": String(channelCtx.seedHue) };
2467
- for (const [name, color] of resolved) {
2468
- const plan = huePlans.get(name);
2469
- if (emitDecls) for (const decl of plan.declarations) {
2470
- const key = `$${decl.prop.slice(2)}`;
2471
- if (!(key in tokens)) tokens[key] = { "": decl.value };
2472
- }
2473
- const colorKey = `#${prefix}${name}`;
2474
- tokens[colorKey] = buildTokenEntry(color, states, modes, format, pastel, huePlans.get(name));
3304
+ const hueDecls = buildHueDeclarations(resolved, channelCtx);
3305
+ for (const decl of hueDecls.light) tokens[`$${decl.prop.slice(2)}`] = { "": decl.value };
3306
+ if (modes.dark) for (const decl of hueDecls.dark) {
3307
+ const key = `$${decl.prop.slice(2)}`;
3308
+ tokens[key] = {
3309
+ ...tokens[key],
3310
+ [states.dark]: decl.value
3311
+ };
2475
3312
  }
3313
+ for (const [name, color] of resolved) tokens[`#${prefix}${name}`] = buildTokenEntry(color, states, modes, format, pastel, huePlans.get(name));
2476
3314
  return tokens;
2477
3315
  }
2478
3316
  for (const [name, color] of resolved) {
@@ -2521,7 +3359,14 @@ function buildCssMap(resolved, prefix, suffix, format, pastel = false, channelCt
2521
3359
  darkContrast: []
2522
3360
  };
2523
3361
  const huePlans = channelCtx !== void 0 && format === "oklch" ? buildHuePlans(resolved, channelCtx) : void 0;
2524
- if (huePlans !== void 0 && channelCtx !== void 0) for (const decl of collectHueDeclarations(resolved, channelCtx)) lines.light.push(`${decl.prop}: ${decl.value};`);
3362
+ if (huePlans !== void 0 && channelCtx !== void 0) {
3363
+ const hueDecls = buildHueDeclarations(resolved, channelCtx);
3364
+ for (const decl of hueDecls.light) lines.light.push(`${decl.prop}: ${decl.value};`);
3365
+ for (const decl of hueDecls.dark) {
3366
+ lines.dark.push(`${decl.prop}: ${decl.value};`);
3367
+ lines.darkContrast.push(`${decl.prop}: ${decl.value};`);
3368
+ }
3369
+ }
2525
3370
  for (const [name, color] of resolved) {
2526
3371
  const prop = `--${prefix}${name}${suffix}`;
2527
3372
  const plan = huePlans?.get(name);
@@ -2632,323 +3477,136 @@ const DEFAULT_DTCG_CONTEXT_NAMES = {
2632
3477
  * produced `result`.
2633
3478
  */
2634
3479
  function buildDtcgResolver(result, options) {
2635
- const setName = options?.setName ?? "base";
2636
- const modifierName = options?.modifierName ?? "scheme";
2637
- const ctx = {
2638
- ...DEFAULT_DTCG_CONTEXT_NAMES,
2639
- ...options?.contextNames
2640
- };
2641
- const contexts = { [ctx.light]: [] };
2642
- if (result.dark) contexts[ctx.dark] = [result.dark];
2643
- if (result.lightContrast) contexts[ctx.lightContrast] = [result.lightContrast];
2644
- if (result.darkContrast) contexts[ctx.darkContrast] = [result.darkContrast];
2645
- return {
2646
- version: options?.version ?? "2025.10",
2647
- sets: { [setName]: { sources: [result.light] } },
2648
- modifiers: { [modifierName]: {
2649
- default: ctx.light,
2650
- contexts
2651
- } },
2652
- resolutionOrder: [{ $ref: `#/sets/${setName}` }, { $ref: `#/modifiers/${modifierName}` }]
2653
- };
2654
- }
2655
- function tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel) {
2656
- const lines = {
2657
- light: [],
2658
- dark: [],
2659
- lightContrast: [],
2660
- darkContrast: []
2661
- };
2662
- for (const [name, color] of resolved) {
2663
- const prop = `--${cssPrefix}${themePrefix}${name}`;
2664
- lines.light.push(`${prop}: ${formatVariant(color.light, format, pastel)};`);
2665
- lines.dark.push(`${prop}: ${formatVariant(color.dark, format, pastel)};`);
2666
- lines.lightContrast.push(`${prop}: ${formatVariant(color.lightContrast, format, pastel)};`);
2667
- lines.darkContrast.push(`${prop}: ${formatVariant(color.darkContrast, format, pastel)};`);
2668
- }
2669
- return lines;
2670
- }
2671
- function indentBlock(text, pad) {
2672
- return text.split("\n").map((line) => line.length === 0 ? line : pad + line).join("\n");
2673
- }
2674
- function emitRule(selector, body) {
2675
- return `${selector} {\n${indentBlock(body, " ")}\n}`;
2676
- }
2677
- /**
2678
- * Emit a CSS block for a set of declarations scoped by one or more selectors
2679
- * / at-rules. Class-like selectors concatenate (`.dark.high-contrast`);
2680
- * at-rules (`@media …`) nest `:root` (or the chained selector) inside.
2681
- */
2682
- function emitScoped(scopes, declarations) {
2683
- if (declarations.length === 0) return void 0;
2684
- const atRules = [];
2685
- let selectorChain = "";
2686
- for (const scope of scopes) if (scope.startsWith("@")) atRules.push(scope);
2687
- else selectorChain += scope;
2688
- let css = emitRule(selectorChain || ":root", declarations.join("\n"));
2689
- for (const rule of atRules) css = emitRule(rule, css);
2690
- return css;
2691
- }
2692
- /**
2693
- * Render accumulated per-scheme declaration lines as a Tailwind v4 CSS string:
2694
- * an `@theme` block (light baseline) plus dark / high-contrast overrides under
2695
- * the configured selectors. Empty blocks are skipped.
2696
- */
2697
- function emitTailwindCss(lines, modes, darkSelector, highContrastSelector) {
2698
- const blocks = [];
2699
- if (lines.light.length > 0) blocks.push(emitRule("@theme", lines.light.join("\n")));
2700
- if (modes.dark) {
2701
- const dark = emitScoped([darkSelector], lines.dark);
2702
- if (dark) blocks.push(dark);
2703
- }
2704
- if (modes.highContrast) {
2705
- const hc = emitScoped([highContrastSelector], lines.lightContrast);
2706
- if (hc) blocks.push(hc);
2707
- }
2708
- if (modes.dark && modes.highContrast) {
2709
- const dhc = emitScoped([darkSelector, highContrastSelector], lines.darkContrast);
2710
- if (dhc) blocks.push(dhc);
2711
- }
2712
- return blocks.join("\n\n");
2713
- }
2714
- /**
2715
- * Build per-scheme declaration lines for a single theme (used by
2716
- * `theme.tailwind()` and as the palette `buildOne` step).
2717
- */
2718
- function buildTailwindLines(resolved, themePrefix, cssPrefix, format, pastel) {
2719
- return tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel);
2720
- }
2721
- /**
2722
- * Build a complete Tailwind v4 CSS string for a single theme.
2723
- */
2724
- function buildTailwindMap(resolved, themePrefix, cssPrefix, modes, format, darkSelector, highContrastSelector, pastel = false) {
2725
- return emitTailwindCss(tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel), modes, darkSelector, highContrastSelector);
2726
- }
2727
-
2728
- //#endregion
2729
- //#region src/color-token.ts
2730
- /**
2731
- * Standalone single-color tokens (`glaze.color()` / `glaze.colorFrom()`).
2732
- *
2733
- * Owns the value-shorthand parser (hex, `rgb()` / `hsl()` / `okhsl()` /
2734
- * `okhst()` / `oklch()`, `{ r, g, b }`, `{ h, s, l }`, `{ h, s, t }`,
2735
- * `{ l, c, h }`), the structured-input validator, the two factory paths
2736
- * (value vs structured), and the JSON-safe export / rehydration round-trip.
2737
- *
2738
- * Standalone tokens snapshot the full effective config at create time
2739
- * so later `configure()` calls do not retroactively change exported
2740
- * tokens. The snapshot is built eagerly in
2741
- * `buildValueFormConfigOverride()` / `buildStructuredConfigOverride()`.
2742
- * The token's resolved variants are then memoized on first
2743
- * `.resolve()` / `.token()` / ... call.
2744
- */
2745
- /** Internal name of the user-facing standalone color in the synthesized def map. */
2746
- const STANDALONE_VALUE = "value";
2747
- /** Internal name of the hidden static-anchor seed used for relative tone / contrast. */
2748
- const STANDALONE_SEED = "seed";
2749
- /** Internal name of an externally-resolved `GlazeColorToken` injected as a base reference. */
2750
- const STANDALONE_BASE = "externalBase";
2751
- /** Reserved internal names that user-supplied `name` must not collide with. */
2752
- const RESERVED_STANDALONE_NAMES = new Set([
2753
- STANDALONE_VALUE,
2754
- STANDALONE_SEED,
2755
- STANDALONE_BASE
2756
- ]);
2757
- /**
2758
- * Build the per-token effective config override for a value-form color.
2759
- *
2760
- * Light window defaults to `false` (preserve input tone exactly).
2761
- * All other fields snapshot from global at create time via
2762
- * `buildEffectiveConfigOverride`. User override fields win.
2763
- */
2764
- function buildValueFormConfigOverride(userOverride) {
2765
- return buildEffectiveConfigOverride({
2766
- ...userOverride,
2767
- lightTone: userOverride?.lightTone !== void 0 ? userOverride.lightTone : false
2768
- });
2769
- }
2770
- /**
2771
- * Build the per-token effective config override for a structured-form color.
2772
- * Snapshots the full effective config (incl. pastel / inferRole).
2773
- */
2774
- function buildStructuredConfigOverride(userOverride) {
2775
- return buildEffectiveConfigOverride(userOverride);
2776
- }
2777
- /**
2778
- * Build the `GlazeConfigResolved` to pass to `resolveAllColors` from a
2779
- * snapshot override. Uses `defaultConfig()` as the base so all required
2780
- * fields are present; the snapshot fields win.
2781
- */
2782
- function resolvedConfigFromOverride(override) {
2783
- return mergeConfig(defaultConfig(), override);
2784
- }
2785
- /**
2786
- * Matches the CSS color functions Glaze itself emits (`rgb()`, `hsl()`,
2787
- * `okhsl()`, `oklch()`) plus their legacy alpha aliases (`rgba()`, `hsla()`).
2788
- *
2789
- * Only bare numeric components are supported. Named colors (`red`),
2790
- * relative-color syntax (`from <color> ...`), and angle units other
2791
- * than bare degrees (`deg` is the only suffix tolerated by `parseFloat`)
2792
- * are out of scope.
2793
- */
2794
- const COLOR_FN_RE = /^(rgba?|hsla?|okhsl|okhst|oklch)\(\s*([^)]*)\s*\)$/i;
2795
- function parseNumberOrPercent(raw, percentScale) {
2796
- if (raw.endsWith("%")) return parseFloat(raw) / 100 * percentScale;
2797
- return parseFloat(raw);
2798
- }
2799
- /**
2800
- * Split the body of a CSS color function into its components and detect
2801
- * whether an alpha channel was present.
2802
- *
2803
- * Handles both modern slash syntax (`R G B / A` or `R, G, B / A`) and
2804
- * legacy comma syntax (`R, G, B, A`). The alpha value itself is discarded
2805
- * by the caller — standalone Glaze colors have no opacity field.
2806
- */
2807
- function splitColorBody(body) {
2808
- const slashIdx = body.indexOf("/");
2809
- if (slashIdx !== -1) return {
2810
- components: body.slice(0, slashIdx).trim().split(/[\s,]+/).filter(Boolean),
2811
- hadAlpha: body.slice(slashIdx + 1).trim().length > 0
2812
- };
2813
- const components = body.split(/[\s,]+/).filter(Boolean);
2814
- if (components.length === 4) {
2815
- components.pop();
2816
- return {
2817
- components,
2818
- hadAlpha: true
2819
- };
2820
- }
2821
- return {
2822
- components,
2823
- hadAlpha: false
2824
- };
2825
- }
2826
- function warnDroppedAlpha(input) {
2827
- console.warn(`glaze: alpha component dropped from "${input}" (standalone color has no opacity field).`);
2828
- }
2829
- function parseColorString(input) {
2830
- if (input.startsWith("#")) {
2831
- const parsed = parseHexAlpha(input);
2832
- if (!parsed) throw new Error(`glaze: invalid hex color "${input}".`);
2833
- if (parsed.alpha !== void 0) warnDroppedAlpha(input);
2834
- const [h, s, l] = srgbToOkhsl(parsed.rgb);
2835
- return {
2836
- h,
2837
- s,
2838
- l
2839
- };
2840
- }
2841
- const m = input.match(COLOR_FN_RE);
2842
- if (!m) throw new Error(`glaze: unsupported color string "${input}".`);
2843
- const fn = m[1].toLowerCase();
2844
- const { components, hadAlpha } = splitColorBody(m[2].trim());
2845
- if (hadAlpha) warnDroppedAlpha(input);
2846
- if (components.length !== 3) throw new Error(`glaze: expected 3 components in "${input}".`);
2847
- switch (fn) {
2848
- case "rgb":
2849
- case "rgba": {
2850
- const [h, s, l] = srgbToOkhsl([
2851
- parseNumberOrPercent(components[0], 255) / 255,
2852
- parseNumberOrPercent(components[1], 255) / 255,
2853
- parseNumberOrPercent(components[2], 255) / 255
2854
- ]);
2855
- return {
2856
- h,
2857
- s,
2858
- l
2859
- };
2860
- }
2861
- case "hsl":
2862
- case "hsla": {
2863
- const [oh, os, ol] = srgbToOkhsl(hslToSrgb(parseFloat(components[0]), parseNumberOrPercent(components[1], 1), parseNumberOrPercent(components[2], 1)));
2864
- return {
2865
- h: oh,
2866
- s: os,
2867
- l: ol
2868
- };
2869
- }
2870
- case "okhsl": return {
2871
- h: parseFloat(components[0]),
2872
- s: parseNumberOrPercent(components[1], 1),
2873
- l: parseNumberOrPercent(components[2], 1)
2874
- };
2875
- case "okhst": return okhstToOkhsl({
2876
- h: parseFloat(components[0]),
2877
- s: parseNumberOrPercent(components[1], 1),
2878
- t: parseNumberOrPercent(components[2], 1)
2879
- });
2880
- case "oklch": {
2881
- const L = parseNumberOrPercent(components[0], 1);
2882
- const C = parseNumberOrPercent(components[1], .4);
2883
- const hRad = parseFloat(components[2]) * Math.PI / 180;
2884
- const [h, s, l] = oklabToOkhsl([
2885
- L,
2886
- C * Math.cos(hRad),
2887
- C * Math.sin(hRad)
2888
- ]);
2889
- return {
2890
- h,
2891
- s,
2892
- l
2893
- };
2894
- }
3480
+ const setName = options?.setName ?? "base";
3481
+ const modifierName = options?.modifierName ?? "scheme";
3482
+ const ctx = {
3483
+ ...DEFAULT_DTCG_CONTEXT_NAMES,
3484
+ ...options?.contextNames
3485
+ };
3486
+ const contexts = { [ctx.light]: [] };
3487
+ if (result.dark) contexts[ctx.dark] = [result.dark];
3488
+ if (result.lightContrast) contexts[ctx.lightContrast] = [result.lightContrast];
3489
+ if (result.darkContrast) contexts[ctx.darkContrast] = [result.darkContrast];
3490
+ return {
3491
+ version: options?.version ?? "2025.10",
3492
+ sets: { [setName]: { sources: [result.light] } },
3493
+ modifiers: { [modifierName]: {
3494
+ default: ctx.light,
3495
+ contexts
3496
+ } },
3497
+ resolutionOrder: [{ $ref: `#/sets/${setName}` }, { $ref: `#/modifiers/${modifierName}` }]
3498
+ };
3499
+ }
3500
+ function tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel) {
3501
+ const lines = {
3502
+ light: [],
3503
+ dark: [],
3504
+ lightContrast: [],
3505
+ darkContrast: []
3506
+ };
3507
+ for (const [name, color] of resolved) {
3508
+ const prop = `--${cssPrefix}${themePrefix}${name}`;
3509
+ lines.light.push(`${prop}: ${formatVariant(color.light, format, pastel)};`);
3510
+ lines.dark.push(`${prop}: ${formatVariant(color.dark, format, pastel)};`);
3511
+ lines.lightContrast.push(`${prop}: ${formatVariant(color.lightContrast, format, pastel)};`);
3512
+ lines.darkContrast.push(`${prop}: ${formatVariant(color.darkContrast, format, pastel)};`);
2895
3513
  }
2896
- throw new Error(`glaze: unsupported color function "${fn}".`);
3514
+ return lines;
3515
+ }
3516
+ function indentBlock(text, pad) {
3517
+ return text.split("\n").map((line) => line.length === 0 ? line : pad + line).join("\n");
3518
+ }
3519
+ function emitRule(selector, body) {
3520
+ return `${selector} {\n${indentBlock(body, " ")}\n}`;
2897
3521
  }
2898
3522
  /**
2899
- * Validate a user-supplied `OkhslColor`. Catches the common 0-100 vs 0-1
2900
- * confusion (the structured form uses 0-100, OKHSL objects use 0-1).
3523
+ * Emit a CSS block for a set of declarations scoped by one or more selectors
3524
+ * / at-rules. Class-like selectors concatenate (`.dark.high-contrast`);
3525
+ * at-rules (`@media …`) nest `:root` (or the chained selector) inside.
2901
3526
  */
2902
- function validateOkhslColor(value) {
2903
- const { h, s, l } = value;
2904
- if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l)) throw new Error("glaze.color: OkhslColor h/s/l must be finite numbers.");
2905
- if (s > 1.5 || l > 1.5) throw new Error("glaze.color: OkhslColor s/l must be in 0–1 range. Did you mean the structured form { hue, saturation, tone } (which uses 0–100)?");
3527
+ function emitScoped(scopes, declarations) {
3528
+ if (declarations.length === 0) return void 0;
3529
+ const atRules = [];
3530
+ let selectorChain = "";
3531
+ for (const scope of scopes) if (scope.startsWith("@")) atRules.push(scope);
3532
+ else selectorChain += scope;
3533
+ let css = emitRule(selectorChain || ":root", declarations.join("\n"));
3534
+ for (const rule of atRules) css = emitRule(rule, css);
3535
+ return css;
2906
3536
  }
2907
- /** Validate a user-supplied `{ r, g, b }` object in 0–255. */
2908
- function validateRgbColor(value) {
2909
- for (const key of [
2910
- "r",
2911
- "g",
2912
- "b"
2913
- ]) {
2914
- const n = value[key];
2915
- if (!Number.isFinite(n) || n < 0 || n > 255) throw new Error(`glaze.color: RgbColor ${key} must be a finite number in 0–255 (got ${n}).`);
3537
+ /**
3538
+ * Render accumulated per-scheme declaration lines as a Tailwind v4 CSS string:
3539
+ * an `@theme` block (light baseline) plus dark / high-contrast overrides under
3540
+ * the configured selectors. Empty blocks are skipped.
3541
+ */
3542
+ function emitTailwindCss(lines, modes, darkSelector, highContrastSelector) {
3543
+ const blocks = [];
3544
+ if (lines.light.length > 0) blocks.push(emitRule("@theme", lines.light.join("\n")));
3545
+ if (modes.dark) {
3546
+ const dark = emitScoped([darkSelector], lines.dark);
3547
+ if (dark) blocks.push(dark);
3548
+ }
3549
+ if (modes.highContrast) {
3550
+ const hc = emitScoped([highContrastSelector], lines.lightContrast);
3551
+ if (hc) blocks.push(hc);
3552
+ }
3553
+ if (modes.dark && modes.highContrast) {
3554
+ const dhc = emitScoped([darkSelector, highContrastSelector], lines.darkContrast);
3555
+ if (dhc) blocks.push(dhc);
2916
3556
  }
3557
+ return blocks.join("\n\n");
2917
3558
  }
2918
- /** Validate a user-supplied `{ l, c, h }` OKLCh object. */
2919
- function validateOklchColor(value) {
2920
- const { l, c, h } = value;
2921
- if (!Number.isFinite(l) || !Number.isFinite(c) || !Number.isFinite(h)) throw new Error("glaze.color: OklchColor l/c/h must be finite numbers.");
2922
- if (l > 1.5 || c > 1.5) throw new Error("glaze.color: OklchColor l/c must be in 0–1 range (matching oklch() strings).");
3559
+ /**
3560
+ * Build per-scheme declaration lines for a single theme (used by
3561
+ * `theme.tailwind()` and as the palette `buildOne` step).
3562
+ */
3563
+ function buildTailwindLines(resolved, themePrefix, cssPrefix, format, pastel) {
3564
+ return tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel);
2923
3565
  }
2924
- function oklchComponentsToOkhsl(l, c, hDeg) {
2925
- const hRad = hDeg * Math.PI / 180;
2926
- const [h, s, outL] = oklabToOkhsl([
2927
- l,
2928
- c * Math.cos(hRad),
2929
- c * Math.sin(hRad)
2930
- ]);
3566
+ /**
3567
+ * Build a complete Tailwind v4 CSS string for a single theme.
3568
+ */
3569
+ function buildTailwindMap(resolved, themePrefix, cssPrefix, modes, format, darkSelector, highContrastSelector, pastel = false) {
3570
+ return emitTailwindCss(tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel), modes, darkSelector, highContrastSelector);
3571
+ }
3572
+
3573
+ //#endregion
3574
+ //#region src/color-token.ts
3575
+ /**
3576
+ * Standalone single-color tokens (`glaze.color()` / `glaze.colorFrom()`).
3577
+ *
3578
+ * Owns the value-shorthand parser (hex, `rgb()` / `hsl()` / `okhsl()` /
3579
+ * `okhst()` / `oklch()`, `{ r, g, b }`, `{ h, s, l }`, `{ h, s, t }`,
3580
+ * `{ l, c, h }`), the structured-input validator, the two factory paths
3581
+ * (value vs structured), and the JSON-safe export / rehydration round-trip.
3582
+ *
3583
+ * Tokens store a sparse local config override only. Resolve merges the
3584
+ * live global config with that local override (invalidated on
3585
+ * `configure()`). Authoring `.export(override?)` freezes
3586
+ * `getConfig() ∪ local ∪ override` at call time.
3587
+ */
3588
+ /** Internal name of the user-facing standalone color in the synthesized def map. */
3589
+ const STANDALONE_VALUE = "value";
3590
+ /** Internal name of the hidden static-anchor seed used for relative tone / contrast. */
3591
+ const STANDALONE_SEED = "seed";
3592
+ /** Internal name of an externally-resolved `GlazeColorToken` injected as a base reference. */
3593
+ const STANDALONE_BASE = "externalBase";
3594
+ /** Reserved internal names that user-supplied `name` must not collide with. */
3595
+ const RESERVED_STANDALONE_NAMES = new Set([
3596
+ STANDALONE_VALUE,
3597
+ STANDALONE_SEED,
3598
+ STANDALONE_BASE
3599
+ ]);
3600
+ /**
3601
+ * Value-form local override: `lightTone` defaults to `false` (preserve
3602
+ * input tone). User override fields win.
3603
+ */
3604
+ function sparseValueFormLocal(userOverride) {
2931
3605
  return {
2932
- h,
2933
- s,
2934
- l: outL
3606
+ ...userOverride,
3607
+ lightTone: userOverride?.lightTone !== void 0 ? userOverride.lightTone : false
2935
3608
  };
2936
3609
  }
2937
- function isRgbColorObject(value) {
2938
- return "r" in value && "g" in value && "b" in value;
2939
- }
2940
- function isOklchColorObject(value) {
2941
- return "c" in value && "l" in value && "h" in value;
2942
- }
2943
- function isOkhstColorObject(value) {
2944
- return "t" in value && "h" in value && "s" in value;
2945
- }
2946
- /** Validate a user-supplied `{ h, s, t }` OKHST object (s/t in 0–1). */
2947
- function validateOkhstColor(value) {
2948
- const { h, s, t } = value;
2949
- if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(t)) throw new Error("glaze.color: OkhstColor h/s/t must be finite numbers.");
2950
- if (s > 1.5 || t > 1.5) throw new Error("glaze.color: OkhstColor s/t must be in 0–1 range. Did you mean the structured form { hue, saturation, tone } (which uses 0–100)?");
2951
- }
2952
3610
  /**
2953
3611
  * Validate a user-supplied `opacity` override on `glaze.color()`.
2954
3612
  * Must be a finite number in `0..=1`.
@@ -2978,6 +3636,13 @@ function validateStructuredInput(input) {
2978
3636
  if (input.saturationFactor !== void 0) {
2979
3637
  if (!Number.isFinite(input.saturationFactor) || input.saturationFactor < 0 || input.saturationFactor > 1) throw new Error(`glaze.color: structured saturationFactor must be a finite number in 0–1 (got ${input.saturationFactor}).`);
2980
3638
  }
3639
+ if (typeof input.darkHue === "number" && !Number.isFinite(input.darkHue)) throw new Error(`glaze.color: structured darkHue must be a finite number (got ${input.darkHue}).`);
3640
+ if (input.darkSaturation !== void 0) {
3641
+ if (!Number.isFinite(input.darkSaturation) || input.darkSaturation < 0 || input.darkSaturation > 100) throw new Error(`glaze.color: structured darkSaturation must be a finite number in 0–100 (got ${input.darkSaturation}).`);
3642
+ }
3643
+ if (input.darkSaturationFactor !== void 0) {
3644
+ if (!Number.isFinite(input.darkSaturationFactor) || input.darkSaturationFactor < 0 || input.darkSaturationFactor > 1) throw new Error(`glaze.color: structured darkSaturationFactor must be a finite number in 0–1 (got ${input.darkSaturationFactor}).`);
3645
+ }
2981
3646
  if (input.opacity !== void 0) validateStandaloneOpacity(input.opacity);
2982
3647
  }
2983
3648
  /**
@@ -2992,36 +3657,16 @@ function validateStandaloneName(name) {
2992
3657
  }
2993
3658
  }
2994
3659
  /**
2995
- * Extract an OKHSL color from any `GlazeColorValue` form. Also used by
2996
- * `glaze.shadow()` so all shadow inputs (hex, color functions, OKHSL,
2997
- * literal objects) go through one parser.
3660
+ * Resolve `'max'` / `'min'` to their literal author tones (100 / 0).
3661
+ *
3662
+ * The hidden `STANDALONE_SEED` anchor exists only so `contrast` has something
3663
+ * to measure against — it is not an authored base. Pinning the extreme keeps
3664
+ * the token on the plain scheme mapping instead of the base-anchored dark
3665
+ * replay the resolver applies to real `base` references.
2998
3666
  */
2999
- function extractOkhslFromValue(value) {
3000
- if (typeof value === "string") return parseColorString(value);
3001
- if (Array.isArray(value)) throw new Error("glaze.color: RGB tuple [r, g, b] is no longer supported — use { r, g, b } instead.");
3002
- if (isRgbColorObject(value)) {
3003
- validateRgbColor(value);
3004
- const [h, s, l] = srgbToOkhsl([
3005
- value.r / 255,
3006
- value.g / 255,
3007
- value.b / 255
3008
- ]);
3009
- return {
3010
- h,
3011
- s,
3012
- l
3013
- };
3014
- }
3015
- if (isOklchColorObject(value)) {
3016
- validateOklchColor(value);
3017
- return oklchComponentsToOkhsl(value.l, value.c, value.h);
3018
- }
3019
- if (isOkhstColorObject(value)) {
3020
- validateOkhstColor(value);
3021
- return okhstToOkhsl(value);
3022
- }
3023
- validateOkhslColor(value);
3024
- return value;
3667
+ function pinExtremeTone(tone) {
3668
+ const pin = (value) => value === "max" ? 100 : value === "min" ? 0 : value;
3669
+ return Array.isArray(tone) ? [pin(tone[0]), pin(tone[1])] : pin(tone);
3025
3670
  }
3026
3671
  /**
3027
3672
  * Build the `ColorMap` for a value-shorthand `glaze.color()` call.
@@ -3029,6 +3674,10 @@ function extractOkhslFromValue(value) {
3029
3674
  * The user-facing color (`STANDALONE_VALUE`) defaults to `mode: 'auto'`
3030
3675
  * across every value-shorthand form.
3031
3676
  *
3677
+ * An absolute `hue` override becomes the seed while a relative one becomes a
3678
+ * def field; `darkHue` always lands on the def in either form, so an absolute
3679
+ * `darkHue` wins outright instead of being re-offset by a relative `hue`.
3680
+ *
3032
3681
  * When the user requests `contrast` or relative `tone`, a hidden
3033
3682
  * `STANDALONE_SEED` def is synthesized at `mode: 'static'`. That keeps
3034
3683
  * the seed pinned to the literal user-provided color across all four
@@ -3046,10 +3695,13 @@ function buildStandaloneValueDefs(main, options) {
3046
3695
  if (userName !== void 0) validateStandaloneName(userName);
3047
3696
  const primary = userName ?? STANDALONE_VALUE;
3048
3697
  const seedTone = toTone(main.l);
3698
+ const primaryTone = toneOption ?? seedTone;
3049
3699
  const valueDef = {
3050
3700
  hue: relativeHue,
3051
3701
  saturation: options?.saturationFactor,
3052
- tone: toneOption ?? seedTone,
3702
+ darkHue: options?.darkHue,
3703
+ darkSaturation: options?.darkSaturationFactor,
3704
+ tone: needsSeedAnchor ? pinExtremeTone(primaryTone) : primaryTone,
3053
3705
  contrast: options?.contrast,
3054
3706
  mode: options?.mode ?? "auto",
3055
3707
  autoFlip: options?.autoFlip,
@@ -3066,18 +3718,39 @@ function buildStandaloneValueDefs(main, options) {
3066
3718
  mode: "static"
3067
3719
  };
3068
3720
  return {
3069
- seedHue,
3070
- seedSaturation,
3721
+ seed: {
3722
+ hue: seedHue,
3723
+ saturation: seedSaturation,
3724
+ darkSaturation: options?.darkSaturation
3725
+ },
3071
3726
  defs,
3072
3727
  primary
3073
3728
  };
3074
3729
  }
3075
- function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effectiveConfig, baseToken, exportData) {
3076
- let cached;
3730
+ function createColorTokenFromDefs(seed, defs, primary, configOverride, baseToken, buildExport) {
3731
+ let cache = null;
3732
+ function getEffectiveConfig() {
3733
+ const version = getConfigVersion();
3734
+ if (cache && cache.version === version) return cache.effectiveConfig;
3735
+ const effectiveConfig = mergeConfig(getConfig(), configOverride);
3736
+ cache = {
3737
+ map: null,
3738
+ version,
3739
+ effectiveConfig
3740
+ };
3741
+ return effectiveConfig;
3742
+ }
3077
3743
  const resolveOnce = () => {
3078
- if (cached) return cached;
3079
- cached = resolveAllColors(seedHue, seedSaturation, defs, effectiveConfig, baseToken ? new Map([[STANDALONE_BASE, baseToken.resolve()]]) : void 0);
3080
- return cached;
3744
+ const version = getConfigVersion();
3745
+ if (cache && cache.version === version && cache.map) return cache.map;
3746
+ const effectiveConfig = getEffectiveConfig();
3747
+ const map = resolveAllColors(seed, defs, effectiveConfig, baseToken ? new Map([[STANDALONE_BASE, baseToken.resolve()]]) : void 0);
3748
+ cache = {
3749
+ map,
3750
+ version,
3751
+ effectiveConfig
3752
+ };
3753
+ return map;
3081
3754
  };
3082
3755
  const resolveStates = (options) => {
3083
3756
  const cfg = getConfig();
@@ -3087,7 +3760,7 @@ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effect
3087
3760
  };
3088
3761
  };
3089
3762
  const tokenLike = (options) => {
3090
- return buildTokenMap(resolveOnce(), "", resolveStates(options), resolveModes(options?.modes), options?.format ?? "oklch", effectiveConfig.pastel)[`#${primary}`];
3763
+ return buildTokenMap(resolveOnce(), "", resolveStates(options), resolveModes(options?.modes), options?.format ?? "oklch", getEffectiveConfig().pastel)[`#${primary}`];
3091
3764
  };
3092
3765
  return {
3093
3766
  resolve() {
@@ -3098,7 +3771,7 @@ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effect
3098
3771
  json(options) {
3099
3772
  const format = options?.format ?? "oklch";
3100
3773
  assertNativeFormat(format, "json");
3101
- return buildJsonMap(resolveOnce(), resolveModes(options?.modes), format, effectiveConfig.pastel)[primary];
3774
+ return buildJsonMap(resolveOnce(), resolveModes(options?.modes), format, getEffectiveConfig().pastel)[primary];
3102
3775
  },
3103
3776
  css(options) {
3104
3777
  const format = options.format ?? "oklch";
@@ -3109,7 +3782,7 @@ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effect
3109
3782
  if (options.splitHue && format === "oklch") {
3110
3783
  assertAllPastel(renamed, resolveModes());
3111
3784
  channelCtx = {
3112
- seedHue,
3785
+ seedHue: seed.hue,
3113
3786
  baseName: options.name,
3114
3787
  prefix: "",
3115
3788
  defs: { [options.name]: defs[primary] },
@@ -3117,11 +3790,11 @@ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effect
3117
3790
  resolvedHue: resolved.light.h
3118
3791
  };
3119
3792
  }
3120
- return buildCssMap(renamed, "", options.suffix ?? "-color", format, effectiveConfig.pastel, channelCtx);
3793
+ return buildCssMap(renamed, "", options.suffix ?? "-color", format, getEffectiveConfig().pastel, channelCtx);
3121
3794
  },
3122
3795
  dtcg(options) {
3123
3796
  const modes = resolveModes(options?.modes);
3124
- const doc = buildDtcgMap(resolveOnce(), "", modes, options?.colorSpace ?? "srgb", effectiveConfig.pastel);
3797
+ const doc = buildDtcgMap(resolveOnce(), "", modes, options?.colorSpace ?? "srgb", getEffectiveConfig().pastel);
3125
3798
  const result = { light: doc.light[primary] };
3126
3799
  if (doc.dark) result.dark = doc.dark[primary];
3127
3800
  if (doc.lightContrast) result.lightContrast = doc.lightContrast[primary];
@@ -3129,7 +3802,7 @@ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effect
3129
3802
  return result;
3130
3803
  },
3131
3804
  dtcgResolver(options) {
3132
- const doc = buildDtcgMap(resolveOnce(), "", resolveModes(options?.modes), options?.colorSpace ?? "srgb", effectiveConfig.pastel);
3805
+ const doc = buildDtcgMap(resolveOnce(), "", resolveModes(options?.modes), options?.colorSpace ?? "srgb", getEffectiveConfig().pastel);
3133
3806
  const name = options.name;
3134
3807
  const result = { light: { [name]: doc.light[primary] } };
3135
3808
  if (doc.dark) result.dark = { [name]: doc.dark[primary] };
@@ -3140,9 +3813,11 @@ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effect
3140
3813
  tailwind(options) {
3141
3814
  const format = options.format ?? "oklch";
3142
3815
  assertNativeFormat(format, "tailwind");
3143
- return buildTailwindMap(new Map([[options.name, resolveOnce().get(primary)]]), "", options.namespace ?? "color-", resolveModes(options?.modes), format, options.darkSelector ?? ".dark", options.highContrastSelector ?? ".high-contrast", effectiveConfig.pastel);
3816
+ return buildTailwindMap(new Map([[options.name, resolveOnce().get(primary)]]), "", options.namespace ?? "color-", resolveModes(options?.modes), format, options.darkSelector ?? ".dark", options.highContrastSelector ?? ".high-contrast", getEffectiveConfig().pastel);
3144
3817
  },
3145
- export: exportData
3818
+ export(override) {
3819
+ return buildExport(override);
3820
+ }
3146
3821
  };
3147
3822
  }
3148
3823
  /**
@@ -3191,8 +3866,10 @@ function createColorToken(input, configOverride) {
3191
3866
  const hasExternalBase = baseToken !== void 0;
3192
3867
  const needsSeedAnchor = !hasExternalBase && input.contrast !== void 0;
3193
3868
  const defs = { [primary]: {
3194
- tone: input.tone,
3869
+ tone: needsSeedAnchor ? pinExtremeTone(input.tone) : input.tone,
3195
3870
  saturation: input.saturationFactor,
3871
+ darkHue: input.darkHue,
3872
+ darkSaturation: input.darkSaturationFactor,
3196
3873
  mode: input.mode ?? "auto",
3197
3874
  autoFlip: input.autoFlip,
3198
3875
  contrast: input.contrast,
@@ -3201,52 +3878,52 @@ function createColorToken(input, configOverride) {
3201
3878
  role: input.role,
3202
3879
  base: hasExternalBase ? STANDALONE_BASE : needsSeedAnchor ? STANDALONE_SEED : void 0
3203
3880
  } };
3204
- if (needsSeedAnchor) {
3205
- const seedTone = pairNormal(input.tone);
3206
- defs[STANDALONE_SEED] = {
3207
- tone: seedTone === "max" ? 100 : seedTone === "min" ? 0 : seedTone,
3208
- saturation: 1,
3209
- mode: "static"
3210
- };
3211
- }
3212
- const effectiveConfigOverride = buildStructuredConfigOverride(configOverride);
3213
- const effectiveConfig = resolvedConfigFromOverride(effectiveConfigOverride);
3214
- const exportData = () => ({
3881
+ if (needsSeedAnchor) defs[STANDALONE_SEED] = {
3882
+ tone: pinExtremeTone(pairNormal(input.tone)),
3883
+ saturation: 1,
3884
+ mode: "static"
3885
+ };
3886
+ const localOverride = configOverride;
3887
+ return createColorTokenFromDefs({
3888
+ hue: input.hue,
3889
+ saturation: input.saturation,
3890
+ darkSaturation: input.darkSaturation
3891
+ }, defs, primary, localOverride, baseToken, (exportArg) => ({
3215
3892
  kind: "color",
3216
3893
  version: GLAZE_EXPORT_VERSION,
3217
3894
  form: "structured",
3218
- input: buildStructuredInputExport(input),
3219
- config: effectiveConfigOverride
3220
- });
3221
- return createColorTokenFromDefs(input.hue, input.saturation, defs, primary, effectiveConfig, baseToken, exportData);
3895
+ input: buildStructuredInputExport(input, exportArg),
3896
+ config: freezeConfigForExport(localOverride, exportArg)
3897
+ }));
3222
3898
  }
3223
3899
  function createColorTokenFromValue(value, options, configOverride) {
3224
3900
  const main = extractOkhslFromValue(value);
3225
3901
  const linkingBase = toLinkingBase(resolveBaseToken(options?.base));
3226
- const { seedHue, seedSaturation, defs, primary } = buildStandaloneValueDefs(main, options);
3227
- const effectiveConfigOverride = buildValueFormConfigOverride(configOverride);
3228
- const effectiveConfig = resolvedConfigFromOverride(effectiveConfigOverride);
3229
- const exportData = () => ({
3902
+ const { seed, defs, primary } = buildStandaloneValueDefs(main, options);
3903
+ const localOverride = sparseValueFormLocal(configOverride);
3904
+ return createColorTokenFromDefs(seed, defs, primary, localOverride, linkingBase, (exportArg) => ({
3230
3905
  kind: "color",
3231
3906
  version: GLAZE_EXPORT_VERSION,
3232
3907
  form: "value",
3233
3908
  input: value,
3234
- ...options !== void 0 ? { overrides: buildOverridesExport(options) } : {},
3235
- config: effectiveConfigOverride
3236
- });
3237
- return createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effectiveConfig, linkingBase, exportData);
3909
+ ...options !== void 0 ? { overrides: buildOverridesExport(options, exportArg) } : {},
3910
+ config: freezeConfigForExport(localOverride, exportArg)
3911
+ }));
3238
3912
  }
3239
3913
  /**
3240
3914
  * Build a JSON-safe snapshot of `GlazeColorOverrides`. `base` is
3241
3915
  * recursively serialized when it was originally a token; raw values are
3242
3916
  * preserved as-is so `glaze.colorFrom(...)` round-trips them.
3243
3917
  */
3244
- function buildOverridesExport(options) {
3918
+ function buildOverridesExport(options, exportArg) {
3245
3919
  const out = {};
3246
3920
  if (options.hue !== void 0) out.hue = options.hue;
3247
3921
  if (options.saturation !== void 0) out.saturation = options.saturation;
3248
3922
  if (options.tone !== void 0) out.tone = options.tone;
3249
3923
  if (options.saturationFactor !== void 0) out.saturationFactor = options.saturationFactor;
3924
+ if (options.darkHue !== void 0) out.darkHue = options.darkHue;
3925
+ if (options.darkSaturation !== void 0) out.darkSaturation = options.darkSaturation;
3926
+ if (options.darkSaturationFactor !== void 0) out.darkSaturationFactor = options.darkSaturationFactor;
3250
3927
  if (options.mode !== void 0) out.mode = options.mode;
3251
3928
  if (options.autoFlip !== void 0) out.autoFlip = options.autoFlip;
3252
3929
  if (options.contrast !== void 0) out.contrast = options.contrast;
@@ -3254,16 +3931,19 @@ function buildOverridesExport(options) {
3254
3931
  if (options.name !== void 0) out.name = options.name;
3255
3932
  if (options.pastel !== void 0) out.pastel = options.pastel;
3256
3933
  if (options.role !== void 0) out.role = options.role;
3257
- if (options.base !== void 0) out.base = isGlazeColorToken(options.base) ? options.base.export() : options.base;
3934
+ if (options.base !== void 0) out.base = isGlazeColorToken(options.base) ? options.base.export(exportArg) : options.base;
3258
3935
  return out;
3259
3936
  }
3260
- function buildStructuredInputExport(input) {
3937
+ function buildStructuredInputExport(input, exportArg) {
3261
3938
  const out = {
3262
3939
  hue: input.hue,
3263
3940
  saturation: input.saturation,
3264
3941
  tone: input.tone
3265
3942
  };
3266
3943
  if (input.saturationFactor !== void 0) out.saturationFactor = input.saturationFactor;
3944
+ if (input.darkHue !== void 0) out.darkHue = input.darkHue;
3945
+ if (input.darkSaturation !== void 0) out.darkSaturation = input.darkSaturation;
3946
+ if (input.darkSaturationFactor !== void 0) out.darkSaturationFactor = input.darkSaturationFactor;
3267
3947
  if (input.mode !== void 0) out.mode = input.mode;
3268
3948
  if (input.autoFlip !== void 0) out.autoFlip = input.autoFlip;
3269
3949
  if (input.opacity !== void 0) out.opacity = input.opacity;
@@ -3271,7 +3951,7 @@ function buildStructuredInputExport(input) {
3271
3951
  if (input.name !== void 0) out.name = input.name;
3272
3952
  if (input.pastel !== void 0) out.pastel = input.pastel;
3273
3953
  if (input.role !== void 0) out.role = input.role;
3274
- if (input.base !== void 0) out.base = isGlazeColorToken(input.base) ? input.base.export() : input.base;
3954
+ if (input.base !== void 0) out.base = isGlazeColorToken(input.base) ? input.base.export(exportArg) : input.base;
3275
3955
  return out;
3276
3956
  }
3277
3957
  /**
@@ -3286,6 +3966,9 @@ function rehydrateOverrides(data) {
3286
3966
  if (data.saturation !== void 0) out.saturation = data.saturation;
3287
3967
  if (data.tone !== void 0) out.tone = data.tone;
3288
3968
  if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
3969
+ if (data.darkHue !== void 0) out.darkHue = data.darkHue;
3970
+ if (data.darkSaturation !== void 0) out.darkSaturation = data.darkSaturation;
3971
+ if (data.darkSaturationFactor !== void 0) out.darkSaturationFactor = data.darkSaturationFactor;
3289
3972
  if (data.mode !== void 0) out.mode = data.mode;
3290
3973
  if (data.autoFlip !== void 0) out.autoFlip = data.autoFlip;
3291
3974
  if (data.contrast !== void 0) out.contrast = data.contrast;
@@ -3303,6 +3986,9 @@ function rehydrateStructuredInput(data) {
3303
3986
  tone: data.tone
3304
3987
  };
3305
3988
  if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
3989
+ if (data.darkHue !== void 0) out.darkHue = data.darkHue;
3990
+ if (data.darkSaturation !== void 0) out.darkSaturation = data.darkSaturation;
3991
+ if (data.darkSaturationFactor !== void 0) out.darkSaturationFactor = data.darkSaturationFactor;
3306
3992
  if (data.mode !== void 0) out.mode = data.mode;
3307
3993
  if (data.autoFlip !== void 0) out.autoFlip = data.autoFlip;
3308
3994
  if (data.opacity !== void 0) out.opacity = data.opacity;
@@ -3317,9 +4003,9 @@ function rehydrateStructuredInput(data) {
3317
4003
  * Rehydrate a token from its `.export()` snapshot. Recursively rebuilds
3318
4004
  * any base dependency. Inverse of `GlazeColorToken.export()`.
3319
4005
  *
3320
- * The stored `config` field contains the full effective config override
3321
- * snapshotted at creation time, so the rehydrated token is deterministic
3322
- * regardless of subsequent `glaze.configure()` calls.
4006
+ * The stored `config` field is the freeze from export time — passed as
4007
+ * the instance local override so the rehydrated token stays pinned
4008
+ * against later `glaze.configure()` calls.
3323
4009
  */
3324
4010
  function colorFromExport(data) {
3325
4011
  if (data === null || typeof data !== "object") throw new Error(`glaze.colorFrom: expected an object from token.export(), got ${data === null ? "null" : typeof data}.`);
@@ -3336,19 +4022,26 @@ function colorFromExport(data) {
3336
4022
 
3337
4023
  //#endregion
3338
4024
  //#region src/theme.ts
3339
- function createTheme(hue, saturation, initialColors, configOverride) {
4025
+ function createTheme(seed, initialColors, configOverride) {
4026
+ const { hue, saturation, darkHue, darkSaturation } = seed;
3340
4027
  let colorDefs = initialColors ? { ...initialColors } : {};
3341
4028
  let cache = null;
3342
4029
  function getEffectiveConfig() {
3343
4030
  const version = getConfigVersion();
3344
4031
  if (cache && cache.version === version) return cache.effectiveConfig;
3345
- return mergeConfig(getConfig(), configOverride);
4032
+ const effectiveConfig = mergeConfig(getConfig(), configOverride);
4033
+ cache = {
4034
+ map: null,
4035
+ version,
4036
+ effectiveConfig
4037
+ };
4038
+ return effectiveConfig;
3346
4039
  }
3347
4040
  function resolveCached() {
3348
4041
  const version = getConfigVersion();
3349
- if (cache && cache.version === version) return cache.map;
3350
- const effectiveConfig = mergeConfig(getConfig(), configOverride);
3351
- const map = resolveAllColors(hue, saturation, colorDefs, effectiveConfig);
4042
+ if (cache && cache.version === version && cache.map) return cache.map;
4043
+ const effectiveConfig = getEffectiveConfig();
4044
+ const map = resolveAllColors(seed, colorDefs, effectiveConfig);
3352
4045
  cache = {
3353
4046
  map,
3354
4047
  version,
@@ -3365,6 +4058,7 @@ function createTheme(hue, saturation, initialColors, configOverride) {
3365
4058
  assertAllPastel(resolveCached(), resolveModes(options?.modes));
3366
4059
  return {
3367
4060
  seedHue: hue,
4061
+ darkSeedHue: darkHue,
3368
4062
  baseName: options.name ?? "theme",
3369
4063
  prefix,
3370
4064
  defs: colorDefs,
@@ -3378,6 +4072,12 @@ function createTheme(hue, saturation, initialColors, configOverride) {
3378
4072
  get saturation() {
3379
4073
  return saturation;
3380
4074
  },
4075
+ get darkHue() {
4076
+ return darkHue;
4077
+ },
4078
+ get darkSaturation() {
4079
+ return darkSaturation;
4080
+ },
3381
4081
  getConfig() {
3382
4082
  return getEffectiveConfig();
3383
4083
  },
@@ -3408,22 +4108,28 @@ function createTheme(hue, saturation, initialColors, configOverride) {
3408
4108
  colorDefs = {};
3409
4109
  invalidate();
3410
4110
  },
3411
- export() {
4111
+ export(override) {
3412
4112
  return {
3413
4113
  kind: "theme",
3414
4114
  version: GLAZE_EXPORT_VERSION,
3415
4115
  hue,
3416
4116
  saturation,
4117
+ ...darkHue !== void 0 ? { darkHue } : {},
4118
+ ...darkSaturation !== void 0 ? { darkSaturation } : {},
3417
4119
  colors: structuredClone(colorDefs),
3418
- config: structuredClone(buildEffectiveConfigOverride(configOverride))
4120
+ config: freezeConfigForExport(configOverride, override)
3419
4121
  };
3420
4122
  },
3421
4123
  extend(options) {
3422
- const newHue = options.hue ?? hue;
3423
- const newSat = options.saturation ?? saturation;
4124
+ const childSeed = {
4125
+ hue: options.hue ?? hue,
4126
+ saturation: options.saturation ?? saturation,
4127
+ darkHue: options.darkHue ?? darkHue,
4128
+ darkSaturation: options.darkSaturation ?? darkSaturation
4129
+ };
3424
4130
  const inheritedColors = {};
3425
4131
  for (const [name, def] of Object.entries(colorDefs)) if (def.inherit !== false) inheritedColors[name] = def;
3426
- return createTheme(newHue, newSat, options.colors ? {
4132
+ return createTheme(childSeed, options.colors ? {
3427
4133
  ...inheritedColors,
3428
4134
  ...options.colors
3429
4135
  } : { ...inheritedColors }, configOverride || options.config ? {
@@ -3533,6 +4239,7 @@ function channelCtxForTheme(theme, themeName, passPrefix, themedPrefix, splitHue
3533
4239
  assertAllPastel(filtered, modes);
3534
4240
  return {
3535
4241
  seedHue: theme.hue,
4242
+ darkSeedHue: theme.darkHue,
3536
4243
  baseName: themeName,
3537
4244
  prefix: themedPrefix,
3538
4245
  defs: colorMapFromTheme(theme),
@@ -3558,11 +4265,20 @@ function buildPaletteOutput(themes, paletteOptions, options, buildOne, merge, em
3558
4265
  }
3559
4266
  return acc;
3560
4267
  }
3561
- function themeFromExportData(data) {
3562
- assertExportKind(data, "theme", "glaze.themeFrom");
3563
- assertExportVersion(data, "glaze.themeFrom");
3564
- if (typeof data.hue !== "number" || typeof data.saturation !== "number") throw new Error(`glaze.themeFrom: expected numeric "hue" and "saturation" fields.`);
3565
- return createTheme(data.hue, data.saturation, data.colors, data.config);
4268
+ /** Rebuild a theme from a `theme.export()` snapshot. */
4269
+ function createThemeFromExport(data, factory = "glaze.themeFrom", fallbackVersion) {
4270
+ if (data === null || typeof data !== "object") throw new Error(`${factory}: expected an object from theme.export(), got ${data === null ? "null" : typeof data}.`);
4271
+ assertExportKind(data, "theme", factory);
4272
+ assertExportVersion(data, factory);
4273
+ assertNoLegacyShadows(data, factory, fallbackVersion);
4274
+ if (typeof data.hue !== "number" || typeof data.saturation !== "number") throw new Error(`${factory}: expected numeric "hue" and "saturation" fields.`);
4275
+ for (const field of ["darkHue", "darkSaturation"]) if (data[field] !== void 0 && typeof data[field] !== "number") throw new Error(`${factory}: expected "${field}" to be a number when present (got ${JSON.stringify(data[field])}).`);
4276
+ return createTheme({
4277
+ hue: data.hue,
4278
+ saturation: data.saturation,
4279
+ darkHue: data.darkHue,
4280
+ darkSaturation: data.darkSaturation
4281
+ }, data.colors, data.config);
3566
4282
  }
3567
4283
  /**
3568
4284
  * Rebuild a palette from a `palette.export()` snapshot.
@@ -3573,17 +4289,9 @@ function createPaletteFromExport(data) {
3573
4289
  assertExportVersion(data, "glaze.paletteFrom");
3574
4290
  if (data.themes === null || typeof data.themes !== "object") throw new Error(`glaze.paletteFrom: expected a "themes" object map of theme exports.`);
3575
4291
  const rebuilt = {};
3576
- for (const [name, themeExport] of Object.entries(data.themes)) {
3577
- if (themeExport === null || typeof themeExport !== "object") throw new Error(`glaze.paletteFrom: theme "${name}" is not a valid theme export.`);
3578
- rebuilt[name] = themeFromExportData(themeExport);
3579
- }
4292
+ for (const [name, themeExport] of Object.entries(data.themes)) rebuilt[name] = createThemeFromExport(themeExport, `glaze.paletteFrom (theme "${name}")`, data.version);
3580
4293
  return createPalette(rebuilt, { primary: data.primary });
3581
4294
  }
3582
- /** Rebuild a theme from a `theme.export()` snapshot. */
3583
- function createThemeFromExport(data) {
3584
- if (data === null || typeof data !== "object") throw new Error(`glaze.themeFrom: expected an object from theme.export(), got ${data === null ? "null" : typeof data}.`);
3585
- return themeFromExportData(data);
3586
- }
3587
4295
  function createPalette(themes, paletteOptions) {
3588
4296
  validatePrimaryTheme(paletteOptions?.primary, themes);
3589
4297
  const buildDtcgResult = (options) => {
@@ -3609,9 +4317,9 @@ function createPalette(themes, paletteOptions) {
3609
4317
  themes() {
3610
4318
  return { ...themes };
3611
4319
  },
3612
- export() {
4320
+ export(override) {
3613
4321
  const themesExport = {};
3614
- for (const [name, theme] of Object.entries(themes)) themesExport[name] = theme.export();
4322
+ for (const [name, theme] of Object.entries(themes)) themesExport[name] = theme.export(override);
3615
4323
  const out = {
3616
4324
  kind: "palette",
3617
4325
  version: GLAZE_EXPORT_VERSION,
@@ -3718,7 +4426,7 @@ function createPalette(themes, paletteOptions) {
3718
4426
  * - `theme.ts` — single-theme factory
3719
4427
  * - `palette.ts` — multi-theme composition
3720
4428
  * - `color-token.ts` — standalone single-color tokens (`glaze.color`)
3721
- * - `shadow.ts` — standalone shadow factory (`glaze.shadow`)
4429
+ * - `lighting.ts` — shadow / glow solver (`glaze.shadow`, `glaze.glow`)
3722
4430
  * - `formatters.ts` — variant → string (`glaze.format`)
3723
4431
  * - `config.ts` — global config singleton
3724
4432
  * - `serialize.ts` — authoring export type guards / version checks
@@ -3732,18 +4440,28 @@ function createPalette(themes, paletteOptions) {
3732
4440
  * the theme still reacts to later `configure()` calls for fields it
3733
4441
  * didn't override.
3734
4442
  *
4443
+ * The object form also accepts `darkHue` / `darkSaturation` — a separate
4444
+ * seed pair for the dark and dark-high-contrast schemes. Both default to
4445
+ * their light counterparts, and an explicit `darkSaturation` opts the theme
4446
+ * out of the global `darkDesaturation` reduction.
4447
+ *
3735
4448
  * @example
3736
4449
  * ```ts
3737
4450
  * const primary = glaze(280, 80);
3738
4451
  * // or shorthand:
3739
4452
  * const primary = glaze({ hue: 280, saturation: 80 });
4453
+ * // with a retuned dark seed:
4454
+ * const primary = glaze({ hue: 280, saturation: 80, darkHue: 268, darkSaturation: 65 });
3740
4455
  * // with config override:
3741
4456
  * const raw = glaze(280, 80, { lightTone: false });
3742
4457
  * ```
3743
4458
  */
3744
4459
  function glaze(hueOrOptions, saturation, config) {
3745
- if (typeof hueOrOptions === "number") return createTheme(hueOrOptions, saturation ?? 100, void 0, config);
3746
- return createTheme(hueOrOptions.hue, hueOrOptions.saturation, void 0, config);
4460
+ if (typeof hueOrOptions === "number") return createTheme({
4461
+ hue: hueOrOptions,
4462
+ saturation: saturation ?? 100
4463
+ }, void 0, config);
4464
+ return createTheme(hueOrOptions, void 0, config);
3747
4465
  }
3748
4466
  /** Configure global glaze settings. */
3749
4467
  glaze.configure = function configure$1(config) {
@@ -3777,8 +4495,8 @@ glaze.from = glaze.themeFrom;
3777
4495
  * **arg2 — config override** (optional, all shapes):
3778
4496
  * Overrides the resolve-relevant global config fields for this token.
3779
4497
  * Fields that are omitted fall through to the live global config at
3780
- * create time (and are snapshotted). Pass `false` for a tone window
3781
- * to disable clamping entirely.
4498
+ * resolve time. Pass `false` for a tone window to disable clamping
4499
+ * entirely. `pastel` is instance-only (not set via `configure()`).
3782
4500
  *
3783
4501
  * ```ts
3784
4502
  * // Bare string — no overrides
@@ -3797,8 +4515,8 @@ glaze.from = glaze.themeFrom;
3797
4515
  *
3798
4516
  * Defaults: every form defaults to `mode: 'auto'`. Value-shorthand forms
3799
4517
  * (bare strings and value objects) preserve light tone exactly
3800
- * (`lightTone: false` internally). Structured form snapshots both
3801
- * tone windows from `globalConfig` at create time.
4518
+ * (`lightTone: false` locally). Structured form falls through to the live
4519
+ * global tone windows for omitted fields.
3802
4520
  *
3803
4521
  * Relative `tone: '+N'` and `contrast` anchor to the literal seed by
3804
4522
  * default; when `base` is set they anchor to the base's resolved variant
@@ -3814,25 +4532,14 @@ glaze.color = function color(input, config) {
3814
4532
  if ("hue" in obj) return createColorToken(input, config);
3815
4533
  return createColorTokenFromValue(input, void 0, config);
3816
4534
  };
3817
- /**
3818
- * Compute a shadow color from a bg/fg pair and intensity.
3819
- *
3820
- * Both `bg` and `fg` accept any `GlazeColorValue` form: hex (`#rgb` /
3821
- * `#rrggbb` / `#rrggbbaa`), `rgb()` / `hsl()` / `okhsl()` / `oklch()`
3822
- * strings, or `{ r, g, b }` / `{ h, s, l }` / `{ l, c, h }` objects.
3823
- */
3824
- glaze.shadow = function shadow(input) {
4535
+ /** Shared body of `glaze.shadow()` / `glaze.glow()`. */
4536
+ function standaloneLighting(kind, input) {
3825
4537
  const bg = extractOkhslFromValue(input.bg);
3826
4538
  const fg = input.fg ? extractOkhslFromValue(input.fg) : void 0;
3827
4539
  const cfg = getConfig();
3828
- const tuning = resolveShadowTuning(input.tuning, cfg.shadowTuning);
3829
- const result = computeShadow({
3830
- ...bg,
3831
- alpha: 1
3832
- }, fg ? {
3833
- ...fg,
3834
- alpha: 1
3835
- } : void 0, input.intensity, tuning);
4540
+ const tuning = resolveLightingTuning(input.tuning, kind === "shadow" ? cfg.shadowTuning : cfg.glowTuning);
4541
+ const result = computeLighting(kind, bg, fg, input.intensity, tuning, false);
4542
+ warnLightingUnreachable(kind, void 0, void 0, result.step, result.reached);
3836
4543
  const { h, s, t } = okhslToOkhst({
3837
4544
  h: result.h,
3838
4545
  s: result.s,
@@ -3844,6 +4551,27 @@ glaze.shadow = function shadow(input) {
3844
4551
  t,
3845
4552
  alpha: result.alpha
3846
4553
  };
4554
+ }
4555
+ /**
4556
+ * Compute a shadow over a surface: a translucent pigment whose opacity lands
4557
+ * `bg` exactly `intensity` tones darker once the browser composites it. The
4558
+ * optional object `fg` scales the step (a darker object casts a deeper
4559
+ * shadow).
4560
+ *
4561
+ * Both `bg` and `fg` accept any `GlazeColorValue` form: hex (`#rgb` /
4562
+ * `#rrggbb` / `#rrggbbaa`), `rgb()` / `hsl()` / `okhsl()` / `oklch()`
4563
+ * strings, or `{ r, g, b }` / `{ h, s, l }` / `{ l, c, h }` objects.
4564
+ */
4565
+ glaze.shadow = function shadow(input) {
4566
+ return standaloneLighting("shadow", input);
4567
+ };
4568
+ /**
4569
+ * Compute a glow over a surface — the mirror of `glaze.shadow()`: the
4570
+ * composite lands `bg` exactly `intensity` tones lighter, and a lighter
4571
+ * object `fg` glows stronger. Accepts the same inputs.
4572
+ */
4573
+ glaze.glow = function glow(input) {
4574
+ return standaloneLighting("glow", input);
3847
4575
  };
3848
4576
  /** Format a resolved color variant as a CSS string. */
3849
4577
  glaze.format = function format(variant, colorFormat, pastel) {
@@ -3857,7 +4585,10 @@ glaze.fromHex = function fromHex(hex) {
3857
4585
  const rgb = parseHex(hex);
3858
4586
  if (!rgb) throw new Error(`glaze: invalid hex color "${hex}".`);
3859
4587
  const [h, s] = srgbToOkhsl(rgb);
3860
- return createTheme(h, s * 100);
4588
+ return createTheme({
4589
+ hue: h,
4590
+ saturation: s * 100
4591
+ });
3861
4592
  };
3862
4593
  /**
3863
4594
  * Create a theme from RGB values (0–255).
@@ -3869,15 +4600,18 @@ glaze.fromRgb = function fromRgb(r, g, b) {
3869
4600
  g / 255,
3870
4601
  b / 255
3871
4602
  ]);
3872
- return createTheme(h, s * 100);
4603
+ return createTheme({
4604
+ hue: h,
4605
+ saturation: s * 100
4606
+ });
3873
4607
  };
3874
4608
  /**
3875
4609
  * Rehydrate a `glaze.color()` token from a `.export()` snapshot.
3876
4610
  *
3877
4611
  * The snapshot is a plain JSON-safe object containing the original
3878
4612
  * input value, overrides (with any `base` token recursively serialized),
3879
- * and the effective config snapshot. The reconstructed token is identical
3880
- * in behavior to the original at the time of export.
4613
+ * and the effective config freeze from export time. The reconstructed
4614
+ * token pins that freeze as its local override.
3881
4615
  *
3882
4616
  * @example
3883
4617
  * ```ts
@@ -3951,6 +4685,7 @@ exports.parseHex = parseHex;
3951
4685
  exports.parseHexAlpha = parseHexAlpha;
3952
4686
  exports.relativeLuminanceFromLinearRgb = relativeLuminanceFromLinearRgb;
3953
4687
  exports.resolveApcaTarget = resolveApcaTarget;
4688
+ exports.resolveContrastForLevel = resolveContrastForLevel;
3954
4689
  exports.resolveContrastForMode = resolveContrastForMode;
3955
4690
  exports.resolveMinContrast = resolveMinContrast;
3956
4691
  exports.roleToPolarity = roleToPolarity;