@ponbac/token-ledger 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -42683,7 +42683,7 @@ var runWith2 = (command, config) => {
42683
42683
  // packages/cli/package.json
42684
42684
  var package_default = {
42685
42685
  name: "@ponbac/token-ledger",
42686
- version: "0.3.0",
42686
+ version: "0.4.0",
42687
42687
  private: true,
42688
42688
  type: "module",
42689
42689
  bin: {
@@ -42694,6 +42694,7 @@ var package_default = {
42694
42694
  "@token-ledger/core": "workspace:*",
42695
42695
  "cli-table3": "^0.6.5",
42696
42696
  effect: "4.0.0",
42697
+ "jsonc-parser": "^3.3.1",
42697
42698
  "wrap-ansi": "^10.0.2"
42698
42699
  },
42699
42700
  description: "Local AI token usage and API-equivalent cost reports by project",
@@ -42711,1363 +42712,2866 @@ var package_default = {
42711
42712
  url: "https://github.com/ponbac/token-ledger/issues"
42712
42713
  }
42713
42714
  };
42714
-
42715
- // packages/cli/src/format.ts
42716
- import { styleText } from "node:util";
42717
- var import_cli_table3 = __toESM(require_table(), 1);
42718
-
42719
- // node_modules/.bun/ansi-regex@6.3.0/node_modules/ansi-regex/index.js
42720
- function ansiRegex({ onlyFirst = false } = {}) {
42721
- const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
42722
- const osc = `(?:\\u001B\\][^\\u0007\\u001B\\u009C]*${ST})`;
42723
- const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
42724
- const pattern = `${osc}|${csi}`;
42725
- return new RegExp(pattern, onlyFirst ? undefined : "g");
42726
- }
42727
-
42728
- // node_modules/.bun/strip-ansi@7.2.0/node_modules/strip-ansi/index.js
42729
- var regex = ansiRegex();
42730
- function stripAnsi2(string4) {
42731
- if (typeof string4 !== "string") {
42732
- throw new TypeError(`Expected a \`string\`, got \`${typeof string4}\``);
42715
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
42716
+ function createScanner(text2, ignoreTrivia = false) {
42717
+ const len = text2.length;
42718
+ let pos = 0, value5 = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
42719
+ function scanHexDigits(count2, exact) {
42720
+ let digits = 0;
42721
+ let value6 = 0;
42722
+ while (digits < count2 || !exact) {
42723
+ let ch = text2.charCodeAt(pos);
42724
+ if (ch >= 48 && ch <= 57) {
42725
+ value6 = value6 * 16 + ch - 48;
42726
+ } else if (ch >= 65 && ch <= 70) {
42727
+ value6 = value6 * 16 + ch - 65 + 10;
42728
+ } else if (ch >= 97 && ch <= 102) {
42729
+ value6 = value6 * 16 + ch - 97 + 10;
42730
+ } else {
42731
+ break;
42732
+ }
42733
+ pos++;
42734
+ digits++;
42735
+ }
42736
+ if (digits < count2) {
42737
+ value6 = -1;
42738
+ }
42739
+ return value6;
42733
42740
  }
42734
- if (!string4.includes("\x1B") && !string4.includes("›")) {
42735
- return string4;
42741
+ function setPosition(newPosition) {
42742
+ pos = newPosition;
42743
+ value5 = "";
42744
+ tokenOffset = 0;
42745
+ token = 16;
42746
+ scanError = 0;
42736
42747
  }
42737
- return string4.replace(regex, "");
42738
- }
42739
-
42740
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup-data.js
42741
- var ambiguousMinimalCodePoint = 161;
42742
- var ambiguousMaximumCodePoint = 1114109;
42743
- var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
42744
- var fullwidthMinimalCodePoint = 12288;
42745
- var fullwidthMaximumCodePoint = 65510;
42746
- var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
42747
- var wideMinimalCodePoint = 4352;
42748
- var wideMaximumCodePoint = 262141;
42749
- var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101594, 101631, 101664, 101760, 101874, 101888, 102801, 102816, 102866, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110888, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110952, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127406, 127406, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128729, 128732, 128735, 128747, 128748, 128756, 128764, 128986, 128986, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129734, 129736, 129736, 129740, 129757, 129759, 129771, 129775, 129786, 131072, 196605, 196608, 262141];
42750
-
42751
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/utilities.js
42752
- var isInRange = (ranges, codePoint) => {
42753
- let low = 0;
42754
- let high = Math.floor(ranges.length / 2) - 1;
42755
- while (low <= high) {
42756
- const mid = Math.floor((low + high) / 2);
42757
- const i = mid * 2;
42758
- if (codePoint < ranges[i]) {
42759
- high = mid - 1;
42760
- } else if (codePoint > ranges[i + 1]) {
42761
- low = mid + 1;
42748
+ function scanNumber() {
42749
+ let start = pos;
42750
+ if (text2.charCodeAt(pos) === 48) {
42751
+ pos++;
42762
42752
  } else {
42763
- return true;
42753
+ pos++;
42754
+ while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42755
+ pos++;
42756
+ }
42764
42757
  }
42765
- }
42766
- return false;
42767
- };
42768
-
42769
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup.js
42770
- var commonCjkCodePoint = 19968;
42771
- var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
42772
- function findWideFastPathRange(ranges) {
42773
- let fastPathStart = ranges[0];
42774
- let fastPathEnd = ranges[1];
42775
- for (let index2 = 0;index2 < ranges.length; index2 += 2) {
42776
- const start = ranges[index2];
42777
- const end3 = ranges[index2 + 1];
42778
- if (commonCjkCodePoint >= start && commonCjkCodePoint <= end3) {
42779
- return [start, end3];
42758
+ if (pos < text2.length && text2.charCodeAt(pos) === 46) {
42759
+ pos++;
42760
+ if (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42761
+ pos++;
42762
+ while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42763
+ pos++;
42764
+ }
42765
+ } else {
42766
+ scanError = 3;
42767
+ return text2.substring(start, pos);
42768
+ }
42780
42769
  }
42781
- if (end3 - start > fastPathEnd - fastPathStart) {
42782
- fastPathStart = start;
42783
- fastPathEnd = end3;
42770
+ let end3 = pos;
42771
+ if (pos < text2.length && (text2.charCodeAt(pos) === 69 || text2.charCodeAt(pos) === 101)) {
42772
+ pos++;
42773
+ if (pos < text2.length && text2.charCodeAt(pos) === 43 || text2.charCodeAt(pos) === 45) {
42774
+ pos++;
42775
+ }
42776
+ if (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42777
+ pos++;
42778
+ while (pos < text2.length && isDigit(text2.charCodeAt(pos))) {
42779
+ pos++;
42780
+ }
42781
+ end3 = pos;
42782
+ } else {
42783
+ scanError = 3;
42784
+ }
42784
42785
  }
42786
+ return text2.substring(start, end3);
42785
42787
  }
42786
- return [fastPathStart, fastPathEnd];
42787
- }
42788
- var isAmbiguous = (codePoint) => {
42789
- if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) {
42790
- return false;
42788
+ function scanString() {
42789
+ let result6 = "", start = pos;
42790
+ while (true) {
42791
+ if (pos >= len) {
42792
+ result6 += text2.substring(start, pos);
42793
+ scanError = 2;
42794
+ break;
42795
+ }
42796
+ const ch = text2.charCodeAt(pos);
42797
+ if (ch === 34) {
42798
+ result6 += text2.substring(start, pos);
42799
+ pos++;
42800
+ break;
42801
+ }
42802
+ if (ch === 92) {
42803
+ result6 += text2.substring(start, pos);
42804
+ pos++;
42805
+ if (pos >= len) {
42806
+ scanError = 2;
42807
+ break;
42808
+ }
42809
+ const ch2 = text2.charCodeAt(pos++);
42810
+ switch (ch2) {
42811
+ case 34:
42812
+ result6 += '"';
42813
+ break;
42814
+ case 92:
42815
+ result6 += "\\";
42816
+ break;
42817
+ case 47:
42818
+ result6 += "/";
42819
+ break;
42820
+ case 98:
42821
+ result6 += "\b";
42822
+ break;
42823
+ case 102:
42824
+ result6 += "\f";
42825
+ break;
42826
+ case 110:
42827
+ result6 += `
42828
+ `;
42829
+ break;
42830
+ case 114:
42831
+ result6 += "\r";
42832
+ break;
42833
+ case 116:
42834
+ result6 += "\t";
42835
+ break;
42836
+ case 117:
42837
+ const ch3 = scanHexDigits(4, true);
42838
+ if (ch3 >= 0) {
42839
+ result6 += String.fromCharCode(ch3);
42840
+ } else {
42841
+ scanError = 4;
42842
+ }
42843
+ break;
42844
+ default:
42845
+ scanError = 5;
42846
+ }
42847
+ start = pos;
42848
+ continue;
42849
+ }
42850
+ if (ch >= 0 && ch <= 31) {
42851
+ if (isLineBreak3(ch)) {
42852
+ result6 += text2.substring(start, pos);
42853
+ scanError = 2;
42854
+ break;
42855
+ } else {
42856
+ scanError = 6;
42857
+ }
42858
+ }
42859
+ pos++;
42860
+ }
42861
+ return result6;
42791
42862
  }
42792
- return isInRange(ambiguousRanges, codePoint);
42793
- };
42794
- var isFullwidth = (codePoint) => {
42795
- if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) {
42796
- return false;
42863
+ function scanNext() {
42864
+ value5 = "";
42865
+ scanError = 0;
42866
+ tokenOffset = pos;
42867
+ lineStartOffset = lineNumber;
42868
+ prevTokenLineStartOffset = tokenLineStartOffset;
42869
+ if (pos >= len) {
42870
+ tokenOffset = len;
42871
+ return token = 17;
42872
+ }
42873
+ let code = text2.charCodeAt(pos);
42874
+ if (isWhiteSpace(code)) {
42875
+ do {
42876
+ pos++;
42877
+ value5 += String.fromCharCode(code);
42878
+ code = text2.charCodeAt(pos);
42879
+ } while (isWhiteSpace(code));
42880
+ return token = 15;
42881
+ }
42882
+ if (isLineBreak3(code)) {
42883
+ pos++;
42884
+ value5 += String.fromCharCode(code);
42885
+ if (code === 13 && text2.charCodeAt(pos) === 10) {
42886
+ pos++;
42887
+ value5 += `
42888
+ `;
42889
+ }
42890
+ lineNumber++;
42891
+ tokenLineStartOffset = pos;
42892
+ return token = 14;
42893
+ }
42894
+ switch (code) {
42895
+ case 123:
42896
+ pos++;
42897
+ return token = 1;
42898
+ case 125:
42899
+ pos++;
42900
+ return token = 2;
42901
+ case 91:
42902
+ pos++;
42903
+ return token = 3;
42904
+ case 93:
42905
+ pos++;
42906
+ return token = 4;
42907
+ case 58:
42908
+ pos++;
42909
+ return token = 6;
42910
+ case 44:
42911
+ pos++;
42912
+ return token = 5;
42913
+ case 34:
42914
+ pos++;
42915
+ value5 = scanString();
42916
+ return token = 10;
42917
+ case 47:
42918
+ const start = pos - 1;
42919
+ if (text2.charCodeAt(pos + 1) === 47) {
42920
+ pos += 2;
42921
+ while (pos < len) {
42922
+ if (isLineBreak3(text2.charCodeAt(pos))) {
42923
+ break;
42924
+ }
42925
+ pos++;
42926
+ }
42927
+ value5 = text2.substring(start, pos);
42928
+ return token = 12;
42929
+ }
42930
+ if (text2.charCodeAt(pos + 1) === 42) {
42931
+ pos += 2;
42932
+ const safeLength = len - 1;
42933
+ let commentClosed = false;
42934
+ while (pos < safeLength) {
42935
+ const ch = text2.charCodeAt(pos);
42936
+ if (ch === 42 && text2.charCodeAt(pos + 1) === 47) {
42937
+ pos += 2;
42938
+ commentClosed = true;
42939
+ break;
42940
+ }
42941
+ pos++;
42942
+ if (isLineBreak3(ch)) {
42943
+ if (ch === 13 && text2.charCodeAt(pos) === 10) {
42944
+ pos++;
42945
+ }
42946
+ lineNumber++;
42947
+ tokenLineStartOffset = pos;
42948
+ }
42949
+ }
42950
+ if (!commentClosed) {
42951
+ pos++;
42952
+ scanError = 1;
42953
+ }
42954
+ value5 = text2.substring(start, pos);
42955
+ return token = 13;
42956
+ }
42957
+ value5 += String.fromCharCode(code);
42958
+ pos++;
42959
+ return token = 16;
42960
+ case 45:
42961
+ value5 += String.fromCharCode(code);
42962
+ pos++;
42963
+ if (pos === len || !isDigit(text2.charCodeAt(pos))) {
42964
+ return token = 16;
42965
+ }
42966
+ case 48:
42967
+ case 49:
42968
+ case 50:
42969
+ case 51:
42970
+ case 52:
42971
+ case 53:
42972
+ case 54:
42973
+ case 55:
42974
+ case 56:
42975
+ case 57:
42976
+ value5 += scanNumber();
42977
+ return token = 11;
42978
+ default:
42979
+ while (pos < len && isUnknownContentCharacter(code)) {
42980
+ pos++;
42981
+ code = text2.charCodeAt(pos);
42982
+ }
42983
+ if (tokenOffset !== pos) {
42984
+ value5 = text2.substring(tokenOffset, pos);
42985
+ switch (value5) {
42986
+ case "true":
42987
+ return token = 8;
42988
+ case "false":
42989
+ return token = 9;
42990
+ case "null":
42991
+ return token = 7;
42992
+ }
42993
+ return token = 16;
42994
+ }
42995
+ value5 += String.fromCharCode(code);
42996
+ pos++;
42997
+ return token = 16;
42998
+ }
42797
42999
  }
42798
- return isInRange(fullwidthRanges, codePoint);
42799
- };
42800
- var isWide = (codePoint) => {
42801
- if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
43000
+ function isUnknownContentCharacter(code) {
43001
+ if (isWhiteSpace(code) || isLineBreak3(code)) {
43002
+ return false;
43003
+ }
43004
+ switch (code) {
43005
+ case 125:
43006
+ case 93:
43007
+ case 123:
43008
+ case 91:
43009
+ case 34:
43010
+ case 58:
43011
+ case 44:
43012
+ case 47:
43013
+ return false;
43014
+ }
42802
43015
  return true;
42803
43016
  }
42804
- if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) {
42805
- return false;
43017
+ function scanNextNonTrivia() {
43018
+ let result6;
43019
+ do {
43020
+ result6 = scanNext();
43021
+ } while (result6 >= 12 && result6 <= 15);
43022
+ return result6;
43023
+ }
43024
+ return {
43025
+ setPosition,
43026
+ getPosition: () => pos,
43027
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
43028
+ getToken: () => token,
43029
+ getTokenValue: () => value5,
43030
+ getTokenOffset: () => tokenOffset,
43031
+ getTokenLength: () => pos - tokenOffset,
43032
+ getTokenStartLine: () => lineStartOffset,
43033
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
43034
+ getTokenError: () => scanError
43035
+ };
43036
+ }
43037
+ function isWhiteSpace(ch) {
43038
+ return ch === 32 || ch === 9;
43039
+ }
43040
+ function isLineBreak3(ch) {
43041
+ return ch === 10 || ch === 13;
43042
+ }
43043
+ function isDigit(ch) {
43044
+ return ch >= 48 && ch <= 57;
43045
+ }
43046
+ var CharacterCodes;
43047
+ (function(CharacterCodes2) {
43048
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
43049
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
43050
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
43051
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
43052
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
43053
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
43054
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
43055
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
43056
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
43057
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
43058
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
43059
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
43060
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
43061
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
43062
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
43063
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
43064
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
43065
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
43066
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
43067
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
43068
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
43069
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
43070
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
43071
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
43072
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
43073
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
43074
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
43075
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
43076
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
43077
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
43078
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
43079
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
43080
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
43081
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
43082
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
43083
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
43084
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
43085
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
43086
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
43087
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
43088
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
43089
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
43090
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
43091
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
43092
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
43093
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
43094
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
43095
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
43096
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
43097
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
43098
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
43099
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
43100
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
43101
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
43102
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
43103
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
43104
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
43105
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
43106
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
43107
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
43108
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
43109
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
43110
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
43111
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
43112
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
43113
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
43114
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
43115
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
43116
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
43117
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
43118
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
43119
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
43120
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
43121
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
43122
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
43123
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
43124
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
43125
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
43126
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
43127
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
43128
+ })(CharacterCodes || (CharacterCodes = {}));
43129
+
43130
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
43131
+ var cachedSpaces = new Array(20).fill(0).map((_, index2) => {
43132
+ return " ".repeat(index2);
43133
+ });
43134
+ var maxCachedValues = 200;
43135
+ var cachedBreakLinesWithSpaces = {
43136
+ " ": {
43137
+ "\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43138
+ return `
43139
+ ` + " ".repeat(index2);
43140
+ }),
43141
+ "\r": new Array(maxCachedValues).fill(0).map((_, index2) => {
43142
+ return "\r" + " ".repeat(index2);
43143
+ }),
43144
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43145
+ return `\r
43146
+ ` + " ".repeat(index2);
43147
+ })
43148
+ },
43149
+ "\t": {
43150
+ "\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43151
+ return `
43152
+ ` + "\t".repeat(index2);
43153
+ }),
43154
+ "\r": new Array(maxCachedValues).fill(0).map((_, index2) => {
43155
+ return "\r" + "\t".repeat(index2);
43156
+ }),
43157
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index2) => {
43158
+ return `\r
43159
+ ` + "\t".repeat(index2);
43160
+ })
42806
43161
  }
42807
- return isInRange(wideRanges, codePoint);
42808
43162
  };
42809
43163
 
