ccusage 15.1.0 → 15.3.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.
@@ -1,8 +1,8 @@
1
- import { modelPricingSchema } from "./_types-Cr2YEzKm.js";
2
- import { logger } from "./logger-Cke8hliP.js";
1
+ import { modelPricingSchema } from "./_types-BHFM59hI.js";
2
+ import { logger } from "./logger-DeTONwj8.js";
3
3
  import { createRequire } from "node:module";
4
- import F, { homedir } from "node:os";
5
4
  import path from "node:path";
5
+ import F, { homedir } from "node:os";
6
6
  var __create = Object.create;
7
7
  var __defProp = Object.defineProperty;
8
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -25,6 +25,107 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  enumerable: true
26
26
  }) : target, mod));
27
27
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
28
+ const isFailure = (result) => "Failure" === result.type;
29
+ const isPromise = (value) => "object" == typeof value && null !== value && "then" in value && "function" == typeof value.then && "catch" in value && "function" == typeof value.catch;
30
+ const andThen = (fn) => (result) => {
31
+ const apply = (r) => {
32
+ if (isFailure(r)) return r;
33
+ return fn(r.value);
34
+ };
35
+ return isPromise(result) ? result.then(apply) : apply(result);
36
+ };
37
+ const andThrough = (fn) => (result) => {
38
+ const apply = (r) => {
39
+ if (isFailure(r)) return r;
40
+ const next = fn(r.value);
41
+ if (isPromise(next)) return next.then((n) => {
42
+ if (isFailure(n)) return n;
43
+ return r;
44
+ });
45
+ if (isFailure(next)) return next;
46
+ return r;
47
+ };
48
+ return isPromise(result) ? result.then(apply) : apply(result);
49
+ };
50
+ const succeed = (...args) => {
51
+ const value = args[0];
52
+ if (void 0 === value) return { type: "Success" };
53
+ if (isPromise(value)) return value.then((value$1) => ({
54
+ type: "Success",
55
+ value: value$1
56
+ }));
57
+ return {
58
+ type: "Success",
59
+ value
60
+ };
61
+ };
62
+ const fail = (...args) => {
63
+ const error = args[0];
64
+ if (void 0 === error) return { type: "Failure" };
65
+ if (isPromise(error)) return error.then((error$1) => ({
66
+ type: "Failure",
67
+ error: error$1
68
+ }));
69
+ return {
70
+ type: "Failure",
71
+ error
72
+ };
73
+ };
74
+ const isSuccess = (result) => "Success" === result.type;
75
+ const inspect = (fn) => (result) => {
76
+ const apply = (r) => {
77
+ if (isSuccess(r)) fn(r.value);
78
+ return r;
79
+ };
80
+ return isPromise(result) ? result.then(apply) : apply(result);
81
+ };
82
+ const inspectError = (fn) => (result) => {
83
+ const apply = (r) => {
84
+ if (isFailure(r)) fn(r.error);
85
+ return r;
86
+ };
87
+ return isPromise(result) ? result.then(apply) : apply(result);
88
+ };
89
+ const map = (fn) => (result) => {
90
+ const apply = (r) => {
91
+ if (isFailure(r)) return r;
92
+ return succeed(fn(r.value));
93
+ };
94
+ if (isPromise(result)) return result.then(apply);
95
+ return apply(result);
96
+ };
97
+ const orElse = (fn) => (result) => {
98
+ const apply = (r) => {
99
+ if (isSuccess(r)) return r;
100
+ return fn(r.error);
101
+ };
102
+ return isPromise(result) ? result.then(apply) : apply(result);
103
+ };
104
+ const pipe = (value, ...functions) => {
105
+ let next = value;
106
+ for (const func of functions) next = func(next);
107
+ return next;
108
+ };
109
+ const try_ = (options) => {
110
+ if (isPromise(options.try)) {
111
+ if ("safe" in options && options.safe) return succeed(options.try);
112
+ return options.try.then((value) => succeed(value), (error) => fail(options.catch(error)));
113
+ }
114
+ return (...args) => {
115
+ try {
116
+ const output = options.try(...args);
117
+ if (isPromise(output)) {
118
+ const promise = succeed(output);
119
+ if ("safe" in options && options.safe) return promise;
120
+ return promise.catch((error) => fail(options.catch(error)));
121
+ }
122
+ return succeed(output);
123
+ } catch (error) {
124
+ if ("safe" in options && options.safe) throw error;
125
+ return fail(options.catch(error));
126
+ }
127
+ };
128
+ };
28
129
  const homeDirectory = F.homedir();
