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