42810
- // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/index.js
42811
- function validate3(codePoint) {
42812
- if (!Number.isSafeInteger(codePoint)) {
42813
- throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
43164
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
43165
+ var ParseOptions;
43166
+ (function(ParseOptions2) {
43167
+ ParseOptions2.DEFAULT = {
43168
+ allowTrailingComma: false
43169
+ };
43170
+ })(ParseOptions || (ParseOptions = {}));
43171
+ function parseTree(text2, errors = [], options3 = ParseOptions.DEFAULT) {
43172
+ let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: undefined };
43173
+ function ensurePropertyComplete(endOffset) {
43174
+ if (currentParent.type === "property") {
43175
+ currentParent.length = endOffset - currentParent.offset;
43176
+ currentParent = currentParent.parent;
43177
+ }
42814
43178
  }
42815
- }
42816
- function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
42817
- validate3(codePoint);
42818
- if (isFullwidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
42819
- return 2;
43179
+ function onValue(valueNode) {
43180
+ currentParent.children.push(valueNode);
43181
+ return valueNode;
42820
43182
  }
42821
- return 1;
43183
+ const visitor = {
43184
+ onObjectBegin: (offset) => {
43185
+ currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
43186
+ },
43187
+ onObjectProperty: (name, offset, length) => {
43188
+ currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
43189
+ currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
43190
+ },
43191
+ onObjectEnd: (offset, length) => {
43192
+ ensurePropertyComplete(offset + length);
43193
+ currentParent.length = offset + length - currentParent.offset;
43194
+ currentParent = currentParent.parent;
43195
+ ensurePropertyComplete(offset + length);
43196
+ },
43197
+ onArrayBegin: (offset, length) => {
43198
+ currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
43199
+ },
43200
+ onArrayEnd: (offset, length) => {
43201
+ currentParent.length = offset + length - currentParent.offset;
43202
+ currentParent = currentParent.parent;
43203
+ ensurePropertyComplete(offset + length);
43204
+ },
43205
+ onLiteralValue: (value5, offset, length) => {
43206
+ onValue({ type: getNodeType(value5), offset, length, parent: currentParent, value: value5 });
43207
+ ensurePropertyComplete(offset + length);
43208
+ },
43209
+ onSeparator: (sep, offset, length) => {
43210
+ if (currentParent.type === "property") {
43211
+ if (sep === ":") {
43212
+ currentParent.colonOffset = offset;
43213
+ } else if (sep === ",") {
43214
+ ensurePropertyComplete(offset);
43215
+ }
43216
+ }
43217
+ },
43218
+ onError: (error2, offset, length) => {
43219
+ errors.push({ error: error2, offset, length });
43220
+ }
43221
+ };
43222
+ visit(text2, visitor, options3);
43223
+ const result6 = currentParent.children[0];
43224
+ if (result6) {
43225
+ delete result6.parent;
43226
+ }
43227
+ return result6;
42822
43228
  }
42823
-
42824
- // node_modules/.bun/string-width@8.2.2/node_modules/string-width/index.js
42825
- var segmenter = new Intl.Segmenter;
42826
- var zeroWidthClusterRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Nonspacing_Mark}|\p{Enclosing_Mark}|\p{Surrogate})+$/v;
42827
- var leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]+/v;
42828
- var spacingMarkRegex = /\p{Spacing_Mark}/v;
42829
- var rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
42830
- var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
42831
- var extendedPictographicRegex = /\p{Extended_Pictographic}/gu;
42832
- function isDoubleWidthNonRgiEmojiSequence(segment) {
42833
- if (segment.length > 50) {
42834
- return false;
43229
+ function getNodeValue(node) {
43230
+ switch (node.type) {
43231
+ case "array":
43232
+ return node.children.map(getNodeValue);
43233
+ case "object":
43234
+ const obj = Object.create(null);
43235
+ for (let prop of node.children) {
43236
+ const valueNode = prop.children[1];
43237
+ if (valueNode) {
43238
+ obj[prop.children[0].value] = getNodeValue(valueNode);
43239
+ }
43240
+ }
43241
+ return obj;
43242
+ case "null":
43243
+ case "string":
43244
+ case "number":
43245
+ case "boolean":
43246
+ return node.value;
43247
+ default:
43248
+ return;
42835
43249
  }
42836
- if (unqualifiedKeycapRegex.test(segment)) {
42837
- return true;
43250
+ }
43251
+ function visit(text2, visitor, options3 = ParseOptions.DEFAULT) {
43252
+ const _scanner = createScanner(text2, false);
43253
+ const _jsonPath = [];
43254
+ let suppressedCallbacks = 0;
43255
+ function toNoArgVisit(visitFunction) {
43256
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
42838
43257
  }
42839
- if (segment.includes("‍")) {
42840
- const pictographics = segment.match(extendedPictographicRegex);
42841
- return pictographics !== null && pictographics.length >= 2;
43258
+ function toOneArgVisit(visitFunction) {
43259
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
42842
43260
  }
42843
- return false;
42844
- }
42845
- function baseVisible(segment) {
42846
- return segment.replace(leadingNonPrintingRegex, "");
42847
- }
42848
- function isZeroWidthCluster(segment) {
42849
- return zeroWidthClusterRegex.test(segment);
42850
- }
42851
- function isHangulLeadingJamo(codePoint) {
42852
- return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
42853
- }
42854
- function isHangulVowelJamo(codePoint) {
42855
- return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
42856
- }
42857
- function isHangulTrailingJamo(codePoint) {
42858
- return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
42859
- }
42860
- function isHangulJamo(codePoint) {
42861
- return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
42862
- }
42863
- function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
42864
- const codePoints = [];
42865
- for (const character of visibleSegment) {
42866
- if (zeroWidthClusterRegex.test(character)) {
42867
- continue;
42868
- }
42869
- codePoints.push(character.codePointAt(0));
43261
+ function toOneArgVisitWithPath(visitFunction) {
43262
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
42870
43263
  }
42871
- if (codePoints.length === 0) {
42872
- return;
43264
+ function toBeginVisit(visitFunction) {
43265
+ return visitFunction ? () => {
43266
+ if (suppressedCallbacks > 0) {
43267
+ suppressedCallbacks++;
43268
+ } else {
43269
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
43270
+ if (cbReturn === false) {
43271
+ suppressedCallbacks = 1;
43272
+ }
43273
+ }
43274
+ } : () => true;
42873
43275
  }
42874
- let width2 = 0;
42875
- for (let index2 = 0;index2 < codePoints.length; index2++) {
42876
- const codePoint = codePoints[index2];
42877
- if (!isHangulJamo(codePoint)) {
42878
- if (width2 === 0) {
42879
- return;
43276
+ function toEndVisit(visitFunction) {
43277
+ return visitFunction ? () => {
43278
+ if (suppressedCallbacks > 0) {
43279
+ suppressedCallbacks--;
42880
43280
  }
42881
- for (let remaining = index2;remaining < codePoints.length; remaining++) {
42882
- width2 += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
43281
+ if (suppressedCallbacks === 0) {
43282
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
42883
43283
  }
42884
- return width2;
42885
- }
42886
- if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index2 + 1])) {
42887
- width2 += 2;
42888
- index2 += isHangulTrailingJamo(codePoints[index2 + 2]) ? 2 : 1;
42889
- continue;
42890
- }
42891
- width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
43284
+ } : () => true;
42892
43285
  }
42893
- return width2;
42894
- }
42895
- function trailingWidth(visibleSegment, eastAsianWidthOptions) {
42896
- let extra = 0;
42897
- let first = true;
42898
- for (const character of visibleSegment) {
42899
- if (first) {
42900
- first = false;
42901
- continue;
43286
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError5 = toOneArgVisit(visitor.onError);
43287
+ const disallowComments = options3 && options3.disallowComments;
43288
+ const allowTrailingComma = options3 && options3.allowTrailingComma;
43289
+ function scanNext() {
43290
+ while (true) {
43291
+ const token = _scanner.scan();
43292
+ switch (_scanner.getTokenError()) {
43293
+ case 4:
43294
+ handleError(14);
43295
+ break;
43296
+ case 5:
43297
+ handleError(15);
43298
+ break;
43299
+ case 3:
43300
+ handleError(13);
43301
+ break;
43302
+ case 1:
43303
+ if (!disallowComments) {
43304
+ handleError(11);
43305
+ }
43306
+ break;
43307
+ case 2:
43308
+ handleError(12);
43309
+ break;
43310
+ case 6:
43311
+ handleError(16);
43312
+ break;
43313
+ }
43314
+ switch (token) {
43315
+ case 12:
43316
+ case 13:
43317
+ if (disallowComments) {
43318
+ handleError(10);
43319
+ } else {
43320
+ onComment();
43321
+ }
43322
+ break;
43323
+ case 16:
43324
+ handleError(1);
43325
+ break;
43326
+ case 15:
43327
+ case 14:
43328
+ break;
43329
+ default:
43330
+ return token;
43331
+ }
42902
43332
  }
42903
- if (spacingMarkRegex.test(character) || character >= "＀" && character <= "￯") {
42904
- extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
43333
+ }
43334
+ function handleError(error2, skipUntilAfter = [], skipUntil = []) {
43335
+ onError5(error2);
43336
+ if (skipUntilAfter.length + skipUntil.length > 0) {
43337
+ let token = _scanner.getToken();
43338
+ while (token !== 17) {
43339
+ if (skipUntilAfter.indexOf(token) !== -1) {
43340
+ scanNext();
43341
+ break;
43342
+ } else if (skipUntil.indexOf(token) !== -1) {
43343
+ break;
43344
+ }
43345
+ token = scanNext();
43346
+ }
42905
43347
  }
42906
43348
  }
42907
- return extra;
42908
- }
42909
- function stringWidth(input, options3 = {}) {
42910
- if (typeof input !== "string" || input.length === 0) {
42911
- return 0;
43349
+ function parseString(isValue) {
43350
+ const value5 = _scanner.getTokenValue();
43351
+ if (isValue) {
43352
+ onLiteralValue(value5);
43353
+ } else {
43354
+ onObjectProperty(value5);
43355
+ _jsonPath.push(value5);
43356
+ }
43357
+ scanNext();
43358
+ return true;
42912
43359
  }
42913
- const {
42914
- ambiguousIsNarrow = true,
42915
- countAnsiEscapeCodes = false
42916
- } = options3;
42917
- let string4 = input;
42918
- if (!countAnsiEscapeCodes && (string4.includes("\x1B") || string4.includes("›"))) {
42919
- string4 = stripAnsi2(string4);
43360
+ function parseLiteral() {
43361
+ switch (_scanner.getToken()) {
43362
+ case 11:
43363
+ const tokenValue = _scanner.getTokenValue();
43364
+ let value5 = Number(tokenValue);
43365
+ if (isNaN(value5)) {
43366
+ handleError(2);
43367
+ value5 = 0;
43368
+ }
43369
+ onLiteralValue(value5);
43370
+ break;
43371
+ case 7:
43372
+ onLiteralValue(null);
43373
+ break;
43374
+ case 8:
43375
+ onLiteralValue(true);
43376
+ break;
43377
+ case 9:
43378
+ onLiteralValue(false);
43379
+ break;
43380
+ default:
43381
+ return false;
43382
+ }
43383
+ scanNext();
43384
+ return true;
42920
43385
  }
42921
- if (string4.length === 0) {
42922
- return 0;
43386
+ function parseProperty() {
43387
+ if (_scanner.getToken() !== 10) {
43388
+ handleError(3, [], [2, 5]);
43389
+ return false;
43390
+ }
43391
+ parseString(false);
43392
+ if (_scanner.getToken() === 6) {
43393
+ onSeparator(":");
43394
+ scanNext();
43395
+ if (!parseValue()) {
43396
+ handleError(4, [], [2, 5]);
43397
+ }
43398
+ } else {
43399
+ handleError(5, [], [2, 5]);
43400
+ }
43401
+ _jsonPath.pop();
43402
+ return true;
42923
43403
  }
42924
- if (/^[\u0020-\u007E]*$/.test(string4)) {
42925
- return string4.length;
43404
+ function parseObject() {
43405
+ onObjectBegin();
43406
+ scanNext();
43407
+ let needsComma = false;
43408
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
43409
+ if (_scanner.getToken() === 5) {
43410
+ if (!needsComma) {
43411
+ handleError(4, [], []);
43412
+ }
43413
+ onSeparator(",");
43414
+ scanNext();
43415
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
43416
+ break;
43417
+ }
43418
+ } else if (needsComma) {
43419
+ handleError(6, [], []);
43420
+ }
43421
+ if (!parseProperty()) {
43422
+ handleError(4, [], [2, 5]);
43423
+ }
43424
+ needsComma = true;
43425
+ }
43426
+ onObjectEnd();
43427
+ if (_scanner.getToken() !== 2) {
43428
+ handleError(7, [2], []);
43429
+ } else {
43430
+ scanNext();
43431
+ }
43432
+ return true;
42926
43433
  }
42927
- let width2 = 0;
42928
- const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
42929
- for (const { segment } of segmenter.segment(string4)) {
42930
- if (isZeroWidthCluster(segment)) {
42931
- continue;
43434
+ function parseArray2() {
43435
+ onArrayBegin();
43436
+ scanNext();
43437
+ let isFirstElement = true;
43438
+ let needsComma = false;
43439
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
43440
+ if (_scanner.getToken() === 5) {
43441
+ if (!needsComma) {
43442
+ handleError(4, [], []);
43443
+ }
43444
+ onSeparator(",");
43445
+ scanNext();
43446
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
43447
+ break;
43448
+ }
43449
+ } else if (needsComma) {
43450
+ handleError(6, [], []);
43451
+ }
43452
+ if (isFirstElement) {
43453
+ _jsonPath.push(0);
43454
+ isFirstElement = false;
43455
+ } else {
43456
+ _jsonPath[_jsonPath.length - 1]++;
43457
+ }
43458
+ if (!parseValue()) {
43459
+ handleError(4, [], [4, 5]);
43460
+ }
43461
+ needsComma = true;
42932
43462
  }
42933
- if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
42934
- width2 += 2;
42935
- continue;
43463
+ onArrayEnd();
43464
+ if (!isFirstElement) {
43465
+ _jsonPath.pop();
42936
43466
  }
42937
- const visibleSegment = baseVisible(segment);
42938
- const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
42939
- if (hangulWidth !== undefined) {
42940
- width2 += hangulWidth;
42941
- continue;
43467
+ if (_scanner.getToken() !== 4) {
43468
+ handleError(8, [4], []);
43469
+ } else {
43470
+ scanNext();
42942
43471
  }
42943
- const codePoint = visibleSegment.codePointAt(0);
42944
- width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
42945
- width2 += trailingWidth(visibleSegment, eastAsianWidthOptions);
43472
+ return true;
42946
43473
  }
42947
- return width2;
42948
- }
42949
-
42950
- // node_modules/.bun/ansi-styles@6.2.3/node_modules/ansi-styles/index.js
42951
- var ANSI_BACKGROUND_OFFSET = 10;
42952
- var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
42953
- var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
42954
- var wrapAnsi16m = (offset = 0) => (red2, green2, blue) => `\x1B[${38 + offset};2;${red2};${green2};${blue}m`;
42955
- var styles = {
42956
- modifier: {
42957
- reset: [0, 0],
42958
- bold: [1, 22],
42959
- dim: [2, 22],
42960
- italic: [3, 23],
42961
- underline: [4, 24],
42962
- overline: [53, 55],
42963
- inverse: [7, 27],
42964
- hidden: [8, 28],
42965
- strikethrough: [9, 29]
42966
- },
42967
- color: {
42968
- black: [30, 39],
42969
- red: [31, 39],
42970
- green: [32, 39],
42971
- yellow: [33, 39],
42972
- blue: [34, 39],
42973
- magenta: [35, 39],
42974
- cyan: [36, 39],
42975
- white: [37, 39],
42976
- blackBright: [90, 39],
42977
- gray: [90, 39],
42978
- grey: [90, 39],
42979
- redBright: [91, 39],
42980
- greenBright: [92, 39],
42981
- yellowBright: [93, 39],
42982
- blueBright: [94, 39],
42983
- magentaBright: [95, 39],
42984
- cyanBright: [96, 39],
42985
- whiteBright: [97, 39]
42986
- },
42987
- bgColor: {
42988
- bgBlack: [40, 49],
42989
- bgRed: [41, 49],
42990
- bgGreen: [42, 49],
42991
- bgYellow: [43, 49],
42992
- bgBlue: [44, 49],
42993
- bgMagenta: [45, 49],
42994
- bgCyan: [46, 49],
42995
- bgWhite: [47, 49],
42996
- bgBlackBright: [100, 49],
42997
- bgGray: [100, 49],
42998
- bgGrey: [100, 49],
42999
- bgRedBright: [101, 49],
43000
- bgGreenBright: [102, 49],
43001
- bgYellowBright: [103, 49],
43002
- bgBlueBright: [104, 49],
43003
- bgMagentaBright: [105, 49],
43004
- bgCyanBright: [106, 49],
43005
- bgWhiteBright: [107, 49]
43474
+ function parseValue() {
43475
+ switch (_scanner.getToken()) {
43476
+ case 3:
43477
+ return parseArray2();
43478
+ case 1:
43479
+ return parseObject();
43480
+ case 10:
43481
+ return parseString(true);
43482
+ default:
43483
+ return parseLiteral();
43484
+ }
43006
43485
  }
43007
- };
43008
- var modifierNames = Object.keys(styles.modifier);
43009
- var foregroundColorNames = Object.keys(styles.color);
43010
- var backgroundColorNames = Object.keys(styles.bgColor);
43011
- var colorNames = [...foregroundColorNames, ...backgroundColorNames];
43012
- function assembleStyles() {
43013
- const codes2 = new Map;
43014
- for (const [groupName, group2] of Object.entries(styles)) {
43015
- for (const [styleName, style] of Object.entries(group2)) {
43016
- styles[styleName] = {
43017
- open: `\x1B[${style[0]}m`,
43018
- close: `\x1B[${style[1]}m`
43019
- };
43020
- group2[styleName] = styles[styleName];
43021
- codes2.set(style[0], style[1]);
43486
+ scanNext();
43487
+ if (_scanner.getToken() === 17) {
43488
+ if (options3.allowEmptyContent) {
43489
+ return true;
43022
43490
  }
43023
- Object.defineProperty(styles, groupName, {
43024
- value: group2,
43025
- enumerable: false
43026
- });
43491
+ handleError(4, [], []);
43492
+ return false;
43027
43493
  }
43028
- Object.defineProperty(styles, "codes", {
43029
- value: codes2,
43030
- enumerable: false
43031
- });
43032
- styles.color.close = "\x1B[39m";
43033
- styles.bgColor.close = "\x1B[49m";
43034
- styles.color.ansi = wrapAnsi16();
43035
- styles.color.ansi256 = wrapAnsi256();
43036
- styles.color.ansi16m = wrapAnsi16m();
43037
- styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
43038
- styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
43039
- styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
43040
- Object.defineProperties(styles, {
43041
- rgbToAnsi256: {
43042
- value(red2, green2, blue) {
43043
- if (red2 === green2 && green2 === blue) {
43044
- if (red2 < 8) {
43045
- return 16;
43046
- }
43047
- if (red2 > 248) {
43048
- return 231;
43049
- }
43050
- return Math.round((red2 - 8) / 247 * 24) + 232;
43051
- }
43052
- return 16 + 36 * Math.round(red2 / 255 * 5) + 6 * Math.round(green2 / 255 * 5) + Math.round(blue / 255 * 5);
43053
- },
43054
- enumerable: false
43055
- },
43056
- hexToRgb: {
43057
- value(hex2) {
43058
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex2.toString(16));
43059
- if (!matches) {
43060
- return [0, 0, 0];
43061
- }
43062
- let [colorString] = matches;
43063
- if (colorString.length === 3) {
43064
- colorString = [...colorString].map((character) => character + character).join("");
43065
- }
43066
- const integer = Number.parseInt(colorString, 16);
43067
- return [
43068
- integer >> 16 & 255,
43069
- integer >> 8 & 255,
43070
- integer & 255
43071
- ];
43072
- },
43073
- enumerable: false
43074
- },
43075
- hexToAnsi256: {
43076
- value: (hex2) => styles.rgbToAnsi256(...styles.hexToRgb(hex2)),
43077
- enumerable: false
43494
+ if (!parseValue()) {
43495
+ handleError(4, [], []);
43496
+ return false;
43497
+ }
43498
+ if (_scanner.getToken() !== 17) {
43499
+ handleError(9, [], []);
43500
+ }
43501
+ return true;
43502
+ }
43503
+ function getNodeType(value5) {
43504
+ switch (typeof value5) {
43505
+ case "boolean":
43506
+ return "boolean";
43507
+ case "number":
43508
+ return "number";
43509
+ case "string":
43510
+ return "string";
43511
+ case "object": {
43512
+ if (!value5) {
43513
+ return "null";
43514
+ } else if (Array.isArray(value5)) {
43515
+ return "array";
43516
+ }
43517
+ return "object";
43518
+ }
43519
+ default:
43520
+ return "null";
43521
+ }
43522
+ }
43523
+
43524
+ // node_modules/.bun/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
43525
+ var ScanError;
43526
+ (function(ScanError2) {
43527
+ ScanError2[ScanError2["None"] = 0] = "None";
43528
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
43529
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
43530
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
43531
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
43532
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
43533
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
43534
+ })(ScanError || (ScanError = {}));
43535
+ var SyntaxKind;
43536
+ (function(SyntaxKind2) {
43537
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
43538
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
43539
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
43540
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
43541
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
43542
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
43543
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
43544
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
43545
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
43546
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
43547
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
43548
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
43549
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
43550
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
43551
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
43552
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
43553
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
43554
+ })(SyntaxKind || (SyntaxKind = {}));
43555
+ var parseTree2 = parseTree;
43556
+ var getNodeValue2 = getNodeValue;
43557
+ var visit2 = visit;
43558
+ var ParseErrorCode;
43559
+ (function(ParseErrorCode2) {
43560
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
43561
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
43562
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
43563
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
43564
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
43565
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
43566
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
43567
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
43568
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
43569
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
43570
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
43571
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
43572
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
43573
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
43574
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
43575
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
43576
+ })(ParseErrorCode || (ParseErrorCode = {}));
43577
+
43578
+ // packages/cli/src/jsonc.ts
43579
+ var parseOptions = { allowTrailingComma: true, allowEmptyContent: true };
43580
+ var defaultIndent = " ";
43581
+ function parse6(text2) {
43582
+ const errors = [];
43583
+ const root = parseTree2(text2, errors, parseOptions);
43584
+ const comments = [];
43585
+ const commas = [];
43586
+ visit2(text2, {
43587
+ onComment: (offset, length) => {
43588
+ comments.push({ offset, length });
43078
43589
  },
43079
- ansi256ToAnsi: {
43080
- value(code) {
43081
- if (code < 8) {
43082
- return 30 + code;
43083
- }
43084
- if (code < 16) {
43085
- return 90 + (code - 8);
43086
- }
43087
- let red2;
43088
- let green2;
43089
- let blue;
43090
- if (code >= 232) {
43091
- red2 = ((code - 232) * 10 + 8) / 255;
43092
- green2 = red2;
43093
- blue = red2;
43094
- } else {
43095
- code -= 16;
43096
- const remainder2 = code % 36;
43097
- red2 = Math.floor(code / 36) / 5;
43098
- green2 = Math.floor(remainder2 / 6) / 5;
43099
- blue = remainder2 % 6 / 5;
43100
- }
43101
- const value5 = Math.max(red2, green2, blue) * 2;
43102
- if (value5 === 0) {
43103
- return 30;
43104
- }
43105
- let result6 = 30 + (Math.round(blue) << 2 | Math.round(green2) << 1 | Math.round(red2));
43106
- if (value5 === 2) {
43107
- result6 += 60;
43108
- }
43109
- return result6;
43110
- },
43111
- enumerable: false
43112
- },
43113
- rgbToAnsi: {
43114
- value: (red2, green2, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red2, green2, blue)),
43115
- enumerable: false
43116
- },
43117
- hexToAnsi: {
43118
- value: (hex2) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex2)),
43119
- enumerable: false
43120
- }
43121
- });
43122
- return styles;
43123
- }
43124
- var ansiStyles = assembleStyles();
43125
- var ansi_styles_default = ansiStyles;
43126
-
43127
- // node_modules/.bun/wrap-ansi@10.0.2/node_modules/wrap-ansi/index.js
43128
- var ANSI_ESCAPE = "\x1B";
43129
- var ANSI_ESCAPE_BELL = "\x07";
43130
- var C1_CSI = "›";
43131
- var ANSI_CSI = "[";
43132
- var ANSI_OSC = "]";
43133
- var ANSI_SGR_TERMINATOR = "m";
43134
- var ANSI_SGR_RESET = 0;
43135
- var ANSI_SGR_RESET_FOREGROUND = 39;
43136
- var ANSI_SGR_RESET_BACKGROUND = 49;
43137
- var ANSI_SGR_RESET_UNDERLINE_COLOR = 59;
43138
- var ANSI_SGR_FOREGROUND_EXTENDED = 38;
43139
- var ANSI_SGR_BACKGROUND_EXTENDED = 48;
43140
- var ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;
43141
- var ANSI_SGR_COLOR_MODE_RGB = 2;
43142
- var ANSI_SGR_COLOR_MODE_256 = 5;
43143
- var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;`;
43144
- var ESCAPES = new Set([
43145
- ANSI_ESCAPE,
43146
- C1_CSI
43147
- ]);
43148
- var ESCAPE_CHARACTERS = [...ESCAPES].join("");
43149
- var CSI_INTRODUCER = `(?:${ANSI_ESCAPE}\\${ANSI_CSI}|${C1_CSI})`;
43150
- var CSI_PARAMETERS = "[0-?]*[ -/]*[@-~]";
43151
- var SGR_PARAMETERS = `(?<sgr>[0-9;:]*)${ANSI_SGR_TERMINATOR}`;
43152
- var OSC_STRING_TERMINATOR = `(?:${ANSI_ESCAPE_BELL}|${ANSI_ESCAPE}\\\\)`;
43153
- var OSC_STRING_PAYLOAD = String.raw`[^\u0000-\u001F\u007F-\u009F]*`;
43154
- var LINK_PARAMETERS = String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${OSC_STRING_PAYLOAD})${OSC_STRING_TERMINATOR}`;
43155
- var OSC_STRING = `${OSC_STRING_PAYLOAD}${OSC_STRING_TERMINATOR}`;
43156
- var ANSI_ESCAPE_REGEX = new RegExp(`${CSI_INTRODUCER}(?:${SGR_PARAMETERS}|${CSI_PARAMETERS})` + `|${ANSI_ESCAPE}\\${ANSI_OSC}(?:${LINK_PARAMETERS}|${OSC_STRING})`, "y");
43157
- var ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansi_styles_default.codes.values());
43158
- ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);
43159
- var segmenter2 = new Intl.Segmenter;
43160
- var getStringWidth = (string4) => stringWidth(string4, { countAnsiEscapeCodes: true });
43161
- var TAB_SIZE = 8;
43162
- var ESCAPE_INTRODUCER_REGEX = new RegExp(`[${ESCAPE_CHARACTERS}]`, "g");
43163
- var ROW_BOUNDARY_REGEX = new RegExp(`[\\n${ESCAPE_CHARACTERS}]`, "g");
43164
- var ASCII_PRINTABLE_REGEX = /^[ -~]*$/;
43165
- var wrapAnsiCode = (code) => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
43166
- var wrapAnsiHyperlink = (url, parameters = "") => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${parameters};${url}${ANSI_ESCAPE_BELL}`;
43167
- var matchAnsiEscape = (string4, index2) => {
43168
- if (!ESCAPES.has(string4[index2])) {
43169
- return;
43170
- }
43171
- ANSI_ESCAPE_REGEX.lastIndex = index2;
43172
- return ANSI_ESCAPE_REGEX.exec(string4) ?? undefined;
43173
- };
43174
- var forEachSegment = (string4, onPlainText, onEscape = () => {}) => {
43175
- let plainStart = 0;
43176
- let index2 = 0;
43177
- while (index2 < string4.length) {
43178
- ESCAPE_INTRODUCER_REGEX.lastIndex = index2;
43179
- const introducer = ESCAPE_INTRODUCER_REGEX.exec(string4);
43180
- if (!introducer) {
43181
- break;
43182
- }
43183
- const escape2 = matchAnsiEscape(string4, introducer.index);
43184
- if (!escape2) {
43185
- index2 = introducer.index + 1;
43186
- continue;
43187
- }
43188
- if (introducer.index > plainStart) {
43189
- onPlainText(string4.slice(plainStart, introducer.index));
43190
- }
43191
- onEscape(escape2[0]);
43192
- index2 = introducer.index + escape2[0].length;
43193
- plainStart = index2;
43590
+ onSeparator: (character, offset) => {
43591
+ if (character === ",")
43592
+ commas.push(offset);
43593
+ }
43594
+ }, parseOptions);
43595
+ return errors.length > 0 ? exports_Option.none() : exports_Option.some({ root: exports_Option.fromUndefinedOr(root), comments, commas });
43596
+ }
43597
+ function members(root) {
43598
+ return (root.children ?? []).flatMap((property) => {
43599
+ const [key, value5] = property.children ?? [];
43600
+ return key === undefined || value5 === undefined ? [] : [{ key, value: value5 }];
43601
+ });
43602
+ }
43603
+ function indentAt(text2, offset) {
43604
+ const prefix3 = text2.slice(text2.lastIndexOf(`
43605
+ `, offset - 1) + 1, offset);
43606
+ return /^[ \t]*$/.test(prefix3) ? exports_Option.some(prefix3) : exports_Option.none();
43607
+ }
43608
+ function lineBreak(text2, parsed, from, to) {
43609
+ let index2 = from;
43610
+ while (index2 < to) {
43611
+ const position = index2;
43612
+ const comment = parsed.comments.find((range3) => position >= range3.offset && position < range3.offset + range3.length);
43613
+ if (comment !== undefined)
43614
+ index2 = comment.offset + comment.length;
43615
+ else if (text2[index2] === `
43616
+ ` || text2[index2] === "\r" && text2[index2 + 1] === `
43617
+ `)
43618
+ return exports_Option.some(index2);
43619
+ else
43620
+ index2++;
43194
43621
  }
43195
- if (plainStart < string4.length) {
43196
- onPlainText(string4.slice(plainStart));
43622
+ return exports_Option.none();
43623
+ }
43624
+ function additions(text2, parsed, root, lines2) {
43625
+ const eol = text2.includes(`\r
43626
+ `) ? `\r
43627
+ ` : `
43628
+ `;
43629
+ const close3 = root.offset + root.length - 1;
43630
+ const last = members(root).at(-1);
43631
+ if (last === undefined) {
43632
+ const outer = exports_Option.getOrElse(indentAt(text2, root.offset), () => "");
43633
+ const body = lines2.map((line) => `${eol}${outer}${defaultIndent}${line}`).join(",");
43634
+ return [
43635
+ exports_Option.match(lineBreak(text2, parsed, root.offset + 1, close3), {
43636
+ onNone: () => ({ offset: root.offset + 1, length: 0, text: `${body}${eol}${outer}` }),
43637
+ onSome: (offset) => ({ offset, length: 0, text: body })
43638
+ })
43639
+ ];
43197
43640
  }
43198
- };
43199
- var getWidth = (string4) => {
43200
- let plainText = "";
43201
- forEachSegment(string4, (part) => {
43202
- plainText += part;
43203
- });
43204
- return getStringWidth(plainText);
43205
- };
43206
- var getTokens = (string4) => {
43207
- const tokens = [];
43208
- forEachSegment(string4, (plainText) => {
43209
- if (ASCII_PRINTABLE_REGEX.test(plainText)) {
43210
- for (const character of plainText) {
43211
- tokens.push({ value: character, width: 1 });
43641
+ const end3 = last.value.offset + last.value.length;
43642
+ const comma = parsed.commas.find((offset) => offset >= end3 && offset < close3);
43643
+ const indent = exports_Option.getOrElse(indentAt(text2, last.key.offset), () => defaultIndent);
43644
+ return exports_Option.match(lineBreak(text2, parsed, comma === undefined ? end3 : comma + 1, close3), {
43645
+ onNone: () => [
43646
+ comma === undefined ? { offset: end3, length: 0, text: lines2.map((line) => `, ${line}`).join("") } : { offset: comma + 1, length: 0, text: lines2.map((line) => ` ${line},`).join("") }
43647
+ ],
43648
+ onSome: (offset) => comma === undefined ? [
43649
+ {
43650
+ offset: end3,
43651
+ length: offset - end3,
43652
+ text: `,${text2.slice(end3, offset)}${lines2.map((line) => `${eol}${indent}${line}`).join(",")}`
43212
43653
  }
43213
- return;
43214
- }
43215
- for (const { segment } of segmenter2.segment(plainText)) {
43216
- tokens.push({ value: segment, width: getStringWidth(segment) });
43217
- }
43218
- }, (escape2) => {
43219
- tokens.push({ value: escape2, width: 0 });
43220
- });
43221
- return tokens;
43222
- };
43223
- var splitWords = (string4) => {
43224
- let currentWord = { value: "", plainText: "" };
43225
- const words = [currentWord];
43226
- forEachSegment(string4, (plainText) => {
43227
- const parts2 = plainText.split(" ");
43228
- currentWord.value += parts2[0];
43229
- currentWord.plainText += parts2[0];
43230
- for (let index2 = 1;index2 < parts2.length; index2++) {
43231
- currentWord = { value: parts2[index2], plainText: parts2[index2] };
43232
- words.push(currentWord);
43233
- }
43234
- }, (escape2) => {
43235
- currentWord.value += escape2;
43654
+ ] : [{ offset, length: 0, text: lines2.map((line) => `${eol}${indent}${line},`).join("") }]
43236
43655
  });
43237
- for (const word of words) {
43238
- word.width = getStringWidth(word.plainText);
43239
- }
43240
- return words;
43241
- };
43242
- var getColonColorToken = (parameter) => {
43243
- const parts2 = parameter.split(":");
43244
- const code = Number.parseInt(parts2[0], 10);
43245
- const mode = Number.parseInt(parts2[1], 10);
43246
- if (![ANSI_SGR_FOREGROUND_EXTENDED, ANSI_SGR_BACKGROUND_EXTENDED, ANSI_SGR_UNDERLINE_COLOR_EXTENDED].includes(code)) {
43247
- return;
43248
- }
43249
- if (mode === ANSI_SGR_COLOR_MODE_256 && parts2.length === 3 && /^\d+$/.test(parts2[2])) {
43250
- return { code, open: parameter, hasArguments: true };
43251
- }
43252
- if (mode !== ANSI_SGR_COLOR_MODE_RGB) {
43253
- return;
43254
- }
43255
- const components = parts2.length === 6 ? parts2.slice(3) : parts2.slice(2);
43256
- const colorSpace = parts2.length === 6 ? parts2[2] : undefined;
43257
- if (components.length === 3 && components.every((component) => /^\d+$/.test(component)) && (colorSpace === undefined || /^\d*$/.test(colorSpace))) {
43258
- return { code, open: parameter, hasArguments: true };
43656
+ }
43657
+ var spliced = (text2, splices) => splices.toSorted((a, b) => b.offset - a.offset).reduce((result6, splice) => `${result6.slice(0, splice.offset)}${splice.text}${result6.slice(splice.offset + splice.length)}`, text2);
43658
+ var others = (root, keys4) => members(root).filter(({ key }) => !keys4.has(String(key.value))).map(({ key, value: value5 }) => `${JSON.stringify(key.value)}=${JSON.stringify(getNodeValue2(value5))}`).join(`
43659
+ `);
43660
+ var holds = (root, properties) => properties.every(([key, value5]) => {
43661
+ const found = members(root).filter((member) => member.key.value === key);
43662
+ return found.length === 1 && found.every((member) => getNodeValue2(member.value) === value5);
43663
+ });
43664
+ function listed(root, key) {
43665
+ const found = members(root).filter((member2) => member2.key.value === key);
43666
+ const [member] = found;
43667
+ return found.length === 1 && member?.value.type === "array" ? exports_Option.some((member.value.children ?? []).map((item) => JSON.stringify(getNodeValue2(item)))) : exports_Option.none();
43668
+ }
43669
+ var includes = (result6, root, memberships) => memberships.every(([key, item]) => {
43670
+ const before = exports_Option.getOrElse(listed(root, key), () => []);
43671
+ const wanted = before.includes(JSON.stringify(item)) ? before : [...before, JSON.stringify(item)];
43672
+ return exports_Option.getOrElse(listed(result6, key), () => []).join(`
43673
+ `) === wanted.join(`
43674
+ `);
43675
+ });
43676
+ function setProperties(source, properties, memberships = []) {
43677
+ const mark = source.startsWith("\uFEFF") ? "\uFEFF" : "";
43678
+ const text2 = source.slice(mark.length);
43679
+ const keys4 = new Set([...properties, ...memberships].map(([key]) => key));
43680
+ const rendered = ([key, value5]) => `${JSON.stringify(key)}: ${JSON.stringify(value5)}`;
43681
+ const holding = ([key, item]) => `${JSON.stringify(key)}: [${JSON.stringify(item)}]`;
43682
+ const parsed = parse6(text2);
43683
+ if (exports_Option.isNone(parsed))
43684
+ return exports_Option.none();
43685
+ if (exports_Option.isNone(parsed.value.root)) {
43686
+ const eol = text2.includes(`\r
43687
+ `) ? `\r
43688
+ ` : `
43689
+ `;
43690
+ const lead = text2 === "" || text2.endsWith(`
43691
+ `) ? text2 : `${text2}${eol}`;
43692
+ const body = [...properties.map(rendered), ...memberships.map(holding)].map((line) => `${defaultIndent}${line}`);
43693
+ return exports_Option.some({
43694
+ text: `${mark}${lead}{${eol}${body.join(`,${eol}`)}${eol}}${eol}`,
43695
+ changes: properties.map(([key, value5]) => ({
43696
+ key,
43697
+ value: JSON.stringify(value5),
43698
+ previous: exports_Option.none()
43699
+ })),
43700
+ included: memberships
43701
+ });
43259
43702
  }
43260
- };
43261
- var getSgrTokens = (sgrParameters) => {
43262
- const parameters = sgrParameters.split(";");
43263
- const sgrTokens = [];
43264
- for (let index2 = 0;index2 < parameters.length; index2++) {
43265
- const parameter = parameters[index2];
43266
- if (parameter.includes(":")) {
43267
- const colonColorToken = getColonColorToken(parameter);
43268
- if (colonColorToken) {
43269
- sgrTokens.push(colonColorToken);
43270
- }
43271
- continue;
43272
- }
43273
- const code = parameter === "" ? ANSI_SGR_RESET : Number.parseInt(parameter, 10);
43274
- if (!Number.isFinite(code)) {
43703
+ const root = parsed.value.root.value;
43704
+ if (root.type !== "object")
43705
+ return exports_Option.none();
43706
+ const changes2 = [];
43707
+ const splices = [];
43708
+ const included = [];
43709
+ const missing2 = [];
43710
+ for (const property of properties) {
43711
+ const [key, value5] = property;
43712
+ const found = members(root).filter((member2) => member2.key.value === key);
43713
+ const [member] = found;
43714
+ if (found.length > 1)
43715
+ return exports_Option.none();
43716
+ if (member !== undefined && getNodeValue2(member.value) === value5)
43275
43717
  continue;
43276
- }
43277
- if (code === ANSI_SGR_FOREGROUND_EXTENDED || code === ANSI_SGR_BACKGROUND_EXTENDED || code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED) {
43278
- if (index2 + 1 >= parameters.length) {
43279
- break;
43280
- }
43281
- const mode = Number.parseInt(parameters[index2 + 1], 10);
43282
- const colorIndex = Number.parseInt(parameters[index2 + 2], 10);
43283
- if (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(colorIndex)) {
43284
- sgrTokens.push({ code, open: [code, mode, colorIndex].join(";"), hasArguments: true });
43285
- index2 += 2;
43286
- continue;
43287
- }
43288
- const red2 = Number.parseInt(parameters[index2 + 2], 10);
43289
- const green2 = Number.parseInt(parameters[index2 + 3], 10);
43290
- const blue = Number.parseInt(parameters[index2 + 4], 10);
43291
- if (mode === ANSI_SGR_COLOR_MODE_RGB && Number.isFinite(red2) && Number.isFinite(green2) && Number.isFinite(blue)) {
43292
- sgrTokens.push({ code, open: [code, mode, red2, green2, blue].join(";"), hasArguments: true });
43293
- index2 += 4;
43294
- continue;
43295
- }
43296
- break;
43297
- }
43298
- sgrTokens.push({ code, open: String(code), hasArguments: false });
43299
- }
43300
- return sgrTokens;
43301
- };
43302
- var removeActiveStyle = (activeStyles, family) => {
43303
- const activeStyleIndex = activeStyles.findIndex((activeStyle) => activeStyle.family === family);
43304
- if (activeStyleIndex !== -1) {
43305
- activeStyles.splice(activeStyleIndex, 1);
43306
- }
43307
- };
43308
- var upsertActiveStyle = (activeStyles, nextActiveStyle) => {
43309
- removeActiveStyle(activeStyles, nextActiveStyle.family);
43310
- activeStyles.push(nextActiveStyle);
43311
- };
43312
- var removeModifierStylesByClose = (activeStyles, closeCode) => {
43313
- for (let index2 = activeStyles.length - 1;index2 >= 0; index2--) {
43314
- const activeStyle = activeStyles[index2];
43315
- if (activeStyle.family.startsWith("modifier-") && activeStyle.close === closeCode) {
43316
- activeStyles.splice(index2, 1);
43317
- }
43318
- }
43319
- };
43320
- var getColorStyle = (sgrToken) => {
43321
- const { code, open: open3, hasArguments } = sgrToken;
43322
- if (code >= 30 && code <= 37 || code >= 90 && code <= 97 || code === ANSI_SGR_FOREGROUND_EXTENDED && hasArguments) {
43323
- return {
43324
- family: "foreground",
43325
- open: open3,
43326
- close: ANSI_SGR_RESET_FOREGROUND
43327
- };
43718
+ changes2.push({
43719
+ key,
43720
+ value: JSON.stringify(value5),
43721
+ previous: exports_Option.map(exports_Option.fromUndefinedOr(member), ({ value: node }) => text2.slice(node.offset, node.offset + node.length))
43722
+ });
43723
+ if (member === undefined)
43724
+ missing2.push(rendered(property));
43725
+ else
43726
+ splices.push({
43727
+ offset: member.value.offset,
43728
+ length: member.value.length,
43729
+ text: JSON.stringify(value5)
43730
+ });
43328
43731
  }
43329
- if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === ANSI_SGR_BACKGROUND_EXTENDED && hasArguments) {
43330
- return {
43331
- family: "background",
43332
- open: open3,
43333
- close: ANSI_SGR_RESET_BACKGROUND
43334
- };
43335
- }
43336
- if (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && hasArguments) {
43337
- return {
43338
- family: "underlineColor",
43339
- open: open3,
43340
- close: ANSI_SGR_RESET_UNDERLINE_COLOR
43341
- };
43342
- }
43343
- };
43344
- var applySgrResetCode = (code, activeStyles) => {
43345
- if (code === ANSI_SGR_RESET) {
43346
- activeStyles.length = 0;
43347
- return true;
43348
- }
43349
- if (code === ANSI_SGR_RESET_FOREGROUND) {
43350
- removeActiveStyle(activeStyles, "foreground");
43351
- return true;
43352
- }
43353
- if (code === ANSI_SGR_RESET_BACKGROUND) {
43354
- removeActiveStyle(activeStyles, "background");
43355
- return true;
43356
- }
43357
- if (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {
43358
- removeActiveStyle(activeStyles, "underlineColor");
43359
- return true;
43360
- }
43361
- if (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {
43362
- removeModifierStylesByClose(activeStyles, code);
43363
- return true;
43364
- }
43365
- return false;
43366
- };
43367
- var applySgrToken = (sgrToken, activeStyles) => {
43368
- const { code } = sgrToken;
43369
- if (applySgrResetCode(code, activeStyles)) {
43370
- return;
43371
- }
43372
- const colorStyle = getColorStyle(sgrToken);
43373
- if (colorStyle) {
43374
- upsertActiveStyle(activeStyles, colorStyle);
43375
- return;
43376
- }
43377
- const close3 = ansi_styles_default.codes.get(code);
43378
- if (close3 !== undefined && close3 !== ANSI_SGR_RESET) {
43379
- upsertActiveStyle(activeStyles, {
43380
- family: `modifier-${code}`,
43381
- open: sgrToken.open,
43382
- close: close3
43383
- });
43384
- }
43385
- };
43386
- var applySgrParameters = (sgrParameters, activeStyles) => {
43387
- for (const sgrToken of getSgrTokens(sgrParameters)) {
43388
- applySgrToken(sgrToken, activeStyles);
43389
- }
43390
- };
43391
- var applySgrResets = (sgrParameters, activeStyles) => {
43392
- for (const { code } of getSgrTokens(sgrParameters)) {
43393
- applySgrResetCode(code, activeStyles);
43394
- }
43395
- };
43396
- var applyLeadingSgrResets = (string4, startIndex, activeStyles) => {
43397
- let index2 = startIndex;
43398
- while (index2 < string4.length) {
43399
- const match10 = matchAnsiEscape(string4, index2);
43400
- if (!match10) {
43401
- break;
43402
- }
43403
- if (match10.groups.sgr !== undefined) {
43404
- applySgrResets(match10.groups.sgr, activeStyles);
43405
- }
43406
- index2 += match10[0].length;
43407
- }
43408
- };
43409
- var getClosingSgrSequence = (activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join("");
43410
- var getOpeningSgrSequence = (activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join("");
43411
- var wrapWord = (rows, word, columns, rowWidth) => {
43412
- const tokens = getTokens(word);
43413
- let visible = rowWidth;
43414
- for (let index2 = 0;index2 < tokens.length; index2++) {
43415
- const token = tokens[index2];
43416
- if (token.width > 0 && visible > 0 && visible + token.width > columns) {
43417
- rows.push("");
43418
- visible = 0;
43419
- }
43420
- rows[rows.length - 1] += token.value;
43421
- visible += token.width;
43422
- if (visible === columns && index2 < tokens.length - 1) {
43423
- rows.push("");
43424
- visible = 0;
43425
- }
43426
- }
43427
- if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
43428
- rows[rows.length - 2] += rows.pop();
43429
- }
43430
- return getWidth(rows.at(-1));
43431
- };
43432
- var stringVisibleTrimSpacesRight = (string4) => {
43433
- if (!string4.includes(" ")) {
43434
- return string4;
43435
- }
43436
- const segments = [];
43437
- forEachSegment(string4, (plainText) => {
43438
- segments.push({ value: plainText, isEscape: false });
43439
- }, (escape2) => {
43440
- segments.push({ value: escape2, isEscape: true });
43441
- });
43442
- for (let index2 = segments.length - 1;index2 >= 0; index2--) {
43443
- const segment = segments[index2];
43444
- if (segment.isEscape) {
43732
+ for (const membership of memberships) {
43733
+ const [key, item] = membership;
43734
+ const found = members(root).filter((member2) => member2.key.value === key);
43735
+ const [member] = found;
43736
+ if (found.length > 1 || member !== undefined && member.value.type !== "array")
43737
+ return exports_Option.none();
43738
+ const items = member?.value.children ?? [];
43739
+ if (items.some((node) => getNodeValue2(node) === item))
43445
43740
  continue;
43446
- }
43447
- let end3 = segment.value.length;
43448
- while (end3 > 0 && segment.value[end3 - 1] === " ") {
43449
- end3--;
43450
- }
43451
- segment.value = segment.value.slice(0, end3);
43452
- if (getStringWidth(segment.value) > 0) {
43453
- break;
43454
- }
43455
- }
43456
- return segments.map((segment) => segment.value).join("");
43457
- };
43458
- var expandTabs = (line) => {
43459
- if (!line.includes("\t")) {
43460
- return line;
43461
- }
43462
- let visible = 0;
43463
- let expandedLine = "";
43464
- let plainTextSinceTab = "";
43465
- const expandPlainText = (plainText) => {
43466
- const segments = plainText.split("\t");
43467
- for (const [index2, segment] of segments.entries()) {
43468
- expandedLine += segment;
43469
- plainTextSinceTab += segment;
43470
- if (index2 < segments.length - 1) {
43471
- visible += getStringWidth(plainTextSinceTab);
43472
- plainTextSinceTab = "";
43473
- const spaces = TAB_SIZE - visible % TAB_SIZE;
43474
- expandedLine += " ".repeat(spaces);
43475
- visible += spaces;
43476
- }
43477
- }
43478
- };
43479
- forEachSegment(line, expandPlainText, (escape2) => {
43480
- expandedLine += escape2;
43741
+ included.push(membership);
43742
+ const last = items.at(-1);
43743
+ if (member === undefined)
43744
+ missing2.push(holding(membership));
43745
+ else
43746
+ splices.push(last === undefined ? { offset: member.value.offset + 1, length: 0, text: JSON.stringify(item) } : { offset: last.offset + last.length, length: 0, text: `, ${JSON.stringify(item)}` });
43747
+ }
43748
+ if (missing2.length > 0)
43749
+ splices.push(...additions(text2, parsed.value, root, missing2));
43750
+ const edited = spliced(text2, splices);
43751
+ return exports_Option.flatMap(parse6(edited), (result6) => exports_Option.match(result6.root, {
43752
+ onNone: () => exports_Option.none(),
43753
+ onSome: (object) => object.type === "object" && holds(object, properties) && includes(object, root, memberships) && others(object, keys4) === others(root, keys4) ? exports_Option.some({ text: `${mark}${edited}`, changes: changes2, included }) : exports_Option.none()
43754
+ }));
43755
+ }
43756
+
43757
+ // packages/cli/src/schedule.ts
43758
+ import { homedir as homedir2, userInfo } from "node:os";
43759
+
43760
+ // packages/cli/src/settings.ts
43761
+ import { randomUUID } from "node:crypto";
43762
+ import { homedir, hostname } from "node:os";
43763
+ class SettingsError extends exports_Schema.TaggedError()("SettingsError", {
43764
+ message: exports_Schema.String
43765
+ }) {
43766
+ }
43767
+ var loopback = new Set(["localhost", "127.0.0.1", "[::1]"]);
43768
+ var ServerUrl = exports_Schema.URLFromString.check(exports_Schema.makeFilter((url) => url.protocol === "https:" || url.protocol === "http:" && loopback.has(url.hostname), { expected: "an https:// URL, or http:// on localhost" }));
43769
+ var SyncSettings = exports_Schema.Struct({
43770
+ server: exports_Schema.optionalKey(ServerUrl),
43771
+ token: exports_Schema.optionalKey(exports_Schema.RedactedFromValue(exports_Schema.NonEmptyString))
43772
+ });
43773
+ var configHome = exports_Effect.gen(function* () {
43774
+ const path = yield* exports_Path.Path;
43775
+ return yield* exports_Config.String("XDG_CONFIG_HOME").pipe(exports_Config.option, exports_Effect.map(exports_Option.filter((directory) => path.isAbsolute(directory))));
43776
+ });
43777
+ var settingsDirectory = exports_Effect.gen(function* () {
43778
+ const path = yield* exports_Path.Path;
43779
+ const home = homedir();
43780
+ const xdg = yield* configHome;
43781
+ const appData = yield* exports_Config.String("APPDATA").pipe(exports_Config.option);
43782
+ const root = exports_Option.getOrElse(xdg, () => exports_Match.value(process.platform).pipe(exports_Match.when("win32", () => exports_Option.getOrElse(appData, () => path.join(home, "AppData", "Roaming"))), exports_Match.when("darwin", () => path.join(home, "Library", "Application Support")), exports_Match.orElse(() => path.join(home, ".config"))));
43783
+ return path.join(root, "token-ledger");
43784
+ });
43785
+ var loadMachine = exports_Effect.fn("Settings.loadMachine")(function* (directory) {
43786
+ const fs = yield* exports_FileSystem.FileSystem;
43787
+ const path = yield* exports_Path.Path;
43788
+ const file2 = path.join(directory, "machine.json");
43789
+ const read2 = fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncMachine))), exports_Effect.mapError(() => new SettingsError({ message: `Cannot read ${file2}; fix or remove it.` })));
43790
+ if (yield* fs.exists(file2).pipe(exports_Effect.orElseSucceed(() => true)))
43791
+ return yield* read2;
43792
+ const machine = yield* SyncMachine.makeEffect({
43793
+ id: randomUUID(),
43794
+ label: hostname().trim() || "machine"
43795
+ }).pipe(exports_Effect.orDie);
43796
+ const created = yield* exports_Effect.gen(function* () {
43797
+ yield* fs.makeDirectory(directory, { recursive: true });
43798
+ const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
43799
+ directory,
43800
+ prefix: ".machine-"
43801
+ });
43802
+ const temporary = path.join(temporaryDirectory, "machine.json");
43803
+ yield* fs.writeFileString(temporary, `${JSON.stringify(machine, null, 2)}
43804
+ `, {
43805
+ flag: "wx",
43806
+ mode: 384
43807
+ });
43808
+ return yield* fs.link(temporary, file2).pipe(exports_Effect.as(true), exports_Effect.catchReason("PlatformError", "AlreadyExists", () => exports_Effect.succeed(false)));
43809
+ }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot create ${file2}.` })));
43810
+ return created ? machine : yield* read2;
43811
+ });
43812
+ var loadSyncSettings = exports_Effect.fn("Settings.loadSync")(function* (directory) {
43813
+ const fs = yield* exports_FileSystem.FileSystem;
43814
+ const path = yield* exports_Path.Path;
43815
+ const file2 = path.join(directory, "sync.json");
43816
+ const failure = new SettingsError({ message: `Cannot read or decode ${file2}.` });
43817
+ if (!(yield* fs.exists(file2).pipe(exports_Effect.mapError(() => failure))))
43818
+ return {};
43819
+ return yield* fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncSettings))), exports_Effect.mapError(() => failure));
43820
+ });
43821
+ var saveSyncSettings = exports_Effect.fn("Settings.saveSync")(function* (directory, server, token) {
43822
+ const fs = yield* exports_FileSystem.FileSystem;
43823
+ const path = yield* exports_Path.Path;
43824
+ const file2 = path.join(directory, "sync.json");
43825
+ yield* exports_Effect.gen(function* () {
43826
+ const settings = yield* exports_Schema.encodeEffect(SyncSettings)({ server, token });
43827
+ yield* fs.makeDirectory(directory, { recursive: true });
43828
+ const temporaryDirectory = yield* fs.makeTempDirectoryScoped({ directory, prefix: ".sync-" });
43829
+ const temporary = path.join(temporaryDirectory, "sync.json");
43830
+ yield* fs.writeFileString(temporary, `${JSON.stringify(settings, null, 2)}
43831
+ `, {
43832
+ flag: "wx",
43833
+ mode: 384
43834
+ });
43835
+ yield* fs.rename(temporary, file2);
43836
+ }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot save ${file2}.` })));
43837
+ return file2;
43838
+ });
43839
+
43840
+ // packages/cli/src/schedule.ts
43841
+ class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
43842
+ message: exports_Schema.String
43843
+ }) {
43844
+ }
43845
+ var TimeOfDay = exports_Schema.String.check(exports_Schema.isPattern(/^(?:[01]\d|2[0-3]):[0-5]\d$/));
43846
+ var Action3 = exports_Data.taggedEnum();
43847
+ var unit = "token-ledger-sync";
43848
+ var label = "com.github.ponbac.token-ledger.sync";
43849
+ var task = "token-ledger sync";
43850
+ var packageSpec = "@ponbac/token-ledger@latest";
43851
+ function run6(outcome, program, args2, hint = "") {
43852
+ return Action3.Run({
43853
+ program,
43854
+ args: args2,
43855
+ shown: [program, ...args2].join(" "),
43856
+ outcome,
43857
+ hint,
43858
+ gone: []
43481
43859
  });
43482
- return expandedLine;
43483
- };
43484
- var restoreStylesAcrossRows = (preString) => {
43485
- let returnValue = "";
43486
- let activeHyperlink;
43487
- const activeStyles = [];
43488
- let index2 = 0;
43489
- let copiedIndex = 0;
43490
- while (index2 < preString.length) {
43491
- ROW_BOUNDARY_REGEX.lastIndex = index2;
43492
- const boundary = ROW_BOUNDARY_REGEX.exec(preString);
43493
- if (!boundary) {
43494
- break;
43495
- }
43496
- index2 = boundary.index;
43497
- if (boundary[0] !== `
43498
- `) {
43499
- const escape2 = matchAnsiEscape(preString, index2);
43500
- if (!escape2) {
43501
- index2++;
43502
- continue;
43503
- }
43504
- const { groups } = escape2;
43505
- if (groups.sgr !== undefined) {
43506
- applySgrParameters(groups.sgr, activeStyles);
43507
- } else if (groups.uri !== undefined) {
43508
- activeHyperlink = groups.uri.length === 0 ? undefined : { parameters: groups.parameters, uri: groups.uri };
43509
- }
43510
- index2 += escape2[0].length;
43511
- continue;
43512
- }
43513
- returnValue += preString.slice(copiedIndex, index2);
43514
- if (index2 > copiedIndex) {
43515
- if (activeHyperlink) {
43516
- returnValue += wrapAnsiHyperlink("");
43860
+ }
43861
+ function quotable(job, forbidden2, described) {
43862
+ const offending = [job.nodeDirectory, ...exports_Option.toArray(job.configHome), ...job.flags].find((value5) => forbidden2.test(value5));
43863
+ return offending === undefined ? exports_Effect.succeed(job) : exports_Effect.fail(new ScheduleError({
43864
+ message: `Cannot schedule with ${JSON.stringify(offending)}: it contains ${described}.`
43865
+ }));
43866
+ }
43867
+ var posixWord = (value5) => /^[\w@+=:,./-]+$/.test(value5) ? value5 : `'${value5.replaceAll("'", "'\\''")}'`;
43868
+ var posixScript = (job) => [
43869
+ "cd /",
43870
+ ...exports_Option.toArray(job.configHome).map((directory) => `export XDG_CONFIG_HOME=${posixWord(directory)}`),
43871
+ `export PATH=${posixWord(job.nodeDirectory)}:"$PATH"`,
43872
+ `exec npx --yes ${packageSpec} ${["sync", ...job.flags].map(posixWord).join(" ")}`
43873
+ ].join("; ");
43874
+ var posixJob = (job) => quotable(job, /\p{Cc}/u, "a control character");
43875
+ var systemdQuoted = (value5) => `"${value5.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("%", "%%").replaceAll("$", () => "$$")}"`;
43876
+ function systemdTimer(directory) {
43877
+ const service4 = `${directory}/${unit}.service`;
43878
+ const timer = `${directory}/${unit}.timer`;
43879
+ const systemctl = (outcome, args2, hint = "") => run6(outcome, "systemctl", ["--user", ...args2], hint);
43880
+ return {
43881
+ name: "systemd user timer",
43882
+ install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => [
43883
+ systemctl("required", ["daemon-reload"], "A systemd user session is required; without one, add the cron entry from the README."),
43884
+ Action3.Write({
43885
+ file: service4,
43886
+ contents: `[Unit]
43887
+ Description=Upload AI usage to toki2
43888
+
43889
+ [Service]
43890
+ Type=oneshot
43891
+ ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
43892
+ `
43893
+ }),
43894
+ Action3.Write({
43895
+ file: timer,
43896
+ contents: `[Unit]
43897
+ Description=Daily AI usage sync
43898
+
43899
+ [Timer]
43900
+ OnCalendar=*-*-* ${job2.at}:00
43901
+ Persistent=true
43902
+ RandomizedDelaySec=10m
43903
+
43904
+ [Install]
43905
+ WantedBy=timers.target
43906
+ `
43907
+ }),
43908
+ systemctl("required", ["daemon-reload"]),
43909
+ systemctl("required", ["enable", `${unit}.timer`]),
43910
+ systemctl("required", ["restart", `${unit}.timer`])
43911
+ ])),
43912
+ uninstall: [
43913
+ systemctl("reported", ["disable", "--now", `${unit}.timer`]),
43914
+ systemctl("reported", ["clean", "--what=state", `${unit}.timer`]),
43915
+ Action3.Remove({ file: service4 }),
43916
+ Action3.Remove({ file: timer }),
43917
+ systemctl("reported", ["daemon-reload"]),
43918
+ Action3.Run({
43919
+ ...systemctl("absent", ["is-active", "--quiet", `${unit}.timer`], "Cannot confirm that the timer is gone; systemd's reason is shown above."),
43920
+ gone: [3, 4]
43921
+ })
43922
+ ],
43923
+ status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])]
43924
+ };
43925
+ }
43926
+ var xmlText = (value5) => value5.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
43927
+ function launchAgent(home, uid) {
43928
+ const plist = `${home}/Library/LaunchAgents/${label}.plist`;
43929
+ const log3 = `${home}/Library/Logs/${unit}.log`;
43930
+ const domain = `gui/${uid}`;
43931
+ return {
43932
+ name: "launchd agent",
43933
+ install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => {
43934
+ const [hour2, minute] = job2.at.split(":").map(Number);
43935
+ return [
43936
+ Action3.Write({
43937
+ file: plist,
43938
+ contents: `<?xml version="1.0" encoding="UTF-8"?>
43939
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
43940
+ <plist version="1.0">
43941
+ <dict>
43942
+ <key>Label</key>
43943
+ <string>${label}</string>
43944
+ <key>ProgramArguments</key>
43945
+ <array>
43946
+ <string>/bin/zsh</string>
43947
+ <string>-lc</string>
43948
+ <string>${xmlText(posixScript(job2))}</string>
43949
+ </array>
43950
+ <key>RunAtLoad</key>
43951
+ <true/>
43952
+ <key>StartCalendarInterval</key>
43953
+ <dict>
43954
+ <key>Hour</key>
43955
+ <integer>${hour2}</integer>
43956
+ <key>Minute</key>
43957
+ <integer>${minute}</integer>
43958
+ </dict>
43959
+ <key>StandardOutPath</key>
43960
+ <string>${xmlText(log3)}</string>
43961
+ <key>StandardErrorPath</key>
43962
+ <string>${xmlText(log3)}</string>
43963
+ </dict>
43964
+ </plist>
43965
+ `
43966
+ }),
43967
+ run6("silent", "launchctl", ["bootout", `${domain}/${label}`]),
43968
+ run6("required", "launchctl", ["bootstrap", domain, plist])
43969
+ ];
43970
+ })),
43971
+ uninstall: [
43972
+ run6("reported", "launchctl", ["bootout", `${domain}/${label}`]),
43973
+ Action3.Remove({ file: plist }),
43974
+ run6("absent", "launchctl", ["print", `${domain}/${label}`], "The agent is still loaded; launchd's reason is shown above.")
43975
+ ],
43976
+ status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])]
43977
+ };
43978
+ }
43979
+ var cmdWord = (value5) => /^[\w@+=:,./\\-]+$/.test(value5) ? value5 : `"${value5}"`;
43980
+ var powershellString = (value5) => `'${value5.replaceAll("'", "''")}'`;
43981
+ var powershellOptions = ["-NoProfile", "-NonInteractive", "-EncodedCommand"];
43982
+ var powershellArguments = (script) => [
43983
+ ...powershellOptions,
43984
+ Buffer.from(script, "utf16le").toString("base64")
43985
+ ];
43986
+ var taskScheduler = {
43987
+ name: "Task Scheduler task",
43988
+ install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
43989
+ const command = [
43990
+ ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
43991
+ `set "PATH=${job2.nodeDirectory};%PATH%"`,
43992
+ `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
43993
+ ].join(" && ");
43994
+ const script = [
43995
+ "$ErrorActionPreference = 'Stop'",
43996
+ "$ProgressPreference = 'SilentlyContinue'",
43997
+ `$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument ${powershellString(`/d /v:off /s /c "${command}"`)}`,
43998
+ `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
43999
+ "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44000
+ `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44001
+ ].join(`
44002
+ `);
44003
+ return [
44004
+ Action3.Run({
44005
+ program: "powershell.exe",
44006
+ args: powershellArguments(script),
44007
+ shown: `powershell.exe ${powershellOptions.join(" ")} <the script below, as UTF-16LE Base64>
44008
+ ${script}`,
44009
+ outcome: "required",
44010
+ hint: "",
44011
+ gone: []
44012
+ })
44013
+ ];
44014
+ })),
44015
+ uninstall: [
44016
+ run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44017
+ run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above.")
44018
+ ],
44019
+ status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
44020
+ };
44021
+ var hostScheduler = exports_Effect.gen(function* () {
44022
+ const path = yield* exports_Path.Path;
44023
+ const home = homedir2();
44024
+ const units = exports_Option.getOrElse(yield* configHome, () => path.join(home, ".config"));
44025
+ return yield* exports_Match.value(process.platform).pipe(exports_Match.when("linux", () => exports_Effect.succeed(systemdTimer(path.join(units, "systemd", "user")))), exports_Match.when("darwin", () => exports_Effect.succeed(launchAgent(home, userInfo().uid))), exports_Match.when("win32", () => exports_Effect.succeed(taskScheduler)), exports_Match.orElse((platform) => exports_Effect.fail(new ScheduleError({
44026
+ message: `No scheduler is supported on ${platform}; schedule token-ledger sync yourself.`
44027
+ }))));
44028
+ });
44029
+ var describe = (actions) => actions.map(Action3.$match({
44030
+ Write: ({ file: file2, contents }) => `write ${file2}
44031
+ ${contents.replaceAll(/^(?=.)/gm, " ")}`,
44032
+ Remove: ({ file: file2 }) => `remove ${file2}
44033
+ `,
44034
+ Run: ({ shown }) => `run ${shown}
44035
+ `
44036
+ })).join(`
44037
+ `);
44038
+ var perform = exports_Effect.fn("Schedule.perform")(function* (actions) {
44039
+ const fs = yield* exports_FileSystem.FileSystem;
44040
+ const path = yield* exports_Path.Path;
44041
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44042
+ for (const action of actions)
44043
+ yield* Action3.$match(action, {
44044
+ Write: ({ file: file2, contents }) => fs.makeDirectory(path.dirname(file2), { recursive: true }).pipe(exports_Effect.andThen(fs.writeFileString(file2, contents)), exports_Effect.mapError(() => new ScheduleError({ message: `Cannot write ${file2}.` }))),
44045
+ Remove: ({ file: file2 }) => fs.remove(file2, { force: true }).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot remove ${file2}.` }))),
44046
+ Run: ({ program, args: args2, outcome, hint, gone }) => {
44047
+ const output = outcome === "silent" || outcome === "absent" ? "ignore" : "inherit";
44048
+ const exit3 = spawner.exitCode(exports_ChildProcess.make(program, args2, { stdin: "ignore", stdout: output, stderr: output })).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot run ${program}. ${hint}`.trim() })));
44049
+ return exports_Match.value(outcome).pipe(exports_Match.when("required", () => exports_Effect.filterOrFail(exit3, (code) => code === 0, (code) => new ScheduleError({
44050
+ message: `${[program, ...args2.slice(0, 2)].join(" ")} failed with exit code ${code}. ${hint}`.trim()
44051
+ }))), exports_Match.when("reported", () => exit3), exports_Match.when("silent", () => exports_Effect.ignore(exit3)), exports_Match.when("absent", () => exit3.pipe(exports_Effect.map((code) => gone.length === 0 ? code !== 0 : gone.includes(code)), exports_Effect.orElseSucceed(() => true), exports_Effect.filterOrFail((confirmed) => confirmed, () => new ScheduleError({ message: hint })))), exports_Match.exhaustive);
43517
44052
  }
43518
- returnValue += getClosingSgrSequence(activeStyles);
43519
- }
43520
- returnValue += `
44053
+ });
44054
+ });
44055
+
44056
+ // packages/cli/src/copilot.ts
44057
+ class CopilotError extends exports_Schema.TaggedError()("CopilotError", {
44058
+ message: exports_Schema.String
44059
+ }) {
44060
+ }
44061
+ var variable = "COPILOT_OTEL_FILE_EXPORTER_PATH";
44062
+ var marker = "# Added by token-ledger copilot enable: Copilot CLI records its usage here.";
44063
+ var affectedVersion = "1.139.1";
44064
+ var builds = [
44065
+ { name: "VS Code", folder: "Code", file: "vscode-chat.jsonl" },
44066
+ { name: "VS Code Insiders", folder: "Code - Insiders", file: "vscode-insiders-chat.jsonl" }
44067
+ ];
44068
+ var placed = exports_Effect.fn("Copilot.placed")(function* (directory, file2) {
44069
+ const fs = yield* exports_FileSystem.FileSystem;
44070
+ const path = yield* exports_Path.Path;
44071
+ const resolved = (folder) => fs.realPath(folder).pipe(exports_Effect.orElseSucceed(() => folder));
44072
+ const relative = path.relative(yield* resolved(directory), path.join(yield* resolved(path.dirname(file2)), path.basename(file2)));
44073
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) ? exports_Option.some(relative) : exports_Option.none();
44074
+ });
44075
+ var copilotSources = exports_Effect.fn("Copilot.sources")(function* (directory, exporter) {
44076
+ if (exports_Option.isNone(exporter))
44077
+ return [directory];
44078
+ const relative = yield* placed(directory, exporter.value);
44079
+ if (exports_Option.isNone(relative))
44080
+ return [exporter.value];
44081
+ return /\.(?:jsonl|db)$/.test(relative.value) || relative.value === "" ? [directory] : [directory, exporter.value];
44082
+ });
44083
+ var Action4 = exports_Data.taggedEnum();
44084
+ var Step = exports_Data.taggedEnum();
44085
+ var indented = (text2, width2) => text2.replaceAll(/^(?=.)/gm, " ".repeat(width2));
44086
+ function assignedValue(assigned, home) {
44087
+ const text2 = assigned.trim();
44088
+ const single = /^'([^']*)'$/.exec(text2);
44089
+ if (single !== null)
44090
+ return exports_Option.fromUndefinedOr(single[1]);
44091
+ const double = /^"([^"\\`]*)"$/.exec(text2)?.[1];
44092
+ const bare = /^([^\s"'`\\;&|<>()#]+)$/.exec(text2)?.[1]?.replace(/^~(?=\/)/, () => home);
44093
+ const expanding = double ?? bare;
44094
+ if (expanding === undefined)
44095
+ return exports_Option.none();
44096
+ const expanded = expanding.replaceAll(/\$HOME\b|\$\{HOME\}/g, () => home);
44097
+ return expanded.includes("$") ? exports_Option.none() : exports_Option.some(expanded);
44098
+ }
44099
+ var touches = (line) => !/^\s*#/.test(line) && new RegExp(`(?<![$\\w{])${variable}\\b`).test(line);
44100
+ var StartupEdit = exports_Data.taggedEnum();
44101
+ var exportsTo = (target, home) => (line) => exports_Option.contains(exports_Option.flatMap(exports_Option.fromUndefinedOr(new RegExp(`^\\s*export\\s+${variable}=(.*)$`).exec(line)?.[1]), (assigned) => assignedValue(assigned, home)), target);
44102
+ function startupEdit(contents, wanted, satisfies) {
44103
+ const lines2 = contents.split(`
44104
+ `);
44105
+ const index2 = lines2.findLastIndex(touches);
44106
+ const current = lines2[index2];
44107
+ if (current === undefined) {
44108
+ const lead = contents === "" ? "" : contents.endsWith(`
44109
+ `) ? `
44110
+ ` : `
44111
+
43521
44112
  `;
43522
- index2++;
43523
- copiedIndex = index2;
43524
- if (index2 < preString.length && preString[index2] !== `
43525
- `) {
43526
- const openingStyles = [...activeStyles];
43527
- applyLeadingSgrResets(preString, index2, openingStyles);
43528
- returnValue += getOpeningSgrSequence(openingStyles);
43529
- if (activeHyperlink) {
43530
- returnValue += wrapAnsiHyperlink(activeHyperlink.uri, activeHyperlink.parameters);
43531
- }
43532
- }
44113
+ return exports_Option.some(StartupEdit.Append({ text: `${lead}${marker}
44114
+ ${wanted}
44115
+ ` }));
43533
44116
  }
43534
- return returnValue + preString.slice(copiedIndex);
43535
- };
43536
- var exec = (string4, columns, options3 = {}) => {
43537
- if (options3.trim !== false && string4.trim() === "") {
43538
- return "";
44117
+ if (current === wanted || satisfies(current))
44118
+ return exports_Option.none();
44119
+ return exports_Option.some(lines2[index2 - 1] === marker ? StartupEdit.Replace({ contents: lines2.with(index2, wanted).join(`
44120
+ `) }) : StartupEdit.Conflict({ line: index2 + 1, text: current.trim() }));
44121
+ }
44122
+ function homeWord(path, host, file2, quoted) {
44123
+ const relative = path.relative(host.home, file2);
44124
+ return /^(?!\.\.)[\w@+=:,./-]+$/.test(relative) && !path.isAbsolute(relative) ? `"$HOME/${relative}"` : quoted(file2);
44125
+ }
44126
+ var fishWord = (value5) => /^[\w@+=:,./-]+$/.test(value5) ? value5 : `'${value5.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
44127
+ var readOptional = exports_Effect.fn("Copilot.readOptional")(function* (file2) {
44128
+ const fs = yield* exports_FileSystem.FileSystem;
44129
+ return yield* fs.readFileString(file2).pipe(exports_Effect.map(exports_Option.some), exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.succeed(exports_Option.none())));
44130
+ });
44131
+ var bashStartup = exports_Effect.fn("Copilot.bashStartup")(function* (host) {
44132
+ const fs = yield* exports_FileSystem.FileSystem;
44133
+ const path = yield* exports_Path.Path;
44134
+ if (host.platform !== "darwin")
44135
+ return path.join(host.home, ".bashrc");
44136
+ for (const name of [".bash_profile", ".bash_login", ".profile"]) {
44137
+ const file2 = path.join(host.home, name);
44138
+ if (yield* fs.exists(file2).pipe(exports_Effect.orElseSucceed(() => false)))
44139
+ return file2;
43539
44140
  }
43540
- const words = splitWords(string4);
43541
- let rows = [""];
43542
- let rowLength = 0;
43543
- let trimmedRowIndex = -1;
43544
- let isFirstWord = true;
43545
- for (const word of words) {
43546
- const rowIndex = rows.length - 1;
43547
- if (options3.trim !== false && trimmedRowIndex !== rowIndex) {
43548
- const row = rows[rowIndex];
43549
- const trimmedRow = row.trimStart();
43550
- if (trimmedRow.length !== row.length) {
43551
- rows[rowIndex] = trimmedRow;
43552
- rowLength = getWidth(trimmedRow);
43553
- }
43554
- if (trimmedRow.length > 0) {
43555
- trimmedRowIndex = rowIndex;
43556
- }
43557
- }
43558
- if (isFirstWord) {
43559
- isFirstWord = false;
43560
- } else {
43561
- if (rowLength >= columns && (options3.wordWrap === false || options3.trim === false)) {
43562
- rows.push("");
43563
- rowLength = 0;
43564
- }
43565
- if (rowLength > 0 || options3.trim === false) {
43566
- rows[rows.length - 1] += " ";
43567
- rowLength++;
43568
- }
43569
- }
43570
- if (options3.hard && options3.wordWrap !== false && word.width > columns) {
43571
- const remainingColumns = columns - rowLength;
43572
- const breaksStartingThisLine = 1 + Math.floor((word.width - remainingColumns - 1) / columns);
43573
- const breaksStartingNextLine = Math.floor((word.width - 1) / columns);
43574
- if (breaksStartingNextLine < breaksStartingThisLine) {
43575
- rows.push("");
43576
- rowLength = 0;
43577
- }
43578
- rowLength = wrapWord(rows, word.value, columns, rowLength);
44141
+ return path.join(host.home, ".bash_profile");
44142
+ });
44143
+ var startupSteps = exports_Effect.fn("Copilot.startupSteps")(function* (host, target) {
44144
+ const fs = yield* exports_FileSystem.FileSystem;
44145
+ const path = yield* exports_Path.Path;
44146
+ const shell = exports_Option.match(host.shell, {
44147
+ onNone: () => "",
44148
+ onSome: (file3) => path.basename(file3)
44149
+ });
44150
+ const exported = `export ${variable}=${homeWord(path, host, target, posixWord)}`;
44151
+ const posix2 = (file3) => ({
44152
+ file: file3,
44153
+ line: exported,
44154
+ satisfies: exportsTo(target, host.home),
44155
+ others: []
44156
+ });
44157
+ const startup = yield* exports_Match.value(shell).pipe(exports_Match.when("zsh", () => exports_Effect.succeed(exports_Option.some(posix2(path.join(exports_Option.getOrElse(host.zshDirectory, () => host.home), ".zshrc"))))), exports_Match.when("bash", () => exports_Effect.map(bashStartup(host), (file3) => exports_Option.some(posix2(file3)))), exports_Match.when("fish", () => {
44158
+ const directory = path.join(exports_Option.getOrElse(host.configHome, () => path.join(host.home, ".config")), "fish");
44159
+ const line2 = `set -gx ${variable} ${homeWord(path, host, target, fishWord)}`;
44160
+ const snippets = path.join(directory, "conf.d");
44161
+ const file3 = path.join(snippets, "token-ledger-copilot.fish");
44162
+ return fs.readDirectory(snippets).pipe(exports_Effect.orElseSucceed(() => []), exports_Effect.map((names) => exports_Option.some({
44163
+ file: file3,
44164
+ line: line2,
44165
+ satisfies: (text2) => text2.trim() === line2,
44166
+ others: [
44167
+ ...names.toSorted((a, b) => a.localeCompare(b)).flatMap((name) => name.endsWith(".fish") && path.join(snippets, name) !== file3 ? [path.join(snippets, name)] : []),
44168
+ path.join(directory, "config.fish")
44169
+ ]
44170
+ })));
44171
+ }), exports_Match.orElse(() => exports_Effect.succeed(exports_Option.none())));
44172
+ if (exports_Option.isNone(startup))
44173
+ return [
44174
+ Step.ByHand({
44175
+ part: "cli",
44176
+ reason: shell === "" ? "SHELL is not set, so there is no startup file to choose." : `${shell} is not a shell this command sets up; it knows bash, zsh, and fish.`,
44177
+ instructions: `Add the equivalent of this line to your shell's startup file:
44178
+ ${indented(exported, 4)}`
44179
+ })
44180
+ ];
44181
+ const { file: file2, line, satisfies, others: others2 } = startup.value;
44182
+ const byHand = `Add this line to ${file2}:
44183
+ ${indented(line, 4)}`;
44184
+ const conflict = (where, found) => Step.ByHand({
44185
+ part: "cli",
44186
+ reason: `${where}, and was left alone:
44187
+ ${indented(found, 4)}`,
44188
+ instructions: `To record Copilot CLI usage where token-ledger reads it, change that line to:
44189
+ ${indented(line, 4)}`
44190
+ });
44191
+ const read2 = yield* exports_Effect.all([
44192
+ readOptional(file2),
44193
+ exports_Effect.forEach(others2, (other) => exports_Effect.map(readOptional(other), (text2) => ({
44194
+ other,
44195
+ found: exports_Option.getOrElse(text2, () => "").split(`
44196
+ `).find(touches)
44197
+ })))
44198
+ ]).pipe(exports_Effect.option);
44199
+ if (exports_Option.isNone(read2))
44200
+ return [Step.ByHand({ part: "cli", reason: `Cannot read ${file2}.`, instructions: byHand })];
44201
+ const [original, mentions] = read2.value;
44202
+ for (const { other, found } of mentions)
44203
+ if (found !== undefined)
44204
+ return [conflict(`${other} already sets ${variable}`, found.trim())];
44205
+ const existing = exports_Option.getOrElse(original, () => "");
44206
+ return [
44207
+ exports_Option.match(startupEdit(existing, line, satisfies), {
44208
+ onNone: () => Step.Kept({ part: "cli", summary: `${file2} already exports ${variable}.` }),
44209
+ onSome: StartupEdit.$match({
44210
+ Append: ({ text: text2 }) => Step.Change({
44211
+ part: "cli",
44212
+ summary: `${exports_Option.isSome(original) ? "add to the end of" : "create"} ${file2}`,
44213
+ detail: [marker, line],
44214
+ action: Action4.Write({ file: file2, contents: `${existing}${text2}`, original }),
44215
+ byHand
44216
+ }),
44217
+ Replace: ({ contents }) => Step.Change({
44218
+ part: "cli",
44219
+ summary: `correct the line this command added to ${file2}`,
44220
+ detail: [line],
44221
+ action: Action4.Write({ file: file2, contents, original }),
44222
+ byHand
44223
+ }),
44224
+ Conflict: ({ line: number4, text: text2 }) => conflict(`${file2} already sets ${variable} on line ${number4}`, text2)
44225
+ })
44226
+ })
44227
+ ];
44228
+ });
44229
+ var userVariableSteps = exports_Effect.fn("Copilot.userVariableSteps")(function* (target) {
44230
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44231
+ const assignment = `[Environment]::SetEnvironmentVariable(${powershellString(variable)}, ${powershellString(target)}, 'User')`;
44232
+ const byHand = `Run this in PowerShell:
44233
+ ${indented(assignment, 4)}`;
44234
+ const current = yield* spawner.string(exports_ChildProcess.make("powershell.exe", powershellArguments(`[Console]::Out.Write('value=' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string][Environment]::GetEnvironmentVariable(${powershellString(variable)}, 'User'))))`), { stdin: "ignore", stderr: "ignore" })).pipe(exports_Effect.map((output) => /^value=([A-Za-z0-9+/=]*)\s*$/.exec(output)?.[1]), exports_Effect.map(exports_Option.fromUndefinedOr), exports_Effect.orElseSucceed(() => exports_Option.none()), exports_Effect.map(exports_Option.map((encoded) => Buffer.from(encoded, "base64").toString("utf8"))));
44235
+ if (exports_Option.isNone(current))
44236
+ return [
44237
+ Step.ByHand({
44238
+ part: "cli",
44239
+ reason: `Cannot read the user environment variable ${variable} through PowerShell.`,
44240
+ instructions: byHand
44241
+ })
44242
+ ];
44243
+ const comparable = (file2) => file2.replaceAll("/", "\\").toLowerCase();
44244
+ return [
44245
+ comparable(current.value) === comparable(target) ? Step.Kept({
44246
+ part: "cli",
44247
+ summary: `The user environment variable ${variable} is already set.`
44248
+ }) : Step.Change({
44249
+ part: "cli",
44250
+ summary: `set the user environment variable ${variable}`,
44251
+ detail: [current.value === "" ? target : `${target} (now ${current.value})`],
44252
+ action: Action4.Run({
44253
+ program: "powershell.exe",
44254
+ args: powershellArguments([
44255
+ "$ErrorActionPreference = 'Stop'",
44256
+ "$ProgressPreference = 'SilentlyContinue'",
44257
+ assignment
44258
+ ].join(`
44259
+ `))
44260
+ }),
44261
+ byHand
44262
+ })
44263
+ ];
44264
+ });
44265
+ var installedVersion = exports_Effect.fn("Copilot.installedVersion")(function* (host) {
44266
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44267
+ const commands = host.platform === "win32" ? [exports_ChildProcess.make("cmd.exe", ["/d", "/s", "/c", "code --version"])] : [
44268
+ "code",
44269
+ ...host.platform === "darwin" ? ["/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"] : []
44270
+ ].map((program) => exports_ChildProcess.make(program, ["--version"]));
44271
+ for (const command of commands) {
44272
+ const version = yield* spawner.lines(command).pipe(exports_Effect.timeoutOption("5 seconds"), exports_Effect.map(exports_Option.flatMap((lines2) => exports_Option.fromUndefinedOr(lines2[0]))), exports_Effect.map(exports_Option.filter((line) => /^\d+\.\d+\.\d+$/.test(line))), exports_Effect.orElseSucceed(() => exports_Option.none()));
44273
+ if (exports_Option.isSome(version))
44274
+ return version;
44275
+ }
44276
+ return exports_Option.none();
44277
+ });
44278
+ var settingsSteps = exports_Effect.fn("Copilot.settingsSteps")(function* (host, directory) {
44279
+ const fs = yield* exports_FileSystem.FileSystem;
44280
+ const path = yield* exports_Path.Path;
44281
+ const root = exports_Match.value(host.platform).pipe(exports_Match.when("win32", () => exports_Option.getOrElse(host.appData, () => path.join(host.home, "AppData", "Roaming"))), exports_Match.when("darwin", () => path.join(host.home, "Library", "Application Support")), exports_Match.orElse(() => exports_Option.getOrElse(host.configHome, () => path.join(host.home, ".config"))));
44282
+ const properties = (file2) => [
44283
+ ["github.copilot.chat.otel.enabled", true],
44284
+ ["github.copilot.chat.otel.exporterType", "file"],
44285
+ ["github.copilot.chat.otel.outfile", path.join(directory, file2).replaceAll("\\", "/")],
44286
+ ["github.copilot.chat.otel.captureContent", false]
44287
+ ];
44288
+ const unsynced = [
44289
+ ["settingsSync.ignoredSettings", "github.copilot.chat.otel.outfile"]
44290
+ ];
44291
+ const unsyncing = unsynced.map(([key, item]) => `add ${JSON.stringify(item)} to the ${JSON.stringify(key)} list, so that Settings Sync does not copy this machine's path to your other machines`);
44292
+ const byHand = (lines2, lists) => [
44293
+ ...lines2.length === 0 ? [] : [
44294
+ `In VS Code, run "Preferences: Open User Settings (JSON)" from the Command Palette; in a profile other than the default, run "Preferences: Open Application Settings (JSON)" instead, where settings shared by all profiles are kept. Give each of these settings the value shown: change its line if the setting is already there, and paste the others on a new line right after the opening {
44295
+ ${indented(lines2.map((line) => `${line},`).join(`
44296
+ `), 4)}`
44297
+ ],
44298
+ ...lists.map((list) => `In the same file, ${list}.`)
44299
+ ].join(`
44300
+ `);
44301
+ const every4 = (file2) => byHand(properties(file2).map(([key, value5]) => `${JSON.stringify(key)}: ${JSON.stringify(value5)}`), unsyncing);
44302
+ const steps = [];
44303
+ for (const build2 of builds) {
44304
+ const user = path.join(root, build2.folder, "User");
44305
+ const file2 = path.join(user, "settings.json");
44306
+ if (!(yield* fs.exists(user).pipe(exports_Effect.orElseSucceed(() => false))))
43579
44307
  continue;
43580
- }
43581
- if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
43582
- if (options3.wordWrap === false && rowLength < columns) {
43583
- rowLength = wrapWord(rows, word.value, columns, rowLength);
43584
- continue;
43585
- }
43586
- rows.push("");
43587
- rowLength = 0;
43588
- }
43589
- if (rowLength + word.width > columns && options3.wordWrap === false) {
43590
- rowLength = wrapWord(rows, word.value, columns, rowLength);
44308
+ const original = yield* readOptional(file2).pipe(exports_Effect.option);
44309
+ if (exports_Option.isNone(original)) {
44310
+ steps.push(Step.ByHand({
44311
+ part: "vscode",
44312
+ reason: `Cannot read ${file2}.`,
44313
+ instructions: every4(build2.file)
44314
+ }));
43591
44315
  continue;
43592
44316
  }
43593
- rows[rows.length - 1] += word.value;
43594
- rowLength += word.width;
44317
+ steps.push(exports_Option.match(setProperties(exports_Option.getOrElse(original.value, () => ""), properties(build2.file), unsynced), {
44318
+ onNone: () => Step.ByHand({
44319
+ part: "vscode",
44320
+ reason: `${file2} has a syntax error, repeats one of these settings, or holds one in a form this command does not expect, so it was left alone.`,
44321
+ instructions: `Repair it first: VS Code marks what is wrong, and a repeated setting should be there once. Then run this command again, or finish by hand.
44322
+ ${every4(build2.file)}`
44323
+ }),
44324
+ onSome: ({ text: text2, changes: changes2, included }) => changes2.length === 0 && included.length === 0 ? Step.Kept({ part: "vscode", summary: `${file2} already has the export settings.` }) : Step.Change({
44325
+ part: "vscode",
44326
+ summary: `${exports_Option.isSome(original.value) ? "edit" : "create"} ${file2}`,
44327
+ detail: [
44328
+ ...changes2.map(({ key, value: value5, previous }) => `${JSON.stringify(key)}: ${value5}${exports_Option.match(previous, {
44329
+ onNone: () => "",
44330
+ onSome: (was) => ` (now ${was})`
44331
+ })}`),
44332
+ ...included.length === 0 ? [] : unsyncing
44333
+ ],
44334
+ action: Action4.Write({ file: file2, contents: text2, original: original.value }),
44335
+ byHand: byHand(changes2.map(({ key, value: value5 }) => `${JSON.stringify(key)}: ${value5}`), included.length === 0 ? [] : unsyncing)
44336
+ })
44337
+ }));
43595
44338
  }