29
130
  const { env } = process;
30
131
  const xdgData = env.XDG_DATA_HOME || (homeDirectory ? path.join(homeDirectory, ".local", "share") : void 0);
@@ -120,6 +221,11 @@ const MIN_REFRESH_INTERVAL_SECONDS = 1;
120
221
  * Prevents too-slow updates that reduce monitoring effectiveness
121
222
  */
122
223
  const MAX_REFRESH_INTERVAL_SECONDS = 60;
224
+ /**
225
+ * Frame rate limit for live monitoring (16ms = ~60fps)
226
+ * Prevents terminal flickering and excessive CPU usage during rapid updates
227
+ */
228
+ const MIN_RENDER_INTERVAL_MS = 16;
123
229
  var require_usingCtx = __commonJSMin((exports, module) => {
124
230
  function _usingCtx() {
125
231
  var r = "function" == typeof SuppressedError ? SuppressedError : function(r$1, e$1) {
@@ -205,12 +311,11 @@ var PricingFetcher = class {
205
311
  this.cachedPricing = null;
206
312
  }
207
313
  /**
208
- * Ensures pricing data is loaded, either from cache or by fetching
314
+ * Loads offline pricing data from pre-fetched cache
209
315
  * @returns Map of model names to pricing information
210
316
  */
211
- async ensurePricingLoaded() {
212
- if (this.cachedPricing != null) return this.cachedPricing;
213
- if (this.offline) {
317
+ loadOfflinePricing = try_({
318
+ try: async () => {
214
319
  const pricing = new Map(Object.entries({
215
320
  "claude-instant-1": {
216
321
  "input_cost_per_token": 163e-8,
@@ -319,24 +424,55 @@ var PricingFetcher = class {
319
424
  }));
320
425
  this.cachedPricing = pricing;
321
426
  return pricing;
322
- }
323
- try {
427
+ },
428
+ catch: (error) => new Error("Failed to load offline pricing data", { cause: error })
429
+ });
430
+ /**
431
+ * Handles fallback to offline pricing when network fetch fails
432
+ * @param originalError - The original error from the network fetch
433
+ * @returns Map of model names to pricing information
434
+ * @throws Error if both network fetch and fallback fail
435
+ */
436
+ async handleFallbackToCachedPricing(originalError) {
437
+ logger.warn("Failed to fetch model pricing from LiteLLM, falling back to cached pricing data");
438
+ logger.debug("Fetch error details:", originalError);
439
+ return pipe(this.loadOfflinePricing(), inspect((pricing) => {
440
+ logger.info(`Using cached pricing data for ${pricing.size} models`);
441
+ }), inspectError((error) => {
442
+ logger.error("Failed to load cached pricing data as fallback:", error);
443
+ logger.error("Original fetch error:", originalError);
444
+ }));
445
+ }
446
+ /**
447
+ * Ensures pricing data is loaded, either from cache or by fetching
448
+ * Automatically falls back to offline mode if network fetch fails
449
+ * @returns Map of model names to pricing information
450
+ */
451
+ async ensurePricingLoaded() {
452
+ return pipe(this.cachedPricing != null ? succeed(this.cachedPricing) : fail(/* @__PURE__ */ new Error("Cached pricing not available")), orElse(async () => {
453
+ if (this.offline) return this.loadOfflinePricing();
324
454
  logger.warn("Fetching latest model pricing from LiteLLM...");
325
- const response = await fetch(LITELLM_PRICING_URL);
326
- if (!response.ok) throw new Error(`Failed to fetch pricing data: ${response.statusText}`);
327
- const data = await response.json();
328
- const pricing = /* @__PURE__ */ new Map();
329
- for (const [modelName, modelData] of Object.entries(data)) if (typeof modelData === "object" && modelData !== null) {
330
- const parsed = modelPricingSchema.safeParse(modelData);
331
- if (parsed.success) pricing.set(modelName, parsed.data);
332
- }
333
- this.cachedPricing = pricing;
334
- logger.info(`Loaded pricing for ${pricing.size} models`);
335
- return pricing;
336
- } catch (error) {
337
- logger.error("Failed to fetch model pricing:", error);
338
- throw new Error("Could not fetch model pricing data");
339
- }
455
+ return pipe(try_({
456
+ try: fetch(LITELLM_PRICING_URL),
457
+ catch: (error) => new Error("Failed to fetch model pricing from LiteLLM", { cause: error })
458
+ }), andThrough((response) => {
459
+ if (!response.ok) return fail(/* @__PURE__ */ new Error(`Failed to fetch pricing data: ${response.statusText}`));
460
+ return succeed();
461
+ }), andThen(async (response) => try_({
462
+ try: response.json(),
463
+ catch: (error) => new Error("Failed to parse pricing data", { cause: error })
464
+ })), map((data) => {
465
+ const pricing = /* @__PURE__ */ new Map();
466
+ for (const [modelName, modelData] of Object.entries(data)) if (typeof modelData === "object" && modelData !== null) {
467
+ const parsed = modelPricingSchema.safeParse(modelData);
468
+ if (parsed.success) pricing.set(modelName, parsed.data);
469
+ }
470
+ return pricing;
471
+ }), inspect((pricing) => {
472
+ this.cachedPricing = pricing;
473
+ logger.info(`Loaded pricing for ${pricing.size} models`);
474
+ }), orElse(async (error) => this.handleFallbackToCachedPricing(error)));
475
+ }));
340
476
  }
341
477
  /**
342
478
  * Fetches all available model pricing data
@@ -352,23 +488,24 @@ var PricingFetcher = class {
352
488
  * @returns Model pricing information or null if not found
353
489
  */
354
490
  async getModelPricing(modelName) {
355
- const pricing = await this.ensurePricingLoaded();
356
- const directMatch = pricing.get(modelName);
357
- if (directMatch != null) return directMatch;
358
- const variations = [
359
- modelName,
360
- `anthropic/${modelName}`,
361
- `claude-3-5-${modelName}`,
362
- `claude-3-${modelName}`,
363
- `claude-${modelName}`
364
- ];
365
- for (const variant of variations) {
366
- const match = pricing.get(variant);
367
- if (match != null) return match;
368
- }
369
- const lowerModel = modelName.toLowerCase();
370
- for (const [key, value] of pricing) if (key.toLowerCase().includes(lowerModel) || lowerModel.includes(key.toLowerCase())) return value;
371
- return null;
491
+ return pipe(this.ensurePricingLoaded(), map((pricing) => {
492
+ const directMatch = pricing.get(modelName);
493
+ if (directMatch != null) return directMatch;
494
+ const variations = [
495
+ modelName,
496
+ `anthropic/${modelName}`,
497
+ `claude-3-5-${modelName}`,
498
+ `claude-3-${modelName}`,
499
+ `claude-${modelName}`
500
+ ];
501
+ for (const variant of variations) {
502
+ const match = pricing.get(variant);
503
+ if (match != null) return match;
504
+ }
505
+ const lowerModel = modelName.toLowerCase();
506
+ for (const [key, value] of pricing) if (key.toLowerCase().includes(lowerModel) || lowerModel.includes(key.toLowerCase())) return value;
507
+ return null;
508
+ }));
372
509
  }
373
510
  /**
374
511
  * Calculates the cost for given token usage and model
@@ -381,9 +518,7 @@ var PricingFetcher = class {
381
518
  * @returns Total cost in USD
382
519
  */
383
520
  async calculateCostFromTokens(tokens, modelName) {
384
- const pricing = await this.getModelPricing(modelName);
385
- if (pricing == null) return 0;
386
- return this.calculateCostFromPricing(tokens, pricing);
521
+ return pipe(this.getModelPricing(modelName), map((pricing) => pricing == null ? 0 : this.calculateCostFromPricing(tokens, pricing)));
387
522
  }
388
523
  /**
389
524
  * Calculates cost from token usage and pricing information
@@ -404,4 +539,4 @@ var PricingFetcher = class {
404
539
  return cost;
405
540
  }
406
541
  };
407
- export { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEBUG_MATCH_THRESHOLD_PERCENT, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, __commonJSMin, __require, __toESM, require_usingCtx };
542
+ export { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEBUG_MATCH_THRESHOLD_PERCENT, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, __commonJSMin, __require, __toESM, isFailure, isPromise, require_usingCtx, try_ };
@@ -1,2 +1,2 @@
1
- import { PricingFetcher } from "./pricing-fetcher-BZe7AafW.js";
1
+ import { PricingFetcher } from "./pricing-fetcher-B3SvKOod.js";
2
2
  export { PricingFetcher };
@@ -1,4 +1,4 @@
1
- import { PricingFetcher } from "./pricing-fetcher-Dm8hcn_h.js";
2
- import "./_types-Cr2YEzKm.js";
3
- import "./logger-Cke8hliP.js";
1
+ import { PricingFetcher } from "./pricing-fetcher-DaK2jizg.js";
2
+ import "./_types-BHFM59hI.js";
3
+ import "./logger-DeTONwj8.js";
4
4
  export { PricingFetcher };
@@ -381,7 +381,7 @@ const iD = sD(), v = new Set(["\x1B", "›"]), CD = 39, w$1 = "\x07", W$1 = "[",
381
381
  `)];
382
382
  for (const [E, a] of o$1.entries()) {
383
383
  if (e$1 += a, v.has(a)) {
384
- const { groups: B$1 } = new RegExp(`(?:\\${W$1}(?<code>\\d+)m|\\${y}(?<uri>.*)${w$1})`).exec(o$1.slice(E).join("")) || { groups: {} };
384
+ const { groups: B$1 } = (/* @__PURE__ */ new RegExp(`(?:\\${W$1}(?<code>\\d+)m|\\${y}(?<uri>.*)${w$1})`)).exec(o$1.slice(E).join("")) || { groups: {} };
385
385
  if (B$1.code !== void 0) {
386
386
  const p = Number.parseFloat(B$1.code);
387
387
  s = p === CD ? void 0 : p;
@@ -804,7 +804,7 @@ async function prompt(message, opts = {}) {
804
804
  if (typeof value !== "symbol" || value.toString() !== "Symbol(clack:cancel)") return value;
805
805
  switch (opts.cancel) {
806
806
  case "reject": {
807
- const error = new Error("Prompt cancelled.");
807
+ const error = /* @__PURE__ */ new Error("Prompt cancelled.");
808
808
  error.name = "ConsolaPromptCancelledError";
809
809
  if (Error.captureStackTrace) Error.captureStackTrace(error, prompt);
810
810
  throw error;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ccusage",
3
3
  "type": "module",
4
- "version": "15.1.0",
4
+ "version": "15.3.0",
5
5
  "description": "Usage analysis tool for Claude Code",
6
6
  "author": "ryoppippi",
7
7
  "license": "MIT",
@@ -30,5 +30,8 @@
30
30
  "bin": "./dist/index.js",
31
31
  "files": [
32
32
  "dist"
33
- ]
33
+ ],
34
+ "engines": {
35
+ "node": ">=20.19.3"
36
+ }
34
37
  }