@oxog/pigment 1.0.2 → 1.1.1

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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @oxog/pigment - Zero-dependency terminal styling
2
+ * @oxog/pigment - Terminal styling
3
3
  * MIT License - https://pigment.oxog.dev
4
4
  */
5
5
  "use strict";
@@ -329,6 +329,12 @@ var PigmentError = class _PigmentError extends Error {
329
329
  Error.captureStackTrace(this, _PigmentError);
330
330
  }
331
331
  };
332
+ var PluginError = class extends PigmentError {
333
+ constructor(pluginName, message) {
334
+ super(`[${pluginName}] ${message}`, "PLUGIN_ERROR");
335
+ this.name = "PluginError";
336
+ }
337
+ };
332
338
  var ColorError = class extends PigmentError {
333
339
  constructor(message) {
334
340
  super(message, "COLOR_ERROR");
@@ -382,11 +388,11 @@ function trueColorPlugin() {
382
388
  k.emit("color:rgb", { ...rgb, background });
383
389
  });
384
390
  k.on("color:hsl", (data) => {
385
- const { h, s, l, background } = data;
391
+ const { h: h2, s, l, background } = data;
386
392
  if (!utils?.hslToRgb) {
387
393
  throw new Error("hslToRgb utility not available");
388
394
  }
389
- const rgb = utils.hslToRgb(h, s, l);
395
+ const rgb = utils.hslToRgb(h2, s, l);
390
396
  k.emit("color:rgb", { ...rgb, background });
391
397
  });
392
398
  }
@@ -464,71 +470,45 @@ function detectColorSupport(overrideLevel) {
464
470
  };
465
471
  return cachedColorSupport;
466
472
  }