43596
- if (options3.trim !== false) {
43597
- rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
44339
+ if (steps.length === 0)
44340
+ return [
44341
+ Step.ByHand({
44342
+ part: "vscode",
44343
+ reason: `No VS Code settings folder at ${path.join(root, builds[0].folder, "User")}.`,
44344
+ instructions: every4(builds[0].file)
44345
+ })
44346
+ ];
44347
+ if (exports_Option.contains(yield* installedVersion(host), affectedVersion))
44348
+ steps.push(Step.Note({
44349
+ part: "vscode",
44350
+ text: `VS Code ${affectedVersion} is installed. Its file export leaves out the repository, so Chat usage is counted but stays Unassigned. Update VS Code, or see "Workaround for VS Code's file exporter bug" in the token-ledger README.`
44351
+ }));
44352
+ return steps;
44353
+ });
44354
+ var plan = exports_Effect.fn("Copilot.plan")(function* (host, wanted) {
44355
+ const fs = yield* exports_FileSystem.FileSystem;
44356
+ const path = yield* exports_Path.Path;
44357
+ if (exports_Option.contains(host.uid, 0) && !wanted.allowRoot)
44358
+ return yield* new CopilotError({
44359
+ message: "Run this as yourself, without sudo. As root, the export folder, your shell startup file, and VS Code's settings would end up owned by root, and Copilot and VS Code could no longer write them. Nothing here needs admin rights. If root really is the account that runs Copilot, as in some containers, add --allow-root."
44360
+ });
44361
+ const directory = path.join(host.copilotHome, "otel");
44362
+ const target = path.join(directory, "usage.jsonl");
44363
+ const existing = yield* fs.stat(directory).pipe(exports_Effect.map((info2) => exports_Option.some(info2.type)), exports_Effect.orElseSucceed(() => exports_Option.none()));
44364
+ if (exports_Option.isSome(existing) && existing.value !== "Directory")
44365
+ return yield* new CopilotError({
44366
+ message: `${directory} exists but is not a folder, so Copilot cannot write its export there. Move it away, then run this again.`
44367
+ });
44368
+ for (const entry of [
44369
+ directory,
44370
+ ...wanted.cli ? [target] : [],
44371
+ ...wanted.vscode ? builds.map((build2) => path.join(directory, build2.file)) : []
44372
+ ]) {
44373
+ const folder = yield* fs.stat(entry).pipe(exports_Effect.map((info2) => entry !== directory && info2.type === "Directory"), exports_Effect.orElseSucceed(() => false));
44374
+ if (folder)
44375
+ return yield* new CopilotError({
44376
+ message: `${entry} is a folder, so Copilot cannot write its export to that name. Move it away, then run this again.`
44377
+ });
44378
+ const locked = yield* fs.access(entry, { writable: true }).pipe(exports_Effect.as(false), exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.succeed(false)), exports_Effect.orElseSucceed(() => true));
44379
+ if (locked)
44380
+ return yield* new CopilotError({
44381
+ message: `Your account cannot write to ${entry}, so Copilot could not record its usage there. Give your account write access to it, then run this again.${host.platform === "win32" ? "" : ` If it was created with sudo, take it back with: sudo chown -R "$(id -un)" ${posixWord(directory)}`}`
44382
+ });
43598
44383
  }
43599
- return restoreStylesAcrossRows(rows.join(`
43600
- `));
43601
- };
43602
- var normalizeText = (string4) => {
43603
- let normalizedString = "";
43604
- forEachSegment(string4, (plainText) => {
43605
- normalizedString += plainText.normalize();
43606
- }, (escape2) => {
43607
- normalizedString += escape2;
43608
- });
43609
- return normalizedString;
43610
- };
43611
- function wrapAnsi(string4, columns, options3) {
43612
- return normalizeText(String(string4)).replaceAll(`\r
43613
- `, `
43614
- `).split(`
43615
- `).map((line) => exec(expandTabs(line), columns, options3)).join(`
44384
+ const steps = [
44385
+ ...exports_Option.isSome(existing) ? [] : [
44386
+ Step.Change({
44387
+ part: "folder",
44388
+ summary: `create the folder ${directory}`,
44389
+ detail: [],
44390
+ action: Action4.MakeDirectory({ directory }),
44391
+ byHand: ""
44392
+ })
44393
+ ],
44394
+ ...wanted.cli ? yield* host.platform === "win32" ? userVariableSteps(target) : startupSteps(host, target) : [],
44395
+ ...wanted.vscode ? yield* settingsSteps(host, directory) : []
44396
+ ];
44397
+ const elsewhere = exports_Option.isSome(host.exporter) ? exports_Option.match(yield* placed(directory, host.exporter.value), {
44398
+ onNone: () => host.exporter,
44399
+ onSome: () => exports_Option.none()
44400
+ }) : exports_Option.none();
44401
+ const settled = steps.some((step) => step.part === "cli" && (Step.$is("Change")(step) || Step.$is("Kept")(step)));
44402
+ return {
44403
+ directory,
44404
+ steps: exports_Option.match(elsewhere, {
44405
+ onNone: () => steps,
44406
+ onSome: (file2) => [
44407
+ ...steps,
44408
+ Step.Note({
44409
+ part: "cli",
44410
+ text: `This terminal has ${variable} set to ${file2}, outside ${directory}. While it is, reports and syncs that see the variable read only that file and skip the exports in ${directory}, VS Code's among them. ${settled ? `Run them from a new terminal; if it still has that value, something else sets it, and should name ${target} instead.` : `Point it at ${target} to have both read.`}`
44411
+ })
44412
+ ]
44413
+ })
44414
+ };
44415
+ });
44416
+ var entries3 = (steps, tag4, render) => steps.flatMap((step) => Step.$is(tag4)(step) ? [indented(render(step), 2)] : []);
44417
+ var leftByHand = (steps) => entries3(steps, "ByHand", ({ reason, instructions }) => `${reason}
44418
+ ${instructions}`);
44419
+ var notes = (steps) => entries3(steps, "Note", ({ text: text2 }) => text2);
44420
+ var sections = (parts2) => parts2.flatMap(([title, lines2]) => lines2.length === 0 ? [] : [`${title}
44421
+
44422
+ ${lines2.join(lines2.some((line) => line.includes(`
44423
+ `)) ? `
44424
+
44425
+ ` : `
44426
+ `)}`]).join(`
44427
+
43616
44428
  `);