467
- if (process.env.NO_COLOR) {
468
- cachedColorSupport = {
469
- level: 0,
470
- hasBasic: false,
471
- has256: false,
472
- has16m: false
473
- };
473
+ const env = process.env;
474
+ const forced = parseForceColor(env.FORCE_COLOR);
475
+ if (forced !== void 0) {
476
+ cachedColorSupport = toColorSupport(forced);
474
477
  return cachedColorSupport;
475
478
  }
476
- if (process.env.FORCE_COLOR) {
477
- const level = parseInt(process.env.FORCE_COLOR, 10);
478
- const clampedLevel = Math.max(0, Math.min(3, level));
479
- cachedColorSupport = {
480
- level: clampedLevel,
481
- hasBasic: clampedLevel >= 1,
482
- has256: clampedLevel >= 2,
483
- has16m: clampedLevel >= 3
484
- };
479
+ if (env.NO_COLOR) {
480
+ cachedColorSupport = toColorSupport(0);
485
481
  return cachedColorSupport;
486
482
  }
487
- if (!hasTTY() && !process.env.CI) {
488
- cachedColorSupport = {
489
- level: 0,
490
- hasBasic: false,
491
- has256: false,
492
- has16m: false
493
- };
483
+ if (!hasTTY() && !env.CI || env.TERM === "dumb") {
484
+ cachedColorSupport = toColorSupport(0);
494
485
  return cachedColorSupport;
495
486
  }
496
- const term = process.env.TERM ?? "";
497
- if (term.includes("truecolor") || term.includes("24bit")) {
498
- cachedColorSupport = {
499
- level: 3,
500
- hasBasic: true,
501
- has256: true,
502
- has16m: true
503
- };
487
+ const term = env.TERM ?? "";
488
+ const colorTerm = (env.COLORTERM ?? "").toLowerCase();
489
+ if (colorTerm === "truecolor" || colorTerm === "24bit" || term.includes("truecolor") || term.includes("24bit")) {
490
+ cachedColorSupport = toColorSupport(3);
504
491
  return cachedColorSupport;
505
492
  }
506
493
  if (term.includes("256color")) {
507
- cachedColorSupport = {
508
- level: 2,
509
- hasBasic: true,
510
- has256: true,
511
- has16m: false
512
- };
513
- return cachedColorSupport;
514
- }
515
- if (process.env.CI) {
516
- cachedColorSupport = {
517
- level: 1,
518
- hasBasic: true,
519
- has256: false,
520
- has16m: false
521
- };
494
+ cachedColorSupport = toColorSupport(2);
522
495
  return cachedColorSupport;
523
496
  }
524
- cachedColorSupport = {
525
- level: 1,
526
- hasBasic: true,
527
- has256: false,
528
- has16m: false
529
- };
497
+ cachedColorSupport = toColorSupport(1);
530
498
  return cachedColorSupport;
531
499
  }
500
+ function parseForceColor(value) {
501
+ if (value === void 0) return void 0;
502
+ const normalized = value.trim().toLowerCase();
503
+ if (normalized === "" || normalized === "true") return 1;
504
+ if (normalized === "false") return 0;
505
+ const level = Number.parseInt(normalized, 10);
506
+ if (Number.isNaN(level)) return 1;
507
+ return Math.max(0, Math.min(3, level));
508
+ }
509
+ function toColorSupport(level) {
510
+ return { level, hasBasic: level >= 1, has256: level >= 2, has16m: level >= 3 };
511
+ }
532
512
 
533
513
  // src/plugins/core/environment.ts
534
514
  function environmentPlugin() {
@@ -543,7 +523,8 @@ function environmentPlugin() {
543
523
  k.updateContext({
544
524
  environment: {
545
525
  isCI: ci,
546
- noColor: process.env.NO_COLOR !== void 0,
526
+ // NO_COLOR only counts when non-empty (no-color.org)
527
+ noColor: Boolean(process.env.NO_COLOR),
547
528
  forceColor: process.env.FORCE_COLOR !== void 0,
548
529
  term: process.env.TERM ?? ""
549
530
  }
@@ -552,13 +533,13 @@ function environmentPlugin() {
552
533
  k.on("environment:check", () => {
553
534
  const ctx = k.getContext();
554
535
  const env = ctx.environment;
536
+ if (env?.forceColor) {
537
+ const level = parseForceColor(process.env.FORCE_COLOR) ?? 1;
538
+ return { level, enabled: level > 0 };
539
+ }
555
540
  if (env?.noColor) {
556
541
  return { level: 0, enabled: false };
557
542
  }
558
- if (env?.forceColor) {
559
- const level = parseInt(process.env.FORCE_COLOR ?? "0", 10);
560
- return { level: Math.max(0, Math.min(3, level)), enabled: true };
561
- }
562
543
  if (ci) {
563
544
  return { level: 1, enabled: colorSupport.hasBasic };
564
545
  }
@@ -583,7 +564,7 @@ function environmentPlugin() {
583
564
  function hexToRgb(hex) {
584
565
  const hexString = hex.trim().replace(/^#/, "");
585
566
  if (hexString.length === 3) {
586
- const expanded = hexString.split("").map((c) => c + c).join("");
567
+ const expanded = hexString.split("").map((c2) => c2 + c2).join("");
587
568
  return parseExpandedHex(expanded);
588
569
  }
589
570
  if (hexString.length === 6) {
@@ -602,8 +583,8 @@ function parseExpandedHex(hex) {
602
583
  }
603
584
 
604
585
  // src/utils/hsl-to-rgb.ts
605
- function hslToRgb(h, s, l) {
606
- const hNormalized = h / 360;
586
+ function hslToRgb(h2, s, l) {
587
+ const hNormalized = h2 / 360;
607
588
  const sNormalized = s / 100;
608
589
  const lNormalized = l / 100;
609
590
  let r;
@@ -633,7 +614,260 @@ function hslToRgb(h, s, l) {
633
614
  };
634
615
  }
635
616
 
617
+ // src/utils/rgb-to-ansi256.ts
618
+ function rgbToAnsi256(r, g, b) {
619
+ const clampedR = Math.max(0, Math.min(255, r));
620
+ const clampedG = Math.max(0, Math.min(255, g));
621
+ const clampedB = Math.max(0, Math.min(255, b));
622
+ if (clampedR === clampedG && clampedG === clampedB) {
623
+ if (clampedR < 8) {
624
+ return 16;
625
+ }
626
+ if (clampedR > 248) {
627
+ return 231;
628
+ }
629
+ return Math.round((clampedR - 8) / 247 * 24) + 232;
630
+ }
631
+ return Math.round(clampedR / 51) * 36 + Math.round(clampedG / 51) * 6 + Math.round(clampedB / 51) + 16;
632
+ }
633
+
634
+ // src/core/ansi.ts
635
+ function generateModifierCode(name) {
636
+ const modifier = ANSI_MODIFIERS[name];
637
+ if (!modifier) {
638
+ throw new StyleError(`Unknown modifier: ${name}`);
639
+ }
640
+ return {
641
+ name,
642
+ code: -1,
643
+ open: modifier.open,
644
+ close: modifier.close,
645
+ type: "modifier"
646
+ };
647
+ }
648
+ function generateColorCode(name, background = false) {
649
+ let normalizedName = name;
650
+ const lowerName = name.toLowerCase();
651
+ if (lowerName === "gray" || lowerName === "grey") {
652
+ normalizedName = "blackBright";
653
+ } else if (lowerName === "bggray" || lowerName === "bggrey") {
654
+ normalizedName = "bgBlackBright";
655
+ }
656
+ const foregroundColors = { ...ANSI_FOREGROUND_COLORS, ...ANSI_FOREGROUND_BRIGHT_COLORS };
657
+ const backgroundColors = { ...ANSI_BACKGROUND_COLORS, ...ANSI_BACKGROUND_BRIGHT_COLORS };
658
+ let lookupName = normalizedName;
659
+ if (background && !normalizedName.startsWith("bg")) {
660
+ lookupName = "bg" + normalizedName.charAt(0).toUpperCase() + normalizedName.slice(1);
661
+ }
662
+ const allColors = background ? backgroundColors : foregroundColors;
663
+ const code = allColors[lookupName];
664
+ if (code === void 0) {
665
+ throw new StyleError(`Unknown color: ${name}`);
666
+ }
667
+ const closeCode = background ? 49 : 39;
668
+ return {
669
+ name,
670
+ code,
671
+ open: `\x1B[${code}m`,
672
+ close: `\x1B[${closeCode}m`,
673
+ type: "color",
674
+ background
675
+ };
676
+ }
677
+ function generateAnsi256Code(code, background = false) {
678
+ if (code < 0 || code > 255) {
679
+ throw new StyleError(`ANSI 256 code must be between 0 and 255, got ${code}`);
680
+ }
681
+ const prefix = background ? 48 : 38;
682
+ const closeCode = background ? 49 : 39;
683
+ return {
684
+ name: `ansi256(${code})`,
685
+ code,
686
+ open: `\x1B[${prefix};5;${code}m`,
687
+ close: `\x1B[${closeCode}m`,
688
+ type: "color",
689
+ background
690
+ };
691
+ }
692
+ function generateRgbCode(r, g, b, background = false) {
693
+ if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
694
+ throw new StyleError(`RGB values must be between 0 and 255, got (${r}, ${g}, ${b})`);
695
+ }
696
+ const prefix = background ? 48 : 38;
697
+ const closeCode = background ? 49 : 39;
698
+ return {
699
+ name: `rgb(${r}, ${g}, ${b})`,
700
+ code: -1,
701
+ open: `\x1B[${prefix};2;${r};${g};${b}m`,
702
+ close: `\x1B[${closeCode}m`,
703
+ type: "color",
704
+ background
705
+ };
706
+ }
707
+ function ansi256ToAnsi16(code) {
708
+ if (code < 8) {
709
+ return 30 + code;
710
+ }
711
+ if (code < 16) {
712
+ return 90 + (code - 8);
713
+ }
714
+ let red;
715
+ let green;
716
+ let blue;
717
+ if (code >= 232) {
718
+ red = ((code - 232) * 10 + 8) / 255;
719
+ green = red;
720
+ blue = red;
721
+ } else {
722
+ const index = code - 16;
723
+ const remainder = index % 36;
724
+ red = Math.floor(index / 36) / 5;
725
+ green = Math.floor(remainder / 6) / 5;
726
+ blue = remainder % 6 / 5;
727
+ }
728
+ const value = Math.max(red, green, blue) * 2;
729
+ if (value === 0) {
730
+ return 30;
731
+ }
732
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
733
+ if (value === 2) {
734
+ result += 60;
735
+ }
736
+ return result;
737
+ }
738
+ function effectiveLevel(level) {
739
+ return level ?? 3;
740
+ }
741
+ function ansi16Style(name, paletteCode, background) {
742
+ const code = ansi256ToAnsi16(paletteCode) + (background ? 10 : 0);
743
+ return {
744
+ name,
745
+ code,
746
+ open: `\x1B[${code}m`,
747
+ close: `\x1B[${background ? 49 : 39}m`,
748
+ type: "color",
749
+ background
750
+ };
751
+ }
752
+ function generateAnsi256CodeForLevel(code, background, level) {
753
+ const style = generateAnsi256Code(code, background);
754
+ if (effectiveLevel(level) >= 2) {
755
+ return style;
756
+ }
757
+ return ansi16Style(style.name, code, background);
758
+ }
759
+ function generateRgbCodeForLevel(r, g, b, background, level) {
760
+ const style = generateRgbCode(r, g, b, background);
761
+ const effective = effectiveLevel(level);
762
+ if (effective >= 3) {
763
+ return style;
764
+ }
765
+ const paletteCode = rgbToAnsi256(r, g, b);
766
+ if (effective === 2) {
767
+ return { ...generateAnsi256Code(paletteCode, background), name: style.name };
768
+ }
769
+ return ansi16Style(style.name, paletteCode, background);
770
+ }
771
+ function paintRgb(text, rgb, background, level) {
772
+ if (level === 0 || text === "") {
773
+ return text;
774
+ }
775
+ const style = generateRgbCodeForLevel(rgb.r, rgb.g, rgb.b, background, level);
776
+ return `${style.open}${text}${style.close}`;
777
+ }
778
+
779
+ // src/core/plugin-api.ts
780
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@oxog/pigment.plugin-api");
781
+ var globalRegistry = globalThis;
782
+ var registry = globalRegistry[REGISTRY_KEY] ??= { apis: /* @__PURE__ */ new WeakMap(), roots: /* @__PURE__ */ new WeakMap() };
783
+ var { apis, roots } = registry;
784
+ var PLUGIN_API_PROVIDERS = {
785
+ gradient: "gradientPlugin",
786
+ rainbow: "gradientPlugin",
787
+ theme: "themePlugin",
788
+ success: "semanticPlugin",
789
+ error: "semanticPlugin",
790
+ warning: "semanticPlugin",
791
+ info: "semanticPlugin",
792
+ debug: "semanticPlugin",
793
+ box: "boxPlugin",
794
+ template: "templatePlugin"
795
+ };
796
+ function registerPluginApi(kernel, name, value) {
797
+ let api = apis.get(kernel);
798
+ if (!api) {
799
+ api = /* @__PURE__ */ new Map();
800
+ apis.set(kernel, api);
801
+ }
802
+ api.set(name, value);
803
+ }
804
+ function getPluginApi(kernel, name) {
805
+ return apis.get(kernel)?.get(name);
806
+ }
807
+ function registerRoot(kernel, root) {
808
+ roots.set(kernel, root);
809
+ }
810
+ function getRoot(kernel) {
811
+ return roots.get(kernel);
812
+ }
813
+ function missingPluginApi(name) {
814
+ const plugin = PLUGIN_API_PROVIDERS[name];
815
+ const fail = () => {
816
+ throw new PluginError(
817
+ plugin,
818
+ `pigment.${name} needs ${plugin}(): createPigment({ plugins: [${plugin}()] }) or pigment.use(${plugin}())`
819
+ );
820
+ };
821
+ if (name === "theme") {
822
+ return {
823
+ keyword: fail,
824
+ string: fail,
825
+ number: fail,
826
+ comment: fail,
827
+ error: fail,
828
+ success: fail,
829
+ warning: fail,
830
+ info: fail
831
+ };
832
+ }
833
+ return fail;
834
+ }
835
+ function installPlugin(kernel, plugin) {
836
+ kernel.use(plugin);
837
+ if (plugin.onInit) {
838
+ Promise.resolve().then(() => plugin.onInit?.(kernel.getContext())).catch(() => {
839
+ });
840
+ }
841
+ }
842
+
636
843
  // src/plugins/optional/gradient.ts
844
+ function toRgb(color) {
845
+ if (typeof color !== "string") {
846
+ const [r, g, b] = color;
847
+ return { r, g, b };
848
+ }
849
+ return color.startsWith("rgb(") ? parseRgb(color) : hexToRgb(color);
850
+ }
851
+ function paintGradient(text, startRgb, endRgb, steps, level) {
852
+ if (text.length === 0) {
853
+ return text;
854
+ }
855
+ const colors = interpolateColors(startRgb, endRgb, text.length, Math.max(2, steps));
856
+ let result = "";
857
+ for (let i = 0; i < text.length; i++) {
858
+ const colorIndex = text.length === 1 ? 0 : Math.floor(i / (text.length - 1) * (colors.length - 1));
859
+ result += paintRgb(text[i], colors[colorIndex], false, level);
860
+ }
861
+ return result;
862
+ }
863
+ function paintRainbow(text, steps, level) {
864
+ const colors = generateRainbowColors(text.length, Math.max(1, steps));
865
+ let result = "";
866
+ for (let i = 0; i < text.length; i++) {
867
+ result += paintRgb(text[i], colors[i % colors.length], false, level);
868
+ }
869
+ return result;
870
+ }
637
871
  function gradientPlugin(options) {
638
872
  const steps = options?.steps ?? 10;
639
873
  return {
@@ -647,6 +881,15 @@ function gradientPlugin(options) {
647
881
  enabled: true
648
882
  }
649
883
  });
884
+ registerPluginApi(kernel, "gradient", (start, end) => {
885
+ const startRgb = toRgb(start);
886
+ const endRgb = toRgb(end);
887
+ if (!startRgb || !endRgb) {
888
+ throw new ColorError(`Invalid gradient color: ${String(startRgb ? end : start)}`);
889
+ }
890
+ return (text) => paintGradient(String(text), startRgb, endRgb, steps, k.getContext().level);
891
+ });
892
+ registerPluginApi(kernel, "rainbow", (text) => paintRainbow(String(text), steps, k.getContext().level));
650
893
  k.on("style:gradient", (data) => {
651
894
  const { start, end, text, steps: gradientSteps = steps } = data;
652
895
  const startRgb = start.startsWith("#") ? hexToRgb(start) : start.startsWith("rgb(") ? parseRgb(start) : hexToRgb(start);
@@ -717,6 +960,7 @@ function generateRainbowColors(length, steps) {
717
960
  }
718
961
 
719
962
  // src/plugins/optional/theme.ts
963
+ var THEME_COLOR_TYPES = ["keyword", "string", "number", "comment", "error", "success", "warning", "info"];
720
964
  function themePlugin(options) {
721
965
  const preset = options?.preset ?? "monokai";
722
966
  const custom = options?.custom ?? {};
@@ -736,6 +980,17 @@ function themePlugin(options) {
736
980
  enabled: true
737
981
  }
738
982
  });
983
+ const api = {};
984
+ for (const type of THEME_COLOR_TYPES) {
985
+ const color = theme[type];
986
+ api[type] = (text) => {
987
+ if (!color) {
988
+ throw new Error(`Unknown theme color type: ${type}`);
989
+ }
990
+ return paintRgb(String(text), hexToRgb(color), false, k.getContext().level);
991
+ };
992
+ }
993
+ registerPluginApi(kernel, "theme", api);
739
994
  k.on("style:theme", (data) => {
740
995
  const { type, text } = data;
741
996
  const color = theme[type];
@@ -805,6 +1060,10 @@ function semanticPlugin(options) {
805
1060
  if (!hexToRgb2) {
806
1061
  throw new Error("hexToRgb utility not available");
807
1062
  }
1063
+ for (const [name, color] of Object.entries(defaultColors)) {
1064
+ const rgb = hexToRgb2(color);
1065
+ registerPluginApi(kernel, name, (text) => paintRgb(String(text), rgb, false, k.getContext().level));
1066
+ }
808
1067
  k.on("style:success", (data) => {
809
1068
  const { r, g, b } = hexToRgb2(defaultColors.success);
810
1069
  return `\x1B[38;2;${r};${g};${b}m${data.text}\x1B[39m`;
@@ -846,9 +1105,12 @@ function boxPlugin(options) {
846
1105
  borders: BOX_BORDERS
847
1106
  }
848
1107
  });
849
- k.on("style:box", (data) => {
850
- const { text, border: boxBorder = border, padding: boxPadding = padding, bgColor } = data;
1108
+ const draw = (text, opts = {}) => {
1109
+ const { border: boxBorder = border, padding: boxPadding = padding, bgColor } = opts;
851
1110
  const chars = BOX_BORDERS[boxBorder];
1111
+ if (!chars) {
1112
+ throw new StyleError(`Unknown box border: ${String(boxBorder)}`);
1113
+ }
852
1114
  const lines = text.split("\n");
853
1115
  const width = Math.max(...lines.map((l) => l.length)) + boxPadding * 2;
854
1116
  const pad = " ".repeat(boxPadding);
@@ -860,149 +1122,18 @@ function boxPlugin(options) {
860
1122
  const bottom = `${chars.bl}${chars.h.repeat(width)}${chars.br}`;
861
1123
  const result = [top, ...middle, bottom].join("\n");
862
1124
  if (bgColor) {
863
- const ctx = k.getContext();
864
- const hexToRgb2 = ctx.utils?.hexToRgb;
865
- if (!hexToRgb2) {
866
- throw new Error("hexToRgb utility not available");
867
- }
868
- const { r, g, b } = hexToRgb2(bgColor);
869
- return `\x1B[48;2;${r};${g};${b}m${result}\x1B[49m`;
870
- }
871
- return result;
872
- });
873
- }
874
- };
875
- }
876
-
877
- // src/plugins/optional/template.ts
878
- function templatePlugin() {
879
- return {
880
- name: "template",
881
- version: "1.0.0",
882
- install(kernel) {
883
- const k = kernel;
884
- k.updateContext({
885
- template: {
886
- enabled: true
887
- }
888
- });
889
- k.on("style:template", (data) => {
890
- const { strings, values } = data;
891
- let result = "";
892
- for (let i = 0; i < strings.length; i++) {
893
- result += strings[i];
894
- if (i < values.length) {
895
- const value = values[i];
896
- if (typeof value === "string") {
897
- const match = value.match(/^\{(.+)\}(.*)$/);
898
- if (match) {
899
- const [, styleExpression, text] = match;
900
- result += parseStyleExpression(styleExpression, text, k);
901
- } else {
902
- result += value;
903
- }
904
- } else {
905
- result += String(value);
906
- }
907
- }
1125
+ return paintRgb(result, hexToRgb(bgColor), true, k.getContext().level);
908
1126
  }
909
1127
  return result;
1128
+ };
1129
+ registerPluginApi(kernel, "box", (text, opts) => draw(String(text), opts));
1130
+ k.on("style:box", (data) => {
1131
+ const { text, ...opts } = data;
1132
+ return draw(text, opts);
910
1133
  });
911
1134
  }
912
1135
  };
913
1136
  }
914
- function parseStyleExpression(expression, text, kernel) {
915
- const parts = expression.split(".");
916
- let current = kernel.getContext();
917
- for (const part of parts) {
918
- if (current && typeof current === "object" && part in current) {
919
- current = current[part];
920
- } else {
921
- return text;
922
- }
923
- }
924
- if (typeof current === "function") {
925
- return current(text);
926
- }
927
- return text;
928
- }
929
-
930
- // src/core/factory.ts
931
- var import_plugin = require("@oxog/plugin");
932
-
933
- // src/core/ansi.ts
934
- function generateModifierCode(name) {
935
- const modifier = ANSI_MODIFIERS[name];
936
- if (!modifier) {
937
- throw new StyleError(`Unknown modifier: ${name}`);
938
- }
939
- return {
940
- name,
941
- code: -1,
942
- open: modifier.open,
943
- close: modifier.close,
944
- type: "modifier"
945
- };
946
- }
947
- function generateColorCode(name, background = false) {
948
- let normalizedName = name;
949
- const lowerName = name.toLowerCase();
950
- if (lowerName === "gray" || lowerName === "grey") {
951
- normalizedName = "blackBright";
952
- } else if (lowerName === "bggray" || lowerName === "bggrey") {
953
- normalizedName = "bgBlackBright";
954
- }
955
- const foregroundColors = { ...ANSI_FOREGROUND_COLORS, ...ANSI_FOREGROUND_BRIGHT_COLORS };
956
- const backgroundColors = { ...ANSI_BACKGROUND_COLORS, ...ANSI_BACKGROUND_BRIGHT_COLORS };
957
- let lookupName = normalizedName;
958
- if (background && !normalizedName.startsWith("bg")) {
959
- lookupName = "bg" + normalizedName.charAt(0).toUpperCase() + normalizedName.slice(1);
960
- }
961
- const allColors = background ? backgroundColors : foregroundColors;
962
- const code = allColors[lookupName];
963
- if (code === void 0) {
964
- throw new StyleError(`Unknown color: ${name}`);
965
- }
966
- const closeCode = background ? 49 : 39;
967
- return {
968
- name,
969
- code,
970
- open: `\x1B[${code}m`,
971
- close: `\x1B[${closeCode}m`,
972
- type: "color",
973
- background
974
- };
975
- }
976
- function generateAnsi256Code(code, background = false) {
977
- if (code < 0 || code > 255) {
978
- throw new StyleError(`ANSI 256 code must be between 0 and 255, got ${code}`);
979
- }
980
- const prefix = background ? 48 : 38;
981
- const closeCode = background ? 49 : 39;
982
- return {
983
- name: `ansi256(${code})`,
984
- code,
985
- open: `\x1B[${prefix};5;${code}m`,
986
- close: `\x1B[${closeCode}m`,
987
- type: "color",
988
- background
989
- };
990
- }
991
- function generateRgbCode(r, g, b, background = false) {
992
- if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
993
- throw new StyleError(`RGB values must be between 0 and 255, got (${r}, ${g}, ${b})`);
994
- }
995
- const prefix = background ? 48 : 38;
996
- const closeCode = background ? 49 : 39;
997
- return {
998
- name: `rgb(${r}, ${g}, ${b})`,
999
- code: -1,
1000
- open: `\x1B[${prefix};2;${r};${g};${b}m`,
1001
- close: `\x1B[${closeCode}m`,
1002
- type: "color",
1003
- background
1004
- };
1005
- }
1006
1137
 
1007
1138
  // src/core/proxy.ts
1008
1139
  var proxyCache = /* @__PURE__ */ new WeakMap();
@@ -1016,28 +1147,28 @@ function createProxyPigment(kernel, styles = []) {
1016
1147
  if (prop === "supportsColor") {
1017
1148
  return ctx.colorSupport;
1018
1149
  }
1019
- if (MODIFIER_NAMES.includes(prop)) {
1150
+ if (MODIFIER_NAMES.some((name) => name === prop)) {
1020
1151
  const modifierStyle = generateModifierCode(prop);
1021
1152
  return createProxyPigment(kernel, [...styles, modifierStyle]);
1022
1153
  }
1023
- if (COLOR_NAMES.includes(prop) || BACKGROUND_COLOR_NAMES.includes(prop)) {
1154
+ if (COLOR_NAMES.some((name) => name === prop) || BACKGROUND_COLOR_NAMES.some((name) => name === prop)) {
1024
1155
  const background = prop.startsWith("bg");
1025
1156
  const colorName = background ? prop.slice(2) : prop;
1026
1157
  const colorStyle = generateColorCode(colorName, background);
1027
1158
  return createProxyPigment(kernel, [...styles, colorStyle]);
1028
1159
  }
1029
- if (EXTENDED_COLOR_METHODS.includes(prop)) {
1160
+ if (EXTENDED_COLOR_METHODS.some((name) => name === prop)) {
1030
1161
  if (prop === "ansi256" || prop === "bgAnsi256") {
1031
1162
  return (code) => {
1032
1163
  const background = prop === "bgAnsi256";
1033
- const ansi256Style = generateAnsi256Code(code, background);
1164
+ const ansi256Style = generateAnsi256CodeForLevel(code, background, ctx.level);
1034
1165
  return createProxyPigment(kernel, [...styles, ansi256Style]);
1035
1166
  };
1036
1167
  }
1037
1168
  if (prop === "rgb" || prop === "bgRgb") {
1038
1169
  return (r, g, b) => {
1039
1170
  const background = prop === "bgRgb";
1040
- const rgbStyle = generateRgbCode(r, g, b, background);
1171
+ const rgbStyle = generateRgbCodeForLevel(r, g, b, background, ctx.level);
1041
1172
  return createProxyPigment(kernel, [...styles, rgbStyle]);
1042
1173
  };
1043
1174
  }
@@ -1049,40 +1180,49 @@ function createProxyPigment(kernel, styles = []) {
1049
1180
  throw new Error("hexToRgb utility not available");
1050
1181
  }
1051
1182
  const { r, g, b } = hexToRgb2(color);
1052
- const rgbStyle = generateRgbCode(r, g, b, background);
1183
+ const rgbStyle = generateRgbCodeForLevel(r, g, b, background, ctx.level);
1053
1184
  return createProxyPigment(kernel, [...styles, rgbStyle]);
1054
1185
  };
1055
1186
  }
1056
1187
  if (prop === "hsl" || prop === "bgHsl") {
1057
- return (h, s, l) => {
1188
+ return (h2, s, l) => {
1058
1189
  const background = prop === "bgHsl";
1059
1190
  const hslToRgb2 = ctx.utils?.hslToRgb;
1060
1191
  if (!hslToRgb2) {
1061
1192
  throw new Error("hslToRgb utility not available");
1062
1193
  }
1063
- const { r, g, b } = hslToRgb2(h, s, l);
1064
- const rgbStyle = generateRgbCode(r, g, b, background);
1194
+ const { r, g, b } = hslToRgb2(h2, s, l);
1195
+ const rgbStyle = generateRgbCodeForLevel(r, g, b, background, ctx.level);
1065
1196
  return createProxyPigment(kernel, [...styles, rgbStyle]);
1066
1197
  };
1067
1198
  }
1068
1199
  }
1069
1200
  if (prop === "visible") {
1070
1201
  const colorSupport = ctx.colorSupport;
1071
- return (text) => colorSupport.level > 0 ? text : "";
1202
+ return (text) => colorSupport.level > 0 ? applyStyles(String(text), styles, ctx.level) : "";
1072
1203
  }
1073
- return target[prop];
1204
+ if (prop === "use") {
1205
+ return (plugin) => {
1206
+ installPlugin(kernel, plugin);
1207
+ return getRoot(kernel) ?? createProxyPigment(kernel);
1208
+ };
1209
+ }
1210
+ if (Object.prototype.hasOwnProperty.call(PLUGIN_API_PROVIDERS, prop)) {
1211
+ return getPluginApi(kernel, prop) ?? missingPluginApi(prop);
1212
+ }
1213
+ return Reflect.get(target, prop);
1074
1214
  },
1075
1215
  apply(_target, _thisArg, argArray) {
1076
1216
  const text = String(argArray[0] ?? "");
1077
- return applyStyles(text, styles);
1217
+ return applyStyles(text, styles, kernel.getContext().level);
1078
1218
  }
1079
1219
  };
1080
1220
  const pigment = new Proxy((() => ""), handler);
1081
1221
  proxyCache.set(pigment, pigment);
1082
1222
  return pigment;
1083
1223
  }
1084
- function applyStyles(text, styles) {
1085
- if (styles.length === 0 || text === "") {
1224
+ function applyStyles(text, styles, level) {
1225
+ if (styles.length === 0 || text === "" || level === 0) {
1086
1226
  return text;
1087
1227
  }
1088
1228
  const open = styles.map((style) => style.open).join("");
@@ -1096,10 +1236,565 @@ function applyStyles(text, styles) {
1096
1236
  return `${open}${result}${close}`;
1097
1237
  }
1098
1238
 
1239
+ // src/plugins/optional/template.ts
1240
+ var STYLE_NAMES = /* @__PURE__ */ new Set([...MODIFIER_NAMES, ...COLOR_NAMES, ...BACKGROUND_COLOR_NAMES]);
1241
+ var BLOCK = /\{([A-Za-z]\w*(?:\.[A-Za-z]\w*)*) ([^{}]*)\}/g;
1242
+ var TOKEN = /\uE000(\d+)\uE001/g;
1243
+ function renderTemplate(root, strings, values) {
1244
+ const parts = values.map((value) => String(value));
1245
+ const token = (index) => `\uE000${index}\uE001`;
1246
+ const restore = (text) => text.replace(TOKEN, (_match, index) => parts[Number(index)]);
1247
+ let source = "";
1248
+ for (let i = 0; i < strings.length; i++) {
1249
+ source += strings[i];
1250
+ if (i < values.length) {
1251
+ source += token(i);
1252
+ }
1253
+ }
1254
+ let previous;
1255
+ do {
1256
+ previous = source;
1257
+ source = source.replace(BLOCK, (_match, chain, text) => {
1258
+ let styler = root;
1259
+ for (const name of chain.split(".")) {
1260
+ if (!STYLE_NAMES.has(name)) {
1261
+ throw new StyleError(`Unknown style in template: ${name}`);
1262
+ }
1263
+ styler = styler[name];
1264
+ }
1265
+ parts.push(styler(restore(text)));
1266
+ return token(parts.length - 1);
1267
+ });
1268
+ } while (source !== previous);
1269
+ return restore(source);
1270
+ }
1271
+ function templatePlugin() {
1272
+ return {
1273
+ name: "template",
1274
+ version: "1.0.0",
1275
+ install(kernel) {
1276
+ const k = kernel;
1277
+ k.updateContext({
1278
+ template: {
1279
+ enabled: true
1280
+ }
1281
+ });
1282
+ registerPluginApi(
1283
+ kernel,
1284
+ "template",
1285
+ (strings, ...values) => renderTemplate(getRoot(kernel) ?? createProxyPigment(k), strings, values)
1286
+ );
1287
+ k.on("style:template", (data) => {
1288
+ const { strings, values } = data;
1289
+ let result = "";
1290
+ for (let i = 0; i < strings.length; i++) {
1291
+ result += strings[i];
1292
+ if (i < values.length) {
1293
+ const value = values[i];
1294
+ if (typeof value === "string") {
1295
+ const match = value.match(/^\{(.+)\}(.*)$/);
1296
+ if (match) {
1297
+ const [, styleExpression, text] = match;
1298
+ result += parseStyleExpression(styleExpression, text, k);
1299
+ } else {
1300
+ result += value;
1301
+ }
1302
+ } else {
1303
+ result += String(value);
1304
+ }
1305
+ }
1306
+ }
1307
+ return result;
1308
+ });
1309
+ }
1310
+ };
1311
+ }
1312
+ function parseStyleExpression(expression, text, kernel) {
1313
+ const parts = expression.split(".");
1314
+ let current = kernel.getContext();
1315
+ for (const part of parts) {
1316
+ if (current && typeof current === "object" && part in current) {
1317
+ current = current[part];
1318
+ } else {
1319
+ return text;
1320
+ }
1321
+ }
1322
+ if (typeof current === "function") {
1323
+ const style = current;
1324
+ return style(text);
1325
+ }
1326
+ return text;
1327
+ }
1328
+
1329
+ // node_modules/@oxog/plugin/dist/index.js
1330
+ var import_types = require("@oxog/types");
1331
+ var import_types2 = require("@oxog/types");
1332
+ var x = ((i) => (i.Created = "created", i.Initializing = "initializing", i.Ready = "ready", i.Destroying = "destroying", i.Destroyed = "destroyed", i))(x || {});
1333
+ var h = class {
1334
+ context;
1335
+ constructor(e) {
1336
+ this.context = e;
1337
+ }
1338
+ get() {
1339
+ return this.context;
1340
+ }
1341
+ update(e) {
1342
+ this.context = Object.assign(this.context, e);
1343
+ }
1344
+ deepUpdate(e) {
1345
+ let t = this.deepMerge(this.context, e);
1346
+ this.context = Object.assign(this.context, t);
1347
+ }
1348
+ deepMerge(e, t) {
1349
+ if (t === null || typeof t != "object") return t;
1350
+ if (Array.isArray(t)) return [...t];
1351
+ if (e === null || typeof e != "object" || Array.isArray(e)) return { ...t };
1352
+ let n = { ...e };
1353
+ for (let r of Object.keys(t)) {
1354
+ let i = t[r], a = n[r];
1355
+ n[r] = this.deepMerge(a, i);
1356
+ }
1357
+ return n;
1358
+ }
1359
+ };
1360
+ var u = class {
1361
+ handlers = /* @__PURE__ */ new Map();
1362
+ wildcardHandlers = new Array();
1363
+ patternHandlers = /* @__PURE__ */ new Map();
1364
+ onceWrappers = /* @__PURE__ */ new Map();
1365
+ on(e, t) {
1366
+ let n = String(e);
1367
+ this.handlers.has(n) || this.handlers.set(n, []);
1368
+ let r = this.handlers.get(n), i = t;
1369
+ return r.includes(i) || r.push(i), () => {
1370
+ let a = this.handlers.get(n);
1371
+ if (a) {
1372
+ let s = a.indexOf(i);
1373
+ s !== -1 && a.splice(s, 1);
1374
+ }
1375
+ };
1376
+ }
1377
+ once(e, t) {
1378
+ let n = t, r = String(e), i = this.onceWrappers.get(r);
1379
+ i || (i = /* @__PURE__ */ new Map(), this.onceWrappers.set(r, i));
1380
+ let a = (s) => {
1381
+ i.delete(n), this.off(e, a), t(s);
1382
+ };
1383
+ return i.set(n, a), this.on(e, a);
1384
+ }
1385
+ off(e, t) {
1386
+ let n = String(e), r = this.handlers.get(n);
1387
+ if (r) {
1388
+ let i = t, a = this.onceWrappers.get(n), s = a?.get(i), o = s || i, l = r.indexOf(o);
1389
+ l !== -1 && (r.splice(l, 1), s && a.delete(i));
1390
+ }
1391
+ }
1392
+ emit(e, t) {
1393
+ let n = String(e), r = this.handlers.get(n);
1394
+ if (r) for (let i of [...r]) try {
1395
+ i(t);
1396
+ } catch {
1397
+ }
1398
+ for (let i of [...this.wildcardHandlers]) try {
1399
+ i(n, t);
1400
+ } catch {
1401
+ }
1402
+ for (let [i, a] of this.patternHandlers) if (this.matchPattern(i, n)) for (let s of [...a]) try {
1403
+ s(n, t);
1404
+ } catch {
1405
+ }
1406
+ }
1407
+ onWildcard(e) {
1408
+ return this.wildcardHandlers.includes(e) || this.wildcardHandlers.push(e), () => {
1409
+ let t = this.wildcardHandlers.indexOf(e);
1410
+ t !== -1 && this.wildcardHandlers.splice(t, 1);
1411
+ };
1412
+ }
1413
+ onPattern(e, t) {
1414
+ this.patternHandlers.has(e) || this.patternHandlers.set(e, []);
1415
+ let n = this.patternHandlers.get(e);
1416
+ return n.includes(t) || n.push(t), () => {
1417
+ let r = this.patternHandlers.get(e);
1418
+ if (r) {
1419
+ let i = r.indexOf(t);
1420
+ i !== -1 && r.splice(i, 1);
1421
+ }
1422
+ };
1423
+ }
1424
+ clear() {
1425
+ this.handlers.clear(), this.wildcardHandlers.length = 0, this.patternHandlers.clear(), this.onceWrappers.clear();
1426
+ }
1427
+ matchPattern(e, t) {
1428
+ if (e === "*") return true;
1429
+ if (e.endsWith(":*")) {
1430
+ let n = e.slice(0, -2);
1431
+ return t.startsWith(n + ":");
1432
+ }
1433
+ return e === t;
1434
+ }
1435
+ };
1436
+ var f = class {
1437
+ graph = /* @__PURE__ */ new Map();
1438
+ addPlugin(e, t = []) {
1439
+ this.graph.set(e, [...t]);
1440
+ }
1441
+ removePlugin(e) {
1442
+ this.graph.delete(e);
1443
+ for (let t of this.graph.values()) {
1444
+ let n = t.indexOf(e);
1445
+ n !== -1 && t.splice(n, 1);
1446
+ }
1447
+ }
1448
+ validateSinglePlugin(e) {
1449
+ let t = this.graph.get(e);
1450
+ if (!t) return;
1451
+ for (let r of t) if (!this.graph.has(r)) throw new import_types.PluginError(`Missing dependency: '${r}' required by '${e}'`, e);
1452
+ let n = this.detectCycle();
1453
+ if (n && n.includes(e)) throw new import_types.PluginError(`Circular dependency detected: ${n.join(" -> ")}`, "dependency-resolver");
1454
+ }
1455
+ resolve() {
1456
+ let e = /* @__PURE__ */ new Map(), t = [], n = [], r = /* @__PURE__ */ new Map();
1457
+ for (let [s, o] of this.graph) {
1458
+ let l = o.filter((p) => this.graph.has(p));
1459
+ r.set(s, l);
1460
+ }
1461
+ for (let [s, o] of this.graph) for (let l of o) if (!this.graph.has(l)) throw new import_types.PluginError(`Missing dependency: '${l}' required by '${s}'`, s);
1462
+ for (let [s, o] of r) e.set(s, o.length), o.length === 0 && t.push(s);
1463
+ let i = /* @__PURE__ */ new Map();
1464
+ for (let [s, o] of r) for (let l of o) {
1465
+ let p = i.get(l);
1466
+ p ? p.push(s) : i.set(l, [s]);
1467
+ }
1468
+ let a = 0;
1469
+ for (; a < t.length; ) {
1470
+ let s = t[a++];
1471
+ n.push(s);
1472
+ for (let o of i.get(s) ?? []) e.set(o, e.get(o) - 1), e.get(o) === 0 && t.push(o);
1473
+ }
1474
+ if (n.length !== r.size) {
1475
+ let s = this.detectCycle();
1476
+ throw new import_types.PluginError(`Circular dependency detected: ${s.join(" -> ")}`, "dependency-resolver");
1477
+ }
1478
+ return n;
1479
+ }
1480
+ detectCycle() {
1481
+ let r = /* @__PURE__ */ new Map();
1482
+ for (let a of this.graph.keys()) r.set(a, 0);
1483
+ let i = (a, s) => {
1484
+ r.set(a, 1), s.push(a);
1485
+ for (let o of this.graph.get(a)) if (this.graph.has(o)) {
1486
+ if (r.get(o) === 1) {
1487
+ let l = s.indexOf(o);
1488
+ return [...s.slice(l), o];
1489
+ }
1490
+ if (r.get(o) === 0) {
1491
+ let l = i(o, s);
1492
+ if (l) return l;
1493
+ }
1494
+ }
1495
+ return s.pop(), r.set(a, 2), null;
1496
+ };
1497
+ for (let a of this.graph.keys()) if (r.get(a) === 0) {
1498
+ let s = i(a, []);
1499
+ if (s) return s;
1500
+ }
1501
+ return null;
1502
+ }
1503
+ getGraph() {
1504
+ let e = {};
1505
+ for (let [t, n] of this.graph) e[t] = [...n];
1506
+ return e;
1507
+ }
1508
+ clear() {
1509
+ this.graph.clear();
1510
+ }
1511
+ };
1512
+ var v = class {
1513
+ strategy;
1514
+ globalHandler;
1515
+ errors = [];
1516
+ constructor(e, t) {
1517
+ this.strategy = e, this.globalHandler = t;
1518
+ }
1519
+ getStrategy() {
1520
+ return this.strategy;
1521
+ }
1522
+ async withBoundary(e, t, n) {
1523
+ try {
1524
+ return await n();
1525
+ } catch (r) {
1526
+ let i = r instanceof Error ? r : new Error(String(r));
1527
+ throw await this.handleError(e, t, i), i;
1528
+ }
1529
+ }
1530
+ async handleError(e, t, n) {
1531
+ if (t.onError) try {
1532
+ t.onError(n);
1533
+ } catch {
1534
+ }
1535
+ if (this.globalHandler) try {
1536
+ this.globalHandler(n, e);
1537
+ } catch {
1538
+ }
1539
+ this.strategy === "collect" && this.errors.push(n);
1540
+ }
1541
+ throwIfErrors() {
1542
+ if (this.strategy === "collect" && this.errors.length > 0) {
1543
+ let e = new AggregateError(this.errors, `${this.errors.length} plugin error(s) occurred`);
1544
+ throw this.clearErrors(), e;
1545
+ }
1546
+ }
1547
+ clearErrors() {
1548
+ this.errors = [];
1549
+ }
1550
+ getErrors() {
1551
+ return Object.freeze([...this.errors]);
1552
+ }
1553
+ };
1554
+ var m = class {
1555
+ async initialize(e, t, n, r, i) {
1556
+ let a = r.getStrategy();
1557
+ for (let s of t) {
1558
+ let o = e.get(s);
1559
+ if (o && o.state !== "ready") {
1560
+ o.state = "initializing";
1561
+ try {
1562
+ await r.withBoundary(s, o.plugin, async () => {
1563
+ o.plugin.onInit && await o.plugin.onInit(n);
1564
+ }), o.state = "ready", o.initializedAt = Date.now(), i?.(s);
1565
+ } catch (l) {
1566
+ if (a === "fail-fast") throw l;
1567
+ o.state = "failed";
1568
+ }
1569
+ }
1570
+ }
1571
+ }
1572
+ async destroy(e, t, n, r) {
1573
+ let i = n.getStrategy(), a = [...t].reverse();
1574
+ for (let s of a) {
1575
+ let o = e.get(s);
1576
+ if (o) {
1577
+ o.state = "destroying";
1578
+ try {
1579
+ await n.withBoundary(s, o.plugin, async () => {
1580
+ o.plugin.onDestroy && await o.plugin.onDestroy();
1581
+ });
1582
+ } catch (l) {
1583
+ if (i === "fail-fast") throw l;
1584
+ }
1585
+ o.state = "destroyed", r?.(s);
1586
+ }
1587
+ }
1588
+ }
1589
+ };
1590
+ var c = class {
1591
+ state = "created";
1592
+ plugins = /* @__PURE__ */ new Map();
1593
+ context;
1594
+ events;
1595
+ resolver;
1596
+ errorBoundary;
1597
+ lifecycle;
1598
+ config;
1599
+ pendingInits = /* @__PURE__ */ new Map();
1600
+ emitInternal(e, t) {
1601
+ this.events.emit(e, t);
1602
+ }
1603
+ constructor(e) {
1604
+ this.config = e || {}, this.context = new h(this.config.context ?? {}), this.events = new u(), this.resolver = new f(), this.errorBoundary = new v(this.config.errorStrategy || "isolate", this.config.onError), this.lifecycle = new m();
1605
+ }
1606
+ use(e) {
1607
+ if (this.state === "destroyed") throw new import_types.PluginError("Cannot add plugins to destroyed kernel", "kernel");
1608
+ if (this.state === "initializing") throw new import_types.PluginError("Cannot add plugins while kernel is initializing. Register all plugins before calling init(), or wait until kernel is ready.", "kernel");
1609
+ if (this.plugins.has(e.name)) throw new import_types.PluginError(`Plugin '${e.name}' is already registered`, "kernel");
1610
+ let t = { plugin: e, state: "registered" };
1611
+ this.plugins.set(e.name, t), this.resolver.addPlugin(e.name, [...e.dependencies || []]);
1612
+ try {
1613
+ if (this.state === "ready" && this.resolver.validateSinglePlugin(e.name), e.install(this), this.emitInternal("plugin:install", { name: e.name, version: e.version }), this.state === "ready") {
1614
+ let n = this.initializeWithDependencies(e.name);
1615
+ this.pendingInits.set(e.name, n), n.finally(() => {
1616
+ this.pendingInits.delete(e.name);
1617
+ });
1618
+ }
1619
+ } catch (n) {
1620
+ throw this.pendingInits.delete(e.name), this.plugins.delete(e.name), this.resolver.removePlugin(e.name), n;
1621
+ }
1622
+ return this;
1623
+ }
1624
+ async waitForPlugin(e) {
1625
+ let t = this.pendingInits.get(e);
1626
+ t && await t;
1627
+ }
1628
+ async waitForAll() {
1629
+ await Promise.all(this.pendingInits.values());
1630
+ }
1631
+ async initializeWithDependencies(e) {
1632
+ let t = this.plugins.get(e);
1633
+ if (!t) return;
1634
+ let n = t.plugin.dependencies || [];
1635
+ for (let r of n) {
1636
+ let i = this.pendingInits.get(r);
1637
+ i && await i;
1638
+ }
1639
+ for (let r of n) {
1640
+ let i = this.plugins.get(r);
1641
+ if (!i || i.state !== "ready") {
1642
+ t.state = "failed";
1643
+ let a = new import_types.PluginError(`Dependency '${r}' is not ready for plugin '${e}'`, e);
1644
+ this.emitInternal("plugin:error", { name: e, error: a });
1645
+ return;
1646
+ }
1647
+ }
1648
+ await this.initializePlugin(e);
1649
+ }
1650
+ async initializePlugin(e) {
1651
+ let t = this.plugins.get(e);
1652
+ if (!(!t || t.state !== "registered")) try {
1653
+ t.state = "initializing", await this.errorBoundary.withBoundary(e, t.plugin, async () => {
1654
+ t.plugin.onInit && await t.plugin.onInit(this.context.get());
1655
+ }), t.state = "ready", t.initializedAt = Date.now(), this.emitInternal("plugin:init", { name: e });
1656
+ } catch (n) {
1657
+ t.state = "failed", this.emitInternal("plugin:error", { name: e, error: n });
1658
+ }
1659
+ }
1660
+ useAll(e) {
1661
+ for (let t of e) this.use(t);
1662
+ return this;
1663
+ }
1664
+ unregister(e) {
1665
+ let t = this.plugins.get(e);
1666
+ if (!t) return false;
1667
+ let n = this.pendingInits.get(e);
1668
+ return t.state === "initializing" && n ? (n.finally(() => {
1669
+ if (t.plugin.onDestroy) return t.plugin.onDestroy();
1670
+ }).then(() => this.emitInternal("plugin:destroy", { name: e })).catch(() => {
1671
+ }), this.pendingInits.delete(e)) : t.state === "ready" && t.plugin.onDestroy && Promise.resolve().then(() => t.plugin.onDestroy()).then(() => this.emitInternal("plugin:destroy", { name: e })).catch(() => {
1672
+ }), this.plugins.delete(e), this.resolver.removePlugin(e), true;
1673
+ }
1674
+ async unregisterAsync(e) {
1675
+ let t = this.plugins.get(e);
1676
+ if (!t) return false;
1677
+ let n = this.pendingInits.get(e);
1678
+ if (t.state === "initializing" && n) {
1679
+ try {
1680
+ await n;
1681
+ } catch {
1682
+ }
1683
+ this.pendingInits.delete(e);
1684
+ }
1685
+ if ((t.state === "ready" || t.state === "failed") && t.plugin.onDestroy) try {
1686
+ await t.plugin.onDestroy(), this.emitInternal("plugin:destroy", { name: e });
1687
+ } catch {
1688
+ }
1689
+ return this.plugins.delete(e), this.resolver.removePlugin(e), true;
1690
+ }
1691
+ async replace(e) {
1692
+ await this.unregisterAsync(e.name), this.use(e), this.state === "ready" && await this.waitForPlugin(e.name);
1693
+ }
1694
+ async reload(e) {
1695
+ let t = this.plugins.get(e);
1696
+ if (!t) return;
1697
+ let n = this.errorBoundary.getStrategy();
1698
+ if (t.state === "ready") {
1699
+ try {
1700
+ t.plugin.onDestroy && await this.errorBoundary.withBoundary(e, t.plugin, async () => t.plugin.onDestroy()), this.emitInternal("plugin:destroy", { name: e });
1701
+ } catch (r) {
1702
+ if (n === "fail-fast") throw r;
1703
+ }
1704
+ t.state = "registered";
1705
+ try {
1706
+ t.plugin.onInit && await this.errorBoundary.withBoundary(e, t.plugin, async () => t.plugin.onInit(this.context.get())), t.state = "ready", this.emitInternal("plugin:init", { name: e });
1707
+ } catch (r) {
1708
+ if (n === "fail-fast") throw r;
1709
+ t.state = "failed";
1710
+ }
1711
+ }
1712
+ }
1713
+ async init() {
1714
+ if (this.state !== "created") throw new import_types.PluginError("Kernel already initialized", "kernel");
1715
+ this.state = "initializing";
1716
+ try {
1717
+ this.config.onBeforeInit && await this.config.onBeforeInit();
1718
+ let e = this.resolver.resolve();
1719
+ this.emitInternal("kernel:init", { timestamp: Date.now() }), await this.lifecycle.initialize(this.plugins, e, this.context.get(), this.errorBoundary, (t) => this.emitInternal("plugin:init", { name: t })), this.state = "ready", this.emitInternal("kernel:ready", { timestamp: Date.now(), plugins: Array.from(this.plugins.keys()) }), this.config.onAfterInit && await this.config.onAfterInit(), this.errorBoundary.throwIfErrors();
1720
+ } catch (e) {
1721
+ throw this.state = "created", e;
1722
+ }
1723
+ }
1724
+ async destroy() {
1725
+ if (this.state === "destroyed") return;
1726
+ this.state = "destroying", this.config.onBeforeDestroy && await this.config.onBeforeDestroy(), this.emitInternal("kernel:destroy", { timestamp: Date.now() }), await Promise.allSettled(this.pendingInits.values());
1727
+ let e;
1728
+ try {
1729
+ e = this.resolver.resolve();
1730
+ } catch {
1731
+ e = Array.from(this.plugins.keys());
1732
+ }
1733
+ await this.lifecycle.destroy(this.plugins, e, this.errorBoundary, (t) => this.emitInternal("plugin:destroy", { name: t })), this.state = "destroyed", this.emitInternal("kernel:destroyed", { timestamp: Date.now() }), this.events.clear(), this.config.onAfterDestroy && await this.config.onAfterDestroy();
1734
+ }
1735
+ isInitialized() {
1736
+ return this.state === "ready";
1737
+ }
1738
+ isDestroyed() {
1739
+ return this.state === "destroyed";
1740
+ }
1741
+ getPlugin(e) {
1742
+ return this.plugins.get(e)?.plugin;
1743
+ }
1744
+ hasPlugin(e) {
1745
+ return this.plugins.has(e);
1746
+ }
1747
+ listPlugins() {
1748
+ return Array.from(this.plugins.values()).map((e) => e.plugin);
1749
+ }
1750
+ getPluginNames() {
1751
+ return Array.from(this.plugins.keys());
1752
+ }
1753
+ getDependencyGraph() {
1754
+ return this.resolver.getGraph();
1755
+ }
1756
+ on(e, t) {
1757
+ return this.events.on(e, t);
1758
+ }
1759
+ once(e, t) {
1760
+ return this.events.once(e, t);
1761
+ }
1762
+ off(e, t) {
1763
+ this.events.off(e, t);
1764
+ }
1765
+ emit(e, t) {
1766
+ this.events.emit(e, t);
1767
+ }
1768
+ onWildcard(e) {
1769
+ return this.events.onWildcard(e);
1770
+ }
1771
+ onPattern(e, t) {
1772
+ return this.events.onPattern(e, t);
1773
+ }
1774
+ getContext() {
1775
+ return this.context.get();
1776
+ }
1777
+ updateContext(e) {
1778
+ this.context.update(e);
1779
+ }
1780
+ deepUpdateContext(e) {
1781
+ this.context.deepUpdate(e);
1782
+ }
1783
+ };
1784
+ function W(d) {
1785
+ return new c(d);
1786
+ }
1787
+
1099
1788
  // src/core/builder.ts
1100
1789
  var BuilderPigment = class {
1101
1790
  styles = [];
1102
- constructor(_kernel) {
1791
+ kernel;
1792
+ constructor(kernel) {
1793
+ this.kernel = kernel;
1794
+ }
1795
+ /** The instance's color level (true color when there is no kernel). */
1796
+ get level() {
1797
+ return this.kernel?.getContext().level;
1103
1798
  }
1104
1799
  bold() {
1105
1800
  this.styles.push(generateModifierCode("bold"));
@@ -1278,26 +1973,26 @@ var BuilderPigment = class {
1278
1973
  return this;
1279
1974
  }
1280
1975
  ansi256(code) {
1281
- this.styles.push(generateAnsi256Code(code, false));
1976
+ this.styles.push(generateAnsi256CodeForLevel(code, false, this.level));
1282
1977
  return this;
1283
1978
  }
1284
1979
  bgAnsi256(code) {
1285
- this.styles.push(generateAnsi256Code(code, true));
1980
+ this.styles.push(generateAnsi256CodeForLevel(code, true, this.level));
1286
1981
  return this;
1287
1982
  }
1288
1983
  rgb(r, g, b) {
1289
- this.styles.push(generateRgbCode(r, g, b, false));
1984
+ this.styles.push(generateRgbCodeForLevel(r, g, b, false, this.level));
1290
1985
  return this;
1291
1986
  }
1292
1987
  bgRgb(r, g, b) {
1293
- this.styles.push(generateRgbCode(r, g, b, true));
1988
+ this.styles.push(generateRgbCodeForLevel(r, g, b, true, this.level));
1294
1989
  return this;
1295
1990
  }
1296
1991
  hex(color) {
1297
1992
  const rgb = hexToRgb(color);
1298
1993
  if (rgb) {
1299
1994
  const { r, g, b } = rgb;
1300
- this.styles.push(generateRgbCode(r, g, b, false));
1995
+ this.styles.push(generateRgbCodeForLevel(r, g, b, false, this.level));
1301
1996
  }
1302
1997
  return this;
1303
1998
  }
@@ -1305,22 +2000,22 @@ var BuilderPigment = class {
1305
2000
  const rgb = hexToRgb(color);
1306
2001
  if (rgb) {
1307
2002
  const { r, g, b } = rgb;
1308
- this.styles.push(generateRgbCode(r, g, b, true));
2003
+ this.styles.push(generateRgbCodeForLevel(r, g, b, true, this.level));
1309
2004
  }
1310
2005
  return this;
1311
2006
  }
1312
- hsl(h, s, l) {
1313
- const { r, g, b } = hslToRgb(h, s, l);
1314
- this.styles.push(generateRgbCode(r, g, b, false));
2007
+ hsl(h2, s, l) {
2008
+ const { r, g, b } = hslToRgb(h2, s, l);
2009
+ this.styles.push(generateRgbCodeForLevel(r, g, b, false, this.level));
1315
2010
  return this;
1316
2011
  }
1317
- bgHsl(h, s, l) {
1318
- const { r, g, b } = hslToRgb(h, s, l);
1319
- this.styles.push(generateRgbCode(r, g, b, true));
2012
+ bgHsl(h2, s, l) {
2013
+ const { r, g, b } = hslToRgb(h2, s, l);
2014
+ this.styles.push(generateRgbCodeForLevel(r, g, b, true, this.level));
1320
2015
  return this;
1321
2016
  }
1322
2017
  paint(text) {
1323
- if (this.styles.length === 0 || text === "") {
2018
+ if (this.styles.length === 0 || text === "" || this.level === 0) {
1324
2019
  return text;
1325
2020
  }
1326
2021
  const open = this.styles.map((style) => style.open).join("");
@@ -1335,30 +2030,13 @@ var BuilderPigment = class {
1335
2030
  }
1336
2031
  };
1337
2032
 
1338
- // src/utils/rgb-to-ansi256.ts
1339
- function rgbToAnsi256(r, g, b) {
1340
- const clampedR = Math.max(0, Math.min(255, r));
1341
- const clampedG = Math.max(0, Math.min(255, g));
1342
- const clampedB = Math.max(0, Math.min(255, b));
1343
- if (clampedR === clampedG && clampedG === clampedB) {
1344
- if (clampedR < 8) {
1345
- return 16;
1346
- }
1347
- if (clampedR > 248) {
1348
- return 231;
1349
- }
1350
- return Math.round((clampedR - 8) / 247 * 24) + 232;
1351
- }
1352
- return Math.round(clampedR / 51) * 36 + Math.round(clampedG / 51) * 6 + Math.round(clampedB / 51) + 16;
1353
- }
1354
-
1355
2033
  // src/core/factory.ts
1356
2034
  function createPigment(options) {
1357
2035
  const colorSupport = detectColorSupport(options?.level);
1358
2036
  const noColor = options?.noColor ?? false;
1359
2037
  const forceColor = options?.forceColor ?? false;
1360
2038
  const level = noColor ? 0 : forceColor ? options?.level ?? 3 : colorSupport.level;
1361
- const kernel = (0, import_plugin.createKernel)({
2039
+ const kernel = W({
1362
2040
  context: {
1363
2041
  colorSupport: { ...colorSupport, level },
1364
2042
  level,
@@ -1381,13 +2059,12 @@ function createPigment(options) {
1381
2059
  kernel.use(environmentPlugin());
1382
2060
  if (options?.plugins) {
1383
2061
  for (const plugin of options.plugins) {
1384
- kernel.use(plugin);
2062
+ installPlugin(kernel, plugin);
1385
2063
  }
1386
2064
  }
1387
- kernel.init();
1388
2065
  const pigment = createProxyPigment(kernel);
1389
- const builder = new BuilderPigment(kernel);
1390
- Object.defineProperty(pigment, "builder", { value: builder, enumerable: false });
2066
+ registerRoot(kernel, pigment);
2067
+ Object.defineProperty(pigment, "builder", { get: () => new BuilderPigment(kernel), enumerable: false });
1391
2068
  Object.defineProperty(pigment, "level", { value: level, enumerable: true });
1392
2069
  Object.defineProperty(pigment, "supportsColor", { value: colorSupport, enumerable: true });
1393
2070
  return pigment;
@@ -1404,7 +2081,7 @@ function pigmentPlugin(options) {
1404
2081
  const k = kernel;
1405
2082
  const themeColors = THEME_PRESETS[theme] ?? THEME_PRESETS.monokai;
1406
2083
  const pigment = createPigment({ level });
1407
- k.pigment = pigment;
2084
+ Object.assign(k, { pigment });
1408
2085
  k.updateContext({
1409
2086
  ecosystem: {
1410
2087
  theme,