44429
+ var describe2 = (steps) => sections([
44430
+ [
44431
+ "Copilot records no usage until its local export is switched on. This will:",
44432
+ entries3(steps, "Change", ({ summary, detail }) => [summary, ...detail.map((line) => indented(line, 4))].join(`
44433
+ `))
44434
+ ],
44435
+ ["Already in place:", entries3(steps, "Kept", ({ summary }) => summary)],
44436
+ ["Left for you to do by hand:", leftByHand(steps)],
44437
+ ["Note:", notes(steps)]
44438
+ ]);
44439
+ var replaceFile = exports_Effect.fn("Copilot.replaceFile")(function* (file2, contents) {
44440
+ const fs = yield* exports_FileSystem.FileSystem;
44441
+ const path = yield* exports_Path.Path;
44442
+ yield* exports_Effect.gen(function* () {
44443
+ const target = yield* fs.realPath(file2).pipe(exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.matchEffect(fs.readLink(file2), {
44444
+ onFailure: () => exports_Effect.succeed(file2),
44445
+ onSuccess: (destination) => exports_Effect.fail(new CopilotError({
44446
+ message: `${file2} is a link to ${destination}, which does not exist, so it was left alone.`
44447
+ }))
44448
+ })));
44449
+ const mode = yield* fs.stat(target).pipe(exports_Effect.map((info2) => exports_Option.some(info2.mode & 4095)), exports_Effect.catchReason("PlatformError", "NotFound", () => exports_Effect.succeed(exports_Option.none())));
44450
+ yield* fs.makeDirectory(path.dirname(target), { recursive: true });
44451
+ const temporary = path.join(yield* fs.makeTempDirectoryScoped({
44452
+ directory: path.dirname(target),
44453
+ prefix: ".token-ledger-"
44454
+ }), path.basename(target));
44455
+ yield* fs.writeFileString(temporary, contents);
44456
+ if (exports_Option.isSome(mode))
44457
+ yield* fs.chmod(temporary, mode.value);
44458
+ yield* fs.rename(temporary, target);
44459
+ }).pipe(exports_Effect.scoped);
44460
+ });
44461
+ var perform2 = exports_Effect.fn("Copilot.perform")(function* (steps) {
44462
+ const fs = yield* exports_FileSystem.FileSystem;
44463
+ const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44464
+ const results2 = [];
44465
+ for (const step of steps) {
44466
+ if (!Step.$is("Change")(step)) {
44467
+ results2.push(step);
44468
+ continue;
44469
+ }
44470
+ const { part, summary, byHand } = step;
44471
+ const done4 = Step.Done({ part, summary });
44472
+ const failed = (reason) => Step.ByHand({ part, reason, instructions: byHand });
44473
+ results2.push(yield* Action4.$match(step.action, {
44474
+ MakeDirectory: ({ directory }) => fs.makeDirectory(directory, { recursive: true }).pipe(exports_Effect.as(done4), exports_Effect.mapError(() => new CopilotError({ message: `Cannot create ${directory}.` }))),
44475
+ Write: ({ file: file2, contents, original }) => exports_Effect.gen(function* () {
44476
+ if (exports_Option.getOrNull(yield* readOptional(file2)) !== exports_Option.getOrNull(original))
44477
+ return failed(`${file2} changed while this command was waiting. Run it again.`);
44478
+ yield* replaceFile(file2, contents);
44479
+ return done4;
44480
+ }).pipe(exports_Effect.catchTag("CopilotError", ({ message }) => exports_Effect.succeed(failed(message))), exports_Effect.orElseSucceed(() => failed(`Cannot write ${file2}.`))),
44481
+ Run: ({ program, args: args2 }) => spawner.exitCode(exports_ChildProcess.make(program, args2, {
44482
+ stdin: "ignore",
44483
+ stdout: "ignore",
44484
+ stderr: "inherit"
44485
+ })).pipe(exports_Effect.map((code) => code === 0 ? done4 : failed(`${program} could not ${summary}.`)), exports_Effect.orElseSucceed(() => failed(`Cannot run ${program}.`)))
44486
+ }));
44487
+ }
44488
+ return results2;
44489
+ });
44490
+ function summarize(steps, directory) {
44491
+ const changed = (part) => steps.some((step) => Step.$is("Done")(step) && step.part === part);
44492
+ const next2 = [
44493
+ ...changed("cli") ? ["Copilot CLI: open a new terminal before you start copilot."] : [],
44494
+ ...changed("vscode") ? [
44495
+ 'VS Code: run "Developer: Reload Window" in each open window, or restart VS Code, then start a new chat.'
44496
+ ] : []
44497
+ ];
44498
+ return sections([
44499
+ ["Done:", entries3(steps, "Done", ({ summary }) => summary)],
44500
+ ["Left for you to do by hand:", leftByHand(steps)],
44501
+ ["Note:", notes(steps)],
44502
+ [
44503
+ "Next:",
44504
+ next2.length === 0 ? [] : [
44505
+ ...next2,
44506
+ `Usage is recorded in ${directory} from then on; earlier sessions cannot be recovered.`,
44507
+ "Check it with: token-ledger report --provider copilot"
44508
+ ].map((line) => indented(line, 2))
44509
+ ]
44510
+ ]);
43617
44511
  }
43618
44512
 
43619
44513
  // packages/cli/src/format.ts
43620
- function csvCell(value5) {
43621
- const text2 = value5 === null ? "" : String(value5);
43622
- const safe = /^[=+\-@\t\r\n]/.test(text2) ? `'${text2}` : text2;
43623
- return `"${safe.replaceAll('"', '""')}"`;
43624
- }
43625
- function csv(report) {
43626
- const summary = projectSummary(report, false);
43627
- const headings = summary.headings.map((heading) => heading === "API estimate" ? "API estimate (USD)" : heading);
43628
- return [headings, ...summary.rows].map((row) => row.map(csvCell).join(",")).join(`
43629
- `);
43630
- }
43631
- function terminalText(value5) {
43632
- return value5.replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
44514
+ import { styleText } from "node:util";
44515
+ var import_cli_table3 = __toESM(require_table(), 1);
44516
+
44517
+ // node_modules/.bun/ansi-regex@6.3.0/node_modules/ansi-regex/index.js
44518
+ function ansiRegex({ onlyFirst = false } = {}) {
44519
+ const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
44520
+ const osc = `(?:\\u001B\\][^\\u0007\\u001B\\u009C]*${ST})`;
44521
+ const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
44522
+ const pattern = `${osc}|${csi}`;
44523
+ return new RegExp(pattern, onlyFirst ? undefined : "g");
43633
44524
  }
43634
- function projectSummary(report, grouped2) {
43635
- const projects = new Map;
43636
- for (const row of report.rows) {
43637
- const previous = projects.get(row.project);
43638
- projects.set(row.project, {
43639
- tokens: addTokens(previous?.tokens ?? zeroTokens, row.tokens),
43640
- cost: (previous?.cost ?? 0) + row.pricedCostUsd,
43641
- unpriced: (previous?.unpriced ?? 0) + row.unpricedRecords
43642
- });
44525
+
44526
+ // node_modules/.bun/strip-ansi@7.2.0/node_modules/strip-ansi/index.js
44527
+ var regex = ansiRegex();
44528
+ function stripAnsi2(string4) {
44529
+ if (typeof string4 !== "string") {
44530
+ throw new TypeError(`Expected a \`string\`, got \`${typeof string4}\``);
43643
44531
  }
43644
- const cost = [...projects.values()].reduce((sum3, project) => sum3 + project.cost, 0);
43645
- const unpriced = [...projects.values()].reduce((sum3, project) => sum3 + project.unpriced, 0);
43646
- const headings = [
43647
- "Project",
43648
- "Input",
43649
- "Cache read",
43650
- "Cache write",
43651
- "Output",
43652
- "API estimate",
43653
- unpriced ? "Known cost %" : "Cost %"
43654
- ];
43655
- const percentage = new Intl.NumberFormat("en-US", {
43656
- style: "percent",
43657
- minimumFractionDigits: 1,
43658
- maximumFractionDigits: 1
43659
- });
43660
- const share2 = (value5) => cost > 0 ? percentage.format(value5 / cost) : "—";
43661
- const number4 = new Intl.NumberFormat("en-US", { useGrouping: grouped2 });
43662
- const dollars = new Intl.NumberFormat("en-US", {
43663
- style: "currency",
43664
- currency: "USD",
43665
- useGrouping: grouped2
43666
- });
43667
- let allTokens = zeroTokens;
43668
- const rows = [];
43669
- const ranked = [...projects].toSorted(([leftProject, left], [rightProject, right]) => right.cost - left.cost || leftProject.localeCompare(rightProject));
43670
- for (const [project, total] of ranked) {
43671
- rows.push([
43672
- project,
43673
- number4.format(total.tokens.input),
43674
- number4.format(total.tokens.cacheRead),
43675
- number4.format(total.tokens.cacheWrite),
43676
- number4.format(total.tokens.output),
43677
- `${dollars.format(total.cost)}${total.unpriced ? " + unknown" : ""}`,
43678
- share2(total.cost)
43679
- ]);
43680
- allTokens = addTokens(allTokens, total.tokens);
44532
+ if (!string4.includes("\x1B") && !string4.includes("›")) {
44533
+ return string4;
43681
44534
  }
43682
- if (projects.size > 0)
43683
- rows.push([
43684
- "Total",
43685
- number4.format(allTokens.input),
43686
- number4.format(allTokens.cacheRead),
43687
- number4.format(allTokens.cacheWrite),
43688
- number4.format(allTokens.output),
43689
- `${dollars.format(cost)}${unpriced ? " + unknown" : ""}`,
43690
- share2(cost)
43691
- ]);
43692
- return { headings, rows, allTokens, unpriced, projectCount: projects.size };
44535
+ return string4.replace(regex, "");
43693
44536
  }
43694
- function table2(report, columns = 120, colorful = false) {
43695
- const paint = (format9, value5) => colorful ? styleText(format9, value5, { validateStream: false }) : value5;
43696
- const { headings, rows, allTokens, unpriced, projectCount } = projectSummary(report, true);
43697
- const number4 = new Intl.NumberFormat("en-US");
43698
- if (projectCount === 0)
43699
- return `No observed usage from ${report.since} through ${report.until} (${report.timeZone}).`;
43700
- const numericWidths = headings.slice(1).map((heading, i) => Math.max(heading.length, ...rows.map((row) => row[i + 1]?.length ?? 0)) + 2);
43701
- const projectWidth = columns - numericWidths.reduce((sum3, width2) => sum3 + width2, 0) - (headings.length + 1);
43702
- const narrow = projectWidth < 22;
43703
- const colWidths = narrow ? [16, Math.max(4, columns - 19)] : [Math.min(50, projectWidth), ...numericWidths];
43704
- const output = new import_cli_table3.default({
43705
- head: narrow ? [] : headings.map((heading) => paint(["bold", "cyan"], heading)),
43706
- colWidths,
43707
- colAligns: narrow ? ["left", "right"] : ["left", "right", "right", "right", "right", "right", "right"],
43708
- wordWrap: false,
43709
- style: { head: [], border: [] }
43710
- });
43711
- const projectColors = [
43712
- "cyan",
43713
- "blueBright",
43714
- "magenta",
43715
- "yellow",
43716
- "green",
43717
- "cyanBright"
43718
- ];
43719
- for (const [index2, row] of rows.entries()) {
43720
- const styled = row.map((value5, column) => {
43721
- const width2 = narrow ? column === 0 ? columns - 4 : columns - 21 : (colWidths[column] ?? 4) - 2;
43722
- const cell = wrapAnsi(terminalText(value5), Math.max(2, width2), {
43723
- hard: true,
43724
- wordWrap: false,
43725
- trim: false
43726
- });
43727
- if (index2 === rows.length - 1)
43728
- return paint(["bold", "magenta"], cell);
43729
- if (column === 0)
43730
- return paint(projectColors[index2 % projectColors.length] ?? "cyan", cell);
43731
- if (column >= headings.length - 2)
43732
- return paint(value5.includes("unknown") ? "yellow" : "green", cell);
43733
- return cell === "0" ? paint("dim", cell) : cell;
43734
- });
43735
- if (narrow) {
43736
- output.push([{ content: styled[0] ?? "", colSpan: 2, hAlign: "left" }]);
43737
- for (const [i, heading] of headings.slice(1).entries()) {
43738
- output.push([paint("cyan", heading), styled[i + 1] ?? ""]);
43739
- }
44537
+
44538
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup-data.js
44539
+ var ambiguousMinimalCodePoint = 161;
44540
+ var ambiguousMaximumCodePoint = 1114109;
44541
+ var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
44542
+ var fullwidthMinimalCodePoint = 12288;
44543
+ var fullwidthMaximumCodePoint = 65510;
44544
+ var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
44545
+ var wideMinimalCodePoint = 4352;
44546
+ var wideMaximumCodePoint = 262141;
44547
+ var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101594, 101631, 101664, 101760, 101874, 101888, 102801, 102816, 102866, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110888, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110952, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127406, 127406, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128729, 128732, 128735, 128747, 128748, 128756, 128764, 128986, 128986, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129734, 129736, 129736, 129740, 129757, 129759, 129771, 129775, 129786, 131072, 196605, 196608, 262141];
44548
+
44549
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/utilities.js
44550
+ var isInRange = (ranges, codePoint) => {
44551
+ let low = 0;
44552
+ let high = Math.floor(ranges.length / 2) - 1;
44553
+ while (low <= high) {
44554
+ const mid = Math.floor((low + high) / 2);
44555
+ const i = mid * 2;
44556
+ if (codePoint < ranges[i]) {
44557
+ high = mid - 1;
44558
+ } else if (codePoint > ranges[i + 1]) {
44559
+ low = mid + 1;
43740
44560
  } else {
43741
- output.push(styled);
44561
+ return true;
43742
44562
  }
43743
44563
  }
43744
- return [
43745
- `${paint(["bold", "cyan"], colorful ? "⚡ Token Ledger" : "Token Ledger")} · ${paint("dim", `${report.since} through ${report.until} (${report.timeZone})`)}`,
43746
- "",
43747
- output.toString(),
43748
- "",
43749
- paint("bold", `${colorful ? "\uD83D\uDCCA " : ""}${number4.format(totalTokens(allTokens))} observed tokens · ${number4.format(projectCount)} ${projectCount === 1 ? "project" : "projects"}`),
43750
- ...unpriced > 0 ? [
43751
- paint("yellow", "Incomplete pricing: sorting and percentages use known API subtotals; unknown costs are additional.")
43752
- ] : [],
43753
- paint("dim", "USD API-equivalent estimates; not your subscription bill.")
43754
- ].join(`
43755
- `);
43756
- }
43757
- function syncSummary(payload, request3, storedBuckets) {
43758
- const number4 = new Intl.NumberFormat("en-US");
43759
- const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
43760
- const sessions = new Set(payload.buckets.map((bucket) => bucket.sessionKey)).size;
43761
- const cost = payload.buckets.reduce((sum3, bucket) => sum3 + (bucket.estimatedCostUsd ?? 0), 0);
43762
- const unknown2 = payload.buckets.some((bucket) => bucket.estimatedCostUsd === null);
43763
- return [
43764
- `Synced ${terminalText(payload.machine.label)} · ${request3.since} through ${request3.until} (${payload.timeZone})`,
43765
- [
43766
- `${number4.format(payload.buckets.length)} hourly buckets`,
43767
- `${number4.format(sessions)} sessions`,
43768
- `${dollars.format(cost)}${unknown2 ? " + unknown" : ""} API estimate`,
43769
- exports_Option.match(storedBuckets, {
43770
- onNone: () => "accepted by the server",
43771
- onSome: (stored) => `server stored ${number4.format(stored)}`
43772
- })
43773
- ].join(" · ")
43774
- ].join(`
43775
- `);
43776
- }
44564
+ return false;
44565
+ };
43777
44566
 
43778
- // packages/cli/src/schedule.ts
43779
- import { homedir as homedir2, userInfo } from "node:os";
43780
- // packages/cli/src/settings.ts
43781
- import { randomUUID } from "node:crypto";
43782
- import { homedir, hostname } from "node:os";
43783
- class SettingsError extends exports_Schema.TaggedError()("SettingsError", {
43784
- message: exports_Schema.String
43785
- }) {
44567
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/lookup.js
44568
+ var commonCjkCodePoint = 19968;
44569
+ var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
44570
+ function findWideFastPathRange(ranges) {
44571
+ let fastPathStart = ranges[0];
44572
+ let fastPathEnd = ranges[1];
44573
+ for (let index2 = 0;index2 < ranges.length; index2 += 2) {
44574
+ const start = ranges[index2];
44575
+ const end3 = ranges[index2 + 1];
44576
+ if (commonCjkCodePoint >= start && commonCjkCodePoint <= end3) {
44577
+ return [start, end3];
44578
+ }
44579
+ if (end3 - start > fastPathEnd - fastPathStart) {
44580
+ fastPathStart = start;
44581
+ fastPathEnd = end3;
44582
+ }
44583
+ }
44584
+ return [fastPathStart, fastPathEnd];
43786
44585
  }
43787
- var loopback = new Set(["localhost", "127.0.0.1", "[::1]"]);
43788
- var ServerUrl = exports_Schema.URLFromString.check(exports_Schema.makeFilter((url) => url.protocol === "https:" || url.protocol === "http:" && loopback.has(url.hostname), { expected: "an https:// URL, or http:// on localhost" }));
43789
- var SyncSettings = exports_Schema.Struct({
43790
- server: exports_Schema.optionalKey(ServerUrl),
43791
- token: exports_Schema.optionalKey(exports_Schema.RedactedFromValue(exports_Schema.NonEmptyString))
43792
- });
43793
- var configHome = exports_Effect.gen(function* () {
43794
- const path = yield* exports_Path.Path;
43795
- return yield* exports_Config.String("XDG_CONFIG_HOME").pipe(exports_Config.option, exports_Effect.map(exports_Option.filter((directory) => path.isAbsolute(directory))));
43796
- });
43797
- var settingsDirectory = exports_Effect.gen(function* () {
43798
- const path = yield* exports_Path.Path;
43799
- const home = homedir();
43800
- const xdg = yield* configHome;
43801
- const appData = yield* exports_Config.String("APPDATA").pipe(exports_Config.option);
43802
- const root = exports_Option.getOrElse(xdg, () => exports_Match.value(process.platform).pipe(exports_Match.when("win32", () => exports_Option.getOrElse(appData, () => path.join(home, "AppData", "Roaming"))), exports_Match.when("darwin", () => path.join(home, "Library", "Application Support")), exports_Match.orElse(() => path.join(home, ".config"))));
43803
- return path.join(root, "token-ledger");
43804
- });
43805
- var loadMachine = exports_Effect.fn("Settings.loadMachine")(function* (directory) {
43806
- const fs = yield* exports_FileSystem.FileSystem;
43807
- const path = yield* exports_Path.Path;
43808
- const file2 = path.join(directory, "machine.json");
43809
- const read2 = fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncMachine))), exports_Effect.mapError(() => new SettingsError({ message: `Cannot read ${file2}; fix or remove it.` })));
43810
- if (yield* fs.exists(file2).pipe(exports_Effect.orElseSucceed(() => true)))
43811
- return yield* read2;
43812
- const machine = yield* SyncMachine.makeEffect({
43813
- id: randomUUID(),
43814
- label: hostname().trim() || "machine"
43815
- }).pipe(exports_Effect.orDie);
43816
- const created = yield* exports_Effect.gen(function* () {
43817
- yield* fs.makeDirectory(directory, { recursive: true });
43818
- const temporaryDirectory = yield* fs.makeTempDirectoryScoped({
43819
- directory,
43820
- prefix: ".machine-"
43821
- });
43822
- const temporary = path.join(temporaryDirectory, "machine.json");
43823
- yield* fs.writeFileString(temporary, `${JSON.stringify(machine, null, 2)}
43824
- `, {
43825
- flag: "wx",
43826
- mode: 384
43827
- });
43828
- return yield* fs.link(temporary, file2).pipe(exports_Effect.as(true), exports_Effect.catchReason("PlatformError", "AlreadyExists", () => exports_Effect.succeed(false)));
43829
- }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot create ${file2}.` })));
43830
- return created ? machine : yield* read2;
43831
- });
43832
- var loadSyncSettings = exports_Effect.fn("Settings.loadSync")(function* (directory) {
43833
- const fs = yield* exports_FileSystem.FileSystem;
43834
- const path = yield* exports_Path.Path;
43835
- const file2 = path.join(directory, "sync.json");
43836
- const failure = new SettingsError({ message: `Cannot read or decode ${file2}.` });
43837
- if (!(yield* fs.exists(file2).pipe(exports_Effect.mapError(() => failure))))
43838
- return {};
43839
- return yield* fs.readFileString(file2).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(SyncSettings))), exports_Effect.mapError(() => failure));
43840
- });
43841
- var saveSyncSettings = exports_Effect.fn("Settings.saveSync")(function* (directory, server, token) {
43842
- const fs = yield* exports_FileSystem.FileSystem;
43843
- const path = yield* exports_Path.Path;
43844
- const file2 = path.join(directory, "sync.json");
43845
- yield* exports_Effect.gen(function* () {
43846
- const settings = yield* exports_Schema.encodeEffect(SyncSettings)({ server, token });
43847
- yield* fs.makeDirectory(directory, { recursive: true });
43848
- const temporaryDirectory = yield* fs.makeTempDirectoryScoped({ directory, prefix: ".sync-" });
43849
- const temporary = path.join(temporaryDirectory, "sync.json");
43850
- yield* fs.writeFileString(temporary, `${JSON.stringify(settings, null, 2)}
43851
- `, {
43852
- flag: "wx",
43853
- mode: 384
43854
- });
43855
- yield* fs.rename(temporary, file2);
43856
- }).pipe(exports_Effect.scoped, exports_Effect.mapError(() => new SettingsError({ message: `Cannot save ${file2}.` })));
43857
- return file2;
43858
- });
44586
+ var isAmbiguous = (codePoint) => {
44587
+ if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) {
44588
+ return false;
44589
+ }
44590
+ return isInRange(ambiguousRanges, codePoint);
44591
+ };
44592
+ var isFullwidth = (codePoint) => {
44593
+ if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) {
44594
+ return false;
44595
+ }
44596
+ return isInRange(fullwidthRanges, codePoint);
44597
+ };
44598
+ var isWide = (codePoint) => {
44599
+ if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
44600
+ return true;
44601
+ }
44602
+ if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) {
44603
+ return false;
44604
+ }
44605
+ return isInRange(wideRanges, codePoint);
44606
+ };
43859
44607
 
43860
- // packages/cli/src/schedule.ts
43861
- class ScheduleError extends exports_Schema.TaggedError()("ScheduleError", {
43862
- message: exports_Schema.String
43863
- }) {
43864
- }
43865
- var TimeOfDay = exports_Schema.String.check(exports_Schema.isPattern(/^(?:[01]\d|2[0-3]):[0-5]\d$/));
43866
- var Action3 = exports_Data.taggedEnum();
43867
- var unit = "token-ledger-sync";
43868
- var label = "com.github.ponbac.token-ledger.sync";
43869
- var task = "token-ledger sync";
43870
- var packageSpec = "@ponbac/token-ledger@latest";
43871
- function run6(outcome, program, args2, hint = "") {
43872
- return Action3.Run({
43873
- program,
43874
- args: args2,
43875
- shown: [program, ...args2].join(" "),
43876
- outcome,
43877
- hint,
43878
- gone: []
43879
- });
44608
+ // node_modules/.bun/get-east-asian-width@1.7.0/node_modules/get-east-asian-width/index.js
44609
+ function validate3(codePoint) {
44610
+ if (!Number.isSafeInteger(codePoint)) {
44611
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
44612
+ }
43880
44613
  }
43881
- function quotable(job, forbidden2, described) {
43882
- const offending = [job.nodeDirectory, ...exports_Option.toArray(job.configHome), ...job.flags].find((value5) => forbidden2.test(value5));
43883
- return offending === undefined ? exports_Effect.succeed(job) : exports_Effect.fail(new ScheduleError({
43884
- message: `Cannot schedule with ${JSON.stringify(offending)}: it contains ${described}.`
43885
- }));
44614
+ function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
44615
+ validate3(codePoint);
44616
+ if (isFullwidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
44617
+ return 2;
44618
+ }
44619
+ return 1;
43886
44620
  }
43887
- var posixWord = (value5) => /^[\w@+=:,./-]+$/.test(value5) ? value5 : `'${value5.replaceAll("'", "'\\''")}'`;
43888
- var posixScript = (job) => [
43889
- "cd /",
43890
- ...exports_Option.toArray(job.configHome).map((directory) => `export XDG_CONFIG_HOME=${posixWord(directory)}`),
43891
- `export PATH=${posixWord(job.nodeDirectory)}:"$PATH"`,
43892
- `exec npx --yes ${packageSpec} ${["sync", ...job.flags].map(posixWord).join(" ")}`
43893
- ].join("; ");
43894
- var posixJob = (job) => quotable(job, /\p{Cc}/u, "a control character");
43895
- var systemdQuoted = (value5) => `"${value5.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("%", "%%").replaceAll("$", () => "$$")}"`;
43896
- function systemdTimer(directory) {
43897
- const service4 = `${directory}/${unit}.service`;
43898
- const timer = `${directory}/${unit}.timer`;
43899
- const systemctl = (outcome, args2, hint = "") => run6(outcome, "systemctl", ["--user", ...args2], hint);
43900
- return {
43901
- name: "systemd user timer",
43902
- install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => [
43903
- systemctl("required", ["daemon-reload"], "A systemd user session is required; without one, add the cron entry from the README."),
43904
- Action3.Write({
43905
- file: service4,
43906
- contents: `[Unit]
43907
- Description=Upload AI usage to toki2
43908
-
43909
- [Service]
43910
- Type=oneshot
43911
- ExecStart=/bin/sh -lc ${systemdQuoted(posixScript(job2))}
43912
- `
43913
- }),
43914
- Action3.Write({
43915
- file: timer,
43916
- contents: `[Unit]
43917
- Description=Daily AI usage sync
43918
-
43919
- [Timer]
43920
- OnCalendar=*-*-* ${job2.at}:00
43921
- Persistent=true
43922
- RandomizedDelaySec=10m
43923
44621
 
43924
- [Install]
43925
- WantedBy=timers.target
43926
- `
43927
- }),
43928
- systemctl("required", ["daemon-reload"]),
43929
- systemctl("required", ["enable", `${unit}.timer`]),
43930
- systemctl("required", ["restart", `${unit}.timer`])
43931
- ])),
43932
- uninstall: [
43933
- systemctl("reported", ["disable", "--now", `${unit}.timer`]),
43934
- systemctl("reported", ["clean", "--what=state", `${unit}.timer`]),
43935
- Action3.Remove({ file: service4 }),
43936
- Action3.Remove({ file: timer }),
43937
- systemctl("reported", ["daemon-reload"]),
43938
- Action3.Run({
43939
- ...systemctl("absent", ["is-active", "--quiet", `${unit}.timer`], "Cannot confirm that the timer is gone; systemd's reason is shown above."),
43940
- gone: [3, 4]
43941
- })
43942
- ],
43943
- status: [systemctl("reported", ["status", "--no-pager", `${unit}.timer`, `${unit}.service`])]
43944
- };
44622
+ // node_modules/.bun/string-width@8.2.2/node_modules/string-width/index.js
44623
+ var segmenter = new Intl.Segmenter;
44624
+ var zeroWidthClusterRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Nonspacing_Mark}|\p{Enclosing_Mark}|\p{Surrogate})+$/v;
44625
+ var leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]+/v;
44626
+ var spacingMarkRegex = /\p{Spacing_Mark}/v;
44627
+ var rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
44628
+ var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
44629
+ var extendedPictographicRegex = /\p{Extended_Pictographic}/gu;
44630
+ function isDoubleWidthNonRgiEmojiSequence(segment) {
44631
+ if (segment.length > 50) {
44632
+ return false;
44633
+ }
44634
+ if (unqualifiedKeycapRegex.test(segment)) {
44635
+ return true;
44636
+ }
44637
+ if (segment.includes("‍")) {
44638
+ const pictographics = segment.match(extendedPictographicRegex);
44639
+ return pictographics !== null && pictographics.length >= 2;
44640
+ }
44641
+ return false;
43945
44642
  }
43946
- var xmlText = (value5) => value5.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
43947
- function launchAgent(home, uid) {
43948
- const plist = `${home}/Library/LaunchAgents/${label}.plist`;
43949
- const log3 = `${home}/Library/Logs/${unit}.log`;
43950
- const domain = `gui/${uid}`;
43951
- return {
43952
- name: "launchd agent",
43953
- install: (job) => posixJob(job).pipe(exports_Effect.map((job2) => {
43954
- const [hour2, minute] = job2.at.split(":").map(Number);
43955
- return [
43956
- Action3.Write({
43957
- file: plist,
43958
- contents: `<?xml version="1.0" encoding="UTF-8"?>
43959
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
43960
- <plist version="1.0">
43961
- <dict>
43962
- <key>Label</key>
43963
- <string>${label}</string>
43964
- <key>ProgramArguments</key>
43965
- <array>
43966
- <string>/bin/zsh</string>
43967
- <string>-lc</string>
43968
- <string>${xmlText(posixScript(job2))}</string>
43969
- </array>
43970
- <key>RunAtLoad</key>
43971
- <true/>
43972
- <key>StartCalendarInterval</key>
43973
- <dict>
43974
- <key>Hour</key>
43975
- <integer>${hour2}</integer>
43976
- <key>Minute</key>
43977
- <integer>${minute}</integer>
43978
- </dict>
43979
- <key>StandardOutPath</key>
43980
- <string>${xmlText(log3)}</string>
43981
- <key>StandardErrorPath</key>
43982
- <string>${xmlText(log3)}</string>
43983
- </dict>
43984
- </plist>
43985
- `
43986
- }),
43987
- run6("silent", "launchctl", ["bootout", `${domain}/${label}`]),
43988
- run6("required", "launchctl", ["bootstrap", domain, plist])
43989
- ];
43990
- })),
43991
- uninstall: [
43992
- run6("reported", "launchctl", ["bootout", `${domain}/${label}`]),
43993
- Action3.Remove({ file: plist }),
43994
- run6("absent", "launchctl", ["print", `${domain}/${label}`], "The agent is still loaded; launchd's reason is shown above.")
43995
- ],
43996
- status: [run6("reported", "launchctl", ["print", `${domain}/${label}`])]
43997
- };
44643
+ function baseVisible(segment) {
44644
+ return segment.replace(leadingNonPrintingRegex, "");
44645
+ }
44646
+ function isZeroWidthCluster(segment) {
44647
+ return zeroWidthClusterRegex.test(segment);
44648
+ }
44649
+ function isHangulLeadingJamo(codePoint) {
44650
+ return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
44651
+ }
44652
+ function isHangulVowelJamo(codePoint) {
44653
+ return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
44654
+ }
44655
+ function isHangulTrailingJamo(codePoint) {
44656
+ return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
44657
+ }
44658
+ function isHangulJamo(codePoint) {
44659
+ return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
44660
+ }
44661
+ function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
44662
+ const codePoints = [];
44663
+ for (const character of visibleSegment) {
44664
+ if (zeroWidthClusterRegex.test(character)) {
44665
+ continue;
44666
+ }
44667
+ codePoints.push(character.codePointAt(0));
44668
+ }
44669
+ if (codePoints.length === 0) {
44670
+ return;
44671
+ }
44672
+ let width2 = 0;
44673
+ for (let index2 = 0;index2 < codePoints.length; index2++) {
44674
+ const codePoint = codePoints[index2];
44675
+ if (!isHangulJamo(codePoint)) {
44676
+ if (width2 === 0) {
44677
+ return;
44678
+ }
44679
+ for (let remaining = index2;remaining < codePoints.length; remaining++) {
44680
+ width2 += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
44681
+ }
44682
+ return width2;
44683
+ }
44684
+ if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index2 + 1])) {
44685
+ width2 += 2;
44686
+ index2 += isHangulTrailingJamo(codePoints[index2 + 2]) ? 2 : 1;
44687
+ continue;
44688
+ }
44689
+ width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
44690
+ }
44691
+ return width2;
44692
+ }
44693
+ function trailingWidth(visibleSegment, eastAsianWidthOptions) {
44694
+ let extra = 0;
44695
+ let first = true;
44696
+ for (const character of visibleSegment) {
44697
+ if (first) {
44698
+ first = false;
44699
+ continue;
44700
+ }
44701
+ if (spacingMarkRegex.test(character) || character >= "＀" && character <= "￯") {
44702
+ extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
44703
+ }
44704
+ }
44705
+ return extra;
44706
+ }
44707
+ function stringWidth(input, options3 = {}) {
44708
+ if (typeof input !== "string" || input.length === 0) {
44709
+ return 0;
44710
+ }
44711
+ const {
44712
+ ambiguousIsNarrow = true,
44713
+ countAnsiEscapeCodes = false
44714
+ } = options3;
44715
+ let string4 = input;
44716
+ if (!countAnsiEscapeCodes && (string4.includes("\x1B") || string4.includes("›"))) {
44717
+ string4 = stripAnsi2(string4);
44718
+ }
44719
+ if (string4.length === 0) {
44720
+ return 0;
44721
+ }
44722
+ if (/^[\u0020-\u007E]*$/.test(string4)) {
44723
+ return string4.length;
44724
+ }
44725
+ let width2 = 0;
44726
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
44727
+ for (const { segment } of segmenter.segment(string4)) {
44728
+ if (isZeroWidthCluster(segment)) {
44729
+ continue;
44730
+ }
44731
+ if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
44732
+ width2 += 2;
44733
+ continue;
44734
+ }
44735
+ const visibleSegment = baseVisible(segment);
44736
+ const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
44737
+ if (hangulWidth !== undefined) {
44738
+ width2 += hangulWidth;
44739
+ continue;
44740
+ }
44741
+ const codePoint = visibleSegment.codePointAt(0);
44742
+ width2 += eastAsianWidth(codePoint, eastAsianWidthOptions);
44743
+ width2 += trailingWidth(visibleSegment, eastAsianWidthOptions);
44744
+ }
44745
+ return width2;
44746
+ }
44747
+
44748
+ // node_modules/.bun/ansi-styles@6.2.3/node_modules/ansi-styles/index.js
44749
+ var ANSI_BACKGROUND_OFFSET = 10;
44750
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
44751
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
44752
+ var wrapAnsi16m = (offset = 0) => (red2, green2, blue) => `\x1B[${38 + offset};2;${red2};${green2};${blue}m`;
44753
+ var styles = {
44754
+ modifier: {
44755
+ reset: [0, 0],
44756
+ bold: [1, 22],
44757
+ dim: [2, 22],
44758
+ italic: [3, 23],
44759
+ underline: [4, 24],
44760
+ overline: [53, 55],
44761
+ inverse: [7, 27],
44762
+ hidden: [8, 28],
44763
+ strikethrough: [9, 29]
44764
+ },
44765
+ color: {
44766
+ black: [30, 39],
44767
+ red: [31, 39],
44768
+ green: [32, 39],
44769
+ yellow: [33, 39],
44770
+ blue: [34, 39],
44771
+ magenta: [35, 39],
44772
+ cyan: [36, 39],
44773
+ white: [37, 39],
44774
+ blackBright: [90, 39],
44775
+ gray: [90, 39],
44776
+ grey: [90, 39],
44777
+ redBright: [91, 39],
44778
+ greenBright: [92, 39],
44779
+ yellowBright: [93, 39],
44780
+ blueBright: [94, 39],
44781
+ magentaBright: [95, 39],
44782
+ cyanBright: [96, 39],
44783
+ whiteBright: [97, 39]
44784
+ },
44785
+ bgColor: {
44786
+ bgBlack: [40, 49],
44787
+ bgRed: [41, 49],
44788
+ bgGreen: [42, 49],
44789
+ bgYellow: [43, 49],
44790
+ bgBlue: [44, 49],
44791
+ bgMagenta: [45, 49],
44792
+ bgCyan: [46, 49],
44793
+ bgWhite: [47, 49],
44794
+ bgBlackBright: [100, 49],
44795
+ bgGray: [100, 49],
44796
+ bgGrey: [100, 49],
44797
+ bgRedBright: [101, 49],
44798
+ bgGreenBright: [102, 49],
44799
+ bgYellowBright: [103, 49],
44800
+ bgBlueBright: [104, 49],
44801
+ bgMagentaBright: [105, 49],
44802
+ bgCyanBright: [106, 49],
44803
+ bgWhiteBright: [107, 49]
44804
+ }
44805
+ };
44806
+ var modifierNames = Object.keys(styles.modifier);
44807
+ var foregroundColorNames = Object.keys(styles.color);
44808
+ var backgroundColorNames = Object.keys(styles.bgColor);
44809
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
44810
+ function assembleStyles() {
44811
+ const codes2 = new Map;
44812
+ for (const [groupName, group2] of Object.entries(styles)) {
44813
+ for (const [styleName, style] of Object.entries(group2)) {
44814
+ styles[styleName] = {
44815
+ open: `\x1B[${style[0]}m`,
44816
+ close: `\x1B[${style[1]}m`
44817
+ };
44818
+ group2[styleName] = styles[styleName];
44819
+ codes2.set(style[0], style[1]);
44820
+ }
44821
+ Object.defineProperty(styles, groupName, {
44822
+ value: group2,
44823
+ enumerable: false
44824
+ });
44825
+ }
44826
+ Object.defineProperty(styles, "codes", {
44827
+ value: codes2,
44828
+ enumerable: false
44829
+ });
44830
+ styles.color.close = "\x1B[39m";
44831
+ styles.bgColor.close = "\x1B[49m";
44832
+ styles.color.ansi = wrapAnsi16();
44833
+ styles.color.ansi256 = wrapAnsi256();
44834
+ styles.color.ansi16m = wrapAnsi16m();
44835
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
44836
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
44837
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
44838
+ Object.defineProperties(styles, {
44839
+ rgbToAnsi256: {
44840
+ value(red2, green2, blue) {
44841
+ if (red2 === green2 && green2 === blue) {
44842
+ if (red2 < 8) {
44843
+ return 16;
44844
+ }
44845
+ if (red2 > 248) {
44846
+ return 231;
44847
+ }
44848
+ return Math.round((red2 - 8) / 247 * 24) + 232;
44849
+ }
44850
+ return 16 + 36 * Math.round(red2 / 255 * 5) + 6 * Math.round(green2 / 255 * 5) + Math.round(blue / 255 * 5);
44851
+ },
44852
+ enumerable: false
44853
+ },
44854
+ hexToRgb: {
44855
+ value(hex2) {
44856
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex2.toString(16));
44857
+ if (!matches) {
44858
+ return [0, 0, 0];
44859
+ }
44860
+ let [colorString] = matches;
44861
+ if (colorString.length === 3) {
44862
+ colorString = [...colorString].map((character) => character + character).join("");
44863
+ }
44864
+ const integer = Number.parseInt(colorString, 16);
44865
+ return [
44866
+ integer >> 16 & 255,
44867
+ integer >> 8 & 255,
44868
+ integer & 255
44869
+ ];
44870
+ },
44871
+ enumerable: false
44872
+ },
44873
+ hexToAnsi256: {
44874
+ value: (hex2) => styles.rgbToAnsi256(...styles.hexToRgb(hex2)),
44875
+ enumerable: false
44876
+ },
44877
+ ansi256ToAnsi: {
44878
+ value(code) {
44879
+ if (code < 8) {
44880
+ return 30 + code;
44881
+ }
44882
+ if (code < 16) {
44883
+ return 90 + (code - 8);
44884
+ }
44885
+ let red2;
44886
+ let green2;
44887
+ let blue;
44888
+ if (code >= 232) {
44889
+ red2 = ((code - 232) * 10 + 8) / 255;
44890
+ green2 = red2;
44891
+ blue = red2;
44892
+ } else {
44893
+ code -= 16;
44894
+ const remainder2 = code % 36;
44895
+ red2 = Math.floor(code / 36) / 5;
44896
+ green2 = Math.floor(remainder2 / 6) / 5;
44897
+ blue = remainder2 % 6 / 5;
44898
+ }
44899
+ const value5 = Math.max(red2, green2, blue) * 2;
44900
+ if (value5 === 0) {
44901
+ return 30;
44902
+ }
44903
+ let result6 = 30 + (Math.round(blue) << 2 | Math.round(green2) << 1 | Math.round(red2));
44904
+ if (value5 === 2) {
44905
+ result6 += 60;
44906
+ }
44907
+ return result6;
44908
+ },
44909
+ enumerable: false
44910
+ },
44911
+ rgbToAnsi: {
44912
+ value: (red2, green2, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red2, green2, blue)),
44913
+ enumerable: false
44914
+ },
44915
+ hexToAnsi: {
44916
+ value: (hex2) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex2)),
44917
+ enumerable: false
44918
+ }
44919
+ });
44920
+ return styles;
44921
+ }
44922
+ var ansiStyles = assembleStyles();
44923
+ var ansi_styles_default = ansiStyles;
44924
+
44925
+ // node_modules/.bun/wrap-ansi@10.0.2/node_modules/wrap-ansi/index.js
44926
+ var ANSI_ESCAPE = "\x1B";
44927
+ var ANSI_ESCAPE_BELL = "\x07";
44928
+ var C1_CSI = "›";
44929
+ var ANSI_CSI = "[";
44930
+ var ANSI_OSC = "]";
44931
+ var ANSI_SGR_TERMINATOR = "m";
44932
+ var ANSI_SGR_RESET = 0;
44933
+ var ANSI_SGR_RESET_FOREGROUND = 39;
44934
+ var ANSI_SGR_RESET_BACKGROUND = 49;
44935
+ var ANSI_SGR_RESET_UNDERLINE_COLOR = 59;
44936
+ var ANSI_SGR_FOREGROUND_EXTENDED = 38;
44937
+ var ANSI_SGR_BACKGROUND_EXTENDED = 48;
44938
+ var ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;
44939
+ var ANSI_SGR_COLOR_MODE_RGB = 2;
44940
+ var ANSI_SGR_COLOR_MODE_256 = 5;
44941
+ var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;`;
44942
+ var ESCAPES = new Set([
44943
+ ANSI_ESCAPE,
44944
+ C1_CSI
44945
+ ]);
44946
+ var ESCAPE_CHARACTERS = [...ESCAPES].join("");
44947
+ var CSI_INTRODUCER = `(?:${ANSI_ESCAPE}\\${ANSI_CSI}|${C1_CSI})`;
44948
+ var CSI_PARAMETERS = "[0-?]*[ -/]*[@-~]";
44949
+ var SGR_PARAMETERS = `(?<sgr>[0-9;:]*)${ANSI_SGR_TERMINATOR}`;
44950
+ var OSC_STRING_TERMINATOR = `(?:${ANSI_ESCAPE_BELL}|${ANSI_ESCAPE}\\\\)`;
44951
+ var OSC_STRING_PAYLOAD = String.raw`[^\u0000-\u001F\u007F-\u009F]*`;
44952
+ var LINK_PARAMETERS = String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${OSC_STRING_PAYLOAD})${OSC_STRING_TERMINATOR}`;
44953
+ var OSC_STRING = `${OSC_STRING_PAYLOAD}${OSC_STRING_TERMINATOR}`;
44954
+ var ANSI_ESCAPE_REGEX = new RegExp(`${CSI_INTRODUCER}(?:${SGR_PARAMETERS}|${CSI_PARAMETERS})` + `|${ANSI_ESCAPE}\\${ANSI_OSC}(?:${LINK_PARAMETERS}|${OSC_STRING})`, "y");
44955
+ var ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansi_styles_default.codes.values());
44956
+ ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);
44957
+ var segmenter2 = new Intl.Segmenter;
44958
+ var getStringWidth = (string4) => stringWidth(string4, { countAnsiEscapeCodes: true });
44959
+ var TAB_SIZE = 8;
44960
+ var ESCAPE_INTRODUCER_REGEX = new RegExp(`[${ESCAPE_CHARACTERS}]`, "g");
44961
+ var ROW_BOUNDARY_REGEX = new RegExp(`[\\n${ESCAPE_CHARACTERS}]`, "g");
44962
+ var ASCII_PRINTABLE_REGEX = /^[ -~]*$/;
44963
+ var wrapAnsiCode = (code) => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
44964
+ var wrapAnsiHyperlink = (url, parameters = "") => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${parameters};${url}${ANSI_ESCAPE_BELL}`;
44965
+ var matchAnsiEscape = (string4, index2) => {
44966
+ if (!ESCAPES.has(string4[index2])) {
44967
+ return;
44968
+ }
44969
+ ANSI_ESCAPE_REGEX.lastIndex = index2;
44970
+ return ANSI_ESCAPE_REGEX.exec(string4) ?? undefined;
44971
+ };
44972
+ var forEachSegment = (string4, onPlainText, onEscape = () => {}) => {
44973
+ let plainStart = 0;
44974
+ let index2 = 0;
44975
+ while (index2 < string4.length) {
44976
+ ESCAPE_INTRODUCER_REGEX.lastIndex = index2;
44977
+ const introducer = ESCAPE_INTRODUCER_REGEX.exec(string4);
44978
+ if (!introducer) {
44979
+ break;
44980
+ }
44981
+ const escape2 = matchAnsiEscape(string4, introducer.index);
44982
+ if (!escape2) {
44983
+ index2 = introducer.index + 1;
44984
+ continue;
44985
+ }
44986
+ if (introducer.index > plainStart) {
44987
+ onPlainText(string4.slice(plainStart, introducer.index));
44988
+ }
44989
+ onEscape(escape2[0]);
44990
+ index2 = introducer.index + escape2[0].length;
44991
+ plainStart = index2;
44992
+ }
44993
+ if (plainStart < string4.length) {
44994
+ onPlainText(string4.slice(plainStart));
44995
+ }
44996
+ };
44997
+ var getWidth = (string4) => {
44998
+ let plainText = "";
44999
+ forEachSegment(string4, (part) => {
45000
+ plainText += part;
45001
+ });
45002
+ return getStringWidth(plainText);
45003
+ };
45004
+ var getTokens = (string4) => {
45005
+ const tokens = [];
45006
+ forEachSegment(string4, (plainText) => {
45007
+ if (ASCII_PRINTABLE_REGEX.test(plainText)) {
45008
+ for (const character of plainText) {
45009
+ tokens.push({ value: character, width: 1 });
45010
+ }
45011
+ return;
45012
+ }
45013
+ for (const { segment } of segmenter2.segment(plainText)) {
45014
+ tokens.push({ value: segment, width: getStringWidth(segment) });
45015
+ }
45016
+ }, (escape2) => {
45017
+ tokens.push({ value: escape2, width: 0 });
45018
+ });
45019
+ return tokens;
45020
+ };
45021
+ var splitWords = (string4) => {
45022
+ let currentWord = { value: "", plainText: "" };
45023
+ const words = [currentWord];
45024
+ forEachSegment(string4, (plainText) => {
45025
+ const parts2 = plainText.split(" ");
45026
+ currentWord.value += parts2[0];
45027
+ currentWord.plainText += parts2[0];
45028
+ for (let index2 = 1;index2 < parts2.length; index2++) {
45029
+ currentWord = { value: parts2[index2], plainText: parts2[index2] };
45030
+ words.push(currentWord);
45031
+ }
45032
+ }, (escape2) => {
45033
+ currentWord.value += escape2;
45034
+ });
45035
+ for (const word of words) {
45036
+ word.width = getStringWidth(word.plainText);
45037
+ }
45038
+ return words;
45039
+ };
45040
+ var getColonColorToken = (parameter) => {
45041
+ const parts2 = parameter.split(":");
45042
+ const code = Number.parseInt(parts2[0], 10);
45043
+ const mode = Number.parseInt(parts2[1], 10);
45044
+ if (![ANSI_SGR_FOREGROUND_EXTENDED, ANSI_SGR_BACKGROUND_EXTENDED, ANSI_SGR_UNDERLINE_COLOR_EXTENDED].includes(code)) {
45045
+ return;
45046
+ }
45047
+ if (mode === ANSI_SGR_COLOR_MODE_256 && parts2.length === 3 && /^\d+$/.test(parts2[2])) {
45048
+ return { code, open: parameter, hasArguments: true };
45049
+ }
45050
+ if (mode !== ANSI_SGR_COLOR_MODE_RGB) {
45051
+ return;
45052
+ }
45053
+ const components = parts2.length === 6 ? parts2.slice(3) : parts2.slice(2);
45054
+ const colorSpace = parts2.length === 6 ? parts2[2] : undefined;
45055
+ if (components.length === 3 && components.every((component) => /^\d+$/.test(component)) && (colorSpace === undefined || /^\d*$/.test(colorSpace))) {
45056
+ return { code, open: parameter, hasArguments: true };
45057
+ }
45058
+ };
45059
+ var getSgrTokens = (sgrParameters) => {
45060
+ const parameters = sgrParameters.split(";");
45061
+ const sgrTokens = [];
45062
+ for (let index2 = 0;index2 < parameters.length; index2++) {
45063
+ const parameter = parameters[index2];
45064
+ if (parameter.includes(":")) {
45065
+ const colonColorToken = getColonColorToken(parameter);
45066
+ if (colonColorToken) {
45067
+ sgrTokens.push(colonColorToken);
45068
+ }
45069
+ continue;
45070
+ }
45071
+ const code = parameter === "" ? ANSI_SGR_RESET : Number.parseInt(parameter, 10);
45072
+ if (!Number.isFinite(code)) {
45073
+ continue;
45074
+ }
45075
+ if (code === ANSI_SGR_FOREGROUND_EXTENDED || code === ANSI_SGR_BACKGROUND_EXTENDED || code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED) {
45076
+ if (index2 + 1 >= parameters.length) {
45077
+ break;
45078
+ }
45079
+ const mode = Number.parseInt(parameters[index2 + 1], 10);
45080
+ const colorIndex = Number.parseInt(parameters[index2 + 2], 10);
45081
+ if (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(colorIndex)) {
45082
+ sgrTokens.push({ code, open: [code, mode, colorIndex].join(";"), hasArguments: true });
45083
+ index2 += 2;
45084
+ continue;
45085
+ }
45086
+ const red2 = Number.parseInt(parameters[index2 + 2], 10);
45087
+ const green2 = Number.parseInt(parameters[index2 + 3], 10);
45088
+ const blue = Number.parseInt(parameters[index2 + 4], 10);
45089
+ if (mode === ANSI_SGR_COLOR_MODE_RGB && Number.isFinite(red2) && Number.isFinite(green2) && Number.isFinite(blue)) {
45090
+ sgrTokens.push({ code, open: [code, mode, red2, green2, blue].join(";"), hasArguments: true });
45091
+ index2 += 4;
45092
+ continue;
45093
+ }
45094
+ break;
45095
+ }
45096
+ sgrTokens.push({ code, open: String(code), hasArguments: false });
45097
+ }
45098
+ return sgrTokens;
45099
+ };
45100
+ var removeActiveStyle = (activeStyles, family) => {
45101
+ const activeStyleIndex = activeStyles.findIndex((activeStyle) => activeStyle.family === family);
45102
+ if (activeStyleIndex !== -1) {
45103
+ activeStyles.splice(activeStyleIndex, 1);
45104
+ }
45105
+ };
45106
+ var upsertActiveStyle = (activeStyles, nextActiveStyle) => {
45107
+ removeActiveStyle(activeStyles, nextActiveStyle.family);
45108
+ activeStyles.push(nextActiveStyle);
45109
+ };
45110
+ var removeModifierStylesByClose = (activeStyles, closeCode) => {
45111
+ for (let index2 = activeStyles.length - 1;index2 >= 0; index2--) {
45112
+ const activeStyle = activeStyles[index2];
45113
+ if (activeStyle.family.startsWith("modifier-") && activeStyle.close === closeCode) {
45114
+ activeStyles.splice(index2, 1);
45115
+ }
45116
+ }
45117
+ };
45118
+ var getColorStyle = (sgrToken) => {
45119
+ const { code, open: open3, hasArguments } = sgrToken;
45120
+ if (code >= 30 && code <= 37 || code >= 90 && code <= 97 || code === ANSI_SGR_FOREGROUND_EXTENDED && hasArguments) {
45121
+ return {
45122
+ family: "foreground",
45123
+ open: open3,
45124
+ close: ANSI_SGR_RESET_FOREGROUND
45125
+ };
45126
+ }
45127
+ if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === ANSI_SGR_BACKGROUND_EXTENDED && hasArguments) {
45128
+ return {
45129
+ family: "background",
45130
+ open: open3,
45131
+ close: ANSI_SGR_RESET_BACKGROUND
45132
+ };
45133
+ }
45134
+ if (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && hasArguments) {
45135
+ return {
45136
+ family: "underlineColor",
45137
+ open: open3,
45138
+ close: ANSI_SGR_RESET_UNDERLINE_COLOR
45139
+ };
45140
+ }
45141
+ };
45142
+ var applySgrResetCode = (code, activeStyles) => {
45143
+ if (code === ANSI_SGR_RESET) {
45144
+ activeStyles.length = 0;
45145
+ return true;
45146
+ }
45147
+ if (code === ANSI_SGR_RESET_FOREGROUND) {
45148
+ removeActiveStyle(activeStyles, "foreground");
45149
+ return true;
45150
+ }
45151
+ if (code === ANSI_SGR_RESET_BACKGROUND) {
45152
+ removeActiveStyle(activeStyles, "background");
45153
+ return true;
45154
+ }
45155
+ if (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {
45156
+ removeActiveStyle(activeStyles, "underlineColor");
45157
+ return true;
45158
+ }
45159
+ if (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {
45160
+ removeModifierStylesByClose(activeStyles, code);
45161
+ return true;
45162
+ }
45163
+ return false;
45164
+ };
45165
+ var applySgrToken = (sgrToken, activeStyles) => {
45166
+ const { code } = sgrToken;
45167
+ if (applySgrResetCode(code, activeStyles)) {
45168
+ return;
45169
+ }
45170
+ const colorStyle = getColorStyle(sgrToken);
45171
+ if (colorStyle) {
45172
+ upsertActiveStyle(activeStyles, colorStyle);
45173
+ return;
45174
+ }
45175
+ const close3 = ansi_styles_default.codes.get(code);
45176
+ if (close3 !== undefined && close3 !== ANSI_SGR_RESET) {
45177
+ upsertActiveStyle(activeStyles, {
45178
+ family: `modifier-${code}`,
45179
+ open: sgrToken.open,
45180
+ close: close3
45181
+ });
45182
+ }
45183
+ };
45184
+ var applySgrParameters = (sgrParameters, activeStyles) => {
45185
+ for (const sgrToken of getSgrTokens(sgrParameters)) {
45186
+ applySgrToken(sgrToken, activeStyles);
45187
+ }
45188
+ };
45189
+ var applySgrResets = (sgrParameters, activeStyles) => {
45190
+ for (const { code } of getSgrTokens(sgrParameters)) {
45191
+ applySgrResetCode(code, activeStyles);
45192
+ }
45193
+ };
45194
+ var applyLeadingSgrResets = (string4, startIndex, activeStyles) => {
45195
+ let index2 = startIndex;
45196
+ while (index2 < string4.length) {
45197
+ const match10 = matchAnsiEscape(string4, index2);
45198
+ if (!match10) {
45199
+ break;
45200
+ }
45201
+ if (match10.groups.sgr !== undefined) {
45202
+ applySgrResets(match10.groups.sgr, activeStyles);
45203
+ }
45204
+ index2 += match10[0].length;
45205
+ }
45206
+ };
45207
+ var getClosingSgrSequence = (activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join("");
45208
+ var getOpeningSgrSequence = (activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join("");
45209
+ var wrapWord = (rows, word, columns, rowWidth) => {
45210
+ const tokens = getTokens(word);
45211
+ let visible = rowWidth;
45212
+ for (let index2 = 0;index2 < tokens.length; index2++) {
45213
+ const token = tokens[index2];
45214
+ if (token.width > 0 && visible > 0 && visible + token.width > columns) {
45215
+ rows.push("");
45216
+ visible = 0;
45217
+ }
45218
+ rows[rows.length - 1] += token.value;
45219
+ visible += token.width;
45220
+ if (visible === columns && index2 < tokens.length - 1) {
45221
+ rows.push("");
45222
+ visible = 0;
45223
+ }
45224
+ }
45225
+ if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
45226
+ rows[rows.length - 2] += rows.pop();
45227
+ }
45228
+ return getWidth(rows.at(-1));
45229
+ };
45230
+ var stringVisibleTrimSpacesRight = (string4) => {
45231
+ if (!string4.includes(" ")) {
45232
+ return string4;
45233
+ }
45234
+ const segments = [];
45235
+ forEachSegment(string4, (plainText) => {
45236
+ segments.push({ value: plainText, isEscape: false });
45237
+ }, (escape2) => {
45238
+ segments.push({ value: escape2, isEscape: true });
45239
+ });
45240
+ for (let index2 = segments.length - 1;index2 >= 0; index2--) {
45241
+ const segment = segments[index2];
45242
+ if (segment.isEscape) {
45243
+ continue;
45244
+ }
45245
+ let end3 = segment.value.length;
45246
+ while (end3 > 0 && segment.value[end3 - 1] === " ") {
45247
+ end3--;
45248
+ }
45249
+ segment.value = segment.value.slice(0, end3);
45250
+ if (getStringWidth(segment.value) > 0) {
45251
+ break;
45252
+ }
45253
+ }
45254
+ return segments.map((segment) => segment.value).join("");
45255
+ };
45256
+ var expandTabs = (line) => {
45257
+ if (!line.includes("\t")) {
45258
+ return line;
45259
+ }
45260
+ let visible = 0;
45261
+ let expandedLine = "";
45262
+ let plainTextSinceTab = "";
45263
+ const expandPlainText = (plainText) => {
45264
+ const segments = plainText.split("\t");
45265
+ for (const [index2, segment] of segments.entries()) {
45266
+ expandedLine += segment;
45267
+ plainTextSinceTab += segment;
45268
+ if (index2 < segments.length - 1) {
45269
+ visible += getStringWidth(plainTextSinceTab);
45270
+ plainTextSinceTab = "";
45271
+ const spaces = TAB_SIZE - visible % TAB_SIZE;
45272
+ expandedLine += " ".repeat(spaces);
45273
+ visible += spaces;
45274
+ }
45275
+ }
45276
+ };
45277
+ forEachSegment(line, expandPlainText, (escape2) => {
45278
+ expandedLine += escape2;
45279
+ });
45280
+ return expandedLine;
45281
+ };
45282
+ var restoreStylesAcrossRows = (preString) => {
45283
+ let returnValue = "";
45284
+ let activeHyperlink;
45285
+ const activeStyles = [];
45286
+ let index2 = 0;
45287
+ let copiedIndex = 0;
45288
+ while (index2 < preString.length) {
45289
+ ROW_BOUNDARY_REGEX.lastIndex = index2;
45290
+ const boundary = ROW_BOUNDARY_REGEX.exec(preString);
45291
+ if (!boundary) {
45292
+ break;
45293
+ }
45294
+ index2 = boundary.index;
45295
+ if (boundary[0] !== `
45296
+ `) {
45297
+ const escape2 = matchAnsiEscape(preString, index2);
45298
+ if (!escape2) {
45299
+ index2++;
45300
+ continue;
45301
+ }
45302
+ const { groups } = escape2;
45303
+ if (groups.sgr !== undefined) {
45304
+ applySgrParameters(groups.sgr, activeStyles);
45305
+ } else if (groups.uri !== undefined) {
45306
+ activeHyperlink = groups.uri.length === 0 ? undefined : { parameters: groups.parameters, uri: groups.uri };
45307
+ }
45308
+ index2 += escape2[0].length;
45309
+ continue;
45310
+ }
45311
+ returnValue += preString.slice(copiedIndex, index2);
45312
+ if (index2 > copiedIndex) {
45313
+ if (activeHyperlink) {
45314
+ returnValue += wrapAnsiHyperlink("");
45315
+ }
45316
+ returnValue += getClosingSgrSequence(activeStyles);
45317
+ }
45318
+ returnValue += `
45319
+ `;
45320
+ index2++;
45321
+ copiedIndex = index2;
45322
+ if (index2 < preString.length && preString[index2] !== `
45323
+ `) {
45324
+ const openingStyles = [...activeStyles];
45325
+ applyLeadingSgrResets(preString, index2, openingStyles);
45326
+ returnValue += getOpeningSgrSequence(openingStyles);
45327
+ if (activeHyperlink) {
45328
+ returnValue += wrapAnsiHyperlink(activeHyperlink.uri, activeHyperlink.parameters);
45329
+ }
45330
+ }
45331
+ }
45332
+ return returnValue + preString.slice(copiedIndex);
45333
+ };
45334
+ var exec = (string4, columns, options3 = {}) => {
45335
+ if (options3.trim !== false && string4.trim() === "") {
45336
+ return "";
45337
+ }
45338
+ const words = splitWords(string4);
45339
+ let rows = [""];
45340
+ let rowLength = 0;
45341
+ let trimmedRowIndex = -1;
45342
+ let isFirstWord = true;
45343
+ for (const word of words) {
45344
+ const rowIndex = rows.length - 1;
45345
+ if (options3.trim !== false && trimmedRowIndex !== rowIndex) {
45346
+ const row = rows[rowIndex];
45347
+ const trimmedRow = row.trimStart();
45348
+ if (trimmedRow.length !== row.length) {
45349
+ rows[rowIndex] = trimmedRow;
45350
+ rowLength = getWidth(trimmedRow);
45351
+ }
45352
+ if (trimmedRow.length > 0) {
45353
+ trimmedRowIndex = rowIndex;
45354
+ }
45355
+ }
45356
+ if (isFirstWord) {
45357
+ isFirstWord = false;
45358
+ } else {
45359
+ if (rowLength >= columns && (options3.wordWrap === false || options3.trim === false)) {
45360
+ rows.push("");
45361
+ rowLength = 0;
45362
+ }
45363
+ if (rowLength > 0 || options3.trim === false) {
45364
+ rows[rows.length - 1] += " ";
45365
+ rowLength++;
45366
+ }
45367
+ }
45368
+ if (options3.hard && options3.wordWrap !== false && word.width > columns) {
45369
+ const remainingColumns = columns - rowLength;
45370
+ const breaksStartingThisLine = 1 + Math.floor((word.width - remainingColumns - 1) / columns);
45371
+ const breaksStartingNextLine = Math.floor((word.width - 1) / columns);
45372
+ if (breaksStartingNextLine < breaksStartingThisLine) {
45373
+ rows.push("");
45374
+ rowLength = 0;
45375
+ }
45376
+ rowLength = wrapWord(rows, word.value, columns, rowLength);
45377
+ continue;
45378
+ }
45379
+ if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
45380
+ if (options3.wordWrap === false && rowLength < columns) {
45381
+ rowLength = wrapWord(rows, word.value, columns, rowLength);
45382
+ continue;
45383
+ }
45384
+ rows.push("");
45385
+ rowLength = 0;
45386
+ }
45387
+ if (rowLength + word.width > columns && options3.wordWrap === false) {
45388
+ rowLength = wrapWord(rows, word.value, columns, rowLength);
45389
+ continue;
45390
+ }
45391
+ rows[rows.length - 1] += word.value;
45392
+ rowLength += word.width;
45393
+ }
45394
+ if (options3.trim !== false) {
45395
+ rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
45396
+ }
45397
+ return restoreStylesAcrossRows(rows.join(`
45398
+ `));
45399
+ };
45400
+ var normalizeText = (string4) => {
45401
+ let normalizedString = "";
45402
+ forEachSegment(string4, (plainText) => {
45403
+ normalizedString += plainText.normalize();
45404
+ }, (escape2) => {
45405
+ normalizedString += escape2;
45406
+ });
45407
+ return normalizedString;
45408
+ };
45409
+ function wrapAnsi(string4, columns, options3) {
45410
+ return normalizeText(String(string4)).replaceAll(`\r
45411
+ `, `
45412
+ `).split(`
45413
+ `).map((line) => exec(expandTabs(line), columns, options3)).join(`
45414
+ `);
43998
45415
  }
43999
- var cmdWord = (value5) => /^[\w@+=:,./\\-]+$/.test(value5) ? value5 : `"${value5}"`;
44000
- var powershellString = (value5) => `'${value5.replaceAll("'", "''")}'`;
44001
- var taskScheduler = {
44002
- name: "Task Scheduler task",
44003
- install: (job) => quotable(job, /[\p{Cc}"%]/u, 'a control character, `"`, or `%`').pipe(exports_Effect.map((job2) => {
44004
- const command = [
44005
- ...exports_Option.toArray(job2.configHome).map((directory) => `set "XDG_CONFIG_HOME=${directory}"`),
44006
- `set "PATH=${job2.nodeDirectory};%PATH%"`,
44007
- `npx --yes ${packageSpec} ${["sync", ...job2.flags].map(cmdWord).join(" ")}`
44008
- ].join(" && ");
44009
- const script = [
44010
- "$ErrorActionPreference = 'Stop'",
44011
- "$ProgressPreference = 'SilentlyContinue'",
44012
- `$action = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument ${powershellString(`/d /v:off /s /c "${command}"`)}`,
44013
- `$trigger = New-ScheduledTaskTrigger -Daily -At '${job2.at}'`,
44014
- "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
44015
- `Register-ScheduledTask -TaskName ${powershellString(task)} -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null`
44016
- ].join(`
45416
+
45417
+ // packages/cli/src/format.ts
45418
+ function csvCell(value5) {
45419
+ const text2 = value5 === null ? "" : String(value5);
45420
+ const safe = /^[=+\-@\t\r\n]/.test(text2) ? `'${text2}` : text2;
45421
+ return `"${safe.replaceAll('"', '""')}"`;
45422
+ }
45423
+ function csv(report) {
45424
+ const summary = projectSummary(report, false);
45425
+ const headings = summary.headings.map((heading) => heading === "API estimate" ? "API estimate (USD)" : heading);
45426
+ return [headings, ...summary.rows].map((row) => row.map(csvCell).join(",")).join(`
44017
45427
  `);
44018
- const options3 = ["-NoProfile", "-NonInteractive", "-EncodedCommand"];
44019
- return [
44020
- Action3.Run({
44021
- program: "powershell.exe",
44022
- args: [...options3, Buffer.from(script, "utf16le").toString("base64")],
44023
- shown: `powershell.exe ${options3.join(" ")} <the script below, as UTF-16LE Base64>
44024
- ${script}`,
44025
- outcome: "required",
44026
- hint: "",
44027
- gone: []
45428
+ }
45429
+ function terminalText(value5) {
45430
+ return value5.replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
45431
+ }
45432
+ function projectSummary(report, grouped2) {
45433
+ const projects = new Map;
45434
+ for (const row of report.rows) {
45435
+ const previous = projects.get(row.project);
45436
+ projects.set(row.project, {
45437
+ tokens: addTokens(previous?.tokens ?? zeroTokens, row.tokens),
45438
+ cost: (previous?.cost ?? 0) + row.pricedCostUsd,
45439
+ unpriced: (previous?.unpriced ?? 0) + row.unpricedRecords
45440
+ });
45441
+ }
45442
+ const cost = [...projects.values()].reduce((sum3, project) => sum3 + project.cost, 0);
45443
+ const unpriced = [...projects.values()].reduce((sum3, project) => sum3 + project.unpriced, 0);
45444
+ const headings = [
45445
+ "Project",
45446
+ "Input",
45447
+ "Cache read",
45448
+ "Cache write",
45449
+ "Output",
45450
+ "API estimate",
45451
+ unpriced ? "Known cost %" : "Cost %"
45452
+ ];
45453
+ const percentage = new Intl.NumberFormat("en-US", {
45454
+ style: "percent",
45455
+ minimumFractionDigits: 1,
45456
+ maximumFractionDigits: 1
45457
+ });
45458
+ const share2 = (value5) => cost > 0 ? percentage.format(value5 / cost) : "—";
45459
+ const number4 = new Intl.NumberFormat("en-US", { useGrouping: grouped2 });
45460
+ const dollars = new Intl.NumberFormat("en-US", {
45461
+ style: "currency",
45462
+ currency: "USD",
45463
+ useGrouping: grouped2
45464
+ });
45465
+ let allTokens = zeroTokens;
45466
+ const rows = [];
45467
+ const ranked = [...projects].toSorted(([leftProject, left], [rightProject, right]) => right.cost - left.cost || leftProject.localeCompare(rightProject));
45468
+ for (const [project, total] of ranked) {
45469
+ rows.push([
45470
+ project,
45471
+ number4.format(total.tokens.input),
45472
+ number4.format(total.tokens.cacheRead),
45473
+ number4.format(total.tokens.cacheWrite),
45474
+ number4.format(total.tokens.output),
45475
+ `${dollars.format(total.cost)}${total.unpriced ? " + unknown" : ""}`,
45476
+ share2(total.cost)
45477
+ ]);
45478
+ allTokens = addTokens(allTokens, total.tokens);
45479
+ }
45480
+ if (projects.size > 0)
45481
+ rows.push([
45482
+ "Total",
45483
+ number4.format(allTokens.input),
45484
+ number4.format(allTokens.cacheRead),
45485
+ number4.format(allTokens.cacheWrite),
45486
+ number4.format(allTokens.output),
45487
+ `${dollars.format(cost)}${unpriced ? " + unknown" : ""}`,
45488
+ share2(cost)
45489
+ ]);
45490
+ return { headings, rows, allTokens, unpriced, projectCount: projects.size };
45491
+ }
45492
+ function table2(report, columns = 120, colorful = false) {
45493
+ const paint = (format10, value5) => colorful ? styleText(format10, value5, { validateStream: false }) : value5;
45494
+ const { headings, rows, allTokens, unpriced, projectCount } = projectSummary(report, true);
45495
+ const number4 = new Intl.NumberFormat("en-US");
45496
+ if (projectCount === 0)
45497
+ return `No observed usage from ${report.since} through ${report.until} (${report.timeZone}).`;
45498
+ const numericWidths = headings.slice(1).map((heading, i) => Math.max(heading.length, ...rows.map((row) => row[i + 1]?.length ?? 0)) + 2);
45499
+ const projectWidth = columns - numericWidths.reduce((sum3, width2) => sum3 + width2, 0) - (headings.length + 1);
45500
+ const narrow = projectWidth < 22;
45501
+ const colWidths = narrow ? [16, Math.max(4, columns - 19)] : [Math.min(50, projectWidth), ...numericWidths];
45502
+ const output = new import_cli_table3.default({
45503
+ head: narrow ? [] : headings.map((heading) => paint(["bold", "cyan"], heading)),
45504
+ colWidths,
45505
+ colAligns: narrow ? ["left", "right"] : ["left", "right", "right", "right", "right", "right", "right"],
45506
+ wordWrap: false,
45507
+ style: { head: [], border: [] }
45508
+ });
45509
+ const projectColors = [
45510
+ "cyan",
45511
+ "blueBright",
45512
+ "magenta",
45513
+ "yellow",
45514
+ "green",
45515
+ "cyanBright"
45516
+ ];
45517
+ for (const [index2, row] of rows.entries()) {
45518
+ const styled = row.map((value5, column) => {
45519
+ const width2 = narrow ? column === 0 ? columns - 4 : columns - 21 : (colWidths[column] ?? 4) - 2;
45520
+ const cell = wrapAnsi(terminalText(value5), Math.max(2, width2), {
45521
+ hard: true,
45522
+ wordWrap: false,
45523
+ trim: false
45524
+ });
45525
+ if (index2 === rows.length - 1)
45526
+ return paint(["bold", "magenta"], cell);
45527
+ if (column === 0)
45528
+ return paint(projectColors[index2 % projectColors.length] ?? "cyan", cell);
45529
+ if (column >= headings.length - 2)
45530
+ return paint(value5.includes("unknown") ? "yellow" : "green", cell);
45531
+ return cell === "0" ? paint("dim", cell) : cell;
45532
+ });
45533
+ if (narrow) {
45534
+ output.push([{ content: styled[0] ?? "", colSpan: 2, hAlign: "left" }]);
45535
+ for (const [i, heading] of headings.slice(1).entries()) {
45536
+ output.push([paint("cyan", heading), styled[i + 1] ?? ""]);
45537
+ }
45538
+ } else {
45539
+ output.push(styled);
45540
+ }
45541
+ }
45542
+ return [
45543
+ `${paint(["bold", "cyan"], colorful ? "⚡ Token Ledger" : "Token Ledger")} · ${paint("dim", `${report.since} through ${report.until} (${report.timeZone})`)}`,
45544
+ "",
45545
+ output.toString(),
45546
+ "",
45547
+ paint("bold", `${colorful ? "\uD83D\uDCCA " : ""}${number4.format(totalTokens(allTokens))} observed tokens · ${number4.format(projectCount)} ${projectCount === 1 ? "project" : "projects"}`),
45548
+ ...unpriced > 0 ? [
45549
+ paint("yellow", "Incomplete pricing: sorting and percentages use known API subtotals; unknown costs are additional.")
45550
+ ] : [],
45551
+ paint("dim", "USD API-equivalent estimates; not your subscription bill.")
45552
+ ].join(`
45553
+ `);
45554
+ }
45555
+ function syncSummary(payload, request3, storedBuckets) {
45556
+ const number4 = new Intl.NumberFormat("en-US");
45557
+ const dollars = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
45558
+ const sessions = new Set(payload.buckets.map((bucket) => bucket.sessionKey)).size;
45559
+ const cost = payload.buckets.reduce((sum3, bucket) => sum3 + (bucket.estimatedCostUsd ?? 0), 0);
45560
+ const unknown2 = payload.buckets.some((bucket) => bucket.estimatedCostUsd === null);
45561
+ return [
45562
+ `Synced ${terminalText(payload.machine.label)} · ${request3.since} through ${request3.until} (${payload.timeZone})`,
45563
+ [
45564
+ `${number4.format(payload.buckets.length)} hourly buckets`,
45565
+ `${number4.format(sessions)} sessions`,
45566
+ `${dollars.format(cost)}${unknown2 ? " + unknown" : ""} API estimate`,
45567
+ exports_Option.match(storedBuckets, {
45568
+ onNone: () => "accepted by the server",
45569
+ onSome: (stored) => `server stored ${number4.format(stored)}`
44028
45570
  })
44029
- ];
44030
- })),
44031
- uninstall: [
44032
- run6("reported", "schtasks.exe", ["/Delete", "/TN", task, "/F"]),
44033
- run6("absent", "schtasks.exe", ["/Query", "/TN", task], "The task is still registered; Task Scheduler's reason is shown above.")
44034
- ],
44035
- status: [run6("reported", "schtasks.exe", ["/Query", "/TN", task, "/V", "/FO", "LIST"])]
44036
- };
44037
- var hostScheduler = exports_Effect.gen(function* () {
44038
- const path = yield* exports_Path.Path;
44039
- const home = homedir2();
44040
- const units = exports_Option.getOrElse(yield* configHome, () => path.join(home, ".config"));
44041
- return yield* exports_Match.value(process.platform).pipe(exports_Match.when("linux", () => exports_Effect.succeed(systemdTimer(path.join(units, "systemd", "user")))), exports_Match.when("darwin", () => exports_Effect.succeed(launchAgent(home, userInfo().uid))), exports_Match.when("win32", () => exports_Effect.succeed(taskScheduler)), exports_Match.orElse((platform) => exports_Effect.fail(new ScheduleError({
44042
- message: `No scheduler is supported on ${platform}; schedule token-ledger sync yourself.`
44043
- }))));
44044
- });
44045
- var describe = (actions) => actions.map(Action3.$match({
44046
- Write: ({ file: file2, contents }) => `write ${file2}
44047
- ${contents.replaceAll(/^(?=.)/gm, " ")}`,
44048
- Remove: ({ file: file2 }) => `remove ${file2}
44049
- `,
44050
- Run: ({ shown }) => `run ${shown}
44051
- `
44052
- })).join(`
45571
+ ].join(" · ")
45572
+ ].join(`
44053
45573
  `);
44054
- var perform = exports_Effect.fn("Schedule.perform")(function* (actions) {
44055
- const fs = yield* exports_FileSystem.FileSystem;
44056
- const path = yield* exports_Path.Path;
44057
- const spawner = yield* exports_ChildProcessSpawner.ChildProcessSpawner;
44058
- for (const action of actions)
44059
- yield* Action3.$match(action, {
44060
- Write: ({ file: file2, contents }) => fs.makeDirectory(path.dirname(file2), { recursive: true }).pipe(exports_Effect.andThen(fs.writeFileString(file2, contents)), exports_Effect.mapError(() => new ScheduleError({ message: `Cannot write ${file2}.` }))),
44061
- Remove: ({ file: file2 }) => fs.remove(file2, { force: true }).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot remove ${file2}.` }))),
44062
- Run: ({ program, args: args2, outcome, hint, gone }) => {
44063
- const output = outcome === "silent" || outcome === "absent" ? "ignore" : "inherit";
44064
- const exit3 = spawner.exitCode(exports_ChildProcess.make(program, args2, { stdin: "ignore", stdout: output, stderr: output })).pipe(exports_Effect.mapError(() => new ScheduleError({ message: `Cannot run ${program}. ${hint}`.trim() })));
44065
- return exports_Match.value(outcome).pipe(exports_Match.when("required", () => exports_Effect.filterOrFail(exit3, (code) => code === 0, (code) => new ScheduleError({
44066
- message: `${[program, ...args2.slice(0, 2)].join(" ")} failed with exit code ${code}. ${hint}`.trim()
44067
- }))), exports_Match.when("reported", () => exit3), exports_Match.when("silent", () => exports_Effect.ignore(exit3)), exports_Match.when("absent", () => exit3.pipe(exports_Effect.map((code) => gone.length === 0 ? code !== 0 : gone.includes(code)), exports_Effect.orElseSucceed(() => true), exports_Effect.filterOrFail((confirmed) => confirmed, () => new ScheduleError({ message: hint })))), exports_Match.exhaustive);
44068
- }
44069
- });
44070
- });
45574
+ }
44071
45575
 
44072
45576
  // packages/cli/src/upload.ts
44073
45577
  class SyncUnreachable extends exports_Schema.TaggedError()("SyncUnreachable", {
@@ -44168,13 +45672,7 @@ var usageRequest = exports_Effect.fn("CLI.usageRequest")(function* (flags, defau
44168
45672
  { provider: "codex", path: path.join(expand(codexHome), "archived_sessions") },
44169
45673
  { provider: "claude", path: path.join(expand(claudeHome), "projects") },
44170
45674
  { provider: "grok", path: path.join(expand(grokHome), "sessions") },
44171
- {
44172
- provider: "copilot",
44173
- path: exports_Option.match(copilotFile, {
44174
- onNone: () => path.join(expand(copilotHome), "otel"),
44175
- onSome: (value5) => expand(value5)
44176
- })
44177
- },
45675
+ ...(yield* copilotSources(path.join(expand(copilotHome), "otel"), exports_Option.map(copilotFile, (value5) => expand(value5)))).map((source) => ({ provider: "copilot", path: source })),
44178
45676
  {
44179
45677
  provider: "pi",
44180
45678
  path: exports_Option.match(piSessions, {
@@ -44366,6 +45864,65 @@ var scheduleUninstall = exports_Command.make("uninstall", {}, exports_Effect.fn(
44366
45864
  yield* exports_Console.log(`Removed the ${scheduler.name}. Saved settings were kept.`);
44367
45865
  })).pipe(exports_Command.withDescription("Remove the daily sync; saved settings stay"));
44368
45866
  var schedule4 = exports_Command.make("schedule").pipe(exports_Command.withDescription("Run sync daily with systemd, launchd, or Task Scheduler"), exports_Command.withSubcommands([scheduleInstall, scheduleStatus, scheduleUninstall]));
45867
+ var copilotEnable = exports_Command.make("enable", {
45868
+ cli: exports_Flag.Boolean("cli").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Copilot CLI: export its usage from every new terminal")),
45869
+ vscode: exports_Flag.Boolean("vscode").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("VS Code Copilot Chat: set its export in the user settings.json")),
45870
+ yes: exports_Flag.Boolean("yes").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Make the listed changes without asking")),
45871
+ dryRun: exports_Flag.Boolean("dry-run").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Print the changes; change nothing")),
45872
+ allowRoot: exports_Flag.Boolean("allow-root").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Run as root, where root is the account that uses Copilot"))
45873
+ }, exports_Effect.fn("CLI.copilotEnable")(function* (flags) {
45874
+ const path = yield* exports_Path.Path;
45875
+ const copilotHome = yield* exports_Config.String("COPILOT_HOME").pipe(exports_Config.withDefault(path.join(home, ".copilot")));
45876
+ const host = {
45877
+ platform: process.platform,
45878
+ home,
45879
+ uid: exports_Option.fromUndefinedOr(process.getuid?.()),
45880
+ copilotHome: expandPath(path, copilotHome),
45881
+ shell: yield* exports_Config.String("SHELL").pipe(exports_Config.option),
45882
+ zshDirectory: yield* exports_Config.String("ZDOTDIR").pipe(exports_Config.option),
45883
+ configHome: yield* configHome,
45884
+ appData: yield* exports_Config.String("APPDATA").pipe(exports_Config.option),
45885
+ exporter: exports_Option.map(yield* exports_Config.String("COPILOT_OTEL_FILE_EXPORTER_PATH").pipe(exports_Config.option), (file2) => expandPath(path, file2))
45886
+ };
45887
+ const stop = (message) => exports_Console.error(message).pipe(exports_Effect.andThen(exports_Effect.sync(() => {
45888
+ process.exitCode = 1;
45889
+ })));
45890
+ const planned = yield* plan(host, {
45891
+ cli: flags.cli || !flags.vscode,
45892
+ vscode: flags.vscode || !flags.cli,
45893
+ allowRoot: flags.allowRoot
45894
+ }).pipe(exports_Effect.result);
45895
+ if (exports_Result.isFailure(planned))
45896
+ return yield* stop(planned.failure.message);
45897
+ const { directory, steps } = planned.success;
45898
+ const incomplete = (results3) => {
45899
+ if (results3.some(Step.$is("ByHand")))
45900
+ process.exitCode = 2;
45901
+ };
45902
+ if (!steps.some(Step.$is("Change"))) {
45903
+ yield* exports_Console.log(steps.some(Step.$is("ByHand")) ? describe2(steps) : `Copilot's usage export is already on; nothing to change.
45904
+
45905
+ ${describe2(steps)}`);
45906
+ return incomplete(steps);
45907
+ }
45908
+ yield* exports_Console.log(`${describe2(steps)}
45909
+ `);
45910
+ if (flags.dryRun)
45911
+ return incomplete(steps);
45912
+ if (!flags.yes) {
45913
+ if (!process.stdin.isTTY)
45914
+ return yield* stop("Nothing was changed: there is no terminal to ask on. Run it again with --yes to make these changes.");
45915
+ const agreed = yield* exports_Prompt.run(exports_Prompt.Confirm({ message: "Make these changes?", initial: true })).pipe(exports_Effect.orElseSucceed(() => false));
45916
+ if (!agreed)
45917
+ return yield* stop("Nothing was changed.");
45918
+ }
45919
+ const results2 = yield* perform2(steps).pipe(exports_Effect.result);
45920
+ if (exports_Result.isFailure(results2))
45921
+ return yield* stop(results2.failure.message);
45922
+ yield* exports_Console.log(summarize(results2.success, directory));
45923
+ return incomplete(results2.success);
45924
+ })).pipe(exports_Command.withDescription("Switch on Copilot's local usage export, after listing the changes and asking"));
45925
+ var copilot = exports_Command.make("copilot").pipe(exports_Command.withDescription("Set up Copilot CLI and VS Code Copilot Chat to record usage"), exports_Command.withSubcommands([copilotEnable]));
44369
45926
  var example = exports_Command.make("config-example", {}, () => exports_Console.log(JSON.stringify({
44370
45927
  projects: [
44371
45928
  {
@@ -44376,4 +45933,4 @@ var example = exports_Command.make("config-example", {}, () => exports_Console.l
44376
45933
  ],
44377
45934
  prices: { "example-model": { input: 2, output: 10, cacheRead: 0.2, cacheWrite: null } }
44378
45935
  }, null, 2))).pipe(exports_Command.withDescription("Print an example configuration to customize"));
44379
- exports_Command.make("token-ledger").pipe(exports_Command.withDescription("Local token accounting across coding agents. API estimates, not subscription bills."), exports_Command.withSubcommands([report, sync6, login, schedule4, example]), exports_Command.run({ version: package_default.version }), exports_Effect.provide(Ledger.layer), exports_Effect.provide(exports_NodeServices.layer), exports_Effect.provide(exports_FetchHttpClient.layer), exports_NodeRuntime.runMain);
45936
+ exports_Command.make("token-ledger").pipe(exports_Command.withDescription("Local token accounting across coding agents. API estimates, not subscription bills."), exports_Command.withSubcommands([report, sync6, login, schedule4, copilot, example]), exports_Command.run({ version: package_default.version }), exports_Effect.provide(Ledger.layer), exports_Effect.provide(exports_NodeServices.layer), exports_Effect.provide(exports_FetchHttpClient.layer), exports_NodeRuntime.runMain);